Happy New Year
[squirrelmail.git] / functions / mailbox_display.php
CommitLineData
59177427 1<?php
2ba13803 2
35586184 3/**
4b4abf93 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 *
33aab559 9 * @copyright 1999-2024 The SquirrelMail Project Team
4b4abf93 10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @version $Id$
12 * @package squirrelmail
13 */
a4c2cd49 14
324ac3c5 15
16/**
17 * Selects a mailbox for header retrieval.
18 * Cache control for message headers is embedded.
19 *
20 * @param resource $imapConnection imap socket handle
21 * @param string $mailbox mailbox to select and retrieve message headers from
22 * @param array $aConfig array with system config settings and incoming vars
23 * @param array $aProps mailbox specific properties
134ee6a8 24 * @param boolean $handle_errors When TRUE, IMAP errors
25 * are handled herein, causing
26 * an error to be displayed on
27 * screen and execution to stop
28 * and when FALSE, error status
29 * is returned to the caller
30 * (OPTIONAL; default is TRUE)
d849b570 31 *
324ac3c5 32 * @return array $aMailbox mailbox array with all relevant information
fae2050d 33 * (if $handle_errors is false and there was an
34 * error, the array will be empty)
d849b570 35 *
4955562f 36 * @since 1.5.1
324ac3c5 37 * @author Marc Groot Koerkamp
38 */
134ee6a8 39function sqm_api_mailbox_select($imapConnection,$account,$mailbox,$aConfig,$aProps,$handle_errors=true) {
91c27aee 40
324ac3c5 41 /**
42 * NB: retrieve this from the session before accessing this function
43 * and make sure you write it back at the end of the script after
44 * the aMailbox var is added so that the headers are added to the cache
45 */
46 global $mailbox_cache;
91c27aee 47
324ac3c5 48 $aDefaultConfigProps = array(
324ac3c5 49// 'charset' => 'US-ASCII',
50 'user' => false, /* no pref storage if false */
51 'setindex' => 0,
52// 'search' => 'ALL',
53 'max_cache_size' => SQM_MAX_MBX_IN_CACHE
54 );
55
56 $aConfig = array_merge($aDefaultConfigProps,$aConfig);
91c27aee 57
324ac3c5 58 $iSetIndx = $aConfig['setindex'];
59
134ee6a8 60 $aMbxResponse = sqimap_mailbox_select($imapConnection, $mailbox, $handle_errors);
fae2050d 61 if (empty($aMbxResponse))
62 return $aMbxResponse;
324ac3c5 63
64 if ($mailbox_cache) {
91c27aee 65 if (isset($mailbox_cache[$account.'_'.$mailbox])) {
66 $aCachedMailbox = $mailbox_cache[$account.'_'.$mailbox];
324ac3c5 67 } else {
68 $aCachedMailbox = false;
69 }
70 /* cleanup cache */
71 if (count($mailbox_cache) > $aConfig['max_cache_size'] -1) {
72 $aTime = array();
73 foreach($mailbox_cache as $cachedmailbox => $aVal) {
74 $aTime[$aVal['TIMESTAMP']] = $cachedmailbox;
75 }
76 if (ksort($aTime,SORT_NUMERIC)) {
77 for ($i=0,$iCnt=count($mailbox_cache);$i<($iCnt-$aConfig['max_cache_size']);++$i) {
78 $sOldestMbx = array_shift($aTime);
79 /**
80 * Remove only the UIDSET and MSG_HEADERS from cache because those can
81 * contain large amounts of data.
82 */
83 if (isset($mailbox_cache[$sOldestMbx]['UIDSET'])) {
84 $mailbox_cache[$sOldestMbx]['UIDSET']= false;
85 }
86 if (isset($mailbox_cache[$sOldestMbx]['MSG_HEADERS'])) {
87 $mailbox_cache[$sOldestMbx]['MSG_HEADERS'] = false;
88 }
89 }
90 }
91 }
92
93 } else {
94 $aCachedMailbox = false;
95 }
96
97 /**
98 * Deal with imap servers that do not return the required UIDNEXT or
99 * UIDVALIDITY response
100 * from a SELECT call (since rfc 3501 it's required).
101 */
102 if (!isset($aMbxResponse['UIDNEXT']) || !isset($aMbxResponse['UIDVALIDITY'])) {
103 $aStatus = sqimap_status_messages($imapConnection,$mailbox,
104 array('UIDNEXT','UIDVALIDITY'));
105 $aMbxResponse['UIDNEXT'] = $aStatus['UIDNEXT'];
106 $aMbxResponse['UIDVALIDTY'] = $aStatus['UIDVALIDITY'];
107 }
108
91c27aee 109 $aMailbox['ACCOUNT'] = $account;
324ac3c5 110 $aMailbox['UIDSET'][$iSetIndx] = false;
111 $aMailbox['ID'] = false;
112 $aMailbox['SETINDEX'] = $iSetIndx;
c3731db5 113 $aMailbox['MSG_HEADERS'] = false;
324ac3c5 114
115 if ($aCachedMailbox) {
116 /**
117 * Validate integrity of cached data
118 */
119 if ($aCachedMailbox['EXISTS'] == $aMbxResponse['EXISTS'] &&
120 $aMbxResponse['EXISTS'] &&
121 $aCachedMailbox['UIDVALIDITY'] == $aMbxResponse['UIDVALIDITY'] &&
122 $aCachedMailbox['UIDNEXT'] == $aMbxResponse['UIDNEXT'] &&
123 isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
124 (!isset($aConfig['search']) || /* always set search from the searchpage */
125 $aCachedMailbox['SEARCH'][$iSetIndx] == $aConfig['search'])) {
126 if (isset($aCachedMailbox['MSG_HEADERS'])) {
127 $aMailbox['MSG_HEADERS'] = $aCachedMailbox['MSG_HEADERS'];
128 }
129 $aMailbox['ID'] = $aCachedMailbox['ID'];
130 if (isset($aCachedMailbox['UIDSET'][$iSetIndx]) && $aCachedMailbox['UIDSET'][$iSetIndx]) {
131 if (isset($aProps[MBX_PREF_SORT]) && $aProps[MBX_PREF_SORT] != $aCachedMailbox['SORT'] ) {
132 $newsort = $aProps[MBX_PREF_SORT];
133 $oldsort = $aCachedMailbox['SORT'];
134 /**
135 * If it concerns a reverse sort we do not need to invalidate
136 * the cached sorted UIDSET, a reverse is sufficient.
137 */
138 if ((($newsort % 2) && ($newsort + 1 == $oldsort)) ||
139 (!($newsort % 2) && ($newsort - 1 == $oldsort))) {
140 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($aCachedMailbox['UIDSET'][$iSetIndx]);
141 } else {
91c27aee 142 $server_sort_array = false;
324ac3c5 143 $aMailbox['MSG_HEADERS'] = false;
144 $aMailbox['ID'] = false;
145 }
146 // store the new sort value in the mailbox pref
147 if ($aConfig['user']) {
148 // FIXME, in ideal situation, we write back the
149 // prefs at the end of the script
91c27aee 150 setUserPref($aConfig['user'],'pref_'.$account.'_'.$mailbox,serialize($aProps));
324ac3c5 151 }
152 } else {
153 $aMailbox['UIDSET'][$iSetIndx] = $aCachedMailbox['UIDSET'][$iSetIndx];
154 }
155 }
156 }
157 }
158 /**
159 * Restore the offset in the paginator if no new offset is provided.
160 */
161 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['offset']) && $aCachedMailbox['OFFSET']) {
162 $aMailbox['OFFSET'] = $aCachedMailbox['OFFSET'];
163 $aMailbox['PAGEOFFSET'] = $aCachedMailbox['PAGEOFFSET'];
164 } else {
165 $aMailbox['OFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ? $aConfig['offset'] -1 : 0;
166 $aMailbox['PAGEOFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ? $aConfig['offset'] : 1;
167 }
91c27aee 168 /**
169 * Restore the number of messages in the result set
170 */
171 if (isset($aCachedMailbox['TOTAL'][$iSetIndx]) && $aCachedMailbox['TOTAL'][$iSetIndx]) {
172 $aMailbox['TOTAL'][$iSetIndx] = $aCachedMailbox['TOTAL'][$iSetIndx];
173 }
324ac3c5 174
175 /**
176 * Restore the showall value no new showall value is provided.
177 */
178 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['showall']) &&
179 isset($aCachedMailbox['SHOWALL'][$iSetIndx]) && $aCachedMailbox['SHOWALL'][$iSetIndx]) {
180 $aMailbox['SHOWALL'][$iSetIndx] = $aCachedMailbox['SHOWALL'][$iSetIndx];
181 } else {
182 $aMailbox['SHOWALL'][$iSetIndx] = (isset($aConfig['showall']) && $aConfig['showall']) ? 1 : 0;
183 }
184
91c27aee 185 /**
186 * Restore the sort order if no new sort order is provided.
187 */
324ac3c5 188 if (!isset($aProps[MBX_PREF_SORT]) && isset($aCachedMailbox['SORT'])) {
189 $aMailbox['SORT'] = $aCachedMailbox['SORT'];
190 } else {
191 $aMailbox['SORT'] = (isset($aProps[MBX_PREF_SORT])) ? $aProps[MBX_PREF_SORT] : 0;
192 }
193
91c27aee 194 /**
195 * Restore the number of message to show per page when no new limit is provided
196 */
324ac3c5 197 if (!isset($aProps[MBX_PREF_LIMIT]) && isset($aCachedMailbox['LIMIT'])) {
198 $aMailbox['LIMIT'] = $aCachedMailbox['LIMIT'];
199 } else {
200 $aMailbox['LIMIT'] = (isset($aProps[MBX_PREF_LIMIT])) ? $aProps[MBX_PREF_LIMIT] : 15;
201 }
202
91c27aee 203 /**
204 * Restore the ordered columns to show when no new ordered columns are provided
205 */
206 if (!isset($aProps[MBX_PREF_COLUMNS]) && isset($aCachedMailbox['COLUMNS'])) {
207 $aMailbox['COLUMNS'] = $aCachedMailbox['COLUMNS'];
324ac3c5 208 } else {
91c27aee 209 $aMailbox['COLUMNS'] = (isset($aProps[MBX_PREF_COLUMNS])) ? $aProps[MBX_PREF_COLUMNS] :
210 array(SQM_COL_FLAGS,SQM_COL_FROM, SQM_COL_SUBJ, SQM_COL_FLAGS);
324ac3c5 211 }
212
d0b119a5 213 /**
214 * Restore the headers we fetch the last time. Saves intitialisation stuff in read_body.
215 */
216 $aMailbox['FETCHHEADERS'] = (isset($aCachedMailbox['FETCHHEADERS'])) ? $aCachedMailbox['FETCHHEADERS'] : null;
217
324ac3c5 218 if (!isset($aProps[MBX_PREF_AUTO_EXPUNGE]) && isset($aCachedMailbox['AUTO_EXPUNGE'])) {
219 $aMailbox['AUTO_EXPUNGE'] = $aCachedMailbox['AUTO_EXPUNGE'];
220 } else {
221 $aMailbox['AUTO_EXPUNGE'] = (isset($aProps[MBX_PREF_AUTO_EXPUNGE])) ? $aProps[MBX_PREF_AUTO_EXPUNGE] : false;
222 }
324ac3c5 223 if (!isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx])) {
224 $aMailbox['SEARCH'][$iSetIndx] = $aCachedMailbox['SEARCH'][$iSetIndx];
7762b03c 225 } else if (isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
226 $aConfig['search'] != $aCachedMailbox['SEARCH'][$iSetIndx]) {
227 // reset the pageindex
228 $aMailbox['SEARCH'][$iSetIndx] = $aConfig['search'];
229 $aMailbox['OFFSET'] = 0;
230 $aMailbox['PAGEOFFSET'] = 1;
324ac3c5 231 } else {
232 $aMailbox['SEARCH'][$iSetIndx] = (isset($aConfig['search'])) ? $aConfig['search'] : 'ALL';
233 }
324ac3c5 234 if (!isset($aConfig['charset']) && isset($aCachedMailbox['CHARSET'][$iSetIndx])) {
235 $aMailbox['CHARSET'][$iSetIndx] = $aCachedMailbox['CHARSET'][$iSetIndx];
236 } else {
237 $aMailbox['CHARSET'][$iSetIndx] = (isset($aConfig['charset'])) ? $aConfig['charset'] : 'US-ASCII';
238 }
239
240 $aMailbox['NAME'] = $mailbox;
241 $aMailbox['EXISTS'] = $aMbxResponse['EXISTS'];
242 $aMailbox['SEEN'] = (isset($aMbxResponse['SEEN'])) ? $aMbxResponse['SEEN'] : $aMbxResponse['EXISTS'];
243 $aMailbox['RECENT'] = (isset($aMbxResponse['RECENT'])) ? $aMbxResponse['RECENT'] : 0;
244 $aMailbox['UIDVALIDITY'] = $aMbxResponse['UIDVALIDITY'];
245 $aMailbox['UIDNEXT'] = $aMbxResponse['UIDNEXT'];
246 $aMailbox['PERMANENTFLAGS'] = $aMbxResponse['PERMANENTFLAGS'];
247 $aMailbox['RIGHTS'] = $aMbxResponse['RIGHTS'];
248
324ac3c5 249 /* decide if we are thread sorting or not */
324ac3c5 250 if ($aMailbox['SORT'] & SQSORT_THREAD) {
91c27aee 251 if (!sqimap_capability($imapConnection,'THREAD')) {
252 $aMailbox['SORT'] ^= SQSORT_THREAD;
253 } else {
254 $aMailbox['THREAD_INDENT'] = $aCachedMailbox['THREAD_INDENT'];
255 }
324ac3c5 256 } else {
324ac3c5 257 $aMailbox['THREAD_INDENT'] = false;
258 }
259
260 /* set a timestamp for cachecontrol */
261 $aMailbox['TIMESTAMP'] = time();
262 return $aMailbox;
263}
264
c7df3f1b 265/**
91c27aee 266 * Fetch the message headers for a mailbox. Settings are part of the aMailbox
4955562f 267 * array. Dependent of the mailbox settings it deals with sort, thread and search
268 * If server sort is supported then SORT is also used for retrieving sorted search results
62f7daa5 269 *
91c27aee 270 * @param resource $imapConnection imap socket handle
271 * @param array $aMailbox (reference) mailbox retrieved from sqm_api_mailbox_select
272 * @return error $error error number
4955562f 273 * @since 1.5.1
91c27aee 274 * @author Marc Groot Koerkamp
62f7daa5 275 */
d0b119a5 276function fetchMessageHeaders($imapConnection, &$aMailbox) {
e0e30169 277
91c27aee 278 /* FIX ME, this function is kind of big, maybe we can split it up in
279 a couple of functions. Make sure the functions are private and starts with _
280 Also make sure that the error codes are propagated */
324ac3c5 281
282 /**
283 * Retrieve the UIDSET.
284 * Setindex is used to be able to store multiple uid sets. That will make it
285 * possible to display the mailbox multiple times in different sort order
286 * or to store serach results separate from normal mailbox view.
287 */
288 $iSetIndx = (isset($aMailbox['SETINDEX'])) ? $aMailbox['SETINDEX'] : 0;
289
290 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $aMailbox['LIMIT'];
291 /**
292 * Adjust the start_msg
293 */
294 $start_msg = $aMailbox['PAGEOFFSET'];
295 if($aMailbox['PAGEOFFSET'] > $aMailbox['EXISTS']) {
296 $start_msg -= $aMailbox['LIMIT'];
297 if($start_msg < 1) {
298 $start_msg = 1;
299 }
300 }
d0b119a5 301
324ac3c5 302 if (is_array($aMailbox['UIDSET'])) {
303 $aUid =& $aMailbox['UIDSET'][$iSetIndx];
f6b262a3 304 } else {
324ac3c5 305 $aUid = false;
306 }
d0b119a5 307 $aFetchHeaders = $aMailbox['FETCHHEADERS'];
324ac3c5 308
91c27aee 309 $iError = 0;
310 $aFetchItems = $aHeaderItems = array();
324ac3c5 311 // initialize the fields we want to retrieve:
b4246036 312 $aHeaderFields = array();
91c27aee 313 foreach ($aFetchHeaders as $v) {
314 switch ($v) {
315 case SQM_COL_DATE: $aHeaderFields[] = 'Date'; break;
316 case SQM_COL_TO: $aHeaderFields[] = 'To'; break;
317 case SQM_COL_CC: $aHeaderFields[] = 'Cc'; break;
318 case SQM_COL_FROM: $aHeaderFields[] = 'From'; break;
319 case SQM_COL_SUBJ: $aHeaderFields[] = 'Subject'; break;
320 case SQM_COL_PRIO: $aHeaderFields[] = 'X-Priority'; break;
321 case SQM_COL_ATTACHMENT: $aHeaderFields[] = 'Content-Type'; break;
322 case SQM_COL_INT_DATE: $aFetchItems[] = 'INTERNALDATE'; break;
323 case SQM_COL_FLAGS: $aFetchItems[] = 'FLAGS'; break;
324 case SQM_COL_SIZE: $aFetchItems[] = 'RFC822.SIZE'; break;
325 default: break;
326 }
324ac3c5 327 }
328
324ac3c5 329 /**
330 * A uidset with sorted uid's is available. We can use the cache
331 */
91c27aee 332 if (isset($aUid) && $aUid ) {
324ac3c5 333 // limit the cache to SQM_MAX_PAGES_IN_CACHE
91c27aee 334 if (!$aMailbox['SHOWALL'][$iSetIndx] && isset($aMailbox['MSG_HEADERS'])) {
324ac3c5 335 $iMaxMsgs = $iLimit * SQM_MAX_PAGES_IN_CACHE;
336 $iCacheSize = count($aMailbox['MSG_HEADERS']);
337 if ($iCacheSize > $iMaxMsgs) {
338 $iReduce = $iCacheSize - $iMaxMsgs;
339 foreach ($aMailbox['MSG_HEADERS'] as $iUid => $value) {
340 if ($iReduce) {
341 unset($aMailbox['MSG_HEADERS'][$iUid]);
342 } else {
343 break;
344 }
345 --$iReduce;
346 }
6a622b59 347 }
e9e5f0fa 348 }
324ac3c5 349
350 $id_slice = array_slice($aUid,$start_msg-1,$iLimit);
351 /* do some funky cache checks */
6ab20f61 352 if (isset($aMailbox['MSG_HEADERS']) && is_array($aMailbox['MSG_HEADERS'])) {
fe1521ef 353 // temp code, read_body del / next links fo not update fields.
354 foreach ($aMailbox['MSG_HEADERS'] as $iUid => $aValue) {
355 if (!isset($aValue['UID'])) {
356 unset($aMailbox['MSG_HEADERS'][$iUid]);
357 }
358 }
91c27aee 359 $aUidCached = array_keys($aMailbox['MSG_HEADERS']);
360 } else {
361 $aMailbox['MSG_HEADERS'] = array();
362 $aUidCached = array();
363 }
324ac3c5 364 $aUidNotCached = array_values(array_diff($id_slice,$aUidCached));
91c27aee 365
324ac3c5 366 /**
367 * $aUidNotCached contains an array with UID's which need to be fetched to
368 * complete the needed message headers.
369 */
370 if (count($aUidNotCached)) {
371 $aMsgs = sqimap_get_small_header_list($imapConnection,$aUidNotCached,
372 $aHeaderFields,$aFetchItems);
373 // append the msgs to the existend headers
374 $aMailbox['MSG_HEADERS'] += $aMsgs;
8cc8ec79 375 }
324ac3c5 376 } else {
377 /**
91c27aee 378 * Initialize the sorted UID list or initiate a UID list with search
379 * results and fetch the visible message headers
324ac3c5 380 */
324ac3c5 381
91c27aee 382 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') { // in case of a search request
383
324ac3c5 384 if ($aMailbox['SEARCH'][$iSetIndx] && $aMailbox['SORT'] == 0) {
385 $aUid = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
386 } else {
91c27aee 387
388 $iError = 0;
389 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
324ac3c5 390 $aUid = $aMailbox['UIDSET'][$iSetIndx];
03975a39 391 }
91c27aee 392 if (!$iError) {
393 /**
394 * Number of messages is the resultset
395 */
396 $aMailbox['TOTAL'][$iSetIndx] = count($aUid);
324ac3c5 397 $id_slice = array_slice($aUid,$aMailbox['OFFSET'], $iLimit);
398 if (count($id_slice)) {
399 $aMailbox['MSG_HEADERS'] = sqimap_get_small_header_list($imapConnection,$id_slice,
400 $aHeaderFields,$aFetchItems);
401 } else {
91c27aee 402 $iError = 1; // FIX ME, define an error code
324ac3c5 403 }
03975a39 404 }
91c27aee 405 } else { //
406 $iError = 0;
407 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
408 $aUid = $aMailbox['UIDSET'][$iSetIndx];
409
410 if (!$iError) {
411 /**
412 * Number of messages is the resultset
413 */
414 $aMailbox['TOTAL'][$iSetIndx] = count($aUid);
415 $id_slice = array_slice($aUid,$aMailbox['OFFSET'], $iLimit);
416 if (count($id_slice)) {
417 $aMailbox['MSG_HEADERS'] = sqimap_get_small_header_list($imapConnection,$id_slice,
418 $aHeaderFields,$aFetchItems);
324ac3c5 419 } else {
91c27aee 420 $iError = 1; // FIX ME, define an error code
324ac3c5 421 }
422 }
8cc8ec79 423 }
8cc8ec79 424 }
91c27aee 425 return $iError;
0fdc2fb6 426}
a966982b 427
4955562f 428/**
429 * Prepares the message headers for display inside a template. The links are calculated,
430 * color for row highlighting is calculated and optionally the strings are truncated.
431 *
432 * @param array $aMailbox (reference) mailbox retrieved from sqm_api_mailbox_select
433 * @param array $aProps properties
434 * @return array $aFormattedMessages array with message headers and format info
435 * @since 1.5.1
436 * @author Marc Groot Koerkamp
437 */
91c27aee 438function prepareMessageList(&$aMailbox, $aProps) {
84bb1d31 439
440 /* Globalize link attributes so plugins can share in modifying them */
02def6a1 441 global $link, $title, $target, $onclick, $link_extra, $preselected;
84bb1d31 442
91c27aee 443 /* retrieve the properties */
444 $my_email_address = (isset($aProps['email'])) ? $aProps['email'] : false;
445 $highlight_list = (isset($aProps['config']['highlight_list'])) ? $aProps['config']['highlight_list'] : false;
446 $aColumnDesc = (isset($aProps['columns'])) ? $aProps['columns'] : false;
447 $aExtraColumns = (isset($aProps['extra_columns'])) ? $aProps['extra_columns'] : array();
448 $iAccount = (isset($aProps['account'])) ? (int) $aProps['account'] : 0;
449 $sMailbox = (isset($aProps['mailbox'])) ? $aProps['mailbox'] : false;
450 $sTargetModule = (isset($aProps['module'])) ? $aProps['module'] : 'read_body';
a966982b 451
91c27aee 452 /*
453 * TODO 1, retrieve array with identity email addresses in order to match against to,cc and set a flag
454 * $aFormattedMessages[$iUid]['match_identity'] = true
455 * The template can show some image if there is a match.
456 * TODO 2, makes sure the matching is done fast by doing a strpos call on the returned $value
457 */
8cc8ec79 458
91c27aee 459 /**
460 * Only retrieve values for displayable columns
461 */
462 foreach ($aColumnDesc as $k => $v) {
463 switch ($k) {
464 case SQM_COL_FROM: $aCol[SQM_COL_FROM] = 'from'; break;
465 case SQM_COL_DATE: $aCol[SQM_COL_DATE] = 'date'; break;
466 case SQM_COL_SUBJ: $aCol[SQM_COL_SUBJ] = 'subject'; break;
467 case SQM_COL_FLAGS: $aCol[SQM_COL_FLAGS] = 'FLAGS'; break;
468 case SQM_COL_SIZE: $aCol[SQM_COL_SIZE] = 'SIZE'; break;
469 case SQM_COL_PRIO: $aCol[SQM_COL_PRIO] = 'x-priority'; break;
470 case SQM_COL_ATTACHMENT: $aCol[SQM_COL_ATTACHMENT] = 'content-type'; break;
471 case SQM_COL_INT_DATE: $aCol[SQM_COL_INT_DATE] = 'INTERNALDATE'; break;
472 case SQM_COL_TO: $aCol[SQM_COL_TO] = 'to'; break;
473 case SQM_COL_CC: $aCol[SQM_COL_CC] = 'cc'; break;
474 case SQM_COL_BCC: $aCol[SQM_COL_BCC] = 'bcc'; break;
475 default: break;
476 }
477 }
83eb12fc 478 $aExtraHighLightColumns = array();
479 foreach ($aExtraColumns as $v) {
480 switch ($v) {
481 case SQM_COL_FROM: $aExtraHighLightColumns[] = 'from'; break;
482 case SQM_COL_SUBJ: $aExtraHighLightColumns[] = 'subject'; break;
483 case SQM_COL_TO: $aExtraHighLightColumns[] = 'to'; break;
484 case SQM_COL_CC: $aExtraHighLightColumns[] = 'cc'; break;
485 case SQM_COL_BCC: $aExtraHighLightColumns[] = 'bcc'; break;
23541351 486 default: break;
487 }
488 }
91c27aee 489 $aFormattedMessages = array();
490
491
492 $iSetIndx = $aMailbox['SETINDEX'];
493 $aId = $aMailbox['UIDSET'][$iSetIndx];
494 $aHeaders =& $aMailbox['MSG_HEADERS']; /* use a reference to avoid a copy.
495 MSG_HEADERS can contain large amounts of data */
496 $iOffset = $aMailbox['OFFSET'];
497 $sort = $aMailbox['SORT'];
498 $iPageOffset = $aMailbox['PAGEOFFSET'];
499 $sMailbox = $aMailbox['NAME'];
500 $sSearch = (isset($aMailbox['SEARCH'][$aMailbox['SETINDEX']]) &&
501 $aMailbox['SEARCH'][$aMailbox['SETINDEX']] != 'ALL') ? $aMailbox['SEARCH'][$aMailbox['SETINDEX']] : false;
502 $aSearch = ($sSearch) ? array('search.php',$aMailbox['SETINDEX']) : null;
503 /* avoid improper usage */
504 if ($sMailbox && isset($iAccount) && $sTargetModule) {
505 $aInitQuery = array("account=$iAccount",'mailbox='.urlencode($sMailbox));
8cc8ec79 506 } else {
91c27aee 507 $aInitQuery = false;
8cc8ec79 508 }
509
91c27aee 510 if ($aMailbox['SORT'] & SQSORT_THREAD) {
511 $aIndentArray =& $aMailbox['THREAD_INDENT'][$aMailbox['SETINDEX']];
512 $bThread = true;
513 } else {
514 $bThread = false;
515 }
516 /*
517 * Retrieve value for checkbox column
518 */
519 if (!sqgetGlobalVar('checkall',$checkall,SQ_GET)) {
520 $checkall = false;
e4b5f9d1 521 }
522
91c27aee 523 /*
524 * Loop through and display the info for each message.
525 */
526 $iEnd = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $iOffset + $aMailbox['LIMIT'];
527 for ($i=$iOffset,$t=0;$i<$iEnd;++$i) {
528 if (isset($aId[$i])) {
529
530 $bHighLight = false;
02e830bd 531 $value = $title = $link = $target = $onclick = $link_extra = '';
91c27aee 532 $aQuery = ($aInitQuery !== false) ? $aInitQuery : false;
533 $aMsg = $aHeaders[$aId[$i]];
534 if (isset($aSearch) && count($aSearch) > 1 && $aQuery) {
535 $aQuery[] = "where=". $aSearch[0];
536 $aQuery[] = "what=" . $aSearch[1];
8008456a 537 }
91c27aee 538 $iUid = (isset($aMsg['UID'])) ? $aMsg['UID'] : $aId[$i];
539 if ($aQuery) {
540 $aQuery[] = "passed_id=$aId[$i]";
541 $aQuery[] = "startMessage=$iPageOffset";
8008456a 542 }
91c27aee 543
544 foreach ($aCol as $k => $v) {
02e830bd 545 $title = $link = $target = $onclick = $link_extra = '';
91c27aee 546 $aColumns[$k] = array();
547 $value = (isset($aMsg[$v])) ? $aMsg[$v] : '';
548 $sUnknown = _("Unknown recipient");
549 switch ($k) {
550 case SQM_COL_FROM:
551 $sUnknown = _("Unknown sender");
552 case SQM_COL_TO:
553 case SQM_COL_CC:
554 case SQM_COL_BCC:
555 $sTmp = false;
556 if ($value) {
557 if ($highlight_list && !$bHighLight) {
558 $bHighLight = highlightMessage($aCol[$k], $value, $highlight_list,$aFormattedMessages[$iUid]);
559 }
582bbe27 560 $aAddressList = parseRFC822Address($value);
561 $sTmp = getAddressString($aAddressList,array('best' => true));
562 $title = $title_maybe = '';
563 foreach ($aAddressList as $aAddr) {
564 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL])) ? $aAddr[SQM_ADDR_PERSONAL] : '';
565 $sMailbox = (isset($aAddr[SQM_ADDR_MAILBOX])) ? $aAddr[SQM_ADDR_MAILBOX] : '';
566 $sHost = (isset($aAddr[SQM_ADDR_HOST])) ? $aAddr[SQM_ADDR_HOST] : '';
567 if ($sPersonal) {
3047e291 568 $title .= sm_encode_html_special_chars($sMailbox.'@'.$sHost).', ';
582bbe27 569 } else {
570 // if $value gets truncated we need to add the addresses with no
571 // personal name as well
3047e291 572 $title_maybe .= sm_encode_html_special_chars($sMailbox.'@'.$sHost).', ';
582bbe27 573 }
574 }
575 if ($title) {
576 $title = substr($title,0,-2); // strip ', ';
577 }
86ef259b 578 $sTmp = decodeHeader($sTmp);
91c27aee 579 if (isset($aColumnDesc[$k]['truncate']) && $aColumnDesc[$k]['truncate']) {
c19e5483 580 $sTrunc = sm_truncate_string($sTmp, $aColumnDesc[$k]['truncate'], '...', TRUE);
582bbe27 581 if ($sTrunc != $sTmp) {
582 if (!$title) {
2b883a9a 583 $title = $sTmp;
582bbe27 584 } else if ($title_maybe) {
585 $title = $title .', '.$title_maybe;
586 $title = substr($title,0,-2); // strip ', ';
587 }
588 }
91c27aee 589 $sTmp = $sTrunc;
590 }
591 }
c04f123a 592 $value = ($sTmp) ? (substr($sTmp, 0, 6) == '&quot;' && substr($sTmp, -6) == '&quot;' ? substr(substr($sTmp, 0, -6), 6) : $sTmp) : $sUnknown;
91c27aee 593 break;
594 case SQM_COL_SUBJ:
d0b119a5 595 // subject is mime encoded, decode it.
129c22ed 596 // value is sanitized in decoding function.
86ef259b 597 // TODO, verify if it should be done before or after the highlighting
129c22ed 598 $value=decodeHeader($value);
91c27aee 599 if ($highlight_list && !$bHighLight) {
600 $bHighLight = highlightMessage('SUBJECT', $value, $highlight_list, $aFormattedMessages[$iUid]);
601 }
602 $iIndent = (isset($aIndentArray[$aId[$i]])) ? $aIndentArray[$aId[$i]] : 0;
129c22ed 603 // FIXME: don't break 8bit symbols and html entities during truncation
91c27aee 604 if (isset($aColumnDesc[$k]['truncate']) && $aColumnDesc[$k]['truncate']) {
c19e5483 605 $sTmp = sm_truncate_string($value, $aColumnDesc[$k]['truncate']-$iIndent, '...', TRUE);
887f7f28 606 // drop any double spaces since these will be displayed in the title
585eaee4 607 // Nah, it's nice to always have a roll-over
608 //$title = ($sTmp != $value) ? preg_replace('/\s{2,}/', ' ', $value) : '';
609 $title = preg_replace('/\s{2,}/', ' ', $value);
91c27aee 610 $value = $sTmp;
611 }
612 /* generate the link to the message */
613 if ($aQuery) {
614 // TODO, $sTargetModule should be a query parameter so that we can use a single entrypoint
615 $link = $sTargetModule.'.php?' . implode('&amp;',$aQuery);
02e830bd 616
84bb1d31 617 // see top of this function for which attributes are available
202bcbcc 618 // in the global scope for plugin use (like $link, $target,
84bb1d31 619 // $onclick, $link_extra, $title, and so forth)
202bcbcc 620 // plugins are responsible for sharing nicely (such as for
84bb1d31 621 // setting the target, etc)
0e525861 622 $temp = array(&$iPageOffset, &$sSearch, &$aSearch, $aMsg);
623 do_hook('subject_link', $temp);
91c27aee 624 }
91c27aee 625 $value = (trim($value)) ? $value : _("(no subject)");
626 /* add thread indentation */
627 $aColumns[$k]['indent'] = $iIndent;
91c27aee 628 break;
629 case SQM_COL_SIZE:
630 $value = show_readable_size($value);
631 break;
632 case SQM_COL_DATE:
633 case SQM_COL_INT_DATE:
d72549cb 634 $value = getTimeStamp(explode(' ',trim($value)));
635 $title = getDateString($value, TRUE);
636 $value = getDateString($value);
91c27aee 637 break;
638 case SQM_COL_FLAGS:
639 $aFlagColumn = array('seen' => false,
640 'deleted'=>false,
641 'answered'=>false,
1a753239 642 'forwarded'=>false,
91c27aee 643 'flagged' => false,
644 'draft' => false);
c3731db5 645
646 if(!is_array($value)) $value = array();
e961d845 647 foreach ($value as $sFlag => $v) {
91c27aee 648 switch ($sFlag) {
1a753239 649 case '\\seen' : $aFlagColumn['seen'] = true; break;
650 case '\\deleted' : $aFlagColumn['deleted'] = true; break;
651 case '\\answered': $aFlagColumn['answered'] = true; break;
652 case '$forwarded': $aFlagColumn['forwarded'] = true; break;
653 case '\\flagged' : $aFlagColumn['flagged'] = true; break;
654 case '\\draft' : $aFlagColumn['draft'] = true; break;
91c27aee 655 default: break;
656 }
657 }
658 $value = $aFlagColumn;
659 break;
660 case SQM_COL_PRIO:
661 $value = ($value) ? (int) $value : 3;
662 break;
663 case SQM_COL_ATTACHMENT:
664 $value = (is_array($value) && $value[0] == 'multipart' && $value[1] == 'mixed') ? true : false;
665 break;
666 case SQM_COL_CHECK:
02def6a1 667 $value = ($checkall || in_array($iUid, $preselected));
91c27aee 668 break;
669 default : break;
670 }
02e830bd 671 if ($title) { $aColumns[$k]['title'] = $title; }
672 if ($link) { $aColumns[$k]['link'] = $link; }
673 if ($link_extra) { $aColumns[$k]['link_extra'] = $link_extra; }
674 if ($onclick) { $aColumns[$k]['onclick'] = $onclick; }
675 if ($target) { $aColumns[$k]['target'] = $target; }
91c27aee 676 $aColumns[$k]['value'] = $value;
8008456a 677 }
91c27aee 678 /* columns which will not be displayed but should be inspected
679 because the highlight list contains rules with those columns */
83eb12fc 680 foreach ($aExtraHighLightColumns as $v) {
681 if ($highlight_list && !$bHighLight && isset($aMsg[$v])) {
682 $bHighLight = highlightMessage($v, $aMsg[$v], $highlight_list,$aFormattedMessages[$iUid]);
91c27aee 683 }
03975a39 684 }
91c27aee 685 $aFormattedMessages[$iUid]['columns'] = $aColumns;
686
687 } else {
8008456a 688 break;
689 }
bdfb67f8 690 }
91c27aee 691 return $aFormattedMessages;
bdfb67f8 692}
693
e9e5f0fa 694
4955562f 695/**
696 * Sets the row color if the provided column value pair matches a hightlight rule
697 *
698 * @param string $sCol column name
699 * @param string $sVal column value
700 * @param array $highlight_list highlight rules
701 * @param array $aFormat (reference) array where row color info is stored
702 * @return bool match found
703 * @since 1.5.1
704 * @author Marc Groot Koerkamp
705 */
91c27aee 706function highlightMessage($sCol, $sVal, $highlight_list, &$aFormat) {
91c27aee 707 if (!is_array($highlight_list) && count($highlight_list) == 0) {
708 return false;
709 }
710 $hlt_color = false;
711 $sCol = strtoupper($sCol);
83eb12fc 712
91c27aee 713 foreach ($highlight_list as $highlight_list_part) {
714 if (trim($highlight_list_part['value'])) {
715 $high_val = strtolower($highlight_list_part['value']);
716 $match_type = strtoupper($highlight_list_part['match_type']);
717 if($match_type == 'TO_CC') {
718 if ($sCol == 'TO' || $sCol == 'CC') {
719 $match_type = $sCol;
720 } else {
721 continue;
722 }
723 } else {
724 if ($match_type != $sCol) {
725 continue;
726 }
727 }
728 if (strpos(strtolower($sVal),$high_val) !== false) {
729 $hlt_color = $highlight_list_part['color'];
730 break;
731 }
732 }
733 }
734 if ($hlt_color) {
d0b119a5 735 // Bug in highlight color???
7b4164c8 736 if ($hlt_color[0] != '#') {
f3a1e5fa 737 $hlt_color = '#'. $hlt_color;
738 }
91c27aee 739 $aFormat['row']['color'] = $hlt_color;
740 return true;
e35045b7 741 } else {
91c27aee 742 return false;
6c930ade 743 }
91c27aee 744}
6a622b59 745
91c27aee 746function setUserPref($username, $pref, $value) {
747 global $data_dir;
748 setPref($data_dir,$username,$pref,$value);
6a622b59 749}
750
c7df3f1b 751/**
4b4abf93 752 * Execute the sorting for a mailbox
753 *
754 * @param resource $imapConnection Imap connection
755 * @param array $aMailbox (reference) Mailbox retrieved with sqm_api_mailbox_select
756 * @return int $error (reference) Error number
757 * @private
4955562f 758 * @since 1.5.1
4b4abf93 759 * @author Marc Groot Koerkamp
760 */
91c27aee 761function _get_sorted_msgs_list($imapConnection,&$aMailbox) {
762 $iSetIndx = (isset($aMailbox['SETINDEX'])) ? $aMailbox['SETINDEX'] : 0;
49719da8 763 $bDirection = !($aMailbox['SORT'] % 2);
91c27aee 764 $error = 0;
765 if (!$aMailbox['SEARCH'][$iSetIndx]) {
766 $aMailbox['SEARCH'][$iSetIndx] = 'ALL';
767 }
768 if (($aMailbox['SORT'] & SQSORT_THREAD) && sqimap_capability($imapConnection,'THREAD')) {
769 $aRes = get_thread_sort($imapConnection,$aMailbox['SEARCH'][$iSetIndx]);
770 if ($aRes === false) {
771 $aMailbox['SORT'] -= SQSORT_THREAD;
772 $error = 1; // fix me, define an error code;
6a622b59 773 } else {
91c27aee 774 $aMailbox['UIDSET'][$iSetIndx] = $aRes[0];
775 $aMailbox['THREAD_INDENT'][$iSetIndx] = $aRes[1];
a6d36aa5 776 }
91c27aee 777 } else if ($aMailbox['SORT'] === SQSORT_NONE) {
778 $id = sqimap_run_search($imapConnection, 'ALL' , '');
779 if ($id === false) {
780 $error = 1; // fix me, define an error code
a6d36aa5 781 } else {
91c27aee 782 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($id);
783 $aMailbox['TOTAL'][$iSetIndx] = $aMailbox['EXISTS'];
a6d36aa5 784 }
91c27aee 785 } else {
786 if (sqimap_capability($imapConnection,'SORT')) {
787 $sSortField = _getSortField($aMailbox['SORT'],true);
788 $id = sqimap_get_sort_order($imapConnection, $sSortField, $bDirection, $aMailbox['SEARCH'][$iSetIndx]);
789 if ($id === false) {
790 $error = 1; // fix me, define an error code
791 } else {
792 $aMailbox['UIDSET'][$iSetIndx] = $id;
793 }
6a622b59 794 } else {
91c27aee 795 $id = NULL;
796 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') {
797 $id = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
798 }
799 $sSortField = _getSortField($aMailbox['SORT'],false);
800 $aMailbox['UIDSET'][$iSetIndx] = get_squirrel_sort($imapConnection, $sSortField, $bDirection, $id);
6a622b59 801 }
e35045b7 802 }
91c27aee 803 return $error;
bdfb67f8 804}
1a0e0983 805
c7df3f1b 806/**
4b4abf93 807 * Does the $srt $_GET var to field mapping
808 *
809 * @param int $srt Field to sort on
810 * @param bool $bServerSort Server sorting is true
811 * @return string $sSortField Field to sort on
4955562f 812 * @since 1.5.1
4b4abf93 813 * @private
814 */
91c27aee 815function _getSortField($sort,$bServerSort) {
816 switch($sort) {
817 case SQSORT_NONE:
818 $sSortField = 'UID';
819 break;
820 case SQSORT_DATE_ASC:
821 case SQSORT_DATE_DESC:
822 $sSortField = 'DATE';
823 break;
824 case SQSORT_FROM_ASC:
825 case SQSORT_FROM_DESC:
f7345823 826// TODO: If capabilities include SORT=DISPLAY then this can be DISPLAYFROM... should this be a user or admin option? Maybe it could cycle/switch between FROM and DISPLAYFROM?
91c27aee 827 $sSortField = 'FROM';
828 break;
829 case SQSORT_SUBJ_ASC:
830 case SQSORT_SUBJ_DESC:
831 $sSortField = 'SUBJECT';
832 break;
833 case SQSORT_SIZE_ASC:
834 case SQSORT_SIZE_DESC:
835 $sSortField = ($bServerSort) ? 'SIZE' : 'RFC822.SIZE';
836 break;
837 case SQSORT_TO_ASC:
838 case SQSORT_TO_DESC:
f7345823 839// TODO: If capabilities include SORT=DISPLAY then this can be DISPLAYTO... should this be a user or admin option? Maybe it could cycle/switch between TO and DISPLAYTO?
91c27aee 840 $sSortField = 'TO';
841 break;
842 case SQSORT_CC_ASC:
843 case SQSORT_CC_DESC:
844 $sSortField = 'CC';
845 break;
846 case SQSORT_INT_DATE_ASC:
847 case SQSORT_INT_DATE_DESC:
848 $sSortField = ($bServerSort) ? 'ARRIVAL' : 'INTERNALDATE';
849 break;
850 case SQSORT_THREAD:
851 break;
852 default: $sSortField = 'UID';
853 break;
854
6a622b59 855 }
91c27aee 856 return $sSortField;
bdfb67f8 857}
858
4955562f 859/**
860 * This function is a utility function for setting which headers should be
861 * fetched. It takes into account the highlight list which requires extra
862 * headers to be fetch in order to make those rules work. It's called before
863 * the headers are fetched which happens in showMessagesForMailbox and when
864 * the next and prev links in read_body.php are used.
865 *
866 * @param array $aMailbox associative array with mailbox related vars
867 * @param array $aProps
868 * @return void
869 * @since 1.5.1
870 */
871
c3731db5 872function calcFetchColumns(&$aMailbox, &$aProps) {
873
874 $highlight_list = (isset($aProps['config']['highlight_list'])) ? $aProps['config']['highlight_list'] : false;
875 $aColumnsDesc = (isset($aProps['columns'])) ? $aProps['columns'] : false;
876
877 $aFetchColumns = $aColumnsDesc;
878 if (isset($aFetchColumns[SQM_COL_CHECK])) {
879 unset($aFetchColumns[SQM_COL_CHECK]);
880 }
881
882 /*
883 * Before we fetch the message headers, check if we need to fetch extra columns
884 * to make the message highlighting work
885 */
886 if (is_array($highlight_list) && count($highlight_list)) {
887 $aHighlightColumns = array();
888 foreach ($highlight_list as $highlight_list_part) {
889 if (trim($highlight_list_part['value'])) {
890 $match_type = strtoupper($highlight_list_part['match_type']);
891 switch ($match_type) {
892 case 'TO_CC':
893 $aHighlightColumns[SQM_COL_TO] = true;
894 $aHighlightColumns[SQM_COL_CC] = true;
895 break;
896 case 'TO': $aHighlightColumns[SQM_COL_TO] = true; break;
897 case 'CC': $aHighlightColumns[SQM_COL_CC] = true; break;
898 case 'FROM': $aHighlightColumns[SQM_COL_FROM] = true; break;
899 case 'SUBJECT':$aHighlightColumns[SQM_COL_SUBJ] = true; break;
900 }
901 }
902 }
903 $aExtraColumns = array();
904 foreach ($aHighlightColumns as $k => $v) {
905 if (!isset($aFetchColumns[$k])) {
906 $aExtraColumns[] = $k;
907 $aFetchColumns[$k] = true;
908 }
909 }
910 if (count($aExtraColumns)) {
911 $aProps['extra_columns'] = $aExtraColumns;
912 }
913 }
914 $aMailbox['FETCHHEADERS'] = array_keys($aFetchColumns);
c3731db5 915}
6a622b59 916
6a622b59 917
91c27aee 918/**
4b4abf93 919 * This function loops through a group of messages in the mailbox
920 * and shows them to the user.
921 *
922 * @param resource $imapConnection
923 * @param array $aMailbox associative array with mailbox related vars
924 * @param array $aProps
925 * @param int $iError error code, 0 is no error
926 */
91c27aee 927function showMessagesForMailbox($imapConnection, &$aMailbox,$aProps, &$iError) {
928 global $PHP_SELF;
24bb7e49 929 global $boxes, $show_copy_buttons;
91c27aee 930
931 $highlight_list = (isset($aProps['config']['highlight_list'])) ? $aProps['config']['highlight_list'] : false;
932 $fancy_index_highlite = (isset($aProps['config']['fancy_index_highlite'])) ? $aProps['config']['fancy_index_highlite'] : true;
933 $aColumnsDesc = (isset($aProps['columns'])) ? $aProps['columns'] : false;
934 $iAccount = (isset($aProps['account'])) ? (int) $aProps['account'] : 0;
935 $sMailbox = (isset($aProps['mailbox'])) ? $aProps['mailbox'] : false;
936 $sTargetModule = (isset($aProps['module'])) ? $aProps['module'] : 'read_body';
937 $show_flag_buttons = (isset($aProps['config']['show_flag_buttons'])) ? $aProps['config']['show_flag_buttons'] : true;
24bb7e49 938
939 /* allows to control copy button in function call. If array key is not set, code follows user preferences */
940 if (isset($aProps['config']['show_copy_buttons']))
941 $show_copy_buttons = $aProps['config']['show_copy_buttons'];
942
91c27aee 943 $lastTargetMailbox = (isset($aProps['config']['lastTargetMailbox'])) ? $aProps['config']['lastTargetMailbox'] : '';
944 $aOrder = array_keys($aProps['columns']);
945 $trash_folder = (isset($aProps['config']['trash_folder']) && $aProps['config']['trash_folder'])
946 ? $aProps['config']['trash_folder'] : false;
947 $sent_folder = (isset($aProps['config']['sent_folder']) && $aProps['config']['sent_folder'])
948 ? $aProps['config']['sent_folder'] : false;
949 $draft_folder = (isset($aProps['config']['draft_folder']) && $aProps['config']['draft_folder'])
950 ? $aProps['config']['draft_folder'] : false;
951 $page_selector = (isset($aProps['config']['page_selector'])) ? $aProps['config']['page_selector'] : false;
952 $page_selector_max = (isset($aProps['config']['page_selector_max'])) ? $aProps['config']['page_selector_max'] : 10;
953 $color = $aProps['config']['color'];
6a622b59 954
6a622b59 955
91c27aee 956 /*
957 * Form ID
958 */
959 static $iFormId;
324ac3c5 960
91c27aee 961 if (!isset($iFormId)) {
962 $iFormId=1;
963 } else {
964 ++$iFormId;
965 }
d0b119a5 966 // store the columns to fetch so we can pick them up in read_body
91c27aee 967 // where we validate the cache.
c3731db5 968 calcFetchColumns($aMailbox ,$aProps);
e35045b7 969
d0b119a5 970 $iError = fetchMessageHeaders($imapConnection, $aMailbox);
91c27aee 971 if ($iError) {
972 return array();
973 } else {
974 $aMessages = prepareMessageList($aMailbox, $aProps);
975 }
6a622b59 976
91c27aee 977 $iSetIndx = $aMailbox['SETINDEX'];
978 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ? $aMailbox['EXISTS'] : $aMailbox['LIMIT'];
979 $iEnd = ($aMailbox['PAGEOFFSET'] + ($iLimit - 1) < $aMailbox['EXISTS']) ?
980 $aMailbox['PAGEOFFSET'] + $iLimit - 1 : $aMailbox['EXISTS'];
6a622b59 981
91c27aee 982 $iNumberOfMessages = $aMailbox['TOTAL'][$iSetIndx];
aa2e9274 983 $iEnd = min ( $iEnd, $iNumberOfMessages );
6a622b59 984
91c27aee 985 $php_self = $PHP_SELF;
6a622b59 986
91c27aee 987 $urlMailbox = urlencode($aMailbox['NAME']);
6a622b59 988
91c27aee 989 if (preg_match('/^(.+)\?.+$/',$php_self,$regs)) {
990 $source_url = $regs[1];
991 } else {
992 $source_url = $php_self;
993 }
6a622b59 994
f830c8ed 995 $baseurl = $source_url.'?mailbox=' . urlencode($aMailbox['NAME']) .'&amp;account='.$aMailbox['ACCOUNT'] . (strpos($source_url, 'src/search.php') ? '&amp;smtoken=' . sm_generate_security_token() : '');
91c27aee 996 $where = urlencode($aMailbox['SEARCH'][$iSetIndx][0]);
997 $what = urlencode($aMailbox['SEARCH'][$iSetIndx][1]);
998 $baseurl .= '&amp;where=' . $where . '&amp;what=' . $what;
999
1000 /* build thread sorting links */
1001 $newsort = $aMailbox['SORT'];
1002 if (sqimap_capability($imapConnection,'THREAD')) {
1003 if ($aMailbox['SORT'] & SQSORT_THREAD) {
1004 $newsort -= SQSORT_THREAD;
1005 $thread_name = _("Unthread View");
1006 } else {
1007 $thread_name = _("Thread View");
1008 $newsort = $aMailbox['SORT'] + SQSORT_THREAD;
6a622b59 1009 }
cd693cf4 1010 $thread_link_uri = $baseurl . '&amp;srt=' . $newsort
1011 . '&amp;startMessage=1';
324ac3c5 1012 } else {
cd693cf4 1013 $thread_link_uri ='';
1014 $thread_name = '';
6a622b59 1015 }
91c27aee 1016 $sort = $aMailbox['SORT'];
6a622b59 1017
91c27aee 1018 /* FIX ME ADD CHECKBOX CONTROL. No checkbox => no buttons */
1019
1020
1021
1022 /* future admin control over displayable buttons */
91c27aee 1023 $aAdminControl = array(
91c27aee 1024 'markFlagged' => 1,
47485591 1025 'markUnflagged' => 1,
91c27aee 1026 'markRead' => 1,
1027 'markUnread' => 1,
a5d40e74 1028 'forward' => 1,
91c27aee 1029 'delete' => 1,
1030 'undeleteButton'=> 1,
1031 'bypass_trash' => 1,
1032 'expungeButton' => 1,
24bb7e49 1033 'moveButton' => 1,
1034 'copyButton' => 1
91c27aee 1035 );
24bb7e49 1036
91c27aee 1037 /* user prefs control */
1038 $aUserControl = array (
a5d40e74 1039
91c27aee 1040 'markFlagged' => $show_flag_buttons,
47485591 1041 'markUnflagged' => $show_flag_buttons,
91c27aee 1042 'markRead' => 1,
1043 'markUnread' => 1,
a5d40e74 1044 'forward' => 1,
91c27aee 1045 'delete' => 1,
1046 'undeleteButton'=> 1,
1047 'bypass_trash' => 1,
1048 'expungeButton' => 1,
24bb7e49 1049 'moveButton' => 1,
1050 'copyButton' => $show_copy_buttons
a5d40e74 1051
91c27aee 1052 );
1053
1054 $showDelete = ($aMailbox['RIGHTS'] != 'READ-ONLY' &&
1055 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ? true : false;
a5d40e74 1056 $showByPassTrash = (($aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
91c27aee 1057 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) &&
a5d40e74 1058 $trash_folder) ? true : false; //
1059
91c27aee 1060 $showUndelete = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
b86c4939 1061 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true) /* trash folder unrelated methinks: && !$trash_folder*/) ? true : false;
91c27aee 1062 $showMove = ($aMailbox['RIGHTS'] != 'READ-ONLY') ? true : false;
1063 $showExpunge = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
1064 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ? true : false;
24bb7e49 1065
1066 /* Button options that depend on IMAP server and selected folder */
91c27aee 1067 $aImapControl = array (
1068 'markUnflagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
1069 'markFlagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
1070 'markRead' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
1071 'markUnread' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
a5d40e74 1072 'forward' => 1,
91c27aee 1073 'delete' => $showDelete,
1074 'undeleteButton'=> $showUndelete,
1075 'bypass_trash' => $showByPassTrash,
1076 'expungeButton' => $showExpunge,
24bb7e49 1077 'moveButton' => $showMove,
1078 'copyButton' => 1
91c27aee 1079 );
24bb7e49 1080 /* Button strings */
91c27aee 1081 $aButtonStrings = array(
47485591 1082 'markFlagged' => _("Flag"),
1083 'markUnflagged' => _("Unflag"),
1084 'markRead' => _("Read"),
1085 'markUnread' => _("Unread"),
1086 'forward' => _("Forward"),
1087 'delete' => _("Delete"),
1088 'undeleteButton' => _("Undelete"),
1089 'bypass_trash' => _("Bypass Trash"),
1090 'expungeButton' => _("Expunge"),
1091 'moveButton' => _("Move"),
1092 'copyButton' => _("Copy")
1093 );
1094 /* Button access keys */
1095 global $accesskey_mailbox_flag, $accesskey_mailbox_unflag,
1096 $accesskey_mailbox_read, $accesskey_mailbox_unread,
1097 $accesskey_mailbox_forward, $accesskey_mailbox_delete,
1098 $accesskey_mailbox_undelete, $accesskey_mailbox_bypass_trash,
1099 $accesskey_mailbox_expunge, $accesskey_mailbox_move,
1100 $accesskey_mailbox_copy, $accesskey_mailbox_move_to;
1101 $aButtonAccessKeys = array(
1102 'markFlagged' => $accesskey_mailbox_flag,
1103 'markUnflagged' => $accesskey_mailbox_unflag,
1104 'markRead' => $accesskey_mailbox_read,
1105 'markUnread' => $accesskey_mailbox_unread,
1106 'forward' => $accesskey_mailbox_forward,
1107 'delete' => $accesskey_mailbox_delete,
1108 'undeleteButton' => $accesskey_mailbox_undelete,
1109 'bypass_trash' => $accesskey_mailbox_bypass_trash,
1110 'expungeButton' => $accesskey_mailbox_expunge,
1111 'moveButton' => $accesskey_mailbox_move,
1112 'copyButton' => $accesskey_mailbox_copy,
91c27aee 1113 );
a5d40e74 1114
1115
6a622b59 1116 /**
91c27aee 1117 * Register buttons in order to an array
1118 * The key is the "name", the first element of the value array is the "value", second argument is the type.
62f7daa5 1119 */
91c27aee 1120 $aFormElements = array();
1121 foreach($aAdminControl as $k => $v) {
1122 if ($v & $aUserControl[$k] & $aImapControl[$k]) {
1123 switch ($k) {
91c27aee 1124 case 'markFlagged':
47485591 1125 case 'markUnflagged':
91c27aee 1126 case 'markRead':
1127 case 'markUnread':
1128 case 'delete':
1129 case 'undeleteButton':
1130 case 'expungeButton':
1131 case 'forward':
4127171c 1132 $aFormElements[$k]
47485591 1133 = array('value' => $aButtonStrings[$k], 'type' => 'submit', 'accesskey' => (isset($aButtonAccessKeys[$k]) ? $aButtonAccessKeys[$k] : 'NONE'));
91c27aee 1134 break;
1135 case 'bypass_trash':
4127171c 1136 $aFormElements[$k]
47485591 1137 = array('value' => $aButtonStrings[$k], 'type' => 'checkbox', 'accesskey' => (isset($aButtonAccessKeys[$k]) ? $aButtonAccessKeys[$k] : 'NONE'));
91c27aee 1138 break;
1139 case 'moveButton':
24bb7e49 1140 case 'copyButton':
4127171c 1141 $aFormElements['targetMailbox']
1142 = array('options_list' => sqimap_mailbox_option_list($imapConnection, array(strtolower($lastTargetMailbox)), 0, $boxes),
47485591 1143 'type' => 'select',
1144 'accesskey' => $accesskey_mailbox_move_to);
4127171c 1145 $aFormElements['mailbox']
1146 = array('value' => $aMailbox['NAME'], 'type' => 'hidden');
1147 $aFormElements['startMessage']
1148 = array('value' => $aMailbox['PAGEOFFSET'], 'type' => 'hidden');
1149 $aFormElements[$k]
47485591 1150 = array('value' => $aButtonStrings[$k], 'type' => 'submit', 'accesskey' => (isset($aButtonAccessKeys[$k]) ? $aButtonAccessKeys[$k] : 'NONE'));
91c27aee 1151 break;
0bb37159 1152 }
1153 }
4127171c 1154 $aFormElements['account'] = array('value' => $iAccount,'type' => 'hidden');
91c27aee 1155 }
4127171c 1156 do_hook('message_list_controls', $aFormElements);
0bb37159 1157
91c27aee 1158 /*
4b4abf93 1159 * This is the beginning of the message list table.
1160 * It wraps around all messages
1161 */
91c27aee 1162 $safe_name = preg_replace("/[^0-9A-Za-z_]/", '_', $aMailbox['NAME']);
1163 $form_name = "FormMsgs" . $safe_name;
0bb37159 1164
91c27aee 1165 //if (!sqgetGlobalVar('align',$align,SQ_SESSION)) {
1166 $align = array('left' => 'left', 'right' => 'right');
1167 //}
1168 //sm_print_r($align);
1169
1170 /* finally set the template vars */
1171
4127171c 1172// FIXME, before we support multiple templates we must review the names of the vars
1173// BUMP!
91c27aee 1174
1175
91c27aee 1176 $aTemplate['color'] = $color;
1177 $aTemplate['form_name'] = "FormMsgs" . $safe_name;
1178 $aTemplate['form_id'] = 'mbx_'.$iFormId;
1179 $aTemplate['page_selector'] = $page_selector;
1180 $aTemplate['page_selector_max'] = $page_selector_max;
1181 $aTemplate['messagesPerPage'] = $aMailbox['LIMIT'];
1182 $aTemplate['showall'] = $aMailbox['SHOWALL'][$iSetIndx];
1183 $aTemplate['end_msg'] = $iEnd;
1184 $aTemplate['align'] = $align;
1185 $aTemplate['iNumberOfMessages'] = $iNumberOfMessages;
1186 $aTemplate['aOrder'] = $aOrder;
1187 $aTemplate['aFormElements'] = $aFormElements;
1188 $aTemplate['sort'] = $sort;
1189 $aTemplate['pageOffset'] = $aMailbox['PAGEOFFSET'];
1190 $aTemplate['baseurl'] = $baseurl;
1191 $aTemplate['aMessages'] =& $aMessages;
1192 $aTemplate['trash_folder'] = $trash_folder;
1193 $aTemplate['sent_folder'] = $sent_folder;
1194 $aTemplate['draft_folder'] = $draft_folder;
cd693cf4 1195 $aTemplate['thread_link_uri'] = $thread_link_uri;
1196 $aTemplate['thread_name'] = $thread_name;
91c27aee 1197 $aTemplate['php_self'] = str_replace('&','&amp;',$php_self);
1198 $aTemplate['mailbox'] = $sMailbox;
83aff890 1199//FIXME: javascript_on is always assigned to the template object in places like init.php; is there some reason to reassign it here? is there some chance that it was changed? if not, please remove this line!
91c27aee 1200 $aTemplate['javascript_on'] = (isset($aProps['config']['javascript_on'])) ? $aProps['config']['javascript_on'] : false;
1201 $aTemplate['enablesort'] = (isset($aProps['config']['enablesort'])) ? $aProps['config']['enablesort'] : false;
1202 $aTemplate['icon_theme'] = (isset($aProps['config']['icon_theme'])) ? $aProps['config']['icon_theme'] : false;
1203 $aTemplate['use_icons'] = (isset($aProps['config']['use_icons'])) ? $aProps['config']['use_icons'] : false;
1204 $aTemplate['alt_index_colors'] = (isset($aProps['config']['alt_index_colors'])) ? $aProps['config']['alt_index_colors'] : false;
1205 $aTemplate['fancy_index_highlite'] = $fancy_index_highlite;
1206
49719da8 1207
4127171c 1208 /**
1209 * Set up sort possibilities; one could argue that this is best
1210 * placed in the template, but most template authors won't understand
1211 * or need to understand it, so some advanced templates can override
1212 * it if they do something different.
1213 */
1214 if (!($aTemplate['sort'] & SQSORT_THREAD) && $aTemplate['enablesort']) {
1215 $aTemplate['aSortSupported']
1216 = array(SQM_COL_SUBJ => array(SQSORT_SUBJ_ASC , SQSORT_SUBJ_DESC),
1217 SQM_COL_DATE => array(SQSORT_DATE_DESC , SQSORT_DATE_ASC),
1218 SQM_COL_INT_DATE => array(SQSORT_INT_DATE_DESC, SQSORT_INT_DATE_ASC),
1219 SQM_COL_FROM => array(SQSORT_FROM_ASC , SQSORT_FROM_DESC),
1220 SQM_COL_TO => array(SQSORT_TO_ASC , SQSORT_TO_DESC),
1221 SQM_COL_CC => array(SQSORT_CC_ASC , SQSORT_CC_DESC),
1222 SQM_COL_SIZE => array(SQSORT_SIZE_ASC , SQSORT_SIZE_DESC));
1223 } else {
1224 $aTemplate['aSortSupported'] = array();
1225 }
1226
1227
1228 /**
1229 * Figure out which columns should serve as labels for checkbox:
1230 * we try to grab the two columns before and after the checkbox,
1231 * except the subject column, since it is the link that opens
1232 * the message view
1233 *
1234 * if $javascript_on is set, then the highlighting code takes
1235 * care of this; just skip it
1236 *
1237 * This code also might be more appropriate in a template file, but
1238 * we are moving this complex stuff out of the way of template
1239 * authors; advanced template sets are always free to override
1240 * the resultant values.
1241 *
1242 */
1243 $show_label_columns = array();
1244 $index_order_part = array();
1245 if (!($aTemplate['javascript_on'] && $aTemplate['fancy_index_highlite'])) {
1246 $get_next_two = 0;
1247 $last_order_part = 0;
1248 $last_last_order_part = 0;
1249 foreach ($aTemplate['aOrder'] as $index_order_part) {
1250 if ($index_order_part == SQM_COL_CHECK) {
1251 $get_next_two = 1;
1252 if ($last_last_order_part != SQM_COL_SUBJ)
1253 $show_label_columns[] = $last_last_order_part;
1254 if ($last_order_part != SQM_COL_SUBJ)
1255 $show_label_columns[] = $last_order_part;
1256
1257 } else if ($get_next_two > 0 && $get_next_two < 3 && $index_order_part != SQM_COL_SUBJ) {
1258 $show_label_columns[] = $index_order_part;
1259 $get_next_two++;
1260 }
1261 $last_last_order_part = $last_order_part;
1262 $last_order_part = $index_order_part;
1263 }
1264 }
1265 $aTemplate['show_label_columns'] = $show_label_columns;
1266
1267
91c27aee 1268 return $aTemplate;
4127171c 1269
bdfb67f8 1270}
1271
91c27aee 1272
324ac3c5 1273/**
1274 * Process messages list form and handle the cache gracefully. If $sButton and
1275 * $aUid are provided as argument then you can fake a message list submit and
1276 * use it i.e. in read_body.php for del move next and update the cache
1277 *
1278 * @param resource $imapConnection imap connection
ee19932b 1279 * @param array $aMailbox (reference) cached mailbox
1280 * @param string $sButton fake a submit button
1281 * @param array $aUid fake the $msg array
1282 * @param string $targetMailbox fake the target mailbox for move operations
1283 * @param boolean $bypass_trash fake the bypass trash checkbox for delete operations
324ac3c5 1284 * @return string $sError error string in case of an error
4955562f 1285 * @since 1.5.1
324ac3c5 1286 * @author Marc Groot Koerkamp
1287 */
ee19932b 1288function handleMessageListForm($imapConnection, &$aMailbox, $sButton='',
1289 $aUid = array(), $targetMailbox='', $bypass_trash=NULL) {
324ac3c5 1290 /* incoming formdata */
c9b94b04 1291 $sButton = (sqgetGlobalVar('moveButton', $sTmp, SQ_FORM)) ? 'move' : $sButton;
1292 $sButton = (sqgetGlobalVar('copyButton', $sTmp, SQ_FORM)) ? 'copy' : $sButton;
1293 $sButton = (sqgetGlobalVar('expungeButton', $sTmp, SQ_FORM)) ? 'expunge' : $sButton;
1294 $sButton = (sqgetGlobalVar('forward', $sTmp, SQ_FORM)) ? 'forward' : $sButton;
1295 $sButton = (sqgetGlobalVar('delete', $sTmp, SQ_FORM)) ? 'setDeleted' : $sButton;
1296 $sButton = (sqgetGlobalVar('undeleteButton', $sTmp, SQ_FORM)) ? 'unsetDeleted' : $sButton;
1297 $sButton = (sqgetGlobalVar('markRead', $sTmp, SQ_FORM)) ? 'setSeen' : $sButton;
1298 $sButton = (sqgetGlobalVar('markUnread', $sTmp, SQ_FORM)) ? 'unsetSeen' : $sButton;
1299 $sButton = (sqgetGlobalVar('markFlagged', $sTmp, SQ_FORM)) ? 'setFlagged' : $sButton;
1300 $sButton = (sqgetGlobalVar('markUnflagged', $sTmp, SQ_FORM)) ? 'unsetFlagged' : $sButton;
ee19932b 1301 if (empty($targetMailbox)) sqgetGlobalVar('targetMailbox', $targetMailbox, SQ_FORM);
1302 if (is_null($bypass_trash)) sqgetGlobalVar('bypass_trash', $bypass_trash, SQ_FORM);
c9b94b04 1303 sqgetGlobalVar('msg', $msg, SQ_FORM);
1304 if (sqgetGlobalVar('account', $iAccount, SQ_FORM) === false) {
91c27aee 1305 $iAccount = 0;
1306 }
324ac3c5 1307 $sError = '';
1308 $mailbox = $aMailbox['NAME'];
1309
1310 /* retrieve the check boxes */
1311 $aUid = (isset($msg) && is_array($msg)) ? array_values($msg) : $aUid;
324ac3c5 1312 if (count($aUid) && $sButton != 'expunge') {
51bbe8fa 1313
199a9ab8 1314 // don't do anything to any messages until we have done security check
1315 // FIXME: not sure this code really belongs here, but there's nowhere else to put it with this architecture
7e6bff9b 1316 sqgetGlobalVar('smtoken', $submitted_token, SQ_FORM, '');
2cefa62a 1317 sm_validate_security_token($submitted_token, -1, TRUE);
199a9ab8 1318
51bbe8fa 1319 // make sure message UIDs are sanitized (BIGINT)
1320 foreach ($aUid as $i => $uid)
1321 $aUid[$i] = (preg_match('/^[0-9]+$/', $uid) ? $uid : '0');
1322
324ac3c5 1323 $aUpdatedMsgs = false;
1324 $bExpunge = false;
1325 switch ($sButton) {
1326 case 'setDeleted':
1327 // check if id exists in case we come from read_body
1328 if (count($aUid) == 1 && is_array($aMailbox['UIDSET'][$aMailbox['SETINDEX']]) &&
1329 !in_array($aUid[0],$aMailbox['UIDSET'][$aMailbox['SETINDEX']])) {
1330 break;
1331 }
7c788b1c 1332 $aUpdatedMsgs = sqimap_msgs_list_delete($imapConnection, $mailbox, $aUid,$bypass_trash);
1333 $bExpunge = true;
91c27aee 1334 //}
324ac3c5 1335 break;
1336 case 'unsetDeleted':
1337 case 'setSeen':
1338 case 'unsetSeen':
1339 case 'setFlagged':
1340 case 'unsetFlagged':
1341 // get flag
1342 $sFlag = (substr($sButton,0,3) == 'set') ? '\\'.substr($sButton,3) : '\\'.substr($sButton,5);
1343 $bSet = (substr($sButton,0,3) == 'set') ? true : false;
1344 $aUpdatedMsgs = sqimap_toggle_flag($imapConnection, $aUid, $sFlag, $bSet, true);
1345 break;
1346 case 'move':
821651ff 1347 $aUpdatedMsgs = sqimap_msgs_list_move($imapConnection,$aUid,$targetMailbox,true,$mailbox);
324ac3c5 1348 sqsession_register($targetMailbox,'lastTargetMailbox');
1349 $bExpunge = true;
1350 break;
24bb7e49 1351 case 'copy':
b400dda3 1352 // sqimap_msgs_list_copy returns true or false.
1353 // If error happens - fourth argument handles it inside function.
1354 sqimap_msgs_list_copy($imapConnection,$aUid,$targetMailbox,true);
24bb7e49 1355 sqsession_register($targetMailbox,'lastTargetMailbox');
1356 break;
91c27aee 1357 case 'forward':
324ac3c5 1358 $aMsgHeaders = array();
1359 foreach ($aUid as $iUid) {
1360 $aMsgHeaders[$iUid] = $aMailbox['MSG_HEADERS'][$iUid];
1361 }
1362 if (count($aMsgHeaders)) {
1363 $composesession = attachSelectedMessages($imapConnection,$aMsgHeaders);
1364 // dirty hack, add info to $aMailbox
e506b6e5 1365 $aMailbox['FORWARD_SESSION']['SESSION_NUMBER'] = $composesession;
1366 $aMailbox['FORWARD_SESSION']['UIDS'] = $aUid;
324ac3c5 1367 }
1368 break;
7c788b1c 1369 default:
91c27aee 1370 // Hook for plugin buttons
c1c0ce3e 1371 $temp = array(&$sButton, &$aMailbox, $iAccount, $aMailbox['NAME'], &$aUid);
b77cbccc 1372 do_hook('mailbox_display_button_action', $temp);
91c27aee 1373 break;
324ac3c5 1374 }
1375 /**
bdfa0f9a 1376 * $aUpdatedMsgs is an array containing the result of the untagged
324ac3c5 1377 * fetch responses send by the imap server due to a flag change. That
bdfa0f9a 1378 * response is parsed in an array with msg arrays by the parseFetch function
324ac3c5 1379 */
1380 if ($aUpdatedMsgs) {
1381 // Update the message headers cache
1382 $aDeleted = array();
1383 foreach ($aUpdatedMsgs as $iUid => $aMsg) {
1384 if (isset($aMsg['FLAGS'])) {
fd28fa79 1385 /**
ddd209f2 1386 * Only update the cached headers if the header is
fd28fa79 1387 * cached.
1388 */
1389 if (isset($aMailbox['MSG_HEADERS'][$iUid])) {
1390 $aMailbox['MSG_HEADERS'][$iUid]['FLAGS'] = $aMsg['FLAGS'];
1391 }
bdfa0f9a 1392 /**
1393 * Also update flags in message object
1394 */
1395//FIXME: WHY are we keeping flags in TWO places?!? This is error-prone and some core code uses the is_xxxx message object values while other code uses the flags array above. That's a mess.
1396 if (isset($aMailbox['MSG_HEADERS'][$iUid]['MESSAGE_OBJECT'])) {
1397 $message = $aMailbox['MSG_HEADERS'][$iUid]['MESSAGE_OBJECT'];
1398 $message->is_seen = false;
1399 $message->is_answered = false;
1a753239 1400 $message->is_forwarded = false;
bdfa0f9a 1401 $message->is_deleted = false;
1402 $message->is_flagged = false;
1403 $message->is_mdnsent = false;
1404 foreach ($aMsg['FLAGS'] as $flag => $value) {
1405 if (strtolower($flag) == '\\seen' && $value)
1406 $message->is_seen = true;
1407 else if (strtolower($flag) == '\\answered' && $value)
1408 $message->is_answered = true;
1a753239 1409 else if (strtolower($flag) == '$forwarded' && $value)
1410 $message->is_forwarded = true;
bdfa0f9a 1411 else if (strtolower($flag) == '\\deleted' && $value)
1412 $message->is_deleted = true;
1413 else if (strtolower($flag) == '\\flagged' && $value)
1414 $message->is_flagged = true;
1415 else if (strtolower($flag) == '$mdnsent' && $value)
1416 $message->is_mdnsent = true;
1417 }
1418 $aMailbox['MSG_HEADERS'][$iUid]['MESSAGE_OBJECT'] = $message;
1419 }
324ac3c5 1420 /**
1421 * Count the messages with the \Delete flag set so we can determine
1422 * if the number of expunged messages equals the number of flagged
1423 * messages for deletion.
1424 */
1425 if (isset($aMsg['FLAGS']['\\deleted']) && $aMsg['FLAGS']['\\deleted']) {
1426 $aDeleted[] = $iUid;
1427 }
1428 }
1429 }
1430 if ($bExpunge && $aMailbox['AUTO_EXPUNGE'] &&
1431 $iExpungedMessages = sqimap_mailbox_expunge($imapConnection, $aMailbox['NAME'], true))
1432 {
1433 if (count($aDeleted) != $iExpungedMessages) {
1434 // there are more messages deleted permanently then we expected
1435 // invalidate the cache
1436 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = false;
1437 $aMailbox['MSG_HEADERS'] = false;
1438 } else {
1439 // remove expunged messages from cache
1440 $aUidSet = $aMailbox['UIDSET'][$aMailbox['SETINDEX']];
1441 if (is_array($aUidSet)) {
1442 // create a UID => array index temp array
1443 $aUidSetDummy = array_flip($aUidSet);
1444 foreach ($aDeleted as $iUid) {
1445 // get the id as well in case of SQM_SORT_NONE
1446 if ($aMailbox['SORT'] == SQSORT_NONE) {
1447 $aMailbox['ID'] = false;
1448 //$iId = $aMailbox['MSG_HEADERS'][$iUid]['ID'];
1449 //unset($aMailbox['ID'][$iId]);
1450 }
1451 // unset the UID and message header
1452 unset($aUidSetDummy[$iUid]);
1453 unset($aMailbox['MSG_HEADERS'][$iUid]);
1454 }
1455 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = array_keys($aUidSetDummy);
324ac3c5 1456 }
1457 }
ddd209f2 1458 // update EXISTS info
1459 if ($iExpungedMessages) {
1460 $aMailbox['EXISTS'] -= (int) $iExpungedMessages;
91c27aee 1461 $aMailbox['TOTAL'][$aMailbox['SETINDEX']] -= (int) $iExpungedMessages;
ddd209f2 1462 }
4c284a74 1463 if (($aMailbox['PAGEOFFSET']-1) >= $aMailbox['EXISTS']) {
324ac3c5 1464 $aMailbox['PAGEOFFSET'] = ($aMailbox['PAGEOFFSET'] > $aMailbox['LIMIT']) ?
1465 $aMailbox['PAGEOFFSET'] - $aMailbox['LIMIT'] : 1;
91c27aee 1466 $aMailbox['OFFSET'] = $aMailbox['PAGEOFFSET'] - 1 ;
324ac3c5 1467 }
1468 }
1469 }
1470 } else {
1471 if ($sButton == 'expunge') {
1472 /**
1473 * on expunge we do not know which messages will be deleted
1474 * so it's useless to try to sync the cache
4b4abf93 1475 *
324ac3c5 1476 * Close the mailbox so we do not need to parse the untagged expunge
1477 * responses which do not contain uid info.
1478 * NB: Closing a mailbox is faster then expunge because the imap
1479 * server does not need to generate the untagged expunge responses
1480 */
1481 sqimap_run_command($imapConnection,'CLOSE',false,$result,$message);
91c27aee 1482 $aMailbox = sqm_api_mailbox_select($imapConnection,$iAccount, $aMailbox['NAME'],array(),array());
324ac3c5 1483 } else {
b262c520 1484 // this is the same hook as above, but here it is called in the
1485 // context of not having had any messages selected and if any
1486 // plugin handles the situation, it should return TRUE so we
1487 // know this was not an erroneous user action
1488 //
1489 global $null;
c1c0ce3e 1490 $temp = array(&$sButton, &$aMailbox, $iAccount, $aMailbox['NAME'], $null);
b77cbccc 1491 if (!boolean_hook_function('mailbox_display_button_action', $temp, 1)
b262c520 1492 && $sButton) {
324ac3c5 1493 $sError = _("No messages were selected.");
1494 }
1495 }
1496 }
1497 return $sError;
1498}
1499
4955562f 1500/**
1501 * Attach messages to a compose session
1502 *
1503 * @param resource $imapConnection imap connection
1504 * @param array $aMsgHeaders
1505 * @return int $composesession unique compose_session_id where the attached messages belong to
1506 * @author Marc Groot Koerkamp
1507 */
324ac3c5 1508function attachSelectedMessages($imapConnection,$aMsgHeaders) {
324ac3c5 1509
91c27aee 1510 sqgetGlobalVar('composesession', $composesession, SQ_SESSION);
1511 sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION);
1512 if (!isset($compose_messages)|| is_null($compose_messages)) {
324ac3c5 1513 $compose_messages = array();
1514 sqsession_register($compose_messages,'compose_messages');
1515 }
1516
1517 if (!$composesession) {
1518 $composesession = 1;
1519 sqsession_register($composesession,'composesession');
1520 } else {
1521 $composesession++;
1522 sqsession_register($composesession,'composesession');
1523 }
1524
324ac3c5 1525 $composeMessage = new Message();
1526 $rfc822_header = new Rfc822Header();
1527 $composeMessage->rfc822_header = $rfc822_header;
1528 $composeMessage->reply_rfc822_header = '';
1529
1530 foreach($aMsgHeaders as $iUid => $aMsgHeader) {
1531 /**
1532 * Retrieve the full message
1533 */
1534 $body_a = sqimap_run_command($imapConnection, "FETCH $iUid RFC822", true, $response, $readmessage, TRUE);
324ac3c5 1535 if ($response == 'OK') {
91c27aee 1536
1537 $subject = (isset($aMsgHeader['subject'])) ? $aMsgHeader['subject'] : $iUid;
324ac3c5 1538
1539 array_shift($body_a);
1540 array_pop($body_a);
1541 $body = implode('', $body_a);
1542 $body .= "\r\n";
1543
1f270d3c 1544 global $username, $attachment_dir;
628bce99 1545 $filename = sq_get_attach_tempfile();
1f270d3c 1546 $fullpath = getHashedDir($username, $attachment_dir) . '/' . $filename;
1547 $fp = fopen($fullpath, 'wb');
324ac3c5 1548 fwrite ($fp, $body);
1549 fclose($fp);
628bce99 1550
54156b1c 1551 $composeMessage->initAttachment('message/rfc822', $subject . '.eml', $filename);
f2ad47f1 1552
1553 // create subject for new message
1554 //
1555 $subject = decodeHeader($subject,false,false,true);
1556 $subject = str_replace('"', "'", $subject);
1557 $subject = trim($subject);
1558 if (substr(strtolower($subject), 0, 4) != 'fwd:') {
1559 $subject = 'Fwd: ' . $subject;
1560 }
1561 $composeMessage->rfc822_header->subject = $subject;
1562
324ac3c5 1563 }
1564 }
1565
1566 $compose_messages[$composesession] = $composeMessage;
1567 sqsession_register($compose_messages,'compose_messages');
1568 return $composesession;
1569}
628bce99 1570