You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_imap_cache.php 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2005-2012, The Roundcube Dev Team |
  6. | |
  7. | Licensed under the GNU General Public License version 3 or |
  8. | any later version with exceptions for skins & plugins. |
  9. | See the README file for a full license statement. |
  10. | |
  11. | PURPOSE: |
  12. | Caching of IMAP folder contents (messages and index) |
  13. +-----------------------------------------------------------------------+
  14. | Author: Thomas Bruederli <roundcube@gmail.com> |
  15. | Author: Aleksander Machniak <alec@alec.pl> |
  16. +-----------------------------------------------------------------------+
  17. */
  18. /**
  19. * Interface class for accessing Roundcube messages cache
  20. *
  21. * @package Framework
  22. * @subpackage Storage
  23. * @author Thomas Bruederli <roundcube@gmail.com>
  24. * @author Aleksander Machniak <alec@alec.pl>
  25. */
  26. class rcube_imap_cache
  27. {
  28. const MODE_INDEX = 1;
  29. const MODE_MESSAGE = 2;
  30. /**
  31. * Instance of rcube_imap
  32. *
  33. * @var rcube_imap
  34. */
  35. private $imap;
  36. /**
  37. * Instance of rcube_db
  38. *
  39. * @var rcube_db
  40. */
  41. private $db;
  42. /**
  43. * User ID
  44. *
  45. * @var int
  46. */
  47. private $userid;
  48. /**
  49. * Expiration time in seconds
  50. *
  51. * @var int
  52. */
  53. private $ttl;
  54. /**
  55. * Maximum cached message size
  56. *
  57. * @var int
  58. */
  59. private $threshold;
  60. /**
  61. * Internal (in-memory) cache
  62. *
  63. * @var array
  64. */
  65. private $icache = array();
  66. private $skip_deleted = false;
  67. private $mode;
  68. /**
  69. * List of known flags. Thanks to this we can handle flag changes
  70. * with good performance. Bad thing is we need to know used flags.
  71. */
  72. public $flags = array(
  73. 1 => 'SEEN', // RFC3501
  74. 2 => 'DELETED', // RFC3501
  75. 4 => 'ANSWERED', // RFC3501
  76. 8 => 'FLAGGED', // RFC3501
  77. 16 => 'DRAFT', // RFC3501
  78. 32 => 'MDNSENT', // RFC3503
  79. 64 => 'FORWARDED', // RFC5550
  80. 128 => 'SUBMITPENDING', // RFC5550
  81. 256 => 'SUBMITTED', // RFC5550
  82. 512 => 'JUNK',
  83. 1024 => 'NONJUNK',
  84. 2048 => 'LABEL1',
  85. 4096 => 'LABEL2',
  86. 8192 => 'LABEL3',
  87. 16384 => 'LABEL4',
  88. 32768 => 'LABEL5',
  89. );
  90. /**
  91. * Object constructor.
  92. *
  93. * @param rcube_db $db DB handler
  94. * @param rcube_imap $imap IMAP handler
  95. * @param int $userid User identifier
  96. * @param bool $skip_deleted skip_deleted flag
  97. * @param string $ttl Expiration time of memcache/apc items
  98. * @param int $threshold Maximum cached message size
  99. */
  100. function __construct($db, $imap, $userid, $skip_deleted, $ttl=0, $threshold=0)
  101. {
  102. // convert ttl string to seconds
  103. $ttl = get_offset_sec($ttl);
  104. if ($ttl > 2592000) $ttl = 2592000;
  105. $this->db = $db;
  106. $this->imap = $imap;
  107. $this->userid = $userid;
  108. $this->skip_deleted = $skip_deleted;
  109. $this->ttl = $ttl;
  110. $this->threshold = $threshold;
  111. // cache all possible information by default
  112. $this->mode = self::MODE_INDEX | self::MODE_MESSAGE;
  113. // database tables
  114. $this->index_table = $db->table_name('cache_index', true);
  115. $this->thread_table = $db->table_name('cache_thread', true);
  116. $this->messages_table = $db->table_name('cache_messages', true);
  117. }
  118. /**
  119. * Cleanup actions (on shutdown).
  120. */
  121. public function close()
  122. {
  123. $this->save_icache();
  124. $this->icache = null;
  125. }
  126. /**
  127. * Set cache mode
  128. *
  129. * @param int $mode Cache mode
  130. */
  131. public function set_mode($mode)
  132. {
  133. $this->mode = $mode;
  134. }
  135. /**
  136. * Return (sorted) messages index (UIDs).
  137. * If index doesn't exist or is invalid, will be updated.
  138. *
  139. * @param string $mailbox Folder name
  140. * @param string $sort_field Sorting column
  141. * @param string $sort_order Sorting order (ASC|DESC)
  142. * @param bool $exiting Skip index initialization if it doesn't exist in DB
  143. *
  144. * @return array Messages index
  145. */
  146. function get_index($mailbox, $sort_field = null, $sort_order = null, $existing = false)
  147. {
  148. if (empty($this->icache[$mailbox])) {
  149. $this->icache[$mailbox] = array();
  150. }
  151. $sort_order = strtoupper($sort_order) == 'ASC' ? 'ASC' : 'DESC';
  152. // Seek in internal cache
  153. if (array_key_exists('index', $this->icache[$mailbox])) {
  154. // The index was fetched from database already, but not validated yet
  155. if (empty($this->icache[$mailbox]['index']['validated'])) {
  156. $index = $this->icache[$mailbox]['index'];
  157. }
  158. // We've got a valid index
  159. else if ($sort_field == 'ANY' || $this->icache[$mailbox]['index']['sort_field'] == $sort_field) {
  160. $result = $this->icache[$mailbox]['index']['object'];
  161. if ($result->get_parameters('ORDER') != $sort_order) {
  162. $result->revert();
  163. }
  164. return $result;
  165. }
  166. }
  167. // Get index from DB (if DB wasn't already queried)
  168. if (empty($index) && empty($this->icache[$mailbox]['index_queried'])) {
  169. $index = $this->get_index_row($mailbox);
  170. // set the flag that DB was already queried for index
  171. // this way we'll be able to skip one SELECT, when
  172. // get_index() is called more than once
  173. $this->icache[$mailbox]['index_queried'] = true;
  174. }
  175. $data = null;
  176. // @TODO: Think about skipping validation checks.
  177. // If we could check only every 10 minutes, we would be able to skip
  178. // expensive checks, mailbox selection or even IMAP connection, this would require
  179. // additional logic to force cache invalidation in some cases
  180. // and many rcube_imap changes to connect when needed
  181. // Entry exists, check cache status
  182. if (!empty($index)) {
  183. $exists = true;
  184. if ($sort_field == 'ANY') {
  185. $sort_field = $index['sort_field'];
  186. }
  187. if ($sort_field != $index['sort_field']) {
  188. $is_valid = false;
  189. }
  190. else {
  191. $is_valid = $this->validate($mailbox, $index, $exists);
  192. }
  193. if ($is_valid) {
  194. $data = $index['object'];
  195. // revert the order if needed
  196. if ($data->get_parameters('ORDER') != $sort_order) {
  197. $data->revert();
  198. }
  199. }
  200. }
  201. else {
  202. if ($existing) {
  203. return null;
  204. }
  205. else if ($sort_field == 'ANY') {
  206. $sort_field = '';
  207. }
  208. // Got it in internal cache, so the row already exist
  209. $exists = array_key_exists('index', $this->icache[$mailbox]);
  210. }
  211. // Index not found, not valid or sort field changed, get index from IMAP server
  212. if ($data === null) {
  213. // Get mailbox data (UIDVALIDITY, counters, etc.) for status check
  214. $mbox_data = $this->imap->folder_data($mailbox);
  215. $data = $this->get_index_data($mailbox, $sort_field, $sort_order, $mbox_data);
  216. // insert/update
  217. $this->add_index_row($mailbox, $sort_field, $data, $mbox_data, $exists, $index['modseq']);
  218. }
  219. $this->icache[$mailbox]['index'] = array(
  220. 'validated' => true,
  221. 'object' => $data,
  222. 'sort_field' => $sort_field,
  223. 'modseq' => !empty($index['modseq']) ? $index['modseq'] : $mbox_data['HIGHESTMODSEQ']
  224. );
  225. return $data;
  226. }
  227. /**
  228. * Return messages thread.
  229. * If threaded index doesn't exist or is invalid, will be updated.
  230. *
  231. * @param string $mailbox Folder name
  232. *
  233. * @return array Messages threaded index
  234. */
  235. function get_thread($mailbox)
  236. {
  237. if (empty($this->icache[$mailbox])) {
  238. $this->icache[$mailbox] = array();
  239. }
  240. // Seek in internal cache
  241. if (array_key_exists('thread', $this->icache[$mailbox])) {
  242. return $this->icache[$mailbox]['thread']['object'];
  243. }
  244. // Get thread from DB (if DB wasn't already queried)
  245. if (empty($this->icache[$mailbox]['thread_queried'])) {
  246. $index = $this->get_thread_row($mailbox);
  247. // set the flag that DB was already queried for thread
  248. // this way we'll be able to skip one SELECT, when
  249. // get_thread() is called more than once or after clear()
  250. $this->icache[$mailbox]['thread_queried'] = true;
  251. }
  252. // Entry exist, check cache status
  253. if (!empty($index)) {
  254. $exists = true;
  255. $is_valid = $this->validate($mailbox, $index, $exists);
  256. if (!$is_valid) {
  257. $index = null;
  258. }
  259. }
  260. // Index not found or not valid, get index from IMAP server
  261. if ($index === null) {
  262. // Get mailbox data (UIDVALIDITY, counters, etc.) for status check
  263. $mbox_data = $this->imap->folder_data($mailbox);
  264. // Get THREADS result
  265. $index['object'] = $this->get_thread_data($mailbox, $mbox_data);
  266. // insert/update
  267. $this->add_thread_row($mailbox, $index['object'], $mbox_data, $exists);
  268. }
  269. $this->icache[$mailbox]['thread'] = $index;
  270. return $index['object'];
  271. }
  272. /**
  273. * Returns list of messages (headers). See rcube_imap::fetch_headers().
  274. *
  275. * @param string $mailbox Folder name
  276. * @param array $msgs Message UIDs
  277. *
  278. * @return array The list of messages (rcube_message_header) indexed by UID
  279. */
  280. function get_messages($mailbox, $msgs = array())
  281. {
  282. if (empty($msgs)) {
  283. return array();
  284. }
  285. $result = array();
  286. if ($this->mode & self::MODE_MESSAGE) {
  287. // Fetch messages from cache
  288. $sql_result = $this->db->query(
  289. "SELECT `uid`, `data`, `flags`"
  290. ." FROM {$this->messages_table}"
  291. ." WHERE `user_id` = ?"
  292. ." AND `mailbox` = ?"
  293. ." AND `uid` IN (".$this->db->array2list($msgs, 'integer').")",
  294. $this->userid, $mailbox);
  295. $msgs = array_flip($msgs);
  296. while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  297. $uid = intval($sql_arr['uid']);
  298. $result[$uid] = $this->build_message($sql_arr);
  299. if (!empty($result[$uid])) {
  300. // save memory, we don't need message body here (?)
  301. $result[$uid]->body = null;
  302. unset($msgs[$uid]);
  303. }
  304. }
  305. $this->db->reset();
  306. $msgs = array_flip($msgs);
  307. }
  308. // Fetch not found messages from IMAP server
  309. if (!empty($msgs)) {
  310. $messages = $this->imap->fetch_headers($mailbox, $msgs, false, true);
  311. // Insert to DB and add to result list
  312. if (!empty($messages)) {
  313. foreach ($messages as $msg) {
  314. if ($this->mode & self::MODE_MESSAGE) {
  315. $this->add_message($mailbox, $msg, !array_key_exists($msg->uid, $result));
  316. }
  317. $result[$msg->uid] = $msg;
  318. }
  319. }
  320. }
  321. return $result;
  322. }
  323. /**
  324. * Returns message data.
  325. *
  326. * @param string $mailbox Folder name
  327. * @param int $uid Message UID
  328. * @param bool $update If message doesn't exists in cache it will be fetched
  329. * from IMAP server
  330. * @param bool $no_cache Enables internal cache usage
  331. *
  332. * @return rcube_message_header Message data
  333. */
  334. function get_message($mailbox, $uid, $update = true, $cache = true)
  335. {
  336. // Check internal cache
  337. if ($this->icache['__message']
  338. && $this->icache['__message']['mailbox'] == $mailbox
  339. && $this->icache['__message']['object']->uid == $uid
  340. ) {
  341. return $this->icache['__message']['object'];
  342. }
  343. if ($this->mode & self::MODE_MESSAGE) {
  344. $sql_result = $this->db->query(
  345. "SELECT `flags`, `data`"
  346. ." FROM {$this->messages_table}"
  347. ." WHERE `user_id` = ?"
  348. ." AND `mailbox` = ?"
  349. ." AND `uid` = ?",
  350. $this->userid, $mailbox, (int)$uid);
  351. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  352. $message = $this->build_message($sql_arr);
  353. $found = true;
  354. }
  355. }
  356. // Get the message from IMAP server
  357. if (empty($message) && $update) {
  358. $message = $this->imap->get_message_headers($uid, $mailbox, true);
  359. // cache will be updated in close(), see below
  360. }
  361. if (!($this->mode & self::MODE_MESSAGE)) {
  362. return $message;
  363. }
  364. // Save the message in internal cache, will be written to DB in close()
  365. // Common scenario: user opens unseen message
  366. // - get message (SELECT)
  367. // - set message headers/structure (INSERT or UPDATE)
  368. // - set \Seen flag (UPDATE)
  369. // This way we can skip one UPDATE
  370. if (!empty($message) && $cache) {
  371. // Save current message from internal cache
  372. $this->save_icache();
  373. $this->icache['__message'] = array(
  374. 'object' => $message,
  375. 'mailbox' => $mailbox,
  376. 'exists' => $found,
  377. 'md5sum' => md5(serialize($message)),
  378. );
  379. }
  380. return $message;
  381. }
  382. /**
  383. * Saves the message in cache.
  384. *
  385. * @param string $mailbox Folder name
  386. * @param rcube_message_header $message Message data
  387. * @param bool $force Skips message in-cache existence check
  388. */
  389. function add_message($mailbox, $message, $force = false)
  390. {
  391. if (!is_object($message) || empty($message->uid)) {
  392. return;
  393. }
  394. if (!($this->mode & self::MODE_MESSAGE)) {
  395. return;
  396. }
  397. $flags = 0;
  398. $msg = clone $message;
  399. if (!empty($message->flags)) {
  400. foreach ($this->flags as $idx => $flag) {
  401. if (!empty($message->flags[$flag])) {
  402. $flags += $idx;
  403. }
  404. }
  405. }
  406. unset($msg->flags);
  407. $msg = $this->db->encode($msg, true);
  408. // update cache record (even if it exists, the update
  409. // here will work as select, assume row exist if affected_rows=0)
  410. if (!$force) {
  411. $res = $this->db->query(
  412. "UPDATE {$this->messages_table}"
  413. ." SET `flags` = ?, `data` = ?, `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  414. ." WHERE `user_id` = ?"
  415. ." AND `mailbox` = ?"
  416. ." AND `uid` = ?",
  417. $flags, $msg, $this->userid, $mailbox, (int) $message->uid);
  418. if ($this->db->affected_rows($res)) {
  419. return;
  420. }
  421. }
  422. $this->db->set_option('ignore_key_errors', true);
  423. // insert new record
  424. $res = $this->db->query(
  425. "INSERT INTO {$this->messages_table}"
  426. ." (`user_id`, `mailbox`, `uid`, `flags`, `expires`, `data`)"
  427. ." VALUES (?, ?, ?, ?, ". ($this->ttl ? $this->db->now($this->ttl) : 'NULL') . ", ?)",
  428. $this->userid, $mailbox, (int) $message->uid, $flags, $msg);
  429. // race-condition, insert failed so try update (#1489146)
  430. // thanks to ignore_key_errors "duplicate row" errors will be ignored
  431. if ($force && !$res && !$this->db->is_error($res)) {
  432. $this->db->query(
  433. "UPDATE {$this->messages_table}"
  434. ." SET `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  435. .", `flags` = ?, `data` = ?"
  436. ." WHERE `user_id` = ?"
  437. ." AND `mailbox` = ?"
  438. ." AND `uid` = ?",
  439. $flags, $msg, $this->userid, $mailbox, (int) $message->uid);
  440. }
  441. $this->db->set_option('ignore_key_errors', false);
  442. }
  443. /**
  444. * Sets the flag for specified message.
  445. *
  446. * @param string $mailbox Folder name
  447. * @param array $uids Message UIDs or null to change flag
  448. * of all messages in a folder
  449. * @param string $flag The name of the flag
  450. * @param bool $enabled Flag state
  451. */
  452. function change_flag($mailbox, $uids, $flag, $enabled = false)
  453. {
  454. if (empty($uids)) {
  455. return;
  456. }
  457. if (!($this->mode & self::MODE_MESSAGE)) {
  458. return;
  459. }
  460. $flag = strtoupper($flag);
  461. $idx = (int) array_search($flag, $this->flags);
  462. $uids = (array) $uids;
  463. if (!$idx) {
  464. return;
  465. }
  466. // Internal cache update
  467. if (($message = $this->icache['__message'])
  468. && $message['mailbox'] === $mailbox
  469. && in_array($message['object']->uid, $uids)
  470. ) {
  471. $message['object']->flags[$flag] = $enabled;
  472. if (count($uids) == 1) {
  473. return;
  474. }
  475. }
  476. $binary_check = $this->db->db_provider == 'oracle' ? "BITAND(`flags`, %d)" : "(`flags` & %d)";
  477. $this->db->query(
  478. "UPDATE {$this->messages_table}"
  479. ." SET `expires` = ". ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  480. .", `flags` = `flags` ".($enabled ? "+ $idx" : "- $idx")
  481. ." WHERE `user_id` = ?"
  482. ." AND `mailbox` = ?"
  483. .(!empty($uids) ? " AND `uid` IN (".$this->db->array2list($uids, 'integer').")" : "")
  484. ." AND " . sprintf($binary_check, $idx) . ($enabled ? " = 0" : " = $idx"),
  485. $this->userid, $mailbox);
  486. }
  487. /**
  488. * Removes message(s) from cache.
  489. *
  490. * @param string $mailbox Folder name
  491. * @param array $uids Message UIDs, NULL removes all messages
  492. */
  493. function remove_message($mailbox = null, $uids = null)
  494. {
  495. if (!($this->mode & self::MODE_MESSAGE)) {
  496. return;
  497. }
  498. if (!strlen($mailbox)) {
  499. $this->db->query(
  500. "DELETE FROM {$this->messages_table}"
  501. ." WHERE `user_id` = ?",
  502. $this->userid);
  503. }
  504. else {
  505. // Remove the message from internal cache
  506. if (!empty($uids) && ($message = $this->icache['__message'])
  507. && $message['mailbox'] === $mailbox
  508. && in_array($message['object']->uid, (array)$uids)
  509. ) {
  510. $this->icache['__message'] = null;
  511. }
  512. $this->db->query(
  513. "DELETE FROM {$this->messages_table}"
  514. ." WHERE `user_id` = ?"
  515. ." AND `mailbox` = ?"
  516. .($uids !== null ? " AND `uid` IN (".$this->db->array2list((array)$uids, 'integer').")" : ""),
  517. $this->userid, $mailbox);
  518. }
  519. }
  520. /**
  521. * Clears index cache.
  522. *
  523. * @param string $mailbox Folder name
  524. * @param bool $remove Enable to remove the DB row
  525. */
  526. function remove_index($mailbox = null, $remove = false)
  527. {
  528. // The index should be only removed from database when
  529. // UIDVALIDITY was detected or the mailbox is empty
  530. // otherwise use 'valid' flag to not loose HIGHESTMODSEQ value
  531. if ($remove) {
  532. $this->db->query(
  533. "DELETE FROM {$this->index_table}"
  534. ." WHERE `user_id` = ?"
  535. .(strlen($mailbox) ? " AND `mailbox` = ".$this->db->quote($mailbox) : ""),
  536. $this->userid
  537. );
  538. }
  539. else {
  540. $this->db->query(
  541. "UPDATE {$this->index_table}"
  542. ." SET `valid` = 0"
  543. ." WHERE `user_id` = ?"
  544. .(strlen($mailbox) ? " AND `mailbox` = ".$this->db->quote($mailbox) : ""),
  545. $this->userid
  546. );
  547. }
  548. if (strlen($mailbox)) {
  549. unset($this->icache[$mailbox]['index']);
  550. // Index removed, set flag to skip SELECT query in get_index()
  551. $this->icache[$mailbox]['index_queried'] = true;
  552. }
  553. else {
  554. $this->icache = array();
  555. }
  556. }
  557. /**
  558. * Clears thread cache.
  559. *
  560. * @param string $mailbox Folder name
  561. */
  562. function remove_thread($mailbox = null)
  563. {
  564. $this->db->query(
  565. "DELETE FROM {$this->thread_table}"
  566. ." WHERE `user_id` = ?"
  567. .(strlen($mailbox) ? " AND `mailbox` = ".$this->db->quote($mailbox) : ""),
  568. $this->userid
  569. );
  570. if (strlen($mailbox)) {
  571. unset($this->icache[$mailbox]['thread']);
  572. // Thread data removed, set flag to skip SELECT query in get_thread()
  573. $this->icache[$mailbox]['thread_queried'] = true;
  574. }
  575. else {
  576. $this->icache = array();
  577. }
  578. }
  579. /**
  580. * Clears the cache.
  581. *
  582. * @param string $mailbox Folder name
  583. * @param array $uids Message UIDs, NULL removes all messages in a folder
  584. */
  585. function clear($mailbox = null, $uids = null)
  586. {
  587. $this->remove_index($mailbox, true);
  588. $this->remove_thread($mailbox);
  589. $this->remove_message($mailbox, $uids);
  590. }
  591. /**
  592. * Delete expired cache entries
  593. */
  594. static function gc()
  595. {
  596. $rcube = rcube::get_instance();
  597. $db = $rcube->get_dbh();
  598. $now = $db->now();
  599. $db->query("DELETE FROM " . $db->table_name('cache_messages', true)
  600. ." WHERE `expires` < $now");
  601. $db->query("DELETE FROM " . $db->table_name('cache_index', true)
  602. ." WHERE `expires` < $now");
  603. $db->query("DELETE FROM ".$db->table_name('cache_thread', true)
  604. ." WHERE `expires` < $now");
  605. }
  606. /**
  607. * Fetches index data from database
  608. */
  609. private function get_index_row($mailbox)
  610. {
  611. // Get index from DB
  612. $sql_result = $this->db->query(
  613. "SELECT `data`, `valid`"
  614. ." FROM {$this->index_table}"
  615. ." WHERE `user_id` = ?"
  616. ." AND `mailbox` = ?",
  617. $this->userid, $mailbox);
  618. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  619. $data = explode('@', $sql_arr['data']);
  620. $index = $this->db->decode($data[0], true);
  621. unset($data[0]);
  622. if (empty($index)) {
  623. $index = new rcube_result_index($mailbox);
  624. }
  625. return array(
  626. 'valid' => $sql_arr['valid'],
  627. 'object' => $index,
  628. 'sort_field' => $data[1],
  629. 'deleted' => $data[2],
  630. 'validity' => $data[3],
  631. 'uidnext' => $data[4],
  632. 'modseq' => $data[5],
  633. );
  634. }
  635. return null;
  636. }
  637. /**
  638. * Fetches thread data from database
  639. */
  640. private function get_thread_row($mailbox)
  641. {
  642. // Get thread from DB
  643. $sql_result = $this->db->query(
  644. "SELECT `data`"
  645. ." FROM {$this->thread_table}"
  646. ." WHERE `user_id` = ?"
  647. ." AND `mailbox` = ?",
  648. $this->userid, $mailbox);
  649. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  650. $data = explode('@', $sql_arr['data']);
  651. $thread = $this->db->decode($data[0], true);
  652. unset($data[0]);
  653. if (empty($thread)) {
  654. $thread = new rcube_result_thread($mailbox);
  655. }
  656. return array(
  657. 'object' => $thread,
  658. 'deleted' => $data[1],
  659. 'validity' => $data[2],
  660. 'uidnext' => $data[3],
  661. );
  662. }
  663. return null;
  664. }
  665. /**
  666. * Saves index data into database
  667. */
  668. private function add_index_row($mailbox, $sort_field,
  669. $data, $mbox_data = array(), $exists = false, $modseq = null)
  670. {
  671. $data = array(
  672. $this->db->encode($data, true),
  673. $sort_field,
  674. (int) $this->skip_deleted,
  675. (int) $mbox_data['UIDVALIDITY'],
  676. (int) $mbox_data['UIDNEXT'],
  677. $modseq ? $modseq : $mbox_data['HIGHESTMODSEQ'],
  678. );
  679. $data = implode('@', $data);
  680. $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';
  681. if ($exists) {
  682. $res = $this->db->query(
  683. "UPDATE {$this->index_table}"
  684. ." SET `data` = ?, `valid` = 1, `expires` = $expires"
  685. ." WHERE `user_id` = ?"
  686. ." AND `mailbox` = ?",
  687. $data, $this->userid, $mailbox);
  688. if ($this->db->affected_rows($res)) {
  689. return;
  690. }
  691. }
  692. $this->db->set_option('ignore_key_errors', true);
  693. $res = $this->db->query(
  694. "INSERT INTO {$this->index_table}"
  695. ." (`user_id`, `mailbox`, `valid`, `expires`, `data`)"
  696. ." VALUES (?, ?, 1, $expires, ?)",
  697. $this->userid, $mailbox, $data);
  698. // race-condition, insert failed so try update (#1489146)
  699. // thanks to ignore_key_errors "duplicate row" errors will be ignored
  700. if (!$exists && !$res && !$this->db->is_error($res)) {
  701. $res = $this->db->query(
  702. "UPDATE {$this->index_table}"
  703. ." SET `data` = ?, `valid` = 1, `expires` = $expires"
  704. ." WHERE `user_id` = ?"
  705. ." AND `mailbox` = ?",
  706. $data, $this->userid, $mailbox);
  707. }
  708. $this->db->set_option('ignore_key_errors', false);
  709. }
  710. /**
  711. * Saves thread data into database
  712. */
  713. private function add_thread_row($mailbox, $data, $mbox_data = array(), $exists = false)
  714. {
  715. $data = array(
  716. $this->db->encode($data, true),
  717. (int) $this->skip_deleted,
  718. (int) $mbox_data['UIDVALIDITY'],
  719. (int) $mbox_data['UIDNEXT'],
  720. );
  721. $data = implode('@', $data);
  722. $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';
  723. if ($exists) {
  724. $res = $this->db->query(
  725. "UPDATE {$this->thread_table}"
  726. ." SET `data` = ?, `expires` = $expires"
  727. ." WHERE `user_id` = ?"
  728. ." AND `mailbox` = ?",
  729. $data, $this->userid, $mailbox);
  730. if ($this->db->affected_rows($res)) {
  731. return;
  732. }
  733. }
  734. $this->db->set_option('ignore_key_errors', true);
  735. $res = $this->db->query(
  736. "INSERT INTO {$this->thread_table}"
  737. ." (`user_id`, `mailbox`, `expires`, `data`)"
  738. ." VALUES (?, ?, $expires, ?)",
  739. $this->userid, $mailbox, $data);
  740. // race-condition, insert failed so try update (#1489146)
  741. // thanks to ignore_key_errors "duplicate row" errors will be ignored
  742. if (!$exists && !$res && !$this->db->is_error($res)) {
  743. $this->db->query(
  744. "UPDATE {$this->thread_table}"
  745. ." SET `expires` = $expires, `data` = ?"
  746. ." WHERE `user_id` = ?"
  747. ." AND `mailbox` = ?",
  748. $data, $this->userid, $mailbox);
  749. }
  750. $this->db->set_option('ignore_key_errors', false);
  751. }
  752. /**
  753. * Checks index/thread validity
  754. */
  755. private function validate($mailbox, $index, &$exists = true)
  756. {
  757. $object = $index['object'];
  758. $is_thread = is_a($object, 'rcube_result_thread');
  759. // sanity check
  760. if (empty($object)) {
  761. return false;
  762. }
  763. $index['validated'] = true;
  764. // Get mailbox data (UIDVALIDITY, counters, etc.) for status check
  765. $mbox_data = $this->imap->folder_data($mailbox);
  766. // @TODO: Think about skipping validation checks.
  767. // If we could check only every 10 minutes, we would be able to skip
  768. // expensive checks, mailbox selection or even IMAP connection, this would require
  769. // additional logic to force cache invalidation in some cases
  770. // and many rcube_imap changes to connect when needed
  771. // Check UIDVALIDITY
  772. if ($index['validity'] != $mbox_data['UIDVALIDITY']) {
  773. $this->clear($mailbox);
  774. $exists = false;
  775. return false;
  776. }
  777. // Folder is empty but cache isn't
  778. if (empty($mbox_data['EXISTS'])) {
  779. if (!$object->is_empty()) {
  780. $this->clear($mailbox);
  781. $exists = false;
  782. return false;
  783. }
  784. }
  785. // Folder is not empty but cache is
  786. else if ($object->is_empty()) {
  787. unset($this->icache[$mailbox][$is_thread ? 'thread' : 'index']);
  788. return false;
  789. }
  790. // Validation flag
  791. if (!$is_thread && empty($index['valid'])) {
  792. unset($this->icache[$mailbox]['index']);
  793. return false;
  794. }
  795. // Index was created with different skip_deleted setting
  796. if ($this->skip_deleted != $index['deleted']) {
  797. return false;
  798. }
  799. // Check HIGHESTMODSEQ
  800. if (!empty($index['modseq']) && !empty($mbox_data['HIGHESTMODSEQ'])
  801. && $index['modseq'] == $mbox_data['HIGHESTMODSEQ']
  802. ) {
  803. return true;
  804. }
  805. // Check UIDNEXT
  806. if ($index['uidnext'] != $mbox_data['UIDNEXT']) {
  807. unset($this->icache[$mailbox][$is_thread ? 'thread' : 'index']);
  808. return false;
  809. }
  810. // @TODO: find better validity check for threaded index
  811. if ($is_thread) {
  812. // check messages number...
  813. if (!$this->skip_deleted && $mbox_data['EXISTS'] != $object->count_messages()) {
  814. return false;
  815. }
  816. return true;
  817. }
  818. // The rest of checks, more expensive
  819. if (!empty($this->skip_deleted)) {
  820. // compare counts if available
  821. if (!empty($mbox_data['UNDELETED'])
  822. && $mbox_data['UNDELETED']->count() != $object->count()
  823. ) {
  824. return false;
  825. }
  826. // compare UID sets
  827. if (!empty($mbox_data['UNDELETED'])) {
  828. $uids_new = $mbox_data['UNDELETED']->get();
  829. $uids_old = $object->get();
  830. if (count($uids_new) != count($uids_old)) {
  831. return false;
  832. }
  833. sort($uids_new, SORT_NUMERIC);
  834. sort($uids_old, SORT_NUMERIC);
  835. if ($uids_old != $uids_new)
  836. return false;
  837. }
  838. else {
  839. // get all undeleted messages excluding cached UIDs
  840. $ids = $this->imap->search_once($mailbox, 'ALL UNDELETED NOT UID '.
  841. rcube_imap_generic::compressMessageSet($object->get()));
  842. if (!$ids->is_empty()) {
  843. return false;
  844. }
  845. }
  846. }
  847. else {
  848. // check messages number...
  849. if ($mbox_data['EXISTS'] != $object->count()) {
  850. return false;
  851. }
  852. // ... and max UID
  853. if ($object->max() != $this->imap->id2uid($mbox_data['EXISTS'], $mailbox)) {
  854. return false;
  855. }
  856. }
  857. return true;
  858. }
  859. /**
  860. * Synchronizes the mailbox.
  861. *
  862. * @param string $mailbox Folder name
  863. */
  864. function synchronize($mailbox)
  865. {
  866. // RFC4549: Synchronization Operations for Disconnected IMAP4 Clients
  867. // RFC4551: IMAP Extension for Conditional STORE Operation
  868. // or Quick Flag Changes Resynchronization
  869. // RFC5162: IMAP Extensions for Quick Mailbox Resynchronization
  870. // @TODO: synchronize with other methods?
  871. $qresync = $this->imap->get_capability('QRESYNC');
  872. $condstore = $qresync ? true : $this->imap->get_capability('CONDSTORE');
  873. if (!$qresync && !$condstore) {
  874. return;
  875. }
  876. // Get stored index
  877. $index = $this->get_index_row($mailbox);
  878. // database is empty
  879. if (empty($index)) {
  880. // set the flag that DB was already queried for index
  881. // this way we'll be able to skip one SELECT in get_index()
  882. $this->icache[$mailbox]['index_queried'] = true;
  883. return;
  884. }
  885. $this->icache[$mailbox]['index'] = $index;
  886. // no last HIGHESTMODSEQ value
  887. if (empty($index['modseq'])) {
  888. return;
  889. }
  890. if (!$this->imap->check_connection()) {
  891. return;
  892. }
  893. // Enable QRESYNC
  894. $res = $this->imap->conn->enable($qresync ? 'QRESYNC' : 'CONDSTORE');
  895. if ($res === false) {
  896. return;
  897. }
  898. // Close mailbox if already selected to get most recent data
  899. if ($this->imap->conn->selected == $mailbox) {
  900. $this->imap->conn->close();
  901. }
  902. // Get mailbox data (UIDVALIDITY, HIGHESTMODSEQ, counters, etc.)
  903. $mbox_data = $this->imap->folder_data($mailbox);
  904. if (empty($mbox_data)) {
  905. return;
  906. }
  907. // Check UIDVALIDITY
  908. if ($index['validity'] != $mbox_data['UIDVALIDITY']) {
  909. $this->clear($mailbox);
  910. return;
  911. }
  912. // QRESYNC not supported on specified mailbox
  913. if (!empty($mbox_data['NOMODSEQ']) || empty($mbox_data['HIGHESTMODSEQ'])) {
  914. return;
  915. }
  916. // Nothing new
  917. if ($mbox_data['HIGHESTMODSEQ'] == $index['modseq']) {
  918. return;
  919. }
  920. $uids = array();
  921. $removed = array();
  922. // Get known UIDs
  923. if ($this->mode & self::MODE_MESSAGE) {
  924. $sql_result = $this->db->query(
  925. "SELECT `uid`"
  926. ." FROM {$this->messages_table}"
  927. ." WHERE `user_id` = ?"
  928. ." AND `mailbox` = ?",
  929. $this->userid, $mailbox);
  930. while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  931. $uids[] = $sql_arr['uid'];
  932. }
  933. }
  934. // Synchronize messages data
  935. if (!empty($uids)) {
  936. // Get modified flags and vanished messages
  937. // UID FETCH 1:* (FLAGS) (CHANGEDSINCE 0123456789 VANISHED)
  938. $result = $this->imap->conn->fetch($mailbox,
  939. $uids, true, array('FLAGS'), $index['modseq'], $qresync);
  940. if (!empty($result)) {
  941. foreach ($result as $msg) {
  942. $uid = $msg->uid;
  943. // Remove deleted message
  944. if ($this->skip_deleted && !empty($msg->flags['DELETED'])) {
  945. $removed[] = $uid;
  946. // Invalidate index
  947. $index['valid'] = false;
  948. continue;
  949. }
  950. $flags = 0;
  951. if (!empty($msg->flags)) {
  952. foreach ($this->flags as $idx => $flag) {
  953. if (!empty($msg->flags[$flag])) {
  954. $flags += $idx;
  955. }
  956. }
  957. }
  958. $this->db->query(
  959. "UPDATE {$this->messages_table}"
  960. ." SET `flags` = ?, `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  961. ." WHERE `user_id` = ?"
  962. ." AND `mailbox` = ?"
  963. ." AND `uid` = ?"
  964. ." AND `flags` <> ?",
  965. $flags, $this->userid, $mailbox, $uid, $flags);
  966. }
  967. }
  968. // VANISHED found?
  969. if ($qresync) {
  970. $mbox_data = $this->imap->folder_data($mailbox);
  971. // Removed messages found
  972. $uids = rcube_imap_generic::uncompressMessageSet($mbox_data['VANISHED']);
  973. if (!empty($uids)) {
  974. $removed = array_merge($removed, $uids);
  975. // Invalidate index
  976. $index['valid'] = false;
  977. }
  978. }
  979. // remove messages from database
  980. if (!empty($removed)) {
  981. $this->remove_message($mailbox, $removed);
  982. }
  983. }
  984. $sort_field = $index['sort_field'];
  985. $sort_order = $index['object']->get_parameters('ORDER');
  986. $exists = true;
  987. // Validate index
  988. if (!$this->validate($mailbox, $index, $exists)) {
  989. // Invalidate (remove) thread index
  990. // if $exists=false it was already removed in validate()
  991. if ($exists) {
  992. $this->remove_thread($mailbox);
  993. }
  994. // Update index
  995. $data = $this->get_index_data($mailbox, $sort_field, $sort_order, $mbox_data);
  996. }
  997. else {
  998. $data = $index['object'];
  999. }
  1000. // update index and/or HIGHESTMODSEQ value
  1001. $this->add_index_row($mailbox, $sort_field, $data, $mbox_data, $exists);
  1002. // update internal cache for get_index()
  1003. $this->icache[$mailbox]['index']['object'] = $data;
  1004. }
  1005. /**
  1006. * Converts cache row into message object.
  1007. *
  1008. * @param array $sql_arr Message row data
  1009. *
  1010. * @return rcube_message_header Message object
  1011. */
  1012. private function build_message($sql_arr)
  1013. {
  1014. $message = $this->db->decode($sql_arr['data'], true);
  1015. if ($message) {
  1016. $message->flags = array();
  1017. foreach ($this->flags as $idx => $flag) {
  1018. if (($sql_arr['flags'] & $idx) == $idx) {
  1019. $message->flags[$flag] = true;
  1020. }
  1021. }
  1022. }
  1023. return $message;
  1024. }
  1025. /**
  1026. * Saves message stored in internal cache
  1027. */
  1028. private function save_icache()
  1029. {
  1030. // Save current message from internal cache
  1031. if ($message = $this->icache['__message']) {
  1032. // clean up some object's data
  1033. $this->message_object_prepare($message['object']);
  1034. // calculate current md5 sum
  1035. $md5sum = md5(serialize($message['object']));
  1036. if ($message['md5sum'] != $md5sum) {
  1037. $this->add_message($message['mailbox'], $message['object'], !$message['exists']);
  1038. }
  1039. $this->icache['__message']['md5sum'] = $md5sum;
  1040. }
  1041. }
  1042. /**
  1043. * Prepares message object to be stored in database.
  1044. *
  1045. * @param rcube_message_header|rcube_message_part
  1046. */
  1047. private function message_object_prepare(&$msg, &$size = 0)
  1048. {
  1049. // Remove body too big
  1050. if (isset($msg->body)) {
  1051. $length = strlen($msg->body);
  1052. if ($msg->body_modified || $size + $length > $this->threshold * 1024) {
  1053. unset($msg->body);
  1054. }
  1055. else {
  1056. $size += $length;
  1057. }
  1058. }
  1059. // Fix mimetype which might be broken by some code when message is displayed
  1060. // Another solution would be to use object's copy in rcube_message class
  1061. // to prevent related issues, however I'm not sure which is better
  1062. if ($msg->mimetype) {
  1063. list($msg->ctype_primary, $msg->ctype_secondary) = explode('/', $msg->mimetype);
  1064. }
  1065. unset($msg->replaces);
  1066. if (is_object($msg->structure)) {
  1067. $this->message_object_prepare($msg->structure, $size);
  1068. }
  1069. if (is_array($msg->parts)) {
  1070. foreach ($msg->parts as $part) {
  1071. $this->message_object_prepare($part, $size);
  1072. }
  1073. }
  1074. }
  1075. /**
  1076. * Fetches index data from IMAP server
  1077. */
  1078. private function get_index_data($mailbox, $sort_field, $sort_order, $mbox_data = array())
  1079. {
  1080. if (empty($mbox_data)) {
  1081. $mbox_data = $this->imap->folder_data($mailbox);
  1082. }
  1083. if ($mbox_data['EXISTS']) {
  1084. // fetch sorted sequence numbers
  1085. $index = $this->imap->index_direct($mailbox, $sort_field, $sort_order);
  1086. }
  1087. else {
  1088. $index = new rcube_result_index($mailbox, '* SORT');
  1089. }
  1090. return $index;
  1091. }
  1092. /**
  1093. * Fetches thread data from IMAP server
  1094. */
  1095. private function get_thread_data($mailbox, $mbox_data = array())
  1096. {
  1097. if (empty($mbox_data)) {
  1098. $mbox_data = $this->imap->folder_data($mailbox);
  1099. }
  1100. if ($mbox_data['EXISTS']) {
  1101. // get all threads (default sort order)
  1102. return $this->imap->threads_direct($mailbox);
  1103. }
  1104. return new rcube_result_thread($mailbox, '* THREAD');
  1105. }
  1106. }
  1107. // for backward compat.
  1108. class rcube_mail_header extends rcube_message_header { }