question on wordpress multiple options validation functions

I have a question regarding the wordpress options validation. Just want some opinions, I am not asking for examples.

I have multiple field types, would it be the best to have multiple validation functions depending on the types? Or can that be done in 1 single function?

I assume it easier to do the separate validation functions for each type.

Joomla 5.2.3 “Class “Factory” not found”

I have created a custom plugin to list Mp3 files from a directory in a table but I am facing an issue Joomla gives me error: 0 Class "Factory" not found

I am using Joomla 5.2.3 and PHP 8.2 on a Linux server

Here is error log:

2025-01-27T10:39:44+00:00   CRITICAL xxx.xx.xxx.xx  error   Uncaught Throwable of type Error thrown with message "Class "Factory" not found". Stack trace: #0 [ROOT]/plugins/content/mp3streaming/mp3streaming.php(29): PlgContentMp3StreamingHelper::getTracksFromFolder('media/mp3/New...')
#1 [ROOT]/libraries/src/Plugin/CMSPlugin.php(289): PlgContentMp3Streaming->onContentPrepare('com_content.art...', Object(stdClass), Object(JoomlaRegistryRegistry), 0)
#2 [ROOT]/libraries/vendor/joomla/event/src/Dispatcher.php(454): 

Here is mp3streaming.php:

<?php
defined('_JEXEC') or die;

use JoomlaCMSPluginCMSPlugin;
use JoomlaCMSFactory;
use JoomlaCMSRouterRoute;

// Load the helper file
require_once __DIR__ . '/helper.php';

class PlgContentMp3Streaming extends CMSPlugin
{
    protected $autoloadLanguage = true;

    public function onContentPrepare($context, &$article, &$params, $limitstart)
    {
        // Regex to match the shortcode
        $regex = '/{mp3streamings+artist="([^"]+)"(?:s+album="([^"]+)")?}/';

        if (preg_match($regex, $article->text, $matches)) {
            $artist = $matches[1];
            $album = isset($matches[2]) ? $matches[2] : null;
            $folderPath = 'media/mp3/' . $artist;
            if ($album) {
                $folderPath .= '/' . $album;
            }

            // Fetch and display tracks
            $tracks = PlgContentMp3StreamingHelper::getTracksFromFolder($folderPath);
            $html = '<div class="mp3-streaming">';
            $html .= '<h3>Artist: ' . htmlspecialchars($artist) . '</h3>';
            if ($album) {
                $html .= '<h4>Album: ' . htmlspecialchars($album) . '</h4>';
            }
            $html .= '<table class="table table-striped table-hover">';
            $html .= '<thead><tr>
                        <th>Title</th>
                        <th>Player</th>
                        <th>Download</th>
                        <th>Plays</th>
                        <th>Downloads</th>
                      </tr></thead><tbody>';

            foreach ($tracks as $track) {
                $playUrl = Route::_('index.php?option=com_ajax&plugin=mp3streaming&format=raw&task=play&id=' . $track->id);
                $downloadUrl = Route::_('index.php?option=com_ajax&plugin=mp3streaming&format=raw&task=download&id=' . $track->id);

                $html .= '<tr>
                            <td>' . htmlspecialchars($track->title) . '</td>
                            <td>
                                <audio controls preload="none" onplay="fetch('' . $playUrl . '')">
                                    <source src="' . JUri::root() . $folderPath . '/' . $track->filename . '" type="audio/mpeg">
                                </audio>
                            </td>
                            <td>
                                <a href="' . $downloadUrl . '" class="btn btn-success btn-sm" download>Download</a>
                            </td>
                            <td>' . $track->play_count . '</td>
                            <td>' . $track->download_count . '</td>
                          </tr>';
            }

            $html .= '</tbody></table></div>';
            $article->text = preg_replace($regex, $html, $article->text);
        }
    }
}

What I am missing here?
Anyone can please guide me as I am new in PHP and Joomla.

How to manage correct orientation for upload image

