WordPress remove_action and wp_deregister_script don’t work

I try to remove script from the footer in my WordPress page.
Here is the end of my footer:

<?php remove_action('wp_footer','woodmart-theme-js-after');?>
<?php wp_deregister_script('woodmart-theme-js-after');?>
<?php do_action( 'woodmart_before_wp_footer' ); ?>
<?php wp_footer(); ?>

Here is the script. It has id, but not src. I don’t know does it matter or not.

Scrin of script

I wasn’t able to find the code of this script to rewrite it. Used search in visual studio code. It’s strange. I also tried to put remove_action in different places of code. Nothing works. Need help

Unit test for the front end component [closed]

I am writing unit test of a front end project, I do have a file which has the below code, tried all scenarios and have not manage to cover below code on the test.

  const handleOpenEndedBranching =(e)=>{
    e.preventDefault()
    handleBranching(question, question?.questionInputTypes[0]?.goTo
    )
  }

How to write the correct regular expression in php?

I need to cut all tags like
<span style="background-color:SOME_COLOR">test</span>
and ONLY if style is background-color, not any others. Also, all text inside the tag must be saved. I tried to use something like this, but it doesn`t work

$pattern = '#<span style="background-color:s*[^;]+;">(.*?)</span>#ui';
$result = preg_replace($pattern, '$1', $inputString);```

Erreur malgré upload du bon fichier [closed]

Je suis confronté à un sérieux problème. J’ai un plugin wordpress dans lequel je souhaite récupérer la preuve de paiement avant de valider la commande. Malgré mes nombreux essaie je ne trouve pas ayant déjà essayer avec ce code, ça me renvoie l’erreur veuillez televerser un fichier même si je l’ai déjà televerser . Voici le fichier :

<?php

// Vérifie si WooCommerce est activé
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    add_action( 'plugins_loaded', 'momo_paid_payment_gateway' );
}

