Restricting Sales Representatives to View Only Their Own Orders in PrestaShop 8.1.1

In PrestaShop 8.1.1, I created a profile named ‘Sales Representative’. This profile has an ID of 5. I’ve added the appropriate permissions so that they can’t do anything other than add, edit, and view orders on the admin page. The problem is that I would like each sales representative to only see the orders that they themselves have added in the orders tab..

I’ve seen a similar problem solved before, but it was on PrestaShop version 1.7 or lower. Now the controllers have changed and there is no typical AdminOrdersController.php. I also searched in the path ‘/src/PrestaShopBundle/Controller/Admin/Sell/Order’ but didn’t find anything that could be useful

Is anyone able to help me?

PHP gRPC ignores keepalive parameters

I put these 3 parameters:

grpc.keepalive_time_ms=7200000
grpc.keepalive_timeout_ms=200000
grpc.keepalive_permit_without_calls=1

in /etc/php/8.1/apache2/conf.d/20-grpc.ini, /etc/php/8.1/apache2/conf.d/custom-php.ini, /etc/php/8.1/cli/conf.d/20-grpc.ini and /etc/php/8.1/cli/conf.d/custom-php.ini. Then I restart webserver (whole Docker container) and list grpc config with php -i | grep grpc and they are missing from the output:

/etc/php/8.1/cli/conf.d/20-grpc.ini,
grpc
grpc support => enabled
grpc module version => 1.59.1
grpc.enable_fork_support => 0 => 0
grpc.grpc_trace => all,-timer_check => all,-timer_check
grpc.grpc_verbosity => debug => debug
grpc.log_filename => /var/log/grpc.log => /var/log/grpc.log
grpc.poll_strategy => no value => no value

I tested it with PHP 8.1, gRPC extension 1.45.0 and 1.59.1.
What am I doing wrong?

creating a widget that can be repeated based on a template [closed]

I want to create a widget in my plugin that can repeat the list of users along with some of their information based on the template that I create, just like that template. What I want is just like the listing in jet engine. Please teach me if you know how to define the listing template and call it inside foreach in the widget.

Disabling the purchase of only one variable-product with specific attribute value in woocommerce

I want some specific products to be bought only with other products in one order, and not solo!
I have some variable-product with “Tester” value for “Size” attribute, i dont want customers to only buy them in one order!
I’ll appriciate if you could help me!

I expect when a customer select only this type of product, woocomerce does not allow customer to proceed and an error message be shown!

How to implement One To Many (Polymorphic) in symfony

Hi I have three entities User, Admin, Log
Both the admin and user have many logs.
Each log has one owner might be Usermight be Admin.

In this case, I was searching for a similar system as Laravel Elequent One To Many (Polymorphic) in Symfony Doctrine to implement.

However, I don’t want to make each AdminLog or UserLog extend Log
Or use the ManyToMany method.

In Laravel we use morphTo and morph in migrations to declare an entity polymorphic.

I tried logable_type and logable_id in the Admin and User entities to simulate that

I want s similar mechanic in Symfony however if there better solution or
way or it’s just not the best practice for let me know which is better

Problem with docker and sftpgo, unable to connect to localhost:2022

I’m trying to set up a project with docker and laravel, but I want to include Sftpgo. It seems to work correctly, because I can access the administration and client panels from localhost:8080, create users, etc., but when I use the service from Laravel and grab any of those files I receive the following error message:
“Unable to connect to host: http://dev.vito.com:2022″
I attach the .yml file, the Laravel .env variables are correct, because when I use sftpgo without docker everything works perfectly.

> services:   app:
>     container_name: appvito
>     user: "root:root"
>     ports:
>       - "80:80"
>     build: './build/app'
>     depends_on:
>       - "db"
>     volumes:
>       - .:/var/www/html
>     networks:
>       - local   db:
>     image: mariadb:10.6
>     container_name: dbvito
>     ports:
>       - "3306:3306"
>     build: './build/db'
>     networks:
>       - local
>     environment:
>       MARIADB_ALLOW_EMPTY_ROOT_PASSWORD: "true"
>       MARIADB_ROOT_PASSWORD: ""
>     volumes:
>       - dbData:/var/lib/mysql   sftpgo:
>     image: drakkan/sftpgo:latest
>     user: "root:root"
>     container_name: sftpgo-container
>     ports:
>       - "8080:8080"
>       - "2022:2022"
>     volumes:
>       - sftpgoData:/etc/sftpgo
>     networks:
>       - local volumes:
>     appData:
>     dbData:
>     sftpgoData:
>     networks:
>     local:
>       name: local-network
>       external: true

