imap_mailbox.php 54 KB

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