ImapSource.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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. switch ($coding) {
  1079. case 0:
  1080. case 1:
  1081. return imap_8bit($message);
  1082. case 2:
  1083. return imap_binary($message);
  1084. case 3:
  1085. return imap_base64($message);
  1086. case 4:
  1087. return imap_qprint($message);
  1088. default:
  1089. // plain
  1090. return $message;
  1091. }
  1092. }
  1093. /**
  1094. * ImapSource::_fetchFirstByMime()
  1095. *
  1096. * @param mixed $flatStructure
  1097. * @param mixed $mimeType
  1098. * @return string
  1099. */
  1100. protected function _fetchFirstByMime($flatStructure, $mimeType) {
  1101. foreach ($flatStructure as $path => $Part) {
  1102. if ($mimeType === $Part->mimeType) {
  1103. $text = $this->_fetchPart($Part);
  1104. if ($Part->format === 'base64') {
  1105. $text = base64_decode($text);
  1106. }
  1107. // No parameters, no charset to decode
  1108. if (empty($Part->parameters)) {
  1109. return $text;
  1110. }
  1111. // Try decode using the charset provided
  1112. foreach ($Part->parameters as $param) {
  1113. if ($param->attribute !== 'charset') {
  1114. continue;
  1115. }
  1116. $params = (object)array(
  1117. 'charset' => $param->value,
  1118. 'text' => $text,
  1119. );
  1120. return $this->_decode($params);
  1121. }
  1122. // Fallback to original text
  1123. return $text;
  1124. }
  1125. }
  1126. }
  1127. /**
  1128. * get id for use in the mail protocol
  1129. *
  1130. * @param <type> $id
  1131. * @return string
  1132. */
  1133. protected function _toUid($id) {
  1134. if (is_array($id)) {
  1135. return array_map(array($this, __FUNCTION__), $id);
  1136. }
  1137. $uid = $id;
  1138. return $uid;
  1139. }
  1140. /**
  1141. * Get id for use in the code
  1142. *
  1143. * @param string $uid in the format <.*@.*> from the email
  1144. * @return mixed on imap its the unique id (int) and for others its a base64_encoded string
  1145. */
  1146. protected function _toId($uid) {
  1147. if (is_array($uid)) {
  1148. return array_map(array($this, __function__ ), $uid);
  1149. }
  1150. $id = $uid;
  1151. return $id;
  1152. }
  1153. /**
  1154. * Figure out how many emails there are in the thread for this mail.
  1155. *
  1156. * @param object $Mail the imap header of the mail
  1157. * @return integer the number of mails in the thred
  1158. */
  1159. protected function _getThreadCount($Mail) {
  1160. if (isset($Mail->reference) || isset($Mail->in_reply_to)) {
  1161. return '?';
  1162. }
  1163. return 0;
  1164. }
  1165. }