I am using GD library to combine two or more than two images in code igniter. The combining part is working fine. But if I open any image in my system and rotate the image and then try to combine the image then it combines with the rotated way. Means, I need to combine image always with correct orientation. If, any image is not in the correct orientation then the image must be in correct orientation then combine, below is my code.

       private function combine_images($tmp_files, $output_path)
    {
        $merged_image_width = 0;
        $merged_image_height = 0;
        $image_resources = [];

        // Load images, fix orientation, and calculate dimensions for the merged image
        foreach ($tmp_files as $tmp_file) {
            $temp_resource = null;

            // Load the image based on its MIME type
            switch (mime_content_type($tmp_file)) {
                case 'image/jpeg':
                    $temp_resource = imagecreatefromjpeg($tmp_file);
                    break;
                case 'image/png':
                    $temp_resource = imagecreatefrompng($tmp_file);
                    break;
                default:
                    throw new Exception("Unsupported image type: " . mime_content_type($tmp_file));
            }

            // Fix orientation, if needed
            $temp_resource = $this->fix_orientation_and_normalize($tmp_file, $temp_resource);

            // Get dimensions after fixing the orientation
            $width = imagesx($temp_resource);
            $height = imagesy($temp_resource);

            $image_resources[] = $temp_resource;

            $merged_image_width = max($merged_image_width, $width); // Use the widest image
            $merged_image_height += $height; // Total height for vertical stacking
        }

        // Create the merged image
        $merged_image = imagecreatetruecolor($merged_image_width, $merged_image_height);
        $y_offset = 0;

        // Copy each image into the merged image
        foreach ($image_resources as $image_resource) {
            imagecopy($merged_image, $image_resource, 0, $y_offset, 0, 0, imagesx($image_resource), imagesy($image_resource));
            $y_offset += imagesy($image_resource); // Increment vertical offset
            imagedestroy($image_resource); // Free memory for each resource
        }

        // Save the merged image
        $merged_image_path = $output_path . '/merged_image_' . time() . rand(10, 30) . '.jpg';
        imagejpeg($merged_image, $merged_image_path, 100); // Save with maximum quality
        imagedestroy($merged_image); // Free the merged image resource

        return $merged_image_path;
    }

    private function fix_orientation_and_normalize($file_path, $image_resource)
    {
        $exif = @exif_read_data($file_path);

        if (!empty($exif['Orientation'])) {
            switch ($exif['Orientation']) {
                case 3: // Rotate 180 degrees
                    $image_resource = imagerotate($image_resource, 180, 0);
                    break;
                case 6: // Rotate 90 degrees clockwise
                    $image_resource = imagerotate($image_resource, -90, 0);
                    break;
                case 8: // Rotate 90 degrees counter-clockwise
                    $image_resource = imagerotate($image_resource, 90, 0);
                    break;
            }
        }

        // Normalize by resetting EXIF orientation (if you save the image later)
        if (function_exists('imagejpeg')) {
            $temp_path = sys_get_temp_dir() . '/temp_' . uniqid() . '.jpg';
            imagejpeg($image_resource, $temp_path, 100);
            $image_resource = imagecreatefromjpeg($temp_path); // Reload normalized image
            unlink($temp_path); // Clean up temporary file
        }

        return $image_resource;
    }

enter image description here

Uncaught ReferenceError: error2 is not defined – Livewire – Filamentphp:

im having this issue with my laravel-filamentphp code

My login form is disabled… when i enter my credentials and press the login button i get the above errors in the console… Please help me to solve this

Laravel PWA: ServiceWorker registration successful with scope:  https://app.cms.com.ec/admin-panel/
livewire.js?id=38dc8241:1173 Uncaught ReferenceError: error2 is not defined
    at safeAsyncFunction (livewire.js?id=38dc8241:1173:10)
    at generateFunctionFromString (livewire.js?id=38dc8241:1187:16)
    at generateEvaluatorFromString (livewire.js?id=38dc8241:1192:16)
    at normalEvaluator (livewire.js?id=38dc8241:1154:111)
    at evaluateLater (livewire.js?id=38dc8241:1144:12)
    at evaluate (livewire.js?id=38dc8241:1140:5)
    at Function.<anonymous> (livewire.js?id=38dc8241:3560:17)
    at flushHandlers (livewire.js?id=38dc8241:1284:48)
    at stopDeferring (livewire.js?id=38dc8241:1289:7)
    at deferHandlingDirectives (livewire.js?id=38dc8241:1292:5)

livewire.js?id=38dc8241:1123 Alpine Expression Error: error2 is not defined

Expression: "[attribute](e) {
        let execute = () => {
          callAndClearComponentDebounces(component, () => {
            module_default.evaluate(el, "$wire." + directive3.expression, { scope: { $event: e } });
          });
        };
        if (el.__livewire_confirm) {
          el.__livewire_confirm(() => {
            execute();
          }, () => {
            e.stopImmediatePropagation();
          });
        } else {
          execute();
        }
      }"

 <form method=​"post" x-data=​"{ isProcessing:​ false }​" x-on:submit=​"if (isProcessing)​ $event.preventDefault()​" x-on:form-processing-started=​"isProcessing = true" x-on:form-processing-finished=​"isProcessing = false" class=​"fi-form grid gap-y-6" id=​"form" wire:submit=​"authenticate">​…​</form>​grid
