Displaying Transaction Fee on WooCommerce Orders in wp-admin

What I am trying to do is show a breakdown of the Woocommerce transaction fee being applied after the order total:

It would something like this:

  • Items Subtotal: £375.00
  • Shipping: £0.00
  • VAT: £75.00
  • Order Total: £450.00
  • Paid: £450.00
  • Transaction Fee: £7.00
  • Total (after fee): £443.00

A visual of where it should go, I have highlighted it and as you see it’s just an error at the moment:

enter image description here

The code in my functions .php

    // Calculate and save transaction fee after order is created/paid
add_action('woocommerce_order_status_changed', 'add_transaction_fee_to_order_meta', 10, 3);
function add_transaction_fee_to_order_meta($order_id, $old_status, $new_status) {
    if ($new_status == 'processing' || $new_status == 'completed') {
        $order = wc_get_order($order_id);

        if (get_post_meta($order_id, '_transaction_fee', true) == '') {
            $order_total = $order->get_total();
            $transaction_fee = ($order_total * 0.015) + 0.25;

            update_post_meta($order_id, '_transaction_fee', $transaction_fee);

        }
    }
}


// Display transaction fee in admin order details *after* "Paid" line
add_action('woocommerce_admin_order_totals_after_total', 'display_transaction_fee_in_admin_order_details', 10, 2);
function display_transaction_fee_in_admin_order_details($order_id, $order) {
    $transaction_fee = get_post_meta($order_id, '_transaction_fee', true);

    if ($transaction_fee) {
        if (is_object($order) && is_a($order, 'WC_Order')) {
            ?>  <tr>
                <td class="label">Transaction Fee:</td>
                <td width="1%"></td>
                <td class="total">
                    <?php echo wc_price($transaction_fee); ?>
                </td>
            </tr>
            <tr>
                <td class="label">Total (after fee):</td>
                <td width="1%"></td>
                <td class="total">
                    <?php echo wc_price($order->get_total() - $transaction_fee); ?>
                </td>
            </tr>
            <?php
        } else {
            error_log("WC_Order object not available in display_transaction_fee_in_admin_order_details for order ID: " . $order_id);
        }
    }
}

Typo3 12 – Override Backend Modules.php

I want to change the workspaces setting for some vendor module in my typo3 project. Is it possible? I tried to search in documentation and I didn’t figure out how to do that.
Thank you

How override backend module settings

Laravel 11: Custom Password Broker Ignores My Tenant-Aware Repository

I’m implementing multi-tenancy in my Laravel 11 application, so I need a tenant_id column in the password_reset_tokens table. I’ve created a custom PasswordBrokerManager and a custom TenantAwareDatabaseTokenRepository, but Laravel still uses the default DatabaseTokenRepository—so the tenant_id never gets inserted.

1. config/auth.php

return [
    'defaults' => [
        'guard' => env('AUTH_GUARD', 'web'),
        'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
    ],
    'guards' => [
        'web' => [
            'driver'   => 'session',
            'provider' => 'users',
        ],
    ],
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model'  => AppModelsUser::class,
        ],
    ],
    'passwords' => [
        'users' => [
            'driver'   => 'custom',  // I made sure to set this
            'provider' => 'users',
            'table'    => 'password_reset_tokens',
            'expire'   => 60,
            'throttle' => 60,
        ],
    ],
];

I ran php artisan config:clear && php artisan cache:clear and verified with dd(config('auth.passwords.users')) that it shows "driver" => "custom".

2. AppServiceProvider

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminateAuthPasswordsPasswordBrokerManager;
use AppExtensionsCustomPasswordBrokerManager;
use IlluminateSupportFacadesLog;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        Log::debug('AppServiceProvider: register() is being called...');

        // Bind my custom password broker manager
        $this->app->singleton(PasswordBrokerManager::class, function ($app) {
            Log::debug('Binding CustomPasswordBrokerManager...');
            return new CustomPasswordBrokerManager($app);
        });
    }

    public function boot(): void
    {
        Log::debug('AppServiceProvider: boot() is being called...');
    }
}

