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