6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This contains functions that display mailbox information, such as the
10 * table row that has sender, date, subject, etc...
13 * @package squirrelmail
16 /** The standard includes.. */
17 require_once(SM_PATH
. 'functions/strings.php');
18 require_once(SM_PATH
. 'functions/html.php');
19 require_once(SM_PATH
. 'functions/imap_mailbox.php');
20 require_once(SM_PATH
. 'functions/imap_messages.php');
21 require_once(SM_PATH
. 'functions/imap_asearch.php');
22 require_once(SM_PATH
. 'functions/mime.php');
23 require_once(SM_PATH
. 'functions/forms.php');
27 * Selects a mailbox for header retrieval.
28 * Cache control for message headers is embedded.
30 * @param resource $imapConnection imap socket handle
31 * @param string $mailbox mailbox to select and retrieve message headers from
32 * @param array $aConfig array with system config settings and incoming vars
33 * @param array $aProps mailbox specific properties
34 * @return array $aMailbox mailbox array with all relevant information
35 * @author Marc Groot Koerkamp
37 function sqm_api_mailbox_select($imapConnection,$account,$mailbox,$aConfig,$aProps) {
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
44 global $mailbox_cache;
46 $aDefaultConfigProps = array(
47 // 'charset' => 'US-ASCII',
48 'user' => false, /* no pref storage if false */
51 'max_cache_size' => SQM_MAX_MBX_IN_CACHE
54 $aConfig = array_merge($aDefaultConfigProps,$aConfig);
56 $iSetIndx = $aConfig['setindex'];
58 $aMbxResponse = sqimap_mailbox_select($imapConnection, $mailbox);
61 if (isset($mailbox_cache[$account.'_'.$mailbox])) {
62 $aCachedMailbox = $mailbox_cache[$account.'_'.$mailbox];
64 $aCachedMailbox = false;
67 if (count($mailbox_cache) > $aConfig['max_cache_size'] -1) {
69 foreach($mailbox_cache as $cachedmailbox => $aVal) {
70 $aTime[$aVal['TIMESTAMP']] = $cachedmailbox;
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);
76 * Remove only the UIDSET and MSG_HEADERS from cache because those can
77 * contain large amounts of data.
79 if (isset($mailbox_cache[$sOldestMbx]['UIDSET'])) {
80 $mailbox_cache[$sOldestMbx]['UIDSET']= false;
82 if (isset($mailbox_cache[$sOldestMbx]['MSG_HEADERS'])) {
83 $mailbox_cache[$sOldestMbx]['MSG_HEADERS'] = false;
90 $aCachedMailbox = false;
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).
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'];
105 $aMailbox['ACCOUNT'] = $account;
106 $aMailbox['UIDSET'][$iSetIndx] = false;
107 $aMailbox['ID'] = false;
108 $aMailbox['SETINDEX'] = $iSetIndx;
110 if ($aCachedMailbox) {
112 * Validate integrity of cached data
114 if ($aCachedMailbox['EXISTS'] == $aMbxResponse['EXISTS'] &&
115 $aMbxResponse['EXISTS'] &&
116 $aCachedMailbox['UIDVALIDITY'] == $aMbxResponse['UIDVALIDITY'] &&
117 $aCachedMailbox['UIDNEXT'] == $aMbxResponse['UIDNEXT'] &&
118 isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
119 (!isset($aConfig['search']) ||
/* always set search from the searchpage */
120 $aCachedMailbox['SEARCH'][$iSetIndx] == $aConfig['search'])) {
121 if (isset($aCachedMailbox['MSG_HEADERS'])) {
122 $aMailbox['MSG_HEADERS'] = $aCachedMailbox['MSG_HEADERS'];
124 $aMailbox['ID'] = $aCachedMailbox['ID'];
125 if (isset($aCachedMailbox['UIDSET'][$iSetIndx]) && $aCachedMailbox['UIDSET'][$iSetIndx]) {
126 if (isset($aProps[MBX_PREF_SORT
]) && $aProps[MBX_PREF_SORT
] != $aCachedMailbox['SORT'] ) {
127 $newsort = $aProps[MBX_PREF_SORT
];
128 $oldsort = $aCachedMailbox['SORT'];
130 * If it concerns a reverse sort we do not need to invalidate
131 * the cached sorted UIDSET, a reverse is sufficient.
133 if ((($newsort %
2) && ($newsort +
1 == $oldsort)) ||
134 (!($newsort %
2) && ($newsort - 1 == $oldsort))) {
135 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($aCachedMailbox['UIDSET'][$iSetIndx]);
137 $server_sort_array = false;
138 $aMailbox['MSG_HEADERS'] = false;
139 $aMailbox['ID'] = false;
141 // store the new sort value in the mailbox pref
142 if ($aConfig['user']) {
143 // FIXME, in ideal situation, we write back the
144 // prefs at the end of the script
145 setUserPref($aConfig['user'],'pref_'.$account.'_'.$mailbox,serialize($aProps));
148 $aMailbox['UIDSET'][$iSetIndx] = $aCachedMailbox['UIDSET'][$iSetIndx];
154 * Restore the offset in the paginator if no new offset is provided.
156 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['offset']) && $aCachedMailbox['OFFSET']) {
157 $aMailbox['OFFSET'] = $aCachedMailbox['OFFSET'];
158 $aMailbox['PAGEOFFSET'] = $aCachedMailbox['PAGEOFFSET'];
160 $aMailbox['OFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ?
$aConfig['offset'] -1 : 0;
161 $aMailbox['PAGEOFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ?
$aConfig['offset'] : 1;
164 * Restore the number of messages in the result set
166 if (isset($aCachedMailbox['TOTAL'][$iSetIndx]) && $aCachedMailbox['TOTAL'][$iSetIndx]) {
167 $aMailbox['TOTAL'][$iSetIndx] = $aCachedMailbox['TOTAL'][$iSetIndx];
171 * Restore the showall value no new showall value is provided.
173 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['showall']) &&
174 isset($aCachedMailbox['SHOWALL'][$iSetIndx]) && $aCachedMailbox['SHOWALL'][$iSetIndx]) {
175 $aMailbox['SHOWALL'][$iSetIndx] = $aCachedMailbox['SHOWALL'][$iSetIndx];
177 $aMailbox['SHOWALL'][$iSetIndx] = (isset($aConfig['showall']) && $aConfig['showall']) ?
1 : 0;
181 * Restore the sort order if no new sort order is provided.
183 if (!isset($aProps[MBX_PREF_SORT
]) && isset($aCachedMailbox['SORT'])) {
184 $aMailbox['SORT'] = $aCachedMailbox['SORT'];
186 $aMailbox['SORT'] = (isset($aProps[MBX_PREF_SORT
])) ?
$aProps[MBX_PREF_SORT
] : 0;
190 * Restore the number of message to show per page when no new limit is provided
192 if (!isset($aProps[MBX_PREF_LIMIT
]) && isset($aCachedMailbox['LIMIT'])) {
193 $aMailbox['LIMIT'] = $aCachedMailbox['LIMIT'];
195 $aMailbox['LIMIT'] = (isset($aProps[MBX_PREF_LIMIT
])) ?
$aProps[MBX_PREF_LIMIT
] : 15;
199 * Restore the ordered columns to show when no new ordered columns are provided
201 if (!isset($aProps[MBX_PREF_COLUMNS
]) && isset($aCachedMailbox['COLUMNS'])) {
202 $aMailbox['COLUMNS'] = $aCachedMailbox['COLUMNS'];
204 $aMailbox['COLUMNS'] = (isset($aProps[MBX_PREF_COLUMNS
])) ?
$aProps[MBX_PREF_COLUMNS
] :
205 array(SQM_COL_FLAGS
,SQM_COL_FROM
, SQM_COL_SUBJ
, SQM_COL_FLAGS
);
209 * Restore the headers we fetch the last time. Saves intitialisation stuff in read_body.
211 $aMailbox['FETCHHEADERS'] = (isset($aCachedMailbox['FETCHHEADERS'])) ?
$aCachedMailbox['FETCHHEADERS'] : null;
213 if (!isset($aProps[MBX_PREF_AUTO_EXPUNGE
]) && isset($aCachedMailbox['AUTO_EXPUNGE'])) {
214 $aMailbox['AUTO_EXPUNGE'] = $aCachedMailbox['AUTO_EXPUNGE'];
216 $aMailbox['AUTO_EXPUNGE'] = (isset($aProps[MBX_PREF_AUTO_EXPUNGE
])) ?
$aProps[MBX_PREF_AUTO_EXPUNGE
] : false;
218 if (!isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx])) {
219 $aMailbox['SEARCH'][$iSetIndx] = $aCachedMailbox['SEARCH'][$iSetIndx];
220 } else if (isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
221 $aConfig['search'] != $aCachedMailbox['SEARCH'][$iSetIndx]) {
222 // reset the pageindex
223 $aMailbox['SEARCH'][$iSetIndx] = $aConfig['search'];
224 $aMailbox['OFFSET'] = 0;
225 $aMailbox['PAGEOFFSET'] = 1;
227 $aMailbox['SEARCH'][$iSetIndx] = (isset($aConfig['search'])) ?
$aConfig['search'] : 'ALL';
229 if (!isset($aConfig['charset']) && isset($aCachedMailbox['CHARSET'][$iSetIndx])) {
230 $aMailbox['CHARSET'][$iSetIndx] = $aCachedMailbox['CHARSET'][$iSetIndx];
232 $aMailbox['CHARSET'][$iSetIndx] = (isset($aConfig['charset'])) ?
$aConfig['charset'] : 'US-ASCII';
235 $aMailbox['NAME'] = $mailbox;
236 $aMailbox['EXISTS'] = $aMbxResponse['EXISTS'];
237 $aMailbox['SEEN'] = (isset($aMbxResponse['SEEN'])) ?
$aMbxResponse['SEEN'] : $aMbxResponse['EXISTS'];
238 $aMailbox['RECENT'] = (isset($aMbxResponse['RECENT'])) ?
$aMbxResponse['RECENT'] : 0;
239 $aMailbox['UIDVALIDITY'] = $aMbxResponse['UIDVALIDITY'];
240 $aMailbox['UIDNEXT'] = $aMbxResponse['UIDNEXT'];
241 $aMailbox['PERMANENTFLAGS'] = $aMbxResponse['PERMANENTFLAGS'];
242 $aMailbox['RIGHTS'] = $aMbxResponse['RIGHTS'];
244 /* decide if we are thread sorting or not */
245 if ($aMailbox['SORT'] & SQSORT_THREAD
) {
246 if (!sqimap_capability($imapConnection,'THREAD')) {
247 $aMailbox['SORT'] ^
= SQSORT_THREAD
;
249 $aMailbox['THREAD_INDENT'] = $aCachedMailbox['THREAD_INDENT'];
252 $aMailbox['THREAD_INDENT'] = false;
255 /* set a timestamp for cachecontrol */
256 $aMailbox['TIMESTAMP'] = time();
261 * Fetch the message headers for a mailbox. Settings are part of the aMailbox
264 * @param resource $imapConnection imap socket handle
265 * @param array $aMailbox (reference) mailbox retrieved from sqm_api_mailbox_select
266 * @return error $error error number
267 * @author Marc Groot Koerkamp
269 function fetchMessageHeaders($imapConnection, &$aMailbox) {
271 /* FIX ME, this function is kind of big, maybe we can split it up in
272 a couple of functions. Make sure the functions are private and starts with _
273 Also make sure that the error codes are propagated */
276 * Retrieve the UIDSET.
277 * Setindex is used to be able to store multiple uid sets. That will make it
278 * possible to display the mailbox multiple times in different sort order
279 * or to store serach results separate from normal mailbox view.
281 $iSetIndx = (isset($aMailbox['SETINDEX'])) ?
$aMailbox['SETINDEX'] : 0;
283 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ?
$aMailbox['EXISTS'] : $aMailbox['LIMIT'];
285 * Adjust the start_msg
287 $start_msg = $aMailbox['PAGEOFFSET'];
288 if($aMailbox['PAGEOFFSET'] > $aMailbox['EXISTS']) {
289 $start_msg -= $aMailbox['LIMIT'];
295 if (is_array($aMailbox['UIDSET'])) {
296 $aUid =& $aMailbox['UIDSET'][$iSetIndx];
300 $aFetchHeaders = $aMailbox['FETCHHEADERS'];
303 $aFetchItems = $aHeaderItems = array();
304 // initialize the fields we want to retrieve:
305 foreach ($aFetchHeaders as $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;
322 * A uidset with sorted uid's is available. We can use the cache
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) {
333 unset($aMailbox['MSG_HEADERS'][$iUid]);
342 $id_slice = array_slice($aUid,$start_msg-1,$iLimit);
343 /* do some funky cache checks */
344 if (isset($aMailbox['MSG_HEADERS'])) {
345 $aUidCached = array_keys($aMailbox['MSG_HEADERS']);
347 $aMailbox['MSG_HEADERS'] = array();
348 $aUidCached = array();
350 $aUidNotCached = array_values(array_diff($id_slice,$aUidCached));
353 * $aUidNotCached contains an array with UID's which need to be fetched to
354 * complete the needed message headers.
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;
364 * Initialize the sorted UID list or initiate a UID list with search
365 * results and fetch the visible message headers
368 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') { // in case of a search request
370 if ($aMailbox['SEARCH'][$iSetIndx] && $aMailbox['SORT'] == 0) {
371 $aUid = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
375 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
376 $aUid = $aMailbox['UIDSET'][$iSetIndx];
380 * Number of messages is the resultset
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);
388 $iError = 1; // FIX ME, define an error code
393 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
394 $aUid = $aMailbox['UIDSET'][$iSetIndx];
398 * Number of messages is the resultset
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);
406 $iError = 1; // FIX ME, define an error code
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';
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
432 * Only retrieve values for displayable columns
434 foreach ($aColumnDesc as $k => $v) {
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;
450 $aExtraHighLightColumns = array();
451 foreach ($aExtraColumns as $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;
461 $aFormattedMessages = array();
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));
482 if ($aMailbox['SORT'] & SQSORT_THREAD
) {
483 $aIndentArray =& $aMailbox['THREAD_INDENT'][$aMailbox['SETINDEX']];
489 * Retrieve value for checkbox column
491 if (!sqgetGlobalVar('checkall',$checkall,SQ_GET
)) {
496 * Loop through and display the info for each message.
498 $iEnd = ($aMailbox['SHOWALL'][$iSetIndx]) ?
$aMailbox['EXISTS'] : $iOffset +
$aMailbox['LIMIT'];
499 for ($i=$iOffset,$t=0;$i<$iEnd;++
$i) {
500 if (isset($aId[$i])) {
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];
510 $iUid = (isset($aMsg['UID'])) ?
$aMsg['UID'] : $aId[$i];
512 $aQuery[] = "passed_id=$aId[$i]";
513 $aQuery[] = "startMessage=$iPageOffset";
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");
523 $sUnknown = _("Unknown sender");
529 if ($highlight_list && !$bHighLight) {
530 $bHighLight = highlightMessage($aCol[$k], $value, $highlight_list,$aFormattedMessages[$iUid]);
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
] : '';
540 $title .= htmlspecialchars($sMailbox.'@'.$sHost).', ';
542 // if $value gets truncated we need to add the addresses with no
543 // personal name as well
544 $title_maybe .= htmlspecialchars($sMailbox.'@'.$sHost).', ';
548 $title = substr($title,0,-2); // strip ', ';
550 $sTmp = decodeHeader($sTmp);
551 if (isset($aColumnDesc[$k]['truncate']) && $aColumnDesc[$k]['truncate']) {
552 $sTrunc = truncateWithEntities($sTmp, $aColumnDesc[$k]['truncate']);
553 if ($sTrunc != $sTmp) {
555 $title = htmlspecialchars($sTmp);
556 } else if ($title_maybe) {
557 $title = $title .', '.$title_maybe;
558 $title = substr($title,0,-2); // strip ', ';
564 $value = ($sTmp) ?
$sTmp : $sUnknown;
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]);
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 $title = ($sTmp != $value) ?
$value : '';
581 /* generate the link to the message */
583 // TODO, $sTargetModule should be a query parameter so that we can use a single entrypoint
584 $link = $sTargetModule.'.php?' . implode('&',$aQuery);
586 $value = (trim($value)) ?
$value : _("(no subject)");
587 /* add thread indentation */
588 $aColumns[$k]['indent'] = $iIndent;
591 $value = show_readable_size($value);
594 case SQM_COL_INT_DATE
:
595 $value = getDateString(getTimeStamp(explode(' ',trim($value))));
598 $aFlagColumn = array('seen' => false,
603 foreach ($value as $sFlag => $value) {
605 case '\\seen' : $aFlagColumn['seen'] = true; break;
606 case '\\deleted' : $aFlagColumn['deleted'] = true; break;
607 case '\\answered': $aFlagColumn['answered'] = true; break;
608 case '\\flagged' : $aFlagColumn['flagged'] = true; break;
609 case '\\draft' : $aFlagColumn['draft'] = true; break;
613 $value = $aFlagColumn;
616 $value = ($value) ?
(int) $value : 3;
618 case SQM_COL_ATTACHMENT
:
619 $value = (is_array($value) && $value[0] == 'multipart' && $value[1] == 'mixed') ?
true : false;
626 if ($title) { $aColumns[$k]['title'] = $title; }
627 if ($link) { $aColumns[$k]['link'] = $link; }
628 if ($target) { $aColumns[$k]['target'] = $target; }
629 $aColumns[$k]['value'] = $value;
631 /* columns which will not be displayed but should be inspected
632 because the highlight list contains rules with those columns */
633 foreach ($aExtraHighLightColumns as $v) {
634 if ($highlight_list && !$bHighLight && isset($aMsg[$v])) {
635 $bHighLight = highlightMessage($v, $aMsg[$v], $highlight_list,$aFormattedMessages[$iUid]);
638 $aFormattedMessages[$iUid]['columns'] = $aColumns;
644 return $aFormattedMessages;
649 function highlightMessage($sCol, $sVal, $highlight_list, &$aFormat) {
650 if (!is_array($highlight_list) && count($highlight_list) == 0) {
654 $sCol = strtoupper($sCol);
656 foreach ($highlight_list as $highlight_list_part) {
657 if (trim($highlight_list_part['value'])) {
658 $high_val = strtolower($highlight_list_part['value']);
659 $match_type = strtoupper($highlight_list_part['match_type']);
660 if($match_type == 'TO_CC') {
661 if ($sCol == 'TO' ||
$sCol == 'CC') {
667 if ($match_type != $sCol) {
671 if (strpos(strtolower($sVal),$high_val) !== false) {
672 $hlt_color = $highlight_list_part['color'];
678 // Bug in highlight color???
679 if ($hlt_color{0} != '#') {
680 $hlt_color = '#'. $hlt_color;
682 $aFormat['row']['color'] = $hlt_color;
689 function setUserPref($username, $pref, $value) {
691 setPref($data_dir,$username,$pref,$value);
695 * Execute the sorting for a mailbox
697 * @param resource $imapConnection Imap connection
698 * @param array $aMailbox (reference) Mailbox retrieved with sqm_api_mailbox_select
699 * @return int $error (reference) Error number
701 * @author Marc Groot Koerkamp
703 function _get_sorted_msgs_list($imapConnection,&$aMailbox) {
704 $iSetIndx = (isset($aMailbox['SETINDEX'])) ?
$aMailbox['SETINDEX'] : 0;
705 $bDirection = !($aMailbox['SORT'] %
2);
707 if (!$aMailbox['SEARCH'][$iSetIndx]) {
708 $aMailbox['SEARCH'][$iSetIndx] = 'ALL';
710 if (($aMailbox['SORT'] & SQSORT_THREAD
) && sqimap_capability($imapConnection,'THREAD')) {
711 $aRes = get_thread_sort($imapConnection,$aMailbox['SEARCH'][$iSetIndx]);
712 if ($aRes === false) {
713 $aMailbox['SORT'] -= SQSORT_THREAD
;
714 $error = 1; // fix me, define an error code;
716 $aMailbox['UIDSET'][$iSetIndx] = $aRes[0];
717 $aMailbox['THREAD_INDENT'][$iSetIndx] = $aRes[1];
719 } else if ($aMailbox['SORT'] === SQSORT_NONE
) {
720 $id = sqimap_run_search($imapConnection, 'ALL' , '');
722 $error = 1; // fix me, define an error code
724 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($id);
725 $aMailbox['TOTAL'][$iSetIndx] = $aMailbox['EXISTS'];
728 if (sqimap_capability($imapConnection,'SORT')) {
729 $sSortField = _getSortField($aMailbox['SORT'],true);
730 $id = sqimap_get_sort_order($imapConnection, $sSortField, $bDirection, $aMailbox['SEARCH'][$iSetIndx]);
732 $error = 1; // fix me, define an error code
734 $aMailbox['UIDSET'][$iSetIndx] = $id;
738 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') {
739 $id = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
741 $sSortField = _getSortField($aMailbox['SORT'],false);
742 $aMailbox['UIDSET'][$iSetIndx] = get_squirrel_sort($imapConnection, $sSortField, $bDirection, $id);
749 * Does the $srt $_GET var to field mapping
751 * @param int $srt Field to sort on
752 * @param bool $bServerSort Server sorting is true
753 * @return string $sSortField Field to sort on
756 function _getSortField($sort,$bServerSort) {
761 case SQSORT_DATE_ASC
:
762 case SQSORT_DATE_DESC
:
763 $sSortField = 'DATE';
765 case SQSORT_FROM_ASC
:
766 case SQSORT_FROM_DESC
:
767 $sSortField = 'FROM';
769 case SQSORT_SUBJ_ASC
:
770 case SQSORT_SUBJ_DESC
:
771 $sSortField = 'SUBJECT';
773 case SQSORT_SIZE_ASC
:
774 case SQSORT_SIZE_DESC
:
775 $sSortField = ($bServerSort) ?
'SIZE' : 'RFC822.SIZE';
785 case SQSORT_INT_DATE_ASC
:
786 case SQSORT_INT_DATE_DESC
:
787 $sSortField = ($bServerSort) ?
'ARRIVAL' : 'INTERNALDATE';
791 default: $sSortField = 'UID';
802 * This function loops through a group of messages in the mailbox
803 * and shows them to the user.
805 * @param resource $imapConnection
806 * @param array $aMailbox associative array with mailbox related vars
807 * @param array $aProps
808 * @param int $iError error code, 0 is no error
810 function showMessagesForMailbox($imapConnection, &$aMailbox,$aProps, &$iError) {
814 $highlight_list = (isset($aProps['config']['highlight_list'])) ?
$aProps['config']['highlight_list'] : false;
815 $fancy_index_highlite = (isset($aProps['config']['fancy_index_highlite'])) ?
$aProps['config']['fancy_index_highlite'] : true;
816 $aColumnsDesc = (isset($aProps['columns'])) ?
$aProps['columns'] : false;
817 $iAccount = (isset($aProps['account'])) ?
(int) $aProps['account'] : 0;
818 $sMailbox = (isset($aProps['mailbox'])) ?
$aProps['mailbox'] : false;
819 $sTargetModule = (isset($aProps['module'])) ?
$aProps['module'] : 'read_body';
820 $show_flag_buttons = (isset($aProps['config']['show_flag_buttons'])) ?
$aProps['config']['show_flag_buttons'] : true;
821 $lastTargetMailbox = (isset($aProps['config']['lastTargetMailbox'])) ?
$aProps['config']['lastTargetMailbox'] : '';
822 $aOrder = array_keys($aProps['columns']);
823 $trash_folder = (isset($aProps['config']['trash_folder']) && $aProps['config']['trash_folder'])
824 ?
$aProps['config']['trash_folder'] : false;
825 $sent_folder = (isset($aProps['config']['sent_folder']) && $aProps['config']['sent_folder'])
826 ?
$aProps['config']['sent_folder'] : false;
827 $draft_folder = (isset($aProps['config']['draft_folder']) && $aProps['config']['draft_folder'])
828 ?
$aProps['config']['draft_folder'] : false;
829 $page_selector = (isset($aProps['config']['page_selector'])) ?
$aProps['config']['page_selector'] : false;
830 $page_selector_max = (isset($aProps['config']['page_selector_max'])) ?
$aProps['config']['page_selector_max'] : 10;
831 $color = $aProps['config']['color'];
839 if (!isset($iFormId)) {
845 * Remove the checkbox column because we cannot fetch it from the imap server
847 $aFetchColumns = $aColumnsDesc;
848 if (isset($aFetchColumns[SQM_COL_CHECK
])) {
849 unset($aFetchColumns[SQM_COL_CHECK
]);
853 * Before we fetch the message headers, check if we need to fetch extra columns
854 * to make the message highlighting work
856 if (is_array($highlight_list) && count($highlight_list)) {
857 $aHighlightColumns = array();
858 foreach ($highlight_list as $highlight_list_part) {
859 if (trim($highlight_list_part['value'])) {
860 $match_type = strtoupper($highlight_list_part['match_type']);
861 switch ($match_type) {
863 $aHighlightColumns[SQM_COL_TO
] = true;
864 $aHighlightColumns[SQM_COL_CC
] = true;
866 case 'TO': $aHighlightColumns[SQM_COL_TO
] = true; break;
867 case 'CC': $aHighlightColumns[SQM_COL_CC
] = true; break;
868 case 'FROM': $aHighlightColumns[SQM_COL_FROM
] = true; break;
869 case 'SUBJECT':$aHighlightColumns[SQM_COL_SUBJ
] = true; break;
873 $aExtraColumns = array();
874 foreach ($aHighlightColumns as $k => $v) {
875 if (!isset($aFetchColumns[$k])) {
876 $aExtraColumns[] = $k;
877 $aFetchColumns[$k] = true;
880 if (count($aExtraColumns)) {
881 $aProps['extra_columns'] = $aExtraColumns;
884 $aFetchColumns = array_keys($aFetchColumns);
885 // store the columns to fetch so we can pick them up in read_body
886 // where we validate the cache.
887 $aMailbox['FETCHHEADERS'] = $aFetchColumns;
889 $iError = fetchMessageHeaders($imapConnection, $aMailbox);
893 $aMessages = prepareMessageList($aMailbox, $aProps);
896 $iSetIndx = $aMailbox['SETINDEX'];
897 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ?
$aMailbox['EXISTS'] : $aMailbox['LIMIT'];
898 $iEnd = ($aMailbox['PAGEOFFSET'] +
($iLimit - 1) < $aMailbox['EXISTS']) ?
899 $aMailbox['PAGEOFFSET'] +
$iLimit - 1 : $aMailbox['EXISTS'];
901 $iNumberOfMessages = $aMailbox['TOTAL'][$iSetIndx];
902 $iEnd = min ( $iEnd, $iNumberOfMessages );
904 $php_self = $PHP_SELF;
906 $urlMailbox = urlencode($aMailbox['NAME']);
908 if (preg_match('/^(.+)\?.+$/',$php_self,$regs)) {
909 $source_url = $regs[1];
911 $source_url = $php_self;
914 $baseurl = $source_url.'?mailbox=' . urlencode($aMailbox['NAME']) .'&account='.$aMailbox['ACCOUNT'];
915 $where = urlencode($aMailbox['SEARCH'][$iSetIndx][0]);
916 $what = urlencode($aMailbox['SEARCH'][$iSetIndx][1]);
917 $baseurl .= '&where=' . $where . '&what=' . $what;
919 /* build thread sorting links */
920 $newsort = $aMailbox['SORT'];
921 if (sqimap_capability($imapConnection,'THREAD')) {
922 if ($aMailbox['SORT'] & SQSORT_THREAD
) {
923 $newsort -= SQSORT_THREAD
;
924 $thread_name = _("Unthread View");
926 $thread_name = _("Thread View");
927 $newsort = $aMailbox['SORT'] + SQSORT_THREAD
;
929 $thread_link_str = '<small>[<a href="' . $baseurl . '&srt='
930 . $newsort . '&startMessage=1">' . $thread_name
933 $thread_link_str ='';
935 $sort = $aMailbox['SORT'];
937 /* FIX ME ADD CHECKBOX CONTROL. No checkbox => no buttons */
941 /* future admin control over displayable buttons */
943 $aAdminControl = array(
944 'markUnflagged' => 1,
950 'undeleteButton'=> 1,
952 'expungeButton' => 1,
955 /* user prefs control */
956 $aUserControl = array (
958 'markUnflagged' => $show_flag_buttons,
959 'markFlagged' => $show_flag_buttons,
964 'undeleteButton'=> 1,
966 'expungeButton' => 1,
971 $showDelete = ($aMailbox['RIGHTS'] != 'READ-ONLY' &&
972 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ?
true : false;
973 $showByPassTrash = (($aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
974 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) &&
975 $trash_folder) ?
true : false; //
977 $showUndelete = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
978 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true) && !$trash_folder) ?
true : false;
979 $showMove = ($aMailbox['RIGHTS'] != 'READ-ONLY') ?
true : false;
980 $showExpunge = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
981 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ?
true : false;
982 $aImapControl = array (
983 'markUnflagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
984 'markFlagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
985 'markRead' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
986 'markUnread' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
988 'delete' => $showDelete,
989 'undeleteButton'=> $showUndelete,
990 'bypass_trash' => $showByPassTrash,
991 'expungeButton' => $showExpunge,
992 'moveButton' => $showMove
994 $aButtonStrings = array(
995 'markUnflagged' => _("Unflag"),
996 'markFlagged' => _("Flag"),
997 'markRead' => _("Read"),
998 'markUnread' => _("Unread"),
999 'forward' => _("Forward"),
1000 'delete' => _("Delete"),
1001 'undeleteButton' => _("Undelete"),
1002 'bypass_trash' => _("Bypass Trash"),
1003 'expungeButton' => _("Expunge"),
1004 'moveButton' => _("Move")
1009 * Register buttons in order to an array
1010 * The key is the "name", the first element of the value array is the "value", second argument is the type.
1012 $aFormElements = array();
1013 foreach($aAdminControl as $k => $v) {
1014 if ($v & $aUserControl[$k] & $aImapControl[$k]) {
1016 case 'markUnflagged':
1021 case 'undeleteButton':
1022 case 'expungeButton':
1024 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1026 case 'bypass_trash':
1027 $aFormElements[$k] = array($aButtonStrings[$k],'checkbox');
1030 $aFormElements['targetMailbox'] =
1031 array(sqimap_mailbox_option_list($imapConnection, array(strtolower($lastTargetMailbox)), 0, $boxes),'select');
1032 $aFormElements['mailbox'] = array($aMailbox['NAME'],'hidden');
1033 $aFormElements['startMessage'] = array($aMailbox['PAGEOFFSET'],'hidden');
1034 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1038 $aFormElements['account'] = array($iAccount,'hidden');
1042 * This is the beginning of the message list table.
1043 * It wraps around all messages
1045 $safe_name = preg_replace("/[^0-9A-Za-z_]/", '_', $aMailbox['NAME']);
1046 $form_name = "FormMsgs" . $safe_name;
1048 //if (!sqgetGlobalVar('align',$align,SQ_SESSION)) {
1049 $align = array('left' => 'left', 'right' => 'right');
1051 //sm_print_r($align);
1053 /* finally set the template vars */
1055 // FIX ME, before we support multiple templates we must review the names of the vars
1058 $aTemplate['color'] = $color;
1059 $aTemplate['form_name'] = "FormMsgs" . $safe_name;
1060 $aTemplate['form_id'] = 'mbx_'.$iFormId;
1061 $aTemplate['page_selector'] = $page_selector;
1062 $aTemplate['page_selector_max'] = $page_selector_max;
1063 $aTemplate['messagesPerPage'] = $aMailbox['LIMIT'];
1064 $aTemplate['showall'] = $aMailbox['SHOWALL'][$iSetIndx];
1065 $aTemplate['end_msg'] = $iEnd;
1066 $aTemplate['align'] = $align;
1067 $aTemplate['iNumberOfMessages'] = $iNumberOfMessages;
1068 $aTemplate['aOrder'] = $aOrder;
1069 $aTemplate['aFormElements'] = $aFormElements;
1070 $aTemplate['sort'] = $sort;
1071 $aTemplate['pageOffset'] = $aMailbox['PAGEOFFSET'];
1072 $aTemplate['baseurl'] = $baseurl;
1073 $aTemplate['aMessages'] =& $aMessages;
1074 $aTemplate['trash_folder'] = $trash_folder;
1075 $aTemplate['sent_folder'] = $sent_folder;
1076 $aTemplate['draft_folder'] = $draft_folder;
1077 $aTemplate['thread_link_str'] = $thread_link_str;
1078 $aTemplate['php_self'] = str_replace('&','&',$php_self);
1079 $aTemplate['mailbox'] = $sMailbox;
1080 $aTemplate['javascript_on'] = (isset($aProps['config']['javascript_on'])) ?
$aProps['config']['javascript_on'] : false;
1081 $aTemplate['enablesort'] = (isset($aProps['config']['enablesort'])) ?
$aProps['config']['enablesort'] : false;
1082 $aTemplate['icon_theme'] = (isset($aProps['config']['icon_theme'])) ?
$aProps['config']['icon_theme'] : false;
1083 $aTemplate['use_icons'] = (isset($aProps['config']['use_icons'])) ?
$aProps['config']['use_icons'] : false;
1084 $aTemplate['alt_index_colors'] = (isset($aProps['config']['alt_index_colors'])) ?
$aProps['config']['alt_index_colors'] : false;
1085 $aTemplate['fancy_index_highlite'] = $fancy_index_highlite;
1093 * Truncates a string and take care of html encoded characters
1095 * @param string $s string to truncate
1096 * @param int $iTrimAt Trim at nn characters
1097 * @return string Trimmed string
1099 function truncateWithEntities($s, $iTrimAt) {
1100 global $languages, $squirrelmail_language;
1102 $ent_strlen = strlen($s);
1103 if (($iTrimAt <= 0) ||
($ent_strlen <= $iTrimAt))
1106 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1107 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth')) {
1108 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth', $s, $iTrimAt);
1111 * see if this is entities-encoded string
1112 * If so, Iterate through the whole string, find out
1113 * the real number of characters, and if more
1114 * than $iTrimAt, substr with an updated trim value.
1116 $trim_val = $iTrimAt;
1119 while ( $ent_loc < $trim_val && (($ent_loc = strpos($s, '&', $ent_offset)) !== false) &&
1120 (($ent_loc_end = strpos($s, ';', $ent_loc+
3)) !== false) ) {
1121 $trim_val +
= ($ent_loc_end-$ent_loc);
1122 $ent_offset = $ent_loc_end+
1;
1125 if (($trim_val > $iTrimAt) && ($ent_strlen > $trim_val) && (strpos($s,';',$trim_val) < ($trim_val +
6))) {
1126 $i = strpos($s,';',$trim_val);
1128 $trim_val = strpos($s,';',$trim_val)+
1;
1131 // only print '...' when we're actually dropping part of the subject
1132 if ($ent_strlen <= $trim_val)
1135 return substr_replace($s, '...', $trim_val);
1140 * This should go in imap_mailbox.php
1141 * @param string $mailbox
1143 function handleAsSent($mailbox) {
1144 global $handleAsSent_result;
1146 /* First check if this is the sent or draft folder. */
1147 $handleAsSent_result = isSentMailbox($mailbox) ||
isDraftMailbox($mailbox);
1149 /* Then check the result of the handleAsSent hook. */
1150 do_hook('check_handleAsSent_result', $mailbox);
1152 /* And return the result. */
1153 return $handleAsSent_result;
1157 * Process messages list form and handle the cache gracefully. If $sButton and
1158 * $aUid are provided as argument then you can fake a message list submit and
1159 * use it i.e. in read_body.php for del move next and update the cache
1161 * @param resource $imapConnection imap connection
1162 * @param array $aMailbox (reference) cached mailbox
1163 * @param string $sButton fake a submit button
1164 * @param array $aUid fake the $msg array
1165 * @return string $sError error string in case of an error
1166 * @author Marc Groot Koerkamp
1168 function handleMessageListForm($imapConnection,&$aMailbox,$sButton='',$aUid = array()) {
1169 /* incoming formdata */
1170 $sButton = (sqgetGlobalVar('moveButton', $sTmp, SQ_POST
)) ?
'move' : $sButton;
1171 $sButton = (sqgetGlobalVar('expungeButton', $sTmp, SQ_POST
)) ?
'expunge' : $sButton;
1172 $sButton = (sqgetGlobalVar('forward', $sTmp, SQ_POST
)) ?
'forward' : $sButton;
1173 $sButton = (sqgetGlobalVar('delete', $sTmp, SQ_POST
)) ?
'setDeleted' : $sButton;
1174 $sButton = (sqgetGlobalVar('undeleteButton', $sTmp, SQ_POST
)) ?
'unsetDeleted' : $sButton;
1175 $sButton = (sqgetGlobalVar('markRead', $sTmp, SQ_POST
)) ?
'setSeen' : $sButton;
1176 $sButton = (sqgetGlobalVar('markUnread', $sTmp, SQ_POST
)) ?
'unsetSeen' : $sButton;
1177 $sButton = (sqgetGlobalVar('markFlagged', $sTmp, SQ_POST
)) ?
'setFlagged' : $sButton;
1178 $sButton = (sqgetGlobalVar('markUnflagged', $sTmp, SQ_POST
)) ?
'unsetFlagged' : $sButton;
1179 sqgetGlobalVar('targetMailbox', $targetMailbox, SQ_POST
);
1180 sqgetGlobalVar('bypass_trash', $bypass_trash, SQ_POST
);
1181 sqgetGlobalVar('msg', $msg, SQ_POST
);
1182 if (sqgetGlobalVar('account', $iAccount, SQ_POST
) === false) {
1186 $mailbox = $aMailbox['NAME'];
1188 /* retrieve the check boxes */
1189 $aUid = (isset($msg) && is_array($msg)) ?
array_values($msg) : $aUid;
1190 if (count($aUid) && $sButton != 'expunge') {
1191 $aUpdatedMsgs = false;
1195 // check if id exists in case we come from read_body
1196 if (count($aUid) == 1 && is_array($aMailbox['UIDSET'][$aMailbox['SETINDEX']]) &&
1197 !in_array($aUid[0],$aMailbox['UIDSET'][$aMailbox['SETINDEX']])) {
1200 $aUpdatedMsgs = sqimap_msgs_list_delete($imapConnection, $mailbox, $aUid,$bypass_trash);
1204 case 'unsetDeleted':
1208 case 'unsetFlagged':
1210 $sFlag = (substr($sButton,0,3) == 'set') ?
'\\'.substr($sButton,3) : '\\'.substr($sButton,5);
1211 $bSet = (substr($sButton,0,3) == 'set') ?
true : false;
1212 $aUpdatedMsgs = sqimap_toggle_flag($imapConnection, $aUid, $sFlag, $bSet, true);
1215 $aUpdatedMsgs = sqimap_msgs_list_move($imapConnection,$aUid,$targetMailbox);
1216 sqsession_register($targetMailbox,'lastTargetMailbox');
1220 $aMsgHeaders = array();
1221 foreach ($aUid as $iUid) {
1222 $aMsgHeaders[$iUid] = $aMailbox['MSG_HEADERS'][$iUid];
1224 if (count($aMsgHeaders)) {
1225 $composesession = attachSelectedMessages($imapConnection,$aMsgHeaders);
1226 // dirty hack, add info to $aMailbox
1227 $aMailbox['FORWARD_SESSION'] = $composesession;
1231 // Hook for plugin buttons
1232 do_hook_function('mailbox_display_button_action', $aUid);
1236 * Updates messages is an array containing the result of the untagged
1237 * fetch responses send by the imap server due to a flag change. That
1238 * response is parsed in a array with msg arrays by the parseFetch function
1240 if ($aUpdatedMsgs) {
1241 // Update the message headers cache
1242 $aDeleted = array();
1243 foreach ($aUpdatedMsgs as $iUid => $aMsg) {
1244 if (isset($aMsg['FLAGS'])) {
1246 * Only update the cached headers if the header is
1249 if (isset($aMailbox['MSG_HEADERS'][$iUid])) {
1250 $aMailbox['MSG_HEADERS'][$iUid]['FLAGS'] = $aMsg['FLAGS'];
1253 * Count the messages with the \Delete flag set so we can determine
1254 * if the number of expunged messages equals the number of flagged
1255 * messages for deletion.
1257 if (isset($aMsg['FLAGS']['\\deleted']) && $aMsg['FLAGS']['\\deleted']) {
1258 $aDeleted[] = $iUid;
1262 if ($bExpunge && $aMailbox['AUTO_EXPUNGE'] &&
1263 $iExpungedMessages = sqimap_mailbox_expunge($imapConnection, $aMailbox['NAME'], true))
1265 if (count($aDeleted) != $iExpungedMessages) {
1266 // there are more messages deleted permanently then we expected
1267 // invalidate the cache
1268 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = false;
1269 $aMailbox['MSG_HEADERS'] = false;
1271 // remove expunged messages from cache
1272 $aUidSet = $aMailbox['UIDSET'][$aMailbox['SETINDEX']];
1273 if (is_array($aUidSet)) {
1274 // create a UID => array index temp array
1275 $aUidSetDummy = array_flip($aUidSet);
1276 foreach ($aDeleted as $iUid) {
1277 // get the id as well in case of SQM_SORT_NONE
1278 if ($aMailbox['SORT'] == SQSORT_NONE
) {
1279 $aMailbox['ID'] = false;
1280 //$iId = $aMailbox['MSG_HEADERS'][$iUid]['ID'];
1281 //unset($aMailbox['ID'][$iId]);
1283 // unset the UID and message header
1284 unset($aUidSetDummy[$iUid]);
1285 unset($aMailbox['MSG_HEADERS'][$iUid]);
1287 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = array_keys($aUidSetDummy);
1290 // update EXISTS info
1291 if ($iExpungedMessages) {
1292 $aMailbox['EXISTS'] -= (int) $iExpungedMessages;
1293 $aMailbox['TOTAL'][$aMailbox['SETINDEX']] -= (int) $iExpungedMessages;
1295 if (($aMailbox['PAGEOFFSET']-1) >= $aMailbox['EXISTS']) {
1296 $aMailbox['PAGEOFFSET'] = ($aMailbox['PAGEOFFSET'] > $aMailbox['LIMIT']) ?
1297 $aMailbox['PAGEOFFSET'] - $aMailbox['LIMIT'] : 1;
1298 $aMailbox['OFFSET'] = $aMailbox['PAGEOFFSET'] - 1 ;
1303 if ($sButton == 'expunge') {
1305 * on expunge we do not know which messages will be deleted
1306 * so it's useless to try to sync the cache
1308 * Close the mailbox so we do not need to parse the untagged expunge
1309 * responses which do not contain uid info.
1310 * NB: Closing a mailbox is faster then expunge because the imap
1311 * server does not need to generate the untagged expunge responses
1313 sqimap_run_command($imapConnection,'CLOSE',false,$result,$message);
1314 $aMailbox = sqm_api_mailbox_select($imapConnection,$iAccount, $aMailbox['NAME'],array(),array());
1317 $sError = _("No messages were selected.");
1324 function attachSelectedMessages($imapConnection,$aMsgHeaders) {
1325 global $username, $attachment_dir,
1329 sqgetGlobalVar('composesession', $composesession, SQ_SESSION
);
1330 sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION
);
1331 if (!isset($compose_messages)||
is_null($compose_messages)) {
1332 $compose_messages = array();
1333 sqsession_register($compose_messages,'compose_messages');
1336 if (!$composesession) {
1337 $composesession = 1;
1338 sqsession_register($composesession,'composesession');
1341 sqsession_register($composesession,'composesession');
1344 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
1346 $composeMessage = new Message();
1347 $rfc822_header = new Rfc822Header();
1348 $composeMessage->rfc822_header
= $rfc822_header;
1349 $composeMessage->reply_rfc822_header
= '';
1351 foreach($aMsgHeaders as $iUid => $aMsgHeader) {
1353 * Retrieve the full message
1355 $body_a = sqimap_run_command($imapConnection, "FETCH $iUid RFC822", true, $response, $readmessage, TRUE);
1356 if ($response == 'OK') {
1358 $subject = (isset($aMsgHeader['subject'])) ?
$aMsgHeader['subject'] : $iUid;
1360 array_shift($body_a);
1362 $body = implode('', $body_a);
1365 $localfilename = GenerateRandomString(32, 'FILE', 7);
1366 $full_localfilename = "$hashed_attachment_dir/$localfilename";
1368 $fp = fopen( $full_localfilename, 'wb');
1369 fwrite ($fp, $body);
1371 $composeMessage->initAttachment('message/rfc822',$subject.'.msg',
1372 $full_localfilename);
1376 $compose_messages[$composesession] = $composeMessage;
1377 sqsession_register($compose_messages,'compose_messages');
1378 return $composesession;