The logs for AppServiceProvider show up, but when I trigger a password reset, my custom code is ignored.

3. CustomPasswordBrokerManager

<?php

namespace AppExtensions;

use IlluminateAuthPasswordsPasswordBrokerManager;
use IlluminateAuthPasswordsTokenRepositoryInterface;
use AppRepositoriesTenantAwareDatabaseTokenRepository;
use AppModelsTenant;
use IlluminateSupportFacadesLog;
use RuntimeException;

class CustomPasswordBrokerManager extends PasswordBrokerManager
{
    public function __construct($app)
    {
        Log::debug('CustomPasswordBrokerManager: constructor called!');
        parent::__construct($app);
    }

    protected function createTokenRepository(array $config): TokenRepositoryInterface
    {
        Log::debug('CustomPasswordBrokerManager: createTokenRepository called! driver=' . ($config['driver'] ?? ''));

        // 1) DB connection
        $connection = $this->app['db']->connection($config['connection'] ?? null);

        // 2) Table name
        $table = $config['table'];

        // 3) Laravel app key
        $hashKey = $this->app['config']['app.key'];

        // 4) Expiry & throttle
        $expire   = $config['expire'];
        $throttle = $config['throttle'] ?? 60;

        // 5) Current tenant
        $tenant = Tenant::current();
        if (! $tenant || ! $tenant->id) {
            throw new RuntimeException('No tenant found. Tenant ID cannot be null.');
        }

        // 6) Return custom repository
        return new TenantAwareDatabaseTokenRepository(
            $connection,
            $this->app['hash'],
            $table,
            $hashKey,
            $expire,
            $throttle,
            $tenant->id
        );
    }
}

I never see the “createTokenRepository called!” log in my laravel.log, meaning Laravel won’t enter this code.

4. TenantAwareDatabaseTokenRepository

<?php

namespace AppRepositories;

use IlluminateAuthPasswordsDatabaseTokenRepository;
use IlluminateContractsAuthCanResetPassword as CanResetPasswordContract;
use IlluminateContractsHashingHasher;
use IlluminateDatabaseConnectionInterface;
use IlluminateSupportCarbon;

class TenantAwareDatabaseTokenRepository extends DatabaseTokenRepository
{
    protected mixed $tenantId;

    public function __construct(
        ConnectionInterface $connection,
        Hasher $hasher,
        string $table,
        string $hashKey,
        int $expires = 60,
        int $throttle = 60,
        mixed $tenantId = null
    ) {
        parent::__construct($connection, $hasher, $table, $hashKey, $expires, $throttle);
        $this->tenantId = $tenantId;
    }

    protected function getPayload($email, $token): array
    {
        return [
            'email'      => $email,
            'tenant_id'  => $this->tenantId,
            'token'      => $this->getHasher()->make($token),
            'created_at' => Carbon::now(),
        ];
    }
}

This class includes tenant_id in the insert, but Laravel keeps using the default DatabaseTokenRepository.

5. Error & Stack Trace

When I request a password reset, I get:

SQLSTATE[HY000]: General error: 1364 Field 'tenant_id' doesn't have a default value
IlluminateAuthPasswordsDatabaseTokenRepository->create()

It shows DatabaseTokenRepository is being called, not TenantAwareDatabaseTokenRepository.

6. Controller Snippet

public function store(Request $request): Responsable
{
    $request->validate(['email' => 'required|email']);

    $status = $this->broker()->sendResetLink($request->only('email'));

    // ...
}

protected function broker(): PasswordBroker
{
    return Password::broker(config('fortify.passwords')); 
    // config('fortify.passwords') is "users"
}

7. Things I Tried

  • Double-checked 'driver' => 'custom' in config/auth.php.
  • Ran php artisan config:clear && php artisan cache:clear.
  • Logged in CustomPasswordBrokerManager::createTokenRepository(), but it never fires.
  • Confirmed 'passwords' => 'users' in config/fortify.php.
  • Verified logs in AppServiceProvider do show up.

