Why mysql delete query is not working with string variable?

I am android developer and I am weak in PHP.

This one is working:

$sql = "DELETE FROM user WHERE id    =       '$user->id'    ";

This one works too:

$sql = "DELETE FROM user WHERE email = '" . '[email protected]' . "'";

But this query not working:

$sql = "DELETE FROM user WHERE email = '" .  "'$user->email'"  . "'";

This is my phpMyAdmin table:

enter image description here

and this is my del.php api that works fine with first two query:

<?php
 include_once('../common/include.php');
 include_once('../common/encipher.php');
 $user = json_decode(file_get_contents("php://input"));
 $conn=getConnection();
 if($conn==null){
     sendResponse(500,$conn,'Server Connection Error !');
     exit;
 }
 $sql = "DELETE FROM user WHERE id = '$user->id'";
 $result = $conn->query($sql);
 if ($conn->affected_rows > 0) {
 sendResponse(200, [], 'User deleted .');
 }
 else 
 {
  sendResponse(404, [], 'Error on delete !');
 }
 $conn->close();

need help in password reset system in codeigniter4

i am new in MVC programming, especially CodeIgniter4, i made a login/register system, it works fine,
and i implemented a password reset system :
1- when a user click reset password link a form appears
2- u put your email address and u click submit (the data is sent for validation)
3- if the email is valid and exist in the database a reset link is sent to the user,
4- when the user click the link it redirect him to the reset form
5- u enter your new password and confirm

her is my code :

1- route.php

$routes->post('sendresetlink', 'ResetPwdController::sendresetlink');
$routes->get('redirect/(:num)/(:any)', 'ResetPwdController::loadResetPage/$1/$2'); // 1st param is id, 2nd is token
$routes->post('resetpassword', 'ResetPwdController::updatepassword');

2- ResetPwdController.php

//---------------------------->->- Reset password : step 1
    public function sendresetlink()
    {
        $userModel = new UserModel();
        $toEmail = $this->request->getVar('email2');
        $row = $userModel->where('email', $toEmail)->first();
        if ($row) {
            $mail = new PHPMailer(true);
            try {
                //Server settings
                // $mail->SMTPDebug = SMTP::DEBUG_SERVER;                   //Enable verbose debug output
                $mail->isSMTP();                                            //Send using SMTP
                $mail->Host       = 'smtp.gmail.com';                       //Set the SMTP server to send through
                $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
                $mail->Username   = '[email protected]';               //SMTP username
                $mail->Password   = 'E123456';                           //SMTP password
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
                $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
                $mail->CharSet = 'UTF-8';

                //Recipients
                $date = getServerTimestamp();
                $mail->setFrom('[email protected]', "Reset password email {$date}");
                $mail->addAddress($toEmail);     //Add a recipient

                // $pwd = generate_password(8);
                $token = generate_token();
                $id = $row["id"];
                $url   = generate_url("redirect", $id, $token);
                $link  = "<a href='" .  $url . "'>reset password</a>";
                $mail->isHTML(true);
                //Set email format to HTML
                $mail->Subject = 'Password recovery';
                $mail->Body    = 'Your new password :  click the link below ' . $link;
                $mail->AltBody = 'Your new password :  click the link below ' . $link;
                $mail->send();
                $data = ['token' => $token, 'token_active' => 1, 'token_date' => getServerTimestamp()];
                $userModel->where('id', $id)
                    ->set($data)
                    ->update();
                echo json_encode(1);  //ok msg sent with token
            } catch (Exception $e) {
                $ajaxresponse = $mail->ErrorInfo;
                echo json_encode($ajaxresponse); //message not sent 
            }
        } else {
            echo json_encode(2); //wrong email adress
        }
    }
    //---------------------------->->- Reset password : step 2  
    public function loadResetPage($id, $token)
    {
        $userModel = new UserModel();
        $row = $userModel->find($id);

        if ($row) {
            if (isValidToken($row, $token)) {
                $data = array('id' => $id, 'token' => $token);
                echo view('resetpassword', $data); // return view => call a view , return redirect => route
                //    return redirect()->to('ResetPwdController');
            } else {
                echo "<h1>Error 1 : Bad link !</h1>";
                return 0;
            }
        } else {
            echo "<h1>Error 2 : Bad user !</h1>";
            return 0;
        }
    }

    //------------------------------ Reset password : step 3
    public function updatepassword()
    {
        $rules = [
            'password' => [
                'label' => 'Password',
                'rules' => 'required|min_length[4]|max_length[50]|alpha_numeric',
                'errors' => [
                    'required' => 'password is required',
                    'min_length' => 'min length is 5',
                    'max_length' => 'max length is 50',
                    'alpha_numeric' => 'add alpha and numeric',
                ]
            ],
            'confpwd' => [
                'label' => 'Confirm Password',
                'rules' => 'required|matches[password]',
                'errors' => [
                    'required' => 'retype password',
                    'matches' => 'password dont matches',
                ],
            ]
        ];

        if ($this->validate($rules)) {
            $userModel = new UserModel();
            $id = $this->request->getVar('id');
            $token = $this->request->getVar('token');
            $row = $userModel->find($id);
            if ($row) {
                if (isValidToken($row, $token)) {
                    $data = [
                        'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
                        'token_active' => 0,
                        'token' => '',
                        'token_date' => ''
                    ];
                    $userModel->update($id, $data);
                    echo json_encode(1);
                } else {
                    echo json_encode(2); //bad token or expired link
                }
            } else {
                echo json_encode(3); //bad id link
            }
        } else {
            echo json_encode($this->validator->listErrors());
            
        }
    }

