Updating attribute values By Renumbering

Renumbering Functionality for Bill Management

Renumbering functionality is crucial for maintaining the integrity of bill numbering systems in various scenarios. It serves two primary purposes:

Rectifying Consecutive Number Breaks: If a user deletes a bill, it can disrupt the consecutive numbering sequence, necessitating renumbering to fill the gap.

Starting Fresh for a Financial Year: At the beginning of a new financial year, it’s often necessary to reset bill numbering, typically starting from 1.

While the renumbering process generally works well, there is a specific case where it fails: renumbering bills based on the order date. This scenario presents challenges that need to be addressed in the renumbering logic.

Below is a sample code snippet demonstrating the renumbering process, with emphasis on the S_SalesBill case. Discussion and refinement of this code can provide insights into resolving the issue encountered during renumbering based on the bill order date.

 public function actionRenumber()
{
    $prefix = Prefixes::find()->one(); // prefix for bill_number
    $toRenumber = $_POST['slug']; // model name for renumber
    $postDate = $_POST['date']; // date for filterout the records
    $date = DateTime::createFromFormat('d-m-Y', $postDate)->format('Y-m-d');
    $dateObj = DateTime::createFromFormat('d-m-Y', $postDate);
    $year = $dateObj->format('Y');
    $smallY =  $dateObj->format('y');
    $month = $dateObj->format('m');
    if ($month >= 4) {
        // If the month is April or later, financial year end is March 31st of the next year
        $financialYearEnd = date_create(($year + 1) . '-03-31')->format('Y-m-d');
        $renum_fin_year = $smallY.'-'.( $smallY+1);
    } else {
        // If the month is before April, financial year end is March 31st of the current year
        $financialYearEnd = date_create($year . '-03-31')->format('Y-m-d');
        $renum_fin_year = ($smallY-1).'-'.( $smallY);
    }
    $current_month = date('n');
    $current_year = date('y');

    // Calculate the financial year based on the current date
    if ($current_month >= 4) {
        // If the current month is April or later, financial year starts from the current year
        $current_fin_year = $current_year . '-' . ($current_year + 1);
    } else {
        // If the current month is before April, financial year starts from the previous year
        $current_fin_year = ($current_year - 1) . '-' . $current_year;
    }

    $outPut = array(); // log / response purpoose
    $outPut['key'] = $toRenumber;
    $outPut['date'] = $date;
    $lastNum = $_POST['lastNum']; // lastNum passed as array of counterkey=>lastnumber
    $inspect = array(); // inspect array is used for inspecting the flow of working.every step inserted to this array so this can see in response tab  
    
    // getting the source counter data to renumber
    switch($toRenumber){
        case "S_SalesBill":
            $source = SalesBill::find()->select('s_gold_counter,s_silver_counter')
            ->andFilterWhere(['>=', 'created_date', $date])
            ->andFilterWhere(['<=', 'created_date', $financialYearEnd])
            ->orderBy('created_date')
            ->asArray()->all();
        break;
        case "R_SalesBill":
            $source = SalesBill::find()->select('r_gold_counter,r_silver_counter')->andFilterWhere(['>=', 'created_date', $date])->orderBy('id')->asArray()->all();
        break;
        case"P_Purchase":
            $source = PurchaseInvoice::find()->select('p_gold_counter,p_silver_counter')->andFilterWhere(['>=','inv_date',$date])->asArray()->all();
        break;
        case"P_OldGold":
            $source = PurchaseInvoice::find()->select('p_oldGold_counter,p_oldSilver_counter')->andFilterWhere(['>=','inv_date',$date])->asArray()->all();
        break;
        case "Despatch":
            $source = Despatch::find()->select('d_gold_counter')->andFilterWhere(['>=','created_date',$date])->orderBy('id')->asArray()->all();
        break;   
        case"HallMarking":
            $source = Despatch::find()->select('d_hallmarking_counter,r_hallmarking_counter')->andFilterWhere(['>=','created_date',$date])->orderBy('id')->asArray()->all();
        break;
        case "DespatchReturn":
                $source = Despatch::find()->select('r_gold_counter')->andFilterWhere(['>=','created_date',$date])->orderBy('id')->asArray()->all();
        break;   

    }
    $inspect['LASTNUM'] = $_POST['lastNum'];
    $inspect['ToRenumber'] = $toRenumber;
    $inspect['sources'] = $source;

    // arranging the source data in to a sing array  $temp
    $temp = [];
    foreach ($source as $record) {
        foreach ($record as $counterKey => $counterValue) {
            if (!isset($temp[$counterKey])) {
                $temp[$counterKey] = [];
            }
            if (!empty($counterValue)) {
                $temp[$counterKey][] = $counterValue;
            }
        }
    }
    // echo "<pre>"; print_r($temp); echo "</pre>"; exit;
    // so the temp array look like example 
    /**
    *   [s_gold_counter] => Array
    *   (
    *       [0] => 1
    *       [1] => 2
    *       [2] => 3
    *       [3] => 649
    *   )

    */
    // here counterKey is s_gold_counter
    // check for firstValue
   
   
       
    $inspect['loopStart'] = "fromeHere";
    
    $renumbered = array();
    $queries = array();
    $itration = 1;
    foreach ($temp as $counterKey => $counterValues) { // itrating temp array with counter key
        $counterValues = array_unique($counterValues);
        sort($counterValues); // getting array of value like Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 649 )
        $firstVal = ($lastNum[$counterKey] != "") ? $lastNum[$counterKey]+1 : 1; // determine lastnumber
        $inspect[] = array('itration'=>$itration);
        $inspect[] = array('key'=>$counterKey);
        $inspect[] = array('value'=>$counterValues);
        $inspect[] = array('firstvalue'=>$firstVal);
        foreach ($counterValues as $counterValue) { // itrating each values inside counter key
            echo "<b>First condition</b> counterValue- ";
            var_dump($counterValue);echo "<br>";
            echo "firstVal ";
            var_dump($firstVal);
            // echo "counterValue- "."<pre>".var_dump($counterValue)."</pre>"."<br>"."firstVal "."<pre>".var_dump($firstVal)."</pre>"."<br>" ;
            if ((int)$counterValue !== $firstVal) {  // skip in the case of starting are same . checking the lastNumber passed is same as in the values array
                echo"true"."<br>";
                $inspect[] = array($counterValue.'NotEqualTo'.$firstVal=>true);
                echo "<b> second condition</b> counterValue- ";
                var_dump($counterValue);echo "<br>";
                echo "firstVal ";
                var_dump($firstVal);
                if ((int)$counterValue !== $firstVal + 1) { // skip in the case  no deleted bills next to current bill number 
                    echo"true"."<br>";
                    $inspect[] = array($counterValue.'NotEqualTo'.($firstVal+1)=>"true");
                        // echo "counterKey-".$counterKey."<br>"."counterValue".$counterValue ; exit;
                        switch($toRenumber){
                            case "S_SalesBill":
                                $bill = SalesBill::find()
                                    ->select(['id','s_gold_counter','bill_no'])
                                    ->where([$counterKey => $counterValue])
                                    ->andFilterWhere(['>=', 'created_date', $date])
                                    ->andFilterWhere(['<=', 'created_date', $financialYearEnd])
                                    ->asArray()->one();
                                echo "<pre>";print_r($bill); echo "</pre>";
                                // $bill_no = preg_replace('//(d+)/', '/'.$firstVal, $bill['bill_no']);
                                // $bill_no = preg_replace('/(d+)(?=(?:[^/]*/){0,2}[^/]*$)/', $firstVal, $bill['bill_no']);  
                                $parts = explode('/', $bill['bill_no']);
                                array_pop($parts);
                                $parts[] = $firstVal;
                                $bill_no = implode('/',$parts);                          
                                
                                // echo "from-".$bill['bill_no']." -to - " .$bill_no ; exit;
                                $query = Yii::$app->db->createCommand()->update('sales_bill', [$counterKey => $firstVal, 'bill_no' => $bill_no], ['id' => $bill['id']])->getRawSql();
                                
                                $queries[] = array('queries' => $query);
                                // update query

                                Yii::$app->db->createCommand()->update('sales_bill', [$counterKey => $firstVal, 'bill_no' => $bill_no], ['id' => $bill['id']])->execute();
                                
                            break;
                            case "R_SalesBill":
                                $bill = SalesBill::find()->where([$counterKey => $counterValue])->asArray()->one();
                                $parts = explode('/', $bill['bill_no']);
                                array_pop($parts);
                                $parts[] = $firstVal;
                                $bill_no = implode('/',$parts); 
                                // $bill_no = preg_replace('//(d+)/', '/'.$firstVal, $bill['bill_no']);
                                
                                $query = Yii::$app->db->createCommand()->update('sales_bill', [$counterKey => $firstVal, 'bill_no' => $bill_no], [$counterKey => $counterValue])->getRawSql();
                                $queries[] = array('queries' => $query);
                                // update query

                                Yii::$app->db->createCommand()->update('sales_bill', [$counterKey => $firstVal, 'bill_no' => $bill_no], [$counterKey => $counterValue])->execute();
                            break;
                            case "P_Purchase":
                                $bill = PurchaseInvoice::find()->where([$counterKey=>$counterValue])->asArray()->one();
                                
                                $parts = explode('/', $bill['invoice_no']);
                                array_pop($parts);
                                $parts[] = $firstVal;
                                $bill_no = implode('/',$parts); 
                               
                                // $bill_no = preg_replace('//(d+)/', '/'.$firstVal, $bill['invoice_no']);
                                $query = Yii::$app->db->createCommand()->update('purchase_invoice',[$counterKey=>$firstVal,'invoice_no'=>$bill_no],[$counterKey =>$counterValue])->getRawSql();
                                $queries[]= array('queries'=>$query);

                                // update query
                                Yii::$app->db->createCommand()->update('purchase_invoice',[$counterKey=>$firstVal,'invoice_no'=>$bill_no],[$counterKey =>$counterValue])->execute();
                            break;  
                            case "P_OldGold":
                                $bill = PurchaseInvoice::find()->where([$counterKey=>$counterValue])->asArray()->one();
                                $parts = explode('/', $bill['invoice_no']);
                                array_pop($parts);
                                $parts[] = $firstVal;
                                $bill_no = implode('/',$parts); 
                                // $bill_no = preg_replace('//(d+)/', '/'.$firstVal, $bill['invoice_no']);
                                $query = Yii::$app->db->createCommand()->update('purchase_invoice',[$counterKey=>$firstVal,'invoice_no'=>$bill_no],[$counterKey =>$counterValue])->getRawSql();
                                $queries[]= array('queries'=>$query);

                                // update query
                                Yii::$app->db->createCommand()->update('purchase_invoice',[$counterKey=>$firstVal,'invoice_no'=>$bill_no],[$counterKey =>$counterValue])->execute();
                            break;   
                            case "Despatch":
                                $bill = Despatch::find()->where([$counterKey=>$counterValue])->asArray()->one();
                                 
                                $parts = explode('/', $bill['despatch_no']);
                                array_pop($parts);
                                $parts[] = $firstVal;
                                $bill_no = implode('/',$parts); 
                                // $bill_no = preg_replace('//(d+)/', '/'.$firstVal, $bill['despatch_no']);
                            
                                $query = Yii::$app->db->createCommand()->update('despatch',[$counterKey=>$firstVal,'despatch_no'=>$bill_no],[$counterKey =>$counterValue])->getRawSql();
                                $queries[]= array('queries'=>$query);
                            
                                // update query
                                Yii::$app->db->createCommand()->update('despatch',[$counterKey=>$firstVal,'despatch_no'=>$bill_no],[$counterKey =>$counterValue])->execute();
                            break;

                            case "DespatchReturn":
                                $bill = Despatch::find()->where([$counterKey=>$counterValue])->asArray()->one();

                                $parts = explode('/', $bill['despatch_no']);
                                array_pop($parts);
                                $parts[] = $firstVal;
                                $bill_no = implode('/',$parts); 
                                // $bill_no = preg_replace('//(d+)/', '/'.$firstVal, $bill['despatch_no']);
                            
                                $query = Yii::$app->db->createCommand()->update('despatch',[$counterKey=>$firstVal,'despatch_no'=>$bill_no],[$counterKey =>$counterValue])->getRawSql();
                                $queries[]= array('queries'=>$query);
                            
                                // update query
                                Yii::$app->db->createCommand()->update('despatch',[$counterKey=>$firstVal,'despatch_no'=>$bill_no],[$counterKey =>$counterValue])->execute();
                            break;
                            case"HallMarking":

                                 $bill = Despatch::find()->where([$counterKey=>$counterValue])->asArray()->one();

                                 
                                $parts = explode('/', $bill['despatch_no']);
                                array_pop($parts);
                                $parts[] = $firstVal;
                                $bill_no = implode('/',$parts); 
                                
                                // $bill_no = preg_replace('//(d+)/', '/'.$firstVal, $bill['despatch_no']);
                            
                                $query = Yii::$app->db->createCommand()->update('despatch',[$counterKey=>$firstVal,'despatch_no'=>$bill_no],[$counterKey =>$counterValue])->getRawSql();
                                $queries[]= array('queries'=>$query);
                            
                                // update query
                                Yii::$app->db->createCommand()->update('despatch',[$counterKey=>$firstVal,'despatch_no'=>$bill_no],[$counterKey =>$counterValue])->execute();
                            break;

                        }
                    }
                }
            $firstVal +=  1;
            $renumbered[$counterKey][$counterValue] = $firstVal;
            $renumbered[] = array('values' => $counterValue,'firstVal'=>$firstVal);
        }
        $itration++;
    }
    switch($toRenumber){
        case "S_SalesBill":
            if($renum_fin_year == $current_fin_year){
                echo "<br> same financial year";
                $salesbill = SalesBill::find()
                ->select([
                    'COALESCE(MAX(s_gold_counter), 1) as s_gold_counter',
                    'COALESCE(MAX(s_silver_counter), 1) as s_silver_counter',
                ])
                ->andFilterWhere(['>=', 'created_date', $date])
                ->andFilterWhere(['<=', 'created_date', $financialYearEnd])
                ->asArray()->one();
                echo "<pre>"; print_r($salesbill); echo "</pre>";
                $seq_s_gold_counter = SequenceInfo::find()->where(['key'=>"SalesBill_s_gold_counter"])->one();
                $seq_s_gold_counter->number = $salesbill['s_gold_counter'];
                $seq_s_gold_counter->financial_year = $current_fin_year;
                $seq_s_gold_counter->last_updated = date('Y-m-d H:i:s');
                $seq_s_gold_counter->detail ="renumbered";
                $seq_s_gold_counter->validate();
                echo "<pre>"; print_r($seq_s_gold_counter); echo "</pre>";
                $seq_s_gold_counter->save();

                $seq_s_silver_counter = SequenceInfo::find()->where(['key'=>"SalesBill_s_silver_counter"])->one();
                $seq_s_silver_counter->number = $salesbill['s_silver_counter'];
                $seq_s_silver_counter->financial_year = $current_fin_year;
                $seq_s_silver_counter->last_updated = date('Y-m-d H:i:s');
                $seq_s_silver_counter->detail ="renumbered";
                $seq_s_silver_counter->save();
                
            }
        break;
    }
    return json_encode(["renumbered" => $renumbered, 'queries' => $queries,'startingfrom'=>$firstVal,'inspect'=>$inspect]);
    die;
}