8. Environment

  • Laravel: 11.x
  • PHP: 8.3
  • MySQL/MariaDB
  • Jetstream + Fortify

Question

How do I ensure Laravel actually uses my CustomPasswordBrokerManager and TenantAwareDatabaseTokenRepository instead of defaulting to DatabaseTokenRepository? Any help is appreciated.

Asserting a method call on a Facade not the underlying proxied class

I’m trying to write tests to assert that methods called in my AppServiceProvider boot method are present & enforced logic.

So far I’m using mocks & reflection, however I am having an issue with the DB::prohibitDestructiveCommands(app()->isProduction()) method call.

The method prohibitDestructiveCommands() isn’t on the underlying proxied class (DatabaseManager), it’s on the actual facade class.

This has made it quite difficult for me. I have spent far too long trying to solve this; to come up with a solution that will allow to assert that the facade method is called.

So I have landed on the following test as being a possible way to solve my issue:

test('Invokes DB::prohibitDestructiveCommands in production', function () 
    {
        $this->app->detectEnvironment(fn() => 'production');
        
        $mock = mock('overload:IlluminateSupportFacadesDB');
    
        $mock->shouldReceive('getFacadeRoot')
             ->once()
             ->andReturn(new DB);
    
        $mock->shouldReceive('prohibitDestructiveCommands')
             ->once()
             ->with(true);
    
        $this->provider->boot();
    
        $mock->shouldHaveReceived('prohibitDestructiveCommands');
    }
);

It still has the problem, that the Facade is already loaded in that namespace and can’t be overloaded, so it results in the test having the following error:

MockeryExceptionRuntimeException:
    Could not load mock IlluminateSupportFacadesDB,
    class already exists
at vendor/mockery/mockery/library/Mockery/Container.php:401
at vendor/mockery/mockery/library/Mockery.php:681
at vendor/mockery/mockery/library/helpers.php:40

If you can figure out how I can overcome this, or another way of asserting that a method from a principal facade class is invoked, then I would really appreciate the assistance.

Note: I know that I could wrap the method like so & mock the provider to assert the call of that method, however it’s not a wonderful solution to enforcing behaviour through tests, as the call to DB::prohibitDestructiveCommands(app()->isProduction()) could be removed or changed by a dev at a later time from the wrapping method & tests wouldn’t pickup the structural change.

I am also aware, I can test the outcome of the calling the prohibited commands, but this is a unit tests, and shouldn’t be cross testing behaviour like this, just the structure of the class.

how to create a dinamic query to all tables in a database php mysql

hello guys i have this query and others similar in a file php mysql:

$laps = "select sum(laps) totallaps
                                    from
                                    (
                                        select laps
                                        from w_silverstone24_25
                                        where steamid='.................'
                                        union all
                                        select laps
                                        from s_monza2024
                                        where steamid='................'
                                        (and more more more)
                                    ) t
                                ";
$resultlaps = $mysqli->query($laps);
$rowlaps = $resultlaps->fetch_assoc();
$valuelaps = $rowlaps["totallaps"];

i want to creat a dinamic query so when i add a new table in my database the results will sum automatically… now i have to add manually the code to interrogate the new tables…
how i have to do? the database is online not on my pc.

How to build a regex pattern from a list of words (in a string or array) and surround each word with word boundary anchors? [duplicate]

I have a string of text and a series of words:

String: Auch ein blindes Huhn findet einmal ein Korn.
Words: auch, ein, sehendes

I want to check which of the words is contained in the string. I am using preg_match_all for that:

$pattern = "/bauchb|beinb|bsehendesb/i";
$subject = "Auch ein blindes Huhn findet einmal ein Korn.";

preg_match_all($pattern, $subject, $matches);
print_r($matches);

Array
(
    [0] => Array
        (
            [0] => Auch
            [1] => ein
            [2] => ein
        )

)

