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