mailbox_display.php 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049
  1. <?php
  2. /**
  3. * mailbox_display.php
  4. *
  5. * Copyright (c) 1999-2004 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This contains functions that display mailbox information, such as the
  9. * table row that has sender, date, subject, etc...
  10. *
  11. * @version $Id$
  12. * @package squirrelmail
  13. */
  14. /** The standard includes.. */
  15. require_once(SM_PATH . 'functions/strings.php');
  16. require_once(SM_PATH . 'functions/html.php');
  17. require_once(SM_PATH . 'class/html.class.php');
  18. require_once(SM_PATH . 'functions/imap_mailbox.php');
  19. require_once(SM_PATH . 'functions/imap_messages.php');
  20. require_once(SM_PATH . 'functions/imap_asearch.php');
  21. require_once(SM_PATH . 'functions/mime.php');
  22. require_once(SM_PATH . 'functions/forms.php');
  23. /**
  24. * default value for page_selector_max
  25. */
  26. define('PG_SEL_MAX', 10);
  27. /**
  28. * The number of pages to cache msg headers
  29. */
  30. define('SQM_MAX_PAGES_IN_CACHE',5);
  31. /**
  32. * Sort constants used for sorting of messages
  33. */
  34. define('SQSORT_NONE',0);
  35. define('SQSORT_DATE_ASC',1);
  36. define('SQSORT_DATE_DEC',2);
  37. define('SQSORT_FROM_ASC',3);
  38. define('SQSORT_FROM_DEC',4);
  39. define('SQSORT_SUBJ_ASC',5);
  40. define('SQSORT_SUBJ_DEC',6);
  41. define('SQSORT_SIZE_ASC',7);
  42. define('SQSORT_SIZE_DEC',8);
  43. define('SQSORT_TO_ASC',9);
  44. define('SQSORT_TO_DEC',10);
  45. define('SQSORT_CC_ASC',11);
  46. define('SQSORT_CC_DEC',12);
  47. define('SQSORT_INT_DATE_ASC',13);
  48. define('SQSORT_INT_DATE_DEC',14);
  49. define('SQSORT_THREAD',32);
  50. define('MBX_PREF_SORT',0);
  51. define('MBX_PREF_LIMIT',1);
  52. define('MBX_PREF_AUTO_EXPUNGE',2);
  53. define('MBX_PREF_INTERNALDATE',3);
  54. define('SQM_MAX_MBX_IN_CACHE',3);
  55. // define('MBX_PREF_FUTURE',unique integer key);
  56. /**
  57. * @param mixed $start UNDOCUMENTED
  58. */
  59. function elapsed($start) {
  60. $end = microtime();
  61. list($start2, $start1) = explode(" ", $start);
  62. list($end2, $end1) = explode(" ", $end);
  63. $diff1 = $end1 - $start1;
  64. $diff2 = $end2 - $start2;
  65. if( $diff2 < 0 ){
  66. $diff1 -= 1;
  67. $diff2 += 1.0;
  68. }
  69. return $diff2 + $diff1;
  70. }
  71. /**
  72. * Displays message header row in messages list
  73. *
  74. * @param array $aMsg contains all message related parameters
  75. * @return void
  76. */
  77. function printMessageInfo($aMsg) {
  78. // FIX ME, remove these globals as well by adding an array as argument for the user settings
  79. // specificly meant for header display
  80. global $checkall,
  81. $color,
  82. $default_use_priority,
  83. $message_highlight_list,
  84. $index_order,
  85. $truncate_sender, /* number of characters for From/To field (<= 0 for unchanged) */
  86. $email_address,
  87. $show_recipient_instead, /* show recipient name instead of default identity */
  88. $use_icons, /* indicates to use icons or text markers */
  89. $icon_theme; /* icons theming */
  90. $color_string = $color[4];
  91. // initialisation:
  92. $mailbox = $aMsg['MAILBOX'];
  93. $msg = $aMsg['HEADER'];
  94. $t = $aMsg['INDX'];
  95. $start_msg = $aMsg['PAGEOFFSET'];
  96. $last = $aMsg['LAST'];
  97. if (isset($aMsg['SEARCH']) && count($aMsg['SEARCH']) >1 ) {
  98. $where = $aMsg['SEARCH'][0];
  99. $what = $aMsg['SEARCH'][1];
  100. } else {
  101. $where = false;
  102. $what = false;
  103. }
  104. $iIndent = $aMsg['INDENT'];
  105. $sSubject = (isset($msg['SUBJECT']) && $msg['SUBJECT'] != '') ? $msg['SUBJECT'] : _("(no subject)");
  106. $sFrom = (isset($msg['FROM'])) ? $msg['FROM'] : _("Unknown sender");
  107. $sTo = (isset($msg['TO'])) ? $msg['TO'] : _("Unknown recipient");
  108. $sCc = (isset($msg['CC'])) ? $msg['CC'] : '';
  109. $aFlags = (isset($msg['FLAGS'])) ? $msg['FLAGS'] : array();
  110. $iPrio = (isset($msg['PRIORITY'])) ? $msg['PRIORITY'] : 3;
  111. $iSize = (isset($msg['SIZE'])) ? $msg['SIZE'] : 0;
  112. $sType0 = (isset($msg['TYPE0'])) ? $msg['TYPE0'] : 'text';
  113. $sType1 = (isset($msg['TYPE1'])) ? $msg['TYPE1'] : 'plain';
  114. if (isset($msg['INTERNALDATE'])) {
  115. $sDate = getDateString(getTimeStamp(explode(' ',$msg['INTERNALDATE'])));
  116. } else {
  117. $sDate = (isset($msg['DATE'])) ? getDateString(getTimeStamp(explode(' ',$msg['DATE']))) : '';
  118. }
  119. $iId = (isset($msg['UID'])) ? $msg['UID'] : false;
  120. if (!$iId) {
  121. return;
  122. }
  123. if ($GLOBALS['alt_index_colors']) {
  124. if (!($t % 2)) {
  125. if (!isset($color[12])) {
  126. $color[12] = '#EAEAEA';
  127. }
  128. $color_string = $color[12];
  129. }
  130. }
  131. $urlMailbox = urlencode($mailbox);
  132. // FIXME, foldertype should be set in right_main.php
  133. // in other words, handle as sent is obsoleted from now.
  134. // We replace that by providing an array to aMailbox with the to shown headers
  135. // that way we are free to show the user different layouts for different folders
  136. $bSentFolder = handleAsSent($mailbox);
  137. if ((!$bSentFolder) && ($show_recipient_instead)) {
  138. // If the From address is the same as $email_address, then handle as Sent
  139. $from_array = parseAddress($sFrom, 1);
  140. if (!isset($email_address)) {
  141. global $datadir, $username;
  142. $email_address = getPref($datadir, $username, 'email_address');
  143. }
  144. $bHandleAsSent = ((isset($from_array[0][0])) && ($from_array[0][0] == $email_address));
  145. } else {
  146. $bHandleAsSent = $bSentFolder;
  147. }
  148. // If this is a Sent message, display To address instead of From
  149. if ($bHandleAsSent) {
  150. $sFrom = $sTo;
  151. }
  152. // Passing 1 below results in only 1 address being parsed, thus defeating the following code
  153. $sFrom = parseAddress($sFrom/*,1*/);
  154. /*
  155. * This is done in case you're looking into Sent folders,
  156. * because you can have multiple receivers.
  157. */
  158. $senderNames = $sFrom;
  159. $senderName = '';
  160. $senderAddress = '';
  161. if (sizeof($senderNames)){
  162. foreach ($senderNames as $senderNames_part) {
  163. if ($senderName != '') {
  164. $senderName .= ', ';
  165. $senderAddress .= ', ';
  166. }
  167. $sender_address_part = htmlspecialchars($senderNames_part[0]);
  168. $sender_name_part = str_replace('&nbsp;',' ', decodeHeader($senderNames_part[1]));
  169. if ($sender_name_part) {
  170. $senderName .= $sender_name_part;
  171. $senderAddress .= $sender_name_part . ' <' . $sender_address_part . '>';
  172. } else {
  173. $senderName .= $sender_address_part;
  174. $senderAddress .= $sender_address_part;
  175. }
  176. }
  177. }
  178. // If Sent, prefix with To: but only if not Sent folder
  179. if ($bHandleAsSent ^ $bSentFolder) {
  180. $senderName = _("To:") . ' ' . $senderName;
  181. $senderAddress = _("To:") . ' ' . $senderAddress;
  182. }
  183. // this is a column property which can apply to multiple columns. Do not use vars for one column
  184. // only. instead we should use something like this:
  185. // 1ed column $aMailbox['columns']['SUBJECT'] value: aray with properties ...
  186. // 2ed column $aMailbox['columns']['FROM'] value: aray with properties ...
  187. // NB in case of the sentfolder this could be the TO field
  188. // properties array example:
  189. // 'truncate' => length (0 is no truncate)
  190. // 'prefix => if (x in b then do that )
  191. if ($truncate_sender > 0) {
  192. $senderName = truncateWithEntities($senderName, $truncate_sender);
  193. }
  194. $flag = $flag_end = $bold = $bold_end = $fontstr = $fontstr_end = $italic = $italic_end = '';
  195. $bold = '<b>';
  196. $bold_end = '</b>';
  197. foreach ($aFlags as $sFlag => $value) {
  198. switch ($sFlag) {
  199. case '\\flagged':
  200. if ($value) {
  201. $flag = "<font color=\"$color[2]\">";
  202. $flag_end = '</font>';
  203. }
  204. break;
  205. case '\\seen':
  206. if ($value) {
  207. $bold = '';
  208. $bold_end = '';
  209. }
  210. break;
  211. case '\\deleted':
  212. if ($value) {
  213. $fontstr = "<font color=\"$color[9]\">";
  214. $fontstr_end = '</font>';
  215. }
  216. break;
  217. }
  218. }
  219. if ($bHandleAsSent) {
  220. $italic = '<i>';
  221. $italic_end = '</i>';
  222. }
  223. if ($where && $what) {
  224. $searchstr = '&amp;where='.$where.'&amp;what='.$what;
  225. } else {
  226. $searchstr = '';
  227. }
  228. /*
  229. * Message highlight code
  230. */
  231. $matches = array('TO' => 'sTo', 'CC' => 'sCc', 'FROM' => 'sFrom', 'SUBJECT' => 'sSubject');
  232. if (is_array($message_highlight_list) && count($message_highlight_list)) {
  233. $sTo = parseAddress($sTo);
  234. $sCc = parseAddress($sCc);
  235. foreach ($message_highlight_list as $message_highlight_list_part) {
  236. if (trim($message_highlight_list_part['value']) != '') {
  237. $high_val = strtolower($message_highlight_list_part['value']);
  238. $match_type = strtoupper($message_highlight_list_part['match_type']);
  239. if($match_type == 'TO_CC') {
  240. $match = array('TO', 'CC');
  241. } else {
  242. $match = array($match_type);
  243. }
  244. foreach($match as $match_type) {
  245. switch($match_type) {
  246. case('TO'):
  247. case('CC'):
  248. case('FROM'):
  249. foreach ($$matches[$match_type] as $address) {
  250. $address[0] = decodeHeader($address[0], true, false);
  251. $address[1] = decodeHeader($address[1], true, false);
  252. if (strstr('^^' . strtolower($address[0]), $high_val) ||
  253. strstr('^^' . strtolower($address[1]), $high_val)) {
  254. $hlt_color = $message_highlight_list_part['color'];
  255. break 4;
  256. }
  257. }
  258. break;
  259. default:
  260. $headertest = strtolower(decodeHeader($$matches[$match_type], true, false));
  261. if (strstr('^^' . $headertest, $high_val)) {
  262. $hlt_color = $message_highlight_list_part['color'];
  263. break 3;
  264. }
  265. break;
  266. }
  267. }
  268. }
  269. }
  270. } /* end Message highlight code */
  271. if (!isset($hlt_color)) {
  272. $hlt_color = $color_string;
  273. }
  274. $col = 0;
  275. $sSubject = str_replace('&nbsp;', ' ', decodeHeader($sSubject));
  276. $subject = processSubject($sSubject, $iIndent);
  277. echo html_tag( 'tr','','','','VALIGN="top"') . "\n";
  278. if (sizeof($index_order)) {
  279. foreach ($index_order as $index_order_part) {
  280. switch ($index_order_part) {
  281. case 1: /* checkbox */
  282. echo html_tag( 'td',
  283. addCheckBox("msg[$t]", $checkall, $iId),
  284. 'center',
  285. $hlt_color );
  286. break;
  287. case 2: /* from */
  288. if ($senderAddress != $senderName) {
  289. $senderAddress = strtr($senderAddress, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
  290. $title = ' title="' . str_replace('"', "''", $senderAddress) . '"';
  291. } else {
  292. $title = '';
  293. }
  294. echo html_tag( 'td',
  295. $italic . $bold . $flag . $fontstr . $senderName .
  296. $fontstr_end . $flag_end . $bold_end . $italic_end,
  297. 'left',
  298. $hlt_color, $title );
  299. break;
  300. case 3: /* date */
  301. if ($sDate == '') {
  302. $sDate = _("Unknown date");
  303. }
  304. echo html_tag( 'td',
  305. $bold . $flag . $fontstr . $sDate .
  306. $fontstr_end . $flag_end . $bold_end,
  307. 'center',
  308. $hlt_color,
  309. 'nowrap' );
  310. break;
  311. case 4: /* subject */
  312. $td_str = $bold;
  313. if ($iIndent) {
  314. $td_str .= str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$iIndent);
  315. }
  316. $td_str .= '<a href="read_body.php?mailbox='.$urlMailbox
  317. . '&amp;passed_id='. $iId
  318. . '&amp;startMessage='.$start_msg.$searchstr.'"';
  319. $td_str .= ' ' .concat_hook_function('subject_link', array($start_msg, $searchstr));
  320. if ($subject != $sSubject) {
  321. $title = get_html_translation_table(HTML_SPECIALCHARS);
  322. $title = array_flip($title);
  323. $title = strtr($sSubject, $title);
  324. $title = str_replace('"', "''", $title);
  325. $td_str .= " title=\"$title\"";
  326. }
  327. $td_str .= ">$flag$subject$flag_end</a>$bold_end";
  328. echo html_tag( 'td', $td_str, 'left', $hlt_color );
  329. break;
  330. case 5: /* flags */
  331. // icon message markers
  332. //
  333. if ($use_icons && $icon_theme != 'none') {
  334. $td_str = "<b><small>";
  335. if (isset($aFlags['\\flagged']) && $aFlags['\\flagged'] == true) {
  336. $td_str .= '<img src="' . SM_PATH . 'images/themes/' . $icon_theme . '/flagged.png" border="0" height="10" width="10" /> ';
  337. }
  338. if ($default_use_priority) {
  339. if ( ($iPrio == 1) || ($iPrio == 2) ) {
  340. $td_str .= '<img src="' . SM_PATH . 'images/themes/' . $icon_theme . '/prio_high.png" border="0" height="10" width="5" /> ';
  341. }
  342. else if ($iPrio == 5) {
  343. $td_str .= '<img src="' . SM_PATH . 'images/themes/' . $icon_theme . '/prio_low.png" border="0" height="10" width="5" /> ';
  344. }
  345. else {
  346. $td_str .= '<img src="' . SM_PATH . 'images/themes/' . $icon_theme . '/transparent.png" border="0" width="5" /> ';
  347. }
  348. }
  349. if ($sType1 == 'mixed') {
  350. $td_str .= '<img src="' . SM_PATH . 'images/themes/' . $icon_theme . '/attach.png" border="0" height="10" width="6" />';
  351. } else {
  352. $td_str .= '<img src="' . SM_PATH . 'images/themes/' . $icon_theme . '/transparent.png" border="0" width="6" />';
  353. }
  354. $msg_icon = '';
  355. if (!isset($aFlags['\\seen']) || ($aFlags['\\seen']) == false) {
  356. $msg_alt = '(' . _("New") . ')';
  357. $msg_title = '(' . _("New") . ')';
  358. $msg_icon .= SM_PATH . 'images/themes/' . $icon_theme . '/msg_new';
  359. } else {
  360. $msg_alt = '(' . _("Read") . ')';
  361. $msg_title = '(' . _("Read") . ')';
  362. $msg_icon .= SM_PATH . 'images/themes/' . $icon_theme . '/msg_read';
  363. }
  364. if (isset($aFlags['\\deleted']) && ($aFlags['\\deleted']) == true) {
  365. $msg_icon .= '_deleted';
  366. }
  367. if (isset($aFlags['\\answered']) && ($aFlags['\\answered']) == true) {
  368. $msg_alt = '(' . _("Answered") . ')';
  369. $msg_title = '(' . _("Answered") . ')';
  370. $msg_icon .= '_reply';
  371. }
  372. $td_str .= '<img src="' . $msg_icon . '.png" border="0" alt="'. $msg_alt . '" title="' . $msg_title . '" height="12" width="18" />';
  373. $td_str .= '</small></b>';
  374. echo html_tag( 'td',
  375. $td_str,
  376. 'right',
  377. $hlt_color,
  378. 'nowrap' );
  379. }
  380. // plain text message markers
  381. //
  382. else {
  383. $stuff = false;
  384. $td_str = "<b><small>";
  385. if (isset($aFlags['\\answered']) && $aFlags['\\answered'] == true) {
  386. $td_str .= _("A");
  387. $stuff = true;
  388. }
  389. if ($sType1 == 'mixed') {
  390. $td_str .= '+';
  391. $stuff = true;
  392. }
  393. if ($default_use_priority) {
  394. if ( ($iPrio == 1) || ($iPrio == 2) ) {
  395. $td_str .= "<font color=\"$color[1]\">!</font>";
  396. $stuff = true;
  397. }
  398. if ($iPrio == 5) {
  399. $td_str .= "<font color=\"$color[8]\">?</font>";
  400. $stuff = true;
  401. }
  402. }
  403. if (isset($aFlags['\\deleted']) && $aFlags['\\deleted'] == true) {
  404. $td_str .= "<font color=\"$color[1]\">D</font>";
  405. $stuff = true;
  406. }
  407. if (!$stuff) {
  408. $td_str .= '&nbsp;';
  409. }
  410. $td_str .= '</small></b>';
  411. echo html_tag( 'td',
  412. $td_str,
  413. 'center',
  414. $hlt_color,
  415. 'nowrap' );
  416. }
  417. break;
  418. case 6: /* size */
  419. echo html_tag( 'td',
  420. $bold . $fontstr . show_readable_size($iSize) .
  421. $fontstr_end . $bold_end,
  422. 'right',
  423. $hlt_color );
  424. break;
  425. }
  426. ++$col;
  427. }
  428. }
  429. /* html for separationlines between rows */
  430. if ($last) {
  431. echo '</tr>'."\n";
  432. } else {
  433. echo '</tr>' . "\n" . '<tr><td colspan="' . $col . '" bgcolor="' .
  434. $color[0] . '" height="1"></td></tr>' . "\n";
  435. }
  436. }
  437. function setUserPref($username, $pref, $value) {
  438. global $data_dir;
  439. setPref($data_dir,$username,$pref,$value);
  440. }
  441. /**
  442. * Selects a mailbox for header retrieval.
  443. * Cache control for message headers is embedded.
  444. *
  445. * @param resource $imapConnection imap socket handle
  446. * @param string $mailbox mailbox to select and retrieve message headers from
  447. * @param array $aConfig array with system config settings and incoming vars
  448. * @param array $aProps mailbox specific properties
  449. * @return array $aMailbox mailbox array with all relevant information
  450. * @author Marc Groot Koerkamp
  451. */
  452. function sqm_api_mailbox_select($imapConnection,$mailbox,$aConfig,$aProps) {
  453. /**
  454. * NB: retrieve this from the session before accessing this function
  455. * and make sure you write it back at the end of the script after
  456. * the aMailbox var is added so that the headers are added to the cache
  457. */
  458. global $mailbox_cache;
  459. /**
  460. * In case the properties arrays are empty set the defaults.
  461. */
  462. $aDefaultMbxPref = array ();
  463. // MBX_PREF_SORT => 0,
  464. // MBX_PREF_LIMIT => 15,
  465. // MBX_PREF_AUTO_EXPUNGE => 0,
  466. // MBX_PREF_INTERNALDATE => 0
  467. // );
  468. /* array_merge doesn't work with integers as keys */
  469. // foreach ($aDefaultMbxPref as $key => $value) {
  470. // if (!isset($aProps[$key])) {
  471. // $aProps[$key] = $value;
  472. // }
  473. // }
  474. $aDefaultConfigProps = array(
  475. // 'allow_thread_sort' => 0,
  476. 'allow_server_sort' => sqimap_capability($imapConnection,'SORT'),
  477. // 'charset' => 'US-ASCII',
  478. 'user' => false, /* no pref storage if false */
  479. 'setindex' => 0,
  480. // 'search' => 'ALL',
  481. 'max_cache_size' => SQM_MAX_MBX_IN_CACHE
  482. );
  483. $aConfig = array_merge($aDefaultConfigProps,$aConfig);
  484. $iSetIndx = $aConfig['setindex'];
  485. $aMbxResponse = sqimap_mailbox_select($imapConnection, $mailbox);
  486. if ($mailbox_cache) {
  487. if (isset($mailbox_cache[$mailbox])) {
  488. $aCachedMailbox = $mailbox_cache[$mailbox];
  489. } else {
  490. $aCachedMailbox = false;
  491. }
  492. /* cleanup cache */
  493. if (count($mailbox_cache) > $aConfig['max_cache_size'] -1) {
  494. $aTime = array();
  495. foreach($mailbox_cache as $cachedmailbox => $aVal) {
  496. $aTime[$aVal['TIMESTAMP']] = $cachedmailbox;
  497. }
  498. if (ksort($aTime,SORT_NUMERIC)) {
  499. for ($i=0,$iCnt=count($mailbox_cache);$i<($iCnt-$aConfig['max_cache_size']);++$i) {
  500. $sOldestMbx = array_shift($aTime);
  501. /**
  502. * Remove only the UIDSET and MSG_HEADERS from cache because those can
  503. * contain large amounts of data.
  504. */
  505. if (isset($mailbox_cache[$sOldestMbx]['UIDSET'])) {
  506. $mailbox_cache[$sOldestMbx]['UIDSET']= false;
  507. }
  508. if (isset($mailbox_cache[$sOldestMbx]['MSG_HEADERS'])) {
  509. $mailbox_cache[$sOldestMbx]['MSG_HEADERS'] = false;
  510. }
  511. }
  512. }
  513. }
  514. } else {
  515. $aCachedMailbox = false;
  516. }
  517. /**
  518. * Deal with imap servers that do not return the required UIDNEXT or
  519. * UIDVALIDITY response
  520. * from a SELECT call (since rfc 3501 it's required).
  521. */
  522. if (!isset($aMbxResponse['UIDNEXT']) || !isset($aMbxResponse['UIDVALIDITY'])) {
  523. $aStatus = sqimap_status_messages($imapConnection,$mailbox,
  524. array('UIDNEXT','UIDVALIDITY'));
  525. $aMbxResponse['UIDNEXT'] = $aStatus['UIDNEXT'];
  526. $aMbxResponse['UIDVALIDTY'] = $aStatus['UIDVALIDITY'];
  527. }
  528. $aMailbox['UIDSET'][$iSetIndx] = false;
  529. $aMailbox['ID'] = false;
  530. $aMailbox['SETINDEX'] = $iSetIndx;
  531. if ($aCachedMailbox) {
  532. /**
  533. * Validate integrity of cached data
  534. */
  535. if ($aCachedMailbox['EXISTS'] == $aMbxResponse['EXISTS'] &&
  536. $aMbxResponse['EXISTS'] &&
  537. $aCachedMailbox['UIDVALIDITY'] == $aMbxResponse['UIDVALIDITY'] &&
  538. $aCachedMailbox['UIDNEXT'] == $aMbxResponse['UIDNEXT'] &&
  539. isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
  540. (!isset($aConfig['search']) || /* always set search from the searchpage */
  541. $aCachedMailbox['SEARCH'][$iSetIndx] == $aConfig['search'])) {
  542. if (isset($aCachedMailbox['MSG_HEADERS'])) {
  543. $aMailbox['MSG_HEADERS'] = $aCachedMailbox['MSG_HEADERS'];
  544. }
  545. $aMailbox['ID'] = $aCachedMailbox['ID'];
  546. if (isset($aCachedMailbox['UIDSET'][$iSetIndx]) && $aCachedMailbox['UIDSET'][$iSetIndx]) {
  547. if (isset($aProps[MBX_PREF_SORT]) && $aProps[MBX_PREF_SORT] != $aCachedMailbox['SORT'] ) {
  548. $newsort = $aProps[MBX_PREF_SORT];
  549. $oldsort = $aCachedMailbox['SORT'];
  550. /**
  551. * If it concerns a reverse sort we do not need to invalidate
  552. * the cached sorted UIDSET, a reverse is sufficient.
  553. */
  554. if ((($newsort % 2) && ($newsort + 1 == $oldsort)) ||
  555. (!($newsort % 2) && ($newsort - 1 == $oldsort))) {
  556. $aMailbox['UIDSET'][$iSetIndx] = array_reverse($aCachedMailbox['UIDSET'][$iSetIndx]);
  557. } else {
  558. $server_sort_array = false;
  559. $aMailbox['MSG_HEADERS'] = false;
  560. $aMailbox['ID'] = false;
  561. }
  562. // store the new sort value in the mailbox pref
  563. if ($aConfig['user']) {
  564. // FIXME, in ideal situation, we write back the
  565. // prefs at the end of the script
  566. setUserPref($aConfig['user'],"pref_$mailbox",serialize($aProps));
  567. }
  568. } else {
  569. $aMailbox['UIDSET'][$iSetIndx] = $aCachedMailbox['UIDSET'][$iSetIndx];
  570. }
  571. }
  572. }
  573. }
  574. /**
  575. * Restore the offset in the paginator if no new offset is provided.
  576. */
  577. if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['offset']) && $aCachedMailbox['OFFSET']) {
  578. $aMailbox['OFFSET'] = $aCachedMailbox['OFFSET'];
  579. $aMailbox['PAGEOFFSET'] = $aCachedMailbox['PAGEOFFSET'];
  580. } else {
  581. $aMailbox['OFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ? $aConfig['offset'] -1 : 0;
  582. $aMailbox['PAGEOFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ? $aConfig['offset'] : 1;
  583. }
  584. /**
  585. * Restore the showall value no new showall value is provided.
  586. */
  587. if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['showall']) &&
  588. isset($aCachedMailbox['SHOWALL'][$iSetIndx]) && $aCachedMailbox['SHOWALL'][$iSetIndx]) {
  589. $aMailbox['SHOWALL'][$iSetIndx] = $aCachedMailbox['SHOWALL'][$iSetIndx];
  590. } else {
  591. $aMailbox['SHOWALL'][$iSetIndx] = (isset($aConfig['showall']) && $aConfig['showall']) ? 1 : 0;
  592. }
  593. if (!isset($aProps[MBX_PREF_SORT]) && isset($aCachedMailbox['SORT'])) {
  594. $aMailbox['SORT'] = $aCachedMailbox['SORT'];
  595. } else {
  596. $aMailbox['SORT'] = (isset($aProps[MBX_PREF_SORT])) ? $aProps[MBX_PREF_SORT] : 0;
  597. }
  598. if (!isset($aProps[MBX_PREF_LIMIT]) && isset($aCachedMailbox['LIMIT'])) {
  599. $aMailbox['LIMIT'] = $aCachedMailbox['LIMIT'];
  600. } else {
  601. $aMailbox['LIMIT'] = (isset($aProps[MBX_PREF_LIMIT])) ? $aProps[MBX_PREF_LIMIT] : 15;
  602. }
  603. if (!isset($aProps[MBX_PREF_INTERNALDATE]) && isset($aCachedMailbox['INTERNALDATE'])) {
  604. $aMailbox['INTERNALDATE'] = $aCachedMailbox['INTERNALDATE'];
  605. } else {
  606. $aMailbox['INTERNALDATE'] = (isset($aProps[MBX_PREF_INTERNALDATE])) ? $aProps[MBX_PREF_INTERNALDATE] : false;
  607. }
  608. if (!isset($aProps[MBX_PREF_AUTO_EXPUNGE]) && isset($aCachedMailbox['AUTO_EXPUNGE'])) {
  609. $aMailbox['AUTO_EXPUNGE'] = $aCachedMailbox['AUTO_EXPUNGE'];
  610. } else {
  611. $aMailbox['AUTO_EXPUNGE'] = (isset($aProps[MBX_PREF_AUTO_EXPUNGE])) ? $aProps[MBX_PREF_AUTO_EXPUNGE] : false;
  612. }
  613. if (!isset($aConfig['allow_thread_sort']) && isset($aCachedMailbox['ALLOW_THREAD'])) {
  614. $aMailbox['ALLOW_THREAD'] = $aCachedMailbox['ALLOW_THREAD'];
  615. } else {
  616. $aMailbox['ALLOW_THREAD'] = (isset($aConfig['allow_thread_sort'])) ? $aConfig['allow_thread_sort'] : false;
  617. }
  618. if (!isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx])) {
  619. $aMailbox['SEARCH'][$iSetIndx] = $aCachedMailbox['SEARCH'][$iSetIndx];
  620. } else {
  621. $aMailbox['SEARCH'][$iSetIndx] = (isset($aConfig['search'])) ? $aConfig['search'] : 'ALL';
  622. }
  623. if (!isset($aConfig['charset']) && isset($aCachedMailbox['CHARSET'][$iSetIndx])) {
  624. $aMailbox['CHARSET'][$iSetIndx] = $aCachedMailbox['CHARSET'][$iSetIndx];
  625. } else {
  626. $aMailbox['CHARSET'][$iSetIndx] = (isset($aConfig['charset'])) ? $aConfig['charset'] : 'US-ASCII';
  627. }
  628. $aMailbox['NAME'] = $mailbox;
  629. $aMailbox['EXISTS'] = $aMbxResponse['EXISTS'];
  630. $aMailbox['SEEN'] = (isset($aMbxResponse['SEEN'])) ? $aMbxResponse['SEEN'] : $aMbxResponse['EXISTS'];
  631. $aMailbox['RECENT'] = (isset($aMbxResponse['RECENT'])) ? $aMbxResponse['RECENT'] : 0;
  632. $aMailbox['UIDVALIDITY'] = $aMbxResponse['UIDVALIDITY'];
  633. $aMailbox['UIDNEXT'] = $aMbxResponse['UIDNEXT'];
  634. $aMailbox['PERMANENTFLAGS'] = $aMbxResponse['PERMANENTFLAGS'];
  635. $aMailbox['RIGHTS'] = $aMbxResponse['RIGHTS'];
  636. /* decide if we are thread sorting or not */
  637. if (!$aMailbox['ALLOW_THREAD']) {
  638. if ($aMailbox['SORT'] & SQSORT_THREAD) {
  639. $aMailbox['SORT'] -= SQSORT_THREAD;
  640. }
  641. }
  642. if ($aMailbox['SORT'] & SQSORT_THREAD) {
  643. $aMailbox['SORT_METHOD'] = 'THREAD';
  644. $aMailbox['THREAD_INDENT'] = $aCachedMailbox['THREAD_INDENT'];
  645. } else if (isset($aConfig['allow_server_sort']) && $aConfig['allow_server_sort']) {
  646. $aMailbox['SORT_METHOD'] = 'SERVER';
  647. $aMailbox['THREAD_INDENT'] = false;
  648. } else {
  649. $aMailbox['SORT_METHOD'] = 'SQUIRREL';
  650. $aMailbox['THREAD_INDENT'] = false;
  651. }
  652. /* set a timestamp for cachecontrol */
  653. $aMailbox['TIMESTAMP'] = time();
  654. return $aMailbox;
  655. }
  656. /**
  657. * Does the $srt $_GET var to field mapping
  658. *
  659. * @param int $srt Field to sort on
  660. * @param bool $bServerSort Server sorting is true
  661. * @return string $sSortField Field to sort on
  662. */
  663. function getSortField($sort,$bServerSort) {
  664. switch($sort) {
  665. case SQSORT_NONE:
  666. $sSortField = 'UID';
  667. break;
  668. case SQSORT_DATE_ASC:
  669. case SQSORT_DATE_DEC:
  670. $sSortField = 'DATE';
  671. break;
  672. case SQSORT_FROM_ASC:
  673. case SQSORT_FROM_DEC:
  674. $sSortField = 'FROM';
  675. break;
  676. case SQSORT_SUBJ_ASC:
  677. case SQSORT_SUBJ_DEC:
  678. $sSortField = 'SUBJECT';
  679. break;
  680. case SQSORT_SIZE_ASC:
  681. case SQSORT_SIZE_DEC:
  682. $sSortField = ($bServerSort) ? 'SIZE' : 'RFC822.SIZE';
  683. break;
  684. case SQSORT_TO_ASC:
  685. case SQSORT_TO_DEC:
  686. $sSortField = 'TO';
  687. break;
  688. case SQSORT_CC_ASC:
  689. case SQSORT_CC_DEC:
  690. $sSortField = 'CC';
  691. break;
  692. case SQSORT_INT_DATE_ASC:
  693. case SQSORT_INT_DATE_DEC:
  694. $sSortField = ($bServerSort) ? 'ARRIVAL' : 'INTERNALDATE';
  695. break;
  696. case SQSORT_THREAD:
  697. break;
  698. default: $sSortField = 'UID';
  699. break;
  700. }
  701. return $sSortField;
  702. }
  703. function get_sorted_msgs_list($imapConnection,&$aMailbox,&$error) {
  704. $iSetIndx = (isset($aMailbox['SETINDEX'])) ? $aMailbox['SETINDEX'] : 0;
  705. $bDirection = ($aMailbox['SORT'] % 2);
  706. $error = false;
  707. if (!$aMailbox['SEARCH'][$iSetIndx]) {
  708. $aMailbox['SEARCH'][$iSetIndx] = 'ALL';
  709. }
  710. switch ($aMailbox['SORT_METHOD']) {
  711. case 'THREAD':
  712. $aRes = get_thread_sort($imapConnection,$aMailbox['SEARCH'][$iSetIndx]);
  713. if ($aRes === false) {
  714. $error = '<b><small><center><font color=red>' .
  715. _("Thread sorting is not supported by your IMAP server.") . '<br />' .
  716. _("Please report this to the system administrator.") .
  717. '</center></small></b>';
  718. $aMailbox['SORT'] -= SQSORT_THREAD;
  719. } else {
  720. $aMailbox['UIDSET'][$iSetIndx] = $aRes[0];
  721. $aMailbox['THREAD_INDENT'][$iSetIndx] = $aRes[1];
  722. }
  723. break;
  724. case 'SERVER':
  725. $sSortField = getSortField($aMailbox['SORT'],true);
  726. $id = sqimap_get_sort_order($imapConnection, $sSortField, $bDirection, $aMailbox['SEARCH'][$iSetIndx]);
  727. if ($id === false) {
  728. $error = '<b><small><center><font color=red>' .
  729. _("Server-side sorting is not supported by your IMAP server.") . '<br />' .
  730. _("Please report this to the system administrator.") .
  731. '</center></small></b>';
  732. } else {
  733. $aMailbox['UIDSET'][$iSetIndx] = $id;
  734. }
  735. break;
  736. default:
  737. $id = NULL;
  738. if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') {
  739. $id = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
  740. }
  741. $sSortField = getSortField($aMailbox['SORT'],false);
  742. $aMailbox['UIDSET'][$iSetIndx] = get_squirrel_sort($imapConnection, $sSortField, $bDirection, $id);
  743. break;
  744. }
  745. return $error;
  746. }
  747. function fetchMessageHeaders($imapConnection, &$aMailbox) {
  748. /**
  749. * Retrieve the UIDSET.
  750. * Setindex is used to be able to store multiple uid sets. That will make it
  751. * possible to display the mailbox multiple times in different sort order
  752. * or to store serach results separate from normal mailbox view.
  753. */
  754. $iSetIndx = (isset($aMailbox['SETINDEX'])) ? $aMailbox['SETINDEX'] : 0;
  755. $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $aMailbox['LIMIT'];
  756. /**
  757. * Adjust the start_msg
  758. */
  759. $start_msg = $aMailbox['PAGEOFFSET'];
  760. if($aMailbox['PAGEOFFSET'] > $aMailbox['EXISTS']) {
  761. $start_msg -= $aMailbox['LIMIT'];
  762. if($start_msg < 1) {
  763. $start_msg = 1;
  764. }
  765. }
  766. if (is_array($aMailbox['UIDSET'])) {
  767. $aUid =& $aMailbox['UIDSET'][$iSetIndx];
  768. } else {
  769. $aUid = false;
  770. }
  771. // initialize the fields we want to retrieve:
  772. $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type');
  773. $aFetchItems = array('FLAGS', 'RFC822.SIZE');
  774. // Are we sorting on internaldate then retrieve the internaldate value as well
  775. if ($aMailbox['INTERNALDATE']) {
  776. $aFetchItems[] = 'INTERNALDATE';
  777. }
  778. /**
  779. * A uidset with sorted uid's is available. We can use the cache
  780. */
  781. if (($aMailbox['SORT'] != SQSORT_NONE || $aMailbox['SEARCH'][$iSetIndx] != 'ALL') &&
  782. isset($aUid) && $aUid ) {
  783. // limit the cache to SQM_MAX_PAGES_IN_CACHE
  784. if (!$aMailbox['SHOWALL'][$iSetIndx]) {
  785. $iMaxMsgs = $iLimit * SQM_MAX_PAGES_IN_CACHE;
  786. $iCacheSize = count($aMailbox['MSG_HEADERS']);
  787. if ($iCacheSize > $iMaxMsgs) {
  788. $iReduce = $iCacheSize - $iMaxMsgs;
  789. foreach ($aMailbox['MSG_HEADERS'] as $iUid => $value) {
  790. if ($iReduce) {
  791. unset($aMailbox['MSG_HEADERS'][$iUid]);
  792. } else {
  793. break;
  794. }
  795. --$iReduce;
  796. }
  797. }
  798. }
  799. $id_slice = array_slice($aUid,$start_msg-1,$iLimit);
  800. /* do some funky cache checks */
  801. $aUidCached = array_keys($aMailbox['MSG_HEADERS']);
  802. $aUidNotCached = array_values(array_diff($id_slice,$aUidCached));
  803. /**
  804. * $aUidNotCached contains an array with UID's which need to be fetched to
  805. * complete the needed message headers.
  806. */
  807. if (count($aUidNotCached)) {
  808. $aMsgs = sqimap_get_small_header_list($imapConnection,$aUidNotCached,
  809. $aHeaderFields,$aFetchItems);
  810. // append the msgs to the existend headers
  811. $aMailbox['MSG_HEADERS'] += $aMsgs;
  812. }
  813. } else {
  814. /**
  815. * Initialize the sorted UID list and fetch the visible message headers
  816. */
  817. if ($aMailbox['SORT'] != SQSORT_NONE || $aMailbox['SEARCH'][$iSetIndx] != 'ALL') {// || $aMailbox['SORT_METHOD'] & SQSORT_THREAD 'THREAD') {
  818. $error = false;
  819. if ($aMailbox['SEARCH'][$iSetIndx] && $aMailbox['SORT'] == 0) {
  820. $aUid = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
  821. } else {
  822. $error = get_sorted_msgs_list($imapConnection,$aMailbox,$error);
  823. $aUid = $aMailbox['UIDSET'][$iSetIndx];
  824. }
  825. if ($error === false) {
  826. $id_slice = array_slice($aUid,$aMailbox['OFFSET'], $iLimit);
  827. if (count($id_slice)) {
  828. $aMailbox['MSG_HEADERS'] = sqimap_get_small_header_list($imapConnection,$id_slice,
  829. $aHeaderFields,$aFetchItems);
  830. } else {
  831. return false;
  832. }
  833. } else {
  834. // FIX ME, format message and fallback to squirrel sort
  835. if ($error) {
  836. echo $error;
  837. }
  838. }
  839. } else {
  840. // limit the cache to SQM_MAX_PAGES_IN_CACHE
  841. if (!$aMailbox['SHOWALL'][$iSetIndx] && isset($aMailbox['MSG_HEADERS']) && is_array($aMailbox['MSG_HEADERS'])) {
  842. $iMaxMsgs = $iLimit * SQM_MAX_PAGES_IN_CACHE;
  843. $iCacheSize = count($aMailbox['MSG_HEADERS']);
  844. if ($iCacheSize > $iMaxMsgs) {
  845. $iReduce = $iCacheSize - $iMaxMsgs;
  846. foreach ($aMailbox['MSG_HEADERS'] as $iUid => $value) {
  847. if ($iReduce) {
  848. $iId = $aMailbox['MSG_HEADERS'][$iUid]['ID'];
  849. unset($aMailbox['MSG_HEADERS'][$iUid]);
  850. unset($aMailbox['ID'][$iId]);
  851. } else {
  852. break;
  853. }
  854. --$iReduce;
  855. }
  856. }
  857. }
  858. /**
  859. * retrieve messages by sequence id's and fetch the UID to retrieve
  860. * the UID. for sorted lists this is not needed because a UID FETCH
  861. * automaticly add the UID value in fetch results
  862. **/
  863. $aFetchItems[] = 'UID';
  864. //create id range
  865. $iRangeStart = $aMailbox['EXISTS'] - $aMailbox['OFFSET'];
  866. $iRangeEnd = ($iRangeStart > $iLimit) ?
  867. ($iRangeStart - $iLimit+1):1;
  868. $id_slice = range($iRangeStart, $iRangeEnd);
  869. /**
  870. * Non sorted mailbox with cached message headers
  871. */
  872. if (isset($aMailbox['ID']) && is_array($aMailbox['ID'])) {
  873. // the fetched id => uid relation
  874. $aId = $aMailbox['ID'];
  875. $aIdCached = array();
  876. foreach ($aId as $iId => $iUid) {
  877. if (isset($aMailbox['MSG_HEADERS'][$iUid])) {
  878. if ($iId <= $iRangeStart && $iId >= $iRangeEnd) {
  879. $aIdCached[] = $iId;
  880. }
  881. }
  882. }
  883. $aIdNotCached = array_diff($id_slice,$aIdCached);
  884. } else {
  885. $aIdNotCached = $id_slice;
  886. }
  887. if (count($aIdNotCached)) {
  888. $aMsgs = sqimap_get_small_header_list($imapConnection,$aIdNotCached,
  889. $aHeaderFields,$aFetchItems);
  890. // append the msgs to the existend headers
  891. if (isset($aMailbox['MSG_HEADERS']) && is_array($aMailbox['MSG_HEADERS'])) {
  892. $aMailbox['MSG_HEADERS'] += $aMsgs;
  893. } else {
  894. $aMailbox['MSG_HEADERS'] = $aMsgs;
  895. }
  896. // update the ID array
  897. foreach ($aMsgs as $iUid => $aMsg) {
  898. if (isset($aMsg['ID'])) {
  899. $aMailbox['ID'][$aMsg['ID']] = $iUid;
  900. }
  901. }
  902. }
  903. /**
  904. * In unsorted state we show newest messages first which means
  905. * that the UIDSET which represents the order of the messages
  906. * should contain a high to low ordered UID list
  907. */
  908. $aSortedUidList = array();
  909. foreach ($id_slice as $iId) {
  910. if (isset($aMailbox['ID'][$iId])) {
  911. $aSortedUidList[] = $aMailbox['ID'][$iId];
  912. }
  913. }
  914. $aMailbox['UIDSET'][$iSetIndx] = $aSortedUidList;
  915. $aMailbox['OFFSET'] = 0;
  916. }
  917. }
  918. return true;
  919. }
  920. /**
  921. * This function loops through a group of messages in the mailbox
  922. * and shows them to the user.
  923. *
  924. * @param mixed $imapConnection
  925. * @param array $aMailbox associative array with mailbox related vars
  926. */
  927. function showMessagesForMailbox($imapConnection, &$aMailbox) {
  928. global $color;
  929. // to retrieve the internaldate pref: (I know this is not the right place to do that, move up in front
  930. // and use a properties array as function argument to provide user preferences
  931. global $data_dir, $username;
  932. if (!fetchMessageHeaders($imapConnection, $aMailbox)) {
  933. return false;
  934. }
  935. $iSetIndx = $aMailbox['SETINDEX'];
  936. $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $aMailbox['LIMIT'];
  937. $iEnd = ($aMailbox['PAGEOFFSET'] + ($iLimit - 1) < $aMailbox['EXISTS']) ?
  938. $aMailbox['PAGEOFFSET'] + $iLimit - 1 : $aMailbox['EXISTS'];
  939. $paginator_str = get_paginator_str($aMailbox['NAME'], $aMailbox['PAGEOFFSET'],
  940. $aMailbox['EXISTS'], $aMailbox['LIMIT'], $aMailbox['SHOWALL'][$iSetIndx]);
  941. $msg_cnt_str = get_msgcnt_str($aMailbox['PAGEOFFSET'], $iEnd,$aMailbox['EXISTS']);
  942. do_hook('mailbox_index_before');
  943. ?>
  944. <table border="0" width="100%" cellpadding="0" cellspacing="0">
  945. <tr>
  946. <td>
  947. <?php mail_message_listing_beginning($imapConnection, $aMailbox, $msg_cnt_str, $paginator_str); ?>
  948. </td>
  949. </tr>
  950. <tr><td height="5" bgcolor="<?php echo $color[4]; ?>"></td></tr>
  951. <tr>
  952. <td>
  953. <table width="100%" cellpadding="1" cellspacing="0" align="center" border="0" bgcolor="<?php echo $color[9]; ?>">
  954. <tr>
  955. <td>
  956. <table width="100%" cellpadding="1" cellspacing="0" align="center" border="0" bgcolor="<?php echo $color[5]; ?>">
  957. <tr>
  958. <td>
  959. <?php
  960. printHeader($aMailbox);
  961. displayMessageArray($imapConnection, $aMailbox);
  962. ?>
  963. </td>
  964. </tr>
  965. </table>
  966. </td>
  967. </tr>
  968. </table>
  969. <?php
  970. mail_message_listing_end($aMailbox['EXISTS'], $paginator_str, $msg_cnt_str);
  971. ?>
  972. </td>
  973. </tr>
  974. </table>
  975. <?php
  976. }
  977. /**
  978. * Function to map an uid list with a msg header array by uid
  979. * The mapped headers are printed with printMessage
  980. * aMailbox parameters contains info about the page we are on, the
  981. * used search criteria, the number of messages to show
  982. *
  983. * @param resource $imapConnection socket handle to imap
  984. * @param array $aMailbox array with required elements MSG_HEADERS, UIDSET, OFFSET, LIMIT
  985. * @return void
  986. **/
  987. function displayMessageArray($imapConnection, $aMailbox) {
  988. $iSetIndx = $aMailbox['SETINDEX'];
  989. $aId = $aMailbox['UIDSET'][$iSetIndx];
  990. $aHeaders = $aMailbox['MSG_HEADERS'];
  991. $iOffset = $aMailbox['OFFSET'];
  992. $sort = $aMailbox['SORT'];
  993. $iPageOffset = $aMailbox['PAGEOFFSET'];
  994. $sMailbox = $aMailbox['NAME'];
  995. $sSearch = (isset($aMailbox['SEARCH'][$aMailbox['SETINDEX']])) ? $aMailbox['SEARCH'][$aMailbox['SETINDEX']] : false;
  996. $aSearch = ($sSearch) ? array('search.php',$aMailbox['SETINDEX']) : null;
  997. if ($aMailbox['SORT'] & SQSORT_THREAD) {
  998. $aIndentArray =& $aMailbox['THREAD_INDENT'][$aMailbox['SETINDEX']];
  999. $bThread = true;
  1000. } else {
  1001. $bThread = false;
  1002. }
  1003. /*
  1004. * Loop through and display the info for each message.
  1005. * ($t is used for the checkbox number)
  1006. */
  1007. $iEnd = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $iOffset + $aMailbox['LIMIT'];
  1008. for ($i=$iOffset,$t=0;$i<$iEnd;++$i) {
  1009. if (isset($aId[$i])) {
  1010. $bLast = ((isset($aId[$i+1]) && isset($aHeaders[$aId[$i+1]]))
  1011. || ($i == $iEnd )) ? false : true;
  1012. if ($bThread) {
  1013. $indent = (isset($aIndentArray[$aId[$i]])) ? $aIndentArray[$aId[$i]] : 0;
  1014. } else {
  1015. $indent = 0;
  1016. }
  1017. $aMsg = array(
  1018. 'HEADER' => $aHeaders[$aId[$i]],
  1019. 'INDX' => $t,
  1020. 'OFFSET' => $iOffset,
  1021. 'PAGEOFFSET' => $iPageOffset,
  1022. 'SORT' => $sort,
  1023. 'SEARCH' => $aSearch,
  1024. 'MAILBOX' => $sMailbox,
  1025. 'INDENT' => $indent,
  1026. 'LAST' => $bLast
  1027. );
  1028. printMessageInfo($aMsg);
  1029. ++$t;
  1030. } else {
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. /**
  1036. * Displays the standard message list header.
  1037. *
  1038. * To finish the table, you need to do a "</table></table>";
  1039. *
  1040. * @param resource $imapConnection
  1041. * @param array $aMailbox associative array with mailbox related information
  1042. * @param string $msg_cnt_str
  1043. * @param string $paginator Paginator string
  1044. */
  1045. function mail_message_listing_beginning ($imapConnection,
  1046. $aMailbox,
  1047. $msg_cnt_str = '',
  1048. $paginator = '&nbsp;'
  1049. ) {
  1050. global $color, $show_flag_buttons, $PHP_SELF;
  1051. global $lastTargetMailbox, $boxes;
  1052. $php_self = $PHP_SELF;
  1053. $urlMailbox = urlencode($aMailbox['NAME']);
  1054. if (preg_match('/^(.+)\?.+$/',$php_self,$regs)) {
  1055. $source_url = $regs[1];
  1056. } else {
  1057. $source_url = $php_self;
  1058. }
  1059. if (!isset($msg)) {
  1060. $msg = '';
  1061. }
  1062. $moveFields = addHidden('msg', $msg).
  1063. addHidden('mailbox', $aMailbox['NAME']).
  1064. addHidden('startMessage', $aMailbox['PAGEOFFSET']);
  1065. /* build thread sorting links */
  1066. $sort = $aMailbox['SORT'];
  1067. if ($aMailbox['ALLOW_THREAD']) {
  1068. if ($aMailbox['SORT'] & SQSORT_THREAD) {
  1069. $sort -= SQSORT_THREAD;
  1070. $thread_name = _("Unthread View");
  1071. } else {
  1072. $thread_name = _("Thread View");
  1073. $sort = $aMailbox['SORT'] + SQSORT_THREAD;
  1074. }
  1075. $thread_link_str = '<small>[<a href="' . $source_url . '?srt='
  1076. . $sort . '&start_messages=1'
  1077. . '&mailbox=' . urlencode($aMailbox['NAME']) . '">' . $thread_name
  1078. . '</a>]</small>';
  1079. } else {
  1080. $thread_link_str ='';
  1081. }
  1082. /*
  1083. * This is the beginning of the message list table.
  1084. * It wraps around all messages
  1085. */
  1086. $safe_name = preg_replace("/[^0-9A-Za-z_]/", '_', $aMailbox['NAME']);
  1087. $form_name = "FormMsgs" . $safe_name;
  1088. echo '<form name="' . $form_name . '" method="post" action="'.$php_self.'">' ."\n"
  1089. . $moveFields;
  1090. $button_str = '';
  1091. // display flag buttons only if supported
  1092. if ($show_flag_buttons &&
  1093. in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true) ) {
  1094. $button_str .= getButton('SUBMIT', 'markUnflagged', _("Unflag"));
  1095. $button_str .= getButton('SUBMIT', 'markFlagged', _("Flag"));
  1096. $button_str .= "&nbsp;\n";
  1097. }
  1098. if (in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true)) {
  1099. $button_str .= getButton('SUBMIT', 'markUnread', _("Unread"));
  1100. $button_str .= getButton('SUBMIT', 'markRead', _("Read"));
  1101. $button_str .= "&nbsp;\n";
  1102. }
  1103. $button_str .= getButton('SUBMIT', 'attache',_("Forward")) .
  1104. "&nbsp;\n";
  1105. if (in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) {
  1106. $button_str .= getButton('SUBMIT', 'delete',_("Delete"));
  1107. $button_str .= '<input type="checkbox" name="bypass_trash" />' . _("Bypass Trash");
  1108. $button_str .= "&nbsp;\n";
  1109. }
  1110. if (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY') {
  1111. $button_str .= getButton('SUBMIT', 'expungeButton',_("Expunge")) .'&nbsp;' . _("mailbox") . "\n";
  1112. $button_str .= '&nbsp;';
  1113. }
  1114. ?>
  1115. <table width="100%" cellpadding="1" cellspacing="0" style="border: 1px solid <?php echo $color[0]; ?>">
  1116. <tr>
  1117. <td>
  1118. <table bgcolor="<?php echo $color[4]; ?>" border="0" width="100%" cellpadding="1" cellspacing="0">
  1119. <tr>
  1120. <?php echo html_tag('td', '<small>' . $paginator . $thread_link_str . '</small>', 'left') . "\n"; ?>
  1121. <?php echo html_tag('td', '', 'center') . "\n"; ?>
  1122. <?php echo html_tag('td', '<small>' . $msg_cnt_str . '</small>', 'right') . "\n"; ?>
  1123. </tr>
  1124. </table>
  1125. </td>
  1126. </tr>
  1127. <tr width="100%" cellpadding="1" cellspacing="0" border="0" bgcolor="<?php echo $color[0]; ?>">
  1128. <td>
  1129. <table border="0" width="100%" cellpadding="1" cellspacing="0">
  1130. <tr>
  1131. <?php echo html_tag('td', '', 'left') . "\n"; ?>
  1132. <small>
  1133. <?php echo $button_str; ?>
  1134. <?php do_hook('mailbox_display_buttons'); ?>
  1135. </small>
  1136. </td>
  1137. <?php
  1138. if (in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) {
  1139. ?>
  1140. <?php echo html_tag('td', '', 'right'); ?>
  1141. <small>&nbsp;<tt>
  1142. <select name="targetMailbox">
  1143. <?php echo sqimap_mailbox_option_list($imapConnection, array(strtolower($lastTargetMailbox)), 0, $boxes); ?>
  1144. </select></tt>&nbsp;
  1145. <?php echo getButton('SUBMIT', 'moveButton',_("Move")); ?>
  1146. </small>
  1147. <?php
  1148. }
  1149. ?>
  1150. </td>
  1151. </tr>
  1152. </table>
  1153. </td>
  1154. </tr>
  1155. </table>
  1156. <?php
  1157. do_hook('mailbox_form_before');
  1158. }
  1159. /**
  1160. * Function to add the last row in a message list, it contains the paginator and info about
  1161. * the number of messages.
  1162. *
  1163. * @param integer $num_msgs number of messages in a mailbox
  1164. * @param string $paginator_str Paginator string [Prev | Next] [ 1 2 3 ... 91 92 94 ] [Show all]
  1165. * @param string $msg_cnt_str Message count string Viewing Messages: 21 to 1861 (20 total)
  1166. */
  1167. function mail_message_listing_end($num_msgs, $paginator_str, $msg_cnt_str) {
  1168. global $color;
  1169. if ($num_msgs) {
  1170. /* space between list and footer */
  1171. ?>
  1172. <tr><td height="5" bgcolor="<?php echo $color[4]; ?>" colspan="1"></td></tr>
  1173. <tr>
  1174. <td>
  1175. <table width="100%" cellpadding="1" cellspacing="0" style="border: 1px solid <?php echo $color[0]; ?>">
  1176. <tr>
  1177. <td>
  1178. <table bgcolor="<?php echo $color[4]; ?>" border="0" width="100%" cellpadding="1" cellspacing="0">
  1179. <tr>
  1180. <?php echo html_tag('td', '<small>' . $paginator_str . '</small>', 'left'); ?>
  1181. <?php echo html_tag('td', '<small>' . $msg_cnt_str . '</small>', 'right'); ?>
  1182. </tr>
  1183. </table>
  1184. </td>
  1185. </tr>
  1186. </table>
  1187. </td>
  1188. </tr>
  1189. <?php
  1190. }
  1191. /* End of message-list table */
  1192. do_hook('mailbox_index_after');
  1193. echo "</form>\n";
  1194. }
  1195. /**
  1196. * Prints the table header for the messages list view
  1197. *
  1198. * @param array $aMailbox
  1199. */
  1200. function printHeader($aMailbox) {
  1201. global $index_order, $internal_date_sort, $color;
  1202. if ($aMailbox['SORT_METHOD'] != 'THREAD') {
  1203. $showsort = true;
  1204. } else {
  1205. $showsort = false;
  1206. }
  1207. echo html_tag( 'tr' ,'' , 'center', $color[5] );
  1208. /* calculate the width of the subject column based on the
  1209. * widths of the other columns */
  1210. $widths = array(1=>1,2=>25,3=>5,4=>0,5=>1,6=>5);
  1211. $subjectwidth = 100;
  1212. foreach($index_order as $item) {
  1213. $subjectwidth -= $widths[$item];
  1214. }
  1215. foreach ($index_order as $item) {
  1216. switch ($item) {
  1217. case 1: /* checkbox */
  1218. echo html_tag( 'td',get_selectall_link($aMailbox) , '', '', 'width="1%"' );
  1219. break;
  1220. case 5: /* flags */
  1221. echo html_tag( 'td','' , '', '', 'width="1%"' );
  1222. break;
  1223. case 2: /* from */
  1224. if (handleAsSent($aMailbox['NAME'])) {
  1225. echo html_tag( 'td' ,'' , 'left', '', 'width="25%"' )
  1226. . '<b>' . _("To") . '</b>';
  1227. if ($showsort) {
  1228. ShowSortButton($aMailbox, SQSORT_TO_ASC, SQSORT_TO_DEC);
  1229. }
  1230. } else {
  1231. echo html_tag( 'td' ,'' , 'left', '', 'width="25%"' )
  1232. . '<b>' . _("From") . '</b>';
  1233. if ($showsort) {
  1234. ShowSortButton($aMailbox, SQSORT_FROM_ASC, SQSORT_FROM_DEC);
  1235. }
  1236. }
  1237. echo "</td>\n";
  1238. break;
  1239. case 3: /* date */
  1240. echo html_tag( 'td' ,'' , 'left', '', 'width="5%" nowrap' )
  1241. . '<b>' . _("Date") . '</b>';
  1242. if ($showsort) {
  1243. if ($internal_date_sort) {
  1244. ShowSortButton($aMailbox, SQSORT_INT_DATE_ASC, SQSORT_INT_DATE_DEC);
  1245. } else {
  1246. ShowSortButton($aMailbox, SQSORT_DATE_ASC, SQSORT_DATE_DEC);
  1247. }
  1248. }
  1249. echo "</td>\n";
  1250. break;
  1251. case 4: /* subject */
  1252. echo html_tag( 'td' ,'' , 'left', '', 'width="'.$subjectwidth.'%"' )
  1253. . '<b>' . _("Subject") . '</b>';
  1254. if ($showsort) {
  1255. ShowSortButton($aMailbox, SQSORT_SUBJ_ASC, SQSORT_SUBJ_DEC);
  1256. }
  1257. echo "</td>\n";
  1258. break;
  1259. case 6: /* size */
  1260. echo html_tag( 'td', '', 'center','','width="5%" nowrap')
  1261. . '<b>' . _("Size") . '</b>';
  1262. if ($showsort) {
  1263. ShowSortButton($aMailbox, SQSORT_SIZE_ASC, SQSORT_SIZE_DEC);
  1264. }
  1265. echo "</td>\n";
  1266. break;
  1267. }
  1268. }
  1269. echo "</tr>\n";
  1270. }
  1271. /**
  1272. * This function shows the sort button. Isn't this a good comment?
  1273. *
  1274. * @param array $aMailbox
  1275. * @param integer $Down
  1276. * @param integer $Up
  1277. */
  1278. function ShowSortButton($aMailbox, $Down, $Up ) {
  1279. global $PHP_SELF;
  1280. /* Figure out which image we want to use. */
  1281. if ($aMailbox['SORT'] != $Up && $aMailbox['SORT'] != $Down) {
  1282. $img = 'sort_none.png';
  1283. $which = $Up;
  1284. } elseif ($aMailbox['SORT'] == $Up) {
  1285. $img = 'up_pointer.png';
  1286. $which = $Down;
  1287. } else {
  1288. $img = 'down_pointer.png';
  1289. $which = 0;
  1290. }
  1291. if (preg_match('/^(.+)\?.+$/',$PHP_SELF,$regs)) {
  1292. $source_url = $regs[1];
  1293. } else {
  1294. $source_url = $PHP_SELF;
  1295. }
  1296. /* Now that we have everything figured out, show the actual button. */
  1297. echo ' <a href="' . $source_url .'?srt=' . $which
  1298. . '&amp;startMessage=1&amp;mailbox=' . urlencode($aMailbox['NAME'])
  1299. . '"><img src="../images/' . $img
  1300. . '" border="0" width="12" height="10" alt="sort" title="'
  1301. . _("Click here to change the sorting of the message list") .'" /></a>';
  1302. }
  1303. /**
  1304. * FIXME: Undocumented function
  1305. *
  1306. * @param array $aMailbox
  1307. */
  1308. function get_selectall_link($aMailbox) {
  1309. global $checkall, $javascript_on;
  1310. global $PHP_SELF;
  1311. $result = '';
  1312. if ($javascript_on) {
  1313. $safe_name = preg_replace("/[^0-9A-Za-z_]/", '_', $aMailbox['NAME']);
  1314. $func_name = "CheckAll" . $safe_name;
  1315. $form_name = "FormMsgs" . $safe_name;
  1316. $result = '<script language="JavaScript" type="text/javascript">'
  1317. . "\n<!-- \n"
  1318. . "function " . $func_name . "() {\n"
  1319. . " for (var i = 0; i < document." . $form_name . ".elements.length; i++) {\n"
  1320. . " if(document." . $form_name . ".elements[i].type == 'checkbox' && "
  1321. . " document." . $form_name . ".elements[i].name.substring(0,3) == 'msg'){\n"
  1322. . " document." . $form_name . ".elements[i].checked = "
  1323. . " !(document." . $form_name . ".elements[i].checked);\n"
  1324. . " }\n"
  1325. . " }\n"
  1326. . "}\n"
  1327. . "//-->\n"
  1328. . '</script>'
  1329. . '<input type="checkbox" name="toggleAll" title="'._("Toggle All").'" onclick="'.$func_name.'();" />';
  1330. // . <a href="javascript:void(0)" onClick="' . $func_name . '();">' . _("Toggle All")
  1331. // . "</a>\n";
  1332. } else {
  1333. if (strpos($PHP_SELF, "?")) {
  1334. $result .= "<a href=\"$PHP_SELF&amp;mailbox=" . urlencode($aMailbox['NAME'])
  1335. . "&amp;startMessage=$aMailbox[PAGEOFFSET]&amp;srt=$aMailbox[SORT]&amp;checkall=";
  1336. } else {
  1337. $result .= "<a href=\"$PHP_SELF?mailbox=" . urlencode($mailbox)
  1338. . "&amp;startMessage=$aMailbox[PAGEOFFSET]&amp;srt=$aMailbox[SORT]&amp;checkall=";
  1339. }
  1340. if (isset($checkall) && $checkall == '1') {
  1341. $result .= '0';
  1342. } else {
  1343. $result .= '1';
  1344. }
  1345. if (isset($aMailbox['SEARCH']) && $aMailbox['SEARCH'][0]) {
  1346. $result .= '&amp;where=' . urlencode($aMailbox['SEARCH'][0])
  1347. . '&amp;what=' . urlencode($aMailbox['SEARCH'][1]);
  1348. }
  1349. $result .= "\">";
  1350. $result .= _("All");
  1351. $result .= "</a>\n";
  1352. }
  1353. /* Return our final result. */
  1354. return ($result);
  1355. }
  1356. /**
  1357. * This function computes the "Viewing Messages..." string.
  1358. *
  1359. * @param integer $start_msg first message number
  1360. * @param integer $end_msg last message number
  1361. * @param integer $num_msgs total number of message in folder
  1362. * @return string
  1363. */
  1364. function get_msgcnt_str($start_msg, $end_msg, $num_msgs) {
  1365. /* Compute the $msg_cnt_str. */
  1366. $result = '';
  1367. if ($start_msg < $end_msg) {
  1368. $result = sprintf(_("Viewing Messages: %s to %s (%s total)"),
  1369. '<b>'.$start_msg.'</b>', '<b>'.$end_msg.'</b>', $num_msgs);
  1370. } else if ($start_msg == $end_msg) {
  1371. $result = sprintf(_("Viewing Message: %s (1 total)"), '<b>'.$start_msg.'</b>');
  1372. } else {
  1373. $result = '<br />';
  1374. }
  1375. /* Return our result string. */
  1376. return ($result);
  1377. }
  1378. /**
  1379. * Generate a paginator link.
  1380. *
  1381. * @param mixed $box Mailbox name
  1382. * @param mixed $start_msg Message Offset
  1383. * @param mixed $use
  1384. * @param string $text text used for paginator link
  1385. * @return string
  1386. */
  1387. function get_paginator_link($box, $start_msg, $text) {
  1388. sqgetGlobalVar('PHP_SELF',$php_self,SQ_SERVER);
  1389. $result = "<a href=\"$php_self?startMessage=$start_msg&amp;mailbox=$box\" "
  1390. . ">$text</a>";
  1391. return ($result);
  1392. }
  1393. /**
  1394. * This function computes the paginator string.
  1395. *
  1396. * @param string $box mailbox name
  1397. * @param integer $iOffset offset in total number of messages
  1398. * @param integer $iTotal total number of messages
  1399. * @param integer $iLimit maximum number of messages to show on a page
  1400. * @param bool $bShowAll show all messages at once (non paginate mode)
  1401. * @return string $result paginate string with links to pages
  1402. */
  1403. function get_paginator_str($box, $iOffset, $iTotal, $iLimit, $bShowAll) {
  1404. global $username, $data_dir;
  1405. sqgetGlobalVar('PHP_SELF',$php_self,SQ_SERVER);
  1406. /* Initialize paginator string chunks. */
  1407. $prv_str = '';
  1408. $nxt_str = '';
  1409. $pg_str = '';
  1410. $all_str = '';
  1411. $box = urlencode($box);
  1412. /* Create simple strings that will be creating the paginator. */
  1413. $spc = '&nbsp;'; /* This will be used as a space. */
  1414. $sep = '|'; /* This will be used as a seperator. */
  1415. /* Get some paginator preference values. */
  1416. $pg_sel = getPref($data_dir, $username, 'page_selector', SMPREF_ON);
  1417. $pg_max = getPref($data_dir, $username, 'page_selector_max', PG_SEL_MAX);
  1418. /* Make sure that our start message number is not too big. */
  1419. $iOffset = min($iOffset, $iTotal);
  1420. /* Compute the starting message of the previous and next page group. */
  1421. $next_grp = $iOffset + $iLimit;
  1422. $prev_grp = $iOffset - $iLimit;
  1423. if (!$bShowAll) {
  1424. /* Compute the basic previous and next strings. */
  1425. if (($next_grp <= $iTotal) && ($prev_grp >= 0)) {
  1426. $prv_str = get_paginator_link($box, $prev_grp, _("Previous"));
  1427. $nxt_str = get_paginator_link($box, $next_grp, _("Next"));
  1428. } else if (($next_grp > $iTotal) && ($prev_grp >= 0)) {
  1429. $prv_str = get_paginator_link($box, $prev_grp, _("Previous"));
  1430. $nxt_str = _("Next");
  1431. } else if (($next_grp <= $iTotal) && ($prev_grp < 0)) {
  1432. $prv_str = _("Previous");
  1433. $nxt_str = get_paginator_link($box, $next_grp, _("Next"));
  1434. }
  1435. /* Page selector block. Following code computes page links. */
  1436. if ($iLimit != 0 && $pg_sel && ($iTotal > $iLimit)) {
  1437. /* Most importantly, what is the current page!!! */
  1438. $cur_pg = intval($iOffset / $iLimit) + 1;
  1439. /* Compute total # of pages and # of paginator page links. */
  1440. $tot_pgs = ceil($iTotal / $iLimit); /* Total number of Pages */
  1441. $vis_pgs = min($pg_max, $tot_pgs - 1); /* Visible Pages */
  1442. /* Compute the size of the four quarters of the page links. */
  1443. /* If we can, just show all the pages. */
  1444. if (($tot_pgs - 1) <= $pg_max) {
  1445. $q1_pgs = $cur_pg - 1;
  1446. $q2_pgs = $q3_pgs = 0;
  1447. $q4_pgs = $tot_pgs - $cur_pg;
  1448. /* Otherwise, compute some magic to choose the four quarters. */
  1449. } else {
  1450. /*
  1451. * Compute the magic base values. Added together,
  1452. * these values will always equal to the $pag_pgs.
  1453. * NOTE: These are DEFAULT values and do not take
  1454. * the current page into account. That is below.
  1455. */
  1456. $q1_pgs = floor($vis_pgs/4);
  1457. $q2_pgs = round($vis_pgs/4, 0);
  1458. $q3_pgs = ceil($vis_pgs/4);
  1459. $q4_pgs = round(($vis_pgs - $q2_pgs)/3, 0);
  1460. /* Adjust if the first quarter contains the current page. */
  1461. if (($cur_pg - $q1_pgs) < 1) {
  1462. $extra_pgs = ($q1_pgs - ($cur_pg - 1)) + $q2_pgs;
  1463. $q1_pgs = $cur_pg - 1;
  1464. $q2_pgs = 0;
  1465. $q3_pgs += ceil($extra_pgs / 2);
  1466. $q4_pgs += floor($extra_pgs / 2);
  1467. /* Adjust if the first and second quarters intersect. */
  1468. } else if (($cur_pg - $q2_pgs - ceil($q2_pgs/3)) <= $q1_pgs) {
  1469. $extra_pgs = $q2_pgs;
  1470. $extra_pgs -= ceil(($cur_pg - $q1_pgs - 1) * 3/4);
  1471. $q2_pgs = ceil(($cur_pg - $q1_pgs - 1) * 3/4);
  1472. $q3_pgs += ceil($extra_pgs / 2);
  1473. $q4_pgs += floor($extra_pgs / 2);
  1474. /* Adjust if the fourth quarter contains the current page. */
  1475. } else if (($cur_pg + $q4_pgs) >= $tot_pgs) {
  1476. $extra_pgs = ($q4_pgs - ($tot_pgs - $cur_pg)) + $q3_pgs;
  1477. $q3_pgs = 0;
  1478. $q4_pgs = $tot_pgs - $cur_pg;
  1479. $q1_pgs += floor($extra_pgs / 2);
  1480. $q2_pgs += ceil($extra_pgs / 2);
  1481. /* Adjust if the third and fourth quarter intersect. */
  1482. } else if (($cur_pg + $q3_pgs + 1) >= ($tot_pgs - $q4_pgs + 1)) {
  1483. $extra_pgs = $q3_pgs;
  1484. $extra_pgs -= ceil(($tot_pgs - $cur_pg - $q4_pgs) * 3/4);
  1485. $q3_pgs = ceil(($tot_pgs - $cur_pg - $q4_pgs) * 3/4);
  1486. $q1_pgs += floor($extra_pgs / 2);
  1487. $q2_pgs += ceil($extra_pgs / 2);
  1488. }
  1489. }
  1490. /*
  1491. * I am leaving this debug code here, commented out, because
  1492. * it is a really nice way to see what the above code is doing.
  1493. * echo "qts = $q1_pgs/$q2_pgs/$q3_pgs/$q4_pgs = "
  1494. * . ($q1_pgs + $q2_pgs + $q3_pgs + $q4_pgs) . '<br />';
  1495. */
  1496. /* Print out the page links from the compute page quarters. */
  1497. /* Start with the first quarter. */
  1498. if (($q1_pgs == 0) && ($cur_pg > 1)) {
  1499. $pg_str .= "...$spc";
  1500. } else {
  1501. for ($pg = 1; $pg <= $q1_pgs; ++$pg) {
  1502. $start = (($pg-1) * $iLimit) + 1;
  1503. $pg_str .= get_paginator_link($box, $start, $pg) . $spc;
  1504. }
  1505. if ($cur_pg - $q2_pgs - $q1_pgs > 1) {
  1506. $pg_str .= "...$spc";
  1507. }
  1508. }
  1509. /* Continue with the second quarter. */
  1510. for ($pg = $cur_pg - $q2_pgs; $pg < $cur_pg; ++$pg) {
  1511. $start = (($pg-1) * $iLimit) + 1;
  1512. $pg_str .= get_paginator_link($box, $start, $pg) . $spc;
  1513. }
  1514. /* Now print the current page. */
  1515. $pg_str .= $cur_pg . $spc;
  1516. /* Next comes the third quarter. */
  1517. for ($pg = $cur_pg + 1; $pg <= $cur_pg + $q3_pgs; ++$pg) {
  1518. $start = (($pg-1) * $iLimit) + 1;
  1519. $pg_str .= get_paginator_link($box, $start, $pg) . $spc;
  1520. }
  1521. /* And last, print the forth quarter page links. */
  1522. if (($q4_pgs == 0) && ($cur_pg < $tot_pgs)) {
  1523. $pg_str .= "...$spc";
  1524. } else {
  1525. if (($tot_pgs - $q4_pgs) > ($cur_pg + $q3_pgs)) {
  1526. $pg_str .= "...$spc";
  1527. }
  1528. for ($pg = $tot_pgs - $q4_pgs + 1; $pg <= $tot_pgs; ++$pg) {
  1529. $start = (($pg-1) * $iLimit) + 1;
  1530. $pg_str .= get_paginator_link($box, $start,$pg) . $spc;
  1531. }
  1532. }
  1533. }
  1534. } else {
  1535. $pg_str = "<a href=\"$php_self?showall=0"
  1536. . "&amp;startMessage=1&amp;mailbox=$box\" "
  1537. . ">" ._("Paginate") . '</a>';
  1538. }
  1539. /* Put all the pieces of the paginator string together. */
  1540. /**
  1541. * Hairy code... But let's leave it like it is since I am not certain
  1542. * a different approach would be any easier to read. ;)
  1543. */
  1544. $result = '';
  1545. if ( $prv_str || $nxt_str ) {
  1546. /* Compute the 'show all' string. */
  1547. $all_str = "<a href=\"$php_self?showall=1"
  1548. . "&amp;startMessage=1&amp;mailbox=$box\" "
  1549. . ">" . _("Show All") . '</a>';
  1550. $result .= '[';
  1551. $result .= ($prv_str != '' ? $prv_str . $spc . $sep . $spc : '');
  1552. $result .= ($nxt_str != '' ? $nxt_str : '');
  1553. $result .= ']' . $spc ;
  1554. }
  1555. $result .= ($pg_str != '' ? $spc . '['.$spc.$pg_str.']' . $spc : '');
  1556. $result .= ($all_str != '' ? $spc . '['.$all_str.']' . $spc . $spc : '');
  1557. /* If the resulting string is blank, return a non-breaking space. */
  1558. if ($result == '') {
  1559. $result = '&nbsp;';
  1560. }
  1561. /* Return our final magical paginator string. */
  1562. return ($result);
  1563. }
  1564. /**
  1565. * FIXME: Undocumented function
  1566. */
  1567. function truncateWithEntities($subject, $trim_at)
  1568. {
  1569. $ent_strlen = strlen($subject);
  1570. if (($trim_at <= 0) || ($ent_strlen <= $trim_at))
  1571. return $subject;
  1572. global $languages, $squirrelmail_language;
  1573. /*
  1574. * see if this is entities-encoded string
  1575. * If so, Iterate through the whole string, find out
  1576. * the real number of characters, and if more
  1577. * than $trim_at, substr with an updated trim value.
  1578. */
  1579. $trim_val = $trim_at;
  1580. $ent_offset = 0;
  1581. $ent_loc = 0;
  1582. while ( $ent_loc < $trim_val && (($ent_loc = strpos($subject, '&', $ent_offset)) !== false) &&
  1583. (($ent_loc_end = strpos($subject, ';', $ent_loc+3)) !== false) ) {
  1584. $trim_val += ($ent_loc_end-$ent_loc);
  1585. $ent_offset = $ent_loc_end+1;
  1586. }
  1587. if (($trim_val > $trim_at) && ($ent_strlen > $trim_val) && (strpos($subject,';',$trim_val) < ($trim_val + 6))) {
  1588. $i = strpos($subject,';',$trim_val);
  1589. if ($i) {
  1590. $trim_val = strpos($subject,';',$trim_val);
  1591. }
  1592. }
  1593. // only print '...' when we're actually dropping part of the subject
  1594. if ($ent_strlen <= $trim_val)
  1595. return $subject;
  1596. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  1597. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  1598. return $languages[$squirrelmail_language]['XTRA_CODE']('strimwidth', $subject, $trim_val);
  1599. }
  1600. return substr_replace($subject, '...', $trim_val);
  1601. }
  1602. /**
  1603. * FIXME: Undocumented function
  1604. */
  1605. function processSubject($subject, $threadlevel = 0) {
  1606. /* Shouldn't ever happen -- caught too many times in the IMAP functions */
  1607. if ($subject == '') {
  1608. return _("(no subject)");
  1609. }
  1610. global $truncate_subject; /* number of characters for Subject field (<= 0 for unchanged) */
  1611. $trim_at = $truncate_subject;
  1612. /* if this is threaded, subtract two chars per indentlevel */
  1613. if (($threadlevel > 0) && ($threadlevel <= 10))
  1614. $trim_at -= (2*$threadlevel);
  1615. return truncateWithEntities($subject, $trim_at);
  1616. }
  1617. /**
  1618. * Creates button
  1619. *
  1620. * @deprecated see form functions available in 1.5.1 and 1.4.3.
  1621. * @param string $type
  1622. * @param string $name
  1623. * @param string $value
  1624. * @param string $js
  1625. * @param bool $enabled
  1626. */
  1627. function getButton($type, $name, $value, $js = '', $enabled = TRUE) {
  1628. $disabled = ( $enabled ? '' : 'disabled ' );
  1629. $js = ( $js ? $js.' ' : '' );
  1630. return '<input '.$disabled.$js.
  1631. 'type="'.$type.
  1632. '" name="'.$name.
  1633. '" value="'.$value .
  1634. '" style="padding: 0px; margin: 0px" />';
  1635. }
  1636. /**
  1637. * Puts string into cell, aligns it and adds <small> tag
  1638. *
  1639. * @param string $string string
  1640. * @param string $align alignment
  1641. */
  1642. function getSmallStringCell($string, $align) {
  1643. return html_tag('td',
  1644. '<small>' . $string . ':&nbsp; </small>',
  1645. $align,
  1646. '',
  1647. 'nowrap' );
  1648. }
  1649. /**
  1650. * This should go in imap_mailbox.php
  1651. * @param string $mailbox
  1652. */
  1653. function handleAsSent($mailbox) {
  1654. global $handleAsSent_result;
  1655. /* First check if this is the sent or draft folder. */
  1656. $handleAsSent_result = isSentMailbox($mailbox) || isDraftMailbox($mailbox);
  1657. /* Then check the result of the handleAsSent hook. */
  1658. do_hook('check_handleAsSent_result', $mailbox);
  1659. /* And return the result. */
  1660. return $handleAsSent_result;
  1661. }
  1662. /**
  1663. * Process messages list form and handle the cache gracefully. If $sButton and
  1664. * $aUid are provided as argument then you can fake a message list submit and
  1665. * use it i.e. in read_body.php for del move next and update the cache
  1666. *
  1667. * @param resource $imapConnection imap connection
  1668. * @param array $aMailbox (reference) cached mailbox
  1669. * @param string $sButton fake a submit button
  1670. * @param array $aUid fake the $msg array
  1671. * @return string $sError error string in case of an error
  1672. * @author Marc Groot Koerkamp
  1673. */
  1674. function handleMessageListForm($imapConnection,&$aMailbox,$sButton='',$aUid = array()) {
  1675. /* incoming formdata */
  1676. $sButton = (sqgetGlobalVar('moveButton', $sTmp, SQ_POST)) ? 'move' : $sButton;
  1677. $sButton = (sqgetGlobalVar('expungeButton', $sTmp, SQ_POST)) ? 'expunge' : $sButton;
  1678. $sButton = (sqgetGlobalVar('attache', $sTmp, SQ_POST)) ? 'attache' : $sButton;
  1679. $sButton = (sqgetGlobalVar('delete', $sTmp, SQ_POST)) ? 'setDeleted' : $sButton;
  1680. $sButton = (sqgetGlobalVar('undeleteButton', $sTmp, SQ_POST)) ? 'setDeleted' : $sButton;
  1681. $sButton = (sqgetGlobalVar('markRead', $sTmp, SQ_POST)) ? 'setSeen' : $sButton;
  1682. $sButton = (sqgetGlobalVar('markUnread', $sTmp, SQ_POST)) ? 'unsetSeen' : $sButton;
  1683. $sButton = (sqgetGlobalVar('markFlagged', $sTmp, SQ_POST)) ? 'setFlagged' : $sButton;
  1684. $sButton = (sqgetGlobalVar('markUnflagged', $sTmp, SQ_POST)) ? 'unsetFlagged' : $sButton;
  1685. sqgetGlobalVar('targetMailbox', $targetMailbox, SQ_POST);
  1686. sqgetGlobalVar('bypass_trash', $bypass_trash, SQ_POST);
  1687. sqgetGlobalVar('msg', $msg, SQ_POST);
  1688. $sError = '';
  1689. $mailbox = $aMailbox['NAME'];
  1690. /* retrieve the check boxes */
  1691. $aUid = (isset($msg) && is_array($msg)) ? array_values($msg) : $aUid;
  1692. if (count($aUid) && $sButton != 'expunge') {
  1693. $aUpdatedMsgs = false;
  1694. $bExpunge = false;
  1695. switch ($sButton) {
  1696. case 'setDeleted':
  1697. // check if id exists in case we come from read_body
  1698. if (count($aUid) == 1 && is_array($aMailbox['UIDSET'][$aMailbox['SETINDEX']]) &&
  1699. !in_array($aUid[0],$aMailbox['UIDSET'][$aMailbox['SETINDEX']])) {
  1700. break;
  1701. }
  1702. // What kind of hook is this, can it be removed? Disabled for now because it can invalidate the cache
  1703. //if (!boolean_hook_function('move_messages_button_action', NULL, 1)) {
  1704. $aUpdatedMsgs = sqimap_msgs_list_delete($imapConnection, $mailbox, $aUid,$bypass_trash);
  1705. $bExpunge = true;
  1706. //}
  1707. break;
  1708. case 'unsetDeleted':
  1709. case 'setSeen':
  1710. case 'unsetSeen':
  1711. case 'setFlagged':
  1712. case 'unsetFlagged':
  1713. // get flag
  1714. $sFlag = (substr($sButton,0,3) == 'set') ? '\\'.substr($sButton,3) : '\\'.substr($sButton,5);
  1715. $bSet = (substr($sButton,0,3) == 'set') ? true : false;
  1716. $aUpdatedMsgs = sqimap_toggle_flag($imapConnection, $aUid, $sFlag, $bSet, true);
  1717. break;
  1718. case 'move':
  1719. $aUpdatedMsgs = sqimap_msgs_list_move($imapConnection,$aUid,$targetMailbox);
  1720. sqsession_register($targetMailbox,'lastTargetMailbox');
  1721. $bExpunge = true;
  1722. break;
  1723. case 'attache':
  1724. $aMsgHeaders = array();
  1725. foreach ($aUid as $iUid) {
  1726. $aMsgHeaders[$iUid] = $aMailbox['MSG_HEADERS'][$iUid];
  1727. }
  1728. if (count($aMsgHeaders)) {
  1729. $composesession = attachSelectedMessages($imapConnection,$aMsgHeaders);
  1730. // dirty hack, add info to $aMailbox
  1731. $aMailbox['FORWARD_SESSION'] = $composesession;
  1732. }
  1733. break;
  1734. }
  1735. /**
  1736. * Updates messages is an array containing the result of the untagged
  1737. * fetch responses send by the imap server due to a flag change. That
  1738. * response is parsed in a array with msg arrays by the parseFetch function
  1739. */
  1740. if ($aUpdatedMsgs) {
  1741. // Update the message headers cache
  1742. $aDeleted = array();
  1743. foreach ($aUpdatedMsgs as $iUid => $aMsg) {
  1744. if (isset($aMsg['FLAGS'])) {
  1745. /**
  1746. * Only update the cached headers if the header is
  1747. * cached.
  1748. */
  1749. if (isset($aMailbox['MSG_HEADERS'][$iUid])) {
  1750. $aMailbox['MSG_HEADERS'][$iUid]['FLAGS'] = $aMsg['FLAGS'];
  1751. }
  1752. /**
  1753. * Count the messages with the \Delete flag set so we can determine
  1754. * if the number of expunged messages equals the number of flagged
  1755. * messages for deletion.
  1756. */
  1757. if (isset($aMsg['FLAGS']['\\deleted']) && $aMsg['FLAGS']['\\deleted']) {
  1758. $aDeleted[] = $iUid;
  1759. }
  1760. }
  1761. }
  1762. if ($bExpunge && $aMailbox['AUTO_EXPUNGE'] &&
  1763. $iExpungedMessages = sqimap_mailbox_expunge($imapConnection, $aMailbox['NAME'], true))
  1764. {
  1765. if (count($aDeleted) != $iExpungedMessages) {
  1766. // there are more messages deleted permanently then we expected
  1767. // invalidate the cache
  1768. $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = false;
  1769. $aMailbox['MSG_HEADERS'] = false;
  1770. } else {
  1771. // remove expunged messages from cache
  1772. $aUidSet = $aMailbox['UIDSET'][$aMailbox['SETINDEX']];
  1773. if (is_array($aUidSet)) {
  1774. // create a UID => array index temp array
  1775. $aUidSetDummy = array_flip($aUidSet);
  1776. foreach ($aDeleted as $iUid) {
  1777. // get the id as well in case of SQM_SORT_NONE
  1778. if ($aMailbox['SORT'] == SQSORT_NONE) {
  1779. $aMailbox['ID'] = false;
  1780. //$iId = $aMailbox['MSG_HEADERS'][$iUid]['ID'];
  1781. //unset($aMailbox['ID'][$iId]);
  1782. }
  1783. // unset the UID and message header
  1784. unset($aUidSetDummy[$iUid]);
  1785. unset($aMailbox['MSG_HEADERS'][$iUid]);
  1786. }
  1787. $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = array_keys($aUidSetDummy);
  1788. }
  1789. }
  1790. // update EXISTS info
  1791. if ($iExpungedMessages) {
  1792. $aMailbox['EXISTS'] -= (int) $iExpungedMessages;
  1793. }
  1794. // Change the startMessage number if the mailbox was changed
  1795. if (($aMailbox['PAGEOFFSET']+$iExpungedMessages-1) >= $aMailbox['EXISTS']) {
  1796. $aMailbox['PAGEOFFSET'] = ($aMailbox['PAGEOFFSET'] > $aMailbox['LIMIT']) ?
  1797. $aMailbox['PAGEOFFSET'] - $aMailbox['LIMIT'] : 1;
  1798. }
  1799. }
  1800. }
  1801. } else {
  1802. if ($sButton == 'expunge') {
  1803. /**
  1804. * on expunge we do not know which messages will be deleted
  1805. * so it's useless to try to sync the cache
  1806. * Close the mailbox so we do not need to parse the untagged expunge
  1807. * responses which do not contain uid info.
  1808. * NB: Closing a mailbox is faster then expunge because the imap
  1809. * server does not need to generate the untagged expunge responses
  1810. */
  1811. sqimap_run_command($imapConnection,'CLOSE',false,$result,$message);
  1812. $aMbxResponse = sqimap_mailbox_select($imapConnection,$aMailbox['NAME']);
  1813. // update the $aMailbox array
  1814. $aMailbox['EXISTS'] = $aMbxResponse['EXISTS'];
  1815. $aMailbox['UIDSET'] = false;
  1816. } else {
  1817. if ($sButton) {
  1818. $sError = _("No messages were selected.");
  1819. }
  1820. }
  1821. }
  1822. return $sError;
  1823. }
  1824. function attachSelectedMessages($imapConnection,$aMsgHeaders) {
  1825. global $username, $attachment_dir,
  1826. $data_dir, $composesession,
  1827. $compose_messages;
  1828. if (!isset($compose_messages)) {
  1829. $compose_messages = array();
  1830. sqsession_register($compose_messages,'compose_messages');
  1831. }
  1832. if (!$composesession) {
  1833. $composesession = 1;
  1834. sqsession_register($composesession,'composesession');
  1835. } else {
  1836. $composesession++;
  1837. sqsession_register($composesession,'composesession');
  1838. }
  1839. $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
  1840. $composeMessage = new Message();
  1841. $rfc822_header = new Rfc822Header();
  1842. $composeMessage->rfc822_header = $rfc822_header;
  1843. $composeMessage->reply_rfc822_header = '';
  1844. foreach($aMsgHeaders as $iUid => $aMsgHeader) {
  1845. /**
  1846. * Retrieve the full message
  1847. */
  1848. $body_a = sqimap_run_command($imapConnection, "FETCH $iUid RFC822", true, $response, $readmessage, TRUE);
  1849. if ($response == 'OK') {
  1850. $subject = (isset($aMsgHeader['SUBJECT'])) ? $aMsgHeader['SUBJECT'] : $iUid;
  1851. array_shift($body_a);
  1852. array_pop($body_a);
  1853. $body = implode('', $body_a);
  1854. $body .= "\r\n";
  1855. $localfilename = GenerateRandomString(32, 'FILE', 7);
  1856. $full_localfilename = "$hashed_attachment_dir/$localfilename";
  1857. $fp = fopen( $full_localfilename, 'wb');
  1858. fwrite ($fp, $body);
  1859. fclose($fp);
  1860. $composeMessage->initAttachment('message/rfc822',$subject.'.msg',
  1861. $full_localfilename);
  1862. }
  1863. }
  1864. $compose_messages[$composesession] = $composeMessage;
  1865. sqsession_register($compose_messages,'compose_messages');
  1866. return $composesession;
  1867. }
  1868. ?>