function momo_paid_payment_gateway() {
    class momo_paid_payment_gateway extends WC_Payment_Gateway {

        public function __construct() {
            $this->id                 = 'momo-paid';
            $this->icon               = plugins_url( '../images/icons.png', __FILE__ );
            $this->method_title       = __( 'MomoPaid', 'momo-paid' );
            $this->title              = $this->method_title;
            $this->has_fields         = true;
            $this->init_form_fields();
            $this->init_settings();
            $this->enabled            = $this->get_option( 'enabled' );
            $this->description        = __( 'MomoPaid: Recevez vos Paiements en ligne par MTN Mobile Money', 'momo-paid' );
            $this->method_description = $this->description;

            $this->recipient_number   = $this->get_option( 'recipient_number' );
            $this->recipient_name     = $this->get_option( 'recipient_name' );

            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
            add_action( 'wp_enqueue_scripts', array( $this, 'payments_scripts' ) );
            add_action( 'woocommerce_checkout_process', array( $this, 'validate_fields' ) );
            add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'save_post_meta' ) );
            add_action( 'woocommerce_admin_order_data_after_order_details', array( $this, 'display_transaction_id' ), 10 );
            add_action( 'woocommerce_admin_order_data_after_order_details', array( $this, 'display_proof_file' ), 20 );
        }

        public function init_form_fields() {
            $this->form_fields = array(
                'enabled' => array(
                    'title'   => __( 'Activer/Desactiver MomoPaid', 'momo-paid' ),
                    'type'    => 'checkbox',
                    'label'   => __( 'Activer/Desactiver MomoPaid', 'momo-paid' ),
                    'default' => 'no',
                ),
                'recipient_name' => array(
                    'title'       => __( 'Identité du Bénéficiaire', 'momo-paid' ),
                    'type'        => 'text',
                    'description' => __( 'Nom du Bénéficiaire du paiement MTN Momo. <u><strong>E.g :</strong></u> Mamadou Diabate', 'momo-paid' ),
                ),
                'recipient_number' => array(
                    'title'       => __( 'Numéro du Bénéficiaire MTN Mobile Money', 'momo-paid' ),
                    'type'        => 'number',
                    'description' => __( 'Numéro du Bénéficiaire du Paiement. <u><strong>E.g :</strong></u> 2290197965267', 'momo-paid' ),
                ),
            );
        }

        public function payment_fields() {
            if ( is_checkout() ) {
                $recipient_name   = $this->recipient_name;
                $recipient_number = $this->recipient_number;

                if ( ! empty( $recipient_name ) || ! empty( $recipient_number ) ) {
                    momo_paid_payment_using_mobile_solutions( $recipient_name, $recipient_number );

                    echo '<br/></BLOCKQUOTE><div class="momo-money-form">';
                    woocommerce_form_field( '_momo_money', array(
                        'type'        => 'number',
                        'label'       => __( 'VÉRIFICATION MTN MOMO', 'momo-paid' ),
                        'placeholder' => __( '(XXXXXXXXXX)', 'momo-paid' ),
                        'required'    => true,
                        'class'       => array( 'form-row-wide' ),
                    ) );
                    echo '</div>';

                    echo '<div class="form-row form-row-wide">
                            <label for="momo_proof">' . esc_html__( 'Preuve de paiement (JPG, PNG, PDF – max 5MB)', 'momo-paid' ) . '</label>
                            <input type="file" name="momo_proof" id="momo_proof" accept=".jpg,.jpeg,.png,.pdf" required>
                          </div>';
                    echo '<br/><div class="momo-paid-know-before"></div>';
                } else {
                    esc_html_e( "Veuillez-bien contacter l'administrateur de ce site, un problème est survenu.", 'momo-paid' );
                }
            }
        }

        public function validate_fields() {
            if ( isset( $_POST['_momo_money'] ) ) {
                $transaction_id = sanitize_text_field( $_POST['_momo_money'] );
                if ( empty( $transaction_id ) ) {
                    wc_add_notice( __( 'L'ID de Transaction Momo Money ne peut être vide.', 'momo-paid' ), 'error' );
                } elseif ( ! preg_match( '/^d{10}$/', $transaction_id ) ) {
                    wc_add_notice( __( 'La valeur de la transaction doit contenir exactement 10 chiffres.', 'momo-paid' ), 'error' );
                }
            }

            if ( empty( $_FILES['momo_proof']['name'] ) ) {
                wc_add_notice( __( 'Veuillez fournir une preuve de paiement.', 'momo-paid' ), 'error' );
            } else {
                $file     = $_FILES['momo_proof'];
                $allowed  = array( 'jpg', 'jpeg', 'png', 'pdf' );
                $ext      = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
                $max_size = 5 * 1024 * 1024;

                if ( ! in_array( $ext, $allowed ) ) {
                    wc_add_notice( __( 'Format de fichier invalide. Seuls JPG, PNG et PDF sont autorisés.', 'momo-paid' ), 'error' );
                } elseif ( $file['size'] > $max_size ) {
                    wc_add_notice( __( 'Fichier trop volumineux. 5MB max.', 'momo-paid' ), 'error' );
                }
            }
        }

        public function save_post_meta( $order_id ) {
            if ( isset( $_POST['_momo_money'] ) ) {
                $transaction_id = sanitize_text_field( wp_unslash( $_POST['_momo_money'] ) );
                if ( preg_match( '/^d{10}$/', $transaction_id ) ) {
                    update_post_meta( $order_id, '_momo_money', $transaction_id );
                }
            }

            if ( ! empty( $_FILES['momo_proof']['name'] ) ) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
                $uploaded = wp_handle_upload( $_FILES['momo_proof'], array( 'test_form' => false ) );
                if ( ! isset( $uploaded['error'] ) ) {
                    update_post_meta( $order_id, '_momo_proof_url', esc_url( $uploaded['url'] ) );
                }
            }
        }

        public function display_transaction_id( $order ) {
            if ( 'momo-paid' === $order->get_payment_method() ) {
                $transaction_id = get_post_meta( $order->get_id(), '_momo_money', true );
                if ( $transaction_id ) {
                    echo '<div class="order_data_column"><h4>' . esc_html__( 'NUMÉRO DE RÉFÉRENCE :', 'momo-paid' ) . ' ' . esc_html( $transaction_id ) . '</h4></div>';
                }
            }
        }

        public function display_proof_file( $order ) {
            if ( 'momo-paid' === $order->get_payment_method() ) {
                $proof_url = get_post_meta( $order->get_id(), '_momo_proof_url', true );
                if ( $proof_url ) {
                    $file_ext = pathinfo( $proof_url, PATHINFO_EXTENSION );
                    echo '<div class="order_data_column"><h4>' . esc_html__( 'Preuve de paiement :', 'momo-paid' ) . '</h4>';
                    if ( in_array( $file_ext, array( 'jpg', 'jpeg', 'png' ) ) ) {
                        echo '<img src="' . esc_url( $proof_url ) . '" style="max-width:200px;"><br>';
                    }
                    echo '<a href="' . esc_url( $proof_url ) . '" target="_blank">' . basename( $proof_url ) . '</a></div>';
                }
            }
        }

        public function process_payment( $order_id ) {
            $order = wc_get_order( $order_id );
            $order->update_status( 'on-hold', __( 'Votre paiement doit être vérifié, merci de bien vouloir patienter.', 'momo-paid' ) );
            WC()->cart->empty_cart();

            return array(
                'result'   => 'success',
                'redirect' => $this->get_return_url( $order ),
            );
        }

        public function payments_scripts() {
            // wp_enqueue_style( 'momo-paid-styles', plugin_dir_url( __FILE__ ) . 'css/momo-paid-styles.css', array(), '1.0' );
        }
    }
}