3 – my custom helper

    function generate_token($len = 25)
{
  $dumpdata = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  $token = substr(str_shuffle($dumpdata), 0, $len);
  return $token;
}
//------------------------------------------------------
function generate_password($len = 8)
{
  $dumpdata = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#&$%_";
  $token = substr(str_shuffle($dumpdata), 0, $len);
  return $token;
}
//------------------------------------------------------
function generate_url(...$segments)
{
  $url = base_url();
  foreach ($segments as $seg) {
    $url .= '/' . $seg;
  }
  return $url;
}
//------------------------------------------------------
function getServerTimestamp()
{
  date_default_timezone_set('Africa/Algiers');
  $stamp =  date('Y-m-d H:i:s');
  return $stamp;
}
//------------------------------------------------------
function isValidToken($data, $token, $period=24)
{
  $date = date(getServerTimestamp());
  $diff = date_diff2($data['token_date'], $date);
  //print_r("Reset  : {$row['token_date']}<br>Server : {$date}<br>Period : {$diff['asString']}");
  $period_second = $period*60*60;
  return ($data['token'] == $token &&
    $data['token_active'] == 1 &&
    $diff['exceeded'] > 0 &&
    $diff['exceeded'] <= $period_second //validation limit $period_second = $period*60*60
  );
}
//------------------------------------------------------
function date_diff2($date1, $date2)
{
  $diff = strtotime($date2) - strtotime($date1);

  if ($diff <= 0) {
    $asString = "[<br> <b>valid :</b> 0 <br><b>Period : </b>00:00:00:00:00:00<br> Diff : </b>" . strval($diff) . "<br>]";
    $result = array(
      'valid' => 0,
      'year' => 0,
      'month' => 0,
      'days' => 0,
      'hours' => 0,
      'minutes' => 0,
      'seconds' => 0,
      'exceeded' => $diff,
      'asString' => $asString
    );
    return $result;
  }

  $years = floor($diff / (365 * 60 * 60 * 24));
  $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
  $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
  $hours = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));
  $minutes = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);
  $seconds = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60 - $minutes * 60));
  $asString = '[ <br> <b>valid :</b> 1 <br><b>Period : </b>' .
    strval($years) . ":" .
    strval($months) . ":" .
    strval($days) . ":" .
    strval($hours) . ":" .
    strval($minutes) . ":" .
    strval($seconds) . "<br> <b>Diff : </b>" .
    strval($diff) . "<br>]";
  $result = array(
    'valid' => 1,
    'year' => $years,
    'month' => $months,
    'days' => $days,
    'hours' => $hours,
    'minutes' => $minutes,
    'seconds' => $seconds,
    'exceeded' => $diff,
    'asString' => $asString
  );
  return $result;
}

my issue is as so i am getting an error :
when submitting data in reset form the it don’t send data to the right route and the URL in the browser is the same as the email link
help please
i do not know if it is because of echo view or my logic is wrong?

How to modify product data using ProductPageLoadedEvent in Shopware 6?

Does anyone knows to modify product data using ShopwareStorefrontPageProductProductPageLoadedEvent ?