Additional Notes:

In the provided code, $_POST[‘lastNum’] represents a number specified by the user to initiate renumbering, starting from $_POST[‘lastNum’]+1.

For further context:

The renumbering process relies on a SequenceInfo model, which stores the updated last number. This model is utilized in the creation function of every single inventory controller, determining the bill number based on the sequence info key number.

An exceptional case arises when a bill’s creation date is modified after renumbering. This scenario aims to eliminate any potential gaps in bill numbering caused by the initial renumbering. However, it results in the bill numbers not aligning chronologically by date. Consequently, performing renumbering again will not rectify the issue of bill numbering order based on date.

Your assistance in resolving this issue is greatly appreciated.

PHP PDO – Inconsistent behavior after succesfull connect

Ever since the move of the MariaDB database to a new host ( (10.5.22, “Mriadb Galera cluster”) I’m sometimes having issues with running queries.

$dsn="mysql:host=".$settings['DB_HOST'].";port=".$settings['DB_PORT'].";dbname=".$settings['DB_DATABASE'].";charset=utf8";
        try {
        
            $this->db = new PDO($dsn, <user>,<password>);
         
             $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
       
             error_log('success')
            
        } catch (PDOException $e) {

            $settings[LOG_ERROR] && error_log($e->getMessage());
        }

This connection is ALWAYS succesfull (the PHP log shows the “success” string)

Then I run this query:

 $query = "SELECT * FROM <table> WHERE (USERNAME = ?) AND (ACTIVE=1) AND (FAILEDLOGIN<3);";
        $user = $this->db->query($query, strtoupper($login));

        if ($user){
            $result = $user->getRow();
        }

        return $result;

Sometimes it returns a “None object” , then 15 minutes later it’s working fine again.

The DB admin could not find anything in the logs.

The DB server is behind “BigIP” but only for load balancing and our BigIP engineer couldn’t find anything in the logs either.

Is there any other debugging method I can use to try to find the issue?

All the articles I find in StackOverflow cover consistent issues, as far as I can see…

Because the PDO connection is working fine and the issue is sometimes fixed without any action from my or anyone else’s action, i’ve got no idea what else to try.

All the articles I find in StackOverflow cover more ‘consistent’ issues, as far as I can see…

PHP-Script failing to write filenames into csv

I have a PHP script running on a web server for a university project. I have a corresponding app sending pictures and additional data to the server. The script is supposed to take the data, write it into a CSV file, and save the pictures. The problem is that I can’t get my script to write the image names into the CSV files. The pictures are correctly named, but I can’t get the names into the CSV file.

The csv still has the “test1”, “test2”, “test3” values.

What am I missing?

<?php
// Set CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postData = file_get_contents('php://input');
    $decodedData = json_decode($postData, true);

    // Initialize variables for image paths and filenames
    $imageFilePaths = [];
    $imageFileNames = ["test1","test2","test3"]; // Array for image filenames

    // Check file uploads, process up to three images
    $count = 0;
    $testvariable = null; // Initialize variable outside foreach loop
    foreach ($_FILES as $key => $value) {
        if ($count >= 3) break; // Process only up to three images
        if ($value['error'] === UPLOAD_ERR_OK) {
            $imageTmpName = $value['tmp_name'];
            $imageFileName = $value['name']; // Original filename of the image
            $testvariable = $imageFileName; // Update variable with the filename of the first image
            $imageFilePath = '/var/www/html/geodata/images/' . $imageFileName; 

            // Save image
            if (!move_uploaded_file($imageTmpName, $imageFilePath)) {
                echo json_encode(['status' => 'error', 'message' => 'Error saving the image']);
                exit;
            }
            $imageFilePaths[] = $imageFilePath; // Add file path to the array
            $imageFileNames[] = $value['name']; // Add filename to the array
            $count++;
        }
    }

    if ($decodedData) {
        // Extract data from decoded JSON
        $reportId = $decodedData['report']['reportId'] ?? '';
        $userId = $decodedData['report']['userId'] ?? '';
        $timestamp = $decodedData['report']['timestamp'] ?? '';
        $latitude = $decodedData['report']['latitude'] ?? '';
        $longitude = $decodedData['report']['longitude'] ?? '';
        $deficiencyType = $decodedData['report']['deficiencyType'] ?? '';
        $onPublicProperty = $decodedData['report']['onPublicProperty'] ?? '';
        $additionalInformation = $decodedData['report']['additionalInformation'] ?? '';

        // Write data to the CSV file
        $csvFilePath = '/var/www/html/geodata/data.CSV';
        $csvFile = fopen($csvFilePath, 'a');

        if ($csvFile) {
            // Check if images were uploaded
            if (!empty($imageFileNames)) {
                // Add filenames of all uploaded images to the dataset
                $data = [$reportId,$testvariable, $userId, $timestamp, $latitude, $longitude, $deficiencyType, $onPublicProperty, $additionalInformation];
                $data = array_merge($data, $imageFileNames); // Use filenames instead of file paths
                fputcsv($csvFile, $data);
            } else {
                fputcsv($csvFile, [$reportId, $userId, $timestamp, $latitude, $longitude, $deficiencyType, $onPublicProperty, $additionalInformation]);
            }
            fclose($csvFile);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Error writing to the CSV file']);
            exit;
        }

        // Add data to the HTML content
        $htmlFilePath = '/var/www/html/index.html';
        $htmlContent = file_get_contents($htmlFilePath);

        $appendedContent = "<p>Report ID: " . $reportId . ", User ID: " . $userId . ", Timestamp: " . $timestamp . "</p>n";
        $updatedHtmlContent = $htmlContent . $appendedContent;

        // Save updated content back to index.html
        file_put_contents($htmlFilePath, $updatedHtmlContent);

        echo json_encode(['status' => 'success', 'message' => 'Data successfully written']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON format']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'No POST request']);
}
?>

Session shared across subdomains weird behavior

I have a weird problem with PHP session shared across subdomains. I’ll try to be as clear as possible.

I have subdomainA and subdomainB, both share the same session. Both have a front end and a back end. I have a JS test function that does a POST to its respective PHP back-end, so I can check the session variables on each back-end.

This is how the session is started on both subdomains

 if(session_status() !== PHP_SESSION_ACTIVE){       
    session_set_cookie_params(0, '/', '.domain.local');   
    session_name('mysession');
    session_start();
 }

When I load either subdomain, each will check if a session variable is present, if not, it will set it (the value is different per subdomain)

if(!isset( $_SESSION['test'] )){
$_SESSION['test'] = 'I was born on subdomainA';  
}

or

if(!isset( $_SESSION['test'] )){
$_SESSION['test'] = 'I was born on subdomainB';  
}

Say I visit subdomainB then open a new tab and visit subdomainA, then use my test function, each return the proper session value (the same) from their respective backend. So far so good.

Now, subdomainB can change the session variable value later on by a POST action from its front-end, which triggers a CURL request from its backend to a 3rd-Party and the result of that call updates the value of the session variable.

To make sure CURL does not mess with the session, I do

 session_write_close(); 
 [CURL]
 session_start();
 $_SESSION['test'] = 'I was set by 3rd party';

Then I can call my JS test function from each-front after that, and I get the updated value pulled from the session variable from both subdomainA and B. Everything works, I get

'I was set by 3rd party'

Now the weird part. Everything works fine until subdomainB changes the value a 2nd time via CURL. If, after, that, I pull the value from the JS function from subdomainA or B, the value in the session is good BUT if I reload subdomainA, then the whole session is empty (but has the same ID).

If I reload subdomainA before subdomainB changes it a 2nd time, it all works fine. It happens after subdomainB does the CURL call for the 2nd time.

Please note that it all works fine as long as I don’t refresh a page, meaning that the 2nd time the CURL calls goes through, and use my JS function, I still get the proper latest updated value and as long as I don’t reload, from both subdomains.

For some reason, reloading subdomainA after the 2nd CURL call wipes the session data.

Any idea?

Edit : my apache error log reports

 * old SSL session ID is stale, removing

How do I fix that?

Regex preg_replace for expressions in quotes [duplicate]

$mystring="I'm happy, I want to 'travel through the world' and eat an 'apple' in the country";

I would like to get

$mystring="I'm happy, I want to <i>travel through the world</i> and eat an <i>apple</i> in the country";

I have found no solution, an idea ?

Found no matching regex.

imagettftext does not work while imagestring works fine

I have an issue with my PHP code.
I want to add text to an image.
When using imagestring(), the image displays fine with the text on top, but it’s written very very small.
And it’s impossible to increase the size with imagestring().
I saw that it’s rather recommended to use imagettftext(), but when I use this function, the image doesn’t display.
I get no errors, it just displays the alt tag text.
I’ve tried dozens and dozens of different function calls but none have worked.
Here’s my code:

$idQuiz = $_GET['qz'];
$user = UtilisateursManager::getList(null, ['idUtilisateur'=>$_SESSION['utilisateur']->getIdUtilisateur()])[0];
$name = $user->getPrenomUtilisateur().' '.$user->getNomUtilisateur();

$font = './FONTS/RedditMono-Black.ttf';
$fontSize = 50;
$img = "./IMG/certificatRealisation.jpg";
$image = imagecreatefromjpeg($img);
$color = imagecolorallocate($image, 255, 0, 0);
// imagestring($image, 5, 600, 700, $name, $color);
imagettftext($image, 52, 0, 500, 600, $color, $font, $name);

header("Content-type: image/jpeg");
imagejpeg($image);
imagedestroy($image);

Symfony SassBundle not recognize the .yaml config

I am working on a Symfony App.
To optimize ressources at the loading, I made differents stylesheets. My main stylesheet is a .ccs template file that I reuse in most of my projects.

My others files are .scss files I include via AssetMapper when I need it. They basically set the style of specific .twig components.

screenshot of the folder “assets” in my working tree

{% extends 'base.html.twig' %}

{% block title %}Hello PublicController!{% endblock %}
{% block stylesheets %}
    <link rel="stylesheet" href="{{ asset('styles/insets.scss') }}">
{% endblock %}

My issue is : I can’t build my .scss stylesheets because SassBundle only want a single file “app.scss”.

PS C:Usersjuliewebweb-app-mairie> php bin/console sass:build --watch
[critical] Error thrown while running command "sass:build --watch". Message: "Could not find Sass file: "C:Usersjuliewebweb-app-mairie/assets/styles/app.scss""

In SassBuilder.php line 116:
                                                                                        
  Could not find Sass file: "C:Usersjuliewebweb-app-mairie/assets/styles/app.scss"  
                                                                                        

sass:build [-w|--watch]

So I tried to build with my external binary.
PS C:Usersjuliewebweb-app-mairie> sass /assets/insets.scss /assets/insets.css
Error :
Error reading ........assetsinsets.scss: Cannot open file.

And I finally tried to add path of my .scss files to the root config like mentioned in symfony doc.
BUT I have the same error thant at the start : the builder could not find the “app.scss”.
This not surprise me enought because I had to create the symfonycasts_sass.yaml file in config/packages myself. There is what I written :

# config/packages/symfonycasts_sass.yaml
symfonycasts_sass:
    root_sass:
        - '%kernel.project_dir%/assets/insets.scss'

I suppose it use a another config file but where ? I searched a bit in vendor directory but I quickly lost my way

So guys, do you know anything about this *** ? Or do you have an other solution / advices for me ?

Install a package manualy into vendor folder with zend 2

I need to use ‘phpword’ package with a zend 2 project but I can’t install this dependancy with composer and I want to install it manualy, (copy package folder to vendor folder) but I have an error like “Fatal error: Class ‘PhpOfficePhpWordPhpWord’ not found in …” . I already load autoload.php file.

Someone have a tips for this please? Thanks

how to assign javascript variable to PHP variable [duplicate]

I am generating dynamic rows with add more function. In JavaScript I am fetching MySQL data and I generate a dropdown. For executing the query I need a php variable value, but I have a JavaScript value. So, to execute the query I need php value. I need help to assign JavaScript variable to the php variable.

I have tried this way:

<script>
var j = 'this is JavaScript value';

<?php $ABC = "<script>document.write(j)</script>"?>   

How to validate firebase login with facebook

I have the following code executing when a user logs in to facebook:

FB.Event.subscribe('auth.authResponseChange', checkLoginState);

Here is the code to analayse:

    function checkLoginState(response) {
        if (response.authResponse) {
            // User is signed-in Facebook.
            const unsubscribe = onAuthStateChanged(auth, (firebaseUser) => {
                unsubscribe();
                // Check if we are already signed-in Firebase with the correct user.
                if (!isUserEqual(response.authResponse, firebaseUser)) {
                    // Build Firebase credential with the Facebook auth token.
                    const credential = FacebookAuthProvider.credential(
                        response.authResponse.accessToken);

                    // Sign in with the credential from the Facebook user.
                    let x = signInWithCredential(auth, credential)
                        .catch((error) => {
                            // Handle Errors here.
                            const errorCode = error.code;
                            const errorMessage = error.message;
                            // The email of the user's account used.
                            const email = error.customData.email;
                            // The AuthCredential type that was used.
                            const credential = FacebookAuthProvider.credentialFromError(error);

                            alert("Login failed. Please try again.");
                        });

                    x.then((userCredential) => {
                        // Signed in
                        const user = userCredential.user;
                        // login(response.authResponse.accessToken, firebasetoken???);
                    });

                } else {
                    // User is already signed-in Firebase with the correct user.
                    console.log(response);
                    // login(response.authResponse.accessToken, firebasetoken???);
                }
            });
        } else {
            // User is signed-out of Facebook.
            signOut(auth);
        }
    }

I’m unsure how to pass the FIREBASE login token to verify in the backend (with kreait):

        $auth = (new Factory)
            ->withServiceAccount($_ENV["PATH"].$_ENV['config']['storage']['firebase']['firebase']['file'] ?? 'firebase-service-account.json')
            ->createAuth();

        // verify token
        $verifiedIdToken = $auth->verifyIdToken($token);
        $uid = $verifiedIdToken->getClaim('sub'); // throws an InvalidToken when invalid

Kreait docs:
https://github.com/kreait/firebase-php

Any help is appreciated.

I need advice on video streaming 3 different feeds into single IP address of website [closed]

So I have 2 Radio Feeds and 1 Video Podcast Feed. When the user clicks on the link on our website, it needs to stream the correct feed. The problem is, we need the feeds to actually go through our website IP address and not the actual direct radio feed. This is for monitoring they require one IP address.

This is for a website on our server. So there are 3 links. Link1 is Radio Channel 1. Link2 is Radio Channel 2. And Link 3 is the video podcast.

The provider requires us to pass everything through 1 IP address. So the server needs to somehow intercept and make a connection and return everything through a tunnel.

Any suggestions are welcome.

How I can sort by relevancy against my searchterm in Laravel upon fulltext search?

In a laravel project I have this migration:


use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::dropIfExists('posts');

        Schema::create('posts',function (Blueprint $table){
            // More columns will be added in next migrations.
            $table->id();
            $table->string('name');
            $table->fulltext(['posts']);
        });

     
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');

    }
};