function momo_paid_add_gateway_class( $methods ) {
    $methods[] = 'momo_paid_payment_gateway';
    return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'momo_paid_add_gateway_class' );

function momo_paid_payment_using_mobile_solutions( $recipient_name, $recipient_number ) {
    global $woocommerce;
    $cart_total_price = $woocommerce->cart->get_total();

    echo sprintf( __( '</br><strong>1°)</strong>  <strong>COMPOSER LE CODE USSD MOMO MONEY DE VOTRE PAYS POUR RÉGLER </strong><h4><strong>%1$s</h4></strong> À <strong>%2$s</strong> <strong>AU</strong> : <strong><h4 style="background-color:#f7e859;"> %3$s</h4></strong>.<br/><br/> <strong>2°) VÉRIFICATION PAR RÉFÉRENCE</strong> <br/>
    * <strong>Cette vérification initiale requiert le numéro de référence envoyé </strong>  <strong>dans l'accusé de réception par votre opérateur mobile après votre transaction</strong>.', 'momo-paid' ), wp_kses_post( $cart_total_price ), esc_html( $recipient_name ), esc_html( $recipient_number ) );
}

Quelqu’un peut me dire quoi faire ?

USDC transfer on Polygon using simple-web3-php succeeds without error but tokens not moved

I’m using drlecks/simple-web3-php v0.10.0 to transfer USDC on Polygon (contract: 0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359). I have the sender’s private key and successfully use the library to send USDT with the same approach.

But when sending USDC, the transaction shows up on the blockchain, but:

  • No USDC is actually transferred.
  • The wallet balance doesn’t change.
  • I see two ERC-20 transfer events, one of them has amount 0.

There’s no error returned from the transfer function, but the transfer clearly doesn’t complete properly.

I’m using the same transfer(address,uint256) method, and everything works for USDT. Why would USDC behave differently? How can I fix this using only drlecks/simple-web3-php?

Code snippets :

class Web3
{
    private $web3;

