imap_mailbox.php 48 KB

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