ImapSource.php 32 KB

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