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