HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.104.1.lve.el8.x86_64 #1 SMP Tue Feb 10 20:07:30 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.29
Disabled: exec,passthru,shell_exec,system
Upload Files
File: /home/posscale/www/printmanager/app/Http/Controllers/SyncPrintersController.php
<?php

namespace App\Http\Controllers;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use App\Actions\SmtpAction;
use App\Http\Controllers\Controller;
use App\Mail\LowTonerAdminEmail;
use App\Mail\OrderPlaced;
use App\Models\AlertThreshold;
use App\Models\connectionSettings;
use App\Models\emailSettings;
use App\Models\GeneralSettings;
use App\Models\Order;
use App\Models\Printer;
use App\Models\PrinterJob;
use App\Models\Reception;
use App\Models\SupplierTonerPrice;
use Illuminate\Http\Request;
use PhpParser\Node\Expr\Print_;
use App\Models\Tenant;
use App\Models\TonerLevelMonitoring;
use App\Models\User;
use Illuminate\Support\Facades\Mail;

class SyncPrintersController extends Controller
{
    public $admin_settings;

    /**
     * Display the user's profile form.
     */
    public function index(Request $request)
    {

        $allTenants = Tenant::all();

        if ($allTenants) {
            foreach ($allTenants as $key => $singleTenants) {
                try {
                    tenancy()->initialize($singleTenants);
                    $this->sync();
                    tenancy()->end();
                } catch (\Throwable $th) {
                    //throw $th;
                }
            }
        }
    }
    public function sync()
    {

        // Get all connections from the general settings and printers.
        $connections = connectionSettings::all();
        $email_set = emailSettings::find(1);
        $this->admin_settings = $email_set ? $email_set->toArray() : [];
        foreach ($connections as $connection):
            if ($connection->connection_status):
                if ($connection->type == 'SMTP'):
                    $this->syncWithSMTP($connection);
                elseif ($connection->type == 'FTP'):
                    echo $connection->type;
                endif;
            endif;
        endforeach;
    }


