Fix for situation when mailbox cache was invalidated while iterating through
[squirrelmail.git] / functions / mailbox_display.php
1 <?php
2
3 /**
4 * mailbox_display.php
5 *
6 * This contains functions that display mailbox information, such as the
7 * table row that has sender, date, subject, etc...
8 *
9 * @copyright &copy; 1999-2005 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @version $Id$
12 * @package squirrelmail
13 */
14
15 /** The standard includes.. */
16 require_once(SM_PATH . 'functions/strings.php');
17 require_once(SM_PATH . 'functions/html.php');
18 require_once(SM_PATH . 'functions/imap_mailbox.php');
19 require_once(SM_PATH . 'functions/imap_messages.php');
20 require_once(SM_PATH . 'functions/imap_asearch.php');
21 require_once(SM_PATH . 'functions/mime.php');
22 require_once(SM_PATH . 'functions/forms.php');
23
24
25 /**
26 * Selects a mailbox for header retrieval.
27 * Cache control for message headers is embedded.
28 *
29 * @param resource $imapConnection imap socket handle
30 * @param string $mailbox mailbox to select and retrieve message headers from
31 * @param array $aConfig array with system config settings and incoming vars
32 * @param array $aProps mailbox specific properties
33 * @return array $aMailbox mailbox array with all relevant information
34 * @author Marc Groot Koerkamp
35 */
36 function sqm_api_mailbox_select($imapConnection,$account,$mailbox,$aConfig,$aProps) {
37
38 /**
39 * NB: retrieve this from the session before accessing this function
40 * and make sure you write it back at the end of the script after
41 * the aMailbox var is added so that the headers are added to the cache
42 */
43 global $mailbox_cache;
44
45 $aDefaultConfigProps = array(
46 // 'charset' => 'US-ASCII',
47 'user' => false, /* no pref storage if false */
48 'setindex' => 0,
49 // 'search' => 'ALL',
50 'max_cache_size' => SQM_MAX_MBX_IN_CACHE
51 );
52
53 $aConfig = array_merge($aDefaultConfigProps,$aConfig);
54
55 $iSetIndx = $aConfig['setindex'];
56
57 $aMbxResponse = sqimap_mailbox_select($imapConnection, $mailbox);
58
59 if ($mailbox_cache) {
60 if (isset($mailbox_cache[$account.'_'.$mailbox])) {
61 $aCachedMailbox = $mailbox_cache[$account.'_'.$mailbox];
62 } else {
63 $aCachedMailbox = false;
64 }
65 /* cleanup cache */
66 if (count($mailbox_cache) > $aConfig['max_cache_size'] -1) {
67 $aTime = array();
68 foreach($mailbox_cache as $cachedmailbox => $aVal) {
69 $aTime[$aVal['TIMESTAMP']] = $cachedmailbox;
70 }
71 if (ksort($aTime,SORT_NUMERIC)) {
72 for ($i=0,$iCnt=count($mailbox_cache);$i<($iCnt-$aConfig['max_cache_size']);++$i) {
73 $sOldestMbx = array_shift($aTime);
74 /**
75 * Remove only the UIDSET and MSG_HEADERS from cache because those can
76 * contain large amounts of data.
77 */
78 if (isset($mailbox_cache[$sOldestMbx]['UIDSET'])) {
79 $mailbox_cache[$sOldestMbx]['UIDSET']= false;
80 }
81 if (isset($mailbox_cache[$sOldestMbx]['MSG_HEADERS'])) {
82 $mailbox_cache[$sOldestMbx]['MSG_HEADERS'] = false;
83 }
84 }
85 }
86 }
87
88 } else {
89 $aCachedMailbox = false;
90 }
91
92 /**
93 * Deal with imap servers that do not return the required UIDNEXT or
94 * UIDVALIDITY response
95 * from a SELECT call (since rfc 3501 it's required).
96 */
97 if (!isset($aMbxResponse['UIDNEXT']) || !isset($aMbxResponse['UIDVALIDITY'])) {
98 $aStatus = sqimap_status_messages($imapConnection,$mailbox,
99 array('UIDNEXT','UIDVALIDITY'));
100 $aMbxResponse['UIDNEXT'] = $aStatus['UIDNEXT'];
101 $aMbxResponse['UIDVALIDTY'] = $aStatus['UIDVALIDITY'];
102 }
103
104 $aMailbox['ACCOUNT'] = $account;
105 $aMailbox['UIDSET'][$iSetIndx] = false;
106 $aMailbox['ID'] = false;
107 $aMailbox['SETINDEX'] = $iSetIndx;
108 $aMailbox['MSG_HEADERS'] = false;
109
110 if ($aCachedMailbox) {
111 /**
112 * Validate integrity of cached data
113 */
114 if ($aCachedMailbox['EXISTS'] == $aMbxResponse['EXISTS'] &&
115 $aMbxResponse['EXISTS'] &&
116 $aCachedMailbox['UIDVALIDITY'] == $aMbxResponse['UIDVALIDITY'] &&
117 $aCachedMailbox['UIDNEXT'] == $aMbxResponse['UIDNEXT'] &&
118 isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
119 (!isset($aConfig['search']) || /* always set search from the searchpage */
120 $aCachedMailbox['SEARCH'][$iSetIndx] == $aConfig['search'])) {
121 if (isset($aCachedMailbox['MSG_HEADERS'])) {
122 $aMailbox['MSG_HEADERS'] = $aCachedMailbox['MSG_HEADERS'];
123 }
124 $aMailbox['ID'] = $aCachedMailbox['ID'];
125 if (isset($aCachedMailbox['UIDSET'][$iSetIndx]) && $aCachedMailbox['UIDSET'][$iSetIndx]) {
126 if (isset($aProps[MBX_PREF_SORT]) && $aProps[MBX_PREF_SORT] != $aCachedMailbox['SORT'] ) {
127 $newsort = $aProps[MBX_PREF_SORT];
128 $oldsort = $aCachedMailbox['SORT'];
129 /**
130 * If it concerns a reverse sort we do not need to invalidate
131 * the cached sorted UIDSET, a reverse is sufficient.
132 */
133 if ((($newsort % 2) && ($newsort + 1 == $oldsort)) ||
134 (!($newsort % 2) && ($newsort - 1 == $oldsort))) {
135 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($aCachedMailbox['UIDSET'][$iSetIndx]);
136 } else {
137 $server_sort_array = false;
138 $aMailbox['MSG_HEADERS'] = false;
139 $aMailbox['ID'] = false;
140 }
141 // store the new sort value in the mailbox pref
142 if ($aConfig['user']) {
143 // FIXME, in ideal situation, we write back the
144 // prefs at the end of the script
145 setUserPref($aConfig['user'],'pref_'.$account.'_'.$mailbox,serialize($aProps));
146 }
147 } else {
148 $aMailbox['UIDSET'][$iSetIndx] = $aCachedMailbox['UIDSET'][$iSetIndx];
149 }
150 }
151 }
152 }
153 /**
154 * Restore the offset in the paginator if no new offset is provided.
155 */
156 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['offset']) && $aCachedMailbox['OFFSET']) {
157 $aMailbox['OFFSET'] = $aCachedMailbox['OFFSET'];
158 $aMailbox['PAGEOFFSET'] = $aCachedMailbox['PAGEOFFSET'];
159 } else {
160 $aMailbox['OFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ? $aConfig['offset'] -1 : 0;
161 $aMailbox['PAGEOFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ? $aConfig['offset'] : 1;
162 }
163 /**
164 * Restore the number of messages in the result set
165 */
166 if (isset($aCachedMailbox['TOTAL'][$iSetIndx]) && $aCachedMailbox['TOTAL'][$iSetIndx]) {
167 $aMailbox['TOTAL'][$iSetIndx] = $aCachedMailbox['TOTAL'][$iSetIndx];
168 }
169
170 /**
171 * Restore the showall value no new showall value is provided.
172 */
173 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['showall']) &&
174 isset($aCachedMailbox['SHOWALL'][$iSetIndx]) && $aCachedMailbox['SHOWALL'][$iSetIndx]) {
175 $aMailbox['SHOWALL'][$iSetIndx] = $aCachedMailbox['SHOWALL'][$iSetIndx];
176 } else {
177 $aMailbox['SHOWALL'][$iSetIndx] = (isset($aConfig['showall']) && $aConfig['showall']) ? 1 : 0;
178 }
179
180 /**
181 * Restore the sort order if no new sort order is provided.
182 */
183 if (!isset($aProps[MBX_PREF_SORT]) && isset($aCachedMailbox['SORT'])) {
184 $aMailbox['SORT'] = $aCachedMailbox['SORT'];
185 } else {
186 $aMailbox['SORT'] = (isset($aProps[MBX_PREF_SORT])) ? $aProps[MBX_PREF_SORT] : 0;
187 }
188
189 /**
190 * Restore the number of message to show per page when no new limit is provided
191 */
192 if (!isset($aProps[MBX_PREF_LIMIT]) && isset($aCachedMailbox['LIMIT'])) {
193 $aMailbox['LIMIT'] = $aCachedMailbox['LIMIT'];
194 } else {
195 $aMailbox['LIMIT'] = (isset($aProps[MBX_PREF_LIMIT])) ? $aProps[MBX_PREF_LIMIT] : 15;
196 }
197
198 /**
199 * Restore the ordered columns to show when no new ordered columns are provided
200 */
201 if (!isset($aProps[MBX_PREF_COLUMNS]) && isset($aCachedMailbox['COLUMNS'])) {
202 $aMailbox['COLUMNS'] = $aCachedMailbox['COLUMNS'];
203 } else {
204 $aMailbox['COLUMNS'] = (isset($aProps[MBX_PREF_COLUMNS])) ? $aProps[MBX_PREF_COLUMNS] :
205 array(SQM_COL_FLAGS,SQM_COL_FROM, SQM_COL_SUBJ, SQM_COL_FLAGS);
206 }
207
208 /**
209 * Restore the headers we fetch the last time. Saves intitialisation stuff in read_body.
210 */
211 $aMailbox['FETCHHEADERS'] = (isset($aCachedMailbox['FETCHHEADERS'])) ? $aCachedMailbox['FETCHHEADERS'] : null;
212
213 if (!isset($aProps[MBX_PREF_AUTO_EXPUNGE]) && isset($aCachedMailbox['AUTO_EXPUNGE'])) {
214 $aMailbox['AUTO_EXPUNGE'] = $aCachedMailbox['AUTO_EXPUNGE'];
215 } else {
216 $aMailbox['AUTO_EXPUNGE'] = (isset($aProps[MBX_PREF_AUTO_EXPUNGE])) ? $aProps[MBX_PREF_AUTO_EXPUNGE] : false;
217 }
218 if (!isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx])) {
219 $aMailbox['SEARCH'][$iSetIndx] = $aCachedMailbox['SEARCH'][$iSetIndx];
220 } else if (isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
221 $aConfig['search'] != $aCachedMailbox['SEARCH'][$iSetIndx]) {
222 // reset the pageindex
223 $aMailbox['SEARCH'][$iSetIndx] = $aConfig['search'];
224 $aMailbox['OFFSET'] = 0;
225 $aMailbox['PAGEOFFSET'] = 1;
226 } else {
227 $aMailbox['SEARCH'][$iSetIndx] = (isset($aConfig['search'])) ? $aConfig['search'] : 'ALL';
228 }
229 if (!isset($aConfig['charset']) && isset($aCachedMailbox['CHARSET'][$iSetIndx])) {
230 $aMailbox['CHARSET'][$iSetIndx] = $aCachedMailbox['CHARSET'][$iSetIndx];
231 } else {
232 $aMailbox['CHARSET'][$iSetIndx] = (isset($aConfig['charset'])) ? $aConfig['charset'] : 'US-ASCII';
233 }
234
235 $aMailbox['NAME'] = $mailbox;
236 $aMailbox['EXISTS'] = $aMbxResponse['EXISTS'];
237 $aMailbox['SEEN'] = (isset($aMbxResponse['SEEN'])) ? $aMbxResponse['SEEN'] : $aMbxResponse['EXISTS'];
238 $aMailbox['RECENT'] = (isset($aMbxResponse['RECENT'])) ? $aMbxResponse['RECENT'] : 0;
239 $aMailbox['UIDVALIDITY'] = $aMbxResponse['UIDVALIDITY'];
240 $aMailbox['UIDNEXT'] = $aMbxResponse['UIDNEXT'];
241 $aMailbox['PERMANENTFLAGS'] = $aMbxResponse['PERMANENTFLAGS'];
242 $aMailbox['RIGHTS'] = $aMbxResponse['RIGHTS'];
243
244 /* decide if we are thread sorting or not */
245 if ($aMailbox['SORT'] & SQSORT_THREAD) {
246 if (!sqimap_capability($imapConnection,'THREAD')) {
247 $aMailbox['SORT'] ^= SQSORT_THREAD;
248 } else {
249 $aMailbox['THREAD_INDENT'] = $aCachedMailbox['THREAD_INDENT'];
250 }
251 } else {
252 $aMailbox['THREAD_INDENT'] = false;
253 }
254
255 /* set a timestamp for cachecontrol */
256 $aMailbox['TIMESTAMP'] = time();
257 return $aMailbox;
258 }
259
260 /**
261 * Fetch the message headers for a mailbox. Settings are part of the aMailbox
262 * array.
263 *
264 * @param resource $imapConnection imap socket handle
265 * @param array $aMailbox (reference) mailbox retrieved from sqm_api_mailbox_select
266 * @return error $error error number
267 * @author Marc Groot Koerkamp
268 */
269 function fetchMessageHeaders($imapConnection, &$aMailbox) {
270
271 /* FIX ME, this function is kind of big, maybe we can split it up in
272 a couple of functions. Make sure the functions are private and starts with _
273 Also make sure that the error codes are propagated */
274
275 /**
276 * Retrieve the UIDSET.
277 * Setindex is used to be able to store multiple uid sets. That will make it
278 * possible to display the mailbox multiple times in different sort order
279 * or to store serach results separate from normal mailbox view.
280 */
281 $iSetIndx = (isset($aMailbox['SETINDEX'])) ? $aMailbox['SETINDEX'] : 0;
282
283 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $aMailbox['LIMIT'];
284 /**
285 * Adjust the start_msg
286 */
287 $start_msg = $aMailbox['PAGEOFFSET'];
288 if($aMailbox['PAGEOFFSET'] > $aMailbox['EXISTS']) {
289 $start_msg -= $aMailbox['LIMIT'];
290 if($start_msg < 1) {
291 $start_msg = 1;
292 }
293 }
294
295 if (is_array($aMailbox['UIDSET'])) {
296 $aUid =& $aMailbox['UIDSET'][$iSetIndx];
297 } else {
298 $aUid = false;
299 }
300 $aFetchHeaders = $aMailbox['FETCHHEADERS'];
301
302 $iError = 0;
303 $aFetchItems = $aHeaderItems = array();
304 // initialize the fields we want to retrieve:
305 $aHeaderFields = array();
306 foreach ($aFetchHeaders as $v) {
307 switch ($v) {
308 case SQM_COL_DATE: $aHeaderFields[] = 'Date'; break;
309 case SQM_COL_TO: $aHeaderFields[] = 'To'; break;
310 case SQM_COL_CC: $aHeaderFields[] = 'Cc'; break;
311 case SQM_COL_FROM: $aHeaderFields[] = 'From'; break;
312 case SQM_COL_SUBJ: $aHeaderFields[] = 'Subject'; break;
313 case SQM_COL_PRIO: $aHeaderFields[] = 'X-Priority'; break;
314 case SQM_COL_ATTACHMENT: $aHeaderFields[] = 'Content-Type'; break;
315 case SQM_COL_INT_DATE: $aFetchItems[] = 'INTERNALDATE'; break;
316 case SQM_COL_FLAGS: $aFetchItems[] = 'FLAGS'; break;
317 case SQM_COL_SIZE: $aFetchItems[] = 'RFC822.SIZE'; break;
318 default: break;
319 }
320 }
321
322 /**
323 * A uidset with sorted uid's is available. We can use the cache
324 */
325 if (isset($aUid) && $aUid ) {
326 // limit the cache to SQM_MAX_PAGES_IN_CACHE
327 if (!$aMailbox['SHOWALL'][$iSetIndx] && isset($aMailbox['MSG_HEADERS'])) {
328 $iMaxMsgs = $iLimit * SQM_MAX_PAGES_IN_CACHE;
329 $iCacheSize = count($aMailbox['MSG_HEADERS']);
330 if ($iCacheSize > $iMaxMsgs) {
331 $iReduce = $iCacheSize - $iMaxMsgs;
332 foreach ($aMailbox['MSG_HEADERS'] as $iUid => $value) {
333 if ($iReduce) {
334 unset($aMailbox['MSG_HEADERS'][$iUid]);
335 } else {
336 break;
337 }
338 --$iReduce;
339 }
340 }
341 }
342
343 $id_slice = array_slice($aUid,$start_msg-1,$iLimit);
344 /* do some funky cache checks */
345 if (isset($aMailbox['MSG_HEADERS']) && is_array($aMailbox['MSG_HEADERS'])) {
346 $aUidCached = array_keys($aMailbox['MSG_HEADERS']);
347 } else {
348 $aMailbox['MSG_HEADERS'] = array();
349 $aUidCached = array();
350 }
351 $aUidNotCached = array_values(array_diff($id_slice,$aUidCached));
352
353 /**
354 * $aUidNotCached contains an array with UID's which need to be fetched to
355 * complete the needed message headers.
356 */
357 if (count($aUidNotCached)) {
358 $aMsgs = sqimap_get_small_header_list($imapConnection,$aUidNotCached,
359 $aHeaderFields,$aFetchItems);
360 // append the msgs to the existend headers
361 $aMailbox['MSG_HEADERS'] += $aMsgs;
362 }
363 } else {
364 /**
365 * Initialize the sorted UID list or initiate a UID list with search
366 * results and fetch the visible message headers
367 */
368
369 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') { // in case of a search request
370
371 if ($aMailbox['SEARCH'][$iSetIndx] && $aMailbox['SORT'] == 0) {
372 $aUid = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
373 } else {
374
375 $iError = 0;
376 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
377 $aUid = $aMailbox['UIDSET'][$iSetIndx];
378 }
379 if (!$iError) {
380 /**
381 * Number of messages is the resultset
382 */
383 $aMailbox['TOTAL'][$iSetIndx] = count($aUid);
384 $id_slice = array_slice($aUid,$aMailbox['OFFSET'], $iLimit);
385 if (count($id_slice)) {
386 $aMailbox['MSG_HEADERS'] = sqimap_get_small_header_list($imapConnection,$id_slice,
387 $aHeaderFields,$aFetchItems);
388 } else {
389 $iError = 1; // FIX ME, define an error code
390 }
391 }
392 } else { //
393 $iError = 0;
394 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
395 $aUid = $aMailbox['UIDSET'][$iSetIndx];
396
397 if (!$iError) {
398 /**
399 * Number of messages is the resultset
400 */
401 $aMailbox['TOTAL'][$iSetIndx] = count($aUid);
402 $id_slice = array_slice($aUid,$aMailbox['OFFSET'], $iLimit);
403 if (count($id_slice)) {
404 $aMailbox['MSG_HEADERS'] = sqimap_get_small_header_list($imapConnection,$id_slice,
405 $aHeaderFields,$aFetchItems);
406 } else {
407 $iError = 1; // FIX ME, define an error code
408 }
409 }
410 }
411 }
412 return $iError;
413 }
414
415 function prepareMessageList(&$aMailbox, $aProps) {
416 /* retrieve the properties */
417 $my_email_address = (isset($aProps['email'])) ? $aProps['email'] : false;
418 $highlight_list = (isset($aProps['config']['highlight_list'])) ? $aProps['config']['highlight_list'] : false;
419 $aColumnDesc = (isset($aProps['columns'])) ? $aProps['columns'] : false;
420 $aExtraColumns = (isset($aProps['extra_columns'])) ? $aProps['extra_columns'] : array();
421 $iAccount = (isset($aProps['account'])) ? (int) $aProps['account'] : 0;
422 $sMailbox = (isset($aProps['mailbox'])) ? $aProps['mailbox'] : false;
423 $sTargetModule = (isset($aProps['module'])) ? $aProps['module'] : 'read_body';
424
425 /*
426 * TODO 1, retrieve array with identity email addresses in order to match against to,cc and set a flag
427 * $aFormattedMessages[$iUid]['match_identity'] = true
428 * The template can show some image if there is a match.
429 * TODO 2, makes sure the matching is done fast by doing a strpos call on the returned $value
430 */
431
432 /**
433 * Only retrieve values for displayable columns
434 */
435 foreach ($aColumnDesc as $k => $v) {
436 switch ($k) {
437 case SQM_COL_FROM: $aCol[SQM_COL_FROM] = 'from'; break;
438 case SQM_COL_DATE: $aCol[SQM_COL_DATE] = 'date'; break;
439 case SQM_COL_SUBJ: $aCol[SQM_COL_SUBJ] = 'subject'; break;
440 case SQM_COL_FLAGS: $aCol[SQM_COL_FLAGS] = 'FLAGS'; break;
441 case SQM_COL_SIZE: $aCol[SQM_COL_SIZE] = 'SIZE'; break;
442 case SQM_COL_PRIO: $aCol[SQM_COL_PRIO] = 'x-priority'; break;
443 case SQM_COL_ATTACHMENT: $aCol[SQM_COL_ATTACHMENT] = 'content-type'; break;
444 case SQM_COL_INT_DATE: $aCol[SQM_COL_INT_DATE] = 'INTERNALDATE'; break;
445 case SQM_COL_TO: $aCol[SQM_COL_TO] = 'to'; break;
446 case SQM_COL_CC: $aCol[SQM_COL_CC] = 'cc'; break;
447 case SQM_COL_BCC: $aCol[SQM_COL_BCC] = 'bcc'; break;
448 default: break;
449 }
450 }
451 $aExtraHighLightColumns = array();
452 foreach ($aExtraColumns as $v) {
453 switch ($v) {
454 case SQM_COL_FROM: $aExtraHighLightColumns[] = 'from'; break;
455 case SQM_COL_SUBJ: $aExtraHighLightColumns[] = 'subject'; break;
456 case SQM_COL_TO: $aExtraHighLightColumns[] = 'to'; break;
457 case SQM_COL_CC: $aExtraHighLightColumns[] = 'cc'; break;
458 case SQM_COL_BCC: $aExtraHighLightColumns[] = 'bcc'; break;
459 default: break;
460 }
461 }
462 $aFormattedMessages = array();
463
464
465 $iSetIndx = $aMailbox['SETINDEX'];
466 $aId = $aMailbox['UIDSET'][$iSetIndx];
467 $aHeaders =& $aMailbox['MSG_HEADERS']; /* use a reference to avoid a copy.
468 MSG_HEADERS can contain large amounts of data */
469 $iOffset = $aMailbox['OFFSET'];
470 $sort = $aMailbox['SORT'];
471 $iPageOffset = $aMailbox['PAGEOFFSET'];
472 $sMailbox = $aMailbox['NAME'];
473 $sSearch = (isset($aMailbox['SEARCH'][$aMailbox['SETINDEX']]) &&
474 $aMailbox['SEARCH'][$aMailbox['SETINDEX']] != 'ALL') ? $aMailbox['SEARCH'][$aMailbox['SETINDEX']] : false;
475 $aSearch = ($sSearch) ? array('search.php',$aMailbox['SETINDEX']) : null;
476 /* avoid improper usage */
477 if ($sMailbox && isset($iAccount) && $sTargetModule) {
478 $aInitQuery = array("account=$iAccount",'mailbox='.urlencode($sMailbox));
479 } else {
480 $aInitQuery = false;
481 }
482
483 if ($aMailbox['SORT'] & SQSORT_THREAD) {
484 $aIndentArray =& $aMailbox['THREAD_INDENT'][$aMailbox['SETINDEX']];
485 $bThread = true;
486 } else {
487 $bThread = false;
488 }
489 /*
490 * Retrieve value for checkbox column
491 */
492 if (!sqgetGlobalVar('checkall',$checkall,SQ_GET)) {
493 $checkall = false;
494 }
495
496 /*
497 * Loop through and display the info for each message.
498 */
499 $iEnd = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $iOffset + $aMailbox['LIMIT'];
500 for ($i=$iOffset,$t=0;$i<$iEnd;++$i) {
501 if (isset($aId[$i])) {
502
503 $bHighLight = false;
504 $value = $title = $link = $target = '';
505 $aQuery = ($aInitQuery !== false) ? $aInitQuery : false;
506 $aMsg = $aHeaders[$aId[$i]];
507 if (isset($aSearch) && count($aSearch) > 1 && $aQuery) {
508 $aQuery[] = "where=". $aSearch[0];
509 $aQuery[] = "what=" . $aSearch[1];
510 }
511 $iUid = (isset($aMsg['UID'])) ? $aMsg['UID'] : $aId[$i];
512 if ($aQuery) {
513 $aQuery[] = "passed_id=$aId[$i]";
514 $aQuery[] = "startMessage=$iPageOffset";
515 }
516
517 foreach ($aCol as $k => $v) {
518 $link = $target = $title = '';
519 $aColumns[$k] = array();
520 $value = (isset($aMsg[$v])) ? $aMsg[$v] : '';
521 $sUnknown = _("Unknown recipient");
522 switch ($k) {
523 case SQM_COL_FROM:
524 $sUnknown = _("Unknown sender");
525 case SQM_COL_TO:
526 case SQM_COL_CC:
527 case SQM_COL_BCC:
528 $sTmp = false;
529 if ($value) {
530 if ($highlight_list && !$bHighLight) {
531 $bHighLight = highlightMessage($aCol[$k], $value, $highlight_list,$aFormattedMessages[$iUid]);
532 }
533 $aAddressList = parseRFC822Address($value);
534 $sTmp = getAddressString($aAddressList,array('best' => true));
535 $title = $title_maybe = '';
536 foreach ($aAddressList as $aAddr) {
537 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL])) ? $aAddr[SQM_ADDR_PERSONAL] : '';
538 $sMailbox = (isset($aAddr[SQM_ADDR_MAILBOX])) ? $aAddr[SQM_ADDR_MAILBOX] : '';
539 $sHost = (isset($aAddr[SQM_ADDR_HOST])) ? $aAddr[SQM_ADDR_HOST] : '';
540 if ($sPersonal) {
541 $title .= htmlspecialchars($sMailbox.'@'.$sHost).', ';
542 } else {
543 // if $value gets truncated we need to add the addresses with no
544 // personal name as well
545 $title_maybe .= htmlspecialchars($sMailbox.'@'.$sHost).', ';
546 }
547 }
548 if ($title) {
549 $title = substr($title,0,-2); // strip ', ';
550 }
551 $sTmp = decodeHeader($sTmp);
552 if (isset($aColumnDesc[$k]['truncate']) && $aColumnDesc[$k]['truncate']) {
553 $sTrunc = truncateWithEntities($sTmp, $aColumnDesc[$k]['truncate']);
554 if ($sTrunc != $sTmp) {
555 if (!$title) {
556 $title = htmlspecialchars($sTmp);
557 } else if ($title_maybe) {
558 $title = $title .', '.$title_maybe;
559 $title = substr($title,0,-2); // strip ', ';
560 }
561 }
562 $sTmp = $sTrunc;
563 }
564 }
565 $value = ($sTmp) ? $sTmp : $sUnknown;
566 break;
567 case SQM_COL_SUBJ:
568 // subject is mime encoded, decode it.
569 // value is sanitized in decoding function.
570 // TODO, verify if it should be done before or after the highlighting
571 $value=decodeHeader($value);
572 if ($highlight_list && !$bHighLight) {
573 $bHighLight = highlightMessage('SUBJECT', $value, $highlight_list, $aFormattedMessages[$iUid]);
574 }
575 $iIndent = (isset($aIndentArray[$aId[$i]])) ? $aIndentArray[$aId[$i]] : 0;
576 // FIXME: don't break 8bit symbols and html entities during truncation
577 if (isset($aColumnDesc[$k]['truncate']) && $aColumnDesc[$k]['truncate']) {
578 $sTmp = truncateWithEntities($value, $aColumnDesc[$k]['truncate']-$iIndent);
579 // drop any double spaces since these will be displayed in the title
580 $title = ($sTmp != $value) ? preg_replace('/\s{2,}/', ' ', $value) : '';
581 $value = $sTmp;
582 }
583 /* generate the link to the message */
584 if ($aQuery) {
585 // TODO, $sTargetModule should be a query parameter so that we can use a single entrypoint
586 $link = $sTargetModule.'.php?' . implode('&amp;',$aQuery);
587 }
588 $value = (trim($value)) ? $value : _("(no subject)");
589 /* add thread indentation */
590 $aColumns[$k]['indent'] = $iIndent;
591 break;
592 case SQM_COL_SIZE:
593 $value = show_readable_size($value);
594 break;
595 case SQM_COL_DATE:
596 case SQM_COL_INT_DATE:
597 $value = getDateString(getTimeStamp(explode(' ',trim($value))));
598 break;
599 case SQM_COL_FLAGS:
600 $aFlagColumn = array('seen' => false,
601 'deleted'=>false,
602 'answered'=>false,
603 'flagged' => false,
604 'draft' => false);
605
606 if(!is_array($value)) $value = array();
607 foreach ($value as $sFlag => $value) {
608 switch ($sFlag) {
609 case '\\seen' : $aFlagColumn['seen'] = true; break;
610 case '\\deleted' : $aFlagColumn['deleted'] = true; break;
611 case '\\answered': $aFlagColumn['answered'] = true; break;
612 case '\\flagged' : $aFlagColumn['flagged'] = true; break;
613 case '\\draft' : $aFlagColumn['draft'] = true; break;
614 default: break;
615 }
616 }
617 $value = $aFlagColumn;
618 break;
619 case SQM_COL_PRIO:
620 $value = ($value) ? (int) $value : 3;
621 break;
622 case SQM_COL_ATTACHMENT:
623 $value = (is_array($value) && $value[0] == 'multipart' && $value[1] == 'mixed') ? true : false;
624 break;
625 case SQM_COL_CHECK:
626 $value = $checkall;
627 break;
628 default : break;
629 }
630 if ($title) { $aColumns[$k]['title'] = $title; }
631 if ($link) { $aColumns[$k]['link'] = $link; }
632 if ($target) { $aColumns[$k]['target'] = $target; }
633 $aColumns[$k]['value'] = $value;
634 }
635 /* columns which will not be displayed but should be inspected
636 because the highlight list contains rules with those columns */
637 foreach ($aExtraHighLightColumns as $v) {
638 if ($highlight_list && !$bHighLight && isset($aMsg[$v])) {
639 $bHighLight = highlightMessage($v, $aMsg[$v], $highlight_list,$aFormattedMessages[$iUid]);
640 }
641 }
642 $aFormattedMessages[$iUid]['columns'] = $aColumns;
643
644 } else {
645 break;
646 }
647 }
648 return $aFormattedMessages;
649 }
650
651
652
653 function highlightMessage($sCol, $sVal, $highlight_list, &$aFormat) {
654 if (!is_array($highlight_list) && count($highlight_list) == 0) {
655 return false;
656 }
657 $hlt_color = false;
658 $sCol = strtoupper($sCol);
659
660 foreach ($highlight_list as $highlight_list_part) {
661 if (trim($highlight_list_part['value'])) {
662 $high_val = strtolower($highlight_list_part['value']);
663 $match_type = strtoupper($highlight_list_part['match_type']);
664 if($match_type == 'TO_CC') {
665 if ($sCol == 'TO' || $sCol == 'CC') {
666 $match_type = $sCol;
667 } else {
668 continue;
669 }
670 } else {
671 if ($match_type != $sCol) {
672 continue;
673 }
674 }
675 if (strpos(strtolower($sVal),$high_val) !== false) {
676 $hlt_color = $highlight_list_part['color'];
677 break;
678 }
679 }
680 }
681 if ($hlt_color) {
682 // Bug in highlight color???
683 if ($hlt_color{0} != '#') {
684 $hlt_color = '#'. $hlt_color;
685 }
686 $aFormat['row']['color'] = $hlt_color;
687 return true;
688 } else {
689 return false;
690 }
691 }
692
693 function setUserPref($username, $pref, $value) {
694 global $data_dir;
695 setPref($data_dir,$username,$pref,$value);
696 }
697
698 /**
699 * Execute the sorting for a mailbox
700 *
701 * @param resource $imapConnection Imap connection
702 * @param array $aMailbox (reference) Mailbox retrieved with sqm_api_mailbox_select
703 * @return int $error (reference) Error number
704 * @private
705 * @author Marc Groot Koerkamp
706 */
707 function _get_sorted_msgs_list($imapConnection,&$aMailbox) {
708 $iSetIndx = (isset($aMailbox['SETINDEX'])) ? $aMailbox['SETINDEX'] : 0;
709 $bDirection = !($aMailbox['SORT'] % 2);
710 $error = 0;
711 if (!$aMailbox['SEARCH'][$iSetIndx]) {
712 $aMailbox['SEARCH'][$iSetIndx] = 'ALL';
713 }
714 if (($aMailbox['SORT'] & SQSORT_THREAD) && sqimap_capability($imapConnection,'THREAD')) {
715 $aRes = get_thread_sort($imapConnection,$aMailbox['SEARCH'][$iSetIndx]);
716 if ($aRes === false) {
717 $aMailbox['SORT'] -= SQSORT_THREAD;
718 $error = 1; // fix me, define an error code;
719 } else {
720 $aMailbox['UIDSET'][$iSetIndx] = $aRes[0];
721 $aMailbox['THREAD_INDENT'][$iSetIndx] = $aRes[1];
722 }
723 } else if ($aMailbox['SORT'] === SQSORT_NONE) {
724 $id = sqimap_run_search($imapConnection, 'ALL' , '');
725 if ($id === false) {
726 $error = 1; // fix me, define an error code
727 } else {
728 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($id);
729 $aMailbox['TOTAL'][$iSetIndx] = $aMailbox['EXISTS'];
730 }
731 } else {
732 if (sqimap_capability($imapConnection,'SORT')) {
733 $sSortField = _getSortField($aMailbox['SORT'],true);
734 $id = sqimap_get_sort_order($imapConnection, $sSortField, $bDirection, $aMailbox['SEARCH'][$iSetIndx]);
735 if ($id === false) {
736 $error = 1; // fix me, define an error code
737 } else {
738 $aMailbox['UIDSET'][$iSetIndx] = $id;
739 }
740 } else {
741 $id = NULL;
742 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') {
743 $id = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
744 }
745 $sSortField = _getSortField($aMailbox['SORT'],false);
746 $aMailbox['UIDSET'][$iSetIndx] = get_squirrel_sort($imapConnection, $sSortField, $bDirection, $id);
747 }
748 }
749 return $error;
750 }
751
752 /**
753 * Does the $srt $_GET var to field mapping
754 *
755 * @param int $srt Field to sort on
756 * @param bool $bServerSort Server sorting is true
757 * @return string $sSortField Field to sort on
758 * @private
759 */
760 function _getSortField($sort,$bServerSort) {
761 switch($sort) {
762 case SQSORT_NONE:
763 $sSortField = 'UID';
764 break;
765 case SQSORT_DATE_ASC:
766 case SQSORT_DATE_DESC:
767 $sSortField = 'DATE';
768 break;
769 case SQSORT_FROM_ASC:
770 case SQSORT_FROM_DESC:
771 $sSortField = 'FROM';
772 break;
773 case SQSORT_SUBJ_ASC:
774 case SQSORT_SUBJ_DESC:
775 $sSortField = 'SUBJECT';
776 break;
777 case SQSORT_SIZE_ASC:
778 case SQSORT_SIZE_DESC:
779 $sSortField = ($bServerSort) ? 'SIZE' : 'RFC822.SIZE';
780 break;
781 case SQSORT_TO_ASC:
782 case SQSORT_TO_DESC:
783 $sSortField = 'TO';
784 break;
785 case SQSORT_CC_ASC:
786 case SQSORT_CC_DESC:
787 $sSortField = 'CC';
788 break;
789 case SQSORT_INT_DATE_ASC:
790 case SQSORT_INT_DATE_DESC:
791 $sSortField = ($bServerSort) ? 'ARRIVAL' : 'INTERNALDATE';
792 break;
793 case SQSORT_THREAD:
794 break;
795 default: $sSortField = 'UID';
796 break;
797
798 }
799 return $sSortField;
800 }
801
802 function calcFetchColumns(&$aMailbox, &$aProps) {
803
804 $highlight_list = (isset($aProps['config']['highlight_list'])) ? $aProps['config']['highlight_list'] : false;
805 $aColumnsDesc = (isset($aProps['columns'])) ? $aProps['columns'] : false;
806
807 $aFetchColumns = $aColumnsDesc;
808 if (isset($aFetchColumns[SQM_COL_CHECK])) {
809 unset($aFetchColumns[SQM_COL_CHECK]);
810 }
811
812 /*
813 * Before we fetch the message headers, check if we need to fetch extra columns
814 * to make the message highlighting work
815 */
816 if (is_array($highlight_list) && count($highlight_list)) {
817 $aHighlightColumns = array();
818 foreach ($highlight_list as $highlight_list_part) {
819 if (trim($highlight_list_part['value'])) {
820 $match_type = strtoupper($highlight_list_part['match_type']);
821 switch ($match_type) {
822 case 'TO_CC':
823 $aHighlightColumns[SQM_COL_TO] = true;
824 $aHighlightColumns[SQM_COL_CC] = true;
825 break;
826 case 'TO': $aHighlightColumns[SQM_COL_TO] = true; break;
827 case 'CC': $aHighlightColumns[SQM_COL_CC] = true; break;
828 case 'FROM': $aHighlightColumns[SQM_COL_FROM] = true; break;
829 case 'SUBJECT':$aHighlightColumns[SQM_COL_SUBJ] = true; break;
830 }
831 }
832 }
833 $aExtraColumns = array();
834 foreach ($aHighlightColumns as $k => $v) {
835 if (!isset($aFetchColumns[$k])) {
836 $aExtraColumns[] = $k;
837 $aFetchColumns[$k] = true;
838 }
839 }
840 if (count($aExtraColumns)) {
841 $aProps['extra_columns'] = $aExtraColumns;
842 }
843 }
844 $aMailbox['FETCHHEADERS'] = array_keys($aFetchColumns);
845
846 ;
847 }
848
849
850 /**
851 * This function loops through a group of messages in the mailbox
852 * and shows them to the user.
853 *
854 * @param resource $imapConnection
855 * @param array $aMailbox associative array with mailbox related vars
856 * @param array $aProps
857 * @param int $iError error code, 0 is no error
858 */
859 function showMessagesForMailbox($imapConnection, &$aMailbox,$aProps, &$iError) {
860 global $PHP_SELF;
861 global $boxes;
862
863 $highlight_list = (isset($aProps['config']['highlight_list'])) ? $aProps['config']['highlight_list'] : false;
864 $fancy_index_highlite = (isset($aProps['config']['fancy_index_highlite'])) ? $aProps['config']['fancy_index_highlite'] : true;
865 $aColumnsDesc = (isset($aProps['columns'])) ? $aProps['columns'] : false;
866 $iAccount = (isset($aProps['account'])) ? (int) $aProps['account'] : 0;
867 $sMailbox = (isset($aProps['mailbox'])) ? $aProps['mailbox'] : false;
868 $sTargetModule = (isset($aProps['module'])) ? $aProps['module'] : 'read_body';
869 $show_flag_buttons = (isset($aProps['config']['show_flag_buttons'])) ? $aProps['config']['show_flag_buttons'] : true;
870 $lastTargetMailbox = (isset($aProps['config']['lastTargetMailbox'])) ? $aProps['config']['lastTargetMailbox'] : '';
871 $aOrder = array_keys($aProps['columns']);
872 $trash_folder = (isset($aProps['config']['trash_folder']) && $aProps['config']['trash_folder'])
873 ? $aProps['config']['trash_folder'] : false;
874 $sent_folder = (isset($aProps['config']['sent_folder']) && $aProps['config']['sent_folder'])
875 ? $aProps['config']['sent_folder'] : false;
876 $draft_folder = (isset($aProps['config']['draft_folder']) && $aProps['config']['draft_folder'])
877 ? $aProps['config']['draft_folder'] : false;
878 $page_selector = (isset($aProps['config']['page_selector'])) ? $aProps['config']['page_selector'] : false;
879 $page_selector_max = (isset($aProps['config']['page_selector_max'])) ? $aProps['config']['page_selector_max'] : 10;
880 $color = $aProps['config']['color'];
881
882
883 /*
884 * Form ID
885 */
886 static $iFormId;
887
888 if (!isset($iFormId)) {
889 $iFormId=1;
890 } else {
891 ++$iFormId;
892 }
893 // store the columns to fetch so we can pick them up in read_body
894 // where we validate the cache.
895 calcFetchColumns($aMailbox ,$aProps);
896
897 $iError = fetchMessageHeaders($imapConnection, $aMailbox);
898 if ($iError) {
899 return array();
900 } else {
901 $aMessages = prepareMessageList($aMailbox, $aProps);
902 }
903
904 $iSetIndx = $aMailbox['SETINDEX'];
905 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $aMailbox['LIMIT'];
906 $iEnd = ($aMailbox['PAGEOFFSET'] + ($iLimit - 1) < $aMailbox['EXISTS']) ?
907 $aMailbox['PAGEOFFSET'] + $iLimit - 1 : $aMailbox['EXISTS'];
908
909 $iNumberOfMessages = $aMailbox['TOTAL'][$iSetIndx];
910 $iEnd = min ( $iEnd, $iNumberOfMessages );
911
912 $php_self = $PHP_SELF;
913
914 $urlMailbox = urlencode($aMailbox['NAME']);
915
916 if (preg_match('/^(.+)\?.+$/',$php_self,$regs)) {
917 $source_url = $regs[1];
918 } else {
919 $source_url = $php_self;
920 }
921
922 $baseurl = $source_url.'?mailbox=' . urlencode($aMailbox['NAME']) .'&amp;account='.$aMailbox['ACCOUNT'];
923 $where = urlencode($aMailbox['SEARCH'][$iSetIndx][0]);
924 $what = urlencode($aMailbox['SEARCH'][$iSetIndx][1]);
925 $baseurl .= '&amp;where=' . $where . '&amp;what=' . $what;
926
927 /* build thread sorting links */
928 $newsort = $aMailbox['SORT'];
929 if (sqimap_capability($imapConnection,'THREAD')) {
930 if ($aMailbox['SORT'] & SQSORT_THREAD) {
931 $newsort -= SQSORT_THREAD;
932 $thread_name = _("Unthread View");
933 } else {
934 $thread_name = _("Thread View");
935 $newsort = $aMailbox['SORT'] + SQSORT_THREAD;
936 }
937 $thread_link_str = '<small>[<a href="' . $baseurl . '&amp;srt='
938 . $newsort . '&amp;startMessage=1">' . $thread_name
939 . '</a>]</small>';
940 } else {
941 $thread_link_str ='';
942 }
943 $sort = $aMailbox['SORT'];
944
945 /* FIX ME ADD CHECKBOX CONTROL. No checkbox => no buttons */
946
947
948
949 /* future admin control over displayable buttons */
950
951 $aAdminControl = array(
952 'markUnflagged' => 1,
953 'markFlagged' => 1,
954 'markRead' => 1,
955 'markUnread' => 1,
956 'forward' => 1,
957 'delete' => 1,
958 'undeleteButton'=> 1,
959 'bypass_trash' => 1,
960 'expungeButton' => 1,
961 'moveButton' => 1
962 );
963 /* user prefs control */
964 $aUserControl = array (
965
966 'markUnflagged' => $show_flag_buttons,
967 'markFlagged' => $show_flag_buttons,
968 'markRead' => 1,
969 'markUnread' => 1,
970 'forward' => 1,
971 'delete' => 1,
972 'undeleteButton'=> 1,
973 'bypass_trash' => 1,
974 'expungeButton' => 1,
975 'moveButton' => 1
976
977 );
978
979 $showDelete = ($aMailbox['RIGHTS'] != 'READ-ONLY' &&
980 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ? true : false;
981 $showByPassTrash = (($aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
982 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) &&
983 $trash_folder) ? true : false; //
984
985 $showUndelete = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
986 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true) && !$trash_folder) ? true : false;
987 $showMove = ($aMailbox['RIGHTS'] != 'READ-ONLY') ? true : false;
988 $showExpunge = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
989 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ? true : false;
990 $aImapControl = array (
991 'markUnflagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
992 'markFlagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
993 'markRead' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
994 'markUnread' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
995 'forward' => 1,
996 'delete' => $showDelete,
997 'undeleteButton'=> $showUndelete,
998 'bypass_trash' => $showByPassTrash,
999 'expungeButton' => $showExpunge,
1000 'moveButton' => $showMove
1001 );
1002 $aButtonStrings = array(
1003 'markUnflagged' => _("Unflag"),
1004 'markFlagged' => _("Flag"),
1005 'markRead' => _("Read"),
1006 'markUnread' => _("Unread"),
1007 'forward' => _("Forward"),
1008 'delete' => _("Delete"),
1009 'undeleteButton' => _("Undelete"),
1010 'bypass_trash' => _("Bypass Trash"),
1011 'expungeButton' => _("Expunge"),
1012 'moveButton' => _("Move")
1013 );
1014
1015
1016 /**
1017 * Register buttons in order to an array
1018 * The key is the "name", the first element of the value array is the "value", second argument is the type.
1019 */
1020 $aFormElements = array();
1021 foreach($aAdminControl as $k => $v) {
1022 if ($v & $aUserControl[$k] & $aImapControl[$k]) {
1023 switch ($k) {
1024 case 'markUnflagged':
1025 case 'markFlagged':
1026 case 'markRead':
1027 case 'markUnread':
1028 case 'delete':
1029 case 'undeleteButton':
1030 case 'expungeButton':
1031 case 'forward':
1032 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1033 break;
1034 case 'bypass_trash':
1035 $aFormElements[$k] = array($aButtonStrings[$k],'checkbox');
1036 break;
1037 case 'moveButton':
1038 $aFormElements['targetMailbox'] =
1039 array(sqimap_mailbox_option_list($imapConnection, array(strtolower($lastTargetMailbox)), 0, $boxes),'select');
1040 $aFormElements['mailbox'] = array($aMailbox['NAME'],'hidden');
1041 $aFormElements['startMessage'] = array($aMailbox['PAGEOFFSET'],'hidden');
1042 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1043 break;
1044 }
1045 }
1046 $aFormElements['account'] = array($iAccount,'hidden');
1047 }
1048
1049 /*
1050 * This is the beginning of the message list table.
1051 * It wraps around all messages
1052 */
1053 $safe_name = preg_replace("/[^0-9A-Za-z_]/", '_', $aMailbox['NAME']);
1054 $form_name = "FormMsgs" . $safe_name;
1055
1056 //if (!sqgetGlobalVar('align',$align,SQ_SESSION)) {
1057 $align = array('left' => 'left', 'right' => 'right');
1058 //}
1059 //sm_print_r($align);
1060
1061 /* finally set the template vars */
1062
1063 // FIX ME, before we support multiple templates we must review the names of the vars
1064
1065
1066 $aTemplate['color'] = $color;
1067 $aTemplate['form_name'] = "FormMsgs" . $safe_name;
1068 $aTemplate['form_id'] = 'mbx_'.$iFormId;
1069 $aTemplate['page_selector'] = $page_selector;
1070 $aTemplate['page_selector_max'] = $page_selector_max;
1071 $aTemplate['messagesPerPage'] = $aMailbox['LIMIT'];
1072 $aTemplate['showall'] = $aMailbox['SHOWALL'][$iSetIndx];
1073 $aTemplate['end_msg'] = $iEnd;
1074 $aTemplate['align'] = $align;
1075 $aTemplate['iNumberOfMessages'] = $iNumberOfMessages;
1076 $aTemplate['aOrder'] = $aOrder;
1077 $aTemplate['aFormElements'] = $aFormElements;
1078 $aTemplate['sort'] = $sort;
1079 $aTemplate['pageOffset'] = $aMailbox['PAGEOFFSET'];
1080 $aTemplate['baseurl'] = $baseurl;
1081 $aTemplate['aMessages'] =& $aMessages;
1082 $aTemplate['trash_folder'] = $trash_folder;
1083 $aTemplate['sent_folder'] = $sent_folder;
1084 $aTemplate['draft_folder'] = $draft_folder;
1085 $aTemplate['thread_link_str'] = $thread_link_str;
1086 $aTemplate['php_self'] = str_replace('&','&amp;',$php_self);
1087 $aTemplate['mailbox'] = $sMailbox;
1088 $aTemplate['javascript_on'] = (isset($aProps['config']['javascript_on'])) ? $aProps['config']['javascript_on'] : false;
1089 $aTemplate['enablesort'] = (isset($aProps['config']['enablesort'])) ? $aProps['config']['enablesort'] : false;
1090 $aTemplate['icon_theme'] = (isset($aProps['config']['icon_theme'])) ? $aProps['config']['icon_theme'] : false;
1091 $aTemplate['use_icons'] = (isset($aProps['config']['use_icons'])) ? $aProps['config']['use_icons'] : false;
1092 $aTemplate['alt_index_colors'] = (isset($aProps['config']['alt_index_colors'])) ? $aProps['config']['alt_index_colors'] : false;
1093 $aTemplate['fancy_index_highlite'] = $fancy_index_highlite;
1094
1095
1096 return $aTemplate;
1097 }
1098
1099
1100 /**
1101 * Truncates a string and take care of html encoded characters
1102 *
1103 * @param string $s string to truncate
1104 * @param int $iTrimAt Trim at nn characters
1105 * @return string Trimmed string
1106 */
1107 function truncateWithEntities($s, $iTrimAt) {
1108 global $languages, $squirrelmail_language;
1109
1110 $ent_strlen = strlen($s);
1111 if (($iTrimAt <= 0) || ($ent_strlen <= $iTrimAt))
1112 return $s;
1113
1114 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1115 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth')) {
1116 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth', $s, $iTrimAt);
1117 } else {
1118 /*
1119 * see if this is entities-encoded string
1120 * If so, Iterate through the whole string, find out
1121 * the real number of characters, and if more
1122 * than $iTrimAt, substr with an updated trim value.
1123 */
1124 $trim_val = $iTrimAt;
1125 $ent_offset = 0;
1126 $ent_loc = 0;
1127 while ( $ent_loc < $trim_val && (($ent_loc = strpos($s, '&', $ent_offset)) !== false) &&
1128 (($ent_loc_end = strpos($s, ';', $ent_loc+3)) !== false) ) {
1129 $trim_val += ($ent_loc_end-$ent_loc);
1130 $ent_offset = $ent_loc_end+1;
1131 }
1132
1133 if (($trim_val > $iTrimAt) && ($ent_strlen > $trim_val) && (strpos($s,';',$trim_val) < ($trim_val + 6))) {
1134 $i = strpos($s,';',$trim_val);
1135 if ($i !== false) {
1136 $trim_val = strpos($s,';',$trim_val)+1;
1137 }
1138 }
1139 // only print '...' when we're actually dropping part of the subject
1140 if ($ent_strlen <= $trim_val)
1141 return $s;
1142 }
1143 return substr_replace($s, '...', $trim_val);
1144 }
1145
1146
1147 /**
1148 * This should go in imap_mailbox.php
1149 * @param string $mailbox
1150 */
1151 function handleAsSent($mailbox) {
1152 global $handleAsSent_result;
1153
1154 /* First check if this is the sent or draft folder. */
1155 $handleAsSent_result = isSentMailbox($mailbox) || isDraftMailbox($mailbox);
1156
1157 /* Then check the result of the handleAsSent hook. */
1158 do_hook('check_handleAsSent_result', $mailbox);
1159
1160 /* And return the result. */
1161 return $handleAsSent_result;
1162 }
1163
1164 /**
1165 * Process messages list form and handle the cache gracefully. If $sButton and
1166 * $aUid are provided as argument then you can fake a message list submit and
1167 * use it i.e. in read_body.php for del move next and update the cache
1168 *
1169 * @param resource $imapConnection imap connection
1170 * @param array $aMailbox (reference) cached mailbox
1171 * @param string $sButton fake a submit button
1172 * @param array $aUid fake the $msg array
1173 * @return string $sError error string in case of an error
1174 * @author Marc Groot Koerkamp
1175 */
1176 function handleMessageListForm($imapConnection,&$aMailbox,$sButton='',$aUid = array()) {
1177 /* incoming formdata */
1178 $sButton = (sqgetGlobalVar('moveButton', $sTmp, SQ_POST)) ? 'move' : $sButton;
1179 $sButton = (sqgetGlobalVar('expungeButton', $sTmp, SQ_POST)) ? 'expunge' : $sButton;
1180 $sButton = (sqgetGlobalVar('forward', $sTmp, SQ_POST)) ? 'forward' : $sButton;
1181 $sButton = (sqgetGlobalVar('delete', $sTmp, SQ_POST)) ? 'setDeleted' : $sButton;
1182 $sButton = (sqgetGlobalVar('undeleteButton', $sTmp, SQ_POST)) ? 'unsetDeleted' : $sButton;
1183 $sButton = (sqgetGlobalVar('markRead', $sTmp, SQ_POST)) ? 'setSeen' : $sButton;
1184 $sButton = (sqgetGlobalVar('markUnread', $sTmp, SQ_POST)) ? 'unsetSeen' : $sButton;
1185 $sButton = (sqgetGlobalVar('markFlagged', $sTmp, SQ_POST)) ? 'setFlagged' : $sButton;
1186 $sButton = (sqgetGlobalVar('markUnflagged', $sTmp, SQ_POST)) ? 'unsetFlagged' : $sButton;
1187 sqgetGlobalVar('targetMailbox', $targetMailbox, SQ_POST);
1188 sqgetGlobalVar('bypass_trash', $bypass_trash, SQ_POST);
1189 sqgetGlobalVar('msg', $msg, SQ_POST);
1190 if (sqgetGlobalVar('account', $iAccount, SQ_POST) === false) {
1191 $iAccount = 0;
1192 }
1193 $sError = '';
1194 $mailbox = $aMailbox['NAME'];
1195
1196 /* retrieve the check boxes */
1197 $aUid = (isset($msg) && is_array($msg)) ? array_values($msg) : $aUid;
1198 if (count($aUid) && $sButton != 'expunge') {
1199 $aUpdatedMsgs = false;
1200 $bExpunge = false;
1201 switch ($sButton) {
1202 case 'setDeleted':
1203 // check if id exists in case we come from read_body
1204 if (count($aUid) == 1 && is_array($aMailbox['UIDSET'][$aMailbox['SETINDEX']]) &&
1205 !in_array($aUid[0],$aMailbox['UIDSET'][$aMailbox['SETINDEX']])) {
1206 break;
1207 }
1208 $aUpdatedMsgs = sqimap_msgs_list_delete($imapConnection, $mailbox, $aUid,$bypass_trash);
1209 $bExpunge = true;
1210 //}
1211 break;
1212 case 'unsetDeleted':
1213 case 'setSeen':
1214 case 'unsetSeen':
1215 case 'setFlagged':
1216 case 'unsetFlagged':
1217 // get flag
1218 $sFlag = (substr($sButton,0,3) == 'set') ? '\\'.substr($sButton,3) : '\\'.substr($sButton,5);
1219 $bSet = (substr($sButton,0,3) == 'set') ? true : false;
1220 $aUpdatedMsgs = sqimap_toggle_flag($imapConnection, $aUid, $sFlag, $bSet, true);
1221 break;
1222 case 'move':
1223 $aUpdatedMsgs = sqimap_msgs_list_move($imapConnection,$aUid,$targetMailbox);
1224 sqsession_register($targetMailbox,'lastTargetMailbox');
1225 $bExpunge = true;
1226 break;
1227 case 'forward':
1228 $aMsgHeaders = array();
1229 foreach ($aUid as $iUid) {
1230 $aMsgHeaders[$iUid] = $aMailbox['MSG_HEADERS'][$iUid];
1231 }
1232 if (count($aMsgHeaders)) {
1233 $composesession = attachSelectedMessages($imapConnection,$aMsgHeaders);
1234 // dirty hack, add info to $aMailbox
1235 $aMailbox['FORWARD_SESSION'] = $composesession;
1236 }
1237 break;
1238 default:
1239 // Hook for plugin buttons
1240 do_hook_function('mailbox_display_button_action', $aUid);
1241 break;
1242 }
1243 /**
1244 * Updates messages is an array containing the result of the untagged
1245 * fetch responses send by the imap server due to a flag change. That
1246 * response is parsed in a array with msg arrays by the parseFetch function
1247 */
1248 if ($aUpdatedMsgs) {
1249 // Update the message headers cache
1250 $aDeleted = array();
1251 foreach ($aUpdatedMsgs as $iUid => $aMsg) {
1252 if (isset($aMsg['FLAGS'])) {
1253 /**
1254 * Only update the cached headers if the header is
1255 * cached.
1256 */
1257 if (isset($aMailbox['MSG_HEADERS'][$iUid])) {
1258 $aMailbox['MSG_HEADERS'][$iUid]['FLAGS'] = $aMsg['FLAGS'];
1259 }
1260 /**
1261 * Count the messages with the \Delete flag set so we can determine
1262 * if the number of expunged messages equals the number of flagged
1263 * messages for deletion.
1264 */
1265 if (isset($aMsg['FLAGS']['\\deleted']) && $aMsg['FLAGS']['\\deleted']) {
1266 $aDeleted[] = $iUid;
1267 }
1268 }
1269 }
1270 if ($bExpunge && $aMailbox['AUTO_EXPUNGE'] &&
1271 $iExpungedMessages = sqimap_mailbox_expunge($imapConnection, $aMailbox['NAME'], true))
1272 {
1273 if (count($aDeleted) != $iExpungedMessages) {
1274 // there are more messages deleted permanently then we expected
1275 // invalidate the cache
1276 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = false;
1277 $aMailbox['MSG_HEADERS'] = false;
1278 } else {
1279 // remove expunged messages from cache
1280 $aUidSet = $aMailbox['UIDSET'][$aMailbox['SETINDEX']];
1281 if (is_array($aUidSet)) {
1282 // create a UID => array index temp array
1283 $aUidSetDummy = array_flip($aUidSet);
1284 foreach ($aDeleted as $iUid) {
1285 // get the id as well in case of SQM_SORT_NONE
1286 if ($aMailbox['SORT'] == SQSORT_NONE) {
1287 $aMailbox['ID'] = false;
1288 //$iId = $aMailbox['MSG_HEADERS'][$iUid]['ID'];
1289 //unset($aMailbox['ID'][$iId]);
1290 }
1291 // unset the UID and message header
1292 unset($aUidSetDummy[$iUid]);
1293 unset($aMailbox['MSG_HEADERS'][$iUid]);
1294 }
1295 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = array_keys($aUidSetDummy);
1296 }
1297 }
1298 // update EXISTS info
1299 if ($iExpungedMessages) {
1300 $aMailbox['EXISTS'] -= (int) $iExpungedMessages;
1301 $aMailbox['TOTAL'][$aMailbox['SETINDEX']] -= (int) $iExpungedMessages;
1302 }
1303 if (($aMailbox['PAGEOFFSET']-1) >= $aMailbox['EXISTS']) {
1304 $aMailbox['PAGEOFFSET'] = ($aMailbox['PAGEOFFSET'] > $aMailbox['LIMIT']) ?
1305 $aMailbox['PAGEOFFSET'] - $aMailbox['LIMIT'] : 1;
1306 $aMailbox['OFFSET'] = $aMailbox['PAGEOFFSET'] - 1 ;
1307 }
1308 }
1309 }
1310 } else {
1311 if ($sButton == 'expunge') {
1312 /**
1313 * on expunge we do not know which messages will be deleted
1314 * so it's useless to try to sync the cache
1315 *
1316 * Close the mailbox so we do not need to parse the untagged expunge
1317 * responses which do not contain uid info.
1318 * NB: Closing a mailbox is faster then expunge because the imap
1319 * server does not need to generate the untagged expunge responses
1320 */
1321 sqimap_run_command($imapConnection,'CLOSE',false,$result,$message);
1322 $aMailbox = sqm_api_mailbox_select($imapConnection,$iAccount, $aMailbox['NAME'],array(),array());
1323 } else {
1324 if ($sButton) {
1325 $sError = _("No messages were selected.");
1326 }
1327 }
1328 }
1329 return $sError;
1330 }
1331
1332 function attachSelectedMessages($imapConnection,$aMsgHeaders) {
1333 global $username, $attachment_dir,
1334 $data_dir;
1335
1336
1337 sqgetGlobalVar('composesession', $composesession, SQ_SESSION);
1338 sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION);
1339 if (!isset($compose_messages)|| is_null($compose_messages)) {
1340 $compose_messages = array();
1341 sqsession_register($compose_messages,'compose_messages');
1342 }
1343
1344 if (!$composesession) {
1345 $composesession = 1;
1346 sqsession_register($composesession,'composesession');
1347 } else {
1348 $composesession++;
1349 sqsession_register($composesession,'composesession');
1350 }
1351
1352 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
1353
1354 $composeMessage = new Message();
1355 $rfc822_header = new Rfc822Header();
1356 $composeMessage->rfc822_header = $rfc822_header;
1357 $composeMessage->reply_rfc822_header = '';
1358
1359 foreach($aMsgHeaders as $iUid => $aMsgHeader) {
1360 /**
1361 * Retrieve the full message
1362 */
1363 $body_a = sqimap_run_command($imapConnection, "FETCH $iUid RFC822", true, $response, $readmessage, TRUE);
1364 if ($response == 'OK') {
1365
1366 $subject = (isset($aMsgHeader['subject'])) ? $aMsgHeader['subject'] : $iUid;
1367
1368 array_shift($body_a);
1369 array_pop($body_a);
1370 $body = implode('', $body_a);
1371 $body .= "\r\n";
1372
1373 $localfilename = GenerateRandomString(32, 'FILE', 7);
1374 $full_localfilename = "$hashed_attachment_dir/$localfilename";
1375
1376 $fp = fopen( $full_localfilename, 'wb');
1377 fwrite ($fp, $body);
1378 fclose($fp);
1379 $composeMessage->initAttachment('message/rfc822',$subject.'.msg',
1380 $full_localfilename);
1381 }
1382 }
1383
1384 $compose_messages[$composesession] = $composeMessage;
1385 sqsession_register($compose_messages,'compose_messages');
1386 return $composesession;
1387 }
1388
1389 ?>