imap_mailbox.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. <?php
  2. /**
  3. * imap_mailbox.php
  4. *
  5. * This implements all functions that manipulate mailboxes
  6. *
  7. * @copyright &copy; 1999-2007 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. /**
  347. * Default UW IMAP server configuration allows to access other files
  348. * on server. $imap_server_type is not checked because interface can
  349. * be used with 'other' or any other server type setting. $mailbox
  350. * variable can be modified in any script that uses variable from GET
  351. * or POST. This code blocks all standard SquirrelMail IMAP API requests
  352. * that use mailbox with full path (/etc/passwd) or with ../ characters
  353. * in path (../../etc/passwd)
  354. */
  355. if (strstr($mailbox, '../') || substr($mailbox, 0, 1) == '/') {
  356. global $oTemplate;
  357. error_box(sprintf(_("Invalid mailbox name: %s"),htmlspecialchars($mailbox)));
  358. sqimap_logout($imap_stream);
  359. $oTemplate->display('footer.tpl');
  360. die();
  361. }
  362. $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox),
  363. true, $response, $message);
  364. $result = array();
  365. for ($i = 0, $cnt = count($read); $i < $cnt; $i++) {
  366. if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
  367. $result[strtoupper($regs[1])] = $regs[2];
  368. } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
  369. $result[strtoupper($regs[2])] = $regs[1];
  370. } else {
  371. if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
  372. $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
  373. $result['PERMANENTFLAGS'] = explode(' ',strtolower($regs[1]));
  374. } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
  375. $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
  376. $result['FLAGS'] = explode(' ',strtolower($regs[1]));
  377. }
  378. }
  379. }
  380. if (!isset($result['PERMANENTFLAGS'])) {
  381. $result['PERMANENTFLAGS'] = $result['FLAGS'];
  382. }
  383. if (preg_match('/^\[(.+)\]/',$message, $regs)) {
  384. $result['RIGHTS']=strtoupper($regs[1]);
  385. }
  386. return $result;
  387. }
  388. /**
  389. * Creates a folder.
  390. *
  391. * Mailbox is automatically subscribed.
  392. *
  393. * Set $type to string that does not match 'noselect' (case insensitive),
  394. * if you don't want to prepend delimiter to mailbox name. Please note
  395. * that 'noinferiors' might be used someday as keyword for folders
  396. * that store only messages.
  397. * @param stream $imap_steam imap connection resource
  398. * @param string $mailbox mailbox name
  399. * @param string $type folder type.
  400. * @since 1.0 or older
  401. */
  402. function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
  403. global $delimiter;
  404. if (strtolower($type) == 'noselect') {
  405. $create_mailbox = $mailbox . $delimiter;
  406. } else {
  407. $create_mailbox = $mailbox;
  408. }
  409. $read_ary = sqimap_run_command($imap_stream, 'CREATE ' .
  410. sqimap_encode_mailbox_name($create_mailbox),
  411. true, $response, $message);
  412. sqimap_subscribe ($imap_stream, $mailbox);
  413. }
  414. /**
  415. * Subscribes to an existing folder.
  416. * @param stream $imap_stream imap connection resource
  417. * @param string $mailbox mailbox name
  418. * @param boolean $debug (since 1.5.1)
  419. * @since 1.0 or older
  420. */
  421. function sqimap_subscribe ($imap_stream, $mailbox,$debug=true) {
  422. $read_ary = sqimap_run_command($imap_stream, 'SUBSCRIBE ' .
  423. sqimap_encode_mailbox_name($mailbox),
  424. $debug, $response, $message);
  425. }
  426. /**
  427. * Unsubscribes from an existing folder
  428. * @param stream $imap_stream imap connection resource
  429. * @param string $mailbox mailbox name
  430. * @since 1.0 or older
  431. */
  432. function sqimap_unsubscribe ($imap_stream, $mailbox) {
  433. $read_ary = sqimap_run_command($imap_stream, 'UNSUBSCRIBE ' .
  434. sqimap_encode_mailbox_name($mailbox),
  435. false, $response, $message);
  436. }
  437. /**
  438. * Deletes the given folder
  439. * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
  440. * @param stream $imap_stream imap connection resource
  441. * @param string $mailbox mailbox name
  442. * @since 1.0 or older
  443. */
  444. function sqimap_mailbox_delete ($imap_stream, $mailbox) {
  445. global $data_dir, $username;
  446. sqimap_unsubscribe ($imap_stream, $mailbox);
  447. if (sqimap_mailbox_exists($imap_stream, $mailbox)) {
  448. $read_ary = sqimap_run_command($imap_stream, 'DELETE ' .
  449. sqimap_encode_mailbox_name($mailbox),
  450. true, $response, $message);
  451. if ($response !== 'OK') {
  452. // subscribe again
  453. sqimap_subscribe ($imap_stream, $mailbox);
  454. } else {
  455. do_hook('rename_or_delete_folder', $temp=array(&$mailbox, 'delete', ''));
  456. removePref($data_dir, $username, "thread_$mailbox");
  457. removePref($data_dir, $username, "collapse_folder_$mailbox");
  458. }
  459. }
  460. }
  461. /**
  462. * Determines if the user is subscribed to the folder or not
  463. * @param stream $imap_stream imap connection resource
  464. * @param string $mailbox mailbox name
  465. * @return boolean
  466. * @since 1.2.0
  467. */
  468. function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
  469. $boxesall = sqimap_mailbox_list ($imap_stream);
  470. foreach ($boxesall as $ref) {
  471. if ($ref['unformatted'] == $folder) {
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. /**
  478. * Renames a mailbox.
  479. * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
  480. * @param stream $imap_stream imap connection resource
  481. * @param string $old_name mailbox name
  482. * @param string $new_name new mailbox name
  483. * @since 1.2.3
  484. */
  485. function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
  486. if ( $old_name != $new_name ) {
  487. global $delimiter, $imap_server_type, $data_dir, $username;
  488. if ( substr( $old_name, -1 ) == $delimiter ) {
  489. $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
  490. $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
  491. $postfix = $delimiter;
  492. } else {
  493. $postfix = '';
  494. }
  495. $boxesall = sqimap_mailbox_list_all($imap_stream);
  496. $cmd = 'RENAME ' . sqimap_encode_mailbox_name($old_name) .
  497. ' ' . sqimap_encode_mailbox_name($new_name);
  498. $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
  499. sqimap_unsubscribe($imap_stream, $old_name.$postfix);
  500. $oldpref_thread = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
  501. $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
  502. removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
  503. removePref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
  504. sqimap_subscribe($imap_stream, $new_name.$postfix);
  505. setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref_thread);
  506. setPref($data_dir, $username, 'collapse_folder_'.$new_name.$postfix, $oldpref_collapse);
  507. do_hook('rename_or_delete_folder', $temp=array(&$old_name, 'rename', &$new_name));
  508. $l = strlen( $old_name ) + 1;
  509. $p = 'unformatted';
  510. foreach ($boxesall as $box) {
  511. if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
  512. $new_sub = $new_name . $delimiter . substr($box[$p], $l);
  513. /* With Cyrus IMAPd >= 2.0 rename is recursive, so don't check for errors here */
  514. if ($imap_server_type == 'cyrus') {
  515. $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
  516. $data = sqimap_run_command($imap_stream, $cmd, false,
  517. $response, $message);
  518. }
  519. $was_subscribed = sqimap_mailbox_is_subscribed($imap_stream, $box[$p]);
  520. if ( $was_subscribed ) {
  521. sqimap_unsubscribe($imap_stream, $box[$p]);
  522. }
  523. $oldpref_thread = getPref($data_dir, $username, 'thread_'.$box[$p]);
  524. $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$box[$p]);
  525. removePref($data_dir, $username, 'thread_'.$box[$p]);
  526. removePref($data_dir, $username, 'collapse_folder_'.$box[$p]);
  527. if ( $was_subscribed ) {
  528. sqimap_subscribe($imap_stream, $new_sub);
  529. }
  530. setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref_thread);
  531. setPref($data_dir, $username, 'collapse_folder_'.$new_sub, $oldpref_collapse);
  532. do_hook('rename_or_delete_folder', $temp=array(&$box[$p], 'rename', &$new_sub));
  533. }
  534. }
  535. }
  536. }
  537. /**
  538. * Formats a mailbox into parts for the $boxesall array
  539. *
  540. * The parts are:
  541. * <ul>
  542. * <li>raw - Raw LIST/LSUB response from the IMAP server
  543. * <li>formatted - nicely formatted folder name
  544. * <li>unformatted - unformatted, but with delimiter at end removed
  545. * <li>unformatted-dm - folder name as it appears in raw response
  546. * <li>unformatted-disp - unformatted without $folder_prefix
  547. * <li>id - TODO: document me
  548. * <li>flags - TODO: document me
  549. * </ul>
  550. * Before 1.2.0 used third argument for delimiter.
  551. *
  552. * Before 1.5.1 used second argument for lsub line. Argument was removed in order to use
  553. * find_mailbox_name() on the raw input. Since 1.5.1 includes RFC3501 names in flags
  554. * array (for example, "\NoSelect" in addition to "noselect")
  555. * @param array $line
  556. * @return array
  557. * @since 1.0 or older
  558. * @todo document id and flags keys in boxes array and function arguments.
  559. */
  560. function sqimap_mailbox_parse ($line) {
  561. global $folder_prefix, $delimiter;
  562. /* Process each folder line */
  563. for ($g = 0, $cnt = count($line); $g < $cnt; ++$g) {
  564. /* Store the raw IMAP reply */
  565. if (isset($line[$g])) {
  566. $boxesall[$g]['raw'] = $line[$g];
  567. } else {
  568. $boxesall[$g]['raw'] = '';
  569. }
  570. /* Count number of delimiters ($delimiter) in folder name */
  571. $mailbox = find_mailbox_name($line[$g]);
  572. $dm_count = substr_count($mailbox, $delimiter);
  573. if (substr($mailbox, -1) == $delimiter) {
  574. /* If name ends in delimiter, decrement count by one */
  575. $dm_count--;
  576. }
  577. /* Format folder name, but only if it's a INBOX.* or has a parent. */
  578. $boxesallbyname[$mailbox] = $g;
  579. $parentfolder = readMailboxParent($mailbox, $delimiter);
  580. if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
  581. (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
  582. (isset($boxesallbyname[$parentfolder]) &&
  583. (strlen($parentfolder) > 0) ) ) {
  584. $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
  585. if ($indent > 0) {
  586. $boxesall[$g]['formatted'] = str_repeat('&nbsp;&nbsp;', $indent);
  587. } else {
  588. $boxesall[$g]['formatted'] = '';
  589. }
  590. $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
  591. } else {
  592. $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
  593. }
  594. $boxesall[$g]['unformatted-dm'] = $mailbox;
  595. if (substr($mailbox, -1) == $delimiter) {
  596. $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
  597. }
  598. $boxesall[$g]['unformatted'] = $mailbox;
  599. if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
  600. $mailbox = substr($mailbox, strlen($folder_prefix));
  601. }
  602. $boxesall[$g]['unformatted-disp'] = $mailbox;
  603. $boxesall[$g]['id'] = $g;
  604. $boxesall[$g]['flags'] = array();
  605. if (isset($line[$g])) {
  606. ereg("\(([^)]*)\)",$line[$g],$regs);
  607. /**
  608. * Since 1.5.1 flags are stored with RFC3501 naming
  609. * and also the old way for backwards compatibility
  610. * so for example "\NoSelect" and "noselect"
  611. */
  612. $flags = trim($regs[1]);
  613. if ($flags) {
  614. $flagsarr = explode(' ',$flags);
  615. $flagsarrnew=$flagsarr;
  616. // add old type
  617. foreach ($flagsarr as $flag) {
  618. $flagsarrnew[]=strtolower(str_replace('\\', '',$flag));
  619. }
  620. $boxesall[$g]['flags']=$flagsarrnew;
  621. }
  622. }
  623. }
  624. return $boxesall;
  625. }
  626. /**
  627. * Returns an array of mailboxes available. Separated from sqimap_mailbox_option_list()
  628. * below for template development.
  629. *
  630. * @author Steve Brown
  631. * @since 1.5.2
  632. */
  633. function sqimap_mailbox_option_array($imap_stream, $folder_skip = 0, $boxes = 0,
  634. $flag = 'noselect', $use_long_format = false ) {
  635. global $username, $data_dir, $translate_special_folders, $sent_folder,
  636. $trash_folder, $draft_folder;
  637. $delimiter = sqimap_get_delimiter($imap_stream);
  638. $mbox_options = '';
  639. if ( $use_long_format ) {
  640. $shorten_box_names = 0;
  641. } else {
  642. $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF);
  643. }
  644. if ($boxes == 0) {
  645. $boxes = sqimap_mailbox_list($imap_stream);
  646. }
  647. $a = array();
  648. foreach ($boxes as $boxes_part) {
  649. if ($flag == NULL || (is_array($boxes_part['flags'])
  650. && !in_array($flag, $boxes_part['flags']))) {
  651. $box = $boxes_part['unformatted'];
  652. if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
  653. continue;
  654. }
  655. $lowerbox = strtolower($box);
  656. // mailboxes are casesensitive => inbox.sent != inbox.Sent
  657. // nevermind, to many dependencies this should be fixed!
  658. if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
  659. $box2 = _("INBOX");
  660. } else {
  661. switch ($shorten_box_names)
  662. {
  663. case 2: /* delimited, style = 2 */
  664. if ($translate_special_folders && $boxes_part['unformatted-dm']==$sent_folder) {
  665. /*
  666. * calculate pad level from number of delimiters. do it inside if control in order
  667. * to reduce number of calculations. Other folders don't need it.
  668. */
  669. $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
  670. // i18n: Name of Sent folder
  671. $box2 = $pad . _("Sent");
  672. } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$trash_folder) {
  673. $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
  674. // i18n: Name of Trash folder
  675. $box2 = $pad . _("Trash");
  676. } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$draft_folder) {
  677. $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
  678. // i18n: Name of Drafts folder
  679. $box2 = $pad . _("Drafts");
  680. } else {
  681. $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '.&nbsp;', htmlspecialchars($boxes_part['formatted']));
  682. }
  683. break;
  684. case 1: /* indent, style = 1 */
  685. if ($translate_special_folders && $boxes_part['unformatted-dm']==$sent_folder) {
  686. $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
  687. $box2 = $pad . _("Sent");
  688. } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$trash_folder) {
  689. $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
  690. $box2 = $pad . _("Trash");
  691. } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$draft_folder) {
  692. $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
  693. $box2 = $pad . _("Drafts");
  694. } else {
  695. $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '&nbsp;&nbsp;', htmlspecialchars($boxes_part['formatted']));
  696. }
  697. break;
  698. default: /* default, long names, style = 0 */
  699. $box2 = str_replace(' ', '&nbsp;', htmlspecialchars(imap_utf7_decode_local($boxes_part['unformatted-disp'])));
  700. break;
  701. }
  702. }
  703. $a[htmlspecialchars($box)] = $box2;
  704. }
  705. }
  706. return $a;
  707. }
  708. /**
  709. * Returns list of options (to be echoed into select statement
  710. * based on available mailboxes and separators
  711. * Caller should surround options with <select ...> </select> and
  712. * any formatting.
  713. * @param stream $imap_stream imap connection resource to query for mailboxes
  714. * @param array $show_selected array containing list of mailboxes to pre-select (0 if none)
  715. * @param array $folder_skip array of folders to keep out of option list (compared in lower)
  716. * @param $boxes list of already fetched boxes (for places like folder panel, where
  717. * you know these options will be shown 3 times in a row.. (most often unset).
  718. * @param string $flag (since 1.4.1) flag to check for in mailbox flags, used to filter out mailboxes.
  719. * 'noselect' by default to remove unselectable mailboxes.
  720. * 'noinferiors' used to filter out folders that can not contain subfolders.
  721. * NULL to avoid flag check entirely.
  722. * NOTE: noselect and noiferiors are used internally. The IMAP representation is
  723. * \NoSelect and \NoInferiors
  724. * @param boolean $use_long_format (since 1.4.1) override folder display preference and always show full folder name.
  725. * @return string html formated mailbox selection options
  726. * @since 1.3.2
  727. */
  728. function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
  729. $flag = 'noselect', $use_long_format = false ) {
  730. global $username, $data_dir, $translate_special_folders, $sent_folder,
  731. $trash_folder, $draft_folder;
  732. $boxes = sqimap_mailbox_option_array($imap_stream, $folder_skip, $boxes, $flag, $use_long_format);
  733. $str = '';
  734. foreach ($boxes as $value=>$option) {
  735. $lowerbox = strtolower(htmlspecialchars($value));
  736. $sel = false;
  737. if ($show_selected != 0) {
  738. reset($show_selected);
  739. while (!$sel && (list($x, $val) = each($show_selected))) {
  740. if (strtolower($value) == strtolower(htmlspecialchars($val))) {
  741. $sel = true;
  742. }
  743. }
  744. }
  745. $str .= '<option value="'. $value .'"'. ($sel ? ' selected="selected"' : '').'>'. $option ."</option>\n";
  746. }
  747. return $str;
  748. }
  749. /**
  750. * Returns sorted mailbox lists in several different ways.
  751. *
  752. * Since 1.5.1 most of the functionality has been moved to new function sqimap_get_mailboxes
  753. *
  754. * See comment on sqimap_mailbox_parse() for info about the returned array.
  755. * @param resource $imap_stream imap connection resource
  756. * @param boolean $force force update of mailbox listing. available since 1.4.2 and 1.5.0
  757. * @return array list of mailboxes
  758. * @since 1.0 or older
  759. */
  760. function sqimap_mailbox_list($imap_stream, $force=false) {
  761. global $boxesnew,$show_only_subscribed_folders;
  762. if (!sqgetGlobalVar('boxesnew',$boxesnew,SQ_SESSION) || $force) {
  763. $boxesnew=sqimap_get_mailboxes($imap_stream,$force,$show_only_subscribed_folders);
  764. }
  765. return $boxesnew;
  766. }
  767. /**
  768. * Returns a list of all folders, subscribed or not
  769. *
  770. * Since 1.5.1 code moved to sqimap_get_mailboxes()
  771. *
  772. * @param stream $imap_stream imap connection resource
  773. * @return array see sqimap_mailbox_parse()
  774. * @since 1.0 or older
  775. */
  776. function sqimap_mailbox_list_all($imap_stream) {
  777. global $show_only_subscribed_folders;
  778. // fourth argument prevents registration of retrieved list of mailboxes in session
  779. $boxes=sqimap_get_mailboxes($imap_stream,true,false,false);
  780. return $boxes;
  781. }
  782. /**
  783. * Gets the list of mailboxes for sqimap_maolbox_tree and sqimap_mailbox_list
  784. *
  785. * This is because both of those functions had duplicated logic, but with slightly different
  786. * implementations. This will make both use the same implementation, which should make it
  787. * easier to maintain and easier to modify in the future
  788. * @param stream $imap_stream imap connection resource
  789. * @param bool $force force a reload and ignore cache
  790. * @param bool $show_only_subscribed controls listing of visible or all folders
  791. * @param bool $session_register controls registration of retrieved data in session.
  792. * @return object boxesnew - array of mailboxes and their attributes
  793. * @since 1.5.1
  794. */
  795. function sqimap_get_mailboxes($imap_stream,$force=false,$show_only_subscribed=true,$session_register=true) {
  796. global $show_only_subscribed_folders,$noselect_fix_enable,$folder_prefix,
  797. $list_special_folders_first,$imap_server_type;
  798. $inbox_subscribed = false;
  799. $listsubscribed = sqimap_capability($imap_stream,'LIST-SUBSCRIBED');
  800. if ($show_only_subscribed) { $show_only_subscribed=$show_only_subscribed_folders; }
  801. //require_once(SM_PATH . 'include/load_prefs.php');
  802. /**
  803. * There are three main listing commands we can use in IMAP:
  804. * LSUB shows just the list of subscribed folders
  805. * may include flags, but these are not necessarily accurate or authoratative
  806. * \NoSelect has special meaning: the folder does not exist -OR- it means this
  807. * folder is not subscribed but children may be
  808. * [RFC-2060]
  809. * LIST this shows every mailbox on the system
  810. * flags are always included and are accurate and authoratative
  811. * \NoSelect means folder should not be selected
  812. * [RFC-2060]
  813. * LIST (SUBSCRIBED) implemented with LIST-SUBSCRIBED extension
  814. * this is like list but returns only subscribed folders
  815. * flag meanings are like LIST, not LSUB
  816. * \NonExistent means mailbox doesn't exist
  817. * \PlaceHolder means parent is not valid (selectable), but one or more children are
  818. * \NoSelect indeed means that the folder should not be selected
  819. * IMAPEXT-LIST-EXTENSIONS-04 August 2003 B. Leiba
  820. */
  821. if (!$show_only_subscribed) {
  822. $lsub = 'LIST';
  823. $sub_cache_name='list_cache';
  824. } elseif ($listsubscribed) {
  825. $lsub = 'LIST (SUBSCRIBED)';
  826. $sub_cache_name='listsub_cache';
  827. } else {
  828. $lsub = 'LSUB';
  829. $sub_cache_name='lsub_cache';
  830. }
  831. // Some IMAP servers allow subfolders to exist even if the parent folders do not
  832. // This fixes some problems with the folder list when this is the case, causing the
  833. // NoSelect folders to be displayed
  834. if ($noselect_fix_enable) {
  835. $lsub_args = "$lsub \"$folder_prefix\" \"*%\"";
  836. $list_args = "LIST \"$folder_prefix\" \"*%\"";
  837. } else {
  838. $lsub_args = "$lsub \"$folder_prefix\" \"*\"";
  839. $list_args = "LIST \"$folder_prefix\" \"*\"";
  840. }
  841. // get subscribed mailbox list from cache (session)
  842. // if not there, then get it from the imap server and store in cache
  843. if (!$force) {
  844. sqgetGlobalVar($sub_cache_name,$lsub_cache,SQ_SESSION);
  845. }
  846. $lsub_assoc_ary=array();
  847. if (!empty($lsub_cache)) {
  848. $lsub_assoc_ary=$lsub_cache;
  849. } else {
  850. $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args, true, $response, $message);
  851. $lsub_ary = compact_mailboxes_response($lsub_ary);
  852. if (!empty($lsub_ary)) {
  853. foreach ($lsub_ary as $rawline) {
  854. $temp_mailbox_name=find_mailbox_name($rawline);
  855. $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
  856. }
  857. unset($lsub_ary);
  858. sqsession_register($lsub_assoc_ary,$sub_cache_name);
  859. }
  860. }
  861. // Now to get the mailbox flags
  862. // The LSUB response may return \NoSelect flags, etc. but it is optional
  863. // according to RFC3501, and even when returned it may not be accurate
  864. // or authoratative. LIST will always return accurate results.
  865. if (($lsub == 'LIST') || ($lsub == 'LIST (SUBSCRIBED)')) {
  866. // we've already done a LIST or LIST (SUBSCRIBED)
  867. // and NOT a LSUB, so no need to do it again
  868. $list_assoc_ary = $lsub_assoc_ary;
  869. } else {
  870. // we did a LSUB so now we need to do a LIST
  871. // first see if it is in cache
  872. $list_cache_name='list_cache';
  873. if (!$force) {
  874. sqgetGlobalVar($list_cache_name,$list_cache,SQ_SESSION);
  875. }
  876. if (!empty($list_cache)) {
  877. $list_assoc_ary=$list_cache;
  878. // we could store this in list_cache_name but not necessary
  879. } else {
  880. // not in cache so we need to go get it from the imap server
  881. $list_assoc_ary = array();
  882. $list_ary = sqimap_run_command($imap_stream, $list_args,
  883. true, $response, $message);
  884. $list_ary = compact_mailboxes_response($list_ary);
  885. if (!empty($list_ary)) {
  886. foreach ($list_ary as $rawline) {
  887. $temp_mailbox_name=find_mailbox_name($rawline);
  888. $list_assoc_ary[$temp_mailbox_name]=$rawline;
  889. }
  890. unset($list_ary);
  891. sqsession_register($list_assoc_ary,$list_cache_name);
  892. }
  893. }
  894. }
  895. // If they aren't subscribed to the inbox, then add it anyway (if its in LIST)
  896. $inbox_subscribed=false;
  897. if (!empty($lsub_assoc_ary)) {
  898. foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
  899. if (strtoupper($temp_mailbox_name) == 'INBOX') {
  900. $inbox_subscribed=true;
  901. }
  902. }
  903. }
  904. if (!$inbox_subscribed) {
  905. if (!empty($list_assoc_ary)) {
  906. foreach ($list_assoc_ary as $temp_mailbox_name=>$rawline) {
  907. if (strtoupper($temp_mailbox_name) == 'INBOX') {
  908. $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
  909. }
  910. }
  911. }
  912. }
  913. // Now we have the raw output, we need to create an array of mailbox names we will return
  914. if (!$show_only_subscribed) {
  915. $final_folders_assoc_ary=$list_assoc_ary;
  916. } else {
  917. /**
  918. * only show subscribed folders
  919. * we need to merge the folders here... we can't trust the flags, etc. from the lsub_assoc_array
  920. * so we use the lsub_assoc_array as the list of folders and the values come from list_assoc_array
  921. */
  922. if (!empty($lsub_assoc_ary)) {
  923. foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
  924. if (!empty($list_assoc_ary[$temp_mailbox_name])) {
  925. $final_folders_assoc_ary[$temp_mailbox_name]=$list_assoc_ary[$temp_mailbox_name];
  926. }
  927. }
  928. }
  929. }
  930. // Now produce a flat, sorted list
  931. if (!empty($final_folders_assoc_ary)) {
  932. uksort($final_folders_assoc_ary,'strnatcasecmp');
  933. foreach ($final_folders_assoc_ary as $temp_mailbox_name=>$rawline) {
  934. $final_folders_ary[]=$rawline;
  935. }
  936. }
  937. // this will put it into an array we can use later
  938. // containing:
  939. // raw - Raw LIST/LSUB response from the IMAP server
  940. // formatted - formatted folder name
  941. // unformatted - unformatted, but with the delimiter at the end removed
  942. // unformated-dm - folder name as it appears in raw response
  943. // unformatted-disp - unformatted without $folder_prefix
  944. // id - the array element number (0, 1, 2, etc.)
  945. // flags - mailbox flags
  946. if (!empty($final_folders_ary)) {
  947. $boxesall = sqimap_mailbox_parse($final_folders_ary);
  948. } else {
  949. // they have no mailboxes
  950. $boxesall=array();
  951. }
  952. /* Now, lets sort for special folders */
  953. $boxesnew = $used = array();
  954. /* Find INBOX */
  955. $cnt = count($boxesall);
  956. $used = array_pad($used,$cnt,false);
  957. $has_inbox = false;
  958. for($k = 0; $k < $cnt; ++$k) {
  959. if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
  960. $boxesnew[] = $boxesall[$k];
  961. $used[$k] = true;
  962. $has_inbox = true;
  963. break;
  964. }
  965. }
  966. if ($has_inbox == false) {
  967. // do a list request for inbox because we should always show
  968. // inbox even if the user isn't subscribed to it.
  969. $inbox_ary = sqimap_run_command($imap_stream, 'LIST "" "INBOX"',
  970. true, $response, $message);
  971. $inbox_ary = compact_mailboxes_response($inbox_ary);
  972. if (count($inbox_ary)) {
  973. $inbox_entry = sqimap_mailbox_parse($inbox_ary);
  974. // add it on top of the list
  975. if (!empty($boxesnew)) {
  976. array_unshift($boxesnew,$inbox_entry[0]);
  977. } else {
  978. $boxesnew[]=$inbox_entry[0];
  979. }
  980. /* array_unshift($used,true); */
  981. }
  982. }
  983. /* List special folders and their subfolders, if requested. */
  984. if ($list_special_folders_first) {
  985. for($k = 0; $k < $cnt; ++$k) {
  986. if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
  987. $boxesnew[] = $boxesall[$k];
  988. $used[$k] = true;
  989. }
  990. }
  991. }
  992. /* Find INBOX's children */
  993. for($k = 0; $k < $cnt; ++$k) {
  994. $isboxbelow=isBoxBelow(strtoupper($boxesall[$k]['unformatted']),'INBOX');
  995. if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
  996. $is_inbox=1;
  997. } else {
  998. $is_inbox=0;
  999. }
  1000. if (!$used[$k] && $isboxbelow && $is_inbox) {
  1001. $boxesnew[] = $boxesall[$k];
  1002. $used[$k] = true;
  1003. }
  1004. }
  1005. /* Rest of the folders */
  1006. for($k = 0; $k < $cnt; $k++) {
  1007. if (!$used[$k]) {
  1008. $boxesnew[] = $boxesall[$k];
  1009. }
  1010. }
  1011. /**
  1012. * Don't register boxes in session, if $session_register is set to false
  1013. * Prevents registration of sqimap_mailbox_list_all() results.
  1014. */
  1015. if ($session_register) sqsession_register($boxesnew,'boxesnew');
  1016. return $boxesnew;
  1017. }
  1018. /**
  1019. * Fills mailbox object
  1020. *
  1021. * this is passed the mailbox array by left_main.php
  1022. * who has previously obtained it from sqimap_get_mailboxes
  1023. * that way, the raw mailbox list is available in left_main to other
  1024. * things besides just sqimap_mailbox_tree
  1025. * imap_stream is just used now to get status info
  1026. *
  1027. * most of the functionality is moved to sqimap_get_mailboxes
  1028. * also takes care of TODO items:
  1029. * caching mailbox tree
  1030. * config setting for UW imap section (not needed now)
  1031. *
  1032. * Some code fragments are present in 1.3.0 - 1.4.4.
  1033. * @param stream $imap_stream imap connection resource
  1034. * @param array $lsub_ary output array from sqimap_get_mailboxes (contains mailboxes and flags)
  1035. * @return object see mailboxes class.
  1036. * @since 1.5.0
  1037. */
  1038. function sqimap_mailbox_tree($imap_stream,$lsub_ary) {
  1039. $sorted_lsub_ary = array();
  1040. $cnt = count($lsub_ary);
  1041. for ($i = 0; $i < $cnt; $i++) {
  1042. $mbx=$lsub_ary[$i]['unformatted'];
  1043. $flags=$lsub_ary[$i]['flags'];
  1044. $noinferiors=0;
  1045. if (in_array('\Noinferiors',$flags)) { $noinferiors=1; }
  1046. if (in_array('\NoInferiors',$flags)) { $noinferiors=1; }
  1047. if (in_array('\HasNoChildren',$flags)) { $noinferiors=1; }
  1048. $noselect=0;
  1049. if (in_array('\NoSelect',$flags)) { $noselect=1; }
  1050. /**
  1051. * LIST (SUBSCRIBED) has two new flags, \NonExistent which means the mailbox is subscribed to
  1052. * but doesn't exist, and \PlaceHolder which is similar (but not the same) as \NoSelect
  1053. * For right now, we'll treat these the same as \NoSelect and this behavior can be changed
  1054. * later if needed
  1055. */
  1056. if (in_array('\NonExistent',$flags)) { $noselect=1; }
  1057. if (in_array('\PlaceHolder',$flags)) { $noselect=1; }
  1058. $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
  1059. }
  1060. $sorted_lsub_ary = array_values($sorted_lsub_ary);
  1061. usort($sorted_lsub_ary, 'mbxSort');
  1062. $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
  1063. return $boxestree;
  1064. }
  1065. /**
  1066. * Callback function used for sorting mailboxes in sqimap_mailbox_tree
  1067. * @param string $a
  1068. * @param string $b
  1069. * @return integer see php strnatcasecmp()
  1070. * @since 1.5.1
  1071. */
  1072. function mbxSort($a, $b) {
  1073. return strnatcasecmp($a['mbx'], $b['mbx']);
  1074. }
  1075. /**
  1076. * Fills mailbox object
  1077. *
  1078. * Some code fragments are present in 1.3.0 - 1.4.4.
  1079. * @param array $mbx_ary
  1080. * @param $mbxs
  1081. * @param stream $imap_stream imap connection resource
  1082. * @return object see mailboxes class
  1083. * @since 1.5.0
  1084. */
  1085. function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
  1086. global $data_dir, $username, $list_special_folders_first,
  1087. $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
  1088. $move_to_trash, $move_to_sent, $save_as_draft,
  1089. $delimiter, $imap_server_type;
  1090. // $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
  1091. /* create virtual root node */
  1092. $mailboxes= new mailboxes();
  1093. $mailboxes->is_root = true;
  1094. $trail_del = false;
  1095. $start = 0;
  1096. if (isset($folder_prefix) && ($folder_prefix != '')) {
  1097. $start = substr_count($folder_prefix,$delimiter);
  1098. if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
  1099. $mailboxes->mailboxname_full = substr($folder_prefix,0, (strlen($folder_prefix)-1));
  1100. } else {
  1101. $mailboxes->mailboxname_full = $folder_prefix;
  1102. $start++;
  1103. }
  1104. $mailboxes->mailboxname_sub = $mailboxes->mailboxname_full;
  1105. } else {
  1106. $start = 0;
  1107. }
  1108. $cnt = count($mbx_ary);
  1109. for ($i=0; $i < $cnt; $i++) {
  1110. if ($mbx_ary[$i]['mbx'] !='' ) {
  1111. $mbx = new mailboxes();
  1112. $mailbox = $mbx_ary[$i]['mbx'];
  1113. /*
  1114. * Set the is_special flag if it concerned a special mailbox.
  1115. * Used for displaying the special folders on top in the mailbox
  1116. * tree displaying code.
  1117. */
  1118. $mbx->is_special |= ($mbx->is_inbox = (strtoupper($mailbox) == 'INBOX'));
  1119. $mbx->is_special |= ($mbx->is_trash = isTrashMailbox($mailbox));
  1120. $mbx->is_special |= ($mbx->is_sent = isSentMailbox($mailbox));
  1121. $mbx->is_special |= ($mbx->is_draft = isDraftMailbox($mailbox));
  1122. if (!$mbx->is_special)
  1123. $mbx->is_special = boolean_hook_function('special_mailbox', $mailbox, 1);
  1124. if (isset($mbx_ary[$i]['unseen'])) {
  1125. $mbx->unseen = $mbx_ary[$i]['unseen'];
  1126. }
  1127. if (isset($mbx_ary[$i]['nummessages'])) {
  1128. $mbx->total = $mbx_ary[$i]['nummessages'];
  1129. }
  1130. $mbx->is_noselect = $mbx_ary[$i]['noselect'];
  1131. $mbx->is_noinferiors = $mbx_ary[$i]['noinferiors'];
  1132. $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
  1133. if ($r_del_pos) {
  1134. $mbx->mailboxname_sub = substr($mbx_ary[$i]['mbx'],$r_del_pos+1);
  1135. } else { /* mailbox is root folder */
  1136. $mbx->mailboxname_sub = $mbx_ary[$i]['mbx'];
  1137. }
  1138. $mbx->mailboxname_full = $mbx_ary[$i]['mbx'];
  1139. $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
  1140. }
  1141. }
  1142. sqimap_utf7_decode_mbx_tree($mailboxes);
  1143. sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
  1144. return $mailboxes;
  1145. }
  1146. /**
  1147. * @param object $mbx_tree
  1148. * @since 1.5.0
  1149. */
  1150. function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
  1151. global $draft_folder, $sent_folder, $trash_folder, $translate_special_folders;
  1152. /* decode folder name and set mailboxname_sub */
  1153. if ($translate_special_folders && strtoupper($mbx_tree->mailboxname_full) == 'INBOX') {
  1154. $mbx_tree->mailboxname_sub = _("INBOX");
  1155. } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $draft_folder) {
  1156. $mbx_tree->mailboxname_sub = _("Drafts");
  1157. } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $sent_folder) {
  1158. $mbx_tree->mailboxname_sub = _("Sent");
  1159. } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $trash_folder) {
  1160. $mbx_tree->mailboxname_sub = _("Trash");
  1161. } else {
  1162. $mbx_tree->mailboxname_sub = imap_utf7_decode_local($mbx_tree->mailboxname_sub);
  1163. }
  1164. if ($mbx_tree->mbxs) {
  1165. $iCnt = count($mbx_tree->mbxs);
  1166. for ($i=0;$i<$iCnt;++$i) {
  1167. sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs[$i]);
  1168. }
  1169. }
  1170. }
  1171. /**
  1172. * @param object $mbx_tree
  1173. * @param array $aMbxs
  1174. * @since 1.5.0
  1175. */
  1176. function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
  1177. if ($mbx_tree)
  1178. $aMbxs[] =& $mbx_tree;
  1179. if ($mbx_tree->mbxs) {
  1180. $iCnt = count($mbx_tree->mbxs);
  1181. for ($i=0;$i<$iCnt;++$i) {
  1182. sqimap_tree_to_ref_array($mbx_tree->mbxs[$i],$aMbxs);
  1183. }
  1184. }
  1185. }
  1186. /**
  1187. * @param stream $imap_stream imap connection resource
  1188. * @param object $mbx_tree
  1189. * @since since 1.5.0
  1190. */
  1191. function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
  1192. global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
  1193. $aMbxs = $aQuery = array();
  1194. sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
  1195. // remove the root node
  1196. array_shift($aMbxs);
  1197. if($unseen_notify == 3) {
  1198. $cnt = count($aMbxs);
  1199. for($i=0;$i<$cnt;++$i) {
  1200. $oMbx =& $aMbxs[$i];
  1201. if (!$oMbx->is_noselect) {
  1202. $mbx = $oMbx->mailboxname_full;
  1203. if ($unseen_type == 2 ||
  1204. ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
  1205. $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (MESSAGES UNSEEN RECENT)';
  1206. } else {
  1207. $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (UNSEEN RECENT)';
  1208. }
  1209. sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
  1210. } else {
  1211. $oMbx->unseen = $oMbx->total = $oMbx->recent = false;
  1212. $tag = false;
  1213. }
  1214. $oMbx->tag = $tag;
  1215. $aMbxs[$i] =& $oMbx;
  1216. }
  1217. // execute all the queries at once
  1218. $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
  1219. $cnt = count($aMbxs);
  1220. for($i=0;$i<$cnt;++$i) {
  1221. $oMbx =& $aMbxs[$i];
  1222. $tag = $oMbx->tag;
  1223. if ($tag && $aServerResponse[$tag] == 'OK') {
  1224. $sResponse = implode('', $aResponse[$tag]);
  1225. if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
  1226. $oMbx->unseen = $regs[1];
  1227. }
  1228. if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
  1229. $oMbx->total = $regs[1];
  1230. }
  1231. if (preg_match('/RECENT\s+([0-9]+)/i', $sResponse, $regs)) {
  1232. $oMbx->recent = $regs[1];
  1233. }
  1234. }
  1235. unset($oMbx->tag);
  1236. }
  1237. } else if ($unseen_notify == 2) { // INBOX only
  1238. $cnt = count($aMbxs);
  1239. for($i=0;$i<$cnt;++$i) {
  1240. $oMbx =& $aMbxs[$i];
  1241. if (strtoupper($oMbx->mailboxname_full) == 'INBOX' ||
  1242. ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
  1243. if ($unseen_type == 2 ||
  1244. ($oMbx->mailboxname_full == $trash_folder && $move_to_trash)) {
  1245. $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full);
  1246. $oMbx->unseen = $aStatus['UNSEEN'];
  1247. $oMbx->total = $aStatus['MESSAGES'];
  1248. $oMbx->recent = $aStatus['RECENT'];
  1249. } else {
  1250. $oMbx->unseen = sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full);
  1251. }
  1252. $aMbxs[$i] =& $oMbx;
  1253. if (!$move_to_trash && $trash_folder) {
  1254. break;
  1255. } else {
  1256. // trash comes after INBOX
  1257. if ($oMbx->mailboxname_full == $trash_folder) {
  1258. break;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. $cnt = count($aMbxs);
  1265. for($i=0;$i<$cnt;++$i) {
  1266. $oMbx =& $aMbxs[$i];
  1267. unset($hook_status);
  1268. if (!empty($oMbx->unseen)) { $hook_status['UNSEEN']=$oMbx->unseen; }
  1269. if (!empty($oMbx->total)) { $hook_status['MESSAGES']=$oMbx->total; }
  1270. if (!empty($oMbx->recent)) { $hook_status['RECENT']=$oMbx->recent; }
  1271. if (!empty($hook_status))
  1272. {
  1273. $hook_status['MAILBOX']=$oMbx->mailboxname_full;
  1274. $hook_status['CALLER']='sqimap_get_status_mbx_tree'; // helps w/ debugging
  1275. do_hook('folder_status', $hook_status);
  1276. }
  1277. }
  1278. }
  1279. /**
  1280. * Checks if folder is noselect (can't store messages)
  1281. *
  1282. * Function does not check if folder subscribed.
  1283. * @param stream $oImapStream imap connection resource
  1284. * @param string $sImapFolder imap folder name
  1285. * @param object $oBoxes mailboxes class object.
  1286. * @return boolean true, when folder has noselect flag. false in any other case.
  1287. * @since 1.5.1
  1288. */
  1289. function sqimap_mailbox_is_noselect($oImapStream,$sImapFolder,&$oBoxes) {
  1290. // build mailbox object if it is not available
  1291. if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
  1292. foreach($oBoxes as $box) {
  1293. if ($box['unformatted']==$sImapFolder) {
  1294. return (bool) check_is_noselect($box['raw']);
  1295. }
  1296. }
  1297. return false;
  1298. }
  1299. /**
  1300. * Checks if folder is noinferiors (can't store other folders)
  1301. *
  1302. * Function does not check if folder subscribed.
  1303. * @param stream $oImapStream imap connection resource
  1304. * @param string $sImapFolder imap folder name
  1305. * @param object $oBoxes mailboxes class object.
  1306. * @return boolean true, when folder has noinferiors flag. false in any other case.
  1307. * @since 1.5.1
  1308. */
  1309. function sqimap_mailbox_is_noinferiors($oImapStream,$sImapFolder,&$oBoxes) {
  1310. // build mailbox object if it is not available
  1311. if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
  1312. foreach($oBoxes as $box) {
  1313. if ($box['unformatted']==$sImapFolder) {
  1314. return (bool) check_is_noinferiors($box['raw']);
  1315. }
  1316. }
  1317. return false;
  1318. }