This works as expected, but since I have to edit the pattern frequently, and I find it confusing to find and replace words when they are all surrounded by word boundary anchors (b), I would like to define the list of words without the word boundary anchors and add them in a second step. Something like:

$pattern = "auch|ein|sehendes";
$pattern = "/b" . $pattern . "b/i";

That, of course, doesn’t work as expected.

I could fill an array with the words and loop over it to build the pattern, but I’d like to avoid loops. Any ideas how to do this fast? The real string and the real number of words are quite large.

Eventually I need the number of matches, as it is returned by preg_match_all. For the example the expected output is “3”.


Here is a similar question where this is done in Javascript: Apply a word-boundary anchor to all tokens in a single regex

using SOLR export request handler with PHP Solarium

I wonder if there is a possibility to use the SOLR export request handler with the PHP Solarium library: https://solr.apache.org/guide/6_6/exporting-result-sets.html

I can access the results applying the example “http://localhost:8983/solr/core_name/export?q=my-query&sort=severity+desc,timestamp+desc&fl=severity,timestamp,msg” through the browser or curl, but not through the Solarium library as there seem to be no such thing as $client->createExport

Am I missing something?

I also tried $request->setHandler('export'), following the example from How to use a custom request handler in Solarium, but it is still using the select handler.

use access token for life time in xero

I am trying to implement xero account software in my php project. I have to create an invoice with an attachment. I am using xero api for this. Initial authentication is working well. Means if I authenticate first time then it generates all the tokens and those tokens are being saved into the table.
Below is the code for authenticate: xero_callback.php is:
This is working fine.

    <?php
session_start();
require 'db.php'; // Include database connection file

define('CLIENT_ID', 'xxxxx');
define('CLIENT_SECRET', 'xxxxx');
define('REDIRECT_URI', 'http://localhost/xero_testing/xero_callback.php');

if (!isset($_GET['code'])) {
    die("No authorization code received.");
}

$code = $_GET['code'];

$tokenUrl = "https://identity.xero.com/connect/token";

$data = [
    "grant_type" => "authorization_code",
    "code" => $code,
    "redirect_uri" => REDIRECT_URI,
    "client_id" => CLIENT_ID,
    "client_secret" => CLIENT_SECRET
];

$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if (!isset($result["access_token"])) {
    die("Failed to get access token.");
}

$accessToken = $result["access_token"];
$refreshToken = $result["refresh_token"];
$expiresIn = $result["expires_in"];

// Get Tenant ID
$ch = curl_init("https://api.xero.com/connections");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $accessToken",
    "Content-Type: application/json"
]);

$tenantResponse = curl_exec($ch);
curl_close($ch);

$tenantData = json_decode($tenantResponse, true);
$tenantId = $tenantData[0]["tenantId"] ?? null;

if (!$tenantId) {
    die("Failed to retrieve Tenant ID.");
}

