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