<?php
 namespace App\Utils\EmailBox; class Imap extends GeneralAbstract { protected \PhpImap\Mailbox $mailbox; public function loadAccountCredentialsFromConfigs(string $accountName) :void { $CFG = \Engine\Loader_Cfg::getInstance()->getGlobal(); if (!key_exists($accountName, $CFG['loadEmailBookings']['accountsList'])) { throw new Exception("Invalid account name `{$accountName}` to load IMAP credentials."); } $accountConfigs = $CFG['loadEmailBookings']['accountsList'][$accountName]; if (!$accountConfigs['active']) { throw new Exception("IMAP account name `{$accountName}` is disabled."); } $this->username = $accountConfigs['username']; $this->password = $accountConfigs['password']; } protected function getConnectionPath() :string { $path = '{' . $this->domain; if ($this->port) { $path .= ":" . $this->port; } $path .= "/imap/ssl}" . $this->dir; return $path; } public function connect() :void { if (!$this->username or !$this->password) { throw new Exception('The credentials (username/password) were not set when trying to connect using IMAP.'); } if (isset($this->mailbox)) { throw new Exception('Cannot call ' . __METHOD__ . ' more than once.'); } $CFG = \Engine\Loader_Cfg::getInstance()->getGlobal(); $tempDir = APP_REAL_PATH . $CFG['paths']['temporary']. '/emailBox'; if (!\Engine\Dir::check($tempDir)) { \Engine\Dir::create($tempDir); } $this->mailbox = new \PhpImap\Mailbox( $this->getConnectionPath(), $this->username, $this->password, $tempDir, $this->serverEncoding, true, false ); } public function disconnect() :void { if (!isset($this->mailbox)) { throw new Exception('Cannot call ' . __METHOD__ . ' as the connection was not executed or successful.'); } $this->mailbox->disconnect(); } public function search(string $searchString) :array { try { return $this->mailbox->searchMailbox($searchString); } catch(\PhpImap\Exceptions\ConnectionException $ex) { throw new Exception( 'IMAP connection failed: ' . implode(', ', $ex->getErrors('all')) ); } } public function getMail(string $idMail, bool $markAsSeen) :\PhpImap\IncomingMail { return $this->mailbox->getMail($idMail, $markAsSeen); } } 