    public function __construct(private $contractAddress = '', private $contractABI = '', private $chainId = 0, private $transactionId = 0)
    {
        $productionBaseUrl = 'https://polygon-rpc.com/';
        $stagingBaseUrl = 'https://rpc-amoy.polygon.technology/';
        $uri = Core::$debug ? $stagingBaseUrl : $productionBaseUrl;
        $this->web3 = new SWeb3($uri);
        $this->web3->chainId = $this->chainId;
        $this->contractABI = html_entity_decode($this->contractABI);
    }

    public function transfer($address, $privateKey, $amount)
    {
        $config = $this->config($address, $privateKey);
        if ($config->code != 1) {
            return $config;
        }

        $responseConvertValue = $this->convertValue(strval($amount), 'transferUsdt');

        if ($responseConvertValue->code != 1) {
            return $responseConvertValue;
        }

        $extraData = [];
        if (json_decode($this->web3->personal->getNonce()->value)) {
            $extraData = ['nonce' => $this->web3->personal->getNonce()];
        } else {
            $extraData = ['nonce' => ''];
        }
        $gasEstimateResult = $this->web3->call('eth_estimateGas', [$extraData]);
        if (!isset($gasEstimateResult->result)) {
            $this->handleError('transferUsdt', 'Cant get estimateGas');
            return (object) ['code' => -3, 'message' => 'Cant get estimateGas'];
        }
        $extraData['gasPrice'] = $this->web3->getGasPrice();
        $extraData['gasLimit'] = $this->web3->utils->hexToBn($gasEstimateResult->result);
        try {
            $contract = new SWeb3_contract($this->web3, $this->contractAddress, $this->contractABI);
            $result =
                $contract->send('transfer', [env('MAIN_ADDRESS_WALLET'), $responseConvertValue->value], $extraData);
            if (isset($result->error)) {
                $message = 'Code :' . $result->error->code . 'Error :' . $result->error->message;
                $this->handleError('transferUsdt', $message);
                return (object) ['code' => -1, 'message' => $result->error->message];
            }
        } catch (Throwable $th) {
            $this->handleError('transferUsdt', $th->getMessage());
            return (object) ['code' => -1, 'message' => $th->getMessage()];
        }
        return (object) ['code' => 1, 'message' => $result];
    }
    private function convertValue($value, $methodName)
    {

        try {
            $value = Utils::toWei($value, $methodName == 'transferUsdt' ? "mwei" : 'ether');
        } catch (Throwable $th) {
            $this->handleError($methodName . ' > convertValue >', $th->getMessage());
            return (object) ['code' => -1, 'message' => $th->getMessage()];
        }
        return (object) ['code' => 1, 'value' => $value];
    }

A snippet of a single transmission attempt (https://i.sstatic.net/KPCILlFG.png)

PHPSpreadsheet: styling completely ignored

Trying to add styling to PHPSpreadsheet’ cells:

$spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $irow = $icol = 1;
        foreach ([
                     'Operation type',
                     'Name',
                     'Status',
                     'Start',
                     'End',
                     'Duration'
                 ] as $title) {
            $sheet->setCellValue([$icol, $irow], $title);
            $sheet->getStyle([$icol, $irow])->getFont()->setBold(true);
            $sheet->getStyle([$icol, $irow])->getAlignment()->setVertical(Alignment::VERTICAL_TOP);
            $icol++;
        }
        //
        $writer = new Xlsx($spreadsheet);
        $writer->save('hello world.xlsx');

Finally, I see properly filled Excel sheet without any styling – no bold font, no vertical alignment.

What’s wrong?

UPDATE:

  1. getStyle accepts array of 4 ints instead of array of 2 ints in setCellValue:
    /**
     * Get style for cell.
     *
     * @param AddressRange|array<int>|CellAddress|int|string $cellCoordinate
     *              A simple string containing a cell address like 'A1' or a cell range like 'A1:E10'
     *              or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]),
     *              or a CellAddress or AddressRange object.
     */
    public function getStyle($cellCoordinate): Style
  1. getStyleByColumnAndRow marked as deprecated. Recommends to use getStyle instead

“expo-camera: Cannot read property ‘BarCodeType’ of undefined” when using BarCodeScanner

I’m currently encountering an error while working on my React Native project that uses expo-camera to implement a QR code scanner.

The issue arises when I try to use the BarCodeType constant from the BarCodeScanner component. The error I’m getting is:

Warning: TypeError: Cannot read property ‘BarCodeType’ of undefined

Here’s the QRScan.js file I’m using:

import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { Camera } from 'expo-camera';

export default function QRScan() {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);

  // ask for camera permission on mount
  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <ActivityIndicator style={styles.center} size="large" />;
  }
  if (hasPermission === false) {
    return (
      <View style={styles.center}>
        <Text style={styles.noAccessText}>No access to camera</Text>
        <TouchableOpacity
          onPress={async () => {
            const { status } = await Camera.requestCameraPermissionsAsync();
            setHasPermission(status === 'granted');
          }}
          style={styles.retryButton}
        >
          <Text style={styles.retryText}>Grant Permission</Text>
        </TouchableOpacity>
      </View>
    );
  }

