Undefined property: DOMDocument::$documentElement

i have a problem with this package on shared-hosting while i haven’t this problem on localhost

gives me the error:

{
"message": "Undefined property: DOMDocument::$documentElement",
"exception": "ErrorException",
"file": "/home/h189025/public_html/system/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php",
"line": 132,
"trace": [
{
"file": "/home/h189025/public_html/system/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php",
"line": 132,
"function": "handleError",
"class": "IlluminateFoundationBootstrapHandleExceptions",
"type": "->"
},
{
"file": "/home/h189025/public_html/system/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php",
"line": 50,
"function": "getHtmlFromDocument",
"class": "TijsVerkoyenCssToInlineStylesCssToInlineStyles",
"type": "->"
},
{
"file": "/home/h189025/public_html/system/vendor/laravel/framework/src/Illuminate/Mail/Markdown.php",
"line": 74,
"function": "convert",
"class": "TijsVerkoyenCssToInlineStylesCssToInlineStyles",
"type": "->"
},
....
]
}

enter image description here

file_get_contents data can not be scarped

This is the code

$link = "https://www.apple.com/au/search/medication-management?src=globalnav";
$str = file_get_contents($link);
//$str= '<a href="https://apps.apple.com/au/app/medicinewise-manage-medicine/id777483494" class="rf-serp-productname-link">MedicineWise: Manage Medicine</a>';
$pattern="/<a href=".+" class="rf-serp-productname-link">/";
if(preg_match_all($pattern, $str, $matches)) {
  print_r($matches);
}

Inisde $str there is

