drop any double spaces since these will be displayed in the title-attribute
[squirrelmail.git] / functions / mailbox_display.php
1 <?php
2
3 /**
4 * mailbox_display.php
5 *
6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This contains functions that display mailbox information, such as the
10 * table row that has sender, date, subject, etc...
11 *
12 * @version $Id$
13 * @package squirrelmail
14 */
15
16 /** The standard includes.. */
17 require_once(SM_PATH . 'functions/strings.php');
18 require_once(SM_PATH . 'functions/html.php');
19 require_once(SM_PATH . 'functions/imap_mailbox.php');
20 require_once(SM_PATH . 'functions/imap_messages.php');
21 require_once(SM_PATH . 'functions/imap_asearch.php');
22 require_once(SM_PATH . 'functions/mime.php');
23 require_once(SM_PATH . 'functions/forms.php');
24
25
26 /**
27 * Selects a mailbox for header retrieval.
28 * Cache control for message headers is embedded.
29 *
30 * @param resource $imapConnection imap socket handle
31 * @param string $mailbox mailbox to select and retrieve message headers from
32 * @param array $aConfig array with system config settings and incoming vars
33 * @param array $aProps mailbox specific properties
34 * @return array $aMailbox mailbox array with all relevant information
35 * @author Marc Groot Koerkamp
36 */
37 function sqm_api_mailbox_select($imapConnection,$account,$mailbox,$aConfig,$aProps) {
38
39 /**
40 * NB: retrieve this from the session before accessing this function
41 * and make sure you write it back at the end of the script after
42 * the aMailbox var is added so that the headers are added to the cache
43 */
44 global $mailbox_cache;
45
46 $aDefaultConfigProps = array(
47 // 'charset' => 'US-ASCII',
48 'user' => false, /* no pref storage if false */
49 'setindex' => 0,
50 // 'search' => 'ALL',
51 'max_cache_size' => SQM_MAX_MBX_IN_CACHE
52 );
53
54 $aConfig = array_merge($aDefaultConfigProps,$aConfig);
55
56 $iSetIndx = $aConfig['setindex'];
57
58 $aMbxResponse = sqimap_mailbox_select($imapConnection, $mailbox);
59
60 if ($mailbox_cache) {
61 if (isset($mailbox_cache[$account.'_'.$mailbox])) {
62 $aCachedMailbox = $mailbox_cache[$account.'_'.$mailbox];
63 } else {
64 $aCachedMailbox = false;
65 }
66 /* cleanup cache */
67 if (count($mailbox_cache) > $aConfig['max_cache_size'] -1) {
68 $aTime = array();
69 foreach($mailbox_cache as $cachedmailbox => $aVal) {
70 $aTime[$aVal['TIMESTAMP']] = $cachedmailbox;
71 }
72 if (ksort($aTime,SORT_NUMERIC)) {
73 for ($i=0,$iCnt=count($mailbox_cache);$i<($iCnt-$aConfig['max_cache_size']);++$i) {
74 $sOldestMbx = array_shift($aTime);
75 /**
76 * Remove only the UIDSET and MSG_HEADERS from cache because those can
77 * contain large amounts of data.
78 */
79 if (isset($mailbox_cache[$sOldestMbx]['UIDSET'])) {
80 $mailbox_cache[$sOldestMbx]['UIDSET']= false;
81 }
82 if (isset($mailbox_cache[$sOldestMbx]['MSG_HEADERS'])) {
83 $mailbox_cache[$sOldestMbx]['MSG_HEADERS'] = false;
84 }
85 }
86 }
87 }
88
89 } else {
90 $aCachedMailbox = false;
91 }
92
93 /**
94 * Deal with imap servers that do not return the required UIDNEXT or
95 * UIDVALIDITY response
96 * from a SELECT call (since rfc 3501 it's required).
97 */
98 if (!isset($aMbxResponse['UIDNEXT']) || !isset($aMbxResponse['UIDVALIDITY'])) {
99 $aStatus = sqimap_status_messages($imapConnection,$mailbox,
100 array('UIDNEXT','UIDVALIDITY'));
101 $aMbxResponse['UIDNEXT'] = $aStatus['UIDNEXT'];
102 $aMbxResponse['UIDVALIDTY'] = $aStatus['UIDVALIDITY'];
103 }
104
105 $aMailbox['ACCOUNT'] = $account;
106 $aMailbox['UIDSET'][$iSetIndx] = false;
107 $aMailbox['ID'] = false;
108 $aMailbox['SETINDEX'] = $iSetIndx;
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'])) {
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
803
804
805 /**
806 * This function loops through a group of messages in the mailbox
807 * and shows them to the user.
808 *
809 * @param resource $imapConnection
810 * @param array $aMailbox associative array with mailbox related vars
811 * @param array $aProps
812 * @param int $iError error code, 0 is no error
813 */
814 function showMessagesForMailbox($imapConnection, &$aMailbox,$aProps, &$iError) {
815 global $PHP_SELF;
816 global $boxes;
817
818 $highlight_list = (isset($aProps['config']['highlight_list'])) ? $aProps['config']['highlight_list'] : false;
819 $fancy_index_highlite = (isset($aProps['config']['fancy_index_highlite'])) ? $aProps['config']['fancy_index_highlite'] : true;
820 $aColumnsDesc = (isset($aProps['columns'])) ? $aProps['columns'] : false;
821 $iAccount = (isset($aProps['account'])) ? (int) $aProps['account'] : 0;
822 $sMailbox = (isset($aProps['mailbox'])) ? $aProps['mailbox'] : false;
823 $sTargetModule = (isset($aProps['module'])) ? $aProps['module'] : 'read_body';
824 $show_flag_buttons = (isset($aProps['config']['show_flag_buttons'])) ? $aProps['config']['show_flag_buttons'] : true;
825 $lastTargetMailbox = (isset($aProps['config']['lastTargetMailbox'])) ? $aProps['config']['lastTargetMailbox'] : '';
826 $aOrder = array_keys($aProps['columns']);
827 $trash_folder = (isset($aProps['config']['trash_folder']) && $aProps['config']['trash_folder'])
828 ? $aProps['config']['trash_folder'] : false;
829 $sent_folder = (isset($aProps['config']['sent_folder']) && $aProps['config']['sent_folder'])
830 ? $aProps['config']['sent_folder'] : false;
831 $draft_folder = (isset($aProps['config']['draft_folder']) && $aProps['config']['draft_folder'])
832 ? $aProps['config']['draft_folder'] : false;
833 $page_selector = (isset($aProps['config']['page_selector'])) ? $aProps['config']['page_selector'] : false;
834 $page_selector_max = (isset($aProps['config']['page_selector_max'])) ? $aProps['config']['page_selector_max'] : 10;
835 $color = $aProps['config']['color'];
836
837
838 /*
839 * Form ID
840 */
841 static $iFormId;
842
843 if (!isset($iFormId)) {
844 $iFormId=1;
845 } else {
846 ++$iFormId;
847 }
848 /*
849 * Remove the checkbox column because we cannot fetch it from the imap server
850 */
851 $aFetchColumns = $aColumnsDesc;
852 if (isset($aFetchColumns[SQM_COL_CHECK])) {
853 unset($aFetchColumns[SQM_COL_CHECK]);
854 }
855
856 /*
857 * Before we fetch the message headers, check if we need to fetch extra columns
858 * to make the message highlighting work
859 */
860 if (is_array($highlight_list) && count($highlight_list)) {
861 $aHighlightColumns = array();
862 foreach ($highlight_list as $highlight_list_part) {
863 if (trim($highlight_list_part['value'])) {
864 $match_type = strtoupper($highlight_list_part['match_type']);
865 switch ($match_type) {
866 case 'TO_CC':
867 $aHighlightColumns[SQM_COL_TO] = true;
868 $aHighlightColumns[SQM_COL_CC] = true;
869 break;
870 case 'TO': $aHighlightColumns[SQM_COL_TO] = true; break;
871 case 'CC': $aHighlightColumns[SQM_COL_CC] = true; break;
872 case 'FROM': $aHighlightColumns[SQM_COL_FROM] = true; break;
873 case 'SUBJECT':$aHighlightColumns[SQM_COL_SUBJ] = true; break;
874 }
875 }
876 }
877 $aExtraColumns = array();
878 foreach ($aHighlightColumns as $k => $v) {
879 if (!isset($aFetchColumns[$k])) {
880 $aExtraColumns[] = $k;
881 $aFetchColumns[$k] = true;
882 }
883 }
884 if (count($aExtraColumns)) {
885 $aProps['extra_columns'] = $aExtraColumns;
886 }
887 }
888 $aFetchColumns = array_keys($aFetchColumns);
889 // store the columns to fetch so we can pick them up in read_body
890 // where we validate the cache.
891 $aMailbox['FETCHHEADERS'] = $aFetchColumns;
892
893 $iError = fetchMessageHeaders($imapConnection, $aMailbox);
894 if ($iError) {
895 return array();
896 } else {
897 $aMessages = prepareMessageList($aMailbox, $aProps);
898 }
899
900 $iSetIndx = $aMailbox['SETINDEX'];
901 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $aMailbox['LIMIT'];
902 $iEnd = ($aMailbox['PAGEOFFSET'] + ($iLimit - 1) < $aMailbox['EXISTS']) ?
903 $aMailbox['PAGEOFFSET'] + $iLimit - 1 : $aMailbox['EXISTS'];
904
905 $iNumberOfMessages = $aMailbox['TOTAL'][$iSetIndx];
906 $iEnd = min ( $iEnd, $iNumberOfMessages );
907
908 $php_self = $PHP_SELF;
909
910 $urlMailbox = urlencode($aMailbox['NAME']);
911
912 if (preg_match('/^(.+)\?.+$/',$php_self,$regs)) {
913 $source_url = $regs[1];
914 } else {
915 $source_url = $php_self;
916 }
917
918 $baseurl = $source_url.'?mailbox=' . urlencode($aMailbox['NAME']) .'&amp;account='.$aMailbox['ACCOUNT'];
919 $where = urlencode($aMailbox['SEARCH'][$iSetIndx][0]);
920 $what = urlencode($aMailbox['SEARCH'][$iSetIndx][1]);
921 $baseurl .= '&amp;where=' . $where . '&amp;what=' . $what;
922
923 /* build thread sorting links */
924 $newsort = $aMailbox['SORT'];
925 if (sqimap_capability($imapConnection,'THREAD')) {
926 if ($aMailbox['SORT'] & SQSORT_THREAD) {
927 $newsort -= SQSORT_THREAD;
928 $thread_name = _("Unthread View");
929 } else {
930 $thread_name = _("Thread View");
931 $newsort = $aMailbox['SORT'] + SQSORT_THREAD;
932 }
933 $thread_link_str = '<small>[<a href="' . $baseurl . '&amp;srt='
934 . $newsort . '&amp;startMessage=1">' . $thread_name
935 . '</a>]</small>';
936 } else {
937 $thread_link_str ='';
938 }
939 $sort = $aMailbox['SORT'];
940
941 /* FIX ME ADD CHECKBOX CONTROL. No checkbox => no buttons */
942
943
944
945 /* future admin control over displayable buttons */
946
947 $aAdminControl = array(
948 'markUnflagged' => 1,
949 'markFlagged' => 1,
950 'markRead' => 1,
951 'markUnread' => 1,
952 'forward' => 1,
953 'delete' => 1,
954 'undeleteButton'=> 1,
955 'bypass_trash' => 1,
956 'expungeButton' => 1,
957 'moveButton' => 1
958 );
959 /* user prefs control */
960 $aUserControl = array (
961
962 'markUnflagged' => $show_flag_buttons,
963 'markFlagged' => $show_flag_buttons,
964 'markRead' => 1,
965 'markUnread' => 1,
966 'forward' => 1,
967 'delete' => 1,
968 'undeleteButton'=> 1,
969 'bypass_trash' => 1,
970 'expungeButton' => 1,
971 'moveButton' => 1
972
973 );
974
975 $showDelete = ($aMailbox['RIGHTS'] != 'READ-ONLY' &&
976 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ? true : false;
977 $showByPassTrash = (($aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
978 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) &&
979 $trash_folder) ? true : false; //
980
981 $showUndelete = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
982 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true) && !$trash_folder) ? true : false;
983 $showMove = ($aMailbox['RIGHTS'] != 'READ-ONLY') ? true : false;
984 $showExpunge = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
985 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ? true : false;
986 $aImapControl = array (
987 'markUnflagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
988 'markFlagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
989 'markRead' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
990 'markUnread' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
991 'forward' => 1,
992 'delete' => $showDelete,
993 'undeleteButton'=> $showUndelete,
994 'bypass_trash' => $showByPassTrash,
995 'expungeButton' => $showExpunge,
996 'moveButton' => $showMove
997 );
998 $aButtonStrings = array(
999 'markUnflagged' => _("Unflag"),
1000 'markFlagged' => _("Flag"),
1001 'markRead' => _("Read"),
1002 'markUnread' => _("Unread"),
1003 'forward' => _("Forward"),
1004 'delete' => _("Delete"),
1005 'undeleteButton' => _("Undelete"),
1006 'bypass_trash' => _("Bypass Trash"),
1007 'expungeButton' => _("Expunge"),
1008 'moveButton' => _("Move")
1009 );
1010
1011
1012 /**
1013 * Register buttons in order to an array
1014 * The key is the "name", the first element of the value array is the "value", second argument is the type.
1015 */
1016 $aFormElements = array();
1017 foreach($aAdminControl as $k => $v) {
1018 if ($v & $aUserControl[$k] & $aImapControl[$k]) {
1019 switch ($k) {
1020 case 'markUnflagged':
1021 case 'markFlagged':
1022 case 'markRead':
1023 case 'markUnread':
1024 case 'delete':
1025 case 'undeleteButton':
1026 case 'expungeButton':
1027 case 'forward':
1028 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1029 break;
1030 case 'bypass_trash':
1031 $aFormElements[$k] = array($aButtonStrings[$k],'checkbox');
1032 break;
1033 case 'moveButton':
1034 $aFormElements['targetMailbox'] =
1035 array(sqimap_mailbox_option_list($imapConnection, array(strtolower($lastTargetMailbox)), 0, $boxes),'select');
1036 $aFormElements['mailbox'] = array($aMailbox['NAME'],'hidden');
1037 $aFormElements['startMessage'] = array($aMailbox['PAGEOFFSET'],'hidden');
1038 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1039 break;
1040 }
1041 }
1042 $aFormElements['account'] = array($iAccount,'hidden');
1043 }
1044
1045 /*
1046 * This is the beginning of the message list table.
1047 * It wraps around all messages
1048 */
1049 $safe_name = preg_replace("/[^0-9A-Za-z_]/", '_', $aMailbox['NAME']);
1050 $form_name = "FormMsgs" . $safe_name;
1051
1052 //if (!sqgetGlobalVar('align',$align,SQ_SESSION)) {
1053 $align = array('left' => 'left', 'right' => 'right');
1054 //}
1055 //sm_print_r($align);
1056
1057 /* finally set the template vars */
1058
1059 // FIX ME, before we support multiple templates we must review the names of the vars
1060
1061
1062 $aTemplate['color'] = $color;
1063 $aTemplate['form_name'] = "FormMsgs" . $safe_name;
1064 $aTemplate['form_id'] = 'mbx_'.$iFormId;
1065 $aTemplate['page_selector'] = $page_selector;
1066 $aTemplate['page_selector_max'] = $page_selector_max;
1067 $aTemplate['messagesPerPage'] = $aMailbox['LIMIT'];
1068 $aTemplate['showall'] = $aMailbox['SHOWALL'][$iSetIndx];
1069 $aTemplate['end_msg'] = $iEnd;
1070 $aTemplate['align'] = $align;
1071 $aTemplate['iNumberOfMessages'] = $iNumberOfMessages;
1072 $aTemplate['aOrder'] = $aOrder;
1073 $aTemplate['aFormElements'] = $aFormElements;
1074 $aTemplate['sort'] = $sort;
1075 $aTemplate['pageOffset'] = $aMailbox['PAGEOFFSET'];
1076 $aTemplate['baseurl'] = $baseurl;
1077 $aTemplate['aMessages'] =& $aMessages;
1078 $aTemplate['trash_folder'] = $trash_folder;
1079 $aTemplate['sent_folder'] = $sent_folder;
1080 $aTemplate['draft_folder'] = $draft_folder;
1081 $aTemplate['thread_link_str'] = $thread_link_str;
1082 $aTemplate['php_self'] = str_replace('&','&amp;',$php_self);
1083 $aTemplate['mailbox'] = $sMailbox;
1084 $aTemplate['javascript_on'] = (isset($aProps['config']['javascript_on'])) ? $aProps['config']['javascript_on'] : false;
1085 $aTemplate['enablesort'] = (isset($aProps['config']['enablesort'])) ? $aProps['config']['enablesort'] : false;
1086 $aTemplate['icon_theme'] = (isset($aProps['config']['icon_theme'])) ? $aProps['config']['icon_theme'] : false;
1087 $aTemplate['use_icons'] = (isset($aProps['config']['use_icons'])) ? $aProps['config']['use_icons'] : false;
1088 $aTemplate['alt_index_colors'] = (isset($aProps['config']['alt_index_colors'])) ? $aProps['config']['alt_index_colors'] : false;
1089 $aTemplate['fancy_index_highlite'] = $fancy_index_highlite;
1090
1091
1092 return $aTemplate;
1093 }
1094
1095
1096 /**
1097 * Truncates a string and take care of html encoded characters
1098 *
1099 * @param string $s string to truncate
1100 * @param int $iTrimAt Trim at nn characters
1101 * @return string Trimmed string
1102 */
1103 function truncateWithEntities($s, $iTrimAt) {
1104 global $languages, $squirrelmail_language;
1105
1106 $ent_strlen = strlen($s);
1107 if (($iTrimAt <= 0) || ($ent_strlen <= $iTrimAt))
1108 return $s;
1109
1110 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1111 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth')) {
1112 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth', $s, $iTrimAt);
1113 } else {
1114 /*
1115 * see if this is entities-encoded string
1116 * If so, Iterate through the whole string, find out
1117 * the real number of characters, and if more
1118 * than $iTrimAt, substr with an updated trim value.
1119 */
1120 $trim_val = $iTrimAt;
1121 $ent_offset = 0;
1122 $ent_loc = 0;
1123 while ( $ent_loc < $trim_val && (($ent_loc = strpos($s, '&', $ent_offset)) !== false) &&
1124 (($ent_loc_end = strpos($s, ';', $ent_loc+3)) !== false) ) {
1125 $trim_val += ($ent_loc_end-$ent_loc);
1126 $ent_offset = $ent_loc_end+1;
1127 }
1128
1129 if (($trim_val > $iTrimAt) && ($ent_strlen > $trim_val) && (strpos($s,';',$trim_val) < ($trim_val + 6))) {
1130 $i = strpos($s,';',$trim_val);
1131 if ($i !== false) {
1132 $trim_val = strpos($s,';',$trim_val)+1;
1133 }
1134 }
1135 // only print '...' when we're actually dropping part of the subject
1136 if ($ent_strlen <= $trim_val)
1137 return $s;
1138 }
1139 return substr_replace($s, '...', $trim_val);
1140 }
1141
1142
1143 /**
1144 * This should go in imap_mailbox.php
1145 * @param string $mailbox
1146 */
1147 function handleAsSent($mailbox) {
1148 global $handleAsSent_result;
1149
1150 /* First check if this is the sent or draft folder. */
1151 $handleAsSent_result = isSentMailbox($mailbox) || isDraftMailbox($mailbox);
1152
1153 /* Then check the result of the handleAsSent hook. */
1154 do_hook('check_handleAsSent_result', $mailbox);
1155
1156 /* And return the result. */
1157 return $handleAsSent_result;
1158 }
1159
1160 /**
1161 * Process messages list form and handle the cache gracefully. If $sButton and
1162 * $aUid are provided as argument then you can fake a message list submit and
1163 * use it i.e. in read_body.php for del move next and update the cache
1164 *
1165 * @param resource $imapConnection imap connection
1166 * @param array $aMailbox (reference) cached mailbox
1167 * @param string $sButton fake a submit button
1168 * @param array $aUid fake the $msg array
1169 * @return string $sError error string in case of an error
1170 * @author Marc Groot Koerkamp
1171 */
1172 function handleMessageListForm($imapConnection,&$aMailbox,$sButton='',$aUid = array()) {
1173 /* incoming formdata */
1174 $sButton = (sqgetGlobalVar('moveButton', $sTmp, SQ_POST)) ? 'move' : $sButton;
1175 $sButton = (sqgetGlobalVar('expungeButton', $sTmp, SQ_POST)) ? 'expunge' : $sButton;
1176 $sButton = (sqgetGlobalVar('forward', $sTmp, SQ_POST)) ? 'forward' : $sButton;
1177 $sButton = (sqgetGlobalVar('delete', $sTmp, SQ_POST)) ? 'setDeleted' : $sButton;
1178 $sButton = (sqgetGlobalVar('undeleteButton', $sTmp, SQ_POST)) ? 'unsetDeleted' : $sButton;
1179 $sButton = (sqgetGlobalVar('markRead', $sTmp, SQ_POST)) ? 'setSeen' : $sButton;
1180 $sButton = (sqgetGlobalVar('markUnread', $sTmp, SQ_POST)) ? 'unsetSeen' : $sButton;
1181 $sButton = (sqgetGlobalVar('markFlagged', $sTmp, SQ_POST)) ? 'setFlagged' : $sButton;
1182 $sButton = (sqgetGlobalVar('markUnflagged', $sTmp, SQ_POST)) ? 'unsetFlagged' : $sButton;
1183 sqgetGlobalVar('targetMailbox', $targetMailbox, SQ_POST);
1184 sqgetGlobalVar('bypass_trash', $bypass_trash, SQ_POST);
1185 sqgetGlobalVar('msg', $msg, SQ_POST);
1186 if (sqgetGlobalVar('account', $iAccount, SQ_POST) === false) {
1187 $iAccount = 0;
1188 }
1189 $sError = '';
1190 $mailbox = $aMailbox['NAME'];
1191
1192 /* retrieve the check boxes */
1193 $aUid = (isset($msg) && is_array($msg)) ? array_values($msg) : $aUid;
1194 if (count($aUid) && $sButton != 'expunge') {
1195 $aUpdatedMsgs = false;
1196 $bExpunge = false;
1197 switch ($sButton) {
1198 case 'setDeleted':
1199 // check if id exists in case we come from read_body
1200 if (count($aUid) == 1 && is_array($aMailbox['UIDSET'][$aMailbox['SETINDEX']]) &&
1201 !in_array($aUid[0],$aMailbox['UIDSET'][$aMailbox['SETINDEX']])) {
1202 break;
1203 }
1204 $aUpdatedMsgs = sqimap_msgs_list_delete($imapConnection, $mailbox, $aUid,$bypass_trash);
1205 $bExpunge = true;
1206 //}
1207 break;
1208 case 'unsetDeleted':
1209 case 'setSeen':
1210 case 'unsetSeen':
1211 case 'setFlagged':
1212 case 'unsetFlagged':
1213 // get flag
1214 $sFlag = (substr($sButton,0,3) == 'set') ? '\\'.substr($sButton,3) : '\\'.substr($sButton,5);
1215 $bSet = (substr($sButton,0,3) == 'set') ? true : false;
1216 $aUpdatedMsgs = sqimap_toggle_flag($imapConnection, $aUid, $sFlag, $bSet, true);
1217 break;
1218 case 'move':
1219 $aUpdatedMsgs = sqimap_msgs_list_move($imapConnection,$aUid,$targetMailbox);
1220 sqsession_register($targetMailbox,'lastTargetMailbox');
1221 $bExpunge = true;
1222 break;
1223 case 'forward':
1224 $aMsgHeaders = array();
1225 foreach ($aUid as $iUid) {
1226 $aMsgHeaders[$iUid] = $aMailbox['MSG_HEADERS'][$iUid];
1227 }
1228 if (count($aMsgHeaders)) {
1229 $composesession = attachSelectedMessages($imapConnection,$aMsgHeaders);
1230 // dirty hack, add info to $aMailbox
1231 $aMailbox['FORWARD_SESSION'] = $composesession;
1232 }
1233 break;
1234 default:
1235 // Hook for plugin buttons
1236 do_hook_function('mailbox_display_button_action', $aUid);
1237 break;
1238 }
1239 /**
1240 * Updates messages is an array containing the result of the untagged
1241 * fetch responses send by the imap server due to a flag change. That
1242 * response is parsed in a array with msg arrays by the parseFetch function
1243 */
1244 if ($aUpdatedMsgs) {
1245 // Update the message headers cache
1246 $aDeleted = array();
1247 foreach ($aUpdatedMsgs as $iUid => $aMsg) {
1248 if (isset($aMsg['FLAGS'])) {
1249 /**
1250 * Only update the cached headers if the header is
1251 * cached.
1252 */
1253 if (isset($aMailbox['MSG_HEADERS'][$iUid])) {
1254 $aMailbox['MSG_HEADERS'][$iUid]['FLAGS'] = $aMsg['FLAGS'];
1255 }
1256 /**
1257 * Count the messages with the \Delete flag set so we can determine
1258 * if the number of expunged messages equals the number of flagged
1259 * messages for deletion.
1260 */
1261 if (isset($aMsg['FLAGS']['\\deleted']) && $aMsg['FLAGS']['\\deleted']) {
1262 $aDeleted[] = $iUid;
1263 }
1264 }
1265 }
1266 if ($bExpunge && $aMailbox['AUTO_EXPUNGE'] &&
1267 $iExpungedMessages = sqimap_mailbox_expunge($imapConnection, $aMailbox['NAME'], true))
1268 {
1269 if (count($aDeleted) != $iExpungedMessages) {
1270 // there are more messages deleted permanently then we expected
1271 // invalidate the cache
1272 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = false;
1273 $aMailbox['MSG_HEADERS'] = false;
1274 } else {
1275 // remove expunged messages from cache
1276 $aUidSet = $aMailbox['UIDSET'][$aMailbox['SETINDEX']];
1277 if (is_array($aUidSet)) {
1278 // create a UID => array index temp array
1279 $aUidSetDummy = array_flip($aUidSet);
1280 foreach ($aDeleted as $iUid) {
1281 // get the id as well in case of SQM_SORT_NONE
1282 if ($aMailbox['SORT'] == SQSORT_NONE) {
1283 $aMailbox['ID'] = false;
1284 //$iId = $aMailbox['MSG_HEADERS'][$iUid]['ID'];
1285 //unset($aMailbox['ID'][$iId]);
1286 }
1287 // unset the UID and message header
1288 unset($aUidSetDummy[$iUid]);
1289 unset($aMailbox['MSG_HEADERS'][$iUid]);
1290 }
1291 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = array_keys($aUidSetDummy);
1292 }
1293 }
1294 // update EXISTS info
1295 if ($iExpungedMessages) {
1296 $aMailbox['EXISTS'] -= (int) $iExpungedMessages;
1297 $aMailbox['TOTAL'][$aMailbox['SETINDEX']] -= (int) $iExpungedMessages;
1298 }
1299 if (($aMailbox['PAGEOFFSET']-1) >= $aMailbox['EXISTS']) {
1300 $aMailbox['PAGEOFFSET'] = ($aMailbox['PAGEOFFSET'] > $aMailbox['LIMIT']) ?
1301 $aMailbox['PAGEOFFSET'] - $aMailbox['LIMIT'] : 1;
1302 $aMailbox['OFFSET'] = $aMailbox['PAGEOFFSET'] - 1 ;
1303 }
1304 }
1305 }
1306 } else {
1307 if ($sButton == 'expunge') {
1308 /**
1309 * on expunge we do not know which messages will be deleted
1310 * so it's useless to try to sync the cache
1311
1312 * Close the mailbox so we do not need to parse the untagged expunge
1313 * responses which do not contain uid info.
1314 * NB: Closing a mailbox is faster then expunge because the imap
1315 * server does not need to generate the untagged expunge responses
1316 */
1317 sqimap_run_command($imapConnection,'CLOSE',false,$result,$message);
1318 $aMailbox = sqm_api_mailbox_select($imapConnection,$iAccount, $aMailbox['NAME'],array(),array());
1319 } else {
1320 if ($sButton) {
1321 $sError = _("No messages were selected.");
1322 }
1323 }
1324 }
1325 return $sError;
1326 }
1327
1328 function attachSelectedMessages($imapConnection,$aMsgHeaders) {
1329 global $username, $attachment_dir,
1330 $data_dir;
1331
1332
1333 sqgetGlobalVar('composesession', $composesession, SQ_SESSION);
1334 sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION);
1335 if (!isset($compose_messages)|| is_null($compose_messages)) {
1336 $compose_messages = array();
1337 sqsession_register($compose_messages,'compose_messages');
1338 }
1339
1340 if (!$composesession) {
1341 $composesession = 1;
1342 sqsession_register($composesession,'composesession');
1343 } else {
1344 $composesession++;
1345 sqsession_register($composesession,'composesession');
1346 }
1347
1348 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
1349
1350 $composeMessage = new Message();
1351 $rfc822_header = new Rfc822Header();
1352 $composeMessage->rfc822_header = $rfc822_header;
1353 $composeMessage->reply_rfc822_header = '';
1354
1355 foreach($aMsgHeaders as $iUid => $aMsgHeader) {
1356 /**
1357 * Retrieve the full message
1358 */
1359 $body_a = sqimap_run_command($imapConnection, "FETCH $iUid RFC822", true, $response, $readmessage, TRUE);
1360 if ($response == 'OK') {
1361
1362 $subject = (isset($aMsgHeader['subject'])) ? $aMsgHeader['subject'] : $iUid;
1363
1364 array_shift($body_a);
1365 array_pop($body_a);
1366 $body = implode('', $body_a);
1367 $body .= "\r\n";
1368
1369 $localfilename = GenerateRandomString(32, 'FILE', 7);
1370 $full_localfilename = "$hashed_attachment_dir/$localfilename";
1371
1372 $fp = fopen( $full_localfilename, 'wb');
1373 fwrite ($fp, $body);
1374 fclose($fp);
1375 $composeMessage->initAttachment('message/rfc822',$subject.'.msg',
1376 $full_localfilename);
1377 }
1378 }
1379
1380 $compose_messages[$composesession] = $composeMessage;
1381 sqsession_register($compose_messages,'compose_messages');
1382 return $composesession;
1383 }
1384
1385 ?>