services.xml

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="SwagBasicExampleServiceAddDataToPage" >
                <argument type="service" id="product.repository"/>
                <tag name="kernel.event_subscriber" />
        </service>
    </services>
</container>

AddDataToPage.php

<?php declare(strict_types=1);

namespace SwagBasicExampleService;

use ShopwareCoreFrameworkDataAbstractionLayerEntityRepositoryInterface;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use ShopwareStorefrontPageProductProductPageLoadedEvent;

class AddDataToPage implements EventSubscriberInterface
{
    /**
     * @var EntityRepositoryInterface
     */
    private $productRepository;

    /**
     * @param EntityRepositoryInterface $productRepository
     */
    public function __construct(
        EntityRepositoryInterface $productRepository
    )
    {
        $this->productRepository = $productRepository;
    }

    /**
     * @return string[]
     */
    public static function getSubscribedEvents(): array
    {
        return [
            ProductPageLoadedEvent::class => 'onProductsLoaded'
        ];
    }


    /**
     * @param ProductPageLoadedEvent $event
     * @return void
     */
    public function onProductsLoaded(
        ProductPageLoadedEvent $event
    )
    {
        // the product is inside the page object
        $productData = $event->getPage()->getProduct();


        //modifying name
        $this->log($productData->getName());
        $productData->setName('Prefix Product Name' . $productData->getName());
        $this->log($productData->getName());


        //modifying ManufacturerNumber
        $this->log($productData->getManufacturerNumber());
        $productData->setManufacturerNumber('Prefix ManufacturerNumber' . $productData->getManufacturerNumber());
        $this->log($productData->getManufacturerNumber());

        $event->getPage()->setProduct($productData);

    }

    /**
     * @param $message
     * @return void
     */
    private function log($message)
    {
        $logFileName = 'someFile.log';
        file_put_contents(
            $logFileName,
            $message . PHP_EOL,
            FILE_APPEND
        );
    }
}


After modifying the above mentioned changes it still shows the original data although
$event->getPage()->setProduct($productData);

I’m in doubt whether ProductPageLoadedEvent is an after dispatching event or before dispatching the event.

Display sql query result (from textarea input) into a table without knowing the number of columns

It starts off with the user having to input their query from a textarea.

<div class="querybar">
        <div class="form-item">
            <form action="" method="POST" class="simple-form">
            <textarea id="sqlquery" name="sqlquery" rows="3" cols="120" placeholder="Type your query here"></textarea>
        </div>
        <div class="form-item">
            <input type="submit" name="submit" value="Submit">
            </form>
        </div>
    </div>

and then it should display the result of the query–if its a select statement–into a table regardless of the number of columns
(example: I have productlist table which has 4 columns, and orders table with 8 columns, and it should be able to display all columns whether I query for ‘productlist’ or ‘orders’)
otherwise it just displays a success message

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit']))
{                 
        $sql = $_POST['sqlquery'];
        $trimmedSQL = trim($sql);
        
        if(!empty($trimmedSQL)) 
        {  
            $stmt = $db-> prepare($trimmedSQL);
            $stmt = execute();
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if ( strstr( strtoupper($trimmedSQL), 'SELECT' ) )
            {
                //print all the results into a table
            } 
            else
            {
                echo "<div class = 'success-msg'><div><i class='fa-solid fa-circle-check'></i><b> Success!</b> Processed SQL query.</div></div>";
            }
        }
        else
        {
                echo "No query!";
        }
}

what should I place in place of the comment, for this to happen? or is it completely wrong?
I’m sorry if this may sound like its already been answered before, but the answer I found didn’t seem to work for my case.

Laravel 5.8 Adding Multiple Middleware Directly To Route

I’m using Laravel 5.8 and I have a route like this:

Route::get("certs","CertController@index")->name('certificate.front')->middleware('auth');

Now I wanted to add another middleware to this route, so I tried this:

Route::get("certs", "CertController@index")->name('certificate.front')->middleware('prevent-back-history','auth');

Now I don’t get any error and it works But I wonder is this way better or not:

Route::get("certs", "CertController@index")->name('certificate.front')->middleware(['prevent-back-history','auth']);

So which is better and correct in this case?

Note that I don’t want to use Route groups and needed to specify the middleware name directly to the route.

How To Get Value from three tables in mysql

I have three tables namely employees, company_cars, and delivery_locations
Each of these tables have two elements in common