`<a href="https://apps.apple.com/au/app/medicinewise-manage-medicine/id777483494" class="rf-serp-productname-link">MedicineWise: Manage Medicine</a>

So expected output is

Array
(
    [0] => Array
        (
            [0] => <a href="https://apps.apple.com/au/app/medadvisor-medications-manager/id626138245" class="rf-serp-productname-link">
        )

)

I get this ouput when I define $str manually. But when I get content from the link I am not getting desired result.

How to comment a function using DocBlock

How can i specify that I’m setting the property $nAds

I was thinking to something like:

@set $nAds

but it didn’t worked

This is what I’m using

/**
 * Extract the number of ads of a province and set the property $nAds
 * 
 * @param string $html         The html of the first classified page
 */
private function extract_nPag($html){
    preg_match('/<strong>([0-9]+)</strong>/iU', $html, $result);
    $result[1] = str_replace(".", "", $result[1]);
    $this->nAds =  $result[1];
    }

Google Services like fcm and map Response Delayed unexpectedly

guys I am facing very strange issue, everything was working fine two days ago, all of sudden google map and fcm push notifications started taking to much time in giving response.sometime they give response within a milliseconds sometime the take almost 75 seconds or more, everything working fine on local machine, this issue is happening on live server.our live server is Scala vps, day before yesterday i asked them to change my supervisor config, and after they change and restart supervisor these issues start arising, after that they stop supervisor but still things are not getting back to normal, i asked Scala team a lot about anything they change in server config but they are saying everything is normal on their end. i deployed same code on another server it is working fine their, the api’s which are delaying responses are google map directions ,distance matrix apis and fcm push notifications api, all other external services api working fine, very strange, i am using guzzel http liabrary to call google directions api, i tried with simple curl but still no luck.and this is my very simple code

            $d_latitude = $request->d_latitude;
            $d_longitude = $request->d_longitude;
            $apiurl = "https://maps.googleapis.com/maps/api/directions/json?origin=" . $s_latitude . "," . $s_longitude . "&destination=" . $d_latitude . "," . $d_longitude . "&mode=driving&sensor=false&units=metric&key=" . Setting::get('map_key')."&alternatives=true";
            $client = new Client;
            $location = $client->get($apiurl);
            $location = json_decode($location->getBody(), true);

Changing content type of mail in Laravel 9

I am trying to send calendar emails through Laravel, I had this working on Laravel 7 with the below code but, on Laravel 9 setContentType has been removed and setbody has been changed to html or text (meaning you can’t set the body content type to text/calendar).

I know the ics file is fine as this has not changed and is also an attachment that and that works.

I have tried using the addParameterizedHeader() function but that seems to make no difference.

Is there a way to do this?

        Mail::send([], [], function($message) use($file,$entitySubject,$entityDesc,$custEmail,$userEmail,$userFullName){
            $message->subject($entitySubject)->from($userEmail,$userFullName)->attach($file, array(
                    'as' => $file->getClientOriginalName(),
                    'mime' => "text/calendar"
                                    )
                                );
            $message->To($custEmail);
            $message->setContentType("text/calendar");
            $message->replyTo($userEmail,$userFullName);
         $message->setbody(file_get_contents($file), "text/calendar; charset='utf-8'; method=REQUEST");

How to use pcov in docker container to generate coverage reports?

I try to use pcov to generate code coverage reports in my Docker container.

This is my container’s dockerfile:

FROM php:8.1-fpm-alpine

WORKDIR /var/www/html

RUN apk add --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/edge/community/ --allow-untrusted gnu-libiconv
ENV LD_PRELOAD /usr/lib/preloadable_libiconv.so php

ENV PHP_MEMORY_LIMIT=1G
ENV PHP_UPLOAD_MAX_FILESIZE: 512M
ENV PHP_POST_MAX_SIZE: 512M

RUN docker-php-ext-install pdo

RUN apk add --no-cache libpng libpng-dev && docker-php-ext-install gd && apk del libpng-dev

RUN apk update 
    && apk upgrade 
    && apk add --no-cache 
        freetype 
        libpng 
        libjpeg-turbo 
        freetype-dev 
        libpng-dev 
        jpeg-dev 
        libwebp-dev 
        libjpeg 
        libjpeg-turbo-dev

RUN docker-php-ext-configure gd 
        --with-freetype=/usr/lib/ 
        --with-jpeg=/usr/lib/ 
        --with-webp=/usr

RUN NUMPROC=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || 1) 
    && docker-php-ext-install -j${NUMPROC} gd


RUN apk add --no-cache sqlite-libs
RUN apk add --no-cache icu sqlite git openssh zip
RUN apk add --no-cache --virtual .build-deps icu-dev libxml2-dev sqlite-dev curl-dev
RUN docker-php-ext-install 
        bcmath 
        curl 
        ctype 
        intl 
        pdo 
        pdo_sqlite 
        xml
RUN apk del .build-deps
RUN docker-php-ext-enable pdo_sqlite

RUN echo memory_limit = -1 >> /usr/local/etc/php/conf.d/docker-php-memlimit.ini;
RUN echo culr.cainfo="/etc/cacert.pem" >> /usr/local/etc/php/conf.d/docker-php-curl-ca-cert.ini

# install composer
RUN curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
RUN HASH=`curl -sS https://composer.github.io/installer.sig`
RUN php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
RUN php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer
RUN composer --version

# install pcov
RUN apk add --no-cache --virtual .build-deps $PHPIZE_DEPS
RUN apk add --update linux-headers
RUN pecl install pcov
RUN docker-php-ext-enable pcov
RUN apk del -f .build-deps

And this is the command to run phpunit:

docker-compose run --rm phpunit ./vendor/phpunit/phpunit/phpunit 
  --configuration phpunit.xml --coverage-html=reports/

The reports/ folder is created, but it’s empty.

I tried with --coverage-clover=coverage.xml options too, but this file also not created.

The runs output is this:

PHPUnit 9.5.16 by Sebastian Bergmann and contributors.

...............................................................  63 / 144 ( 43%)
............................................................... 126 / 144 ( 87%)
..................                                              144 / 144 (100%)

Time: 02:09.917, Memory: 227.00 MB

OK (144 tests, 1972 assertions)

Generating code coverage report in HTML format ...

And last line if I use clover format:

Generating code coverage report in Clover XML format ...

What I miss here?

Unable to get twitter user public tweets using Twitter streaming API 2