// Store in Database
$db->query("INSERT INTO xero_tokens (tenant_id, access_token, refresh_token, expires_in) 
            VALUES ('$tenantId', '$accessToken', '$refreshToken', '$expiresIn')");

echo "Successfully connected to Xero! Tenant ID: $tenantId";
?>

Now below is the code to create invoice and update access token when it expires. After authenticating first time everything is working. But when access token gets expired after 30 mins and then if I regenerate the access token using the refresh token then it gives error: below is the code for create invoice:

    <?php
require 'db.php';
$result = $db->query("SELECT * FROM xero_tokens ORDER BY created_at DESC LIMIT 1");
$xero = $result->fetch_assoc();
$accessToken = $xero['access_token'];
$tenantId = $xero['tenant_id'];
$refreshToken = $xero['refresh_token'];
$record_id = $xero['id'];
$contactID = getContactID('John Doe', $accessToken, $tenantId);

$invoiceData = [
    "Type" => "ACCREC",
    "Contact" => ["ContactID" => $contactID],
    "LineItems" => [[
        "Description" => "Consulting Service",
        "Quantity" => 1,
        "UnitAmount" => 200.00,
        "AccountCode" => "200"
    ]],
    "Date" => date("Y-m-d"),
    "DueDate" => date("Y-m-d", strtotime("+30 days")),
    "InvoiceNumber" => "INV-" . time()
];

$headers = [
    "Authorization: Bearer $accessToken",
    "Xero-tenant-id: $tenantId",
    "Content-Type: application/json",
    "Accept: application/json",
];

$ch = curl_init("https://api.xero.com/api.xro/2.0/Invoices");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($invoiceData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 401 || $httpCode == 403) {    
    refreshAccessToken($refreshToken, $record_id);

    // Fetch the latest access token from DB after refreshing
    $result = $db->query("SELECT * FROM xero_tokens ORDER BY created_at DESC LIMIT 1");
    $xero = $result->fetch_assoc();
    $accessToken = $xero['access_token'];
    $tenantId = $xero['tenant_id'];

    $headers = [
        "Authorization: Bearer $accessToken",
        "Xero-tenant-id: $tenantId",
        "Content-Type: application/json",
        "Accept: application/json",
    ];

    $ch = curl_init("https://api.xero.com/api.xro/2.0/Invoices");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($invoiceData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}

curl_close($ch);
$responseData = json_decode($response, true);

$invoiceId = $responseData['Invoices'][0]['InvoiceID'] ?? null;

if (!$invoiceId) {
    die("Failed to create Invoice.");
}

echo "Invoice Created: ID = $invoiceId";

$path = 'ALK.pdf';
$filename = 'ALK.pdf';
if (file_exists($path)) {
    $fileHandle = fopen($path, 'r');
    $fileSize = filesize($path);

    $ch = curl_init("https://api.xero.com/api.xro/2.0/Invoices/$invoiceId/Attachments/$filename");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_UPLOAD, true);
    curl_setopt($ch, CURLOPT_INFILE, $fileHandle);
    curl_setopt($ch, CURLOPT_INFILESIZE, $fileSize);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken",
        "Xero-tenant-id: $tenantId",
        "Content-Type: application/octet-stream",
        "Content-Length: $fileSize"
    ]);

    $attachmentResponse = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    fclose($fileHandle);
    curl_close($ch);

    if ($httpCode == 200) {
        echo "Attachment Uploaded Successfully!";
    } else {
        echo "Error uploading attachment: ";
        print_r(json_decode($attachmentResponse, true));
    }
} else {
    echo "File does not exist at path: " . $path;
}


function getContactID($contactName, $accessToken, $tenantId) {

$headers = [
    "Authorization: Bearer $accessToken",
    "Accept: application/json"
];

$ch = curl_init("https://api.xero.com/connections");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode == 200) {
    echo "Access Token is valid.";
    print_r($response); 
} else {
    echo "Access Token is invalid or expired. HTTP Code: $httpCode";
}

//exit;
    
    $contactName = urlencode($contactName);
    $url = "https://api.xero.com/api.xro/2.0/Contacts?where=Name.Contains("$contactName")";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken",
        "Xero-tenant-id: $tenantId",
        "Content-Type: application/json",
        "Accept: application/json"
    ]);

    $response = curl_exec($ch);
    $data = json_decode($response, true);

    if (isset($data['Contacts'][0]['ContactID'])) {
        return $data['Contacts'][0]['ContactID']; // Return ContactID if found
    } else {
        return null; // Contact not found
    }
}

