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