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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. $msgs = array_flip($msgs);
  306. }
  307. // Fetch not found messages from IMAP server
  308. if (!empty($msgs)) {
  309. $messages = $this->imap->fetch_headers($mailbox, $msgs, false, true);
  310. // Insert to DB and add to result list
  311. if (!empty($messages)) {
  312. foreach ($messages as $msg) {
  313. if ($this->mode & self::MODE_MESSAGE) {
  314. $this->add_message($mailbox, $msg, !array_key_exists($msg->uid, $result));
  315. }
  316. $result[$msg->uid] = $msg;
  317. }
  318. }
  319. }
  320. return $result;
  321. }
  322. /**
  323. * Returns message data.
  324. *
  325. * @param string $mailbox Folder name
  326. * @param int $uid Message UID
  327. * @param bool $update If message doesn't exists in cache it will be fetched
  328. * from IMAP server
  329. * @param bool $no_cache Enables internal cache usage
  330. *
  331. * @return rcube_message_header Message data
  332. */
  333. function get_message($mailbox, $uid, $update = true, $cache = true)
  334. {
  335. // Check internal cache
  336. if ($this->icache['__message']
  337. && $this->icache['__message']['mailbox'] == $mailbox
  338. && $this->icache['__message']['object']->uid == $uid
  339. ) {
  340. return $this->icache['__message']['object'];
  341. }
  342. if ($this->mode & self::MODE_MESSAGE) {
  343. $sql_result = $this->db->query(
  344. "SELECT `flags`, `data`"
  345. ." FROM {$this->messages_table}"
  346. ." WHERE `user_id` = ?"
  347. ." AND `mailbox` = ?"
  348. ." AND `uid` = ?",
  349. $this->userid, $mailbox, (int)$uid);
  350. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  351. $message = $this->build_message($sql_arr);
  352. $found = true;
  353. }
  354. }
  355. // Get the message from IMAP server
  356. if (empty($message) && $update) {
  357. $message = $this->imap->get_message_headers($uid, $mailbox, true);
  358. // cache will be updated in close(), see below
  359. }
  360. if (!($this->mode & self::MODE_MESSAGE)) {
  361. return $message;
  362. }
  363. // Save the message in internal cache, will be written to DB in close()
  364. // Common scenario: user opens unseen message
  365. // - get message (SELECT)
  366. // - set message headers/structure (INSERT or UPDATE)
  367. // - set \Seen flag (UPDATE)
  368. // This way we can skip one UPDATE
  369. if (!empty($message) && $cache) {
  370. // Save current message from internal cache
  371. $this->save_icache();
  372. $this->icache['__message'] = array(
  373. 'object' => $message,
  374. 'mailbox' => $mailbox,
  375. 'exists' => $found,
  376. 'md5sum' => md5(serialize($message)),
  377. );
  378. }
  379. return $message;
  380. }
  381. /**
  382. * Saves the message in cache.
  383. *
  384. * @param string $mailbox Folder name
  385. * @param rcube_message_header $message Message data
  386. * @param bool $force Skips message in-cache existance check
  387. */
  388. function add_message($mailbox, $message, $force = false)
  389. {
  390. if (!is_object($message) || empty($message->uid)) {
  391. return;
  392. }
  393. if (!($this->mode & self::MODE_MESSAGE)) {
  394. return;
  395. }
  396. $flags = 0;
  397. $msg = clone $message;
  398. if (!empty($message->flags)) {
  399. foreach ($this->flags as $idx => $flag) {
  400. if (!empty($message->flags[$flag])) {
  401. $flags += $idx;
  402. }
  403. }
  404. }
  405. unset($msg->flags);
  406. $msg = $this->db->encode($msg, true);
  407. // update cache record (even if it exists, the update
  408. // here will work as select, assume row exist if affected_rows=0)
  409. if (!$force) {
  410. $res = $this->db->query(
  411. "UPDATE {$this->messages_table}"
  412. ." SET `flags` = ?, `data` = ?, `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  413. ." WHERE `user_id` = ?"
  414. ." AND `mailbox` = ?"
  415. ." AND `uid` = ?",
  416. $flags, $msg, $this->userid, $mailbox, (int) $message->uid);
  417. if ($this->db->affected_rows($res)) {
  418. return;
  419. }
  420. }
  421. $this->db->set_option('ignore_key_errors', true);
  422. // insert new record
  423. $res = $this->db->query(
  424. "INSERT INTO {$this->messages_table}"
  425. ." (`user_id`, `mailbox`, `uid`, `flags`, `expires`, `data`)"
  426. ." VALUES (?, ?, ?, ?, ". ($this->ttl ? $this->db->now($this->ttl) : 'NULL') . ", ?)",
  427. $this->userid, $mailbox, (int) $message->uid, $flags, $msg);
  428. // race-condition, insert failed so try update (#1489146)
  429. // thanks to ignore_key_errors "duplicate row" errors will be ignored
  430. if ($force && !$res && !$this->db->is_error($res)) {
  431. $this->db->query(
  432. "UPDATE {$this->messages_table}"
  433. ." SET `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  434. .", `flags` = ?, `data` = ?"
  435. ." WHERE `user_id` = ?"
  436. ." AND `mailbox` = ?"
  437. ." AND `uid` = ?",
  438. $flags, $msg, $this->userid, $mailbox, (int) $message->uid);
  439. }
  440. $this->db->set_option('ignore_key_errors', false);
  441. }
  442. /**
  443. * Sets the flag for specified message.
  444. *
  445. * @param string $mailbox Folder name
  446. * @param array $uids Message UIDs or null to change flag
  447. * of all messages in a folder
  448. * @param string $flag The name of the flag
  449. * @param bool $enabled Flag state
  450. */
  451. function change_flag($mailbox, $uids, $flag, $enabled = false)
  452. {
  453. if (empty($uids)) {
  454. return;
  455. }
  456. if (!($this->mode & self::MODE_MESSAGE)) {
  457. return;
  458. }
  459. $flag = strtoupper($flag);
  460. $idx = (int) array_search($flag, $this->flags);
  461. $uids = (array) $uids;
  462. if (!$idx) {
  463. return;
  464. }
  465. // Internal cache update
  466. if (($message = $this->icache['__message'])
  467. && $message['mailbox'] === $mailbox
  468. && in_array($message['object']->uid, $uids)
  469. ) {
  470. $message['object']->flags[$flag] = $enabled;
  471. if (count($uids) == 1) {
  472. return;
  473. }
  474. }
  475. $binary_check = $this->db->db_provider == 'oracle' ? "BITAND(`flags`, %d)" : "(`flags` & %d)";
  476. $this->db->query(
  477. "UPDATE {$this->messages_table}"
  478. ." SET `expires` = ". ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  479. .", `flags` = `flags` ".($enabled ? "+ $idx" : "- $idx")
  480. ." WHERE `user_id` = ?"
  481. ." AND `mailbox` = ?"
  482. .(!empty($uids) ? " AND `uid` IN (".$this->db->array2list($uids, 'integer').")" : "")
  483. ." AND " . sprintf($binary_check, $idx) . ($enabled ? " = 0" : " = $idx"),
  484. $this->userid, $mailbox);
  485. }
  486. /**
  487. * Removes message(s) from cache.
  488. *
  489. * @param string $mailbox Folder name
  490. * @param array $uids Message UIDs, NULL removes all messages
  491. */
  492. function remove_message($mailbox = null, $uids = null)
  493. {
  494. if (!($this->mode & self::MODE_MESSAGE)) {
  495. return;
  496. }
  497. if (!strlen($mailbox)) {
  498. $this->db->query(
  499. "DELETE FROM {$this->messages_table}"
  500. ." WHERE `user_id` = ?",
  501. $this->userid);
  502. }
  503. else {
  504. // Remove the message from internal cache
  505. if (!empty($uids) && ($message = $this->icache['__message'])
  506. && $message['mailbox'] === $mailbox
  507. && in_array($message['object']->uid, (array)$uids)
  508. ) {
  509. $this->icache['__message'] = null;
  510. }
  511. $this->db->query(
  512. "DELETE FROM {$this->messages_table}"
  513. ." WHERE `user_id` = ?"
  514. ." AND `mailbox` = ?"
  515. .($uids !== null ? " AND `uid` IN (".$this->db->array2list((array)$uids, 'integer').")" : ""),
  516. $this->userid, $mailbox);
  517. }
  518. }
  519. /**
  520. * Clears index cache.
  521. *
  522. * @param string $mailbox Folder name
  523. * @param bool $remove Enable to remove the DB row
  524. */
  525. function remove_index($mailbox = null, $remove = false)
  526. {
  527. // The index should be only removed from database when
  528. // UIDVALIDITY was detected or the mailbox is empty
  529. // otherwise use 'valid' flag to not loose HIGHESTMODSEQ value
  530. if ($remove) {
  531. $this->db->query(
  532. "DELETE FROM {$this->index_table}"
  533. ." WHERE `user_id` = ?"
  534. .(strlen($mailbox) ? " AND `mailbox` = ".$this->db->quote($mailbox) : ""),
  535. $this->userid
  536. );
  537. }
  538. else {
  539. $this->db->query(
  540. "UPDATE {$this->index_table}"
  541. ." SET `valid` = 0"
  542. ." WHERE `user_id` = ?"
  543. .(strlen($mailbox) ? " AND `mailbox` = ".$this->db->quote($mailbox) : ""),
  544. $this->userid
  545. );
  546. }
  547. if (strlen($mailbox)) {
  548. unset($this->icache[$mailbox]['index']);
  549. // Index removed, set flag to skip SELECT query in get_index()
  550. $this->icache[$mailbox]['index_queried'] = true;
  551. }
  552. else {
  553. $this->icache = array();
  554. }
  555. }
  556. /**
  557. * Clears thread cache.
  558. *
  559. * @param string $mailbox Folder name
  560. */
  561. function remove_thread($mailbox = null)
  562. {
  563. $this->db->query(
  564. "DELETE FROM {$this->thread_table}"
  565. ." WHERE `user_id` = ?"
  566. .(strlen($mailbox) ? " AND `mailbox` = ".$this->db->quote($mailbox) : ""),
  567. $this->userid
  568. );
  569. if (strlen($mailbox)) {
  570. unset($this->icache[$mailbox]['thread']);
  571. // Thread data removed, set flag to skip SELECT query in get_thread()
  572. $this->icache[$mailbox]['thread_queried'] = true;
  573. }
  574. else {
  575. $this->icache = array();
  576. }
  577. }
  578. /**
  579. * Clears the cache.
  580. *
  581. * @param string $mailbox Folder name
  582. * @param array $uids Message UIDs, NULL removes all messages in a folder
  583. */
  584. function clear($mailbox = null, $uids = null)
  585. {
  586. $this->remove_index($mailbox, true);
  587. $this->remove_thread($mailbox);
  588. $this->remove_message($mailbox, $uids);
  589. }
  590. /**
  591. * Delete expired cache entries
  592. */
  593. static function gc()
  594. {
  595. $rcube = rcube::get_instance();
  596. $db = $rcube->get_dbh();
  597. $now = $db->now();
  598. $db->query("DELETE FROM " . $db->table_name('cache_messages', true)
  599. ." WHERE `expires` < $now");
  600. $db->query("DELETE FROM " . $db->table_name('cache_index', true)
  601. ." WHERE `expires` < $now");
  602. $db->query("DELETE FROM ".$db->table_name('cache_thread', true)
  603. ." WHERE `expires` < $now");
  604. }
  605. /**
  606. * Fetches index data from database
  607. */
  608. private function get_index_row($mailbox)
  609. {
  610. // Get index from DB
  611. $sql_result = $this->db->query(
  612. "SELECT `data`, `valid`"
  613. ." FROM {$this->index_table}"
  614. ." WHERE `user_id` = ?"
  615. ." AND `mailbox` = ?",
  616. $this->userid, $mailbox);
  617. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  618. $data = explode('@', $sql_arr['data']);
  619. $index = $this->db->decode($data[0], true);
  620. unset($data[0]);
  621. if (empty($index)) {
  622. $index = new rcube_result_index($mailbox);
  623. }
  624. return array(
  625. 'valid' => $sql_arr['valid'],
  626. 'object' => $index,
  627. 'sort_field' => $data[1],
  628. 'deleted' => $data[2],
  629. 'validity' => $data[3],
  630. 'uidnext' => $data[4],
  631. 'modseq' => $data[5],
  632. );
  633. }
  634. return null;
  635. }
  636. /**
  637. * Fetches thread data from database
  638. */
  639. private function get_thread_row($mailbox)
  640. {
  641. // Get thread from DB
  642. $sql_result = $this->db->query(
  643. "SELECT `data`"
  644. ." FROM {$this->thread_table}"
  645. ." WHERE `user_id` = ?"
  646. ." AND `mailbox` = ?",
  647. $this->userid, $mailbox);
  648. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  649. $data = explode('@', $sql_arr['data']);
  650. $thread = $this->db->decode($data[0], true);
  651. unset($data[0]);
  652. if (empty($thread)) {
  653. $thread = new rcube_result_thread($mailbox);
  654. }
  655. return array(
  656. 'object' => $thread,
  657. 'deleted' => $data[1],
  658. 'validity' => $data[2],
  659. 'uidnext' => $data[3],
  660. );
  661. }
  662. return null;
  663. }
  664. /**
  665. * Saves index data into database
  666. */
  667. private function add_index_row($mailbox, $sort_field,
  668. $data, $mbox_data = array(), $exists = false, $modseq = null)
  669. {
  670. $data = array(
  671. $this->db->encode($data, true),
  672. $sort_field,
  673. (int) $this->skip_deleted,
  674. (int) $mbox_data['UIDVALIDITY'],
  675. (int) $mbox_data['UIDNEXT'],
  676. $modseq ? $modseq : $mbox_data['HIGHESTMODSEQ'],
  677. );
  678. $data = implode('@', $data);
  679. $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';
  680. if ($exists) {
  681. $res = $this->db->query(
  682. "UPDATE {$this->index_table}"
  683. ." SET `data` = ?, `valid` = 1, `expires` = $expires"
  684. ." WHERE `user_id` = ?"
  685. ." AND `mailbox` = ?",
  686. $data, $this->userid, $mailbox);
  687. if ($this->db->affected_rows($res)) {
  688. return;
  689. }
  690. }
  691. $this->db->set_option('ignore_key_errors', true);
  692. $res = $this->db->query(
  693. "INSERT INTO {$this->index_table}"
  694. ." (`user_id`, `mailbox`, `valid`, `expires`, `data`)"
  695. ." VALUES (?, ?, 1, $expires, ?)",
  696. $this->userid, $mailbox, $data);
  697. // race-condition, insert failed so try update (#1489146)
  698. // thanks to ignore_key_errors "duplicate row" errors will be ignored
  699. if (!$exists && !$res && !$this->db->is_error($res)) {
  700. $res = $this->db->query(
  701. "UPDATE {$this->index_table}"
  702. ." SET `data` = ?, `valid` = 1, `expires` = $expires"
  703. ." WHERE `user_id` = ?"
  704. ." AND `mailbox` = ?",
  705. $data, $this->userid, $mailbox);
  706. }
  707. $this->db->set_option('ignore_key_errors', false);
  708. }
  709. /**
  710. * Saves thread data into database
  711. */
  712. private function add_thread_row($mailbox, $data, $mbox_data = array(), $exists = false)
  713. {
  714. $data = array(
  715. $this->db->encode($data, true),
  716. (int) $this->skip_deleted,
  717. (int) $mbox_data['UIDVALIDITY'],
  718. (int) $mbox_data['UIDNEXT'],
  719. );
  720. $data = implode('@', $data);
  721. $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';
  722. if ($exists) {
  723. $res = $this->db->query(
  724. "UPDATE {$this->thread_table}"
  725. ." SET `data` = ?, `expires` = $expires"
  726. ." WHERE `user_id` = ?"
  727. ." AND `mailbox` = ?",
  728. $data, $this->userid, $mailbox);
  729. if ($this->db->affected_rows($res)) {
  730. return;
  731. }
  732. }
  733. $this->db->set_option('ignore_key_errors', true);
  734. $res = $this->db->query(
  735. "INSERT INTO {$this->thread_table}"
  736. ." (`user_id`, `mailbox`, `expires`, `data`)"
  737. ." VALUES (?, ?, $expires, ?)",
  738. $this->userid, $mailbox, $data);
  739. // race-condition, insert failed so try update (#1489146)
  740. // thanks to ignore_key_errors "duplicate row" errors will be ignored
  741. if (!$exists && !$res && !$this->db->is_error($res)) {
  742. $this->db->query(
  743. "UPDATE {$this->thread_table}"
  744. ." SET `expires` = $expires, `data` = ?"
  745. ." WHERE `user_id` = ?"
  746. ." AND `mailbox` = ?",
  747. $data, $this->userid, $mailbox);
  748. }
  749. $this->db->set_option('ignore_key_errors', false);
  750. }
  751. /**
  752. * Checks index/thread validity
  753. */
  754. private function validate($mailbox, $index, &$exists = true)
  755. {
  756. $object = $index['object'];
  757. $is_thread = is_a($object, 'rcube_result_thread');
  758. // sanity check
  759. if (empty($object)) {
  760. return false;
  761. }
  762. $index['validated'] = true;
  763. // Get mailbox data (UIDVALIDITY, counters, etc.) for status check
  764. $mbox_data = $this->imap->folder_data($mailbox);
  765. // @TODO: Think about skipping validation checks.
  766. // If we could check only every 10 minutes, we would be able to skip
  767. // expensive checks, mailbox selection or even IMAP connection, this would require
  768. // additional logic to force cache invalidation in some cases
  769. // and many rcube_imap changes to connect when needed
  770. // Check UIDVALIDITY
  771. if ($index['validity'] != $mbox_data['UIDVALIDITY']) {
  772. $this->clear($mailbox);
  773. $exists = false;
  774. return false;
  775. }
  776. // Folder is empty but cache isn't
  777. if (empty($mbox_data['EXISTS'])) {
  778. if (!$object->is_empty()) {
  779. $this->clear($mailbox);
  780. $exists = false;
  781. return false;
  782. }
  783. }
  784. // Folder is not empty but cache is
  785. else if ($object->is_empty()) {
  786. unset($this->icache[$mailbox][$is_thread ? 'thread' : 'index']);
  787. return false;
  788. }
  789. // Validation flag
  790. if (!$is_thread && empty($index['valid'])) {
  791. unset($this->icache[$mailbox]['index']);
  792. return false;
  793. }
  794. // Index was created with different skip_deleted setting
  795. if ($this->skip_deleted != $index['deleted']) {
  796. return false;
  797. }
  798. // Check HIGHESTMODSEQ
  799. if (!empty($index['modseq']) && !empty($mbox_data['HIGHESTMODSEQ'])
  800. && $index['modseq'] == $mbox_data['HIGHESTMODSEQ']
  801. ) {
  802. return true;
  803. }
  804. // Check UIDNEXT
  805. if ($index['uidnext'] != $mbox_data['UIDNEXT']) {
  806. unset($this->icache[$mailbox][$is_thread ? 'thread' : 'index']);
  807. return false;
  808. }
  809. // @TODO: find better validity check for threaded index
  810. if ($is_thread) {
  811. // check messages number...
  812. if (!$this->skip_deleted && $mbox_data['EXISTS'] != $object->count_messages()) {
  813. return false;
  814. }
  815. return true;
  816. }
  817. // The rest of checks, more expensive
  818. if (!empty($this->skip_deleted)) {
  819. // compare counts if available
  820. if (!empty($mbox_data['UNDELETED'])
  821. && $mbox_data['UNDELETED']->count() != $object->count()
  822. ) {
  823. return false;
  824. }
  825. // compare UID sets
  826. if (!empty($mbox_data['UNDELETED'])) {
  827. $uids_new = $mbox_data['UNDELETED']->get();
  828. $uids_old = $object->get();
  829. if (count($uids_new) != count($uids_old)) {
  830. return false;
  831. }
  832. sort($uids_new, SORT_NUMERIC);
  833. sort($uids_old, SORT_NUMERIC);
  834. if ($uids_old != $uids_new)
  835. return false;
  836. }
  837. else {
  838. // get all undeleted messages excluding cached UIDs
  839. $ids = $this->imap->search_once($mailbox, 'ALL UNDELETED NOT UID '.
  840. rcube_imap_generic::compressMessageSet($object->get()));
  841. if (!$ids->is_empty()) {
  842. return false;
  843. }
  844. }
  845. }
  846. else {
  847. // check messages number...
  848. if ($mbox_data['EXISTS'] != $object->count()) {
  849. return false;
  850. }
  851. // ... and max UID
  852. if ($object->max() != $this->imap->id2uid($mbox_data['EXISTS'], $mailbox)) {
  853. return false;
  854. }
  855. }
  856. return true;
  857. }
  858. /**
  859. * Synchronizes the mailbox.
  860. *
  861. * @param string $mailbox Folder name
  862. */
  863. function synchronize($mailbox)
  864. {
  865. // RFC4549: Synchronization Operations for Disconnected IMAP4 Clients
  866. // RFC4551: IMAP Extension for Conditional STORE Operation
  867. // or Quick Flag Changes Resynchronization
  868. // RFC5162: IMAP Extensions for Quick Mailbox Resynchronization
  869. // @TODO: synchronize with other methods?
  870. $qresync = $this->imap->get_capability('QRESYNC');
  871. $condstore = $qresync ? true : $this->imap->get_capability('CONDSTORE');
  872. if (!$qresync && !$condstore) {
  873. return;
  874. }
  875. // Get stored index
  876. $index = $this->get_index_row($mailbox);
  877. // database is empty
  878. if (empty($index)) {
  879. // set the flag that DB was already queried for index
  880. // this way we'll be able to skip one SELECT in get_index()
  881. $this->icache[$mailbox]['index_queried'] = true;
  882. return;
  883. }
  884. $this->icache[$mailbox]['index'] = $index;
  885. // no last HIGHESTMODSEQ value
  886. if (empty($index['modseq'])) {
  887. return;
  888. }
  889. if (!$this->imap->check_connection()) {
  890. return;
  891. }
  892. // Enable QRESYNC
  893. $res = $this->imap->conn->enable($qresync ? 'QRESYNC' : 'CONDSTORE');
  894. if ($res === false) {
  895. return;
  896. }
  897. // Close mailbox if already selected to get most recent data
  898. if ($this->imap->conn->selected == $mailbox) {
  899. $this->imap->conn->close();
  900. }
  901. // Get mailbox data (UIDVALIDITY, HIGHESTMODSEQ, counters, etc.)
  902. $mbox_data = $this->imap->folder_data($mailbox);
  903. if (empty($mbox_data)) {
  904. return;
  905. }
  906. // Check UIDVALIDITY
  907. if ($index['validity'] != $mbox_data['UIDVALIDITY']) {
  908. $this->clear($mailbox);
  909. return;
  910. }
  911. // QRESYNC not supported on specified mailbox
  912. if (!empty($mbox_data['NOMODSEQ']) || empty($mbox_data['HIGHESTMODSEQ'])) {
  913. return;
  914. }
  915. // Nothing new
  916. if ($mbox_data['HIGHESTMODSEQ'] == $index['modseq']) {
  917. return;
  918. }
  919. $uids = array();
  920. $removed = array();
  921. // Get known UIDs
  922. if ($this->mode & self::MODE_MESSAGE) {
  923. $sql_result = $this->db->query(
  924. "SELECT `uid`"
  925. ." FROM {$this->messages_table}"
  926. ." WHERE `user_id` = ?"
  927. ." AND `mailbox` = ?",
  928. $this->userid, $mailbox);
  929. while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  930. $uids[] = $sql_arr['uid'];
  931. }
  932. }
  933. // Synchronize messages data
  934. if (!empty($uids)) {
  935. // Get modified flags and vanished messages
  936. // UID FETCH 1:* (FLAGS) (CHANGEDSINCE 0123456789 VANISHED)
  937. $result = $this->imap->conn->fetch($mailbox,
  938. $uids, true, array('FLAGS'), $index['modseq'], $qresync);
  939. if (!empty($result)) {
  940. foreach ($result as $msg) {
  941. $uid = $msg->uid;
  942. // Remove deleted message
  943. if ($this->skip_deleted && !empty($msg->flags['DELETED'])) {
  944. $removed[] = $uid;
  945. // Invalidate index
  946. $index['valid'] = false;
  947. continue;
  948. }
  949. $flags = 0;
  950. if (!empty($msg->flags)) {
  951. foreach ($this->flags as $idx => $flag) {
  952. if (!empty($msg->flags[$flag])) {
  953. $flags += $idx;
  954. }
  955. }
  956. }
  957. $this->db->query(
  958. "UPDATE {$this->messages_table}"
  959. ." SET `flags` = ?, `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
  960. ." WHERE `user_id` = ?"
  961. ." AND `mailbox` = ?"
  962. ." AND `uid` = ?"
  963. ." AND `flags` <> ?",
  964. $flags, $this->userid, $mailbox, $uid, $flags);
  965. }
  966. }
  967. // VANISHED found?
  968. if ($qresync) {
  969. $mbox_data = $this->imap->folder_data($mailbox);
  970. // Removed messages found
  971. $uids = rcube_imap_generic::uncompressMessageSet($mbox_data['VANISHED']);
  972. if (!empty($uids)) {
  973. $removed = array_merge($removed, $uids);
  974. // Invalidate index
  975. $index['valid'] = false;
  976. }
  977. }
  978. // remove messages from database
  979. if (!empty($removed)) {
  980. $this->remove_message($mailbox, $removed);
  981. }
  982. }
  983. $sort_field = $index['sort_field'];
  984. $sort_order = $index['object']->get_parameters('ORDER');
  985. $exists = true;
  986. // Validate index
  987. if (!$this->validate($mailbox, $index, $exists)) {
  988. // Invalidate (remove) thread index
  989. // if $exists=false it was already removed in validate()
  990. if ($exists) {
  991. $this->remove_thread($mailbox);
  992. }
  993. // Update index
  994. $data = $this->get_index_data($mailbox, $sort_field, $sort_order, $mbox_data);
  995. }
  996. else {
  997. $data = $index['object'];
  998. }
  999. // update index and/or HIGHESTMODSEQ value
  1000. $this->add_index_row($mailbox, $sort_field, $data, $mbox_data, $exists);
  1001. // update internal cache for get_index()
  1002. $this->icache[$mailbox]['index']['object'] = $data;
  1003. }
  1004. /**
  1005. * Converts cache row into message object.
  1006. *
  1007. * @param array $sql_arr Message row data
  1008. *
  1009. * @return rcube_message_header Message object
  1010. */
  1011. private function build_message($sql_arr)
  1012. {
  1013. $message = $this->db->decode($sql_arr['data'], true);
  1014. if ($message) {
  1015. $message->flags = array();
  1016. foreach ($this->flags as $idx => $flag) {
  1017. if (($sql_arr['flags'] & $idx) == $idx) {
  1018. $message->flags[$flag] = true;
  1019. }
  1020. }
  1021. }
  1022. return $message;
  1023. }
  1024. /**
  1025. * Saves message stored in internal cache
  1026. */
  1027. private function save_icache()
  1028. {
  1029. // Save current message from internal cache
  1030. if ($message = $this->icache['__message']) {
  1031. // clean up some object's data
  1032. $this->message_object_prepare($message['object']);
  1033. // calculate current md5 sum
  1034. $md5sum = md5(serialize($message['object']));
  1035. if ($message['md5sum'] != $md5sum) {
  1036. $this->add_message($message['mailbox'], $message['object'], !$message['exists']);
  1037. }
  1038. $this->icache['__message']['md5sum'] = $md5sum;
  1039. }
  1040. }
  1041. /**
  1042. * Prepares message object to be stored in database.
  1043. *
  1044. * @param rcube_message_header|rcube_message_part
  1045. */
  1046. private function message_object_prepare(&$msg, &$size = 0)
  1047. {
  1048. // Remove body too big
  1049. if (isset($msg->body)) {
  1050. $length = strlen($msg->body);
  1051. if ($msg->body_modified || $size + $length > $this->threshold * 1024) {
  1052. unset($msg->body);
  1053. }
  1054. else {
  1055. $size += $length;
  1056. }
  1057. }
  1058. // Fix mimetype which might be broken by some code when message is displayed
  1059. // Another solution would be to use object's copy in rcube_message class
  1060. // to prevent related issues, however I'm not sure which is better
  1061. if ($msg->mimetype) {
  1062. list($msg->ctype_primary, $msg->ctype_secondary) = explode('/', $msg->mimetype);
  1063. }
  1064. unset($msg->replaces);
  1065. if (is_object($msg->structure)) {
  1066. $this->message_object_prepare($msg->structure, $size);
  1067. }
  1068. if (is_array($msg->parts)) {
  1069. foreach ($msg->parts as $part) {
  1070. $this->message_object_prepare($part, $size);
  1071. }
  1072. }
  1073. }
  1074. /**
  1075. * Fetches index data from IMAP server
  1076. */
  1077. private function get_index_data($mailbox, $sort_field, $sort_order, $mbox_data = array())
  1078. {
  1079. if (empty($mbox_data)) {
  1080. $mbox_data = $this->imap->folder_data($mailbox);
  1081. }
  1082. if ($mbox_data['EXISTS']) {
  1083. // fetch sorted sequence numbers
  1084. $index = $this->imap->index_direct($mailbox, $sort_field, $sort_order);
  1085. }
  1086. else {
  1087. $index = new rcube_result_index($mailbox, '* SORT');
  1088. }
  1089. return $index;
  1090. }
  1091. /**
  1092. * Fetches thread data from IMAP server
  1093. */
  1094. private function get_thread_data($mailbox, $mbox_data = array())
  1095. {
  1096. if (empty($mbox_data)) {
  1097. $mbox_data = $this->imap->folder_data($mailbox);
  1098. }
  1099. if ($mbox_data['EXISTS']) {
  1100. // get all threads (default sort order)
  1101. return $this->imap->threads_direct($mailbox);
  1102. }
  1103. return new rcube_result_thread($mailbox, '* THREAD');
  1104. }
  1105. }
  1106. // for backward compat.
  1107. class rcube_mail_header extends rcube_message_header { }