function refreshAccessToken($refreshToken, $record_id) {
    global $db; 

    $clientId = 'xxxx'; 
    $clientSecret = 'xxxxx'; 

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://identity.xero.com/connect/token',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type' => 'refresh_token',
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'refresh_token' => $refreshToken
        ]),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded'
        ],
    ));

    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    if ($httpCode == 200) {
        $tokenData = json_decode($response, true);
        if (isset($tokenData['access_token'], $tokenData['refresh_token'])) {
            // Update the database with the new tokens
            $newAccessToken = $tokenData['access_token'];
            $newRefreshToken = $tokenData['refresh_token'];

            $updateQuery = $db->prepare("UPDATE xero_tokens SET access_token = ?, refresh_token = ?, created_at = NOW() WHERE id = ?");
            $updateQuery->bind_param("ssi", $newAccessToken, $newRefreshToken, $record_id);
            $updateQuery->execute();

            if ($updateQuery->affected_rows > 0) {
                echo "Access token refreshed successfully!";
            } else {
                echo "Failed to update token in the database.";
            }
        } else {
            echo " Refresh token response missing expected fields.";
        }
    } else {
        echo "Failed to refresh access token. HTTP Code: $httpCode";
    }
}

function saveNewToken($accessToken, $refreshToken, $record_id)
{
    global $db;
    $stmt = $db->prepare("UPDATE xero_tokens SET access_token = ?, refresh_token = ?, created_at = NOW() WHERE id = ?");
    $stmt->bind_param("ssi", $accessToken, $refreshToken, $record_id);
    $stmt->execute();
}



?>

Error is:

    Access Token is valid.[]403
{"Type":null,"Title":"Forbidden","Status":403,"Detail":"AuthenticationUnsuccessful","Instance":"1111eace-cfc0-413b-8111-5c53832769b7","Extensions":{}}

How to track Facebook MetaPixel event in laravel /php?

In my Laravel project, I’m successfully tracking frontend events using the JavaScript code fbq('track', 'PageView'), which works well for tracking page views.

However, when attempting to use the MetaPixel::track() method within a Laravel controller, I used the following code:

use CombindmaFacebookPixelFacadesMetaPixel;
MetaPixel::track('SignIn', [
    'User_Email' => $customer->email,
    'Status' => 'logged in successfully'
]);

Despite installing all the necessary dependencies and adding the required code in the config file, the event tracking does not seem to function as expected.

<?php

return [
    /*
     * The Meta pixel id, should be a code that looks something like "1202417153106158".
     */
    'pixel_id' => env('META_PIXEL_ID', ''),

    /*
     * The key under which data is saved to the session with flash.
     */
    'session_key' => env('META_PIXEL_SESSION_KEY', config('app.name').'_metaPixel'),

    /*
     * Only if you plan using Conversions API for server events
     * To use the Conversions API, you need an access token. For Documentation please see: https://developers.facebook.com/docs/marketing-api/conversions-api/get-started
     */
    'token' => env('META_PIXEL_TOKEN', ''),

    /*
     * Enable or disable advanced matching. Useful for adjusting user privacy.
     */
    'advanced_matching_enabled' => env('META_PIXEL_ADVANCED_MATCHING_ENABLED', true),

    /*
     * Enable or disable script rendering. Useful for local development.
     */
    'enabled' => env('META_PIXEL_ENABLED', true),

    /*
     * Enable or disable logging. Useful for debugging.
     */
    'logging' => env('META_PIXEL_LOGGING', true),

    /*
     * This is used to test server events
     */
    'test_event_code' => env('META_TEST_EVENT_CODE'),
];

Can anyone help me out, so that i can track my events in laravel

Pass JavaScript prompt variable to input text using PHP [duplicate]

I have a simple page written with (php + html) I just want user enter value into prompt box then when click button the value send to textbox. I tried below code but I get error inside textbox.

<?php
    echo "<script>var age=prompt('Enter your age')</script>";
    $age="<script>document.write(age)</script>";
    echo $age ; 
?>

<html>
   <input type="text" name="age" id="age" value="<?php echo ($age) ; ?>"  >
</html>

How to Run WebSocket server.php on VPS

Summary:
I’m trying to run a WebSocket server using Ratchet and ReactPHP on my VPS. However, when executing server.php, I receive the following error:

PHP Fatal error:  Uncaught RuntimeException: Failed to listen on "tcp://0.0.0.0:2053": Address already in use (EADDRINUSE) in /var/www/meetwithchat/vendor/react/socket/src/TcpServer.php:188

