imap_mailbox.php 57 KB

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