  const onBarCodeScanned = ({ data }) => {
    setScanned(true);
    Alert.alert('QR Code', data, [
      { text: 'OK', onPress: () => setScanned(false) },
    ]);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Device{'n'}Connection</Text>

      <View style={styles.scannerWrapper}>
        <Camera
          style={StyleSheet.absoluteFill}
          onBarCodeScanned={scanned ? undefined : onBarCodeScanned}
          barCodeScannerSettings={{
            barCodeTypes: [Camera.Constants.BarCodeType.qr],
          }}
        />

        <View style={styles.overlay}>
          <View style={styles.frameTop} />
          <View style={styles.frameMiddle}>
            <View style={styles.frameSide} />
            <View style={styles.frameCenter} />
            <View style={styles.frameSide} />
          </View>
          <View style={styles.frameBottom} />
        </View>
      </View>

      <Text style={styles.instructionTitle}>Scan QR code to connect</Text>
      <Text style={styles.instructionSubtitle}>
        Align the QR code within the frame to scan
      </Text>

      {scanned && (
        <TouchableOpacity
          onPress={() => setScanned(false)}
          style={styles.retryButton}
        >
          <Text style={styles.retryText}>Tap to Scan Again</Text>
        </TouchableOpacity>
      )}
    </View>
  );
}

In React we are calling the api in one component now we use the same data of api in other component withut calling api again how we can do this? [closed]

“We want to avoid calling the API separately in each component. Instead, we’d like to call the API once and share the data across components. Currently, I’m trying to achieve this using localStorage, but I’m looking for a more optimized and efficient solution. Ideally, we want a centralized state management approach that ensures better performance and cleaner code.

How to open chrome forcibly instead of open webview when I click on my url in any app

My problem:
I have a service with web interface. The customers receives a link to the web page and click’s on it.
Depends on a customer platform – the link must be opened in a different way:

  • in case if the platform is an iOS or desktop – then nothing to do, the link can be opened in a default browser

  • in case if the platform is an android – the next flow will be performed:

    1. if the google chrome browser is installed – the link must be opened in the chrome broser not in an android system webview browser.
    2. if it is no the chrome browser installed – the play market with the browser must be opened

I have used Firebase Dynamic Links before. And it had working fine. But the firebase dynamic links will end of life at 25 august 2025. Now i need in alternative.

Now I trying to solve the first problem – open my link in the installed chrome browser. Im trying to solve it using a custom html page with the redirect:

...
<a href="intent://" + TARGET_URL + "#Intent;scheme=https;package=com.android.chrome;end;">open it in Chrome</a>
...

but it not lead to redirect into the chrome.

I tried to use such services as branch.io – but no ways to avoid opening my page in the system webview

How it can be solved?

Dragging thunderbird email into html text area gets link, not message contents

I am trying to drag an email from Thunderbird (or perhaps gmail) into a textarea.

