imap_mailbox.php 54 KB

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