Client.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. <?php
  2. /*
  3. * File: Client.php
  4. * Category: -
  5. * Author: M. Goldenbaum
  6. * Created: 19.01.17 22:21
  7. * Updated: -
  8. *
  9. * Description:
  10. * -
  11. */
  12. namespace Webklex\PHPIMAP;
  13. use ErrorException;
  14. use Exception;
  15. use Webklex\PHPIMAP\Connection\Protocols\ImapProtocol;
  16. use Webklex\PHPIMAP\Connection\Protocols\LegacyProtocol;
  17. use Webklex\PHPIMAP\Connection\Protocols\Protocol;
  18. use Webklex\PHPIMAP\Connection\Protocols\ProtocolInterface;
  19. use Webklex\PHPIMAP\Exceptions\AuthFailedException;
  20. use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
  21. use Webklex\PHPIMAP\Exceptions\FolderFetchingException;
  22. use Webklex\PHPIMAP\Exceptions\MaskNotFoundException;
  23. use Webklex\PHPIMAP\Exceptions\ProtocolNotSupportedException;
  24. use Webklex\PHPIMAP\Support\FolderCollection;
  25. use Webklex\PHPIMAP\Support\Masks\AttachmentMask;
  26. use Webklex\PHPIMAP\Support\Masks\MessageMask;
  27. use Webklex\PHPIMAP\Traits\HasEvents;
  28. /**
  29. * Class Client
  30. *
  31. * @package Webklex\PHPIMAP
  32. */
  33. class Client {
  34. use HasEvents;
  35. /**
  36. * Connection resource
  37. *
  38. * @var boolean|Protocol|ProtocolInterface
  39. */
  40. public $connection = false;
  41. /**
  42. * Server hostname.
  43. *
  44. * @var string
  45. */
  46. public $host;
  47. /**
  48. * Server port.
  49. *
  50. * @var int
  51. */
  52. public $port;
  53. /**
  54. * Service protocol.
  55. *
  56. * @var int
  57. */
  58. public $protocol;
  59. /**
  60. * Server encryption.
  61. * Supported: none, ssl, tls, or notls.
  62. *
  63. * @var string
  64. */
  65. public $encryption;
  66. /**
  67. * If server has to validate cert.
  68. *
  69. * @var bool
  70. */
  71. public $validate_cert = true;
  72. /**
  73. * Proxy settings
  74. * @var array
  75. */
  76. protected $proxy = [
  77. 'socket' => null,
  78. 'request_fulluri' => false,
  79. 'username' => null,
  80. 'password' => null,
  81. ];
  82. /**
  83. * Connection timeout
  84. * @var int $timeout
  85. */
  86. public $timeout;
  87. /**
  88. * Account username/
  89. *
  90. * @var mixed
  91. */
  92. public $username;
  93. /**
  94. * Account password.
  95. *
  96. * @var string
  97. */
  98. public $password;
  99. /**
  100. * Account authentication method.
  101. *
  102. * @var string
  103. */
  104. public $authentication;
  105. /**
  106. * Active folder path.
  107. *
  108. * @var string
  109. */
  110. protected $active_folder = null;
  111. /**
  112. * Default message mask
  113. *
  114. * @var string $default_message_mask
  115. */
  116. protected $default_message_mask = MessageMask::class;
  117. /**
  118. * Default attachment mask
  119. *
  120. * @var string $default_attachment_mask
  121. */
  122. protected $default_attachment_mask = AttachmentMask::class;
  123. /**
  124. * Used default account values
  125. *
  126. * @var array $default_account_config
  127. */
  128. protected $default_account_config = [
  129. 'host' => 'localhost',
  130. 'port' => 993,
  131. 'protocol' => 'imap',
  132. 'encryption' => 'ssl',
  133. 'validate_cert' => true,
  134. 'username' => '',
  135. 'password' => '',
  136. 'authentication' => null,
  137. 'proxy' => [
  138. 'socket' => null,
  139. 'request_fulluri' => false,
  140. 'username' => null,
  141. 'password' => null,
  142. ],
  143. "timeout" => 30
  144. ];
  145. /**
  146. * Client constructor.
  147. * @param array $config
  148. *
  149. * @throws MaskNotFoundException
  150. */
  151. public function __construct($config = []) {
  152. $this->setConfig($config);
  153. $this->setMaskFromConfig($config);
  154. $this->setEventsFromConfig($config);
  155. }
  156. /**
  157. * Client destructor
  158. */
  159. public function __destruct() {
  160. $this->disconnect();
  161. }
  162. /**
  163. * Set the Client configuration
  164. * @param array $config
  165. *
  166. * @return self
  167. */
  168. public function setConfig(array $config) {
  169. $default_account = ClientManager::get('default');
  170. $default_config = ClientManager::get("accounts.$default_account");
  171. foreach ($this->default_account_config as $key => $value) {
  172. $this->setAccountConfig($key, $config, $default_config);
  173. }
  174. return $this;
  175. }
  176. /**
  177. * Set a specific account config
  178. * @param string $key
  179. * @param array $config
  180. * @param array $default_config
  181. */
  182. private function setAccountConfig($key, $config, $default_config){
  183. $value = $this->default_account_config[$key];
  184. if(isset($config[$key])) {
  185. $value = $config[$key];
  186. }elseif(isset($default_config[$key])) {
  187. $value = $default_config[$key];
  188. }
  189. $this->$key = $value;
  190. }
  191. /**
  192. * Look for a possible events in any available config
  193. * @param $config
  194. */
  195. protected function setEventsFromConfig($config) {
  196. $this->events = ClientManager::get("events");
  197. if(isset($config['events'])){
  198. foreach($config['events'] as $section => $events) {
  199. $this->events[$section] = array_merge($this->events[$section], $events);
  200. }
  201. }
  202. }
  203. /**
  204. * Look for a possible mask in any available config
  205. * @param $config
  206. *
  207. * @throws MaskNotFoundException
  208. */
  209. protected function setMaskFromConfig($config) {
  210. $default_config = ClientManager::get("masks");
  211. if(isset($config['masks'])){
  212. if(isset($config['masks']['message'])) {
  213. if(class_exists($config['masks']['message'])) {
  214. $this->default_message_mask = $config['masks']['message'];
  215. }else{
  216. throw new MaskNotFoundException("Unknown mask provided: ".$config['masks']['message']);
  217. }
  218. }else{
  219. if(class_exists($default_config['message'])) {
  220. $this->default_message_mask = $default_config['message'];
  221. }else{
  222. throw new MaskNotFoundException("Unknown mask provided: ".$default_config['message']);
  223. }
  224. }
  225. if(isset($config['masks']['attachment'])) {
  226. if(class_exists($config['masks']['attachment'])) {
  227. $this->default_attachment_mask = $config['masks']['attachment'];
  228. }else{
  229. throw new MaskNotFoundException("Unknown mask provided: ".$config['masks']['attachment']);
  230. }
  231. }else{
  232. if(class_exists($default_config['attachment'])) {
  233. $this->default_attachment_mask = $default_config['attachment'];
  234. }else{
  235. throw new MaskNotFoundException("Unknown mask provided: ".$default_config['attachment']);
  236. }
  237. }
  238. }else{
  239. if(class_exists($default_config['message'])) {
  240. $this->default_message_mask = $default_config['message'];
  241. }else{
  242. throw new MaskNotFoundException("Unknown mask provided: ".$default_config['message']);
  243. }
  244. if(class_exists($default_config['attachment'])) {
  245. $this->default_attachment_mask = $default_config['attachment'];
  246. }else{
  247. throw new MaskNotFoundException("Unknown mask provided: ".$default_config['attachment']);
  248. }
  249. }
  250. }
  251. /**
  252. * Get the current imap resource
  253. *
  254. * @return bool|Protocol|ProtocolInterface
  255. * @throws ConnectionFailedException
  256. */
  257. public function getConnection() {
  258. $this->checkConnection();
  259. return $this->connection;
  260. }
  261. /**
  262. * Determine if connection was established.
  263. *
  264. * @return bool
  265. */
  266. public function isConnected() {
  267. return $this->connection ? $this->connection->connected() : false;
  268. }
  269. /**
  270. * Determine if connection was established and connect if not.
  271. *
  272. * @throws ConnectionFailedException
  273. */
  274. public function checkConnection() {
  275. if (!$this->isConnected()) {
  276. $this->connect();
  277. }
  278. }
  279. /**
  280. * Force a reconnect
  281. *
  282. * @throws ConnectionFailedException
  283. */
  284. public function reconnect() {
  285. if ($this->isConnected()) {
  286. $this->disconnect();
  287. }
  288. $this->connect();
  289. }
  290. /**
  291. * Connect to server.
  292. *
  293. * @return $this
  294. * @throws ConnectionFailedException
  295. */
  296. public function connect() {
  297. $this->disconnect();
  298. $protocol = strtolower($this->protocol);
  299. if (in_array($protocol, ['imap', 'imap4', 'imap4rev1'])) {
  300. $this->connection = new ImapProtocol($this->validate_cert, $this->encryption);
  301. $this->connection->setConnectionTimeout($this->timeout);
  302. $this->connection->setProxy($this->proxy);
  303. }else{
  304. if (extension_loaded('imap') === false) {
  305. throw new ConnectionFailedException("connection setup failed - no imap function", 0, new ProtocolNotSupportedException($protocol." is an unsupported protocol"));
  306. }
  307. $this->connection = new LegacyProtocol($this->validate_cert, $this->encryption);
  308. if (strpos($protocol, "legacy-") === 0) {
  309. $protocol = substr($protocol, 7);
  310. }
  311. $this->connection->setProtocol($protocol);
  312. }
  313. try {
  314. $this->connection->connect($this->host, $this->port);
  315. } catch (ErrorException $e) {
  316. throw new ConnectionFailedException("connection setup failed - connect exception", 0, $e);
  317. } catch (Exceptions\RuntimeException $e) {
  318. throw new ConnectionFailedException("connection setup failed - run exception", 0, $e);
  319. }
  320. $this->authenticate();
  321. return $this;
  322. }
  323. /**
  324. * Authenticate the current session
  325. *
  326. * @throws ConnectionFailedException
  327. */
  328. protected function authenticate() {
  329. try {
  330. if ($this->authentication == "oauth") {
  331. if (!$this->connection->authenticate($this->username, $this->password)) {
  332. throw new AuthFailedException();
  333. }
  334. } elseif (!$this->connection->login($this->username, $this->password)) {
  335. throw new AuthFailedException();
  336. }
  337. } catch (AuthFailedException $e) {
  338. throw new ConnectionFailedException("connection setup failed - authenticate", 0, $e);
  339. }
  340. }
  341. /**
  342. * Disconnect from server.
  343. *
  344. * @return $this
  345. */
  346. public function disconnect() {
  347. if ($this->isConnected() && $this->connection !== false) {
  348. $this->connection->logout();
  349. }
  350. $this->active_folder = null;
  351. return $this;
  352. }
  353. /**
  354. * Get a folder instance by a folder name
  355. * @param string $folder_name
  356. * @param string|bool|null $delimiter
  357. *
  358. * @return mixed
  359. * @throws ConnectionFailedException
  360. * @throws FolderFetchingException
  361. * @throws Exceptions\RuntimeException
  362. */
  363. public function getFolder($folder_name, $delimiter = null) {
  364. if ($delimiter !== false && $delimiter !== null) {
  365. return $this->getFolderByPath($folder_name);
  366. }
  367. // Set delimiter to false to force selection via getFolderByName (maybe useful for uncommon folder names)
  368. $delimiter = is_null($delimiter) ? ClientManager::get('options.delimiter', "/") : $delimiter;
  369. if (strpos($folder_name, (string)$delimiter) !== false) {
  370. return $this->getFolderByPath($folder_name);
  371. }
  372. return $this->getFolderByName($folder_name);
  373. }
  374. /**
  375. * Get a folder instance by a folder name
  376. * @param $folder_name
  377. *
  378. * @return mixed
  379. * @throws ConnectionFailedException
  380. * @throws FolderFetchingException
  381. * @throws Exceptions\RuntimeException
  382. */
  383. public function getFolderByName($folder_name) {
  384. return $this->getFolders(false)->where("name", $folder_name)->first();
  385. }
  386. /**
  387. * Get a folder instance by a folder path
  388. * @param $folder_path
  389. *
  390. * @return mixed
  391. * @throws ConnectionFailedException
  392. * @throws FolderFetchingException
  393. * @throws Exceptions\RuntimeException
  394. */
  395. public function getFolderByPath($folder_path) {
  396. return $this->getFolders(false)->where("path", $folder_path)->first();
  397. }
  398. /**
  399. * Get folders list.
  400. * If hierarchical order is set to true, it will make a tree of folders, otherwise it will return flat array.
  401. *
  402. * @param boolean $hierarchical
  403. * @param string|null $parent_folder
  404. *
  405. * @return FolderCollection
  406. * @throws ConnectionFailedException
  407. * @throws FolderFetchingException
  408. * @throws Exceptions\RuntimeException
  409. */
  410. public function getFolders($hierarchical = true, $parent_folder = null) {
  411. $this->checkConnection();
  412. $folders = FolderCollection::make([]);
  413. $pattern = $parent_folder.($hierarchical ? '%' : '*');
  414. $items = $this->connection->folders('', $pattern);
  415. if(is_array($items)){
  416. foreach ($items as $folder_name => $item) {
  417. $folder = new Folder($this, $folder_name, $item["delimiter"], $item["flags"]);
  418. if ($hierarchical && $folder->hasChildren()) {
  419. $pattern = $folder->full_name.$folder->delimiter.'%';
  420. $children = $this->getFolders(true, $pattern);
  421. $folder->setChildren($children);
  422. }
  423. $folders->push($folder);
  424. }
  425. return $folders;
  426. }else{
  427. throw new FolderFetchingException("failed to fetch any folders");
  428. }
  429. }
  430. /**
  431. * Open a given folder.
  432. * @param string $folder_path
  433. * @param boolean $force_select
  434. *
  435. * @return mixed
  436. * @throws ConnectionFailedException
  437. * @throws Exceptions\RuntimeException
  438. */
  439. public function openFolder($folder_path, $force_select = false) {
  440. if ($this->active_folder == $folder_path && $this->isConnected() && $force_select === false) {
  441. return true;
  442. }
  443. $this->checkConnection();
  444. $this->active_folder = $folder_path;
  445. return $this->connection->selectFolder($folder_path);
  446. }
  447. /**
  448. * Create a new Folder
  449. * @param string $folder
  450. * @param boolean $expunge
  451. *
  452. * @return bool
  453. * @throws ConnectionFailedException
  454. * @throws FolderFetchingException
  455. * @throws Exceptions\EventNotFoundException
  456. * @throws Exceptions\RuntimeException
  457. */
  458. public function createFolder($folder, $expunge = true) {
  459. $this->checkConnection();
  460. $status = $this->connection->createFolder($folder);
  461. if($expunge) $this->expunge();
  462. $folder = $this->getFolder($folder);
  463. if($status && $folder) {
  464. $event = $this->getEvent("folder", "new");
  465. $event::dispatch($folder);
  466. }
  467. return $folder;
  468. }
  469. /**
  470. * Check a given folder
  471. * @param $folder
  472. *
  473. * @return false|object
  474. * @throws ConnectionFailedException
  475. * @throws Exceptions\RuntimeException
  476. */
  477. public function checkFolder($folder) {
  478. $this->checkConnection();
  479. return $this->connection->examineFolder($folder);
  480. }
  481. /**
  482. * Get the current active folder
  483. *
  484. * @return string
  485. */
  486. public function getFolderPath(){
  487. return $this->active_folder;
  488. }
  489. /**
  490. * Retrieve the quota level settings, and usage statics per mailbox
  491. *
  492. * @return array
  493. * @throws ConnectionFailedException
  494. * @throws Exceptions\RuntimeException
  495. */
  496. public function getQuota() {
  497. $this->checkConnection();
  498. return $this->connection->getQuota($this->username);
  499. }
  500. /**
  501. * Retrieve the quota settings per user
  502. * @param string $quota_root
  503. *
  504. * @return array
  505. * @throws ConnectionFailedException
  506. */
  507. public function getQuotaRoot($quota_root = 'INBOX') {
  508. $this->checkConnection();
  509. return $this->connection->getQuotaRoot($quota_root);
  510. }
  511. /**
  512. * Delete all messages marked for deletion
  513. *
  514. * @return bool
  515. * @throws ConnectionFailedException
  516. * @throws Exceptions\RuntimeException
  517. */
  518. public function expunge() {
  519. $this->checkConnection();
  520. return $this->connection->expunge();
  521. }
  522. /**
  523. * Set the connection timeout
  524. * @param integer $timeout
  525. *
  526. * @return Protocol
  527. * @throws ConnectionFailedException
  528. */
  529. public function setTimeout($timeout) {
  530. $this->checkConnection();
  531. return $this->connection->setConnectionTimeout($timeout);
  532. }
  533. /**
  534. * Get the connection timeout
  535. *
  536. * @return int
  537. * @throws ConnectionFailedException
  538. */
  539. public function getTimeout(){
  540. $this->checkConnection();
  541. return $this->connection->getConnectionTimeout();
  542. }
  543. /**
  544. * Get the default message mask
  545. *
  546. * @return string
  547. */
  548. public function getDefaultMessageMask(){
  549. return $this->default_message_mask;
  550. }
  551. /**
  552. * Get the default events for a given section
  553. * @param $section
  554. *
  555. * @return array
  556. */
  557. public function getDefaultEvents($section){
  558. return $this->events[$section];
  559. }
  560. /**
  561. * Set the default message mask
  562. * @param $mask
  563. *
  564. * @return $this
  565. * @throws MaskNotFoundException
  566. */
  567. public function setDefaultMessageMask($mask) {
  568. if(class_exists($mask)) {
  569. $this->default_message_mask = $mask;
  570. return $this;
  571. }
  572. throw new MaskNotFoundException("Unknown mask provided: ".$mask);
  573. }
  574. /**
  575. * Get the default attachment mask
  576. *
  577. * @return string
  578. */
  579. public function getDefaultAttachmentMask(){
  580. return $this->default_attachment_mask;
  581. }
  582. /**
  583. * Set the default attachment mask
  584. * @param $mask
  585. *
  586. * @return $this
  587. * @throws MaskNotFoundException
  588. */
  589. public function setDefaultAttachmentMask($mask) {
  590. if(class_exists($mask)) {
  591. $this->default_attachment_mask = $mask;
  592. return $this;
  593. }
  594. throw new MaskNotFoundException("Unknown mask provided: ".$mask);
  595. }
  596. }