I get an error Unparenthesized `a ? b : c ? d : e` [duplicate]

I get an error on one of my WordPress plugins, I know it is a php version related error, but I am not able to find the solution, tried many variant but with no luck

value="<?php isset($results->value) && !empty($results->value) ? print_r($results->value) : '' ?>" <?php isset($results->value) && !empty($results->value) ? '' : !empty($results->id) ? print_r('disabled="disabled"') : ''; ?>/> 

Unparenthesized a ? b : c ? d : e is not supported. Use either (a ? b : c) ? d : e or a ? b : (c ? d : e)

Can you help me figure it out?
Thanks!

AMPHP async Function Not Working as Expected in WordPress Plugin

I am developing a WordPress plugin and attempting to use the AmpPHP library to handle asynchronous tasks. I have set up my plugin with the following code:

require_once plugin_dir_path(__FILE__) . 'SMSService.php';
require_once plugin_dir_path(__FILE__) . 'EmailService.php';
require_once plugin_dir_path(__FILE__) . '/../libraries/Amp/vendor/autoload.php';

use function Ampasync;
use function Ampdelay;

class MessageService
{
    public $smsService;
    public $emailService;

    public function __construct()
    {
    }

    public function sendSMS($to, $body, $from = null)
    {
        $this->smsService = new SMSService();
        async(function () use ($to, $body, $from) {
            $this->smsService->handle($to, $body, $from);
        });
    }
}

In my implementation, I call the sendSMS method, but the asynchronous code inside async does not seem to execute.

I installed the AmpPHP library using composer require amphp/amp. After calling the sendSMS method, I also attempted to run EventLoop::run() to process the asynchronous tasks. However, despite this, the sendSMS method executes synchronously.

I expected the asynchronous function to run separately and not block the execution of subsequent code. Could someone help me understand why the async function is not working as expected in this setup?

How to play a video in this PHP player code to use in a mobile app using an embed link [closed]

I found a player (SE player) coded through PHP, and it’s working if I use it on my mobile app using this embed link: “https://mywebsite.com/player.php?video_id=imdb_id.” I just want to ask how this PHP code is used on other video streaming APIs such as vidsrc, soap2day, 123movies, and others using an IMDB link or embed link.

<?php
////////////////////////// PLAYER SETTINGS ///////////////////////////////////////////////

$player_font = "Poppins";

$player_bg_color = "000000";
$player_font_color = "ffffff";
$player_primary_color = "34cfeb";
$player_secondary_color = "6900e0";

$player_loader = 1;

// preferred server - you can choose server that will be on top of the list and open after
// clicking play button, works only for quality >= 720p
// options are: vidlox = 7, fembed = 11, mixdrop = 12, upstream = 17, videobin = 18,
// doodstream = 21, streamtape = 25, streamsb = 26, voe = 29, ninjastream = 33
$preferred_server = 0; // paste only server number, leave 0 for no preference

