Multiple select using select2 in Livewire 3

I want to create multiple selects using the select2 plugin in the livewire component, but the first time I do select “onchange”, my select2 disappears into a regular select option. I’ve used wire:ignore to keep my select element from re-rendering, but it still doesn’t work.

Here is my blade component.

    <div wire:ignore>
      <select class="select2" name="named[]" wire:model="named" multiple="multiple">
               @foreach ($jobs as $job)
                    <option value="{{ $job->id }}">{{ $job->name }}</option>
               @endforeach
      </select>
    </div>



<script>
loadContactDeviceSelect2 = () => {
        $('.select2').select2().on('change',function () {
            var value = $(this).val();
            console.log(value);
            @this.dispatchTo('ticket', 'selectedItemChange',value);
        });
        }
        loadContactDeviceSelect2();
        @this.on('loadContactDeviceSelect2',()=>{
        console.log('Event loadContactDeviceSelect2 triggered');
        loadContactDeviceSelect2();
        });
</script>

##and here is my livewire component##

class Ticket extends Component
{
public $named = [];
public $listeners = [
        'selectedItemChange',
    ];

public function save()
    {
if (is_string($this->named)) {
                $this->named = explode(',', $this->named);
            }

            foreach ($this->named as $userId) {
                DB::table('job_user')->insert([
                    'user_id' => $userId,
                    'job_id' => 2, // Assuming job_id is fixed as 2 in your case
                    'created_at' => Carbon::now(),
                ]);
            }
}

public function hydrate()
    {
        $this->dispatch('loadContactDeviceSelect2');
    }
public function selectedItemChange($value)
    {
$this->named = explode(',', $value);
}

public function render()
    {
$jobs = User::all();

        return view('livewire.ticket', ['jobs' => $jobs]);
}

}

Livewire image preview upload not showing

I am experiencing an issue where PNG images, specifically screenshots taken on my Mac, do not display correctly in the image preview after being uploaded via Livewire. The temporary URL is generated successfully, but the image itself doesn’t show up. Interestingly, if I manually copy the URL and paste it into the browser, the image loads just fine.

PNG files downloaded from Google or other sources load and display without issues. The problem only seems to occur with PNG screenshots taken on macOS.

This issue occurs both in my local development environment and on the server. I’ve already checked my Livewire configuration and confirmed that the PNG format is included in the preview_mimes array.

'temporary_file_upload' => [
    'disk' => 's3',        // Example: 'local', 's3'              | Default: 'default'
    'rules' => ['required', 'file', 'mimes:png,jpg,jpeg', 'max:12288'],
    // Example: ['file', 'mimes:png,jpg']  | Default: ['required', 'file', 'max:12288'] (12MB)
    'directory' => 'tmp',   // Example: 'tmp'                      | Default: 'livewire-tmp'
    'middleware' => null,  // Example: 'throttle:5,1'             | Default: 'throttle:60,1'
    'preview_mimes' => [   // Supported file types for temporary pre-signed file URLs...
        'png', 'gif', 'bmp', 'svg', 'wav', 'mp4',
        'mov', 'avi', 'wmv', 'mp3', 'm4a',
        'jpg', 'jpeg', 'mpga', 'webp', 'wma', 'avif',
    ],
    'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated...
],

I use:
“laravel/framework”: “^11”,
“livewire/livewire”: “^3.4”,
“php”: “^8.2”,

can somebody help me?
Thanks

enter image description here
enter image description here

Tried to describe what problem I am facing when i upload screenshots on my web, and I expect to get help to solve it.

CakePHP giving error 302 (due to sessions?) after migrating a website

I have to migrate CakePHP 1.3.0 website which uses PHP 5.6 version, in this case from CPanel to Plesk, I tried using Plesk Migrator extension, for those who don’t know it, it connects to source server and brings everything automatically, but for this website gave me issues. I tried migrating the website manually but I got issues too.

When previewing the website I only get “ERR_TOO_MANY_REDIRECTS” or 302 codes. Researching I found out that this problem could be related to sessions, but I’m not 100% sure that’s the problem.

This is the current core.php file (I have to censor sensitive info):