handleError @ livewire.js?id=38dc8241:1123
tryCatch @ livewire.js?id=38dc8241:1115
(anonymous) @ livewire.js?id=38dc8241:3877
handler4 @ livewire.js?id=38dc8241:3179
(anonymous) @ livewire.js?id=38dc8241:3207
(anonymous) @ livewire.js?id=38dc8241:3181
livewire.js?id=38dc8241:1173 Uncaught ReferenceError: error2 is not defined

QBO is not sending a payment event to my webhook

I have a implemented a webbook in my laravel application which received the events from QBO.

Problem

I also enabled the Payment event in QBO, and when I applied a payment to a single invoice, QBO successfully sent a payment event to me. However, when I applied a payment to multiple invoices, QBO did not send any event for it.

Any possible solution?

Below one is the screenshot showing a single payment made for both invoices and event not trigger against it.

enter image description here

php foreach loop using the mvc model guidance for a begginer [closed]

New to the PHP and the MVC model structure so please be gentle as I try to figure this out as I know I making some mistakes but cannot figure out where. I have been trying to search and experiment with other submitted questions and YouTube with no luck.

Trying to query my database table personal_best and return a looped list <li></li> for the columns pb_species, pb_weight_lbs and pb_weight_oz for a specific user and display them to my webpage.

I have my model class (class PBInfo extends Dbh)
controller class (class PBInfoContr extends PBInfo)
view class (class PersonalBestInfoView extends PBInfo).

In my model class I have the following:

protected function getPBRecords($userId) {
        $stmt = $this->connect()->prepare('SELECT * FROM personal_best WHERE users_id = ?;');
        $stmt->execute(array($userId));

        while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
            $results [] = $row;
        }
        
        return $results;
    }

In my controller class I have the following:

public function displayPBRecords() {
        $row = $this->getPBRecords();
        $this->row = $pbRecords;
    }

In my view class I have the following code:

public function fetchPBRecords($userId) {
        $personalBestInfo = $this->getPBRecords($userId);
        
        foreach ($pbRecords as $data) {
        echo "<li>".$data['pb_species']."<br>".$data['pb_weight_lbs']." lbs ".$data['pb_weight_oz']." oz</li>";
        }
    }

In the webpage to display the looped data I have:

<?php $personalBestRecord->fetchPBRecords($_SESSION['userid'])?>

I get the following 2 error messages when I try to run the page:

  1. Undefined variable $pbRecords in my view class.
  2. foreach() argument must be of type array|object null given in my view class.

Any suggestions would be appreciated and thanks in advance.

how to make asychronous multiple upload files with progress bar in laravel

I have a problem where during the file upload process the progress bar does not appear. and I also have a problem where during the file upload process I cannot add more files that I want to upload. how can I solve this? btw I use livewire for my laravel application

this is my view:

<div class="w-full lg:ps-64">
    <div class="p-4 sm:p-6 space-y-4 sm:space-y-6">
        <!-- Upload Files Section -->
        <div class="bg-neutral-800 shadow-md rounded-lg p-6 space-y-6">
            <h2 class="text-2xl font-bold text-neutral-100">Upload Files</h2>

            <!-- Success Message -->
            @if (session()->has('success'))
                <div class="p-4 text-lime-500 bg-neutral-700 rounded-lg">
                    {{ session('success') }}
                </div>
            @endif

            <!-- Upload Form -->
            <form wire:submit.prevent="store" class="space-y-6">
                <!-- File Input -->
                <div
                    class="relative border-2 border-dashed border-neutral-600 rounded-lg p-6 flex flex-col items-center justify-center transition hover:bg-neutral-700">
                    <input type="file" wire:model="files" multiple
                        class="absolute inset-0 opacity-0 cursor-pointer z-10">
                    <div class="text-center">
                        <div class="text-neutral-400 mb-2">


                            <i class="fas fa-cloud-upload-alt text-3xl"></i>
                        </div>
                        <p class="text-sm text-neutral-300">
                            <span class="text-neutral-100 font-medium cursor-pointer">Drop your file here</span> or
                            <span class="text-neutral-100 font-medium cursor-pointer">browse</span>
                        </p>
                        <p class="text-xs text-neutral-400 mt-1">Only SVG, PNG, JPG, and MP4 are allowed.</p>
                    </div>
                </div>

                <!-- Validation Error -->
                @error('files.*')
                    <span class="text-sm text-red-500">{{ $message }}</span>
                @enderror

                <!-- Selected Files -->
                @if ($files)
                    <div class="mt-4">
                        <p class="text-sm font-semibold text-neutral-300">Files to Upload:</p>
                        <ul class="space-y-2">
                            @foreach ($files as $index => $file)
                                <li class="flex items-center justify-between bg-neutral-700 p-3 rounded-lg shadow">
                                    <div>
                                        <p class="text-neutral-100 text-sm font-medium truncate">
                                            {{ $file->getClientOriginalName() }}
                                        </p>
                                        <p class="text-xs text-neutral-400">
                                            {{ round($file->getSize() / 1024, 2) }} KB
                                        </p>
                                    </div>
                                    <button type="button" wire:click="removeFile({{ $index }})"
                                        class="text-red-700 hover:text-red-500 transition">
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                            class="size-6">
                                            <path fill-rule="evenodd"
                                                d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-1.72 6.97a.75.75 0 1 0-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06L12 13.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L13.06 12l1.72-1.72a.75.75 0 1 0-1.06-1.06L12 10.94l-1.72-1.72Z"
                                                clip-rule="evenodd" />
                                        </svg>

                                    </button>
                                </li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <!-- Upload Button -->
                <button type="submit"
                    class="w-full py-2 px-4 text-neutral-100 bg-neutral-700 hover:bg-neutral-600 rounded-lg font-medium transition">
                    Upload Files
                </button>
            </form>

            <!-- Progress Bar -->
            <div class="mt-6">
                <div wire:loading wire:target="store" class="w-full bg-neutral-700 rounded-full h-2 overflow-hidden">
                    <div wire:loading wire:target="store" class="bg-neutral-100 h-2 rounded-full animate-pulse"
                        id="progressBar"></div>
                </div>
                <p wire:loading wire:target="store" class="text-xs text-neutral-400 mt-2">Uploading files, please
                    wait...</p>
            </div>
        </div>
    </div>