for employees and company_cars we have employee_id, where employee_id is the driver of the car in company_cars table
employees table   cars table

for company_cars and delivery_locations we have car_id where car_id is the car used for delivering employees for a certain location….

Now I want to display the name of The driver the employees table from a car selected for a particular location.

I have tried the following but I can only get the employees id

$fetch_locations=mysqli_query($con,"SELECT *,
(SELECT car_name from company_cars as d WHERE r.selected_car = f.car_id) as bus,
(SELECT car_driver from company_cars as f WHERE r.selected_car = f.car_id) as driver
from delivery_locations as r order by name_of_location ASC LIMIT $start_from, $per_page_record");

Problem: Display name of Driver

How to get activate particular conversation chat

I’m using wschat wordpress plugin. I’m passing link with the conversation id. If there is conversation id we need to get id and activate the particular user conversation.
I’m passing link as https://brookstone220.com/wp-admin/admin.php?page=wschat_chat&cid=3
and the js file will be shown below:
admin_chat.js:

import {WSChat, formatDate} from './chat';
import { AdminApiConnector } from './admin_api_connector';
import { AdminPusherConnector } from './admin_pusher_connector';
import { EVENTS } from './events';
import { EmojiButton } from '@joeattardi/emoji-button';
import UserMetaInfo from './components/user_meta_info.html'

jQuery(document).ready(function() {

    const wrapper = jQuery('.wschat-wrapper');

    if (wrapper.length === 0) {
        return;
    }
   
    const CONVERSATION_TEMPLATE = `
        <div class="friend-drawer friend-drawer--onhover" data-conversation-id="{{CONVERSATION_ID}}">
          <img class="profile-image" src="https://ui-avatars.com/api/?rounded=true&name=Guest" alt="">
          <div class="text">
            <h6>{{NAME}}</h6>
            <p class="last-message text-truncate">{{LAST_MESSAGE}}</p>
          </div>
          <span class="time small d-none">{{TIMESTAMP}}</span>
          <span class="unread-count badge rounded-pill align-self-center">{{UNREAD_COUNT}}</span>
        </div>
        <hr>`;

    const CHAT_BUBBLE_TEMPLATE = `
          <div class="row g-0 w-100 message-item" data-message-id="{{MESSAGE_ID}}">
            <div class="col-xs-10 col-md-9 col-lg-6 {{OFFSET}}">
              <div class="chat-bubble chat-bubble--{{POS}}">
                {{CONTENT}}
              </div>
              <span class="time">{{TIMESTAMP}}</span>
            </div>
          </div>`;

    const CONVERSATION_TEMPLATE_DEFAULTS = {
        '{{CONVERSATION_ID}}': '',
        '{{LAST_MESSAGE}}': 'left',
        '{{TIMESTAMP}}': '',
        '{{NAME}}': '',
    };

    const BUBBLE_TEMPLATE_DEFAULTS = {
        '{{OFFSET}}': '',
        '{{POS}}': 'left',
        '{{CONTENT}}': '',
        '{{TIMESTAMP}}': '',
        '{{MESSAGE_ID}}': '',
    };

    jQuery.ajaxSetup({
        data: {
            wschat_ajax_nonce: wschat_ajax_obj.nonce
        }
    });

    var chat = new WSChat(jQuery('.wschat-wrapper'), {
        connector: wschat_ajax_obj.settings.communication_protocol === 'pusher' ? AdminPusherConnector : AdminApiConnector,
        api: {
            endpoint: wschat_ajax_obj.ajax_url,
            interval: 3000,
            wschat_ajax_nonce: wschat_ajax_obj.nonce,
            pusher: {
                key: wschat_ajax_obj.settings.pusher.app_key,
                cluster: wschat_ajax_obj.settings.pusher.cluster,
            }
        },
        alert: {
            url: wschat_ajax_obj.settings.alert_tone_url
        },
        header: {
            status_text: wschat_ajax_obj.settings.widget_status === 'online' ? wschat_ajax_obj.settings.header_online_text : wschat_ajax_obj.settings.header_offline_text,
        }
    });

    if (wschat_ajax_obj.settings) {
        for(let key in wschat_ajax_obj.settings.colors) {
            key && chat.$el.get(0).style.setProperty(key,  '#' +wschat_ajax_obj.settings.colors[key]);
        }
    }

    setInterval(() => {
        chat.connector.start_conversation();
    }, 5000);

    const chat_panel = chat.$el.find('.chat-panel');
    const conversation_panel = chat.$el.find('.conversation-list');
    const chat_panel_header = chat.$el.find('.chat-panel-header');
    const chat_tray_box = chat.$el.find('.chat-box-tray');
    const message_input = jQuery('#wschat_message_input');
    const MESSAGE_INFO = {
        min: 0,
        max: 0,
    };
    let PAST_REQUEST_IS_PENDING = false;
    let SCROLL_PAUSED = false;
    let DISABLE_SCROLL_LOCK = false;
    const SCROLL_OFFSET = 100;


    const replaceConversation = (conversation) => {
        let item = conversation_panel.find('[data-conversation-id='+conversation.id+']');
        if (item.length === 0 ) {
            return false;
        }

        item.find('.time').text(conversation.updated_at);
        item.find('.last-message').text( conversation.recent_message ? conversation.recent_message.body.text : '');
        item.find('.unread-count').text(conversation.unread_count || '');

        if (conversation.is_user_online) {
            item.addClass('online');
        } else {
            item.removeClass('online');
        }

        return true;
    };

    const sortConversation = () => {
        const new_conversation_panel = conversation_panel.clone();
        const items = [];

        new_conversation_panel.find('[data-conversation-id]').each(function (i, item) {
            items.push(item);
        });

        items.sort((a, b) => {
            let timestamp1 = jQuery(a).find('.time').html();
            let timestamp2 = jQuery(b).find('.time').html();

            return strToDate(timestamp2) - strToDate(timestamp1);
        });

        new_conversation_panel.html('');

        items.forEach((item) => {
            new_conversation_panel.append(item);
        });

        conversation_panel.html(new_conversation_panel.html());
    };

    const strToDate = (timestamp) => {
        let [date1, time1] = timestamp.split(' ');
        date1 = date1.split('-');
        time1 = time1.split(':');

        return parseInt(date1.join('') + time1.join(''));
    };

    const showNoConversation = () => {
        const no_conversation_alert = jQuery('.no-conversation-alert');
        conversation_panel.append(no_conversation_alert.removeClass('d-none'));
    }

    chat.on(EVENTS.WSCHAT_ON_NO_CONVERSATIONS, () => {
        showNoConversation();
    });
    chat.on(EVENTS.WSCHAT_ON_FETCH_CONVERSATIONS, (conversations) => {

        conversations.forEach(conversation => {
            if (replaceConversation(conversation)) {
                return;
            }

            CONVERSATION_TEMPLATE_DEFAULTS['{{CONVERSATION_ID}}'] = conversation.id;
            CONVERSATION_TEMPLATE_DEFAULTS['{{NAME}}'] = conversation.user.meta.name;
            CONVERSATION_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(conversation.updated_at);
            CONVERSATION_TEMPLATE_DEFAULTS['{{LAST_MESSAGE}}'] = conversation.recent_message ? conversation.recent_message.body.text : '';
            CONVERSATION_TEMPLATE_DEFAULTS['{{UNREAD_COUNT}}'] = conversation.unread_count || '';

            let row_template = CONVERSATION_TEMPLATE;

            row_template = row_template.replace(new RegExp(Object.keys(CONVERSATION_TEMPLATE_DEFAULTS).join('|'), 'g'), match => CONVERSATION_TEMPLATE_DEFAULTS[match]);

            row_template = jQuery(row_template);

            if (conversation.is_user_online) {
                row_template = row_template.addClass('online');
            }

            if (conversation.user && conversation.user.meta.avatar) {
                row_template.find('img.profile-image').attr('src', conversation.user.meta.avatar)
            }
            conversation_panel.append(row_template);
        });

        sortConversation();

        setTimeout(() => {
            let activeItem = conversation_panel.find('.active[data-conversation-id]').length
            activeItem === 0 && conversation_panel.find('[data-conversation-id]').eq(0).click();
        }, 1000);
    });

    chat.on(EVENTS.WSCHAT_ON_SET_CONVERSATION, (data) => {
        data.user &&
            chat_panel_header.find('.username').text(data.user.meta.name);
        let info = chat.$el.find('.user-meta-info').html(UserMetaInfo);

        chat_panel_header.parent().removeClass('d-none')

        info.find('.name').html(data.user.meta.name);
        info.find('.browser').html(data.user.meta.browser);
        info.find('.os').html(data.user.meta.os);
        info.find('.device').html(data.user.meta.device);
        info.find('.url').html(data.user.meta.current_url);

        message_input.focus();
        MESSAGE_INFO.min = 0;
        MESSAGE_INFO.max = 0;
        DISABLE_SCROLL_LOCK = true;
        resizeChat();

        setTimeout(() => DISABLE_SCROLL_LOCK = false, 1000);
    });

    chat.on(EVENTS.WSCHAT_ON_FETCH_MESSAGES, (data) => {
        for (let i = 0; i < data.messages.length; i++) {
            let row = data.messages[i];

            if (row.is_agent === true) {
                BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = 'offset-lg-6 offset-md-3 offset-xs-2';
                BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'right';
            } else {
                BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = '';
                BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'left';
            }
            BUBBLE_TEMPLATE_DEFAULTS['{{MESSAGE_ID}}'] = row.id;
            BUBBLE_TEMPLATE_DEFAULTS['{{CONTENT}}'] = row.body.formatted_content;
            BUBBLE_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(row.created_at);

            let row_template = CHAT_BUBBLE_TEMPLATE;

            row_template = row_template.replace(new RegExp(Object.keys(BUBBLE_TEMPLATE_DEFAULTS).join('|'), 'g'), match => BUBBLE_TEMPLATE_DEFAULTS[match]);

            if (MESSAGE_INFO.min === 0) {
                chat_panel.append('<span data-message-id="0"></span>');
            }

            if (MESSAGE_INFO.min > row.id) {
                chat_panel.find('[data-message-id='+MESSAGE_INFO.min+']').before(row_template);
                MESSAGE_INFO.min = row.id;
            }

            if (MESSAGE_INFO.max === 0 || MESSAGE_INFO.max < row.id) {
                chat_panel.find('[data-message-id='+MESSAGE_INFO.max+']').after(row_template);
                MESSAGE_INFO.max = row.id;
                scrollIfNotPaused();
            }

            if (MESSAGE_INFO.min === 0) {
               scrollIfNotPaused();
            }

            MESSAGE_INFO.min = MESSAGE_INFO.min || row.id;
            MESSAGE_INFO.max = MESSAGE_INFO.max || row.id;
        }

        if (DISABLE_SCROLL_LOCK === true) {
            scrollIfNotPaused();
        }

    });

    chat.on(EVENTS.WSCHAT_ON_PONG, (data) => {
        let drawer = chat_panel_header.find('.friend-drawer');
        let row_template = conversation_panel.find('[data-conversation-id='+data.id+']');
        let row_unread_count = row_template.find('.unread-count');
        let header_unread_count = chat_panel_header.find('.unread-count');

        chat_panel_header.find('.status').text(data.status);
        header_unread_count.text(data.unread_count);
        row_unread_count.text(data.unread_count || '');

        if (data.unread_count) {
            header_unread_count.removeClass('d-none');
        } else {
            header_unread_count.addClass('d-none');
        }

        if (data.is_online) {
            drawer.addClass('online');
            row_template.addClass('online');
        } else {
            drawer.removeClass('online');
            row_template.removeClass('online');
        }
    });

    const scrollIfNotPaused = () => {
        if (SCROLL_PAUSED === false || DISABLE_SCROLL_LOCK === true) {
            chat_panel[0].scrollTop = chat_panel[0].scrollHeight;
        }
    }

    const send_btn = jQuery('#wschat_send_message').on('click', function() {
        let msg = message_input.val();

        if (msg.trim() === '' && chat.trigger(EVENTS.WSCHAT_CAN_SEND_EMPTY_MESSAGE, false, true) === false) {
            return false;
        }

        chat.sendMessage({
            // Type is text by default now, it needs to changed based on the selection content
            wschat_ajax_nonce: wschat_ajax_obj.nonce,
            type: 'text',
            'content[text]': message_input.val()

        });
        message_input.val('').focus();
    });

    message_input.keyup(function(e) {
        e.key === 'Enter' && send_btn.click();
    });

    message_input.on('focus', function() {
        let unread_count = chat_panel_header.find('.unread-count').text();

        if (parseInt(unread_count) > 0) {
            chat.trigger(EVENTS.WSCHAT_ON_READ_ALL_MESSAGE);
        }
    });

    chat_panel_header.on('click', '.user-meta-info-toggle', function () {
        chat.$el.find('.conversation-wrapper .user-meta-info').toggleClass('d-none');
    });

    conversation_panel.on('click', '[data-conversation-id]', function() {
        chat_panel.html('');
        let item = jQuery(this);
        let converssation_id = item.data('conversation-id');
        conversation_panel.find('[data-conversation-id]').removeClass('active');
        item.addClass('active')
        chat.connector.join_conversation(converssation_id);
    });

    chat_panel.on('scroll', function () {
        if (DISABLE_SCROLL_LOCK) {
            SCROLL_PAUSED = false;
            return;
        }
        if (this.scrollTop < SCROLL_OFFSET) {
            if (PAST_REQUEST_IS_PENDING === false) {
                PAST_REQUEST_IS_PENDING = true;
                chat.connector.get_messages({
                    after: 0,
                    before: MESSAGE_INFO.min
                });
                setTimeout(() => PAST_REQUEST_IS_PENDING = false, 500);
            }
        }

        if (this.offsetHeight + this.scrollTop >= this.scrollHeight - SCROLL_OFFSET) {
            SCROLL_PAUSED = false;
        } else {
            SCROLL_PAUSED = true;
        }
    });

    const resizeChat = () => {
        const window_height = jQuery(window).height() - chat.$el.offset().top;

        const height = window_height - (
            chat_panel_header.height()*2 + chat_tray_box.height()
        );

        conversation_panel.css({
            'min-height': height + 'px'
        });

        chat_panel.css({
            'min-height': height + 'px'
        });
    };

    jQuery(window).resize(() => resizeChat());
    resizeChat();

    const emojiPicker = document.getElementById('wschat_emoji_picker');
    const emoji = new EmojiButton({
        style: 'twemoji',
        rootElement: emojiPicker.parentElement,
        position: 'top'
    });


    emojiPicker.addEventListener('click', function() {
        emoji.togglePicker();
    });

    emoji.on('emoji', function(selection) {
        console.log(selection)
        message_input.val(message_input.val() + selection.emoji).focus();
        setTimeout(() => message_input.focus(), 500)
    });


    // Attachment toggler
    chat.$el.find('#attachment_picker').click(function (e) {
        e.preventDefault();
        chat.$el.find('.attachment-list').toggleClass('show d-none');
    });
    chat.$el.find('.attachment-list').on('click','button', function () {

        chat.$el.find('#attachment_picker').click();
    });

});

Can someone help me on this? How to activate the conversation by getting id from url?
Also, i don’t know what type of js they are used can any one let me know?

Update shipping method woocommerce

I have a site with woocommerce and several other plugins (Role Based Methods in particular)

Each user role has two shipping methods: a paid one (the price changes according to the role) and a free one (with a min_amount which also changes according to the role)

During a specific action by the administrator on an order (or an order batch), an update of the prices of the items is done and I wish to update the shipping method (only in the case where the user had a paid method and the new rates exceed the min_amount of his free method)

I manage to retrieve the order total and the shipping methods available for the role of the user

But I can’t update the shipping method.

In fact here is the var_dump of $order->get_items(‘shipping’)when it’s free shipping:
var_dump of $order->get_items('shipping')when it's free shipping

And the var_dump when isn’t free shipping
var_dump when isn't free shipping

as you can see, the shipping method name and price is in the “data” table

So I tried this code:

foreach ($actualShipping as $item_id => $item){
    $data = $item->get_data();
    $data["instance_id"] = $freeMethodForUser[0]["instance_id"];
    $data["name"] = $freeMethodForUser[0]["method_title"];
    $data["method_title"] = $freeMethodForUser[0]["method_title"];
    $data["method_id"] = $freeMethodForUser[0]["id"];
    $data["total"] = "0.00";
    $item->set_props(array(
            'method_title' => $item->get_method_title(),
        'method_id' => $item->get_method_id(),
        'total' => wc_format_decimal($item->get_total()),
        'taxes' => $item->get_total_tax(),
        'meta_data' => $item->get_meta_data(),
        'data' => $data)
    );
    $item->save();
}
$order->calculate_totals();
$order->save();

$freeMethodForUser[0] is an object of type WC_Shipping_Free_Shipping
Before the $item->set_props if I put a var_dump of $data, it’s okay my new shipping method is here

But I can’t save it

Could you please help me to update my shipping method ?

How to copy a file inside a newly created folder and rename the file?

Good day experts!

I want to copy a file inside a newly created folder and rename the file but it seems there’s something wrong with codes and I cant figure it out. Here’s my code:

<?php
$name = $_POST["newFileName"];
$folder = mkdir($name);
session_start();
$name = $_POST["newFileName2"];
$file = 'data.php';
$newfile = $folder/$_POST["newFileName2"].'.php';

file_exists($newfile) && die(" <center><br><br><br><br>The Exam name already exists.! Change it! <br><br> <a href='quiz.php'><button>GO BACK</button></a>");

if (!copy($file, $newfile)) {
    echo "Failed to create Quiz";
}else {
   echo "Created Successfully";
}
?>

Is PHP ldap_escape compatible with Microsoft Active Directory?

Here

https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx

you can see how AD requires to escape individual components of a distinguished name (a backslash in front of the character to be escaped).

The ldap_bind function, however, adopts a different escaping technique (I think according to RFC4514) so for example:

SalesEngineering would be:

Sales\Engineering according to 1

and:

Sales5cEngineering if you use ldap_bind

I know that 5c is just the xx hex sequence for , but can this create problems?

I am having troubles using ldap_bind with domainuser DNs in Active Directory that’s why I am wondering if there are compatibility issues.

Thanks

Block users from REST API endpoint while still grabbing data from it

I have created 2 REST API endpoint to store the CPT data and their custom fields:

Archive Data: xyz.com/wp-json/wl/v2/businesses
Single Business data: xyz.com/wp-json/wl/v2/businesses/<ID>

Both these endpoints have been registered with the permission callbacks;

register_rest_route( 'wl/v2', '/businesses', array(
    'methods'   => WP_REST_Server::READABLE,
    'callback'  =>  'wl_businesses_posts',
    'permission_callback'   => '__return_true'
));

It is a business directory website where a common dashboard ( xyz.com/dashboard ) for each ‘business’ client exists and this dashboard page pulls in data for that ‘business’ from the Single Business data REST API endpoint above and fills the input fields on the page.

There is also another page accessible to the non-logged in visitors( xyz.com/business1 ) that is common for all businesses and is a read-only page where visitors can check that business’ details. This page too pulls data from the Single Business data REST API endpoint mentioned above.

What I am trying to accomplish is that no one except the Admin should be able to peep into the Archive Data or the Single Business data endpoints, to avoid stealing info of all the businesses registered with the site. But at the same time, I would want these endpoints to be accessible by the wp_remote_retrieve_body( wp_remote_get( $url ) );code to populate the dashboard and single business info pages.

I tried this code but it obviously also blocks the requests made by the page code to pull and populate data in the pages.

add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) {
      return $result;
    }
    if ( ! is_user_logged_in() ) {
      return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
    }
    return $result;
  });