Even after killing the process that appears to be using port 2053, a new process is automatically restarted and binds to the same port. Consequently, my client-side code in script.js fails to establish a WebSocket connection.

I also get

WebSocket connection to 'wss://meetwithchat.com:2053/' failed: 

Error on Chrome Console.

server.php:

<?php
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
require __DIR__ . '/vendor/autoload.php';

class ChatServer implements MessageComponentInterface {
    // [Properties and constructor omitted for brevity]

    public function onOpen(ConnectionInterface $conn) {
        // [Code omitted for brevity]
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        // [Code omitted for brevity]
    }

    // Additional methods (matchUsers, endChatForBoth, onClose, onError)...
}

// Create the event loop
$loop = ReactEventLoopFactory::create();

// Set up the SSL context
$context = [
    'ssl' => [
        'local_cert' => '/etc/ssl/certs/cloudflare_origin.crt',
        'local_pk'   => '/etc/ssl/private/cloudflare_origin.key',
        'allow_self_signed' => true,
        'verify_peer' => false
    ]
];

// Create a TCP socket listening on all interfaces on port 2053
$socket = new ReactSocketServer('0.0.0.0:2053', $loop);
// Wrap it with SSL
$secureSocket = new ReactSocketSecureServer($socket, $loop, $context);

// Set up the WebSocket server
$server = new RatchetServerIoServer(
    new RatchetHttpHttpServer(
        new RatchetWebSocketWsServer(
            new ChatServer()
        )
    ),
    $secureSocket,
    $loop
);

error_log("Secure WebSocket server is running on port 2053...");
$server->run();
?>

script.js:

let ws = new WebSocket("wss://meetwithchat.com:2053/");

ws.onopen = function () {
    // Send initial messages to set gender and preference
    ws.send(JSON.stringify({ type: "setGender", gender: genderValue }));
    ws.send(JSON.stringify({ type: "setPreference", preference: preferenceValue }));
};

ws.onmessage = function (event) {
    const data = JSON.parse(event.data);
    if (data.type === "match") {
        // Handle a successful match
    } else if (data.type === "message") {
        // Append message to chat UI
    } else if (data.type === "chatEnded") {
        alert("Partner has left the chat. Chat ended!");
        resetChat();
    }
};

ws.onclose = function () {
    resetChat();
};

“Composer SSL certificate problem: unable to get local issuer certificate (curl error 60)” [duplicate]

I am trying to install spatie/laravel-medialibrary using Composer in my Laravel project, but I keep getting an SSL certificate error. Here’s the command I run:

composer require "spatie/laravel-medialibrary:^10.0.0"
And this is the error message I receive:
https://repo.packagist.org could not be fully loaded (curl error 60 while downloading https://repo.packagist.org/packages.json:
SSL certificate problem: unable to get local issuer certificate), package information was loaded from the local cache and may be out of date

In CurlDownloader.php line 390:

curl error 60 while downloading https://repo.packagist.org/p2/spatie/laravel-medialibrary.json: SSL certificate problem:
unable to get local issuer certificate

Checked my php.ini file and made sure curl.cainfo is set correctly:

Environment:

  • OS: Windows
  • PHP version: 8.1.10
  • Composer version: 2.8.4
  • Server: Laragon

What I’ve tried so far:

Checked my php.ini file and made sure curl.cainfo is set correctly:

