imap_mailbox.php 57 KB

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