imap_mailbox.php 52 KB

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