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