<?php
    if( isset($_SERVER['REMOTE_ADDR'] ) && ($_SERVER['REMOTE_ADDR'] == 'XX.XXX.XXX.XX' || $_SERVER['REMOTE_ADDR'] == 
'XX.XX.XXX.XXX'))
  {
    Configure::write('debug', 1);
  }

  else
          Configure::write('debug', 1);


    Configure::write('App.encoding', 'UTF-8');

    Configure::write('Routing.prefixes', array('admin'));

    define('LOG_ERROR', 2);

    Configure::write('Session.save', 'php');

    Configure::write('Session.cookie', 'CAKEPHP');

    Configure::write('Session.timeout', '120');

    Configure::write('Session.start', true);

    Configure::write('Session.checkAgent', false);

    Configure::write('Security.level', 'low');

    Configure::write('Security.salt', 'f7e2b4XXXXXXXXXXXXXXXXXXXXXXXXXXeed5a');

    Configure::write('Acl.classname', 'DbAcl');
    Configure::write('Acl.database', 'default');

    Cache::config('default', array('engine' => 'File', 'path'=> CACHE, 'duration' => '1 day'));

    Configure::write('Cache.disable', true);
    Configure::write('Cache.check', true);
    
  Configure::write ('site_env', 'production');

if( isset($_SERVER['REMOTE_ADDR'] ) && ($_SERVER['REMOTE_ADDR'] == 'XX.XX.XXX.XXX'))
   Configure::write ('site_env', 'development');
  
  Configure::write( 'App.theme', 'forma');
  
  Configure::write( 'App.mail_form', '[email protected]');

  Configure::write ('Google.map_key', 'ABQIAAAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2n7Q');

?>

Looks like this website was using PHP to persist sessions. According to official documentation it saves session files as indicated by php.ini. php.ini default location is session.save_path = "/var/lib/php/session" , which exists and it has permissions, since other domains are using the same one too. For some reason I don’t understand it’s not working.

The DocumentRoot and the database connection are established, I’m sure because if I remove any of both the website returns different errors.

What can I do to make it work (in case of sessions are the source of the problem)? I don’t mind moving to cake or database sessions if these are easier to configure. In any case I wasn’t able to configure them because I didn’t find many helpful guides.

I changed session.save_path value to the following one:
/var/www/vhosts/domain.com/httpdocs/tmp/sessions

[root@server02 ~]# ls -lah /var/www/vhosts/domain.com/httpdocs/tmp/
total 16K
drwxr-xr-x  7 formamus psacln    73 abr  6  2020 .
drwxr-x--- 18 formamus psaserv 4,0K ago 13 11:32 ..
drwxrwxrwx  5 formamus psacln    51 abr  6  2020 cache
drwxrwxrwx  2 formamus psacln    26 abr  6  2020 files
drwxrwxrwx  2 formamus psacln     6 abr  6  2020 logs
drwxrwxrwx  2 formamus psacln  8,0K ago 14 10:59 sessions
drwxrwxrwx  2 formamus psacln     6 abr  6  2020 tests

Now session files are being created and saved in the specified path, but the website still gives error 302 (I already tried with different browsers and deleting cache), so I don’t know which is the problem.

Schedule posts in WordPress not working properly

I’ve got this script in PHP to schedule my posts. I don’t see an error with this code. Can you help me? It should schedule all drafts in future, but it’s publishing it at once right now.

<?php
// Wczytanie środowiska WordPress
require_once('wp-load.php');

// Parametry
$min_posts_per_day = 1;  // Minimalna liczba postów na dzień
$max_posts_per_day = 5;  // Maksymalna liczba postów na dzień
$start_hour = 10;        // Najwcześniejsza godzina publikacji
$end_hour = 18;          // Najpóźniejsza godzina publikacji
$total_posts = 137;      // Liczba postów do zaplanowania
$end_date = strtotime('2024-11-01'); // Ostateczna data zakończenia publikacji

// Pobierz aktualną strefę czasową z ustawień WordPressa
$timezone_string = get_option('timezone_string');
if (!$timezone_string) {
    $timezone_string = 'UTC'; // Jeśli nie ustawiono strefy czasowej, użyj UTC
}
$timezone = new DateTimeZone($timezone_string);
$start_date = new DateTime('2024-08-15', $timezone);

// Pobierz wszystkie szkice postów
$args = array(
    'post_type'      => 'post',
    'post_status'    => 'draft',    // Tylko szkice
    'posts_per_page' => $total_posts
);
$draft_posts = get_posts($args);