Thank you

Laravel: mocking service class in job

I have problem.
There is a service class, what I want to mocking for test, but I can not.

My test:

    protected function setUp() : void
    {
        parent::setUp();

        Queue::fake();

        $this->client = $this->createClient();
    }

    private function callJob()
    {
        CreateBrevoContactJob::dispatch($this->client);
    }

    /** @test */
    public function it_calls_create_brevo_contact_api_endpoint()
    {
        $this->mock(ContactsApi::class, function (MockInterface $mock) {
            $mock->shouldReceive('createContact')->once();
        });

        $this->callJob();
    }

My job:


class CreateBrevoContactJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public Client $client;
    private ContactsApi $brevo;

    /**
     * Create a new job instance.
     * @param Client $client
     * @return void
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
        $this->brevo = (new Brevo())->getContactInstance();
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->brevo->createContact((new ClientBrevoContactAdapter($this->client))->convert());
        // create new contact (api)
        // create BrevoContact from brevo api instance
    }
}

Brevo.php:

class Brevo extends Model
{
    private Configuration $config;

    public function __construct()
    {
        parent::__construct();

        $this->config = Configuration::getDefaultConfiguration()->setApiKey('api-key', env('BREVO_API_KEY'));
    }

    public function getContactInstance(): ContactsApi
    {
        return new ContactsApi(
            new Client(),
            $this->config
        );
    }
}

test result:

  1. TestsUnitJobsCreateBrevoContactJobTest::it_calls_create_brevo_contact_api_endpoint
    MockeryExceptionInvalidCountException: Method createContact() from Mockery_2_SendinBlue_Client_Api_ContactsApi should be called
    exactly 1 times but called 0 times.

Maybe someone can help me… 🙂
Thanks,

Exporting SQL data to CSV using PHP [closed]

I am trying to export sql tables to CSV, however, my output doesn’t produce column headings. How can I retrieve the column headings from SQL table without manually creating an array?

I tried mysqli_num_fields but it is not working.
I get an error code saying that it doesn’t convert string. I am not sure what else to use.
Fatal error: Uncaught Error: Call to undefined function mysql_num_fields() in C:xampphtdocsnew.php:16 Here is the error that I am receiving.
I want to export tables to excel with dynamic column headings

Why does my login script not authenticate username or password? [closed]

I’m trying to make as basic of a login process as I can using PHP. After I submit username and password it does not appear to be running my PHP code. The form is intended to trigger the authentication process which is checking session variables to see if they match the preset values, and if so pass along another page.

I’ve tried to create it so that when you hit submit, it is checking if the correct username and password were entered. If they are, then the session variable should be set to valid/logged-in and then will bring the user to another page that greets the user with a successful login. However when I hit submit the form action occurs regardless of any information being submitted which indicates to me the PHP portion isnt functioning at all.

<?php

//start php session
    session_start();
    
    //sets username password
    $username = "admin";
    $password = "1234";
    
    
    //check for if session value is set to logged in 
    if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true {
        header("Location: success.php");
    }
    
    //check if username & password are equal to set variables from lines 7 & 8
    if (isset($_POST['username']) && isset($_POST['password'])) {
        if ($_POST['username'] == $username && $_POST['password'] == $password) 
        {
            $_SESSION['logged_in'] = true;
            $_SESSION['username']=$username;
            header ("Location: success.php");
        }
    }

?>
<html>
  <style>
         body {
            padding-top: 40px;
            padding-bottom: 40px;
            background-color: #ffcc66;
         }
         
         h1{
             margin: 0 auto;
             width: 250px;
            text-align: center;
            color: #017572;
         }
      </style>
      <h1>Login Page</h1>
    <body>
    <div align="center">
        <form method="post" action="welcome.php">
            Username:<br/>
            <input type="text" name="username"><br/>
            Password<br/>
            <input type="password" name="password"><br/>
            <input type="submit" name="submit" value="Login!">
        </form>
        </div>
    </body>
</html>

Displaying Multiple Student Reports: Only One Record Appears Despite Multiple Reports Uploaded [duplicate]

I am facing an issue with displaying student reports on my website. I have a database where students upload their reports. Each student can upload multiple reports, but when I try to display these reports on their profiles, only one record is appearing, even if they have uploaded several reports.

I am currently fetching data from two tables: ‘student’ and ‘reports’. The ‘reports’ table has a foreign key ‘student_id’ linking it to the ‘student’ table. I’m using a MySQL query to fetch the records, but it seems to fetch only one report per student.

The image I provided, what happened to the output:

Student 1st row in table “student” student_id [2]

Student 2nd row in table “student” student_id [5]

Here’s a snippet of my code:

<?php 
include("../../include/config.php"); 
 
if(isset($_GET["id"])){ 
    $id = mysqli_real_escape_string($conn, $_GET["id"]); 
    $sql = "SELECT reports.id AS report_id, reports.title, reports.objective, reports.content, reports.report_date, reports.report_time,  
            student.student_id, student.username, student.ic_number, student.email, student.address, student.status, student.phone_number, student.programme 
            FROM reports  
            JOIN student ON reports.student_id = student.id 
            WHERE student.id = $id"; 
    $result = mysqli_query($conn, $sql); 
 
    if(mysqli_num_rows($result) > 0) { 
        $student = mysqli_fetch_assoc($result); 
    } else { 
         
        die("Student not found."); 
    } 
} 
function getFormattedDate($timestamp, $timezone) { 
    date_default_timezone_set($timezone); 
    $dateObj = new DateTime($timestamp); 
    $currentYear = date("Y"); 
    if ($dateObj->format("Y") == $currentYear) { 
        $formattedDate = $dateObj->format("d-M"); 
    } else { 
        $formattedDate = $dateObj->format("d M Y"); 
    } 
    return $formattedDate; 
} 
?>
<table class="table"> 
                <tr> 
                    <th>Username</th> 
                    <td><?php echo $student["username"];?></td> 
                </tr> 
                <tr> 
                    <th>Student ID</th> 
                    <td><?php echo $student["student_id"];?></td> 
                </tr> 
                <tr> 
                    <th>Email</th> 
                    <td><?php echo $student["email"];?></td> 
                </tr> 
                <tr> 
                    <th>No. Tel</th> 
                    <td><?php echo empty($student["phone_number"]) ? '-': $student['phone_number'];?></td> 
                </tr> 
                <tr> 
                    <th>IC Number</th> 
                    <td><?php echo $student["ic_number"];?></td> 
                </tr> 
                <tr> 
                    <th>Address</th> 
                    <td><?php echo empty($student["address"]) ? '-': $student["address"] ;?></td> 
                </tr> 
                <tr> 
                    <th>Programme</th> 
                    <td><?php echo empty($student["programme"]) ? '-': $student["programme"];?></td> 
                </tr> 
                <tr> 
                    <th>Status</th> 
                    <td> 
                        <?php 
                        if ($student["status"] == 1) { 
                            echo "<span class='badge text-bg-success'>Active</span>"; 
                        } else { 
                            echo "<span class='badge text-bg-danger'>No Active</span>"; 
                        } 
                        ?> 
                    </td> 
                </tr> 
            </table> 
            </div> 
        </div> 
 
        <h2 class="mt-5">Reports</h2> 
        <table class="table table-striped"> 
            <thead> 
                <tr> 
                    <th>#</th> 
                    <th>Title</th> 
                    <th>Content</th> 
                    <th>Date Sent</th> 
                </tr> 
            </thead> 
            <tbody> 
                <?php 
                 
                $counter = 1; 
                $j=1; 
                while ($row = mysqli_fetch_assoc($result)) { 
                    echo "<tr class='clickable-row' data-href='../view-report?id=" .  $row["report_id"] . "'>"; 
                    echo "<td>" . $counter . "</td>"; 
                    echo "<td>" . $row["title"] . "</td>"; 
                    echo "<td>" . $row["content"] . "</td>"; 
                    $formattedDate = getFormattedDate($row["report_date"], "UTC"); 
                    echo "<td>" . $formattedDate . "</td>"; 
                     
                    echo "</tr>"; 
                    $counter++; 
                    $j++; 
                } 
                ?> 
            </tbody> 
        </table>

table “reports”

To address this issue, needed to modify the code to fetch all the reports associated with a specific student. Achieved this by adding an additional SQL query $reportSql inside the main if block. This query retrieved all reports related to the specific student using their student_id. By executing this query and iterating through the results in a separate while loop, were able to display all the reports associated with the student on their profile page. This approach ensured that all relevant information was accurately displayed for each student.

Issue Creating Google Calender Event with spatie/laravel-google-calendar

Question:

I’m trying to create an event using Laravel and Ajax, but I’m encountering an issue where nothing happens when I change the start and end dates. I’ve provided my code below for reference.

Description:

I have a Laravel controller with a store method that handles the creation of an event. When I change the start and end dates in the form, I want to use Ajax to send the data to the server and create the event. However, it’s not working as expected, and I need help identifying what’s going wrong.

web.php(Route)

Route::resource('event',EventController::class);

EventController

 public function store(Request $request)
    {
     
        if ($request->isMethod('post')) {
            $event = $this->createEventInstance($request);
            
            // Perform other actions if needed
            
            return;
        }

    }
      
    private function createEventInstance(Request $request)
{
    $startTime = Carbon::parse($request->input('effective_period_start_date'));
    $endTime = Carbon::parse($request->input('effective_period_end_date'));

    return new Event([
        'startDateTime' => $startTime,
        'endDateTime' => $endTime
    ]);
}

Blade code

 <div class="col-sm-4">
    <div class="mb-3">
      <label class="form-label">Effective Period Start date</label>
      <input type="date" class="form-control effective_period_start_date" name="effective_period_start_date" value="{{@$obj->effective_period_start_date}}" {{ $disabledfield }}>
    </div>
  </div>
  <div class="col-sm-4">
    <div class="mb-3">
      <label class="form-label">Effective Period End date</label>
      <input type="date" class="form-control effective_period_end_date" name="effective_period_end_date" value="{{@$obj->effective_period_end_date }}" {{ $disabledfield }}>
    </div>
  </div>


var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    var url = '/event';
    $(document).ready(function() {
    $('.effective_period_start_date, .effective_period_end_date').on('change', function() {
        var startDate = $('.effective_period_start_date').val();
        var endDate = $('.effective_period_end_date').val();

        if (startDate && endDate) {
            // Prepare the data to send to the server
            // var data = {// Include CSRF token
                
            //     "effective_period_start_date": startDate,
            //     "effective_period_end_date": endDate
            // };
            $.ajax({
                type: 'POST',
                url: url,
                data: {
                    effective_period_start_date: startDate,
                    effective_period_end_date: endDate
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }, // Send data in the request body
                success: function(response) {
                    console.log('Event created:', response);
                    // You can handle the success response here
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);
                    // You can handle errors here
                }
            });
        }
    });
});

Issue Details:

  1. I’m using the store method in my controller to create an event.

  2. I have a private method createEventInstance to prepare the event data.

  3. I’m using Js and Ajax to send the data to the server when the start and end dates change.

Expected Behavior:

I expect the event to be created and the success response to be handled.

Actual Behavior:

The event is not being created, and I’m not receiving any success response.

Questions:

  • Can you please help me identify what might be causing this issue?

  • Is there anything wrong with my Ajax request or controller logic?

  • Are there any specific Laravel routes or configurations I need to check?

Method Illuminate\Routing\UrlGenerator::nullable does not exist

In Laravel Nova, I have a problem that doesn’t occur locally, but it happens in the staging area, and that’s when I open a page this error happens: Method IlluminateRoutingUrlGenerator::nullable does not exist. I don’t know why this problem happens in some areas but doesn’t happen in others?

How to access Apache environmental variables cross-request from PHP?

What I want is a login wrapper around the entire webroot on a server running Apache 2.4 and PHP 8.2. This wrapper is only to be triggered when the client IP address is an outdoor address (i.e. other than indoor IPs like 10.0.0.0/8 or 192.168.0.0/16).
So far so good, that can I handle in Apache in .htaccess.
But when this is the case, all pages, regardless any, of the webserver should redirect to the login page when not logged in.

RewriteEngine  on
# No indoor addresses
RewriteCond %{REMOTE_ADDR} !(^::1|127.0|192.168.0.0|10.0)
# All webpages on this server
RewriteCond %{REQUEST_URI} ^.*$ [NC]
# Cookie with name $(THECOOKIENAME) should not be set (this is the line I ask about)
RewriteCond expr "%{HTTP_COOKIE} -strcmatch '!*%{ENV:THECOOKIENAME}'"
# When all conditions met, go to login page
RewriteRule $ /loginpage.php [L]

So Apache checks whether a cookie is set with the name set in an envrironment variable $(THECOOKIENAME), which is to be set in a PHP script with a unique hexstring per session. I cannot use constants obviously because then setting the fixed cookie name simply allows login without credentials.

PHP code in loginpage.php::

if ($cookiename = auth_login()) { // check for login and generate unique key
    apache_setenv($cookiename, 1);   
    header("Location: " .$_SERVER["REQUEST_URI"]); exit;
} else {
    apache_setenv($cookiename, "");   
    echo showloginprompt();
}

Now the problem is that the env variable set by apache_setenv() is not recognized in Apache. I tried with a fixed $cookiename but even then it does not recognize the environmental variable.
I tried putenv($hexstring, 1) or even $_ENV['THECOOKIENAME'] = $hexstring; but to no avail as well.
It appears these functions only works in a single request. AFAIK, the $_SESSION would be nice, but it is not available under Apache (httpd.conf or .htaccess).

Does somebody know how to pass variables cross request between PHP and Apache ?

WordPress: displaying a list of posts in `edit` page of admin panel (meta box) cause all fields empty

I have a custom post type in my WordPress that authors will send new posts in it. I want to display a list of posts in “Edit” page of that custom post type in admin panel.

So I created a meta box and used a code to get posts from another custom post type (it suppose to be such a quick posts that i had to add it).

Meta box added fine, posts getting fine, but when i enter edit page, another custom fields (Advanced custom fields) will fully clear and empty! When I remove that post’s list code, field’s data will show but when i add getting post’s code, it will clear fields data.

this is code for getting posts list:

<?php
global $post;
$post_id = $_GET['post'];

$args = array( 'posts_per_page' => -1, 'post_type' => 'vosooli', 'meta_query' => array(array('key' => 'parvande_id_invosolli','value' => $post_id,),), );

$myposts = get_posts( $args );

foreach ( $myposts as $post ) : 
  setup_postdata( $post ); ?>
    
    <?php $post_idm = get_the_ID(); ?>
    <?php $vaziat_vosoolyi = get_post_meta($post->ID, 'vosooli_status', true); ?>

    <a status="<?php echo $vaziat_vosoolyi; ?>" class="listvosoole vosoolshode" href="https://example.com/vosooli-info.php?id=<?php echo $post_idm; ?>" >
        <?php $mablaaq = get_post_meta($post->ID, 'vosooli_mablaq', true); echo number_format($mablaaq, 0, '.', ','); ?>
        <span><?php echo $vaziat_vosoolyi; ?></span>
    </a>
    
<?php endforeach; wp_reset_postdata(); ?>

I think there is a problem to end postdata and end query and let page to continue loading fields data like wp_reset_postdata(); etc. Any advise?

I want to trun off toggle on my wooCommerce checkout pag ” have a coupon? Click here to enter your code” i need the box and apply button no toggle

Hi I would like to remove this line ” have a coupon? Click here to enter your code

My customers did not see this option many times.

I need the only box and apply button that shows after click on the click here to enter your code. O don’t need this click feature. I want to use the box and apply button directly.

Please help me how can i do that. I have the access to cpnel and know the coupons-form.php and function.php but how can i do that

Regards
Awais

I need the code that resolved my issue i replaced with answer code to existing code