`php -r “echo ini_get(‘curl.cainfo’);”

Output: C:laragonetcsslcacert.pem

Disabled SSL temporarily in Composer:

composer config --global disable-tls true
composer config --global secure-http false

But the error still persists.

Tried clearing Composer cache:

composer clear-cache

but I still get the same error.

Error on PHP 8.4-fpm IMAP package install with Dockerfile

In my Dockerfile for php8.4-fpm i am installing IMAP package with the following commands:

FROM php:8.4-fpm
[...]
RUN docker-php-ext-configure imap --with-kerberos --with-imap-ssl && 
    docker-php-ext-install imap

But got an error:

process "/bin/sh -c docker-php-ext-configure imap --with-kerberos --with-imap-ssl" did not complete successfully: exit code: 1

How to solve it?

Track the connection status from the backend?

I am Working on a Chat Application developed By laravel (Laravel Reverb) and reactjs.

Two Projects are developed separately and also i am configuring with Laravel Passport.

The Backend basically serve the Api and Chat server where the frontend configuring the chat server and implementing Apis.

For Tracking User Activity (Online or Offline Status) I am Configuring Presence Channel.

Previously, my task was, when a user connected to the channel A User History Saved on Redis. Which Perfectly Work without any issue.

Now I am trying to configure user disconnected system. When a user is disconnected from the channel it will remove that user history from Redis.

Now Every where i am founding calling a api from frontend so that it can remove that entity.

But I need to Determine the user disconnection from Backend cause When connection stablish i can see Connection stablish message on debug panel and also connection closed message inside debug console.

So I think i can track the connection and disconnection from the server side rather than implementing something on frontend.

So is there a way to track the connection status from the backend side? I can’t Handel The Laravel Reverb Disconnect When Tab is closed

I am giving you the whole code. So that any one can understand what is doing and what to do next.

<?php

namespace AppListeners;

use AppEventsUserStatus;
use IlluminateContractsQueueShouldQueue;
use IlluminateQueueInteractsWithQueue;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesRedis;

class UserStatusListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(UserStatus $event): void
    {
        $user_id = $event->user_id;
        $status = $event->status;

        Log::info("User Status Changed: User ID {$user_id} is now {$status}");

        if ($status === "connected") {
            // Store user as online in Redis
            Redis::setex("user:online:{$user_id}", 300, json_encode([
                'user_id' => $user_id,
                'status' => 'online',
                'last_seen' => now()->toDateTimeString(),
            ]));
        } elseif ($status === "disconnected") {
            // Remove user from Redis (user disconnected)
            Redis::del("user:online:{$user_id}");
        }
    }
}

This is my UserStatusListner Where I am determining the User Connected status and store this inside Redis.

<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateContractsBroadcastingShouldBroadcastNow;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;


class UserStatus implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $user_id;
    public $status;

    /**
     * Create a new event instance.
     */
    public function __construct($user_id, $status)
    {
        $this->user_id = $user_id;
        $this->status = $status;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, IlluminateBroadcastingChannel>
     */
    public function broadcastOn()
    {
        return new PresenceChannel('presence-user-status-'.$this->user_id);
    }

    public function broadcastAs()
    {
        return 'user.status'; // Custom event name
    }
}

This is my UserStatus Event Where i called when a Presence Channel is successfully connected.

Broadcast::channel('presence-user-status-{user_id}', function ($user, $user_id) {
    // Check the authenticated user from multiple guards
    $staffUser = Auth::guard('staff_users')->user();
    $businessUser = Auth::guard('business_users')->user();
    $normalUser = Auth::guard('users')->user();

    $userData = [];
    if ($normalUser && (int) $normalUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $normalUser->user_id,
            'type' => "user"
        ];

    }

    if ($businessUser && (int) $businessUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $businessUser->user_id,
            'type' => "business"
        ];
    }

    if ($staffUser && (int) $staffUser->staff_id === (int) $user_id) {
        $userData = [
            'user_id' => $staffUser->staff_id,
            'type' => "staff"
        ];
        
    }

    if (!empty($userData)) {
        Redis::setex("user:online:{$user_id}", 300, json_encode([
            'user_id' => $userData['user_id'],
            'type' => $userData['type'],
            'last_seen' => now()->toDateTimeString(),
        ]));
        
        // Fire the UserStatus event for tracking
        event(new UserStatus($userData['user_id'], 'connected'));
        return $userData;
    }

    return false; 
});

This is my channel Code of the Presence Channel inside routes/channels

Here When user is online i can store the data into Redis but when a user is disconnect i can’t track that. Anyone have any advise or any way to resolve this issue?

N.B – I am Using Laravel 10 Version.