if ($draft_posts) {
    $scheduled_posts = 0;
    $current_date = clone $start_date;

    while ($scheduled_posts < $total_posts && $current_date->getTimestamp() <= $end_date) {
        // Losowa liczba postów na dzień (od 1 do 5)
        $posts_per_day = rand($min_posts_per_day, $max_posts_per_day);

        // Ustawienie nowej daty publikacji dla każdego postu
        for ($i = 0; $i < $posts_per_day && $scheduled_posts < $total_posts; $i++) {
            // Losowa godzina publikacji
            $random_hour = rand($start_hour, $end_hour);
            $random_minute = rand(0, 59);
            
            // Ustawienie godziny publikacji
            $current_date->setTime($random_hour, $random_minute);

            // Sprawdzenie, czy nowa data jest późniejsza niż aktualna data i czas
            if ($current_date->getTimestamp() > time()) {
                // Ustawienie daty publikacji i statusu postu
                $post_data = array(
                    'ID'            => $draft_posts[$scheduled_posts]->ID,
                    'post_date'     => $current_date->format('Y-m-d H:i:s'),
                    'post_date_gmt' => get_gmt_from_date($current_date->format('Y-m-d H:i:s')),
                    'post_status'   => 'future',  // Ustawienie statusu na zaplanowany
                );

                // Aktualizacja postu w bazie danych
                wp_update_post($post_data);

                $scheduled_posts++;
            }
        }

        // Przesunięcie daty o losową liczbę dni (od 1 do 5) po zaplanowaniu wszystkich postów na dany dzień
        $days_to_add = rand(1, 5);
        $current_date->modify("+{$days_to_add} days");
    }
    echo 'Daty publikacji postów zostały zmienione.';
} else {
    echo 'Brak szkiców postów do zaplanowania.';
}
?>

And it’s publishing all drafts, without planning posts without schedule it. Where is the problem? Do you see it?

How do I retrieve the current Tenant ID from FilamentPHP?

I have a FilamentPHP application with multi-tenancy enabled. I’m trying to create a link in my Filament navigation that contains the ID of the Tenant I’m currently connected to.

Do you know how I can retrieve the ID of the current Tenant in order to then add a link like /ID/settings in my Filament navigation ?

Thanks,

I’ve tried to consult the documentation, but I can’t seem to find anything that would allow me to retrieve the Tenant ID from the AdminPanelProvider file (into which I’m going to insert my custom navigation element).

How do I format my time in php as hh:mm 00:00 instead of hh:m 00:0 if the minute varible is greater than 10? [duplicate]

I have created a Report that shows the total amount of time. My problem is that if I have minutes which are not a double digit the time is displayed as 00:1. How do i make it such that the time displays as 00:01 if the minute variable is less than 10? See table in image below:

enter image description here

variables:

// Oliver Block Hours

$result = mysqli_query($conn, "SELECT SUM(flt_hrs) AS value_sum FROM college WHERE (captain ='ot1olivertavares' OR examiner ='ot1olivertavares' OR safetyfirst ='ot1olivertavares' OR firstofficer ='ot1olivertavares') and thedate between '2024-07-01' AND '2024-07-31'"); 
$row = mysqli_fetch_assoc($result); 
$olivert1totalfltjuly = $row['value_sum'];

$result = mysqli_query($conn, "SELECT SUM(flt_min) AS value_sum FROM college WHERE (captain ='ot1olivertavares' OR examiner ='ot1olivertavares' OR safetyfirst ='ot1olivertavares' OR firstofficer ='ot1olivertavares') and thedate between '2024-07-01' AND '2024-07-31'  "); 
$row = mysqli_fetch_assoc($result); 
$olivert1totalfltminjuly = $row['value_sum'];

I have tried the below:

<td><?php echo $olivert1totalfltjuly+(int)($olivert1totalfltminjuly/60). ':'. $olivert1totalfltminjuly%60 ?>                     </td>

Laravel JWT middleware not detecting cookies despite being present in browser dev-tools

I’m working on a Laravel project where I’m using JWT (JSON Web Token) for user authentication. The authentication process seems to work correctly, as the JWT token is available in the browser’s Dev Tools as a cookie when the user logs in.

However, I’ve implemented middleware to protect certain routes and check for the presence of this JWT cookie, but the middleware logs an error stating that the cookie is not found or the user is not authorized, even though the cookie is clearly present in the browser.

CheckUserJWT.php

namespace AppHttpMiddleware;

use Closure;
use TymonJWTAuthFacadesJWTAuth;
use TymonJWTAuthExceptionsJWTException;
use IlluminateSupportFacadesLog;

class CheckUserJWT
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Check if the user JWT cookie exists
        if ($request->hasCookie('user')) {
            $token = $request->cookie('user');

            Log::info("Cookie exists");
            try {
                // Attempt to authenticate the user using the JWT token
                $user = JWTAuth::setToken($token)->authenticate();

                // Check if the user is a regular user
                if ($user && $user->role === 'USER') {
                    return $next($request);
                }
            } catch (JWTException $e) {
                Log::error('JWT Authentication error: ' . $e->getMessage());

                // Handle token expiration or invalid token
                return redirect()->route('login');
            }
        }

        Log::warning('User cookie not found or user is not a regular user.');

        // If the cookie doesn't exist or user is not a regular user, redirect to login
        return redirect()->route('login');
    }
}

