gestione gare pubbliche
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 

282 righe
10 KiB

<?php
namespace App\Jobs\Communications;
use Exception;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Webklex\PHPIMAP\Header;
use App\Models\Main\Messaggi;
use Illuminate\Bus\Queueable;
use Web64\Colors\Facades\Colors;
use Illuminate\Support\Collection;
use Webklex\PHPIMAP\ClientManager;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Webklex\PHPIMAP\Support\MessageCollection;
class ProcessDownloadDeliveryReceipts implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 5;
/**
* The maximum number of unhandled exceptions to allow before failing.
*
* @var int
*/
public $maxExceptions = 3;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 3600;
/**
* Casella email
*
* array[codice_pec] int
* array[codice_ente] int
* array[pec] string
* array[password] string
* array[imap] string
* array[port] int
* array[ssl] int
*
* @var Array
*
*/
public $mailbox = [];
/**
* Messaggi da sincronizzare
*
* array[codice_comunicazione] int
* array[identificativo] int
* array[destinatario] string
*
* @var Array
*/
public $messages = [];
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Array $mailbox, Array $messages)
{
$this->mailbox = $mailbox;
$this->messages = $messages;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$limit = ini_get('memory_limit');
ini_set('memory_limit', 1024 * 2 . "M");
try {
$found = [];
$timestamp = Carbon::now()->format('Y-m-d H:i:s');
Colors::italic()->white("{$timestamp} PROCESSING {$this->mailbox["email"]} @ {$this->mailbox["imap"]}:{$this->mailbox["port"]}");
$manager = new ClientManager(config('imap'));
$client = $manager->make([
'host' => $this->mailbox["imap"],
'port' => $this->mailbox["port"],
'protocol' => 'imap',
'encryption' => 'ssl',
'validate_cert' => false,
'username' => $this->mailbox["email"],
'password' => $this->mailbox["password"],
"timeout" => 30
]);
$client->connect();
if(! $client->isConnected()) { throw new Exception("AUTHENTICATIONFAILED", 1); }
$emails = [];
$folders = [];
$timestamp = min(array_column($this->messages, 'timestamp'));
foreach ($client->getFolders() as $j => $folder) {
Colors::italic()->light_yellow("{$timestamp} GETTING MAIL FROM [{$folder->path}] SINCE " . \date('Y-m-d', strtotime($timestamp)));
$folders[$j] = $folder->path;
$client->openFolder($folder->path);
$uids = $client->getConnection()->search(['SINCE "' . \date('d-M-Y', strtotime($timestamp)) . '" HEADER "X-Ricevuta" ""'], \Webklex\PHPIMAP\IMAP::ST_UID);
if(! empty($uids)) {
$emails[$j] = $client->getConnection()->headers($uids, "RFC822", \Webklex\PHPIMAP\IMAP::ST_UID);
}
}
if(empty($emails)) { throw new Exception("NOXRICEVUTAFOUND", 2); }
foreach ($this->messages as $message) {
$found[$message["codice_messaggio"]] = false;
$record = Messaggi::where('codice', $message["codice_messaggio"])->first();
if(! empty($record)) {
$record->sync_attempts += 1;
$record->save();
foreach ($emails as $j => $headers) {
foreach ($headers as $uid => $header) {
if (preg_match("/X-Riferimento-Message-ID:\s*(<[^>]+>)/i", $header, $matchesMessageID)) {
$identifier = $matchesMessageID[1];
if(! empty($identifier) && $identifier == $message["identifier"]) {
if (preg_match("/X-Ricevuta:\s*(avvenuta-consegna|accettazione|error-consegna)/i", $header, $matchesXRicevuta)) {
$type = trim(strtolower($matchesXRicevuta[1]));
$filename = \strtoupper(Str::random(16));
$timestamp = Carbon::now()->format('Y-m-d H:i:s');
switch ($type) {
case 'accettazione':
Colors::italic()->light_magenta("{$timestamp} MESSAGE ID {$record["codice"]} - FOUND: RICEVUTA DI ACCETTAZIONE");
$filename = "ACCETTAZIONE-{$filename}";
$record->accettazione = 'S';
break;
case 'errore-consegna':
Colors::italic()->light_magenta("{$timestamp} MESSAGE ID {$record["codice"]} - FOUND: MANCATA CONSEGNA");
$filename = "ERRORE-CONSEGNA-{$filename}";
$record->mancata_consegna = 'S';
break;
case 'avvenuta-consegna':
Colors::italic()->light_magenta("{$timestamp} MESSAGE ID {$record["codice"]} - FOUND: RICEVUTA DI CONSEGNA");
$filename = "AVVENUTA-CONSEGNA-{$filename}";
$record->consegna = 'S';
break;
default:
Colors::italic()->light_red("{$timestamp} FOUND UNKNOWN HEADER: {$type}");
break;
}
$record->save();
$path = base_path("../media/{$this->mailbox["codice_ente"]}/ricevute/{$message["codice_comunicazione"]}/{$message["codice_messaggio"]}");
if(! \is_dir($path)) { \mkdir($path, 0755, true); }
$client->openFolder($folders[$j]);
$content = $client->getConnection()->content([$uid], "RFC822", \Webklex\PHPIMAP\IMAP::ST_UID);
\file_put_contents("{$path}/{$filename}.eml", $header . PHP_EOL . $content[$uid]);
$record->refresh();
if($record->consegna == "S" && $record->accettazione = "S") {
$found[$message["codice_messaggio"]] = true;
break 2;
}
}
}
}
}
}
}
if(! $found[$message["codice_messaggio"]]) {
$timestamp = Carbon::now()->format('Y-m-d H:i:s');
Colors::italic()->bg_light_red("{$timestamp} MESSAGE ID {$record["codice"]} - RECEIPTS NOT FOUND!");
}
}
} catch (\Exception $e) {
if(isset($client->getConnection()->stream)) {
fclose($client->getConnection()->stream);
$client->getConnection()->stream = null;
}
$error = "Error processing download delivery receipts job while processing {$this->mailbox["email"]} @ {$this->mailbox["imap"]}:{$this->mailbox["port"]}. " . PHP_EOL .
"\tError:" . $e->getMessage() . PHP_EOL .
"\tLine: " . $e->getLine() . PHP_EOL .
"\tFile: " . $e->getFile() . PHP_EOL;
if(! empty($e->getPrevious())) {
$e2 = $e->getPrevious();
$error .= "\t\tPrevious: " . $e2->getMessage() . PHP_EOL .
"\t\tLine: " . $e2->getLine() . PHP_EOL .
"\t\tFile: " . $e2->getFile() . PHP_EOL;
if(! empty($e2->getPrevious())) {
$e3 = $e2->getPrevious();
$error .= "\t\t\tPrevious: " . $e3->getPrevious()->getMessage() . PHP_EOL .
"\t\t\tLine: " . $e3->getLine() . PHP_EOL .
"\t\t\tFile: " . $e3->getFile() . PHP_EOL;
}
}
Log::emergency($error);
Colors::italic()->light_magenta("{$timestamp} {$error}");
}
ini_set('memory_limit', $limit);
}
/**
* Handle a job failure.
*
* @param \Throwable $exception
* @return void
*/
public function failed(\Throwable $exception)
{
Log::emergency($exception);
Log::emergency("Error processing download delivery receipts. Error:" . $exception->getMessage() . " @ line " . $exception->getLine() . " in " . $exception->getFile());
$timestamp = Carbon::now()->format('Y-m-d H:i:s');
Colors::italic()->light_magenta("{$timestamp} Error processing download delivery receipts job while processing {$this->mailbox["email"]} @ {$this->mailbox["imap"]}:{$this->mailbox["port"]}. Error:" . $exception->getMessage() . " @ line " . $exception->getLine() . " in " . $exception->getFile());
}
}