I want to get real time user tweets from twitter using twitter streaming api v2,
I use https://api.twitter.com/2/tweets/search/stream/rules
endpoint to set rules with rule
like “value”: “from:GulzadeNaser” first according to twitter developer api doc, then
by calling https://api.twitter.com/2/tweets/search/stream end point to get the real time tweets
Unfortunately I could not get the user tweets, but when I add the rule beside above mentioned rule like #demetakalin hashtag, then the mentioned user tweets and other tweets which have hashtag #demetakalin will be on on the result response.

I am using PHP/laravel to get the response, Is there any one who used Twitter streaming API v2 to get the user realtime tweets?
Thanks,

Laravel factory for a relationship with multiple columns

Creating factories for a project I’m working on, I have a problem creating a belongsTo relationship.

In my Cards table, I have 2 columns referencing the same relation :
Card->order->id and Card->order->ref (don’t ask me why, I don’t even know).

So, in my CardFactory I need to be able to use the same instance of Order for both $card->order_ref and $card->order_id. Using factory states, I did create the following state :

public function sold(int $userId) : Factory
{
    $createdOrder = Order::factory()->forUser($userId)->create();

    return $this->state(function (array $attributes) use ($createdOrder) {
        return [
            'state' => Card::STATE_SOLD,
            'sold' => Carbon::now()->subDay(),
            'addedincart' => Carbon::now()->subDay()->subHour(),
            'selling_date' => Carbon::now()->subDay(),
            'order_id' => $createdOrder->id,
            'order_ref' => $createdOrder->ref,
        ];
    });
}

and in my CardSeeder.php :

public function run()
{
    $user = User::query()->where("email", "[email protected]")->first();
    
    Card::factory()->sold($user->id)->count(15)->create();
    Card::factory()->selling()->count(15)->create();
}

The problem is, for each sold state created, the same $createdOrder->id is used.

How could I, for each row, use a different order ?

How to Parse table data from a pdf link in php [closed]

I have this link that takes me to a pdf file. I’ve tried to parse the data in the table in this pdf file using php but nothing works. Any help?