If I open the message in Thunderbird, select everything (Ctrl-A) and drag the selected text it achieves what I am looking for.

But to simplify things more I want to drag the e-mail summary line (before you open it). However this just results in a link being pasted, of the form:

  imap-message://[email protected]@imap.gmail.com/folder#123456

I haven’t been able to work out how to get the content of the message from here in JavaScript

The module reloads when navigating to another page in Next.js

I encountered a problem that I have been investigating for two days but can’t find why it happens.

This is what the count function does in the count.js file. It runs on the server.

let n = 0

export async function count() {
  n = n + 1;
  return n 
}

This is the main page.js

import { count } from "./counter";

let GETNUMBER = await count()

export default async function Home() {
  return GETNUMBER 
}

In GETNUMBER I should get the number 2, because there is another page that also runs the same function as start.

As soon as I go to another page GO using redirect
which looks like this

import { count } from "./counter";
    
let GETNUMBER = await count()
    
export default async function GO() {
  return GETNUMBER
}

Here I get number 1.

It seems like the count.js page is reloaded again
And if I go back to page.js then I get 2 again
I don’t understand what’s going on here.
In React the module is only loaded once.

When i run: npm run build
the server should run onces all codes above this line:

export default async function Home() {

I hope I was understood I would appreciate help.

How can i extract Failed Selector URLs from Cypress Tests

I’m working on a self-healing project for Cypress, and I need to extract URLs that have failed selectors from my test files (.cy.js). My goal is to automatically log these URLs into a file for further analysis.

If a test fails due to a missing element, I want to log it in a way that’s easily readable,
like:


{  
   "url": "http://example.com/page",  
   "failedSelectors": ["#nonexistent-element", ".another-failed-selector"]  
}  

i developed a custom command in commands.js:

let currentUrl = 'unknown';
const fs = require('fs');
const path = require('path');

Cypress.Commands.add('trackUrlOnError', () => {
  Cypress.on('fail', (error, runnable) => {
    const timestamp = new Date().toISOString();
    const testName = runnable.fullTitle();
    const errorMessage = error.message;
    const selectorMatch = error.message.match(/Expected to find element: [`'](.*?)[`']/);
    const selector = selectorMatch ? selectorMatch[1] : "unknown";

    return cy.url().then((url) => {
      cy.task('logErrorDetails', {
        url,
        timestamp,
        testName,
        message: error.message,
        selector: selector

      });

      throw error; 
  });
});

and in e2e also :

let lastVisitedUrl = 'unknown';

beforeEach(() => {
  cy.intercept('GET', '**', (req) => {
    if (req.url.startsWith('http')) {
      lastVisitedUrl = req.url;
    }
  });
});

afterEach(function () {
  if (this.currentTest.state === 'failed') {
    const error = this.currentTest.err;
    cy.task('logErrorDetails', {
      url: lastVisitedUrl,
      timestamp: new Date().toISOString(),
      testName: this.currentTest.fullTitle(),
      message: error.message,
      selecteur: error.message.match(/Expected to find element: `([^`]+)`/)?.[1] || "unknown"
    });
  }
});

the problem is the url is not correctly extracted for example : https://google.com i got “https://www.google.com/xjs/_/js/k=xjs.hd.ar.W3bsuzNPU5A.es5.O/am=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA” idk why ..please help me fix this problem.

Is there any way I can make the ‘create version’ button disappear when clicked? [closed]

<button type=’button’
OnClick=’ let newVersionID=RelaticsAPI.CreateInstanceElement(“f02cb920-1316-f011-b6c2-001dd8d702ae”);

newVersionID=newVersionID.Element.ID;

RelaticsAPI.UpdateInstanceElement(newVersionID,”Name”,”Version”);

RelaticsAPI.CreateInstanceRelation([DocID], newVersionID, “1b78a05a-c21a-f011-b6c2-001dd8d702ae”); RelaticsAPI.Refresh([currentTableID]);’>New version