$player_sources_toggle_type = 2;

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
if (isset($_GET['video_id'])) {
  $video_id = $_GET['video_id'];
  $is_tmdb = 0;
  $season = 0;
  $episode = 0;
  $player_url = "";
  if (isset($_GET['tmdb'])) {
    $is_tmdb = $_GET['tmdb'];
  }
  if (isset($_GET['season'])) {
    $season = $_GET['season'];
  } else if (isset($_GET['s'])) {
    $season = $_GET['s'];
  }
  if (isset($_GET['episode'])) {
    $episode = $_GET['episode'];
  } else if (isset($_GET['e'])) {
    $episode = $_GET['e'];
  }
  if (!empty(trim($video_id))) {
    $request_url = "https://getsuperembed.link/?video_id=$video_id&tmdb=$is_tmdb&season=$season&episode=$episode&player_font=$player_font&player_bg_color=$player_bg_color&player_font_color=$player_font_color&player_primary_color=$player_primary_color&player_secondary_color=$player_secondary_color&player_loader=$player_loader&preferred_server=$preferred_server&player_sources_toggle_type=$player_sources_toggle_type";
    if (function_exists('curl_version')) {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $request_url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($curl, CURLOPT_TIMEOUT, 7);
      curl_setopt($curl, CURLOPT_HEADER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      $player_url = curl_exec($curl);
      curl_close($curl);
    } else {
      $player_url = file_get_contents($request_url);
    }
    if (!empty($player_url)) {
      if (strpos($player_url, "https://") !== false) {
        header("Location: $player_url");
      } else {
        echo "<span style='color:red'>$player_url</span>";
      }
    } else {
      echo "Request server didn't respond";
    }
  } else {
    echo "Missing video_id";
  }
} else {
  echo "Missing video_id";
}
?>

I tried to change this “https://getsuperembed.link/?video_id=” to this “https://vidsrc.io/embed/movie?imdb=” for example in vidsrc, but the link is not working or didn’t play on my mobile app. Is there other way to used the code in other streaming using embed link that play on my mobile app using a player from PHP code. By the way, my mobile is connected to my wordpress data that all my movies and anime can access on my mobile app.

Rates and Transit Times API is giving 400 Bad Request error if I change the account number using codeigniter 4

I am working with program where we need to fetch details from fedex Rates and Transit API, the API works fine with the account number which is linked to API project in developers portal but once I try to change another account number the API returns “file_get_contents(https://apis.fedex.com/rate/v1/rates/quotes): Failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request” error ..
can’t find the enough information on API documentation and in search.

Qustion 1: I want to confirm is there any restriction on API end that we can fetch data from only those accounts which are linked? or we need to change our parametes?

Question 2: I’ve used try catch block to handle error but this errors still crash the application, any way to handle this?

public function callAPI()
{

    $this->accountNumber->set_value('11111111');


    //set shipper postalcode and country code 
    $this->shipper->set_postalCode(12345);
    $this->shipper->set_countryCode('US');
    $this->shipper->set_residential(false);



    //set recipient postalcode and country code 
    $this->recipient->set_postalCode(456789);
    $this->recipient->set_countryCode('US');
    $this->recipient->set_residential(true);


    //set weight and units 
    $this->weight->set_units('LB');
    $this->weight->set_value(26);



   $this->requestedShipment->set_shipper(['address' => $this->shipper]);
   $this->requestedShipment->set_recipient(['address' => $this->recipient]);
   $this->requestedShipment->set_requestedPackageLineItems(array(['weight' => $this->weight]));


    //set pickup type 
    //types: "CONTACT_FEDEX_TO_SCHEDULE", "DROPOFF_AT_FEDEX_LOCATION", "USE_SCHEDULED_PICKUP"
    $this->requestedShipment->set_pickupType("USE_SCHEDULED_PICKUP");

    // set type of rate to be returned 
    //types: "LIST", "INCENTIVE", "ACCOUNT", "PREFERRED" (see documentation for explanations)
    $this->requestedShipment->set_rateRequestType(['ACCOUNT']);


    //set shipment date 
    $this->requestedShipment->set_shipDateStamp("2023-08-17");


  $this->rateRequestControlParameters->set_return_tranist(true);
    $accountNumberJSON = json_encode($this->accountNumber);
    $requestedShipmentJSON = json_encode($this->requestedShipment);

     $url = "https://apis.fedex.com/oauth/token";


    //client id is api key and client secret is secret key
    $data = [
        'grant_type' => 'client_credentials',
        'client_id' => 'my_clinet_id',
        'client_secret' => 'my_clinet_secret'
    ];

    $options = array(
        'http' => array(
            'header' => "Content-type: application/x-www-form-urlencoded",
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );

    $context = stream_context_create($options);
    $resp = file_get_contents($url, false, $context);
    $response_data = json_decode($resp);
    $access_token = $response_data->access_token;
    
    //calls function if token is working (token changes every minute)
    if (isset($access_token)) {
        echo $this->get_rates($access_token, $this->accountNumber, $this->requestedShipment, $this->rateRequestControlParameters); 
    }
}

function get_rates($token, $acct, $ship, $rateReqCtrlPara)
{
    $url = "https://apis.fedex.com/rate/v1/rates/quotes";

    $data = ['accountNumber' => $acct, 'requestedShipment' => $ship, 'rateRequestControlParameters' => $rateReqCtrlPara, 'carrierCodes' => array('FDXG') ];
    $options = array(
        'http' => array(
            'header' => [
                "Content-type: application/json",
                "Authorization: Bearer {$token}",
                "X-locale: en_US"
            ],
            'method' => 'POST',
            'content' => json_encode($data)
        )
    );

    $context = stream_context_create($options);
    try{ 
            $resp_data = file_get_contents($url, false, $context); //error here
    }
    catch (exception $e) { echo $e; }
  return $resp_data;
}

Error “WebAssetManager is locked, you came late” in Joomla

I’m using Joomla 4.4, and this code to load a module to display it in a plugin.

echo JHtml::_('content.prepare', '{loadmoduleid 16}');

error

But the website say error WebAssetManager is locked, you came late

If I use {loadmoduleid 16} in a Joomla article it still working fine. I don’t sure what’s wrong?

Please help.

Thanks

WebAssetManager is locked, you came late

Savsoft correct_answer

after creating and starting the quiz, how can I create a session variable that for each answer I give, the application evaluates whether it is a correct answer and displays in the header the total number of correct answers each time the button is chosen NEXT?

I tried to initialize a session variable $_SESSION[‘counter’] in the quiz.php controller in the saved_answer method, but it is not incremented.

What is the best way to validate an uploaded file in drupal 10

I’m very new to drupal and it has been one hell of a ride already.

I’m creating a custom module where people can fill out a form to apply for a job. Of course I want to implement form validation but it goes wrong when I want to validate the uploaded file.

I can’t seem to find a clear way to validate uploaded files, like anywhere. I’m trying to rely on my php knowledge but of course it is not entirly te same when it comes down to drupal.

I’m providing you guys with something I had now, which clearly doesn’t work, but I would like to ask what you would say is the best way to validate uploaded files? And without installing third party modules..

What I tried:

// Validate the uploaded file
$validators = ['file_validate_extensions' => ['docx doc pdf jpg jpeg png']];
$file = file_save_upload('cv', $validators, FALSE, 0);

if (!$file) {
    // Add error message if the file isn't validated
    $form_state->setErrorByName('cv', $this->t('Uw CV heeft een niet-toegestane extensie. Probeer het opnieuw.'));
} else {
    // Set the correct file in the form state
    $form_state->setValue('cv', $file);
}

Unfortunately, file_save_upload is not recognized because it’s deprecated and drupals documentation is a bit confusing to me..

Thanks in advance!

Remote Xdebug and 504 on lost connection

I set up a remote Xdebug to work through the SSH tunnel. Everything works perfectly, but if I eventually drop the SSH connection (lost internet connection, switch VPNs or just close the laptop screen) my remote website drops into 504 error. Restarting nginx and php-fpm doesn’t help. The website simply wakes up on its own after 15-20 min.

Seems that there is a kind of timeout somewhere? Can you help where? And what can I do to prevent the site dropping into 504?

php.ini:

zend_extension=xdebug
xdebug.mode=debug
xdebug.client_host=127.0.0.1
xdebug.client_port=9093
xdebug.start_with_request=yes
xdebug.remote_handler = dbgp
xdebug.idekey=PHPSTORM

(yes, I use port 9093 for Xdebug and it works)

To create SSH tunnel I use putty:

enter image description here

How can I restrict Filament select field options to the ones explicitly associated with the logged in user?

In my application, users can add their residential properties and create a listing based on that listing. Users can have many

  • The Listing model relation
    public function property(): BelongsTo
    {
        return $this->belongsTo(Property::class);
    }
  • The Property model relations
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

   public function listing(): HasMany
    {
        return $this->hasMany(Listing::class);
    }
  • The field to select the property that the Listing is based on
            Select::make('property_id')
                        ->relationship('property', 'house_no')
                        ->label('Stand Number')
                        ->createOptionForm([
                            Section::make('Details')->schema([
                                Select::make('area')
                                    ->options([
                                        "Bloomingdale" => "Bloomingdale",
                                        'Ashdown Park' => "Ashdown Park"
                                    ]),
                                TextInput::make('house_no')
                                    ->required()
                                    ->label('House Number')
                                    ->numeric(),
                                TextInput::make('street')
                                    ->nullable(),
                                TextInput::make('families')
                                    ->label('Families On The Property')
                                    ->required()
                                    ->numeric(),
                            ]),

My current setup of this field allows users that are not associated with the property to select it and associate it with their listing.

I want users’ property options to be limited to the ones they added. How do I do that?

Laravel 8.12 Composer Install Error: “Target class [request] does not exist

I’m encountering an error while running composer install in my Laravel 8.12 project with PHP 7.4.33. The error message is:

In Container.php line 879:
  Target class [request] does not exist.

In Container.php line 877:
  Class "request" does not exist

Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Nothing to install, update or remove
Package fruitcake/laravel-cors is abandoned, you should avoid using it. No replacement was suggested.
Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
Generating optimized autoload files
> IlluminateFoundationComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi

In Container.php line 879:
  Target class [request] does not exist.

In Container.php line 877:
  Class "request" does not exist

Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

Steps I’ve Already Taken:

Cleared Composer cache (composer clear-cache).
Verified aliases in config/app.php.
Regenerated Composer autoload files (composer dump-autoload).
Deleted vendor directory and composer.lock, then reinstalled dependencies (composer install).
Additional Information:

Laravel version: 8.12
PHP version: 7.4.33
Abandoned packages: fruitcake/laravel-cors and swiftmailer/swiftmailer
What I Need Help With:

Any guidance on resolving the “Target class [request] does not exist” error.
Suggestions for updating or replacing the abandoned packages.
Any additional troubleshooting steps I might have missed.
Thank you!

I get error 40532 when I try to connect to Azure SQL

I am trying to connect to my azure sql database with the script below.
But I get the message error code = 40532
I have added my IP address to my firewall.
I can log in via portal.azure.com and open the Play SQL database.

What am I doing wrong?

<?php
    // Variables to tune the retry logic.
    $connectionTimeoutSeconds = 30;  // Default of 15 seconds is too short over the Internet, sometimes.
    $maxCountTriesConnectAndQuery = 3;  // You can adjust the various retry count values.
    $secondsBetweenRetries = 4;  // Simple retry strategy.
    $errNo = 0;
    $serverName = "sql-xxxx-xxxx-xxxxx.database.windows.net";
    $connectionOptions = array("Database"=>"AdventureWorks",
       "Uid"=>"[email protected]", "PWD"=>"itssecret", "LoginTimeout" => $connectionTimeoutSeconds);
    $conn = null;
    $arrayOfTransientErrors = array('08001', '08002', '08003', '08004', '08007', '08S01');
    for ($cc = 1; $cc <= $maxCountTriesConnectAndQuery; $cc++) {
        // [A.2] Connect, which proceeds to issue a query command.
        $conn = sqlsrv_connect($serverName, $connectionOptions);
        if ($conn === true) {
            echo "Connection was established";
            echo "<br>";

            $tsql = "SELECT Name FROM Production.ProductCategory";
            $stmt = sqlsrv_query($conn, $tsql);
            if ($stmt === false) {
                echo "Error in query execution";
                echo "<br>";
                die(print_r(sqlsrv_errors(), true));
            }
            while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                echo $row['Name'] . "<br/>" ;
            }
            sqlsrv_free_stmt($stmt);
            sqlsrv_close( $conn);
            break;
        } else {
            // [A.4] Check whether the error code is on the list of allowed transients.
            $isTransientError = false;
            $errorCode = '';
            if (($errors = sqlsrv_errors()) != null) {
                foreach ($errors as $error) {
                    $errorCode = $error['code'];
                    $isTransientError = in_array($errorCode, $arrayOfTransientErrors);
                    if ($isTransientError) {
                        break;
                    }
                }
            }
            if (!$isTransientError) {
                // it is a static persistent error...
                echo("Persistent error suffered with error code = $errorCode. Program will terminate.");
                echo "<br>";
                // [A.5] Either the connection attempt or the query command attempt suffered a persistent error condition.
                // Break the loop, let the hopeless program end.
                exit(0);
            }
            // [A.6] It is a transient error from an attempt to issue a query command.
            // So let this method reloop and try again. However, we recommend that the new query
            // attempt should start at the beginning and establish a new connection.
            if ($cc >= $maxCountTriesConnectAndQuery) {
                echo "Transient errors suffered in too many retries - $cc. Program will terminate.";
                echo "<br>";
                exit(0);
            }
            echo("Transient error encountered with error code = $errorCode. Program might retry by itself.");
            echo "<br>";
            echo "$cc attempts so far. Might retry.";
            echo "<br>";
            // A very simple retry strategy, a brief pause before looping.
            sleep(1*$secondsBetweenRetries);
        }
        // [A.3] All has gone well, so let the program end.
    }
?>

I m not sure what ive tried but nothings is working. I think it has to do with rights or something. But I can’t figure it out.

nginx conf on docker same for xampp

I’m following a youtube tutorial on how to setup docker with PHP. I came across this code for nginx configuration.

server {
    listen 80;
    server_name localhost;
    root /app/public;
    index index.php;

    location ~ .php$ {
       fastcgi_pass   app:9000;
       fastcgi_index  index.php;
       fastcgi_param REQUEST_METHOD $request_method;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       include        fastcgi_params;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
}

I’m wondering how can I setup this configuration to work the same way with xampp.

For example now. if I go to localhost/un-known-text it redirects back to index.php which is not the default behaviour of xampp.

Any help would be appreciated.

Database Migration Failed in laravel

Schema::create(‘jobs’, function (Blueprint $table) {
$table->id();

        $table->string('title');
        $table->text('description');
        $table->unsignedInteger('salary');
        $table->string('location');
        $table->string('category');
        $table->enum('experience', ['entry', 'intermediate', 'senior']);
        $table->timestamps();
    });

I’ve tried to seed the database with a factory using php artisan migrate:refresh –seed but i get this error:

SQLSTATE[42S01]: Base table or view already exists: 1050 Table ‘jobs’ already exists (Connection: mysql, SQL: create table jobs (id bigint unsigned not null auto_increment primary key, title varchar(255) not null, description text not null, salary int unsigned not null, location varchar(255) not null, category varchar(255) not null, experience enum(‘entry’, ‘intermediate’, ‘senior’) not null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate ‘utf8mb4_unicode_ci’)

cant send confirmation to reboot ont zte

$expect_script = <<<EOD
#!/usr/bin/expect -f
exp_internal 1
log_user 1  ;# Enable logging of user interaction
set timeout 20

# Start Telnet session
spawn telnet $telnet_host

# Handle initial banners or messages
expect {
    "User Access Verification" { exp_continue }
    "Username:" { send "$telnet_usernamer" }
}

# Expect password prompt and send password
expect "Password:"
send "$telnet_passwordr"

# Expect the command prompt after successful login
expect "#"

# Send each command from the array except 'reboot'
foreach command [split "$command_interface" "n"] {
    if { [string match "*reboot*" "$command"] } {
        # If the command is 'reboot', handle it separately
        send "$commandr"
        expect {
            "Confirm to reboot.*" {
                send "yesr"
                expect "#"
            }
            timeout { puts "Timed out waiting for reboot confirmation prompt."; exit 2 }
        }
    } else {
        # For all other commands
        send "$commandr"
        expect {
            "#" { 
                set output $expect_out(buffer)
            }
            timeout {
                puts "Timed out waiting for command prompt."
                exit 1
            }
        }
    }
}

# Send exit command to close the Telnet session
send "exitr"

# Wait for session to end
expect eof

# Output the entire buffer captured
puts "$output"
EOD;

$commands = [
        "config t",
        "pon-onu",
        "pon-onu-mng gpon-onu_1/14/8:45",
        "reboot"
           ];

this shoud be running like this ,sampling from terminal

OL01-NGN-SMG-ERLGOD#config t
%Info 20272: Enter configuration commands, one per line. End with CTRL/Z.
OL01-NGN-SMG-ERLGOD(config)#pon-onu-mng gpon-onu_1/14/8:45
OL01-NGN-SMG-ERLGOD(gpon-onu-mng 1/14/8:45)#reboot
Confirm to reboot? [yes/no]:yes

but somehow the confrimation yes can not be put and resulted

Username: 
ossapp01
Password: 
OL01-NGN-SMG-ERLGOD#config t
%Info 20272: Enter configuration commands, one per line. End with CTRL/Z.
OL01-NGN-SMG-ERLGOD(config)#pon-onu
%Error 20203: Incomplete command.
OL01-NGN-SMG-ERLGOD(config)#pon-onu-mng gpon-onu_1/14/8:45
OL01-NGN-SMG-ERLGOD(gpon-onu-mng 1/14/8:45)#reboot
Confirm to reboot? [yes/no]:Timed out waiting for reboot confirmation prompt.

help me modify the expect script to achieve this, thankyou in advance

Ajax Request Returns Html Response

I have come across this question before but I haven’t found a helpful answer whatsoever. What I want to know is why an ajax call to a codeigniter controller is returning an HTML response even when the controller function is not returning nothing explicitly.

So I have the following jquery ajax code:


$('#lgaStateField').change(function(){
var state = $(this).val();
            
if(state != 0){
    $('#lgaField').attr('disabled', false);
    $(processOngoing).css('display', 'block');

    $.ajax({
    url: "<?=base_url('adverts-report/fetch-lgas')?>",
    type: 'post',
    data: {stateId : state},
    success: function(r){
            //console.log(r);return false;
       // const resLgas = JSON.parse(r);
      // $('#lgaField').empty().append('<option value="0">Select Lga</option>');

     // for(var i = 0; i < resLgas.length; i++){
        $('#lgaField').append('<option value="' + resLgas[i].id + '">' + resLgas[i].name + '</option>');
    // }

    $(processOngoing).css('display','none');
    },
    error: function(err){
            console.log(err);
        $(processOngoing).css('display','none');
    }
      })
    }
})

And the following is a snippet of the endpoint that supposed to return a response but is currently empty:

public function fetch_lgas(){
        
    }

Yet when i check the Network section of my developer tab, there is an html response that is more or less the content of the current view.