And this Model:

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelPost;

class Post extends Model
{
   use HasFactory;
   protected $table="posts";
}

And I search as fulltext in a controller:

class PostController extends Controller
{
  public function search()
  {
     $searchterm = $request->get('searchterm');
     $qb = Post::query();
     
     if(!empty($searchterm)){
         $request->whereFullText(['name'],$searchterm);
     }

     $page = $request->get('page')??1;
     $limit = $request->get('limit')??20;

       $results = $request->offset(($page - 1) * $limit)
            ->simplePaginate($limit);

     return new JsonResponse($results,200);
  }
}

But how upon my controller can I return the results order by relevancy? I want the closest matching to be the first ones.

Cant load user with LdapUserProvider : Could not complete search with dn

With LdapUserProvider i have some errors when i try to load my user.

In this method :

    public function loadUserByIdentifier(string $identifier): UserInterface
{
    try {
        $this->ldap->bind($this->searchDn, $this->searchPassword);
    } catch (InvalidCredentialsException) {
        throw new InvalidSearchCredentialsException();
    }

    $identifier = $this->ldap->escape($identifier, '', LdapInterface::ESCAPE_FILTER);
    $query = str_replace('{username}', '{user_identifier}', $this->defaultSearch, $replaceCount);

    if ($replaceCount > 0) {
        trigger_deprecation('symfony/ldap', '6.2', 'Using "{username}" parameter in LDAP configuration is deprecated, consider using "{user_identifier}" instead.');
    }
    $query = str_replace('{user_identifier}', $identifier, $query);
    $search = $this->ldap->query($this->baseDn, $query, ['filter' => 0 == count($this->extraFields) ? '*' : $this->extraFields]);
    $entries = $search->execute();
    $count = count($entries);

    if (!$count) {
        $e = new UserNotFoundException(sprintf('User "%s" not found.', $identifier));
        $e->setUserIdentifier($identifier);

        throw $e;
    }

    if ($count > 1) {
        $e = new UserNotFoundException('More than one user found.');
        $e->setUserIdentifier($identifier);

        throw $e;
    }

    $entry = $entries[0];
    try {
        if (null !== $this->uidKey) {
            $identifier = $this->getAttributeValue($entry, $this->uidKey);
        }
    } catch (InvalidArgumentException) {
    }
    dd($entry);
    return $this->loadUser($identifier, $entry);
}