I tried Pdfbox but it doesnt seem to work.

        new Pdfbox(
            '/path/to/java',
            '/path/to/pdfbox-app.jar',
            new PsrLogNullLogger()
                );
    );
    
    // Convert pdf to text
    echo $file->toText('https://www.axisbank.com/docs/default-source/default-document-library/axis-bank-mclr-website-18-july-2022.pdf');```

Is it possible to have two seperate Carts on WooCommerce?

I’m trying to create a custom WooCommerce Cart. It would have the same capabilities as the real WooCommerce Cart. The only difference would be that in each cart, only specific types of products can go in.

Let’s say I have a session variable that tells me which products to show. And based on that session variable, I add products to a specific cart. And you can always change that session variable but keep the products for each cart until the session ends.

After that, I go to the checkout and it will list items from the specific cart based on that session variable once again.

Is something like that possible, specifically having two separate WooCommerce carts, the default one and a new custom one?

I tried this:

if (! isset(WC()->cart_custom) || '' === WC()->cart_custom) {
    WC()->cart_custom = new WC_Cart();
}

but every time I add products to the default cart and open the default cart page, the default cart is emptied. I don’t know why.

I hope my question makes some sense.

Auto update shopping cart when clicking -/+ 1 in Woocommerce

The following code was working fine for auto changing the quantity on the shopping cart. Yet, at the moment it only sometimes responds to changing the quantity. What is wrong?

/**
 * @snippet       Automatically Update Cart on Quantity Change - WooCommerce
 * @compatible    Woo 3.4
 */

add_action( 'wp_footer', 'ava_cart_refresh_update_qty', 9999 ); 
function ava_cart_refresh_update_qty() { 
    if (is_cart()) { 
        ?> 
        <script type="text/javascript">
        (function($) {
            var triggerUpdate = function() {
                $('.woocommerce-cart-form .quantity').on('click', '.qty, .plus, .minus', function(){ 
                    console.log('test');
                    $("button[name='update_cart']").trigger("click");
                 });
            }

            triggerUpdate();
           
            $(document).ajaxComplete(function() {
                triggerUpdate();
            });
        })(jQuery);
        </script> 
        <?php 
    } 
}

Progress bar using PHP data from SQL Server start and stop button

i need help for my case. Need example for finished this.Like my picture. i want to make Allocation Job for mechanic, Mechanic name and License Plate source from sql , when i press start button , bar progress will run(maybe 8 clock) and when i press stop button (maybe at 10 clock) that progress will stop at 10 clock. any body can help me?
I really thanks when somenone can help me.

enter image description here

How to get all records from the database via an endpoint in PHP

Here is the endpoint

http://localhost/mudb/unitedapi/

I need to get all the records in a json format from my table when i load the url in my browser. I can now only get a single record using the id from http://localhost/mudb/unitedapi/1. How can I get them all?

My .htaccess

RewriteEngine On    # Turn on the rewriting engine

RewriteRule ^unitedapi/([0-9a-zA-Z_-]*)$ api.php?player_id=$1 [NC,L]

My code

<?php

 header("Content-Type:application/json");
 if (isset($_GET['player_id']) && $_GET['player_id']!="") {
   include('db.php');
   $player_id = $_GET['player_id'];

   $result = mysqli_query($con, "SELECT * FROM `players` ");

   if(mysqli_num_rows($result)>0)
   {
     $row = mysqli_fetch_array($result);
     $fname = $row['fname'];
     $lname = $row['lname'];
     $shirtno = $row['shirtno'];
     $position = $row['position'];
     $response_code = $row['response_code'];
     $response_desc = $row['response_desc'];

     response($player_id, $fname,$lname,$shirtno,$position, 
 $response_code,$response_desc);
     mysqli_close($con);
    }
    else {
      response(NULL, NULL,NULL, NULL, NULL, 200,"No Record Found");
    }
 } 
 else {
   response(NULL, NULL,NULL, NULL, NULL,400, "Invalid Request");
 }

 function response($player_id, $fname,$lname,$shirtno,$position, 
 $response_code,$response_desc)
 {
   $response['player_id'] = $player_id;
   $response['fname'] = $fname;
   $response['lname'] = $lname;
   $response['shirtno'] = $shirtno;
   $response['position'] = $position;
   $response['response_code'] = $response_code;
   $response['response_desc'] = $response_desc;

   $json_response = json_encode($response);
   echo $json_response;
 }
 ?>

filter data by ID

I want an email filtering function.
this is my url :

https://localhost/quantrictvv1/preview/271.

this is my database:

enter image description here

I want the condition that numbers in the email column matching the id of the above url (which is 271) are allowed to appear, I’m new.
I want a filter function with the condition that email equals url’s id 271, what should I do? I’m new to javascript

View :

<div class="row">
                                                          <div class="col-md-12 mt-4">
                                                             <div class="table-responsive">
                                                                 <table class="table" id="records">
                                                                     <thead>
                                                            
                                                                        <tr>
                                                                    
                                                                         <th>Nhận xét</th>
                                                                           <th>Note</th>
                                                                             <!-- <th>Email</th> -->
                                                                                <th>Action</th>
                                                                                  </tr>
                                                                                 </thead>
                                                                                </table>
                                                                              </div>
                                                                            </div>
                                                                          </div>

Javascript :

<script>
    $(document).on("click", "#add", function(e){
        e.preventDefault();
        var name = $("#name").val();
        var email = $("#email").val();
      
        if (name == "" || email == ""){
            alert("Không được để trống");
        }else{
            $.ajax({
                url:"<?php echo base_url(); ?>insert",
                type: "post",
                dataType: "json",
                data: {
                    name: name,
                    email: email
                },
                success: function(data){
                  if (data.responce == "success") {
                      $('#records').DataTable().destroy();
                    fetch();
                    $('#exampleModal').modal('hide');
                    toastr["success"](data.message);
                  }else{
                    toastr["error"]('Ghi chú không thành công');
                  }
                }
            });
            $("#form")[0].reset();
        }
    });
    //fetch records
    function fetch(){   
      //lấy url xuống
          var check = window.location.href ;
          var final = check.substr(check.lastIndexOf('/') + 1);
           var text = <?= $text_from_db; ?>
        $.ajax({
            url:"<?php echo base_url();?>fetch",
            type: "post",
            dataType: "json",       
            success: function(data){         
                var i = "1";
                var check_id_js = $("#check_id_js").val();         
                $('#records').DataTable({
               "data": data.posts,
               
            columns: [
                {"render": function(){
                    return a = i++;
                }},
                
                { data: 'name',
                 },
                //{ data: 'email' },
                { "render": function ( data, type, row, meta ) {
           var a = `<a href="#" value="${row.id}" id="del" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></a>
                                        <a href="#" value="${row.id}" id="edit" class="btn btn-sm btn-outline-success"><i class="fas fa-edit"></i></a>`;
                                return a ;
        } }
            ],
        });
            }
        });
    }
       fetch();
      // Delete Record
    
          $(document).on("click", "#del", function(e){
            e.preventDefault();
    
            var del_id = $(this).attr("value");
    
            const swalWithBootstrapButtons = Swal.mixin({
              customClass: {
                confirmButton: 'btn btn-success',
                cancelButton: 'btn btn-danger mr-2'
              },
              buttonsStyling: false
            })
    
            swalWithBootstrapButtons.fire({
              title: 'Are you sure?',
              text: "You won't be able to revert this!",
              icon: 'warning',
              showCancelButton: true,
              confirmButtonText: 'Yes, delete it!',
              cancelButtonText: 'No, cancel!',
              reverseButtons: true
            }).then((result) => {
              if (result.value) {
    
                  $.ajax({
                    url: "<?php echo base_url(); ?>delete",
                    type: "post",
                    dataType: "json",
                    data: {
                      del_id: del_id
                    },
                    success: function(data){
                      if (data.responce == "success") {
                          $('#records').DataTable().destroy();
                          fetch();
                          swalWithBootstrapButtons.fire(
                            'Deleted!',
                            'Your file has been deleted.',
                            'success'
                          );
                      }else{
                          swalWithBootstrapButtons.fire(
                            'Cancelled',
                            'Your imaginary file is safe :)',
                            'error'
                          );
                      }
    
                    }
                  });
    
    
                
              } else if (
                /* Read more about handling dismissals below */
                result.dismiss === Swal.DismissReason.cancel
              ) {
                swalWithBootstrapButtons.fire(
                  'Cancelled',
                  'Your imaginary file is safe :)',
                  'error'
                )
              }
            });
    
          });
    
    
           // Edit Record
    
          $(document).on("click", "#edit", function(e){
            e.preventDefault();
    
            var edit_id = $(this).attr("value");
    
            $.ajax({
              url: "<?php echo base_url(); ?>edit",
              type: "post",
              dataType: "json",
              data: {
                edit_id: edit_id
              },
              success: function(data){
                if (data.responce == "success") {
                    $('#edit_modal').modal('show');
                    $("#edit_record_id").val(data.post.id);
                    $("#edit_name").val(data.post.name);
                    $("#edit_email").val(data.post.email);
                  }else{
                    toastr["error"](data.message);
                  }
              }
            });
    
          });
          
           // Update Record
    
          $(document).on("click", "#update", function(e){
            e.preventDefault();
    
            var edit_record_id = $("#edit_record_id").val();
            var edit_name = $("#edit_name").val();
            var edit_email = $("#edit_email").val();
    
            if (edit_record_id == "" || edit_name == "" || edit_email == "") {
              alert("Both field is required");
            }else{
              $.ajax({
                url: "<?php echo base_url(); ?>update",
                type: "post",
                dataType: "json",
                data: {
                  edit_record_id: edit_record_id,
                  edit_name: edit_name,
                  edit_email: edit_email
                },
                success: function(data){
                  if (data.responce == "success") {
                    $('#records').DataTable().destroy();
                    fetch();
                    $('#edit_modal').modal('hide');
                    toastr["success"](data.message);
                  }else{
                    toastr["error"](data.message);
                  }
                }
              });
    
            }
    
          });
    </script>

Controllers :

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    
     class Welcome extends CI_Controller{
       public function __construct()
       {  
          parent::__construct();
          $this->load->helper(array('form', 'url'));
    
            $this->load->library('form_validation');
          $this->load->model('crud_model');
       }
       public function index()
       {
          $this->load->view('preview');
       }
      public function insert()
        {
            if ($this->input->is_ajax_request()) {
                $this->form_validation->set_rules('name', 'Name', 'required');
                $this->form_validation->set_rules('email', 'Email', 'required');
                if ($this->form_validation->run() == FALSE)
              {
                    $data = array('responce' => 'error', 'message' => validation_errors());
                 }
              else 
             {
               $ajax_data = $this->input->post();
                    if ($this->crud_model->insert_entry($ajax_data)) {
                        $data = array('responce' => 'success', 'message' => 'Ghi chú thành công');
                    } else {
                        $data = array('responce' => 'error', 'message' => 'Không thêm được bản ghi');
                    }
                }
    
                echo json_encode($data);
            } else {
                echo "No direct script access allowed";
            }
        }
        public function fetch(){
            if($this->input->is_ajax_request()){
                if($posts = $this->crud_model->get_entries()){
                    $data = array('responce' => 'success','posts' => $posts);
                }else{
                    $data = array('responce' => 'error','massage' => 'Không tìm thấy dữ liệu');
                }
                echo json_encode($data);
            }else{
                echo "không cho phép truy cập data";
            }
        }
        public function delete(){
            if($this->input->is_ajax_request()){
                $del_id = $this->input->post('del_id');
                if($this->crud_model->delete_entry($del_id)){
                    $data = array('responce' => 'success');
                }else{
                    $data = array('responce' => 'error');
                }
                echo json_encode($data);
            }else{
                echo "không cho phép truy cập data";
            }
        }
            public function edit()
        {
            if ($this->input->is_ajax_request()) {
                $edit_id = $this->input->post('edit_id');
    
                if ($post = $this->crud_model->edit_entry($edit_id)) {
                    $data = array('responce' => 'success', 'post' => $post);
                } else {
                    $data = array('responce' => 'error', 'message' => 'failed to fetch record');
                }
                echo json_encode($data);
            } else {
                echo "No direct script access allowed";
            }
        }
        
        public function update(){
            if($this->input->is_ajax_request()){
    
             $this->form_validation->set_rules('edit_name', 'Name', 'required');
                $this->form_validation->set_rules('edit_email', 'Email', 'required');
                if ($this->form_validation->run() == FALSE)
              {
                    $data = array('responce' => 'error', 'message' => validation_errors());
                 }
              else 
             {
                        $data['id'] = $this->input->post('edit_record_id');
                         $data['name'] = $this->input->post('edit_name');
                         $data['email'] = $this->input->post('edit_email');
    
                    if ($this->crud_model->update_entry($data)) {
                        $data = array('responce' => 'success', 'message' => 'Cập nhật thành công');
                    } else {
                        $data = array('responce' => 'error', 'message' => 'Cập nhật không thành công');
                    }
                }
    
                echo json_encode($data);
    
            }else{
                echo "No direct script access allowed";
            }
        }
     } ''
    models :
    `` ` <?php 
    
        class Crud_model extends CI_Model {
    
            public function get_entries()
            {
                    $query = $this->db->get('crud');
                     if (count( $query->result() ) > 0) {
                        return $query->result();
                     }
            }
    
            public function insert_entry($data)
            {
                return $this->db->insert('crud', $data);
            }
    
            public function delete_entry($id){
                return $this->db->delete('crud', array('id' => $id));
            }      
    
            public function edit_entry($id){
                $this->db->select("*");
                $this->db->from("crud");
                $this->db->where("id", $id);
                $query = $this->db->get();
                if (count($query->result()) > 0) {
                    return $query->row();
                }
            }
    
            public function update_entry($data)
            {
                return $this->db->update('crud', $data, array('id' => $data['id']));
            }
            
    
    }