</div>

and this is my controller:

<?php

namespace AppLivewire;

use AppModelsFile;
use LivewireComponent;
use LivewireWithFileUploads;
use IlluminateSupportFacadesRequest;
use IlluminateSupportFacadesStorage;

class UploadPage extends Component
{

    use WithFileUploads;

    public $files = [];

    public function removeFile($index)
    {
        array_splice($this->files, $index, 1);
    }

    public function store()
    {
        $this->validate([
            'files.*' => 'required|file|mimes:jpg,png,svg,mp4',
        ]);

        foreach ($this->files as $file) {

            sleep(1);

            $path = Storage::disk('r2')->put('uploads', $file);

            File::create([
                'name' => $file->getClientOriginalName(),
                'type' => $file->getMimeType(),
                'path' => $path,
            ]);
        }

        $this->files = [];
        session()->flash('success', 'Files uploaded successfully.');
    }

    public function render()
    {
        return view('livewire.upload-page');
    }
}

I want to know what is wrong with my code and how to solve the problem.

Possible to group class functions and access them by group in PHP/Codeigniter?

i have a library in my codeigniter4 project, now i want to make my lib with lots of functions more clear.

For that i want to know if its possible to group the functions inside the class-defination by a kind of groups and make them accessable by the groupname.

What i mean. The function “my_classfunction” of the lib “mylib” i normaly use by "$this->mylib->my_classfunction()"

Now i think to make groups of functions and access them by a kind of groupname for example “function funcA is in group testA, funB is in group testB”
and use it in a kind like "$this->mylib->testA->funcA()" – is something like this possible, and if, how?

WordPress query_posts with multiple tax_query

The below query only works if $_POST[‘product_cat’] and $_POST[‘sub_category’] return something. How do I make this work if either one of these are empty?

In the end I will have 6 different optional taxonomies so I can’t really have a separate query for every combination.

        query_posts(array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'product_cat',
                    'terms' => $_POST['product_cat'],
                ),
                array(
                    'taxonomy' => 'sub_category',
                    // 'field' => 'slug',
                    'terms' => $_POST['sub_category'],
                ),
                ...
            )
        ));

Use dynamic variables in curl for using API system [closed]

Here is API code for SMS provider site and I want use PHP data variables inside of places that should be fill with changeable variables I tried some solutions but no SMS received after test that

  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api......',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS =>'{
    "mobile": "xxxx",   ----> i want use php variables like $number  here
    "templateId": xxxx,     ------>  and here 
    "parameters": [
      {
        "name": "NAME",
        "value": "xxx"    ---------> here
      },
      {
          "name":"DESCRIPTION",
          "value":"xxx"         ------------> here
      },
      {
          "name":"ORDER",
          "value":"xxx"        -----> here
          
      }
    ]
  }',
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/json',
      'Accept: text/plain',
      'x-api-key:xxxxxxxx...'
    ),
  ));

  $response = curl_exec($curl);

  curl_close($curl);
 echo $response;

