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