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