my dd() gave me an array with my users Ldpa’s attributes like this :

LdapUserProvider.php on line 110: SymfonyComponentLdapEntry {#394 ▼   -dn: "CN=test test,OU=WORK,OU=USER,DC=DOMAIN,DC=COM"  

-attributes: array:48 [▼
“objectClass” => array:4 [▶]
“cn” => array:1 [▶]
“sn” => array:1 [▶]
“title” => array:1 [▶]
“description” => array:1 [▶]
“givenName” => array:1 [▶]
“initials” => array:1 [▶]
“distinguishedName” => array:1 [▶]
“instanceType” => array:1 [▶]
“whenCreated” => array:1 [▶]
“whenChanged” => array:1 [▶]
“displayName” => array:1 [▶]
“uSNCreated” => array:1 [▶]
“memberOf” => array:17 [▶]

Thats fine.

But, if i comment dd(), the method give me an error :

Could not complete search with dn "dc=DOMAIN,dc=COM", query "(sAMAccountName=test)" and filters "*". LDAP error was [1] Operations error.

On this line :

        $entries = $search->execute();

Any idea is appreciated

NotFoundHttpException with ApiPlatform: Custom URL Parameter Treated as Identifier

I’m encountering an issue within my Symfony project that utilizes ApiPlatform. Whenever I include a custom parameter in the URL, I face a NotFoundHttpException with the message “Invalid URI variables”. It seems that ApiPlatform, within Symfony, is interpreting my custom URL parameter as an identifier instead of a variable.

Here’s a snippet of the relevant code:

#[ApiResource(
    operations: [
        new GetCollection(
            uriTemplate: '/{tenant}/agreement',
            openapi: new ModelOperation(
                parameters: [
                    new ModelParameter(
                        name: 'tenant',
                        in: 'path',
                        required: true,
                    ),
                ],
            ),
        ),
    ]
)]

My goal is to include this custom parameter in the SQL query condition for retrieving the collection.

I suspect that ApiPlatform might be misinterpreting the parameter configuration. I’m seeking guidance on how to address this issue and ensure that ApiPlatform correctly handles the custom URL parameter as a variable rather than an identifier. Any advice or insights on resolving this matter would be highly appreciated. Thank you!