The middleware is applied to the user.home route:

Route::middleware(CheckUserJWT::class)->group(function () {
    Route::get('/user/home', function () {
        return view('user.home'); 
    })->name('user.home');
});

Issue:

Even though the JWT token is visible in the browser’s Dev Tools under the “Cookies” section, the middleware logs the following warning:

User cookie not found or user is not a regular user.

Keep session active without logging out automatically

I intend to keep my session active without ending for 24 hours. On a computer or on a cell phone with the screen on, it works, but if you lock the screen after two minutes, the session ends. I will post my code:

First I configured php.ini:

session.cookie_lifetime 86400 86400

session.gc_maxlifetime 86400 86400

Now I’m going to publish the code, where I’m using it at the beginning of each page:

$lifetime = 86400; // 24 horas em segundos

if (session_status() == PHP_SESSION_NONE) {   
    session_start(); // Inicia a sessão se ainda não estiver iniciada
}

// Renova o cookie de sessão para que ele expire após 24 horas do último acesso
setcookie(session_name(), session_id(), time() + $lifetime);

// Verifica se a sessão está válida (se as variáveis necessárias estão definidas)
if (!isset($_SESSION["usuarioNome"]) || !isset($_SESSION["usuarioSenha"])) {
    // Se a sessão não é válida, redireciona para a página de login
    header("Location: ../index.html");
    exit;
}

// Inclui a conexão com o banco de dados e define o fuso horário
require_once 'conexao.php';
date_default_timezone_set('Europe/Lisbon');

Where then I have a function that checks whether the session is active or not:

$(function(){
  setInterval(function(){
      $.ajax({
          url: 'logout_status.php',
          method: 'get',
          dataType: 'json'
      })
      .done(function(retorno){
          
      })
      .fail(function(erro){
          window.location.href = '../index.html';
          console.log(erro);
      });
  }, 60000);
});

logout_status.php

require("validsessao.php");
$response = array("logout" => isset($_SESSION['usuarioNome']) ? true : null);
header('Content-Type: application/json');
echo json_encode($response);

Everything works fine, but when I use my cell phone and log in and leave the session logged in and lock the screen, after two minutes the session ends and it shouldn’t end. Can you help?

I’ll just add a note here:

I added logout_status.php to the code, a way to create a log file to understand what happens when I lock the cell phone screen, but if the screen is on, it creates the file and gives me an active session. From the moment I lock the screen it no longer sends information to the text file

require("validsessao.php");
$response = array("logout" => isset($_SESSION['usuarioNome']) ? true : null);
header('Content-Type: application/json');
echo json_encode($response);

if($_SESSION['usuarioId'] == 350){
    $log_file = '/var/www/html/assets/utente/sessao_logs.txt';  // Defina o caminho para o arquivo de log

    $log_data = sprintf(
        "[%s] Sessão iniciada com ID: %s, Nome de Usuário: %s, Status: %sn",
        date("Y-m-d H:i:s"),
        session_id(),
        isset($_SESSION['usuarioNome']) ? $_SESSION['usuarioNome'] : 'N/A',
        session_status() == PHP_SESSION_ACTIVE ? 'Ativa' : 'Inativa'
    );

    file_put_contents($log_file, $log_data, FILE_APPEND);
}

Unable to run a script in ProcessMaker

I’m working on dockerized version of ProcessMaker pm4core-docker and trying to run a script as part of a leave request process, what I want is that once an employee fills out his request and sends it, an email is automatically sent to the manager asking him to verify the request

Unable to create a docker container: Unable to find image 'processmaker4/executor-processmaker-php-3:v1.0.0' locally Error response from daemon: pull access denied for processmaker4/executor-processmaker-php-3, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

Here is the PHP script I’m trying to run :

<?php

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->isSMTP();
    $mail->Host       = 'live.smtp.mailtrap.io';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'api';
    $mail->Password   = '****************************';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('****************@gmail.com', 'Manager'); // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'New leave request';
    $mail->Body    = 'Hello, you have a new leave request to review';
    $mail->AltBody = 'Hello, you have a new leave request to review';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

And here is the error as mentioned previously :

Unable to create a docker container: Unable to find image 'processmaker4/executor-processmaker-php-3:v1.0.0' locally Error response from daemon: pull access denied for processmaker4/executor-processmaker-php-3, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