Using fibers with PHP <8.4? [closed]

I am looking into PHP fibers. I read that to use fibers it’s a good idea to have PHP 8.4 but my servers will only support partially 8.1 and partially 8.3 for some time ahead.

Question: Are the changes to fibers in 8.4 so significant that you would advise against using them when not having access to PHP 8.4?

I want to access my static video files with expire time

I want to access my static video files with expire time the video file will only work when it have valid token and expire time.

function generateSignedUrl($file, $secret, $expiry) {
    $md5 = md5($file . $expiry . $secret);
    return "https://example.com/files/$file?md5=$md5&expires=$expiry";
}
$file = "sample-file.mp4";
$secret = "secret-key";
$expiry = time() + 3600;

$signedUrl = generateSignedUrl($file, $secret, $expiry);
echo "Signed URL: $signedUrl";

i try to control it using .htaccess but it not working here is my htaccess code.

RewriteEngine On
RewriteCond %{QUERY_STRING} (^|&)md5=([^&]+) [NC]
RewriteCond %{QUERY_STRING} (^|&)expires=([0-9]+) [NC]
RewriteCond %{TIME} >%3
RewriteRule ^files/(.*)$ - [F]
RewriteCond %{QUERY_STRING} (^|&)md5=([^&]+) [NC]
RewriteCond %{QUERY_STRING} (^|&)expires=([0-9]+) [NC]
RewriteCond %{REQUEST_URI} (.*) [NC]
RewriteCond %{ENV:SECURE_KEY} (secret-key) [NC]
RewriteCond %{QUERY_STRING} (^|&)md5=%{ENV:CALC_MD5} [NC]
RewriteRule ^files/(.*)$ /files/$1 [L]
RewriteCond %{QUERY_STRING} !(md5=.+&expires=.+) [NC]
RewriteRule ^files/ - [F]

i need that url will only work when it was access like this https://example.com/files/sample-file.mp4?md5=545f27b2a8b719c6ed87b1db624b1eb5&expires=1737717458 if someone try to access directly it with return 403 https://example.com/files/sample-file.mp4 this will not work.

How to test and what should be tested for CommandHandler in CQRS?

I have a bunch of handlers. Every of them, eventually, contains code for saving data and releasing events.

How to test CommandHandler? What should be tested? For now it is unit tests, maybe it should be integrational? Should I mock anything or not? Why? Should it be tested at all?

Code of handlers:

public function __invoke(AddCategory $command): int
{
    // some code

    $this->categories->save($category);
    $this->events->publishAll($category->releaseEvents());

    return $category->id()->value;
}

public function __invoke(RenameCategory $command): void
{
    // some code

    $this->categories->save($category);
    $this->events->publishAll($category->releaseEvents());
}

At the moment my tests look like that:

Test addition

protected function setUp(): void
{
    $this->categories = new TestCategoryRepository();
    $this->events     = new TestEventDispatcher();
    $this->handler    = new AddCategoryHandler($this->categories, $this->events);
}

public function testHandler(): void
{
    // preparing code

    ($this->handler)($command);

    $this->assertTrue($currentEventsCountMoreThanInitialEventsCount);
    $this->assertTrue($currentRepositoryCountMoreThanInitialRepositoryCount);
    $this->assertIsInt($categoryId);
    $this->assertNotNull($category);
}

Test some changes:

protected function setUp(): void
{
    $this->categories = $this->createMock(CategoryRepository::class);
    $this->events     = new TestEventDispatcher();
    $this->handler    = new RenameCategoryHandler($this->categories, $this->events);
}

public function testHandler(): void
{
    // preparing code

    $this->categories->expects($this->once())
                     ->method('getById')
                     ->with($categoryId)
                     ->willReturn($category);

    $this->categories->expects($this->once())->method('save');

    ($this->handler)($command);

    $this->assertTrue($currentEventsCountMoreThanInitialEventsCount);
}

Storing app secret key in database, smart move, over-engineering, or dump act? [closed]

I am building a backend application with some basic user authentication mechanisms, so I did what most would: creating a .env file, putting APP_SECRET inside, and having the application load from it.

Now, since I also have a database dedicated to this application, it should be feasible to store that APP_SECRET inside the database (It could be a table with just one column and one row storing the value) and have the application load from it on start.

Although I’ll still have to supply DB connection credentials via the .env file, so it won’t go anywhere, at least I have one less thing to put inside now.

The question is: Is this a legitimate move? Does this paradigm have any security concerns? Is there a better alternative if I don’t like to generate APP_SECRET and put them in .env?