imap_mailbox.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. <?php
  2. /**
  3. * imap_mailbox.php
  4. *
  5. * This implements all functions that manipulate mailboxes
  6. *
  7. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  8. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  9. * @version $Id$
  10. * @package squirrelmail
  11. * @subpackage imap
  12. */
  13. /** @ignore */
  14. if (! defined('SM_PATH')) define('SM_PATH','../');
  15. /** UTF7 support */
  16. require_once(SM_PATH . 'functions/imap_utf7_local.php');
  17. global $boxesnew;
  18. /**
  19. * Mailboxes class
  20. *
  21. * FIXME. This class should be extracted and placed in a separate file that
  22. * can be included before we start the session. That makes caching of the tree
  23. * possible. On a refresh mailboxes from left_main.php the only function that
  24. * should be called is the sqimap_get_status_mbx_tree. In case of subscribe
  25. * / rename / delete / new we have to create methods for adding/changing the
  26. * mailbox in the mbx_tree without the need for a refresh.
  27. *
  28. * Some code fragments are present in 1.3.0 - 1.4.4.
  29. * @package squirrelmail
  30. * @subpackage imap
  31. * @since 1.5.0
  32. */
  33. class mailboxes {
  34. var $mailboxname_full = '', $mailboxname_sub= '', $is_noselect = false, $is_noinferiors = false,
  35. $is_special = false, $is_root = false, $is_inbox = false, $is_sent = false,
  36. $is_trash = false, $is_draft = false, $mbxs = array(),
  37. $unseen = false, $total = false, $recent = false;
  38. function addMbx($mbx, $delimiter, $start, $specialfirst) {
  39. $ary = explode($delimiter, $mbx->mailboxname_full);
  40. $mbx_parent =& $this;
  41. for ($i = $start, $c = count($ary)-1; $i < $c; $i++) {
  42. $mbx_childs =& $mbx_parent->mbxs;
  43. $found = false;
  44. if ($mbx_childs) {
  45. foreach ($mbx_childs as $key => $parent) {
  46. if ($parent->mailboxname_sub == $ary[$i]) {
  47. $mbx_parent =& $mbx_parent->mbxs[$key];
  48. $found = true;
  49. break;
  50. }
  51. }
  52. }
  53. if (!$found) {
  54. $no_select_mbx = new mailboxes();
  55. if (isset($mbx_parent->mailboxname_full) && $mbx_parent->mailboxname_full != '') {
  56. $no_select_mbx->mailboxname_full = $mbx_parent->mailboxname_full.$delimiter.$ary[$i];
  57. } else {
  58. $no_select_mbx->mailboxname_full = $ary[$i];
  59. }
  60. $no_select_mbx->mailboxname_sub = $ary[$i];
  61. $no_select_mbx->is_noselect = true;
  62. $mbx_parent->mbxs[] = $no_select_mbx;
  63. $i--;
  64. }
  65. }
  66. $mbx_parent->mbxs[] = $mbx;
  67. if ($mbx->is_special && $specialfirst) {
  68. usort($mbx_parent->mbxs, 'sortSpecialMbx');
  69. }
  70. }
  71. }
  72. /**
  73. * array callback used for sorting in mailboxes class
  74. * @param object $a
  75. * @param object $b
  76. * @return integer see php strnatcasecmp()
  77. * @since 1.3.0
  78. */
  79. function sortSpecialMbx($a, $b) {
  80. if ($a->is_inbox) {
  81. $acmp = '0'. $a->mailboxname_full;
  82. } else if ($a->is_special) {
  83. $acmp = '1'. $a->mailboxname_full;
  84. } else {
  85. $acmp = '2' . $a->mailboxname_full;
  86. }
  87. if ($b->is_inbox) {
  88. $bcmp = '0'. $b->mailboxname_full;
  89. }else if ($b->is_special) {
  90. $bcmp = '1' . $b->mailboxname_full;
  91. } else {
  92. $bcmp = '2' . $b->mailboxname_full;
  93. }
  94. return strnatcasecmp($acmp, $bcmp);
  95. }
  96. /**
  97. * @param array $ary
  98. * @return array
  99. * @since 1.5.0
  100. */
  101. function compact_mailboxes_response($ary) {
  102. /*
  103. * Workaround for mailboxes returned as literal
  104. * FIXME : Doesn't work if the mailbox name is multiple lines
  105. * (larger then fgets buffer)
  106. */
  107. for ($i = 0, $iCnt=count($ary); $i < $iCnt; $i++) {
  108. if (isset($ary[$i + 1]) && substr($ary[$i], -3) == "}\r\n") {
  109. if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
  110. $ary[$i], $regs)) {
  111. $ary[$i] = $regs[1] . '"' . addslashes(trim($ary[$i+1])) . '"' . $regs[2];
  112. array_splice($ary, $i+1, 2);
  113. }
  114. }
  115. }
  116. /* remove duplicates and ensure array is contiguous */
  117. return array_values(array_unique($ary));
  118. }
  119. /**
  120. * Extract the mailbox name from an untagged LIST (7.2.2) or LSUB (7.2.3) answer
  121. * (LIST|LSUB) (<Flags list>) (NIL|"<separator atom>") <mailbox name string>\r\n
  122. * mailbox name in quoted string MUST be unquoted and stripslashed (sm API)
  123. *
  124. * Originally stored in functions/strings.php. Since 1.2.6 stored in
  125. * functions/imap_mailbox.php
  126. * @param string $line imap LIST/LSUB response line
  127. * @return string mailbox name
  128. */
  129. function find_mailbox_name($line) {
  130. if (preg_match('/^\* (?:LIST|LSUB) \([^\)]*\) (?:NIL|\"[^\"]*\") ([^\r\n]*)[\r\n]*$/i', $line, $regs)) {
  131. if (substr($regs[1], 0, 1) == '"')
  132. return stripslashes(substr($regs[1], 1, -1));
  133. return $regs[1];
  134. }
  135. return '';
  136. }
  137. /**
  138. * Detects if mailbox has noselect flag (can't store messages)
  139. * In versions older than 1.4.5 function checks only LSUB responses
  140. * and can produce pcre warnings.
  141. * @param string $lsub_line mailbox line from untagged LIST or LSUB response
  142. * @return bool whether this is a Noselect mailbox.
  143. * @since 1.3.2
  144. */
  145. function check_is_noselect ($lsub_line) {
  146. return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noselect[^\)]*\)/i", $lsub_line);
  147. }
  148. /**
  149. * Detects if mailbox has noinferiors flag (can't store subfolders)
  150. * @param string $lsub_line mailbox line from untagged LIST or LSUB response
  151. * @return bool whether this is a Noinferiors mailbox.
  152. * @since 1.5.0
  153. */
  154. function check_is_noinferiors ($lsub_line) {
  155. return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noinferiors[^\)]*\)/i", $lsub_line);
  156. }
  157. /**
  158. * Detects mailbox's parent folder
  159. *
  160. * If $haystack is a full mailbox name, and $needle is the mailbox
  161. * separator character, returns the second last part of the full
  162. * mailbox name (i.e. the mailbox's parent mailbox)
  163. *
  164. * Originally stored in functions/strings.php. Since 1.2.6 stored in
  165. * functions/imap_mailbox.php
  166. * @param string $haystack full mailbox name
  167. * @param string $needle delimiter
  168. * @return string parent mailbox
  169. */
  170. function readMailboxParent($haystack, $needle) {
  171. if ($needle == '') {
  172. $ret = '';
  173. } else {
  174. $parts = explode($needle, $haystack);
  175. $elem = array_pop($parts);
  176. while ($elem == '' && count($parts)) {
  177. $elem = array_pop($parts);
  178. }
  179. $ret = join($needle, $parts);
  180. }
  181. return( $ret );
  182. }
  183. /**
  184. * Check if $subbox is below the specified $parentbox
  185. * @param string $subbox potential sub folder
  186. * @param string $parentbox potential parent
  187. * @return boolean
  188. * @since 1.2.3
  189. */
  190. function isBoxBelow( $subbox, $parentbox ) {
  191. global $delimiter;
  192. /*
  193. * Eliminate the obvious mismatch, where the
  194. * subfolder path is shorter than that of the potential parent
  195. */
  196. if ( strlen($subbox) < strlen($parentbox) ) {
  197. return false;
  198. }
  199. /* check for delimiter */
  200. if (substr($parentbox,-1) != $delimiter) {
  201. $parentbox .= $delimiter;
  202. }
  203. return (substr($subbox,0,strlen($parentbox)) == $parentbox);
  204. }
  205. /**
  206. * Defines special mailboxes: given a mailbox name, it checks if this is a
  207. * "special" one: INBOX, Trash, Sent or Draft.
  208. *
  209. * Since 1.2.5 function includes special_mailbox hook.<br>
  210. * Since 1.4.3 hook supports more than one plugin.
  211. * @param string $box mailbox name
  212. * @return boolean
  213. * @since 1.2.3
  214. */
  215. function isSpecialMailbox( $box ) {
  216. $ret = ( (strtolower($box) == 'inbox') ||
  217. isTrashMailbox($box) || isSentMailbox($box) || isDraftMailbox($box) );
  218. if ( !$ret ) {
  219. $ret = boolean_hook_function('special_mailbox',$box,1);
  220. }
  221. return $ret;
  222. }
  223. /**
  224. * Detects if mailbox is a Trash folder or subfolder of Trash
  225. * @param string $box mailbox name
  226. * @return bool whether this is a Trash folder
  227. * @since 1.4.0
  228. */
  229. function isTrashMailbox ($box) {
  230. global $trash_folder, $move_to_trash;
  231. return $move_to_trash && $trash_folder &&
  232. ( $box == $trash_folder || isBoxBelow($box, $trash_folder) );
  233. }
  234. /**
  235. * Detects if mailbox is a Sent folder or subfolder of Sent
  236. * @param string $box mailbox name
  237. * @return bool whether this is a Sent folder
  238. * @since 1.4.0
  239. */
  240. function isSentMailbox($box) {
  241. global $sent_folder, $move_to_sent;
  242. return $move_to_sent && $sent_folder &&
  243. ( $box == $sent_folder || isBoxBelow($box, $sent_folder) );
  244. }
  245. /**
  246. * Detects if mailbox is a Drafts folder or subfolder of Drafts
  247. * @param string $box mailbox name
  248. * @return bool whether this is a Draft folder
  249. * @since 1.4.0
  250. */
  251. function isDraftMailbox($box) {
  252. global $draft_folder, $save_as_draft;
  253. return $save_as_draft &&
  254. ( $box == $draft_folder || isBoxBelow($box, $draft_folder) );
  255. }
  256. /**
  257. * Expunges a mailbox
  258. *
  259. * WARNING: Select mailbox before calling this function.
  260. *
  261. * permanently removes all messages that have the \Deleted flag
  262. * set from the selected mailbox. See EXPUNGE command chapter in
  263. * IMAP RFC.
  264. * @param stream $imap_stream imap connection resource
  265. * @param string $mailbox mailbox name (unused since 1.1.3).
  266. * @param boolean $handle_errors error handling control (displays error_box on error).
  267. * @param mixed $id (since 1.3.0) integer message id or array with integer ids
  268. * @return integer number of expunged messages
  269. * @since 1.0 or older
  270. */
  271. function sqimap_mailbox_expunge ($imap_stream, $mailbox, $handle_errors = true, $id='') {
  272. if ($id) {
  273. if (is_array($id)) {
  274. $id = sqimap_message_list_squisher($id);
  275. }
  276. $id = ' '.$id;
  277. $uid = TRUE;
  278. } else {
  279. $uid = false;
  280. }
  281. $read = sqimap_run_command($imap_stream, 'EXPUNGE'.$id, $handle_errors,
  282. $response, $message, $uid);
  283. $cnt = 0;
  284. if (is_array($read)) {
  285. foreach ($read as $r) {
  286. if (preg_match('/^\*\s[0-9]+\sEXPUNGE/AUi',$r,$regs)) {
  287. $cnt++;
  288. }
  289. }
  290. }
  291. return $cnt;
  292. }
  293. /**
  294. * Checks whether or not the specified mailbox exists
  295. *
  296. * @param stream $imap_stream imap connection resource
  297. * @param string $mailbox mailbox name
  298. * @param array $mailboxlist (since 1.5.1) optional array of mailboxes from
  299. * sqimap_get_mailboxes() (to avoid having to talk to imap server)
  300. * @return boolean
  301. * @since 1.0 or older
  302. */
  303. function sqimap_mailbox_exists ($imap_stream, $mailbox, $mailboxlist=null) {
  304. if (!isset($mailbox) || empty($mailbox)) {
  305. return false;
  306. }
  307. if (is_array($mailboxlist)) {
  308. // use previously retrieved mailbox list
  309. foreach ($mailboxlist as $mbox) {
  310. if ($mbox['unformatted-dm'] == $mailbox) { return true; }
  311. }
  312. return false;
  313. } else {
  314. // go to imap server
  315. $mbx = sqimap_run_command($imap_stream, 'LIST "" ' . sqimap_encode_mailbox_name($mailbox),
  316. true, $response, $message);
  317. return isset($mbx[0]);
  318. }
  319. }
  320. /**
  321. * Selects a mailbox
  322. * Before 1.3.0 used more arguments and returned data depended on those argumements.
  323. * @param stream $imap_stream imap connection resource
  324. * @param string $mailbox mailbox name
  325. * @return array results of select command (on success - permanentflags, flags and rights)
  326. * @since 1.0 or older
  327. */
  328. function sqimap_mailbox_select ($imap_stream, $mailbox) {
  329. // FIX ME: WHAAAA DO NOT USE "None" for something that does not exist. Use false or NULL instead
  330. if ($mailbox == 'None') {
  331. return;
  332. }
  333. // cleanup $mailbox in order to prevent IMAP injection attacks
  334. $mailbox = str_replace(array("\r","\n"), array("",""),$mailbox);
  335. $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox),
  336. true, $response, $message);
  337. $result = array();
  338. for ($i = 0, $cnt = count($read); $i < $cnt; $i++) {
  339. if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
  340. $result[strtoupper($regs[1])] = $regs[2];
  341. } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
  342. $result[strtoupper($regs[2])] = $regs[1];
  343. } else {
  344. if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
  345. $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
  346. $result['PERMANENTFLAGS'] = explode(' ',strtolower($regs[1]));
  347. } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
  348. $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
  349. $result['FLAGS'] = explode(' ',strtolower($regs[1]));
  350. }
  351. }
  352. }
  353. if (!isset($result['PERMANENTFLAGS'])) {
  354. $result['PERMANENTFLAGS'] = $result['FLAGS'];
  355. }
  356. if (preg_match('/^\[(.+)\]/',$message, $regs)) {
  357. $result['RIGHTS']=strtoupper($regs[1]);
  358. }
  359. return $result;
  360. }
  361. /**
  362. * Creates a folder.
  363. *
  364. * Mailbox is automatically subscribed.
  365. *
  366. * Set $type to string that does not match 'noselect' (case insensitive),
  367. * if you don't want to prepend delimiter to mailbox name. Please note
  368. * that 'noinferiors' might be used someday as keyword for folders
  369. * that store only messages.
  370. * @param stream $imap_steam imap connection resource
  371. * @param string $mailbox mailbox name
  372. * @param string $type folder type.
  373. * @since 1.0 or older
  374. */
  375. function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
  376. global $delimiter;
  377. if (strtolower($type) == 'noselect') {
  378. $mailbox .= $delimiter;
  379. }
  380. $read_ary = sqimap_run_command($imap_stream, 'CREATE ' .
  381. sqimap_encode_mailbox_name($mailbox),
  382. true, $response, $message);
  383. sqimap_subscribe ($imap_stream, $mailbox);
  384. }
  385. /**
  386. * Subscribes to an existing folder.
  387. * @param stream $imap_stream imap connection resource
  388. * @param string $mailbox mailbox name
  389. * @param boolean $debug (since 1.5.1)
  390. * @since 1.0 or older
  391. */
  392. function sqimap_subscribe ($imap_stream, $mailbox,$debug=true) {
  393. $read_ary = sqimap_run_command($imap_stream, 'SUBSCRIBE ' .
  394. sqimap_encode_mailbox_name($mailbox),
  395. $debug, $response, $message);
  396. }
  397. /**
  398. * Unsubscribes from an existing folder
  399. * @param stream $imap_stream imap connection resource
  400. * @param string $mailbox mailbox name
  401. * @since 1.0 or older
  402. */
  403. function sqimap_unsubscribe ($imap_stream, $mailbox) {
  404. $read_ary = sqimap_run_command($imap_stream, 'UNSUBSCRIBE ' .
  405. sqimap_encode_mailbox_name($mailbox),
  406. false, $response, $message);
  407. }
  408. /**
  409. * Deletes the given folder
  410. * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
  411. * @param stream $imap_stream imap connection resource
  412. * @param string $mailbox mailbox name
  413. * @since 1.0 or older
  414. */
  415. function sqimap_mailbox_delete ($imap_stream, $mailbox) {
  416. global $data_dir, $username;
  417. sqimap_unsubscribe ($imap_stream, $mailbox);
  418. if (sqimap_mailbox_exists($imap_stream, $mailbox)) {
  419. $read_ary = sqimap_run_command($imap_stream, 'DELETE ' .
  420. sqimap_encode_mailbox_name($mailbox),
  421. true, $response, $message);
  422. if ($response !== 'OK') {
  423. // subscribe again
  424. sqimap_subscribe ($imap_stream, $mailbox);
  425. } else {
  426. do_hook_function('rename_or_delete_folder', $args = array($mailbox, 'delete', ''));
  427. removePref($data_dir, $username, "thread_$mailbox");
  428. removePref($data_dir, $username, "collapse_folder_$mailbox");
  429. }
  430. }
  431. }
  432. /**
  433. * Determines if the user is subscribed to the folder or not
  434. * @param stream $imap_stream imap connection resource
  435. * @param string $mailbox mailbox name
  436. * @return boolean
  437. * @since 1.2.0
  438. */
  439. function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
  440. $boxesall = sqimap_mailbox_list ($imap_stream);
  441. foreach ($boxesall as $ref) {
  442. if ($ref['unformatted'] == $folder) {
  443. return true;
  444. }
  445. }
  446. return false;
  447. }
  448. /**
  449. * Renames a mailbox.
  450. * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
  451. * @param stream $imap_stream imap connection resource
  452. * @param string $old_name mailbox name
  453. * @param string $new_name new mailbox name
  454. * @since 1.2.3
  455. */
  456. function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
  457. if ( $old_name != $new_name ) {
  458. global $delimiter, $imap_server_type, $data_dir, $username;
  459. if ( substr( $old_name, -1 ) == $delimiter ) {
  460. $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
  461. $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
  462. $postfix = $delimiter;
  463. } else {
  464. $postfix = '';
  465. }
  466. $boxesall = sqimap_mailbox_list_all($imap_stream);
  467. $cmd = 'RENAME ' . sqimap_encode_mailbox_name($old_name) .
  468. ' ' . sqimap_encode_mailbox_name($new_name);
  469. $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
  470. sqimap_unsubscribe($imap_stream, $old_name.$postfix);
  471. $oldpref_thread = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
  472. $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
  473. removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
  474. removePref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
  475. sqimap_subscribe($imap_stream, $new_name.$postfix);
  476. setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref_thread);
  477. setPref($data_dir, $username, 'collapse_folder_'.$new_name.$postfix, $oldpref_collapse);
  478. do_hook_function('rename_or_delete_folder',$args = array($old_name, 'rename', $new_name));
  479. $l = strlen( $old_name ) + 1;
  480. $p = 'unformatted';
  481. foreach ($boxesall as $box) {
  482. if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
  483. $new_sub = $new_name . $delimiter . substr($box[$p], $l);
  484. /* With Cyrus IMAPd >= 2.0 rename is recursive, so don't check for errors here */
  485. if ($imap_server_type == 'cyrus') {
  486. $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
  487. $data = sqimap_run_command($imap_stream, $cmd, false,
  488. $response, $message);
  489. }
  490. $was_subscribed = sqimap_mailbox_is_subscribed($imap_stream, $box[$p]);
  491. if ( $was_subscribed ) {
  492. sqimap_unsubscribe($imap_stream, $box[$p]);
  493. }
  494. $oldpref_thread = getPref($data_dir, $username, 'thread_'.$box[$p]);
  495. $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$box[$p]);
  496. removePref($data_dir, $username, 'thread_'.$box[$p]);
  497. removePref($data_dir, $username, 'collapse_folder_'.$box[$p]);
  498. if ( $was_subscribed ) {
  499. sqimap_subscribe($imap_stream, $new_sub);
  500. }
  501. setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref_thread);
  502. setPref($data_dir, $username, 'collapse_folder_'.$new_sub, $oldpref_collapse);
  503. do_hook_function('rename_or_delete_folder',
  504. $args = array($box[$p], 'rename', $new_sub));
  505. }
  506. }
  507. }
  508. }
  509. /**
  510. * Formats a mailbox into parts for the $boxesall array
  511. *
  512. * The parts are:
  513. * <ul>
  514. * <li>raw - Raw LIST/LSUB response from the IMAP server
  515. * <li>formatted - nicely formatted folder name
  516. * <li>unformatted - unformatted, but with delimiter at end removed
  517. * <li>unformatted-dm - folder name as it appears in raw response
  518. * <li>unformatted-disp - unformatted without $folder_prefix
  519. * <li>id - TODO: document me
  520. * <li>flags - TODO: document me
  521. * </ul>
  522. * Before 1.2.0 used third argument for delimiter.
  523. *
  524. * Before 1.5.1 used second argument for lsub line. Argument was removed in order to use
  525. * find_mailbox_name() on the raw input. Since 1.5.1 includes RFC3501 names in flags
  526. * array (for example, "\NoSelect" in addition to "noselect")
  527. * @param array $line
  528. * @return array
  529. * @since 1.0 or older
  530. * @todo document id and flags keys in boxes array and function arguments.
  531. */
  532. function sqimap_mailbox_parse ($line) {
  533. global $folder_prefix, $delimiter;
  534. /* Process each folder line */
  535. for ($g = 0, $cnt = count($line); $g < $cnt; ++$g) {
  536. /* Store the raw IMAP reply */
  537. if (isset($line[$g])) {
  538. $boxesall[$g]['raw'] = $line[$g];
  539. } else {
  540. $boxesall[$g]['raw'] = '';
  541. }
  542. /* Count number of delimiters ($delimiter) in folder name */
  543. $mailbox = find_mailbox_name($line[$g]);
  544. $dm_count = substr_count($mailbox, $delimiter);
  545. if (substr($mailbox, -1) == $delimiter) {
  546. /* If name ends in delimiter, decrement count by one */
  547. $dm_count--;
  548. }
  549. /* Format folder name, but only if it's a INBOX.* or has a parent. */
  550. $boxesallbyname[$mailbox] = $g;
  551. $parentfolder = readMailboxParent($mailbox, $delimiter);
  552. if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
  553. (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
  554. (isset($boxesallbyname[$parentfolder]) &&
  555. (strlen($parentfolder) > 0) ) ) {
  556. $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
  557. if ($indent > 0) {
  558. $boxesall[$g]['formatted'] = str_repeat('&nbsp;&nbsp;', $indent);
  559. } else {
  560. $boxesall[$g]['formatted'] = '';
  561. }
  562. $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
  563. } else {
  564. $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
  565. }
  566. $boxesall[$g]['unformatted-dm'] = $mailbox;
  567. if (substr($mailbox, -1) == $delimiter) {
  568. $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
  569. }
  570. $boxesall[$g]['unformatted'] = $mailbox;
  571. if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
  572. $mailbox = substr($mailbox, strlen($folder_prefix));
  573. }
  574. $boxesall[$g]['unformatted-disp'] = $mailbox;
  575. $boxesall[$g]['id'] = $g;
  576. $boxesall[$g]['flags'] = array();
  577. if (isset($line[$g])) {
  578. ereg("\(([^)]*)\)",$line[$g],$regs);
  579. /**
  580. * Since 1.5.1 flags are stored with RFC3501 naming
  581. * and also the old way for backwards compatibility
  582. * so for example "\NoSelect" and "noselect"
  583. */
  584. $flags = trim($regs[1]);
  585. if ($flags) {
  586. $flagsarr = explode(' ',$flags);
  587. $flagsarrnew=$flagsarr;
  588. // add old type
  589. foreach ($flagsarr as $flag) {
  590. $flagsarrnew[]=strtolower(str_replace('\\', '',$flag));
  591. }
  592. $boxesall[$g]['flags']=$flagsarrnew;
  593. }
  594. }
  595. }
  596. return $boxesall;
  597. }
  598. /**
  599. * Returns list of options (to be echoed into select statement
  600. * based on available mailboxes and separators
  601. * Caller should surround options with <select ...> </select> and
  602. * any formatting.
  603. * @param stream $imap_stream imap connection resource to query for mailboxes
  604. * @param array $show_selected array containing list of mailboxes to pre-select (0 if none)
  605. * @param array $folder_skip array of folders to keep out of option list (compared in lower)
  606. * @param $boxes list of already fetched boxes (for places like folder panel, where
  607. * you know these options will be shown 3 times in a row.. (most often unset).
  608. * @param string $flag (since 1.4.1) flag to check for in mailbox flags, used to filter out mailboxes.
  609. * 'noselect' by default to remove unselectable mailboxes.
  610. * 'noinferiors' used to filter out folders that can not contain subfolders.
  611. * NULL to avoid flag check entirely.
  612. * NOTE: noselect and noiferiors are used internally. The IMAP representation is
  613. * \NoSelect and \NoInferiors
  614. * @param boolean $use_long_format (since 1.4.1) override folder display preference and always show full folder name.
  615. * @return string html formated mailbox selection options
  616. * @since 1.3.2
  617. */
  618. function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
  619. $flag = 'noselect', $use_long_format = false ) {
  620. global $username, $data_dir;
  621. $mbox_options = '';
  622. if ( $use_long_format ) {
  623. $shorten_box_names = 0;
  624. } else {
  625. $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF);
  626. }
  627. if ($boxes == 0) {
  628. $boxes = sqimap_mailbox_list($imap_stream);
  629. }
  630. foreach ($boxes as $boxes_part) {
  631. if ($flag == NULL || (is_array($boxes_part['flags'])
  632. && !in_array($flag, $boxes_part['flags']))) {
  633. $box = $boxes_part['unformatted'];
  634. if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
  635. continue;
  636. }
  637. $lowerbox = strtolower($box);
  638. // mailboxes are casesensitive => inbox.sent != inbox.Sent
  639. // nevermind, to many dependencies this should be fixed!
  640. if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
  641. $box2 = _("INBOX");
  642. } else {
  643. switch ($shorten_box_names)
  644. {
  645. case 2: /* delimited, style = 2 */
  646. $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '.&nbsp;', htmlspecialchars($boxes_part['formatted']));
  647. break;
  648. case 1: /* indent, style = 1 */
  649. $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '&nbsp;&nbsp;', htmlspecialchars($boxes_part['formatted']));
  650. break;
  651. default: /* default, long names, style = 0 */
  652. $box2 = str_replace(' ', '&nbsp;', htmlspecialchars(imap_utf7_decode_local($boxes_part['unformatted-disp'])));
  653. break;
  654. }
  655. }
  656. if ($show_selected != 0 && in_array($lowerbox, $show_selected) ) {
  657. $mbox_options .= '<option value="' . htmlspecialchars($box) .'" selected="selected">'.$box2.'</option>' . "\n";
  658. } else {
  659. $mbox_options .= '<option value="' . htmlspecialchars($box) .'">'.$box2.'</option>' . "\n";
  660. }
  661. }
  662. }
  663. return $mbox_options;
  664. }
  665. /**
  666. * Returns sorted mailbox lists in several different ways.
  667. *
  668. * Since 1.5.1 most of the functionality has been moved to new function sqimap_get_mailboxes
  669. *
  670. * See comment on sqimap_mailbox_parse() for info about the returned array.
  671. * @param resource $imap_stream imap connection resource
  672. * @param boolean $force force update of mailbox listing. available since 1.4.2 and 1.5.0
  673. * @return array list of mailboxes
  674. * @since 1.0 or older
  675. */
  676. function sqimap_mailbox_list($imap_stream, $force=false) {
  677. global $boxesnew,$show_only_subscribed_folders;
  678. if (!sqgetGlobalVar('boxesnew',$boxesnew,SQ_SESSION) || $force) {
  679. $boxesnew=sqimap_get_mailboxes($imap_stream,$force,$show_only_subscribed_folders);
  680. }
  681. return $boxesnew;
  682. }
  683. /**
  684. * Returns a list of all folders, subscribed or not
  685. *
  686. * Since 1.5.1 code moved to sqimap_get_mailboxes()
  687. *
  688. * @param stream $imap_stream imap connection resource
  689. * @return array see sqimap_mailbox_parse()
  690. * @since 1.0 or older
  691. */
  692. function sqimap_mailbox_list_all($imap_stream) {
  693. global $show_only_subscribed_folders;
  694. // fourth argument prevents registration of retrieved list of mailboxes in session
  695. $boxes=sqimap_get_mailboxes($imap_stream,true,false,false);
  696. return $boxes;
  697. }
  698. /**
  699. * Gets the list of mailboxes for sqimap_maolbox_tree and sqimap_mailbox_list
  700. *
  701. * This is because both of those functions had duplicated logic, but with slightly different
  702. * implementations. This will make both use the same implementation, which should make it
  703. * easier to maintain and easier to modify in the future
  704. * @param stream $imap_stream imap connection resource
  705. * @param bool $force force a reload and ignore cache
  706. * @param bool $show_only_subscribed controls listing of visible or all folders
  707. * @param bool $session_register controls registration of retrieved data in session.
  708. * @return object boxesnew - array of mailboxes and their attributes
  709. * @since 1.5.1
  710. */
  711. function sqimap_get_mailboxes($imap_stream,$force=false,$show_only_subscribed=true,$session_register=true) {
  712. global $show_only_subscribed_folders,$noselect_fix_enable,$folder_prefix,
  713. $list_special_folders_first,$imap_server_type;
  714. $inbox_subscribed = false;
  715. $listsubscribed = sqimap_capability($imap_stream,'LIST-SUBSCRIBED');
  716. if ($show_only_subscribed) { $show_only_subscribed=$show_only_subscribed_folders; }
  717. require_once(SM_PATH . 'include/load_prefs.php');
  718. /**
  719. * There are three main listing commands we can use in IMAP:
  720. * LSUB shows just the list of subscribed folders
  721. * may include flags, but these are not necessarily accurate or authoratative
  722. * \NoSelect has special meaning: the folder does not exist -OR- it means this
  723. * folder is not subscribed but children may be
  724. * [RFC-2060]
  725. * LIST this shows every mailbox on the system
  726. * flags are always included and are accurate and authoratative
  727. * \NoSelect means folder should not be selected
  728. * [RFC-2060]
  729. * LIST (SUBSCRIBED) implemented with LIST-SUBSCRIBED extension
  730. * this is like list but returns only subscribed folders
  731. * flag meanings are like LIST, not LSUB
  732. * \NonExistent means mailbox doesn't exist
  733. * \PlaceHolder means parent is not valid (selectable), but one or more children are
  734. * \NoSelect indeed means that the folder should not be selected
  735. * IMAPEXT-LIST-EXTENSIONS-04 August 2003 B. Leiba
  736. */
  737. if (!$show_only_subscribed) {
  738. $lsub = 'LIST';
  739. $sub_cache_name='list_cache';
  740. } elseif ($listsubscribed) {
  741. $lsub = 'LIST (SUBSCRIBED)';
  742. $sub_cache_name='listsub_cache';
  743. } else {
  744. $lsub = 'LSUB';
  745. $sub_cache_name='lsub_cache';
  746. }
  747. // Some IMAP servers allow subfolders to exist even if the parent folders do not
  748. // This fixes some problems with the folder list when this is the case, causing the
  749. // NoSelect folders to be displayed
  750. if ($noselect_fix_enable) {
  751. $lsub_args = "$lsub \"$folder_prefix\" \"*%\"";
  752. $list_args = "LIST \"$folder_prefix\" \"*%\"";
  753. } else {
  754. $lsub_args = "$lsub \"$folder_prefix\" \"*\"";
  755. $list_args = "LIST \"$folder_prefix\" \"*\"";
  756. }
  757. // get subscribed mailbox list from cache (session)
  758. // if not there, then get it from the imap server and store in cache
  759. sqsession_is_active();
  760. if (!$force) {
  761. sqgetGlobalVar($sub_cache_name,$lsub_cache,SQ_SESSION);
  762. }
  763. $lsub_assoc_ary=array();
  764. if (!empty($lsub_cache)) {
  765. $lsub_assoc_ary=$lsub_cache;
  766. } else {
  767. $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args, true, $response, $message);
  768. $lsub_ary = compact_mailboxes_response($lsub_ary);
  769. if (!empty($lsub_ary)) {
  770. foreach ($lsub_ary as $rawline) {
  771. $temp_mailbox_name=find_mailbox_name($rawline);
  772. $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
  773. }
  774. unset($lsub_ary);
  775. sqsession_register($lsub_assoc_ary,$sub_cache_name);
  776. }
  777. }
  778. // Now to get the mailbox flags
  779. // The LSUB response may return \NoSelect flags, etc. but it is optional
  780. // according to RFC3501, and even when returned it may not be accurate
  781. // or authoratative. LIST will always return accurate results.
  782. if (($lsub == 'LIST') || ($lsub == 'LIST (SUBSCRIBED)')) {
  783. // we've already done a LIST or LIST (SUBSCRIBED)
  784. // and NOT a LSUB, so no need to do it again
  785. $list_assoc_ary = $lsub_assoc_ary;
  786. } else {
  787. // we did a LSUB so now we need to do a LIST
  788. // first see if it is in cache
  789. $list_cache_name='list_cache';
  790. if (!$force) {
  791. sqgetGlobalVar($list_cache_name,$list_cache,SQ_SESSION);
  792. }
  793. if (!empty($list_cache)) {
  794. $list_assoc_ary=$list_cache;
  795. // we could store this in list_cache_name but not necessary
  796. } else {
  797. // not in cache so we need to go get it from the imap server
  798. $list_assoc_ary = array();
  799. $list_ary = sqimap_run_command($imap_stream, $list_args,
  800. true, $response, $message);
  801. $list_ary = compact_mailboxes_response($list_ary);
  802. if (!empty($list_ary)) {
  803. foreach ($list_ary as $rawline) {
  804. $temp_mailbox_name=find_mailbox_name($rawline);
  805. $list_assoc_ary[$temp_mailbox_name]=$rawline;
  806. }
  807. unset($list_ary);
  808. sqsession_register($list_assoc_ary,$list_cache_name);
  809. }
  810. }
  811. }
  812. // If they aren't subscribed to the inbox, then add it anyway (if its in LIST)
  813. $inbox_subscribed=false;
  814. if (!empty($lsub_assoc_ary)) {
  815. foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
  816. if (strtoupper($temp_mailbox_name) == 'INBOX') {
  817. $inbox_subscribed=true;
  818. }
  819. }
  820. }
  821. if (!$inbox_subscribed) {
  822. if (!empty($list_assoc_ary)) {
  823. foreach ($list_assoc_ary as $temp_mailbox_name=>$rawline) {
  824. if (strtoupper($temp_mailbox_name) == 'INBOX') {
  825. $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
  826. }
  827. }
  828. }
  829. }
  830. // Now we have the raw output, we need to create an array of mailbox names we will return
  831. if (!$show_only_subscribed) {
  832. $final_folders_assoc_ary=$list_assoc_ary;
  833. } else {
  834. /**
  835. * only show subscribed folders
  836. * we need to merge the folders here... we can't trust the flags, etc. from the lsub_assoc_array
  837. * so we use the lsub_assoc_array as the list of folders and the values come from list_assoc_array
  838. */
  839. if (!empty($lsub_assoc_ary)) {
  840. foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
  841. if (!empty($list_assoc_ary[$temp_mailbox_name])) {
  842. $final_folders_assoc_ary[$temp_mailbox_name]=$list_assoc_ary[$temp_mailbox_name];
  843. }
  844. }
  845. }
  846. }
  847. // Now produce a flat, sorted list
  848. if (!empty($final_folders_assoc_ary)) {
  849. uksort($final_folders_assoc_ary,'strnatcasecmp');
  850. foreach ($final_folders_assoc_ary as $temp_mailbox_name=>$rawline) {
  851. $final_folders_ary[]=$rawline;
  852. }
  853. }
  854. // this will put it into an array we can use later
  855. // containing:
  856. // raw - Raw LIST/LSUB response from the IMAP server
  857. // formatted - formatted folder name
  858. // unformatted - unformatted, but with the delimiter at the end removed
  859. // unformated-dm - folder name as it appears in raw response
  860. // unformatted-disp - unformatted without $folder_prefix
  861. // id - the array element number (0, 1, 2, etc.)
  862. // flags - mailbox flags
  863. if (!empty($final_folders_ary)) {
  864. $boxesall = sqimap_mailbox_parse($final_folders_ary);
  865. } else {
  866. // they have no mailboxes
  867. $boxesall=array();
  868. }
  869. /* Now, lets sort for special folders */
  870. $boxesnew = $used = array();
  871. /* Find INBOX */
  872. $cnt = count($boxesall);
  873. $used = array_pad($used,$cnt,false);
  874. $has_inbox = false;
  875. for($k = 0; $k < $cnt; ++$k) {
  876. if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
  877. $boxesnew[] = $boxesall[$k];
  878. $used[$k] = true;
  879. $has_inbox = true;
  880. break;
  881. }
  882. }
  883. if ($has_inbox == false) {
  884. // do a list request for inbox because we should always show
  885. // inbox even if the user isn't subscribed to it.
  886. $inbox_ary = sqimap_run_command($imap_stream, 'LIST "" "INBOX"',
  887. true, $response, $message);
  888. $inbox_ary = compact_mailboxes_response($inbox_ary);
  889. if (count($inbox_ary)) {
  890. $inbox_entry = sqimap_mailbox_parse($inbox_ary);
  891. // add it on top of the list
  892. if (!empty($boxesnew)) {
  893. array_unshift($boxesnew,$inbox_entry[0]);
  894. } else {
  895. $boxesnew[]=$inbox_entry[0];
  896. }
  897. /* array_unshift($used,true); */
  898. }
  899. }
  900. /* List special folders and their subfolders, if requested. */
  901. if ($list_special_folders_first) {
  902. for($k = 0; $k < $cnt; ++$k) {
  903. if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
  904. $boxesnew[] = $boxesall[$k];
  905. $used[$k] = true;
  906. }
  907. }
  908. }
  909. /* Find INBOX's children */
  910. for($k = 0; $k < $cnt; ++$k) {
  911. $isboxbelow=isBoxBelow(strtoupper($boxesall[$k]['unformatted']),'INBOX');
  912. if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
  913. $is_inbox=1;
  914. } else {
  915. $is_inbox=0;
  916. }
  917. if (!$used[$k] && $isboxbelow && $is_inbox) {
  918. $boxesnew[] = $boxesall[$k];
  919. $used[$k] = true;
  920. }
  921. }
  922. /* Rest of the folders */
  923. for($k = 0; $k < $cnt; $k++) {
  924. if (!$used[$k]) {
  925. $boxesnew[] = $boxesall[$k];
  926. }
  927. }
  928. /**
  929. * Don't register boxes in session, if $session_register is set to false
  930. * Prevents registration of sqimap_mailbox_list_all() results.
  931. */
  932. if ($session_register) sqsession_register($boxesnew,'boxesnew');
  933. return $boxesnew;
  934. }
  935. /**
  936. * Fills mailbox object
  937. *
  938. * this is passed the mailbox array by left_main.php
  939. * who has previously obtained it from sqimap_get_mailboxes
  940. * that way, the raw mailbox list is available in left_main to other
  941. * things besides just sqimap_mailbox_tree
  942. * imap_stream is just used now to get status info
  943. *
  944. * most of the functionality is moved to sqimap_get_mailboxes
  945. * also takes care of TODO items:
  946. * caching mailbox tree
  947. * config setting for UW imap section (not needed now)
  948. *
  949. * Some code fragments are present in 1.3.0 - 1.4.4.
  950. * @param stream $imap_stream imap connection resource
  951. * @param array $lsub_ary output array from sqimap_get_mailboxes (contains mailboxes and flags)
  952. * @return object see mailboxes class.
  953. * @since 1.5.0
  954. */
  955. function sqimap_mailbox_tree($imap_stream,$lsub_ary) {
  956. $sorted_lsub_ary = array();
  957. $cnt = count($lsub_ary);
  958. for ($i = 0; $i < $cnt; $i++) {
  959. $mbx=$lsub_ary[$i]['unformatted'];
  960. $flags=$lsub_ary[$i]['flags'];
  961. $noinferiors=0;
  962. if (in_array('\Noinferiors',$flags)) { $noinferiors=1; }
  963. if (in_array('\NoInferiors',$flags)) { $noinferiors=1; }
  964. if (in_array('\HasNoChildren',$flags)) { $noinferiors=1; }
  965. $noselect=0;
  966. if (in_array('\NoSelect',$flags)) { $noselect=1; }
  967. /**
  968. * LIST (SUBSCRIBED) has two new flags, \NonExistent which means the mailbox is subscribed to
  969. * but doesn't exist, and \PlaceHolder which is similar (but not the same) as \NoSelect
  970. * For right now, we'll treat these the same as \NoSelect and this behavior can be changed
  971. * later if needed
  972. */
  973. if (in_array('\NonExistent',$flags)) { $noselect=1; }
  974. if (in_array('\PlaceHolder',$flags)) { $noselect=1; }
  975. $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
  976. }
  977. $sorted_lsub_ary = array_values($sorted_lsub_ary);
  978. usort($sorted_lsub_ary, 'mbxSort');
  979. $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
  980. return $boxestree;
  981. }
  982. /**
  983. * Callback function used for sorting mailboxes in sqimap_mailbox_tree
  984. * @param string $a
  985. * @param string $b
  986. * @return integer see php strnatcasecmp()
  987. * @since 1.5.1
  988. */
  989. function mbxSort($a, $b) {
  990. return strnatcasecmp($a['mbx'], $b['mbx']);
  991. }
  992. /**
  993. * Fills mailbox object
  994. *
  995. * Some code fragments are present in 1.3.0 - 1.4.4.
  996. * @param array $mbx_ary
  997. * @param $mbxs
  998. * @param stream $imap_stream imap connection resource
  999. * @return object see mailboxes class
  1000. * @since 1.5.0
  1001. */
  1002. function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
  1003. global $data_dir, $username, $list_special_folders_first,
  1004. $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
  1005. $move_to_trash, $move_to_sent, $save_as_draft,
  1006. $delimiter, $imap_server_type;
  1007. // $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
  1008. /* create virtual root node */
  1009. $mailboxes= new mailboxes();
  1010. $mailboxes->is_root = true;
  1011. $trail_del = false;
  1012. $start = 0;
  1013. if (isset($folder_prefix) && ($folder_prefix != '')) {
  1014. $start = substr_count($folder_prefix,$delimiter);
  1015. if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
  1016. $mailboxes->mailboxname_full = substr($folder_prefix,0, (strlen($folder_prefix)-1));
  1017. } else {
  1018. $mailboxes->mailboxname_full = $folder_prefix;
  1019. $start++;
  1020. }
  1021. $mailboxes->mailboxname_sub = $mailboxes->mailboxname_full;
  1022. } else {
  1023. $start = 0;
  1024. }
  1025. $cnt = count($mbx_ary);
  1026. for ($i=0; $i < $cnt; $i++) {
  1027. if ($mbx_ary[$i]['mbx'] !='' ) {
  1028. $mbx = new mailboxes();
  1029. $mailbox = $mbx_ary[$i]['mbx'];
  1030. /*
  1031. * Set the is_special flag if it concerned a special mailbox.
  1032. * Used for displaying the special folders on top in the mailbox
  1033. * tree displaying code.
  1034. */
  1035. $mbx->is_special |= ($mbx->is_inbox = (strtoupper($mailbox) == 'INBOX'));
  1036. $mbx->is_special |= ($mbx->is_trash = isTrashMailbox($mailbox));
  1037. $mbx->is_special |= ($mbx->is_sent = isSentMailbox($mailbox));
  1038. $mbx->is_special |= ($mbx->is_draft = isDraftMailbox($mailbox));
  1039. if (!$mbx->is_special)
  1040. $mbx->is_special = boolean_hook_function('special_mailbox', $mailbox, 1);
  1041. if (isset($mbx_ary[$i]['unseen'])) {
  1042. $mbx->unseen = $mbx_ary[$i]['unseen'];
  1043. }
  1044. if (isset($mbx_ary[$i]['nummessages'])) {
  1045. $mbx->total = $mbx_ary[$i]['nummessages'];
  1046. }
  1047. $mbx->is_noselect = $mbx_ary[$i]['noselect'];
  1048. $mbx->is_noinferiors = $mbx_ary[$i]['noinferiors'];
  1049. $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
  1050. if ($r_del_pos) {
  1051. $mbx->mailboxname_sub = substr($mbx_ary[$i]['mbx'],$r_del_pos+1);
  1052. } else { /* mailbox is root folder */
  1053. $mbx->mailboxname_sub = $mbx_ary[$i]['mbx'];
  1054. }
  1055. $mbx->mailboxname_full = $mbx_ary[$i]['mbx'];
  1056. $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
  1057. }
  1058. }
  1059. sqimap_utf7_decode_mbx_tree($mailboxes);
  1060. sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
  1061. return $mailboxes;
  1062. }
  1063. /**
  1064. * @param object $mbx_tree
  1065. * @since 1.5.0
  1066. */
  1067. function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
  1068. if (strtoupper($mbx_tree->mailboxname_full) == 'INBOX')
  1069. $mbx_tree->mailboxname_sub = _("INBOX");
  1070. else
  1071. $mbx_tree->mailboxname_sub = imap_utf7_decode_local($mbx_tree->mailboxname_sub);
  1072. if ($mbx_tree->mbxs) {
  1073. $iCnt = count($mbx_tree->mbxs);
  1074. for ($i=0;$i<$iCnt;++$i) {
  1075. sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs[$i]);
  1076. }
  1077. }
  1078. }
  1079. /**
  1080. * @param object $mbx_tree
  1081. * @param array $aMbxs
  1082. * @since 1.5.0
  1083. */
  1084. function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
  1085. if ($mbx_tree)
  1086. $aMbxs[] =& $mbx_tree;
  1087. if ($mbx_tree->mbxs) {
  1088. $iCnt = count($mbx_tree->mbxs);
  1089. for ($i=0;$i<$iCnt;++$i) {
  1090. sqimap_tree_to_ref_array($mbx_tree->mbxs[$i],$aMbxs);
  1091. }
  1092. }
  1093. }
  1094. /**
  1095. * @param stream $imap_stream imap connection resource
  1096. * @param object $mbx_tree
  1097. * @since since 1.5.0
  1098. */
  1099. function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
  1100. global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
  1101. $aMbxs = $aQuery = array();
  1102. sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
  1103. // remove the root node
  1104. array_shift($aMbxs);
  1105. if($unseen_notify == 3) {
  1106. $cnt = count($aMbxs);
  1107. for($i=0;$i<$cnt;++$i) {
  1108. $oMbx =& $aMbxs[$i];
  1109. if (!$oMbx->is_noselect) {
  1110. $mbx = $oMbx->mailboxname_full;
  1111. if ($unseen_type == 2 ||
  1112. ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
  1113. $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (MESSAGES UNSEEN RECENT)';
  1114. } else {
  1115. $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (UNSEEN RECENT)';
  1116. }
  1117. sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
  1118. } else {
  1119. $oMbx->unseen = $oMbx->total = $oMbx->recent = false;
  1120. $tag = false;
  1121. }
  1122. $oMbx->tag = $tag;
  1123. $aMbxs[$i] =& $oMbx;
  1124. }
  1125. // execute all the queries at once
  1126. $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
  1127. $cnt = count($aMbxs);
  1128. for($i=0;$i<$cnt;++$i) {
  1129. $oMbx =& $aMbxs[$i];
  1130. $tag = $oMbx->tag;
  1131. if ($tag && $aServerResponse[$tag] == 'OK') {
  1132. $sResponse = implode('', $aResponse[$tag]);
  1133. if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
  1134. $oMbx->unseen = $regs[1];
  1135. }
  1136. if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
  1137. $oMbx->total = $regs[1];
  1138. }
  1139. if (preg_match('/RECENT\s+([0-9]+)/i', $sResponse, $regs)) {
  1140. $oMbx->recent = $regs[1];
  1141. }
  1142. }
  1143. unset($oMbx->tag);
  1144. }
  1145. } else if ($unseen_notify == 2) { // INBOX only
  1146. $cnt = count($aMbxs);
  1147. for($i=0;$i<$cnt;++$i) {
  1148. $oMbx =& $aMbxs[$i];
  1149. if (strtoupper($oMbx->mailboxname_full) == 'INBOX' ||
  1150. ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
  1151. if ($unseen_type == 2 ||
  1152. ($oMbx->mailboxname_full == $trash_folder && $move_to_trash)) {
  1153. $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full);
  1154. $oMbx->unseen = $aStatus['UNSEEN'];
  1155. $oMbx->total = $aStatus['MESSAGES'];
  1156. $oMbx->recent = $aStatus['RECENT'];
  1157. } else {
  1158. $oMbx->unseen = sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full);
  1159. }
  1160. $aMbxs[$i] =& $oMbx;
  1161. if (!$move_to_trash && $trash_folder) {
  1162. break;
  1163. } else {
  1164. // trash comes after INBOX
  1165. if ($oMbx->mailboxname_full == $trash_folder) {
  1166. break;
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. $cnt = count($aMbxs);
  1173. for($i=0;$i<$cnt;++$i) {
  1174. $oMbx =& $aMbxs[$i];
  1175. unset($hook_status);
  1176. if (!empty($oMbx->unseen)) { $hook_status['UNSEEN']=$oMbx->unseen; }
  1177. if (!empty($oMbx->total)) { $hook_status['MESSAGES']=$oMbx->total; }
  1178. if (!empty($oMbx->recent)) { $hook_status['RECENT']=$oMbx->recent; }
  1179. if (!empty($hook_status))
  1180. {
  1181. $hook_status['MAILBOX']=$oMbx->mailboxname_full;
  1182. $hook_status['CALLER']='sqimap_get_status_mbx_tree'; // helps w/ debugging
  1183. do_hook_function('folder_status',$hook_status);
  1184. }
  1185. }
  1186. }
  1187. /**
  1188. * Checks if folder is noselect (can't store messages)
  1189. *
  1190. * Function does not check if folder subscribed.
  1191. * @param stream $oImapStream imap connection resource
  1192. * @param string $sImapFolder imap folder name
  1193. * @param object $oBoxes mailboxes class object.
  1194. * @return boolean true, when folder has noselect flag. false in any other case.
  1195. * @since 1.5.1
  1196. */
  1197. function sqimap_mailbox_is_noselect($oImapStream,$sImapFolder,&$oBoxes) {
  1198. // build mailbox object if it is not available
  1199. if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
  1200. foreach($oBoxes as $box) {
  1201. if ($box['unformatted']==$sImapFolder) {
  1202. return (bool) check_is_noselect($box['raw']);
  1203. }
  1204. }
  1205. return false;
  1206. }
  1207. /**
  1208. * Checks if folder is noinferiors (can't store other folders)
  1209. *
  1210. * Function does not check if folder subscribed.
  1211. * @param stream $oImapStream imap connection resource
  1212. * @param string $sImapFolder imap folder name
  1213. * @param object $oBoxes mailboxes class object.
  1214. * @return boolean true, when folder has noinferiors flag. false in any other case.
  1215. * @since 1.5.1
  1216. */
  1217. function sqimap_mailbox_is_noinferiors($oImapStream,$sImapFolder,&$oBoxes) {
  1218. // build mailbox object if it is not available
  1219. if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
  1220. foreach($oBoxes as $box) {
  1221. if ($box['unformatted']==$sImapFolder) {
  1222. return (bool) check_is_noinferiors($box['raw']);
  1223. }
  1224. }
  1225. return false;
  1226. }
  1227. ?>