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