Query.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. <?php
  2. /*
  3. * File: Query.php
  4. * Category: -
  5. * Author: M. Goldenbaum
  6. * Created: 21.07.18 18:54
  7. * Updated: -
  8. *
  9. * Description:
  10. * -
  11. */
  12. namespace Webklex\PHPIMAP\Query;
  13. use Carbon\Carbon;
  14. use Exception;
  15. use Illuminate\Pagination\LengthAwarePaginator;
  16. use Illuminate\Support\Collection;
  17. use ReflectionException;
  18. use Webklex\PHPIMAP\Client;
  19. use Webklex\PHPIMAP\ClientManager;
  20. use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
  21. use Webklex\PHPIMAP\Exceptions\EventNotFoundException;
  22. use Webklex\PHPIMAP\Exceptions\GetMessagesFailedException;
  23. use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
  24. use Webklex\PHPIMAP\Exceptions\MessageContentFetchingException;
  25. use Webklex\PHPIMAP\Exceptions\MessageFlagException;
  26. use Webklex\PHPIMAP\Exceptions\MessageHeaderFetchingException;
  27. use Webklex\PHPIMAP\Exceptions\MessageNotFoundException;
  28. use Webklex\PHPIMAP\Exceptions\MessageSearchValidationException;
  29. use Webklex\PHPIMAP\Exceptions\RuntimeException;
  30. use Webklex\PHPIMAP\IMAP;
  31. use Webklex\PHPIMAP\Message;
  32. use Webklex\PHPIMAP\Support\MessageCollection;
  33. /**
  34. * Class Query
  35. *
  36. * @package Webklex\PHPIMAP\Query
  37. */
  38. class Query {
  39. /** @var Collection $query */
  40. protected $query;
  41. /** @var string $raw_query */
  42. protected $raw_query;
  43. /** @var string $charset */
  44. protected $charset;
  45. /** @var Client $client */
  46. protected $client;
  47. /** @var int $limit */
  48. protected $limit = null;
  49. /** @var int $page */
  50. protected $page = 1;
  51. /** @var int $fetch_options */
  52. protected $fetch_options = null;
  53. /** @var int $fetch_body */
  54. protected $fetch_body = true;
  55. /** @var int $fetch_flags */
  56. protected $fetch_flags = true;
  57. /** @var int $sequence */
  58. protected $sequence = IMAP::NIL;
  59. /** @var string $fetch_order */
  60. protected $fetch_order;
  61. /** @var string $date_format */
  62. protected $date_format;
  63. /** @var bool $soft_fail */
  64. protected $soft_fail = false;
  65. /** @var array $errors */
  66. protected $errors = [];
  67. /**
  68. * Query constructor.
  69. * @param Client $client
  70. * @param string $charset
  71. */
  72. public function __construct(Client $client, $charset = 'UTF-8') {
  73. $this->setClient($client);
  74. $this->sequence = ClientManager::get('options.sequence', IMAP::ST_MSGN);
  75. if (ClientManager::get('options.fetch') === IMAP::FT_PEEK) $this->leaveUnread();
  76. if (ClientManager::get('options.fetch_order') === 'desc') {
  77. $this->fetch_order = 'desc';
  78. } else {
  79. $this->fetch_order = 'asc';
  80. }
  81. $this->date_format = ClientManager::get('date_format', 'd M y');
  82. $this->soft_fail = ClientManager::get('options.soft_fail', false);
  83. $this->charset = $charset;
  84. $this->query = new Collection();
  85. $this->boot();
  86. }
  87. /**
  88. * Instance boot method for additional functionality
  89. */
  90. protected function boot() {
  91. }
  92. /**
  93. * Parse a given value
  94. * @param mixed $value
  95. *
  96. * @return string
  97. */
  98. protected function parse_value($value) {
  99. switch (true) {
  100. case $value instanceof Carbon:
  101. $value = $value->format($this->date_format);
  102. break;
  103. }
  104. return (string)$value;
  105. }
  106. /**
  107. * Check if a given date is a valid carbon object and if not try to convert it
  108. * @param string|Carbon $date
  109. *
  110. * @return Carbon
  111. * @throws MessageSearchValidationException
  112. */
  113. protected function parse_date($date) {
  114. if ($date instanceof Carbon) return $date;
  115. try {
  116. $date = Carbon::parse($date);
  117. } catch (Exception $e) {
  118. throw new MessageSearchValidationException();
  119. }
  120. return $date;
  121. }
  122. /**
  123. * Get the raw IMAP search query
  124. *
  125. * @return string
  126. */
  127. public function generate_query() {
  128. $query = '';
  129. $this->query->each(function($statement) use (&$query) {
  130. if (count($statement) == 1) {
  131. $query .= $statement[0];
  132. } else {
  133. if ($statement[1] === null) {
  134. $query .= $statement[0];
  135. } else {
  136. $query .= $statement[0] . ' "' . $statement[1] . '"';
  137. }
  138. }
  139. $query .= ' ';
  140. });
  141. $this->raw_query = trim($query);
  142. return $this->raw_query;
  143. }
  144. /**
  145. * Perform an imap search request
  146. *
  147. * @return Collection
  148. * @throws GetMessagesFailedException
  149. */
  150. protected function search() {
  151. $this->generate_query();
  152. try {
  153. $available_messages = $this->client->getConnection()->search([$this->getRawQuery()], $this->sequence == IMAP::ST_UID);
  154. return $available_messages !== false ? new Collection($available_messages) : new Collection();
  155. } catch (RuntimeException $e) {
  156. throw new GetMessagesFailedException("failed to fetch messages", 0, $e);
  157. } catch (ConnectionFailedException $e) {
  158. throw new GetMessagesFailedException("failed to fetch messages", 0, $e);
  159. }
  160. }
  161. /**
  162. * Count all available messages matching the current search criteria
  163. *
  164. * @return int
  165. * @throws GetMessagesFailedException
  166. */
  167. public function count() {
  168. return $this->search()->count();
  169. }
  170. /**
  171. * Fetch a given id collection
  172. * @param Collection $available_messages
  173. *
  174. * @return array
  175. * @throws ConnectionFailedException
  176. * @throws RuntimeException
  177. */
  178. protected function fetch($available_messages) {
  179. if ($this->fetch_order === 'desc') {
  180. $available_messages = $available_messages->reverse();
  181. }
  182. $uids = $available_messages->forPage($this->page, $this->limit)->toArray();
  183. $flags = $this->client->getConnection()->flags($uids, $this->sequence == IMAP::ST_UID);
  184. $headers = $this->client->getConnection()->headers($uids, "RFC822", $this->sequence == IMAP::ST_UID);
  185. $contents = [];
  186. if ($this->getFetchBody()) {
  187. $contents = $this->client->getConnection()->content($uids, "RFC822", $this->sequence == IMAP::ST_UID);
  188. }
  189. return [
  190. "uids" => $uids,
  191. "flags" => $flags,
  192. "headers" => $headers,
  193. "contents" => $contents,
  194. ];
  195. }
  196. /**
  197. * Make a new message from given raw components
  198. * @param integer $uid
  199. * @param integer $msglist
  200. * @param string $header
  201. * @param string $content
  202. * @param array $flags
  203. *
  204. * @return Message|null
  205. * @throws ConnectionFailedException
  206. * @throws EventNotFoundException
  207. * @throws GetMessagesFailedException
  208. * @throws ReflectionException
  209. */
  210. protected function make($uid, $msglist, $header, $content, $flags){
  211. try {
  212. return Message::make($uid, $msglist, $this->getClient(), $header, $content, $flags, $this->getFetchOptions(), $this->sequence);
  213. }catch (MessageNotFoundException $e) {
  214. $this->setError($uid, $e);
  215. }catch (RuntimeException $e) {
  216. $this->setError($uid, $e);
  217. }catch (MessageFlagException $e) {
  218. $this->setError($uid, $e);
  219. }catch (InvalidMessageDateException $e) {
  220. $this->setError($uid, $e);
  221. }catch (MessageContentFetchingException $e) {
  222. $this->setError($uid, $e);
  223. }
  224. $this->handleException($uid);
  225. return null;
  226. }
  227. /**
  228. * Get the message key for a given message
  229. * @param string $message_key
  230. * @param integer $msglist
  231. * @param Message $message
  232. *
  233. * @return string
  234. */
  235. protected function getMessageKey($message_key, $msglist, $message){
  236. switch ($message_key) {
  237. case 'number':
  238. $key = $message->getMessageNo();
  239. break;
  240. case 'list':
  241. $key = $msglist;
  242. break;
  243. case 'uid':
  244. $key = $message->getUid();
  245. break;
  246. default:
  247. $key = $message->getMessageId();
  248. break;
  249. }
  250. return (string)$key;
  251. }
  252. /**
  253. * Populate a given id collection and receive a fully fetched message collection
  254. * @param Collection $available_messages
  255. *
  256. * @return MessageCollection
  257. * @throws ConnectionFailedException
  258. * @throws EventNotFoundException
  259. * @throws GetMessagesFailedException
  260. * @throws ReflectionException
  261. * @throws RuntimeException
  262. */
  263. protected function populate($available_messages) {
  264. $messages = MessageCollection::make([]);
  265. $messages->total($available_messages->count());
  266. $message_key = ClientManager::get('options.message_key');
  267. $raw_messages = $this->fetch($available_messages);
  268. $msglist = 0;
  269. foreach ($raw_messages["headers"] as $uid => $header) {
  270. $content = isset($raw_messages["contents"][$uid]) ? $raw_messages["contents"][$uid] : "";
  271. $flag = isset($raw_messages["flags"][$uid]) ? $raw_messages["flags"][$uid] : [];
  272. $message = $this->make($uid, $msglist, $header, $content, $flag);
  273. if ($message !== null) {
  274. $key = $this->getMessageKey($message_key, $msglist, $message);
  275. $messages->put("$key", $message);
  276. }
  277. $msglist++;
  278. }
  279. return $messages;
  280. }
  281. /**
  282. * Fetch the current query and return all found messages
  283. *
  284. * @return MessageCollection
  285. * @throws GetMessagesFailedException
  286. */
  287. public function get() {
  288. $available_messages = $this->search();
  289. try {
  290. if ($available_messages->count() > 0) {
  291. return $this->populate($available_messages);
  292. }
  293. return MessageCollection::make([]);
  294. } catch (Exception $e) {
  295. throw new GetMessagesFailedException($e->getMessage(), 0, $e);
  296. }
  297. }
  298. /**
  299. * Fetch the current query as chunked requests
  300. * @param callable $callback
  301. * @param int $chunk_size
  302. * @param int $start_chunk
  303. *
  304. * @throws ConnectionFailedException
  305. * @throws EventNotFoundException
  306. * @throws GetMessagesFailedException
  307. * @throws ReflectionException
  308. * @throws RuntimeException
  309. */
  310. public function chunked($callback, $chunk_size = 10, $start_chunk = 1) {
  311. $available_messages = $this->search();
  312. if (($available_messages_count = $available_messages->count()) > 0) {
  313. $old_limit = $this->limit;
  314. $old_page = $this->page;
  315. $this->limit = $chunk_size;
  316. $this->page = $start_chunk;
  317. do {
  318. $messages = $this->populate($available_messages);
  319. $callback($messages, $this->page);
  320. $this->page++;
  321. } while ($this->limit * $this->page <= $available_messages_count);
  322. $this->limit = $old_limit;
  323. $this->page = $old_page;
  324. }
  325. }
  326. /**
  327. * Paginate the current query
  328. * @param int $per_page Results you which to receive per page
  329. * @param int|null $page The current page you are on (e.g. 0, 1, 2, ...) use `null` to enable auto mode
  330. * @param string $page_name The page name / uri parameter used for the generated links and the auto mode
  331. *
  332. * @return LengthAwarePaginator
  333. * @throws GetMessagesFailedException
  334. */
  335. public function paginate($per_page = 5, $page = null, $page_name = 'imap_page') {
  336. if (
  337. $page === null
  338. && isset($_GET[$page_name])
  339. && $_GET[$page_name] > 0
  340. ) {
  341. $this->page = intval($_GET[$page_name]);
  342. } elseif ($page > 0) {
  343. $this->page = $page;
  344. }
  345. $this->limit = $per_page;
  346. return $this->get()->paginate($per_page, $this->page, $page_name, true);
  347. }
  348. /**
  349. * Get a new Message instance
  350. * @param int $uid
  351. * @param int|null $msglist
  352. * @param int|null $sequence
  353. *
  354. * @return Message
  355. * @throws ConnectionFailedException
  356. * @throws RuntimeException
  357. * @throws InvalidMessageDateException
  358. * @throws MessageContentFetchingException
  359. * @throws MessageHeaderFetchingException
  360. * @throws EventNotFoundException
  361. * @throws MessageFlagException
  362. * @throws MessageNotFoundException
  363. */
  364. public function getMessage($uid, $msglist = null, $sequence = null) {
  365. return new Message($uid, $msglist, $this->getClient(), $this->getFetchOptions(), $this->getFetchBody(), $this->getFetchFlags(), $sequence ? $sequence : $this->sequence);
  366. }
  367. /**
  368. * Get a message by its message number
  369. * @param $msgn
  370. * @param int|null $msglist
  371. *
  372. * @return Message
  373. * @throws ConnectionFailedException
  374. * @throws InvalidMessageDateException
  375. * @throws MessageContentFetchingException
  376. * @throws MessageHeaderFetchingException
  377. * @throws RuntimeException
  378. * @throws EventNotFoundException
  379. * @throws MessageFlagException
  380. * @throws MessageNotFoundException
  381. */
  382. public function getMessageByMsgn($msgn, $msglist = null) {
  383. return $this->getMessage($msgn, $msglist, IMAP::ST_MSGN);
  384. }
  385. /**
  386. * Get a message by its uid
  387. * @param $uid
  388. *
  389. * @return Message
  390. * @throws ConnectionFailedException
  391. * @throws InvalidMessageDateException
  392. * @throws MessageContentFetchingException
  393. * @throws MessageHeaderFetchingException
  394. * @throws RuntimeException
  395. * @throws EventNotFoundException
  396. * @throws MessageFlagException
  397. * @throws MessageNotFoundException
  398. */
  399. public function getMessageByUid($uid) {
  400. return $this->getMessage($uid, null, IMAP::ST_UID);
  401. }
  402. /**
  403. * Don't mark messages as read when fetching
  404. *
  405. * @return $this
  406. */
  407. public function leaveUnread() {
  408. $this->setFetchOptions(IMAP::FT_PEEK);
  409. return $this;
  410. }
  411. /**
  412. * Mark all messages as read when fetching
  413. *
  414. * @return $this
  415. */
  416. public function markAsRead() {
  417. $this->setFetchOptions(IMAP::FT_UID);
  418. return $this;
  419. }
  420. /**
  421. * Set the sequence type
  422. * @param int $sequence
  423. *
  424. * @return $this
  425. */
  426. public function setSequence($sequence) {
  427. $this->sequence = $sequence != IMAP::ST_MSGN ? IMAP::ST_UID : $sequence;
  428. return $this;
  429. }
  430. /**
  431. * @return Client
  432. * @throws ConnectionFailedException
  433. */
  434. public function getClient() {
  435. $this->client->checkConnection();
  436. return $this->client;
  437. }
  438. /**
  439. * Set the limit and page for the current query
  440. * @param int $limit
  441. * @param int $page
  442. *
  443. * @return $this
  444. */
  445. public function limit($limit, $page = 1) {
  446. if ($page >= 1) $this->page = $page;
  447. $this->limit = $limit;
  448. return $this;
  449. }
  450. /**
  451. * @return Collection
  452. */
  453. public function getQuery() {
  454. return $this->query;
  455. }
  456. /**
  457. * @param array $query
  458. * @return Query
  459. */
  460. public function setQuery($query) {
  461. $this->query = new Collection($query);
  462. return $this;
  463. }
  464. /**
  465. * @return string
  466. */
  467. public function getRawQuery() {
  468. return $this->raw_query;
  469. }
  470. /**
  471. * @param string $raw_query
  472. * @return Query
  473. */
  474. public function setRawQuery($raw_query) {
  475. $this->raw_query = $raw_query;
  476. return $this;
  477. }
  478. /**
  479. * @return string
  480. */
  481. public function getCharset() {
  482. return $this->charset;
  483. }
  484. /**
  485. * @param string $charset
  486. * @return Query
  487. */
  488. public function setCharset($charset) {
  489. $this->charset = $charset;
  490. return $this;
  491. }
  492. /**
  493. * @param Client $client
  494. * @return Query
  495. */
  496. public function setClient(Client $client) {
  497. $this->client = $client;
  498. return $this;
  499. }
  500. /**
  501. * @return int
  502. */
  503. public function getLimit() {
  504. return $this->limit;
  505. }
  506. /**
  507. * @param int $limit
  508. * @return Query
  509. */
  510. public function setLimit($limit) {
  511. $this->limit = $limit <= 0 ? null : $limit;
  512. return $this;
  513. }
  514. /**
  515. * @return int
  516. */
  517. public function getPage() {
  518. return $this->page;
  519. }
  520. /**
  521. * @param int $page
  522. * @return Query
  523. */
  524. public function setPage($page) {
  525. $this->page = $page;
  526. return $this;
  527. }
  528. /**
  529. * @param boolean $fetch_options
  530. * @return Query
  531. */
  532. public function setFetchOptions($fetch_options) {
  533. $this->fetch_options = $fetch_options;
  534. return $this;
  535. }
  536. /**
  537. * @param boolean $fetch_options
  538. * @return Query
  539. */
  540. public function fetchOptions($fetch_options) {
  541. return $this->setFetchOptions($fetch_options);
  542. }
  543. /**
  544. * @return int
  545. */
  546. public function getFetchOptions() {
  547. return $this->fetch_options;
  548. }
  549. /**
  550. * @return boolean
  551. */
  552. public function getFetchBody() {
  553. return $this->fetch_body;
  554. }
  555. /**
  556. * @param boolean $fetch_body
  557. * @return Query
  558. */
  559. public function setFetchBody($fetch_body) {
  560. $this->fetch_body = $fetch_body;
  561. return $this;
  562. }
  563. /**
  564. * @param boolean $fetch_body
  565. * @return Query
  566. */
  567. public function fetchBody($fetch_body) {
  568. return $this->setFetchBody($fetch_body);
  569. }
  570. /**
  571. * @return int
  572. */
  573. public function getFetchFlags() {
  574. return $this->fetch_flags;
  575. }
  576. /**
  577. * @param int $fetch_flags
  578. * @return Query
  579. */
  580. public function setFetchFlags($fetch_flags) {
  581. $this->fetch_flags = $fetch_flags;
  582. return $this;
  583. }
  584. /**
  585. * @param string $fetch_order
  586. * @return Query
  587. */
  588. public function setFetchOrder($fetch_order) {
  589. $fetch_order = strtolower($fetch_order);
  590. if (in_array($fetch_order, ['asc', 'desc'])) {
  591. $this->fetch_order = $fetch_order;
  592. }
  593. return $this;
  594. }
  595. /**
  596. * @param string $fetch_order
  597. * @return Query
  598. */
  599. public function fetchOrder($fetch_order) {
  600. return $this->setFetchOrder($fetch_order);
  601. }
  602. /**
  603. * @return string
  604. */
  605. public function getFetchOrder() {
  606. return $this->fetch_order;
  607. }
  608. /**
  609. * @return Query
  610. */
  611. public function setFetchOrderAsc() {
  612. return $this->setFetchOrder('asc');
  613. }
  614. /**
  615. * @return Query
  616. */
  617. public function fetchOrderAsc() {
  618. return $this->setFetchOrderAsc();
  619. }
  620. /**
  621. * @return Query
  622. */
  623. public function setFetchOrderDesc() {
  624. return $this->setFetchOrder('desc');
  625. }
  626. /**
  627. * @return Query
  628. */
  629. public function fetchOrderDesc() {
  630. return $this->setFetchOrderDesc();
  631. }
  632. /**
  633. * @var boolean $state
  634. *
  635. * @return Query
  636. */
  637. public function softFail($state = true) {
  638. return $this->setSoftFail($state);
  639. }
  640. /**
  641. * @var boolean $state
  642. *
  643. * @return Query
  644. */
  645. public function setSoftFail($state = true) {
  646. $this->soft_fail = $state;
  647. return $this;
  648. }
  649. /**
  650. * @return boolean
  651. */
  652. public function getSoftFail() {
  653. return $this->soft_fail;
  654. }
  655. /**
  656. * Handle the exception for a given uid
  657. * @param integer $uid
  658. *
  659. * @throws GetMessagesFailedException
  660. */
  661. protected function handleException($uid) {
  662. if ($this->soft_fail === false && $this->hasError($uid)) {
  663. $error = $this->getError($uid);
  664. throw new GetMessagesFailedException($error->getMessage(), 0, $error);
  665. }
  666. }
  667. /**
  668. * Add a new error to the error holder
  669. * @param integer $uid
  670. * @param Exception $error
  671. */
  672. protected function setError($uid, $error) {
  673. $this->errors[$uid] = $error;
  674. }
  675. /**
  676. * Check if there are any errors / exceptions present
  677. * @var integer|null $uid
  678. *
  679. * @return boolean
  680. */
  681. public function hasErrors($uid = null){
  682. if ($uid !== null) {
  683. return $this->hasError($uid);
  684. }
  685. return count($this->errors) > 0;
  686. }
  687. /**
  688. * Check if there is an error / exception present
  689. * @var integer $uid
  690. *
  691. * @return boolean
  692. */
  693. public function hasError($uid){
  694. return isset($this->errors[$uid]);
  695. }
  696. /**
  697. * Get all available errors / exceptions
  698. *
  699. * @return array
  700. */
  701. public function errors(){
  702. return $this->getErrors();
  703. }
  704. /**
  705. * Get all available errors / exceptions
  706. *
  707. * @return array
  708. */
  709. public function getErrors(){
  710. return $this->errors;
  711. }
  712. /**
  713. * Get a specific error / exception
  714. * @var integer $uid
  715. *
  716. * @return Exception|null
  717. */
  718. public function error($uid){
  719. return $this->getError($uid);
  720. }
  721. /**
  722. * Get a specific error / exception
  723. * @var integer $uid
  724. *
  725. * @return Exception|null
  726. */
  727. public function getError($uid){
  728. if ($this->hasError($uid)) {
  729. return $this->errors[$uid];
  730. }
  731. return null;
  732. }
  733. }