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