imap_mailbox.php 53 KB

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