I am not necessarily looking for a code, just the direction about how to solve this problem.

file_exists(): open_basedir restriction in effect is checking for a file that doesn’t exist

I have a simple Laravel project, it runs just fine on my local machine, but after uploading to the server, when accessing a certain page, the following error is displayed:

file_exists(): open_basedir restriction in effect.
File(C:inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4resourceslang/ar/Forgot
Your Password?.php) is not within the allowed path(s):
(C:/Inetpub/vhosts/goldenmedpharma.com;C:WindowsTemp;C:Inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4public;C:WindowsTemp)
(View:
C:inetpubvhostsgoldenmedpharma.comhttpdocslaravelgoldenmedpharma.net.v4resourcesviewsauthlogin.blade.php)

I don’t have a file named (Forgot Your Password?.php)! What exactly is this?
I’m using Plesk Obsidian to manage PHP and files on the server.

if condition in Laravelll

I want to check whether the user has cv or not. I used the following expression but doesn’t work any one can help

 public function create()
      
    {   
         if (auth()->user()->cv) {
         
        return $this->edit()-with('You already have a cv!', 'info');
   }
   return view('cv.create');
   }

WordPress search only showing a few posts

I am working on a Website and am linking category links to the search page.
Now the search behaves seemingly random as seen here: https://hasel.dev/?s=dizh

The search for the post returns the post, so far so good. If I click the ‘Developer Productivity’ Tag (= search for it), however, it returns a number of posts, not including the ‘DIZH’ post. If I click the ‘papers’ tag, I don’t get any results at all, although having added the category to over 20 posts.

enter image description here

What is the issue here?