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