Prepend URLs with directory if a language is selected (Polylang Synced Pages)

I’m using Polylang on a WordPress page where there are multiple languages and translated pages.
There are two languages who are very similar (90% the same) but a few pages are different, therefore I’ve synced most of the pages.

That means it also syncs the links which then direct to the origin language and the therefore displaying the content in that origin language. I need to be able to add the language directory in front of every URL so the user stays on that language page.

I can get the the directory with the following code:
$language = pll_current_language('slug');

I’ve tried it with the following code but the directory get’s ignored:

add_action( 'init', 'rewrite_page_based_on_language' );

function rewrite_page_based_on_language() {
    global $wp_rewrite;
    $wp_rewrite->page_structure = $wp_rewrite->root . $language . '/%pagename%';
}

i got this error when post json data using cURL , error message :Failed to connect to localhost port 8080: Connection refused

i got this error when post json data using cURL , error message :Failed to connect to localhost port 8080: Connection refused

$session = $this->authentication->getAuth();
        // JSON DATA
$json_data = json_encode($response_data);

        // POST DATA USING CURL
$curl = curl_init();
$username = $session['id'];
$password = $session['name'];
$auth = base64_encode("$username:$password");
        
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost:8080/api/store_book/create",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => 'gzip',
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $json_data, // Only send JSON data
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_HTTPHEADER => array(
   'Content-Type: application/json',
   'Authorization: Basic ' . $auth
 ),
 ));
        
$response = curl_exec($curl);
        
if(curl_errno($curl)) {
  echo 'API Error: ' . curl_error($curl);
 } else {
  echo $response;
 }

Deprecated: Creation of dynamic property PHPMailerPHPMailerPHPMailer::$port is deprecated

I’m trying to send an email via PHPMailer.

My local development environment:

OS Windows 11 Pro
XAMPP with PHP 8.2.12
PHPMailer Version 6.9.1

The code looks like this:

      try {
        $phpMailer = new PHPMailer(true);
          
        $phpMailer->CharSet = $this->charSet;

        // server settings
        $phpMailer->isSMTP();
        $phpMailer->Host       = $this->mailHost;
        $phpMailer->SMTPAuth   = true;
        $phpMailer->Username   = $this->mailUser;
        $phpMailer->Password   = $this->mailPwd;
        $phpMailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $phpMailer->port       = $this->mailPort; // is set to 587
          
            // recipients
        $phpMailer->setFrom($this->from, 'test.test');
        $phpMailer->addAddress($addressMail);

        // content
        $phpMailer->isHTML($this->isHtml);
        $phpMailer->Subject = $this->subject;
        $phpMailer->Body    = $this->body;
          
        // add attachments
        if (!empty($attachments) && $addAttachment) {
          for ($i = 0; $i < count($attachments["filePaths"]); $i++) {
            if ( count($attachments["filePaths"]) > 0
              && array_key_exists( $i, $attachments["fileNames"])) {
              $phpMailer->AddAttachment($attachments["filePaths"][$i], $attachments["fileNames"][$i]);
            }
          }
        }

        $returnValue = $phpMailer->send();
      } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$phpMailer->ErrorInfo}";
      }

However, I get the message:
Deprecated: Creation of dynamic property PHPMailerPHPMailerPHPMailer::$port is deprecated

What is the reason for this?

Am I maybe using the wrong version (upgrade PHPMailer)?

I tried to switch the sending to SMTP, but my server does not support it and therefore no mails are sent.

With port 465 and TLS mails are sent, but I get the info that the port is outdated.

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘super_cms_page_translations.custom_super_cms_page_id’

please help stack trace cannot be uploaded as it shows the msg looks like spam

I have never used custom_super_cms_page_id in my entire codebase

[2024-08-12 15:14:55] local.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘super_cms_page_translations.custom_super_cms_page_id’ in ‘where clause’ (SQL: select * from super_cms_page_translations where super_cms_page_translations.custom_super_cms_page_id in (84))

Sylius override AvailableProductOptionValuesResolver

With sylius 1.13 i wan’t to override AvailableProductOptionValuesResolver.php

I’ve copied the original class in src/Component/Product/Resolver/AvailableProductOptionValuesResolver.php

and change the namespace and add debug:

<?php

namespace AppComponentProductResolver;
class AvailableProductOptionValuesResolver implements AvailableProductOptionValuesResolverInterface
{
    public function resolve(ProductInterface $product, ProductOptionInterface $productOption): Collection
    {
        dd('modify');

What other changes need to be made for this class to be used? Because here it’s always the file in /vendor/…/AvailableProductOptionValuesResolver that’s used.