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