    public function syncWithSMTP(connectionSettings $conneciton_details)
    {

        /* Connect to SMTP */
        $smtp_info = json_decode($conneciton_details->data);
        $smtp_details['client'] = [
            'host'          => $smtp_info->host,
            'port'          => $smtp_info->port,
            'encryption'    => 'ssl',
            'username'      => $smtp_info->user_name,
            'password'      =>  $smtp_info->user_password,
            'protocol'      => $smtp_info->type_for_monitoring,
        ];

        $last_sync = $conneciton_details->last_sync_date;
        $smtp_connection = new SmtpAction($smtp_details);
        $connection_info = $smtp_connection->testConnection();

        if ($connection_info['status']) {
            $conneciton_details->connection_status = 1;
            $conneciton_details->last_connection_date = date('Y-m-d h:i:s');
            $conneciton_details->last_sync_date = date('Y-m-d h:i:s');
        } else {
            $conneciton_details->connection_status = 0;
        }

        $conneciton_details->save();

        $folder =  $smtp_connection->client->getFolder('INBOX');

        $sinceDateTime = date('Y-m-d h:i:s', strtotime($last_sync));
        $query = $folder->query()
            ->setFetchOrder("asc")
            ->since($sinceDateTime)
            ->limit(100);
        /*->limit(20);*/
        $messages =  $query->get();
        foreach ($messages as $message) {

            $message_id = $message->get('message_id');
            $body_text = $message->getTextBody();
            $array_of_job = (explode("\n", $body_text));
            $job_details_data = [];
            $prefix = '';

            $events = [];
            $currentDate = "";
            $low_toner = 0;
            $send_mail_to_admin = 0;

            $header = $message->getHeader();
            // dd($header->get('from')->toArray());
            $header_arr =  $header->get('from')->toArray();

            $reception_email = $header_arr[0]->mail;
            $reception_name = $header_arr[0]->host;

            foreach ($array_of_job as $job_details) {

                if (trim($job_details) == '-------------------') {
                    break;
                }
                $line = trim($job_details);

                if (preg_match('/^<.*>$/', $line)) {
                    $currentDate = $line;
                    $events[$currentDate] = [];
                    continue;
                } elseif (!empty($line) && $currentDate != '') {
                    if (!isset($events[$currentDate])) {
                        $events[$currentDate] = [];
                    }

                    $events[$currentDate][] = $line;

                    if ($this->admin_settings['is_active'] == 1) {
                        $line_data = explode(':', $line);
                        if (trim($line_data[0]) == 'black') {
                            $toner =  trim($line_data[1], '%, ');
                            if ($toner <= $this->admin_settings['toner_level']) {
                                $send_mail_to_admin = 1;
                            }
                        }
                    }

                    if (trim($line) == '[*] Low Toner') {
                        $low_toner = 1;
                    }
                    continue;
                }

                $row_data = explode(':', $job_details);

                if (trim($row_data[0]) == 'Printed Pages') {
                    $prefix = 'Printed ';
                }

                if (trim($row_data[0]) == 'Scanned Pages') {
                    $prefix = 'Scanned ';
                }

                if (trim($row_data[0]) == 'Counters by Paper Size') {
                    $prefix = 'Counters ';
                }

                if (trim($row_data[0]) == 'Counters by Duplex') {
                    $prefix = 'Counters D ';
                }

                if (trim($row_data[0]) == 'Counters by Combine') {
                    $prefix = 'Counters C ';
                }

                if (trim($row_data[0]) == 'none') {
                    $prefix = 'none ';
                }

                $key = array_search($prefix . trim($row_data[0]), $smtp_connection->field_connections);

                if (isset($smtp_connection->ignore_fields[$key])) {
                    continue;
                }

                if (isset($row_data[1])) {
                    if (isset($smtp_connection->printer_fields[$key])) {
                    } else {
                        $job_details_data[$key] = trim($row_data[1]);
                    }
                }
            }


            if (isset($job_details_data['serial_number']) && isset($job_details_data['model_name'])) {
                $existing_printers = Printer::withTrashed()->where('model_name', $job_details_data['model_name'])->where('serial_number', $job_details_data['serial_number'])->get();
                if ($existing_printers->count() == 0) {

                    if ($job_details_data['equiment_id'] != '') {
                        $new_printer = new Printer();
                        $new_printer->serial_number =  $job_details_data['serial_number'];
                        $new_printer->model_name =  $job_details_data['model_name'];
                        $new_printer->model =  $job_details_data['model_name'];
                        $new_printer->equipment_id = $job_details_data['equiment_id'];
                        $new_printer->smtp_active = 1;
                        $new_printer->smtp_status = 1;
                        $new_printer->smtp_sync_date = $message->getDate()->toDate()->format('Y-m-d h:i:s');
                        $new_printer->smtp_error = '';
                        try {
                            $new_printer->save();
                        } catch (\Throwable $th) {
                            dd($th);
                        }

                        $new_printer->reception()->create([
                            'name'              => $reception_name,
                            'email'             => $reception_email,
                        ]);
                    }
                } else {
                   
                    if ($existing_printers->count() !=  0) {
                        foreach ($existing_printers as $p) {
                            if ($p->trashed()) {
                                $p->restore();
                            } else {
                                $p->equipment_id =  $job_details_data['equiment_id'];
                                $p->model =  $p->model ?? $job_details_data['model_name'];

                                if (!$p->reception) {
                                    $p->reception()->create([
                                        'name'              => $reception_name,
                                        'email'             => $reception_email
                                    ]);
                                } else {
                                    $p->reception->name            = $reception_name;
                                    $p->reception->email            = $reception_email;
                                    $p->reception->save();
                                }

                                try {
                                    $p->save();
                                } catch (\Throwable $th) {
                                     dd($th);
                                }
                            }
                        }
                    }
                }
            } else {
                continue;
            }
        }

        $printers = Printer::whereNotNull('customer_id')->get();

        if ($conneciton_details->connection_status) {
            foreach ($printers as $printer) {

                $folder =  $smtp_connection->client->getFolder('INBOX');
                $sinceDateTime = date('Y-m-d h:i:s', strtotime($printer->smtp_sync_date));
                $query = $folder->query()
                    ->setFetchOrder("asc")
                    ->subject($printer->model_name)
                    ->since($sinceDateTime)
                    // ->unseen()
                    ->limit(round(1500 / count($printers)));
                // ->limit(10);
                /*->limit(20);*/

                // Printer job delete start
                $twoMonthsAgo = now()->subMonths(2);
                $totalJobs = PrinterJob::where('printer_id', $printer->id)->count();
                
                if ($totalJobs >= 1000) {
                    $thousandthNewestJob = PrinterJob::where('printer_id', $printer->id)
                        ->orderBy('created_at', 'desc')
                        ->orderBy('id', 'desc')
                        ->limit(1000)
                        ->pluck('id');
                     
                     if ($thousandthNewestJob) {
                        PrinterJob::where('printer_id', $printer->id)
                        ->where('created_at', '<', $twoMonthsAgo)
                        ->whereNotIn('id', $thousandthNewestJob)
                        ->delete();
                     }    

                }
                // Printer job delete end


                $messages =  $query->get();

                // $query->markAsRead();
                foreach ($messages as $message) {

                    $message_id = $message->get('message_id');
                    $job = PrinterJob::where('mail_id', $message_id)->count();
                    if ($job) {
                        continue;
                    }

                    $body_text = $message->getTextBody();
                    $array_of_job = (explode("\n", $body_text));

                    $job_details_data = [];
                    $prefix = '';

                    $events = [];
                    $currentDate = "";
                    $low_toner = 0;
                    $send_mail_to_admin = 0;

                    $job_error = [];
                    foreach ($array_of_job as $job_details) {

                        if (trim($job_details) == '-------------------') {
                            break;
                        }
                        $line = trim($job_details);
                        if (preg_match('/^<.*>$/', $line)) {
                            $currentDate = $line;
                            $events[$currentDate] = [];
                            continue;
                        } elseif (!empty($line) && $currentDate != '') {
                            if (!isset($events[$currentDate])) {
                                $events[$currentDate] = [];
                            }

                            $events[$currentDate][] = $line;
                            $line_data = explode(':', $line);
                            if (trim($line_data[0]) == 'black') {
                                $old_toner_pr = $printer->toner_pr;
                                $printer->toner_type = $line_data[0];
                                $toner =  trim($line_data[1], '%, ');
                                $printer->toner_pr = $toner;
                                if ($old_toner_pr <= 10 && $toner >= 85) {
                                    if ($printer->toner_stock != null) {
                                        $old_toner_stock = $printer->toner_stock;
                                        $old_toner_stock--;
                                        $printer->toner_stock = $old_toner_stock;
                                    }
                                }
                            }
                            if ($this->admin_settings['is_active'] == 1 && $this->admin_settings['toner_level'] > 0) {
                                if (trim($line_data[0]) == 'black') {
                                    $toner =  trim($line_data[1], '%, ');
                                    if ($toner <= $this->admin_settings['toner_level']) {
                                        $send_mail_to_admin = 1;
                                    }
                                }
                            }

                            // if (trim($line) == '[ ] Low Toner') {
                            //     $low_toner = 0;
                            //     $printer->toner_status = 0;
                            // }

                            if ($printer->toner_pr <= $this->admin_settings['toner_level']) {
                                $printer->toner_status = 1;
                            } else {
                                $printer->toner_status = 0;
                            }

                            /*if (trim($line) == '[*] Low Toner') {
                                $printer->toner_status = 1;
                            }*/
                            $error_types = ['[ ] Low Toner', '[ ] Add Toner', '[ ] Paper Jam', '[ ] Add Paper', '[ ] Cover Open', '[ ] All Other Errors', '[ ] Near Full Waste Toner', '[*] Low Toner', '[*] Add Toner', '[*] Paper Jam', '[*] Add Paper', '[*] Cover Open', '[*] All Other Errors', '[*] Near Full Waste Toner'];
                            if (in_array(trim($line), $error_types)) {
                                $job_error[] = trim($line);
                            }
                            continue;
                        }


                        $row_data = explode(':', $job_details);

                        if (trim($row_data[0]) == 'Printed Pages') {
                            $prefix = 'Printed ';
                        }

                        if (trim($row_data[0]) == 'Scanned Pages') {
                            $prefix = 'Scanned ';
                        }

                        if (trim($row_data[0]) == 'Counters by Paper Size') {
                            $prefix = 'Counters ';
                        }

                        if (trim($row_data[0]) == 'Counters by Duplex') {
                            $prefix = 'Counters D ';
                        }

                        if (trim($row_data[0]) == 'Counters by Combine') {
                            $prefix = 'Counters C ';
                        }

                        if (trim($row_data[0]) == 'none') {
                            $prefix = 'none ';
                        }

                        $key = array_search($prefix . trim($row_data[0]), $smtp_connection->field_connections);

                        if (isset($smtp_connection->ignore_fields[$key])) {
                            continue;
                        }

                        if (isset($row_data[1])) {
                            if (isset($smtp_connection->printer_fields[$key])) {
                            } else {
                                $job_details_data[$key] = trim($row_data[1]);
                            }
                        }
                    }

                    $detected_error = null;
                    if (!empty($job_error)) {
                        $lastElementError = end($job_error);
                        if (strpos($lastElementError, "[*]") !== false) {
                            $detected_error = $lastElementError;
                        }
                    }

                    if ($printer->serial_number != $job_details_data['serial_number']) {
                        continue;
                    }

                    $job_details_data['printer_id'] = $printer->id;
                    $job_details_data['mail_date'] = $message->getDate()->toDate()->format('Y-m-d h:i:s');
                    $job_details_data['mail_id'] = $message_id;
                    $new_printer_job = new PrinterJob($job_details_data);
                    $new_printer_job->save();

                    $id = tenancy()->tenant->id;
                    $printer_id = $printer->id;
                    $toner_level =  TonerLevelMonitoring::on('mysql')->where('tenant_id',  $id)->where('printer_instance_id', $printer_id)->first();

                    $alert_threshold =  AlertThreshold::on('mysql')->where('tenant_id',  $id)->where('printer_instance_id', $printer_id)->first();
                    if($alert_threshold){
                           if($printer->toner_pr <= $alert_threshold->threshold){
                                if($printer->toner_inks_id!=''){
                                    $SupplierTonerPrice = SupplierTonerPrice::on('mysql')->where('toner_inks_id', $printer->toner_inks_id)->orderBy('price', 'asc')->first();
                                    if($SupplierTonerPrice){
                                        $existingOrder = Order::on('mysql')
                                        ->where('printer_instance_id', $printer_id)
                                        ->where('toner_ink_id', $printer->toner_inks_id)
                                        ->where('status', 'Pending')
                                        ->first();
                                        if (!$existingOrder) {
                                            $order = new Order();
                                            $order->setConnection('mysql');
                                            $order->printer_instance_id = $printer_id;
                                            $order->tenant_id = $id;
                                            $order->toner_ink_id = $printer->toner_inks_id;
                                            $order->quantity = 1;
                                            $order->total_price = $SupplierTonerPrice->price;
                                            $order->supplier_id = $SupplierTonerPrice->supplier_id;
                                            $order->status = 'Pending';
                                            $order->auto_ordered = 1;
                                            $order->save();

                                            // Send notification email after new order is created
                                            try {
                                                $adminEmail = $this->admin_settings['notification_email'] ?? env('MAIL_FROM_ADDRESS');
                                                if ($adminEmail) {
                                                    Mail::to($adminEmail)->send(new OrderPlaced($order));
                                                }
                                            } catch (\Throwable $e) {
                                               
                                            }
                                        }
                                    }
                                }
                                
                                
                           } 
                    }

                    
                    try {
                        // Update or create toner level snapshot for this printer
                        if (!$toner_level) {
                            $toner_level = new TonerLevelMonitoring();
                            $toner_level->setConnection('mysql');
                            $toner_level->printer_instance_id = $printer_id;
                            $toner_level->toner_ink_id        = $printer->toner_inks_id;
                            $toner_level->color               = '';
                            $toner_level->current_level       = $printer->toner_pr;
                            $toner_level->tenant_id           = $id;
                            $toner_level->save();
                        } else {
                            $toner_level->toner_ink_id        = $printer->toner_inks_id;
                            $toner_level->current_level       = $printer->toner_pr;
                            $toner_level->save();
                        }
                    } catch (\Throwable $th) {
                        dd($th);
                    }

                    $printer_new_fields = [];
                    $printer_new_fields['toner_discreptions'] = $printer->toner_discreptions;
                    $printer_new_fields['make'] = $printer->make;
                    $printer_new_fields['model'] = $printer->model;
                    $printer_new_fields['address'] = $printer->address;
                    $printer_new_fields['city'] = $printer->city;
                    $printer_new_fields['zip'] = $printer->zip;
                    $printer_new_fields['state'] = $printer->state;
                    $printer_new_fields['country'] = $printer->country;


                    if ($send_mail_to_admin) {
                        Mail::to($this->admin_settings['notification_email'])->send(new LowTonerAdminEmail([
                            'printer'  => $new_printer_job,
                            'printer_new_fields'  => $printer_new_fields,
                            'toner' => $toner
                        ]));
                    }
                    $printer->smtp_sync_date = $message->getDate()->toDate()->format('Y-m-d h:i:s');
                    $printer->detected_error = $detected_error;
                    $printer->save();
                }
            }
        }
        echo "sync done";
    }
}