ImapSource.php 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. <?php
  2. App::uses('DataSource', 'Model/Datasource');
  3. App::uses('Inflector', 'Utility');
  4. App::uses('Set', 'Utility');
  5. /**
  6. * Get emails in your app with cake like finds.
  7. *
  8. * TODO: implement https://github.com/kvz/cakephp-emails-plugin/commits
  9. * TODO: check for search stuff from https://github.com/barbushin/php-imap
  10. *
  11. * @copyright Copyright (c) 2010 Carl Sutton ( dogmatic69 )
  12. * @link http://www.infinitas-cms.org
  13. * @license http://opensource.org/licenses/mit-license.php MIT
  14. *
  15. * @author dogmatic69
  16. * @author kvz
  17. * @author Mark Scherer
  18. */
  19. class ImapSource extends DataSource {
  20. protected $_isConnected = false;
  21. protected $_connectionString = null;
  22. protected $_connectionType = '';
  23. protected $_defaultConfigs = [
  24. 'global' => [
  25. 'username' => false,
  26. 'password' => false,
  27. 'email' => false,
  28. 'server' => 'localhost',
  29. 'type' => 'imap',
  30. 'ssl' => false,
  31. 'mailbox' => 'INBOX',
  32. 'retry' => 3,
  33. 'error_handler' => 'php',
  34. 'auto_mark_as' => ['seen'],
  35. 'auto_transform' => true // transform attachments back into the original file content
  36. ],
  37. 'imap' => ['port' => 143],
  38. 'pop3' => ['port' => 110],
  39. ];
  40. public $marks = [
  41. '\Seen',
  42. '\Answered',
  43. '\Flagged',
  44. '\Deleted',
  45. '\Draft',
  46. ];
  47. public $config = [];
  48. public $driver = null;
  49. /**
  50. * Default array of field list for imap mailbox.
  51. *
  52. * @var array
  53. */
  54. protected $_schema = [
  55. 'id' => [
  56. 'type' => 'integer',
  57. 'default' => null,
  58. 'length' => 15,
  59. 'key' => 'primary',
  60. ],
  61. 'message_id' => [
  62. 'type' => 'string',
  63. 'default' => null,
  64. 'length' => 255,
  65. ],
  66. 'email_number' => [
  67. 'type' => 'integer',
  68. 'default' => null,
  69. 'length' => 15,
  70. ],
  71. 'to' => [
  72. 'type' => 'string',
  73. 'default' => null,
  74. 'length' => 255,
  75. ],
  76. 'to_name' => [
  77. 'type' => 'string',
  78. 'default' => null,
  79. 'length' => 255,
  80. ],
  81. 'from' => [
  82. 'type' => 'string',
  83. 'default' => null,
  84. 'length' => 255,
  85. ],
  86. 'from_name' => [
  87. 'type' => 'string',
  88. 'default' => null,
  89. 'length' => 255,
  90. ],
  91. 'reply_to' => [
  92. 'type' => 'string',
  93. 'default' => null,
  94. 'length' => 255,
  95. ],
  96. 'reply_to_name' => [
  97. 'type' => 'string',
  98. 'default' => null,
  99. 'length' => 255,
  100. ],
  101. 'sender' => [
  102. 'type' => 'string',
  103. 'default' => null,
  104. 'length' => 255,
  105. ],
  106. 'sender_name' => [
  107. 'type' => 'string',
  108. 'default' => null,
  109. 'length' => 255,
  110. ],
  111. 'subject' => [
  112. 'type' => 'string',
  113. 'default' => null,
  114. 'length' => 255,
  115. ],
  116. 'slug' => [
  117. 'type' => 'string',
  118. 'default' => null,
  119. 'length' => 255,
  120. ],
  121. 'body_html' => [
  122. 'type' => 'text',
  123. 'default' => null,
  124. ],
  125. 'body_text' => [
  126. 'type' => 'text',
  127. 'default' => null,
  128. ],
  129. 'size' => [
  130. 'type' => 'string',
  131. 'default' => null,
  132. 'length' => 255,
  133. ],
  134. 'recent' => [
  135. 'type' => 'boolean',
  136. 'default' => null,
  137. 'length' => 1,
  138. ],
  139. 'seen' => [
  140. 'type' => 'boolean',
  141. 'default' => null,
  142. 'length' => 1,
  143. ],
  144. 'flagged' => [
  145. 'type' => 'boolean',
  146. 'default' => null,
  147. 'length' => 1,
  148. ],
  149. 'answered' => [
  150. 'type' => 'boolean',
  151. 'default' => null,
  152. 'length' => 1,
  153. ],
  154. 'draft' => [
  155. 'type' => 'boolean',
  156. 'default' => null,
  157. 'length' => 1,
  158. ],
  159. 'deleted' => [
  160. 'type' => 'boolean',
  161. 'default' => null,
  162. 'length' => 1,
  163. ],
  164. 'thread_count' => [
  165. 'type' => 'integer',
  166. 'default' => null,
  167. 'length' => 15,
  168. 'key' => 'primary',
  169. ],
  170. 'attachments' => [
  171. 'type' => 'text',
  172. 'default' => null,
  173. ],
  174. 'in_reply_to' => [
  175. 'type' => 'string',
  176. 'default' => null,
  177. 'length' => 255,
  178. ],
  179. 'reference' => [
  180. 'type' => 'string',
  181. 'default' => null,
  182. 'length' => 255,
  183. ],
  184. 'new' => [
  185. 'type' => 'boolean',
  186. 'default' => null,
  187. 'length' => 1,
  188. ],
  189. 'created' => [
  190. 'type' => 'datetime',
  191. 'default' => null,
  192. ],
  193. ];
  194. public $columns = [
  195. 'primary_key' => ['name' => 'NOT NULL AUTO_INCREMENT'],
  196. 'string' => ['name' => 'varchar', 'limit' => '255'],
  197. 'text' => ['name' => 'text'],
  198. 'integer' => [
  199. 'name' => 'int',
  200. 'limit' => '11',
  201. 'formatter' => 'intval'],
  202. 'float' => ['name' => 'float', 'formatter' => 'floatval'],
  203. 'datetime' => [
  204. 'name' => 'datetime',
  205. 'format' => 'Y-m-d H:i:s',
  206. 'formatter' => 'date'],
  207. 'timestamp' => [
  208. 'name' => 'timestamp',
  209. 'format' => 'Y-m-d H:i:s',
  210. 'formatter' => 'date'],
  211. 'time' => [
  212. 'name' => 'time',
  213. 'format' => 'H:i:s',
  214. 'formatter' => 'date'],
  215. 'date' => [
  216. 'name' => 'date',
  217. 'format' => 'Y-m-d',
  218. 'formatter' => 'date'],
  219. 'binary' => ['name' => 'blob'],
  220. 'boolean' => ['name' => 'tinyint', 'limit' => '1']];
  221. public $dataTypes = [
  222. 0 => 'text',
  223. 1 => 'multipart',
  224. 2 => 'message',
  225. 3 => 'application',
  226. 4 => 'audio',
  227. 5 => 'image',
  228. 6 => 'video',
  229. 7 => 'other',
  230. ];
  231. public $encodingTypes = [
  232. 0 => '7bit',
  233. 1 => '8bit',
  234. 2 => 'binary',
  235. 3 => 'base64',
  236. 4 => 'quoted-printable',
  237. 5 => 'other',
  238. ];
  239. /**
  240. * __construct()
  241. *
  242. * @param mixed $config
  243. */
  244. public function __construct($config) {
  245. parent::__construct($config);
  246. if (!function_exists('imap_open')) {
  247. throw new InternalErrorException('imap_open not available. Please install extension/module.');
  248. }
  249. if (!isset($config['type'])) {
  250. $type = $this->_defaultConfigs['global']['type'];
  251. } else {
  252. $type = $config['type'];
  253. }
  254. $newConfig = array_merge($this->_defaultConfigs['global'], $this->_defaultConfigs[$type], $this->config);
  255. $newConfig['email'] = !empty($newConfig['email']) ? $newConfig['email'] : $newConfig['username'];
  256. $this->config = $newConfig;
  257. }
  258. /**
  259. * Expunge messages marked for deletion
  260. *
  261. */
  262. public function __destruct() {
  263. if ($this->_isConnected && $this->Stream) {
  264. $this->_isConnected = false;
  265. // If set to CL_EXPUNGE, the function will silently expunge the
  266. // mailbox before closing, removing all messages marked for deletion.
  267. // You can achieve the same thing by using imap_expunge()
  268. imap_close($this->Stream, CL_EXPUNGE);
  269. }
  270. }
  271. /**
  272. * Describe the data
  273. *
  274. * @param Model $Model
  275. * @return array The schema of the model
  276. */
  277. public function describe($Model) {
  278. return $this->_schema;
  279. }
  280. /**
  281. * listSources
  282. *
  283. * @return array Sources
  284. */
  285. public function listSources($data = null) {
  286. return ['listSources'];
  287. }
  288. /**
  289. * ImapSource::delete()
  290. *
  291. * @param Model $Model
  292. * @param mixed $conditions
  293. * @return bool Success
  294. */
  295. public function delete(Model $Model, $conditions = null) {
  296. $query = compact('conditions');
  297. $searchCriteria = $this->_makeSearch($Model, $query);
  298. $uids = $this->_uidsByCriteria($searchCriteria);
  299. if ($uids === false) {
  300. $uids = $Model->find('list', $query);
  301. }
  302. // Nothing was found
  303. if (empty($uids)) {
  304. return false;
  305. }
  306. $success = true;
  307. foreach ($uids as $uid) {
  308. if (!imap_delete($this->Stream, $uid, FT_UID)) {
  309. $this->err($Model, 'Unable to delete email with uid: %s', $uid);
  310. $success = false;
  311. }
  312. }
  313. return $success;
  314. }
  315. /**
  316. * Read data
  317. *
  318. * this is the main method that reads data from the datasource and
  319. * formats it according to the request from the model.
  320. *
  321. * @param Model $Model the model that is requesting data
  322. * @param mixed $query the qurey that was sent
  323. *
  324. * @return the data requested by the model
  325. */
  326. public function read(Model $Model, $queryData = [], $recursive = null) {
  327. if (!$this->connect($Model, $queryData)) {
  328. //throw new RuntimeException('something is wrong');
  329. return $this->err($Model, 'Cannot connect to server');
  330. }
  331. $searchCriteria = $this->_makeSearch($Model, $queryData);
  332. $uids = $this->_uidsByCriteria($searchCriteria);
  333. if ($uids === false) {
  334. // Perform Search & Order. Returns list of ids
  335. list($orderReverse, $orderCriteria) = $this->_makeOrder($Model, $queryData);
  336. $uids = imap_sort($this->Stream, $orderCriteria, $orderReverse, SE_UID, implode(' ', $searchCriteria));
  337. }
  338. // Nothing was found
  339. if (empty($uids)) {
  340. return [];
  341. }
  342. // Trim resulting ids based on pagination / limitation
  343. if (@$queryData['start'] && @$queryData['end']) {
  344. $uids = array_slice($uids, @$queryData['start'], @$queryData['end'] - @$queryData['start']);
  345. } elseif (@$queryData['limit']) {
  346. $uids = array_slice($uids, @$queryData['start'] ? @$queryData['start'] : 0, @$queryData['limit']);
  347. } elseif ($Model->findQueryType === 'first') {
  348. $uids = array_slice($uids, 0, 1);
  349. }
  350. // Format output depending on findQueryType
  351. if ($Model->findQueryType === 'list') {
  352. return $uids;
  353. }
  354. if ($Model->findQueryType === 'count') {
  355. return [[$Model->alias => ['count' => count($uids)]]];
  356. }
  357. if ($Model->findQueryType === 'all' || $Model->findQueryType === 'first') {
  358. $recursive = isset($queryData['recursive']) ? $queryData['recursive'] : $Model->recursive;
  359. $fetchAttachments = $recursive > 0;
  360. $mails = [];
  361. foreach ($uids as $uid) {
  362. if (($mail = $this->_getFormattedMail($Model, $uid, $fetchAttachments))) {
  363. $mails[] = $mail;
  364. }
  365. }
  366. return $mails;
  367. }
  368. return $this->err($Model, 'Unknown find type %s for query %s', $Model->findQueryType, $queryData);
  369. }
  370. /**
  371. * Calculate
  372. *
  373. * @param <type> $Model
  374. * @param <type> $func
  375. * @param <type> $params
  376. * @return string
  377. */
  378. public function calculate(Model $Model, $func, $params = []) {
  379. $params = (array)$params;
  380. switch (strtolower($func)) {
  381. case 'count':
  382. return 'count';
  383. }
  384. }
  385. /**
  386. * Update the email setting flags
  387. *
  388. * @return bool Success
  389. */
  390. public function update(Model $model, $fields = null, $values = null, $conditions = null) {
  391. if (empty($model->id)) {
  392. return $this->err($model, 'Cannot update a record without id');
  393. }
  394. $flags = [
  395. 'recent',
  396. 'seen',
  397. 'flagged',
  398. 'answered',
  399. 'draft',
  400. 'deleted'];
  401. $data = array_combine($fields, $values);
  402. foreach ($data as $field => $value) {
  403. if (!in_array($field, $flags)) {
  404. continue;
  405. }
  406. $flag = '\\' . ucfirst($field);
  407. if ($value === true || $value === 1 || $value === '1') {
  408. if (!imap_setflag_full($this->Stream, $model->id, $flag, ST_UID)) {
  409. $this->err($model, 'Unable to mark email %s as %s', $model->id, $flag);
  410. }
  411. } else {
  412. if (!imap_clearflag_full($this->Stream, $model->id, $flag, ST_UID)) {
  413. $this->err($model, 'Unable to unmark email %s as %s', $model->id, $flag);
  414. }
  415. }
  416. }
  417. return true;
  418. }
  419. /**
  420. * ImapSource::query()
  421. *
  422. * Allow Source methods to be called from the model
  423. *
  424. * @param string $method
  425. * @param array $params
  426. * @return mixed Result
  427. */
  428. public function query($method, $params, Model $Model) {
  429. array_unshift($params, $Model);
  430. return call_user_func_array([$this, $method], $params);
  431. }
  432. /**
  433. * ImapSource::err()
  434. *
  435. * @param Model $Model
  436. * @param mixed $format
  437. * @param mixed $args (3...x arguments)
  438. * @return bool false if error handler is not set to `exception`
  439. */
  440. public function err($Model, $format, $args = null) {
  441. $arguments = func_get_args();
  442. $Model = array_shift($arguments);
  443. $format = array_shift($arguments);
  444. $str = $format;
  445. if (!empty($arguments)) {
  446. foreach ($arguments as $k => $v) {
  447. $arguments[$k] = $this->_sensible($v);
  448. }
  449. $str = vsprintf($str, $arguments);
  450. }
  451. $this->error = $str;
  452. $Model->onError();
  453. if ($this->config['error_handler'] === 'php') {
  454. trigger_error($str, E_USER_ERROR);
  455. } elseif ($this->config['error_handler'] === 'exception') {
  456. throw new CakeException($str);
  457. }
  458. return false;
  459. }
  460. /**
  461. * ImapSource::lastError()
  462. *
  463. * @return string Error or bool false if no error is available
  464. */
  465. public function lastError() {
  466. if (($lastError = $this->error)) {
  467. return $lastError;
  468. }
  469. if (($lastError = imap_last_error())) {
  470. $this->error = $lastError;
  471. return $lastError;
  472. }
  473. return false;
  474. }
  475. /**
  476. * ImapSource::listMailboxes()
  477. *
  478. * There are two special characters you can pass as part of the pattern :
  479. * '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*',
  480. * you will get a list of the entire mailbox hierarchy. '%' means to return the current level only.
  481. *
  482. * @param Model $Model
  483. * @param bool|string $current
  484. * @return array Array containing the names of the mailboxes.
  485. */
  486. public function listMailboxes(Model $Model, $current = true) {
  487. if (is_bool($current)) {
  488. if ($current) {
  489. $current = '%';
  490. } else {
  491. $current = '*';
  492. }
  493. }
  494. $this->connect($Model, []);
  495. return imap_list($this->Stream, $this->_connectionString, $current);
  496. }
  497. /**
  498. * Connect to the mail server
  499. */
  500. public function connect(Model $Model, $query) {
  501. if ($this->_isConnected) {
  502. return true;
  503. }
  504. $this->_connectionString = $this->_buildConnector();
  505. try {
  506. $retries = $this->config['retry'];
  507. $this->Stream = imap_open($this->_connectionString, $this->config['username'], $this->config['password'], NIL, $retries);
  508. //$this->thread = @imap_thread($this->Stream);
  509. } catch (exception $Exception) {
  510. return $this->err($Model, 'Unable to connect to IMAP server %s retries. %s', $this->_connectionString, $Exception->getMessage() . ' ' . imap_last_error());
  511. }
  512. return $this->_isConnected = true;
  513. }
  514. protected function _buildConnector() {
  515. $data = $this->config;
  516. $string = sprintf('{%s:%s%s%s}', $this->config['server'], $this->config['port'], @$this->config['ssl'] ? '/ssl' : '', @$this->
  517. config['connect'] ? '/' . @$this->config['connect'] : '/novalidate-cert');
  518. return $string;
  519. $string = '{';
  520. $string .= $data['server'];
  521. if (!empty($data['port'])) {
  522. $string .= ':' . $data['port'];
  523. }
  524. if (!empty($data['service'])) {
  525. $string .= '/service=' . $data['service'];
  526. }
  527. if (!empty($data['user'])) {
  528. $string .= '/user=' . $data['user'];
  529. } else {
  530. $string .= '/anonymous';
  531. }
  532. if (!empty($data['authuser'])) {
  533. $string .= '/authuser=' . $data['authuser'];
  534. }
  535. if (!empty($data['debug'])) {
  536. $string .= '/debug';
  537. }
  538. if (!empty($data['secure'])) {
  539. $string .= '/secure';
  540. }
  541. if (!empty($data['norsh'])) {
  542. $string .= '/norsh';
  543. }
  544. if (!empty($data['ssl'])) {
  545. $string .= '/ssl';
  546. }
  547. if (!empty($data['validate'])) {
  548. $string .= '/validate-cert';
  549. } else {
  550. $string .= '/novalidate-cert';
  551. }
  552. if (!empty($data['tls'])) {
  553. $string .= '/tls';
  554. }
  555. if (!empty($data['notls'])) {
  556. $string .= '/notls';
  557. }
  558. if (!empty($data['readonly'])) {
  559. $string .= '/readonly';
  560. }
  561. $string .= '}';
  562. if (!empty($data['mailbox'])) {
  563. $string .= $data['mailbox'];
  564. }
  565. return $string;
  566. // deprecated part
  567. switch ($this->config['type']) {
  568. case 'imap':
  569. $this->_connectionString = sprintf('{%s:%s%s%s}', $this->config['server'], $this->config['port'], @$this->config['ssl'] ? '/ssl' : '', @$this->
  570. config['connect'] ? '/' . @$this->config['connect'] : '');
  571. break;
  572. case 'pop3':
  573. $this->_connectionString = sprintf('{%s:%s/pop3%s%s}', $this->config['server'], $this->config['port'], @$this->config['ssl'] ? '/ssl' : '',
  574. @$this->config['connect'] ? '/' . @$this->config['connect'] : '');
  575. break;
  576. }
  577. }
  578. /**
  579. * Tranform search criteria from CakePHP -> Imap
  580. * Does AND, not OR
  581. *
  582. * Supported:
  583. * FROM "string" - match messages with "string" in the From: field
  584. *
  585. * ANSWERED - match messages with the \\ANSWERED flag set
  586. * UNANSWERED - match messages that have not been answered
  587. *
  588. * SEEN - match messages that have been read (the \\SEEN flag is set)
  589. * UNSEEN - match messages which have not been read yet
  590. *
  591. * DELETED - match deleted messages
  592. * UNDELETED - match messages that are not deleted
  593. *
  594. * FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
  595. * UNFLAGGED - match messages that are not flagged
  596. *
  597. * RECENT - match messages with the \\RECENT flag set
  598. *
  599. * @todo:
  600. * A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted.
  601. * ALL - return all messages matching the rest of the criteria
  602. * BCC "string" - match messages with "string" in the Bcc: field
  603. * BEFORE "date" - match messages with Date: before "date"
  604. * BODY "string" - match messages with "string" in the body of the message
  605. * CC "string" - match messages with "string" in the Cc: field
  606. * KEYWORD "string" - match messages with "string" as a keyword
  607. * NEW - match new messages
  608. * OLD - match old messages
  609. * ON "date" - match messages with Date: matching "date"
  610. * SINCE "date" - match messages with Date: after "date"
  611. * SUBJECT "string" - match messages with "string" in the Subject:
  612. * TEXT "string" - match messages with text "string"
  613. * TO "string" - match messages with "string" in the To:
  614. * UNKEYWORD "string" - match messages that do not have the keyword "string"
  615. *
  616. * @param Model $Model
  617. * @param array $query
  618. *
  619. * @return array
  620. */
  621. protected function _makeSearch(Model $Model, $query) {
  622. $searchCriteria = [];
  623. if (empty($query['conditions'])) {
  624. $query['conditions'] = [];
  625. }
  626. // Special case. When somebody specifies primaryKey(s),
  627. // We don't have to do an actual search
  628. if (($id = $this->_cond($Model, $query, $Model->primaryKey))) {
  629. return $this->_toUid($id);
  630. }
  631. // Flag search parameters
  632. $flags = [
  633. 'recent',
  634. 'seen',
  635. 'flagged',
  636. 'answered',
  637. 'draft',
  638. 'deleted',
  639. ];
  640. foreach ($flags as $flag) {
  641. if (($val = $this->_cond($Model, $query, $flag)) === null) {
  642. continue;
  643. }
  644. $upper = strtoupper($flag);
  645. $unupper = 'UN' . $upper;
  646. if (!$val && ($flag === 'recent')) {
  647. // There is no UNRECENT :/
  648. // Just don't set the condition
  649. continue;
  650. }
  651. $searchCriteria[] = $val ? $upper : $unupper;
  652. }
  653. // String search parameters
  654. if (($val = $this->_cond($Model, $query, 'from'))) {
  655. $searchCriteria[] = 'FROM "' . $val . '"';
  656. }
  657. return $searchCriteria;
  658. }
  659. /**
  660. * Tranform order criteria from CakePHP -> Imap
  661. *
  662. * For now always sorts on date descending.
  663. * @todo: Support the following sort parameters:
  664. * SORTDATE - message Date
  665. * SORTARRIVAL - arrival date
  666. * SORTFROM - mailbox in first From address
  667. * SORTSUBJECT - message subject
  668. * SORTTO - mailbox in first To address
  669. * SORTCC - mailbox in first cc address
  670. * SORTSIZE - size of message in octets
  671. *
  672. * @param Model $Model
  673. * @param array $query
  674. *
  675. * @return array
  676. */
  677. protected function _makeOrder(Model $Model, $query) {
  678. $criterias = [
  679. 'date',
  680. 'arrival',
  681. 'from',
  682. 'subject',
  683. 'to',
  684. 'cc',
  685. 'size'];
  686. $order = [1, SORTDATE];
  687. if (empty($query['order']) || empty($query['order'][0])) {
  688. return $order;
  689. }
  690. foreach ($query['order'][0] as $key => $dir) {
  691. if (in_array($key, $criterias)) {
  692. return [(strtoupper($dir) === 'ASC') ? 0 : 1, constant('SORT' . strtoupper($key))];
  693. }
  694. }
  695. return $order;
  696. }
  697. /**
  698. * Returns a query condition, or null if it wasn't found
  699. *
  700. * @param Model $Model
  701. * @param array $query
  702. * @param string $field
  703. *
  704. * @return mixed or null
  705. */
  706. protected function _cond(Model $Model, $query, $field) {
  707. $keys = [
  708. '`' . $Model->alias . '`.`' . $field . '`',
  709. $Model->alias . '.' . $field,
  710. $field,
  711. ];
  712. if (empty($query['conditions'])) {
  713. return null;
  714. }
  715. foreach ($keys as $key) {
  716. if (array_key_exists($key, $query['conditions'])) {
  717. return $query['conditions'][$key];
  718. }
  719. }
  720. return null;
  721. }
  722. /**
  723. * Returns ids from searchCriteria or false if there's other criteria involved
  724. *
  725. * @param array $searchCriteria
  726. *
  727. * @return false or array
  728. */
  729. protected function _uidsByCriteria($searchCriteria) {
  730. if (is_numeric($searchCriteria) || Set::numeric($searchCriteria)) {
  731. // We already know the id, or list of ids
  732. $results = $searchCriteria;
  733. if (!is_array($results)) {
  734. $results = [$results];
  735. }
  736. return $results;
  737. }
  738. return false;
  739. }
  740. /**
  741. * ImapSource::_sensible() for error output
  742. *
  743. * @param mixed $arguments
  744. * @return string
  745. */
  746. protected function _sensible($arguments) {
  747. if (is_object($arguments)) {
  748. return get_class($arguments);
  749. }
  750. if (!is_array($arguments)) {
  751. if (!is_numeric($arguments) && !is_bool($arguments)) {
  752. $arguments = "'" . $arguments . "'";
  753. }
  754. return $arguments;
  755. }
  756. $arr = [];
  757. foreach ($arguments as $key => $val) {
  758. if (is_array($val)) {
  759. $val = json_encode($val);
  760. } elseif (!is_numeric($val) && !is_bool($val)) {
  761. $val = "'" . $val . "'";
  762. }
  763. if (strlen($val) > 33) {
  764. $val = substr($val, 0, 30) . '...';
  765. }
  766. $arr[] = $key . ': ' . $val;
  767. }
  768. return implode(', ', $arr);
  769. }
  770. /**
  771. * Tries to parse mail & name data from Mail object for to, from, etc.
  772. * Gracefully degrades where needed
  773. *
  774. * Type: to, cc, bcc, from, sender, reply_to
  775. * Need: box, name, host, address, full
  776. *
  777. * @param object $Mail
  778. * @param string $type
  779. * @param string $need
  780. *
  781. * @return mixed string or array
  782. */
  783. protected function _personId($Mail, $type = 'to', $need = null) {
  784. if ($type === 'sender' && !isset($Mail->sender)) {
  785. $type = 'from';
  786. }
  787. if (!isset($Mail->{$type})) {
  788. return [];
  789. }
  790. $results = [];
  791. foreach ($Mail->{$type} as $person) {
  792. $info = [
  793. 'box' => '',
  794. 'host' => '',
  795. 'address' => '',
  796. ];
  797. if (isset($person->mailbox)) {
  798. $info['box'] = $person->mailbox;
  799. }
  800. if (isset($person->host)) {
  801. $info['host'] = $person->host;
  802. }
  803. if ($info['box'] && $info['host']) {
  804. $info['address'] = $info['box'] . '@' . $info['host'];
  805. }
  806. $info['name'] = $info['box'];
  807. if (isset($person->personal)) {
  808. $info['name'] = $this->_decode($person->personal);
  809. }
  810. $info['full'] = $info['address'];
  811. if ($info['name']) {
  812. $info['full'] = sprintf('"%s" <%s>', $info['name'], $info['address']);
  813. }
  814. $results[] = $info;
  815. }
  816. if ($need !== null) {
  817. return $results[0][$need];
  818. }
  819. return $results;
  820. }
  821. /**
  822. * Decode text to the application encoding
  823. *
  824. * @param string $text
  825. * @return string text
  826. */
  827. protected function _decode($text) {
  828. if (is_object($text)) {
  829. $decoded = $text;
  830. $text = $decoded->text;
  831. } else {
  832. $decoded = imap_mime_header_decode($text);
  833. $decoded = $decoded[0];
  834. }
  835. if (empty($decoded) || empty($decoded->text) || $decoded->charset === 'default') {
  836. return $text;
  837. }
  838. $text = imap_qprint($decoded->text);
  839. $appEncoding = Configure::read('App.encoding');
  840. $mailEncoding = $decoded->charset;
  841. $encodings = mb_list_encodings();
  842. $valid = true;
  843. if ($appEncoding !== $mailEncoding || !($valid = mb_check_encoding($text, $mailEncoding))) {
  844. if (!in_array($mailEncoding, $encodings) || !$valid) {
  845. $mailEncoding = mb_detect_encoding($text);
  846. }
  847. if (!in_array($appEncoding, $encodings)) {
  848. $appEncoding = 'UTF-8';
  849. }
  850. $text = mb_convert_encoding($text, $appEncoding, $mailEncoding);
  851. }
  852. return $text;
  853. }
  854. /**
  855. * Get the basic details like sender and reciver with flags like attatchments etc
  856. *
  857. * @param int $uid the number of the message
  858. * @return array empty on error/nothing or array of formatted details
  859. */
  860. protected function _getFormattedMail(Model $Model, $uid, $fetchAttachments = false) {
  861. // Translate uid to msg_no. Has no decent fail
  862. $msgNumber = imap_msgno($this->Stream, $uid);
  863. // A hack to detect if imap_msgno failed, and we're in fact looking at the wrong mail
  864. if ($uid != ($mailuid = imap_uid($this->Stream, $msgNumber))) {
  865. //pr(compact('Mail'));
  866. return $this->err($Model, 'Mail id mismatch. parameter id: %s vs mail id: %s', $uid, $mailuid);
  867. }
  868. // Get Mail with a property: 'date' or fail
  869. if (!($Mail = imap_headerinfo($this->Stream, $msgNumber)) || !property_exists($Mail, 'date')) {
  870. //pr(compact('Mail'));
  871. return $this->err($Model, 'Unable to find mail date property in Mail corresponding with uid: %s. Something must be wrong', $uid);
  872. }
  873. // Get Mail with a property: 'type' or fail
  874. if (!($flatStructure = $this->_flatStructure($Model, $uid))) {
  875. return $this->err($Model, 'Unable to find structure type property in Mail corresponding with uid: %s. Something must be wrong', $uid);
  876. }
  877. $text = $this->_fetchFirstByMime($flatStructure, 'text/plain');
  878. $html = $this->_fetchFirstByMime($flatStructure, 'text/html');
  879. $return[$Model->alias] = [
  880. 'id' => $this->_toId($uid),
  881. 'message_id' => $Mail->messageId,
  882. 'email_number' => $Mail->Msgno,
  883. 'from' => $this->_personId($Mail, 'from', 'address'),
  884. 'from_name' => $this->_personId($Mail, 'from', 'name'),
  885. 'reply_to' => $this->_personId($Mail, 'reply_to', 'address'),
  886. 'reply_to_name' => $this->_personId($Mail, 'reply_to', 'name'),
  887. 'sender' => $this->_personId($Mail, 'sender', 'address'),
  888. 'sender_name' => $this->_personId($Mail, 'sender', 'name'),
  889. 'subject' => htmlspecialchars(@$Mail->subject),
  890. 'slug' => Inflector::slug(@$Mail->subject, '-'),
  891. 'header' => @imap_fetchheader($this->Stream, $uid, FT_UID),
  892. 'body_html' => $html,
  893. 'body_text' => $text,
  894. 'size' => @$Mail->Size,
  895. 'recent' => @$Mail->Recent === 'R' ? 1 : 0,
  896. 'seen' => @$Mail->Unseen === 'U' ? 0 : 1,
  897. 'flagged' => @$Mail->Flagged === 'F' ? 1 : 0,
  898. 'answered' => @$Mail->Answered === 'A' ? 1 : 0,
  899. 'draft' => @$Mail->Draft === 'X' ? 1 : 0,
  900. 'deleted' => @$Mail->Deleted === 'D' ? 1 : 0,
  901. 'thread_count' => $this->_getThreadCount($Mail),
  902. 'in_reply_to' => @$Mail->inReplyTo,
  903. 'reference' => @$Mail->references,
  904. 'new' => (int)@$Mail->inReplyTo,
  905. 'created' => date('Y-m-d H:i:s', strtotime($Mail->date)),
  906. ];
  907. $return['Recipient'] = $this->_personId($Mail, 'to');
  908. $return['RecipientCopy'] = $this->_personId($Mail, 'cc');
  909. $return['RecipientBlindCopy'] = $this->_personId($Mail, 'bcc');
  910. if ($fetchAttachments) {
  911. $return['Attachment'] = $this->_fetchAttachments($flatStructure, $Model);
  912. }
  913. // Auto mark after read
  914. if (!empty($this->config['auto_mark_as'])) {
  915. $marks = '\\' . implode(' \\', $this->config['auto_mark_as']);
  916. if (!imap_setflag_full($this->Stream, $uid, $marks, ST_UID)) {
  917. $this->err($Model, 'Unable to mark email %s as %s', $uid, $marks);
  918. }
  919. }
  920. return $return;
  921. }
  922. /**
  923. * ImapSource::_decodePart()
  924. *
  925. * @param object $Part
  926. * @param mixed $uid
  927. * @return object Part
  928. */
  929. protected function _decodePart($Part, $uid) {
  930. if (!($Part->format = @$this->encodingTypes[$Part->encoding])) {
  931. $Part->format = $this->encodingTypes[0];
  932. }
  933. if (!($Part->datatype = @$this->dataTypes[$Part->type])) {
  934. $Part->datatype = $this->dataTypes[0];
  935. }
  936. $Part->mimeType = strtolower($Part->datatype . '/' . $Part->subtype);
  937. $Part->filename = '';
  938. $Part->name = '';
  939. $Part->uid = $uid;
  940. if ($Part->ifdparameters) {
  941. foreach ($Part->dparameters as $Object) {
  942. if (strtolower($Object->attribute) === 'filename') {
  943. $Part->filename = $Object->value;
  944. }
  945. }
  946. }
  947. if ($Part->ifparameters) {
  948. foreach ($Part->parameters as $Object) {
  949. if (strtolower($Object->attribute) === 'name') {
  950. $Part->name = $Object->value;
  951. }
  952. }
  953. }
  954. $Part->isAttachment = (!empty($Part->disposition) && !empty($Part->filename) && in_array(strtolower($Part->disposition), ['attachment',
  955. 'inline']));
  956. return $Part;
  957. }
  958. /**
  959. *
  960. * Contains parts of:
  961. * http://p2p.wrox.com/pro-php/8658-fyi-parsing-imap_fetchstructure.html
  962. * http://www.php.net/manual/en/function.imap-fetchstructure.php#86685
  963. *
  964. * @param <type> $uid
  965. * @param <type> $mixed
  966. * @param <type> $Structure
  967. * @param <type> $partnr
  968. *
  969. * @return array
  970. */
  971. protected function _flatStructure(Model $Model, $uid, $Structure = false, $partnr = 1) {
  972. $mainRun = false;
  973. if (!$Structure) {
  974. $mainRun = true;
  975. $Structure = imap_fetchstructure($this->Stream, $uid, FT_UID);
  976. if (!property_exists($Structure, 'type')) {
  977. return $this->err($Model, 'No type in structure');
  978. }
  979. }
  980. $flatParts = [];
  981. if (!empty($Structure->parts)) {
  982. $decimas = explode('.', $partnr);
  983. $decimas[count($decimas) - 1] -= 1;
  984. $Structure->path = implode('.', $decimas);
  985. } else {
  986. $Structure->path = $partnr;
  987. }
  988. $flatParts[$Structure->path] = $this->_decodePart($Structure, $uid);
  989. if (!empty($Structure->parts)) {
  990. foreach ($Structure->parts as $n => $Part) {
  991. if ($n >= 1) {
  992. $arrDecimas = explode('.', $partnr);
  993. $arrDecimas[count($arrDecimas) - 1] += 1;
  994. $partnr = implode('.', $arrDecimas);
  995. }
  996. $Part->path = $partnr;
  997. $flatParts[$Part->path] = $this->_decodePart($Part, $uid);
  998. if (!empty($Part->parts)) {
  999. if ($Part->type == 1) {
  1000. $flatParts = Set::merge($flatParts, $this->_flatStructure($Model, $uid, $Part, $partnr . '.' . ($n + 1)));
  1001. } else {
  1002. foreach ($Part->parts as $idx => $Part2) {
  1003. $flatParts = Set::merge($flatParts, $this->_flatStructure($Model, $uid, $Part2, $partnr . '.' . ($idx + 1)));
  1004. }
  1005. }
  1006. }
  1007. }
  1008. }
  1009. // Filter mixed
  1010. if ($mainRun) {
  1011. foreach ($flatParts as $path => $Part) {
  1012. if ($Part->mimeType === 'multipart/mixed') {
  1013. unset($flatParts[$path]);
  1014. }
  1015. if ($Part->mimeType === 'multipart/alternative') {
  1016. unset($flatParts[$path]);
  1017. }
  1018. if ($Part->mimeType === 'multipart/related') {
  1019. unset($flatParts[$path]);
  1020. }
  1021. if ($Part->mimeType === 'message/rfc822') {
  1022. unset($flatParts[$path]);
  1023. }
  1024. }
  1025. }
  1026. // Flatten more (remove childs)
  1027. if ($mainRun) {
  1028. foreach ($flatParts as $path => $Part) {
  1029. unset($Part->parts);
  1030. }
  1031. }
  1032. return $flatParts;
  1033. }
  1034. /**
  1035. * ImapSource::_fetchAttachments()
  1036. *
  1037. * @param mixed $flatStructure
  1038. * @param Model $Model
  1039. * @return array
  1040. */
  1041. protected function _fetchAttachments($flatStructure, Model $Model) {
  1042. $attachments = [];
  1043. foreach ($flatStructure as $path => $Part) {
  1044. if (!$Part->isAttachment) {
  1045. continue;
  1046. }
  1047. $attachments[] = [
  1048. strtolower(Inflector::singularize($Model->alias) . '_id') => $this->_toId($Part->uid),
  1049. 'message_id' => $Part->uid,
  1050. 'isAttachment' => $Part->isAttachment,
  1051. 'filename' => $Part->filename,
  1052. 'mime_type' => $Part->mimeType,
  1053. 'type' => strtolower($Part->subtype),
  1054. 'datatype' => $Part->datatype,
  1055. 'format' => $Part->format,
  1056. 'name' => $Part->name,
  1057. 'size' => $Part->bytes,
  1058. 'attachment' => $this->_fetchPart($Part),
  1059. ];
  1060. }
  1061. return $attachments;
  1062. }
  1063. protected function _fetchPart($Part) {
  1064. $data = imap_fetchbody($this->Stream, $Part->uid, $Part->path, FT_UID | FT_PEEK);
  1065. if ($Part->format === 'quoted-printable') {
  1066. $data = quoted_printable_decode($data);
  1067. } elseif ($this->config['auto_transform']) {
  1068. $data = $this->_decodeString($data, $Part->encoding);
  1069. }
  1070. return $data;
  1071. }
  1072. /**
  1073. * @see http://www.nerdydork.com/download-pop3imap-email-attachments-with-php.html
  1074. */
  1075. protected function _decodeString($message, $coding) {
  1076. switch ($coding) {
  1077. case 0:
  1078. case 1:
  1079. return imap_8bit($message);
  1080. case 2:
  1081. return imap_binary($message);
  1082. case 3:
  1083. return imap_base64($message);
  1084. case 4:
  1085. return imap_qprint($message);
  1086. default:
  1087. // plain
  1088. return $message;
  1089. }
  1090. }
  1091. /**
  1092. * ImapSource::_fetchFirstByMime()
  1093. *
  1094. * @param mixed $flatStructure
  1095. * @param mixed $mimeType
  1096. * @return string
  1097. */
  1098. protected function _fetchFirstByMime($flatStructure, $mimeType) {
  1099. foreach ($flatStructure as $path => $Part) {
  1100. if ($mimeType === $Part->mimeType) {
  1101. $text = $this->_fetchPart($Part);
  1102. if ($Part->format === 'base64') {
  1103. $text = base64_decode($text);
  1104. }
  1105. // No parameters, no charset to decode
  1106. if (empty($Part->parameters)) {
  1107. return $text;
  1108. }
  1109. // Try decode using the charset provided
  1110. foreach ($Part->parameters as $param) {
  1111. if ($param->attribute !== 'charset') {
  1112. continue;
  1113. }
  1114. $params = (object)[
  1115. 'charset' => $param->value,
  1116. 'text' => $text,
  1117. ];
  1118. return $this->_decode($params);
  1119. }
  1120. // Fallback to original text
  1121. return $text;
  1122. }
  1123. }
  1124. }
  1125. /**
  1126. * Get id for use in the mail protocol
  1127. *
  1128. * @param <type> $id
  1129. * @return string
  1130. */
  1131. protected function _toUid($id) {
  1132. if (is_array($id)) {
  1133. return array_map([$this, __FUNCTION__], $id);
  1134. }
  1135. $uid = $id;
  1136. return $uid;
  1137. }
  1138. /**
  1139. * Get id for use in the code
  1140. *
  1141. * @param string $uid in the format <.*@.*> from the email
  1142. * @return mixed on imap its the unique id (int) and for others its a base64_encoded string
  1143. */
  1144. protected function _toId($uid) {
  1145. if (is_array($uid)) {
  1146. return array_map([$this, __function__ ], $uid);
  1147. }
  1148. $id = $uid;
  1149. return $id;
  1150. }
  1151. /**
  1152. * Figure out how many emails there are in the thread for this mail.
  1153. *
  1154. * @param object $Mail the imap header of the mail
  1155. * @return int the number of mails in the thred
  1156. */
  1157. protected function _getThreadCount($Mail) {
  1158. if (isset($Mail->reference) || isset($Mail->inReplyTo)) {
  1159. return '?';
  1160. }
  1161. return 0;
  1162. }
  1163. }