43b98f758183e4d2ef00b4bf5749e76f9e38ab0e
6 * This contains functions that display mailbox information, such as the
7 * table row that has sender, date, subject, etc...
9 * @copyright © 1999-2005 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
12 * @package squirrelmail
15 /** The standard includes.. */
16 require_once(SM_PATH
. 'functions/strings.php');
17 require_once(SM_PATH
. 'functions/html.php');
18 require_once(SM_PATH
. 'functions/imap_mailbox.php');
19 require_once(SM_PATH
. 'functions/imap_messages.php');
20 require_once(SM_PATH
. 'functions/imap_asearch.php');
21 require_once(SM_PATH
. 'functions/mime.php');
22 require_once(SM_PATH
. 'functions/forms.php');
26 * Selects a mailbox for header retrieval.
27 * Cache control for message headers is embedded.
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
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;
109 $aMailbox['MSG_HEADERS'] = false;
111 if ($aCachedMailbox) {
113 * Validate integrity of cached data
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'];
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'];
131 * If it concerns a reverse sort we do not need to invalidate
132 * the cached sorted UIDSET, a reverse is sufficient.
134 if ((($newsort %
2) && ($newsort +
1 == $oldsort)) ||
135 (!($newsort %
2) && ($newsort - 1 == $oldsort))) {
136 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($aCachedMailbox['UIDSET'][$iSetIndx]);
138 $server_sort_array = false;
139 $aMailbox['MSG_HEADERS'] = false;
140 $aMailbox['ID'] = false;
142 // store the new sort value in the mailbox pref
143 if ($aConfig['user']) {
144 // FIXME, in ideal situation, we write back the
145 // prefs at the end of the script
146 setUserPref($aConfig['user'],'pref_'.$account.'_'.$mailbox,serialize($aProps));
149 $aMailbox['UIDSET'][$iSetIndx] = $aCachedMailbox['UIDSET'][$iSetIndx];
155 * Restore the offset in the paginator if no new offset is provided.
157 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['offset']) && $aCachedMailbox['OFFSET']) {
158 $aMailbox['OFFSET'] = $aCachedMailbox['OFFSET'];
159 $aMailbox['PAGEOFFSET'] = $aCachedMailbox['PAGEOFFSET'];
161 $aMailbox['OFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ?
$aConfig['offset'] -1 : 0;
162 $aMailbox['PAGEOFFSET'] = (isset($aConfig['offset']) && $aConfig['offset']) ?
$aConfig['offset'] : 1;
165 * Restore the number of messages in the result set
167 if (isset($aCachedMailbox['TOTAL'][$iSetIndx]) && $aCachedMailbox['TOTAL'][$iSetIndx]) {
168 $aMailbox['TOTAL'][$iSetIndx] = $aCachedMailbox['TOTAL'][$iSetIndx];
172 * Restore the showall value no new showall value is provided.
174 if (isset($aMailbox['UIDSET'][$iSetIndx]) && !isset($aConfig['showall']) &&
175 isset($aCachedMailbox['SHOWALL'][$iSetIndx]) && $aCachedMailbox['SHOWALL'][$iSetIndx]) {
176 $aMailbox['SHOWALL'][$iSetIndx] = $aCachedMailbox['SHOWALL'][$iSetIndx];
178 $aMailbox['SHOWALL'][$iSetIndx] = (isset($aConfig['showall']) && $aConfig['showall']) ?
1 : 0;
182 * Restore the sort order if no new sort order is provided.
184 if (!isset($aProps[MBX_PREF_SORT
]) && isset($aCachedMailbox['SORT'])) {
185 $aMailbox['SORT'] = $aCachedMailbox['SORT'];
187 $aMailbox['SORT'] = (isset($aProps[MBX_PREF_SORT
])) ?
$aProps[MBX_PREF_SORT
] : 0;
191 * Restore the number of message to show per page when no new limit is provided
193 if (!isset($aProps[MBX_PREF_LIMIT
]) && isset($aCachedMailbox['LIMIT'])) {
194 $aMailbox['LIMIT'] = $aCachedMailbox['LIMIT'];
196 $aMailbox['LIMIT'] = (isset($aProps[MBX_PREF_LIMIT
])) ?
$aProps[MBX_PREF_LIMIT
] : 15;
200 * Restore the ordered columns to show when no new ordered columns are provided
202 if (!isset($aProps[MBX_PREF_COLUMNS
]) && isset($aCachedMailbox['COLUMNS'])) {
203 $aMailbox['COLUMNS'] = $aCachedMailbox['COLUMNS'];
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
);
210 * Restore the headers we fetch the last time. Saves intitialisation stuff in read_body.
212 $aMailbox['FETCHHEADERS'] = (isset($aCachedMailbox['FETCHHEADERS'])) ?
$aCachedMailbox['FETCHHEADERS'] : null;
214 if (!isset($aProps[MBX_PREF_AUTO_EXPUNGE
]) && isset($aCachedMailbox['AUTO_EXPUNGE'])) {
215 $aMailbox['AUTO_EXPUNGE'] = $aCachedMailbox['AUTO_EXPUNGE'];
217 $aMailbox['AUTO_EXPUNGE'] = (isset($aProps[MBX_PREF_AUTO_EXPUNGE
])) ?
$aProps[MBX_PREF_AUTO_EXPUNGE
] : false;
219 if (!isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx])) {
220 $aMailbox['SEARCH'][$iSetIndx] = $aCachedMailbox['SEARCH'][$iSetIndx];
221 } else if (isset($aConfig['search']) && isset($aCachedMailbox['SEARCH'][$iSetIndx]) &&
222 $aConfig['search'] != $aCachedMailbox['SEARCH'][$iSetIndx]) {
223 // reset the pageindex
224 $aMailbox['SEARCH'][$iSetIndx] = $aConfig['search'];
225 $aMailbox['OFFSET'] = 0;
226 $aMailbox['PAGEOFFSET'] = 1;
228 $aMailbox['SEARCH'][$iSetIndx] = (isset($aConfig['search'])) ?
$aConfig['search'] : 'ALL';
230 if (!isset($aConfig['charset']) && isset($aCachedMailbox['CHARSET'][$iSetIndx])) {
231 $aMailbox['CHARSET'][$iSetIndx] = $aCachedMailbox['CHARSET'][$iSetIndx];
233 $aMailbox['CHARSET'][$iSetIndx] = (isset($aConfig['charset'])) ?
$aConfig['charset'] : 'US-ASCII';
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'];
245 /* decide if we are thread sorting or not */
246 if ($aMailbox['SORT'] & SQSORT_THREAD
) {
247 if (!sqimap_capability($imapConnection,'THREAD')) {
248 $aMailbox['SORT'] ^
= SQSORT_THREAD
;
250 $aMailbox['THREAD_INDENT'] = $aCachedMailbox['THREAD_INDENT'];
253 $aMailbox['THREAD_INDENT'] = false;
256 /* set a timestamp for cachecontrol */
257 $aMailbox['TIMESTAMP'] = time();
262 * Fetch the message headers for a mailbox. Settings are part of the aMailbox
263 * array. Dependent of the mailbox settings it deals with sort, thread and search
264 * If server sort is supported then SORT is also used for retrieving sorted search results
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
270 * @author Marc Groot Koerkamp
272 function fetchMessageHeaders($imapConnection, &$aMailbox) {
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 */
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.
284 $iSetIndx = (isset($aMailbox['SETINDEX'])) ?
$aMailbox['SETINDEX'] : 0;
286 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ?
$aMailbox['EXISTS'] : $aMailbox['LIMIT'];
288 * Adjust the start_msg
290 $start_msg = $aMailbox['PAGEOFFSET'];
291 if($aMailbox['PAGEOFFSET'] > $aMailbox['EXISTS']) {
292 $start_msg -= $aMailbox['LIMIT'];
298 if (is_array($aMailbox['UIDSET'])) {
299 $aUid =& $aMailbox['UIDSET'][$iSetIndx];
303 $aFetchHeaders = $aMailbox['FETCHHEADERS'];
306 $aFetchItems = $aHeaderItems = array();
307 // initialize the fields we want to retrieve:
308 $aHeaderFields = array();
309 foreach ($aFetchHeaders as $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;
326 * A uidset with sorted uid's is available. We can use the cache
328 if (isset($aUid) && $aUid ) {
329 // limit the cache to SQM_MAX_PAGES_IN_CACHE
330 if (!$aMailbox['SHOWALL'][$iSetIndx] && isset($aMailbox['MSG_HEADERS'])) {
331 $iMaxMsgs = $iLimit * SQM_MAX_PAGES_IN_CACHE
;
332 $iCacheSize = count($aMailbox['MSG_HEADERS']);
333 if ($iCacheSize > $iMaxMsgs) {
334 $iReduce = $iCacheSize - $iMaxMsgs;
335 foreach ($aMailbox['MSG_HEADERS'] as $iUid => $value) {
337 unset($aMailbox['MSG_HEADERS'][$iUid]);
346 $id_slice = array_slice($aUid,$start_msg-1,$iLimit);
347 /* do some funky cache checks */
348 if (isset($aMailbox['MSG_HEADERS']) && is_array($aMailbox['MSG_HEADERS'])) {
349 $aUidCached = array_keys($aMailbox['MSG_HEADERS']);
351 $aMailbox['MSG_HEADERS'] = array();
352 $aUidCached = array();
354 $aUidNotCached = array_values(array_diff($id_slice,$aUidCached));
357 * $aUidNotCached contains an array with UID's which need to be fetched to
358 * complete the needed message headers.
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;
368 * Initialize the sorted UID list or initiate a UID list with search
369 * results and fetch the visible message headers
372 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') { // in case of a search request
374 if ($aMailbox['SEARCH'][$iSetIndx] && $aMailbox['SORT'] == 0) {
375 $aUid = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
379 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
380 $aUid = $aMailbox['UIDSET'][$iSetIndx];
384 * Number of messages is the resultset
386 $aMailbox['TOTAL'][$iSetIndx] = count($aUid);
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);
392 $iError = 1; // FIX ME, define an error code
397 $iError = _get_sorted_msgs_list($imapConnection,$aMailbox,$iError);
398 $aUid = $aMailbox['UIDSET'][$iSetIndx];
402 * Number of messages is the resultset
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);
410 $iError = 1; // FIX ME, define an error code
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.
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
426 * @author Marc Groot Koerkamp
428 function prepareMessageList(&$aMailbox, $aProps) {
429 /* retrieve the properties */
430 $my_email_address = (isset($aProps['email'])) ?
$aProps['email'] : false;
431 $highlight_list = (isset($aProps['config']['highlight_list'])) ?
$aProps['config']['highlight_list'] : false;
432 $aColumnDesc = (isset($aProps['columns'])) ?
$aProps['columns'] : false;
433 $aExtraColumns = (isset($aProps['extra_columns'])) ?
$aProps['extra_columns'] : array();
434 $iAccount = (isset($aProps['account'])) ?
(int) $aProps['account'] : 0;
435 $sMailbox = (isset($aProps['mailbox'])) ?
$aProps['mailbox'] : false;
436 $sTargetModule = (isset($aProps['module'])) ?
$aProps['module'] : 'read_body';
439 * TODO 1, retrieve array with identity email addresses in order to match against to,cc and set a flag
440 * $aFormattedMessages[$iUid]['match_identity'] = true
441 * The template can show some image if there is a match.
442 * TODO 2, makes sure the matching is done fast by doing a strpos call on the returned $value
446 * Only retrieve values for displayable columns
448 foreach ($aColumnDesc as $k => $v) {
450 case SQM_COL_FROM
: $aCol[SQM_COL_FROM
] = 'from'; break;
451 case SQM_COL_DATE
: $aCol[SQM_COL_DATE
] = 'date'; break;
452 case SQM_COL_SUBJ
: $aCol[SQM_COL_SUBJ
] = 'subject'; break;
453 case SQM_COL_FLAGS
: $aCol[SQM_COL_FLAGS
] = 'FLAGS'; break;
454 case SQM_COL_SIZE
: $aCol[SQM_COL_SIZE
] = 'SIZE'; break;
455 case SQM_COL_PRIO
: $aCol[SQM_COL_PRIO
] = 'x-priority'; break;
456 case SQM_COL_ATTACHMENT
: $aCol[SQM_COL_ATTACHMENT
] = 'content-type'; break;
457 case SQM_COL_INT_DATE
: $aCol[SQM_COL_INT_DATE
] = 'INTERNALDATE'; break;
458 case SQM_COL_TO
: $aCol[SQM_COL_TO
] = 'to'; break;
459 case SQM_COL_CC
: $aCol[SQM_COL_CC
] = 'cc'; break;
460 case SQM_COL_BCC
: $aCol[SQM_COL_BCC
] = 'bcc'; break;
464 $aExtraHighLightColumns = array();
465 foreach ($aExtraColumns as $v) {
467 case SQM_COL_FROM
: $aExtraHighLightColumns[] = 'from'; break;
468 case SQM_COL_SUBJ
: $aExtraHighLightColumns[] = 'subject'; break;
469 case SQM_COL_TO
: $aExtraHighLightColumns[] = 'to'; break;
470 case SQM_COL_CC
: $aExtraHighLightColumns[] = 'cc'; break;
471 case SQM_COL_BCC
: $aExtraHighLightColumns[] = 'bcc'; break;
475 $aFormattedMessages = array();
478 $iSetIndx = $aMailbox['SETINDEX'];
479 $aId = $aMailbox['UIDSET'][$iSetIndx];
480 $aHeaders =& $aMailbox['MSG_HEADERS']; /* use a reference to avoid a copy.
481 MSG_HEADERS can contain large amounts of data */
482 $iOffset = $aMailbox['OFFSET'];
483 $sort = $aMailbox['SORT'];
484 $iPageOffset = $aMailbox['PAGEOFFSET'];
485 $sMailbox = $aMailbox['NAME'];
486 $sSearch = (isset($aMailbox['SEARCH'][$aMailbox['SETINDEX']]) &&
487 $aMailbox['SEARCH'][$aMailbox['SETINDEX']] != 'ALL') ?
$aMailbox['SEARCH'][$aMailbox['SETINDEX']] : false;
488 $aSearch = ($sSearch) ?
array('search.php',$aMailbox['SETINDEX']) : null;
489 /* avoid improper usage */
490 if ($sMailbox && isset($iAccount) && $sTargetModule) {
491 $aInitQuery = array("account=$iAccount",'mailbox='.urlencode($sMailbox));
496 if ($aMailbox['SORT'] & SQSORT_THREAD
) {
497 $aIndentArray =& $aMailbox['THREAD_INDENT'][$aMailbox['SETINDEX']];
503 * Retrieve value for checkbox column
505 if (!sqgetGlobalVar('checkall',$checkall,SQ_GET
)) {
510 * Loop through and display the info for each message.
512 $iEnd = ($aMailbox['SHOWALL'][$iSetIndx]) ?
$aMailbox['EXISTS'] : $iOffset +
$aMailbox['LIMIT'];
513 for ($i=$iOffset,$t=0;$i<$iEnd;++
$i) {
514 if (isset($aId[$i])) {
517 $value = $title = $link = $target = $onclick = $link_extra = '';
518 $aQuery = ($aInitQuery !== false) ?
$aInitQuery : false;
519 $aMsg = $aHeaders[$aId[$i]];
520 if (isset($aSearch) && count($aSearch) > 1 && $aQuery) {
521 $aQuery[] = "where=". $aSearch[0];
522 $aQuery[] = "what=" . $aSearch[1];
524 $iUid = (isset($aMsg['UID'])) ?
$aMsg['UID'] : $aId[$i];
526 $aQuery[] = "passed_id=$aId[$i]";
527 $aQuery[] = "startMessage=$iPageOffset";
530 foreach ($aCol as $k => $v) {
531 $title = $link = $target = $onclick = $link_extra = '';
532 $aColumns[$k] = array();
533 $value = (isset($aMsg[$v])) ?
$aMsg[$v] : '';
534 $sUnknown = _("Unknown recipient");
537 $sUnknown = _("Unknown sender");
543 if ($highlight_list && !$bHighLight) {
544 $bHighLight = highlightMessage($aCol[$k], $value, $highlight_list,$aFormattedMessages[$iUid]);
546 $aAddressList = parseRFC822Address($value);
547 $sTmp = getAddressString($aAddressList,array('best' => true));
548 $title = $title_maybe = '';
549 foreach ($aAddressList as $aAddr) {
550 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL
])) ?
$aAddr[SQM_ADDR_PERSONAL
] : '';
551 $sMailbox = (isset($aAddr[SQM_ADDR_MAILBOX
])) ?
$aAddr[SQM_ADDR_MAILBOX
] : '';
552 $sHost = (isset($aAddr[SQM_ADDR_HOST
])) ?
$aAddr[SQM_ADDR_HOST
] : '';
554 $title .= htmlspecialchars($sMailbox.'@'.$sHost).', ';
556 // if $value gets truncated we need to add the addresses with no
557 // personal name as well
558 $title_maybe .= htmlspecialchars($sMailbox.'@'.$sHost).', ';
562 $title = substr($title,0,-2); // strip ', ';
564 $sTmp = decodeHeader($sTmp);
565 if (isset($aColumnDesc[$k]['truncate']) && $aColumnDesc[$k]['truncate']) {
566 $sTrunc = truncateWithEntities($sTmp, $aColumnDesc[$k]['truncate']);
567 if ($sTrunc != $sTmp) {
569 $title = htmlspecialchars($sTmp);
570 } else if ($title_maybe) {
571 $title = $title .', '.$title_maybe;
572 $title = substr($title,0,-2); // strip ', ';
578 $value = ($sTmp) ?
$sTmp : $sUnknown;
581 // subject is mime encoded, decode it.
582 // value is sanitized in decoding function.
583 // TODO, verify if it should be done before or after the highlighting
584 $value=decodeHeader($value);
585 if ($highlight_list && !$bHighLight) {
586 $bHighLight = highlightMessage('SUBJECT', $value, $highlight_list, $aFormattedMessages[$iUid]);
588 $iIndent = (isset($aIndentArray[$aId[$i]])) ?
$aIndentArray[$aId[$i]] : 0;
589 // FIXME: don't break 8bit symbols and html entities during truncation
590 if (isset($aColumnDesc[$k]['truncate']) && $aColumnDesc[$k]['truncate']) {
591 $sTmp = truncateWithEntities($value, $aColumnDesc[$k]['truncate']-$iIndent);
592 // drop any double spaces since these will be displayed in the title
593 $title = ($sTmp != $value) ?
preg_replace('/\s{2,}/', ' ', $value) : '';
596 /* generate the link to the message */
598 // TODO, $sTargetModule should be a query parameter so that we can use a single entrypoint
599 $link = $sTargetModule.'.php?' . implode('&',$aQuery);
601 // globalize link attributes so plugins can share in
602 // modifying them; plugins are responsible for sharing
603 // nicely (such as for setting the target, etc)
604 global $link, $title, $target, $onclick, $link_extra;
605 do_hook('subject_link', array($iPageOffset, $sSearch, $aSearch));
607 $value = (trim($value)) ?
$value : _("(no subject)");
608 /* add thread indentation */
609 $aColumns[$k]['indent'] = $iIndent;
612 $value = show_readable_size($value);
615 case SQM_COL_INT_DATE
:
616 $value = getDateString(getTimeStamp(explode(' ',trim($value))));
619 $aFlagColumn = array('seen' => false,
625 if(!is_array($value)) $value = array();
626 foreach ($value as $sFlag => $value) {
628 case '\\seen' : $aFlagColumn['seen'] = true; break;
629 case '\\deleted' : $aFlagColumn['deleted'] = true; break;
630 case '\\answered': $aFlagColumn['answered'] = true; break;
631 case '\\flagged' : $aFlagColumn['flagged'] = true; break;
632 case '\\draft' : $aFlagColumn['draft'] = true; break;
636 $value = $aFlagColumn;
639 $value = ($value) ?
(int) $value : 3;
641 case SQM_COL_ATTACHMENT
:
642 $value = (is_array($value) && $value[0] == 'multipart' && $value[1] == 'mixed') ?
true : false;
649 if ($title) { $aColumns[$k]['title'] = $title; }
650 if ($link) { $aColumns[$k]['link'] = $link; }
651 if ($link_extra) { $aColumns[$k]['link_extra'] = $link_extra; }
652 if ($onclick) { $aColumns[$k]['onclick'] = $onclick; }
653 if ($target) { $aColumns[$k]['target'] = $target; }
654 $aColumns[$k]['value'] = $value;
656 /* columns which will not be displayed but should be inspected
657 because the highlight list contains rules with those columns */
658 foreach ($aExtraHighLightColumns as $v) {
659 if ($highlight_list && !$bHighLight && isset($aMsg[$v])) {
660 $bHighLight = highlightMessage($v, $aMsg[$v], $highlight_list,$aFormattedMessages[$iUid]);
663 $aFormattedMessages[$iUid]['columns'] = $aColumns;
669 return $aFormattedMessages;
674 * Sets the row color if the provided column value pair matches a hightlight rule
676 * @param string $sCol column name
677 * @param string $sVal column value
678 * @param array $highlight_list highlight rules
679 * @param array $aFormat (reference) array where row color info is stored
680 * @return bool match found
682 * @author Marc Groot Koerkamp
684 function highlightMessage($sCol, $sVal, $highlight_list, &$aFormat) {
685 if (!is_array($highlight_list) && count($highlight_list) == 0) {
689 $sCol = strtoupper($sCol);
691 foreach ($highlight_list as $highlight_list_part) {
692 if (trim($highlight_list_part['value'])) {
693 $high_val = strtolower($highlight_list_part['value']);
694 $match_type = strtoupper($highlight_list_part['match_type']);
695 if($match_type == 'TO_CC') {
696 if ($sCol == 'TO' ||
$sCol == 'CC') {
702 if ($match_type != $sCol) {
706 if (strpos(strtolower($sVal),$high_val) !== false) {
707 $hlt_color = $highlight_list_part['color'];
713 // Bug in highlight color???
714 if ($hlt_color{0} != '#') {
715 $hlt_color = '#'. $hlt_color;
717 $aFormat['row']['color'] = $hlt_color;
724 function setUserPref($username, $pref, $value) {
726 setPref($data_dir,$username,$pref,$value);
730 * Execute the sorting for a mailbox
732 * @param resource $imapConnection Imap connection
733 * @param array $aMailbox (reference) Mailbox retrieved with sqm_api_mailbox_select
734 * @return int $error (reference) Error number
737 * @author Marc Groot Koerkamp
739 function _get_sorted_msgs_list($imapConnection,&$aMailbox) {
740 $iSetIndx = (isset($aMailbox['SETINDEX'])) ?
$aMailbox['SETINDEX'] : 0;
741 $bDirection = !($aMailbox['SORT'] %
2);
743 if (!$aMailbox['SEARCH'][$iSetIndx]) {
744 $aMailbox['SEARCH'][$iSetIndx] = 'ALL';
746 if (($aMailbox['SORT'] & SQSORT_THREAD
) && sqimap_capability($imapConnection,'THREAD')) {
747 $aRes = get_thread_sort($imapConnection,$aMailbox['SEARCH'][$iSetIndx]);
748 if ($aRes === false) {
749 $aMailbox['SORT'] -= SQSORT_THREAD
;
750 $error = 1; // fix me, define an error code;
752 $aMailbox['UIDSET'][$iSetIndx] = $aRes[0];
753 $aMailbox['THREAD_INDENT'][$iSetIndx] = $aRes[1];
755 } else if ($aMailbox['SORT'] === SQSORT_NONE
) {
756 $id = sqimap_run_search($imapConnection, 'ALL' , '');
758 $error = 1; // fix me, define an error code
760 $aMailbox['UIDSET'][$iSetIndx] = array_reverse($id);
761 $aMailbox['TOTAL'][$iSetIndx] = $aMailbox['EXISTS'];
764 if (sqimap_capability($imapConnection,'SORT')) {
765 $sSortField = _getSortField($aMailbox['SORT'],true);
766 $id = sqimap_get_sort_order($imapConnection, $sSortField, $bDirection, $aMailbox['SEARCH'][$iSetIndx]);
768 $error = 1; // fix me, define an error code
770 $aMailbox['UIDSET'][$iSetIndx] = $id;
774 if ($aMailbox['SEARCH'][$iSetIndx] != 'ALL') {
775 $id = sqimap_run_search($imapConnection, $aMailbox['SEARCH'][$iSetIndx], $aMailbox['CHARSET'][$iSetIndx]);
777 $sSortField = _getSortField($aMailbox['SORT'],false);
778 $aMailbox['UIDSET'][$iSetIndx] = get_squirrel_sort($imapConnection, $sSortField, $bDirection, $id);
785 * Does the $srt $_GET var to field mapping
787 * @param int $srt Field to sort on
788 * @param bool $bServerSort Server sorting is true
789 * @return string $sSortField Field to sort on
793 function _getSortField($sort,$bServerSort) {
798 case SQSORT_DATE_ASC
:
799 case SQSORT_DATE_DESC
:
800 $sSortField = 'DATE';
802 case SQSORT_FROM_ASC
:
803 case SQSORT_FROM_DESC
:
804 $sSortField = 'FROM';
806 case SQSORT_SUBJ_ASC
:
807 case SQSORT_SUBJ_DESC
:
808 $sSortField = 'SUBJECT';
810 case SQSORT_SIZE_ASC
:
811 case SQSORT_SIZE_DESC
:
812 $sSortField = ($bServerSort) ?
'SIZE' : 'RFC822.SIZE';
822 case SQSORT_INT_DATE_ASC
:
823 case SQSORT_INT_DATE_DESC
:
824 $sSortField = ($bServerSort) ?
'ARRIVAL' : 'INTERNALDATE';
828 default: $sSortField = 'UID';
836 * This function is a utility function for setting which headers should be
837 * fetched. It takes into account the highlight list which requires extra
838 * headers to be fetch in order to make those rules work. It's called before
839 * the headers are fetched which happens in showMessagesForMailbox and when
840 * the next and prev links in read_body.php are used.
842 * @param array $aMailbox associative array with mailbox related vars
843 * @param array $aProps
848 function calcFetchColumns(&$aMailbox, &$aProps) {
850 $highlight_list = (isset($aProps['config']['highlight_list'])) ?
$aProps['config']['highlight_list'] : false;
851 $aColumnsDesc = (isset($aProps['columns'])) ?
$aProps['columns'] : false;
853 $aFetchColumns = $aColumnsDesc;
854 if (isset($aFetchColumns[SQM_COL_CHECK
])) {
855 unset($aFetchColumns[SQM_COL_CHECK
]);
859 * Before we fetch the message headers, check if we need to fetch extra columns
860 * to make the message highlighting work
862 if (is_array($highlight_list) && count($highlight_list)) {
863 $aHighlightColumns = array();
864 foreach ($highlight_list as $highlight_list_part) {
865 if (trim($highlight_list_part['value'])) {
866 $match_type = strtoupper($highlight_list_part['match_type']);
867 switch ($match_type) {
869 $aHighlightColumns[SQM_COL_TO
] = true;
870 $aHighlightColumns[SQM_COL_CC
] = true;
872 case 'TO': $aHighlightColumns[SQM_COL_TO
] = true; break;
873 case 'CC': $aHighlightColumns[SQM_COL_CC
] = true; break;
874 case 'FROM': $aHighlightColumns[SQM_COL_FROM
] = true; break;
875 case 'SUBJECT':$aHighlightColumns[SQM_COL_SUBJ
] = true; break;
879 $aExtraColumns = array();
880 foreach ($aHighlightColumns as $k => $v) {
881 if (!isset($aFetchColumns[$k])) {
882 $aExtraColumns[] = $k;
883 $aFetchColumns[$k] = true;
886 if (count($aExtraColumns)) {
887 $aProps['extra_columns'] = $aExtraColumns;
890 $aMailbox['FETCHHEADERS'] = array_keys($aFetchColumns);
895 * This function loops through a group of messages in the mailbox
896 * and shows them to the user.
898 * @param resource $imapConnection
899 * @param array $aMailbox associative array with mailbox related vars
900 * @param array $aProps
901 * @param int $iError error code, 0 is no error
903 function showMessagesForMailbox($imapConnection, &$aMailbox,$aProps, &$iError) {
907 $highlight_list = (isset($aProps['config']['highlight_list'])) ?
$aProps['config']['highlight_list'] : false;
908 $fancy_index_highlite = (isset($aProps['config']['fancy_index_highlite'])) ?
$aProps['config']['fancy_index_highlite'] : true;
909 $aColumnsDesc = (isset($aProps['columns'])) ?
$aProps['columns'] : false;
910 $iAccount = (isset($aProps['account'])) ?
(int) $aProps['account'] : 0;
911 $sMailbox = (isset($aProps['mailbox'])) ?
$aProps['mailbox'] : false;
912 $sTargetModule = (isset($aProps['module'])) ?
$aProps['module'] : 'read_body';
913 $show_flag_buttons = (isset($aProps['config']['show_flag_buttons'])) ?
$aProps['config']['show_flag_buttons'] : true;
914 $lastTargetMailbox = (isset($aProps['config']['lastTargetMailbox'])) ?
$aProps['config']['lastTargetMailbox'] : '';
915 $aOrder = array_keys($aProps['columns']);
916 $trash_folder = (isset($aProps['config']['trash_folder']) && $aProps['config']['trash_folder'])
917 ?
$aProps['config']['trash_folder'] : false;
918 $sent_folder = (isset($aProps['config']['sent_folder']) && $aProps['config']['sent_folder'])
919 ?
$aProps['config']['sent_folder'] : false;
920 $draft_folder = (isset($aProps['config']['draft_folder']) && $aProps['config']['draft_folder'])
921 ?
$aProps['config']['draft_folder'] : false;
922 $page_selector = (isset($aProps['config']['page_selector'])) ?
$aProps['config']['page_selector'] : false;
923 $page_selector_max = (isset($aProps['config']['page_selector_max'])) ?
$aProps['config']['page_selector_max'] : 10;
924 $color = $aProps['config']['color'];
932 if (!isset($iFormId)) {
937 // store the columns to fetch so we can pick them up in read_body
938 // where we validate the cache.
939 calcFetchColumns($aMailbox ,$aProps);
941 $iError = fetchMessageHeaders($imapConnection, $aMailbox);
945 $aMessages = prepareMessageList($aMailbox, $aProps);
948 $iSetIndx = $aMailbox['SETINDEX'];
949 $iLimit = ($aMailbox['SHOWALL'][$iSetIndx]) ?
$aMailbox['EXISTS'] : $aMailbox['LIMIT'];
950 $iEnd = ($aMailbox['PAGEOFFSET'] +
($iLimit - 1) < $aMailbox['EXISTS']) ?
951 $aMailbox['PAGEOFFSET'] +
$iLimit - 1 : $aMailbox['EXISTS'];
953 $iNumberOfMessages = $aMailbox['TOTAL'][$iSetIndx];
954 $iEnd = min ( $iEnd, $iNumberOfMessages );
956 $php_self = $PHP_SELF;
958 $urlMailbox = urlencode($aMailbox['NAME']);
960 if (preg_match('/^(.+)\?.+$/',$php_self,$regs)) {
961 $source_url = $regs[1];
963 $source_url = $php_self;
966 $baseurl = $source_url.'?mailbox=' . urlencode($aMailbox['NAME']) .'&account='.$aMailbox['ACCOUNT'];
967 $where = urlencode($aMailbox['SEARCH'][$iSetIndx][0]);
968 $what = urlencode($aMailbox['SEARCH'][$iSetIndx][1]);
969 $baseurl .= '&where=' . $where . '&what=' . $what;
971 /* build thread sorting links */
972 $newsort = $aMailbox['SORT'];
973 if (sqimap_capability($imapConnection,'THREAD')) {
974 if ($aMailbox['SORT'] & SQSORT_THREAD
) {
975 $newsort -= SQSORT_THREAD
;
976 $thread_name = _("Unthread View");
978 $thread_name = _("Thread View");
979 $newsort = $aMailbox['SORT'] + SQSORT_THREAD
;
981 $thread_link_str = '<small>[<a href="' . $baseurl . '&srt='
982 . $newsort . '&startMessage=1">' . $thread_name
985 $thread_link_str ='';
987 $sort = $aMailbox['SORT'];
989 /* FIX ME ADD CHECKBOX CONTROL. No checkbox => no buttons */
993 /* future admin control over displayable buttons */
995 $aAdminControl = array(
996 'markUnflagged' => 1,
1002 'undeleteButton'=> 1,
1003 'bypass_trash' => 1,
1004 'expungeButton' => 1,
1007 /* user prefs control */
1008 $aUserControl = array (
1010 'markUnflagged' => $show_flag_buttons,
1011 'markFlagged' => $show_flag_buttons,
1016 'undeleteButton'=> 1,
1017 'bypass_trash' => 1,
1018 'expungeButton' => 1,
1023 $showDelete = ($aMailbox['RIGHTS'] != 'READ-ONLY' &&
1024 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ?
true : false;
1025 $showByPassTrash = (($aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
1026 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) &&
1027 $trash_folder) ?
true : false; //
1029 $showUndelete = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
1030 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true) && !$trash_folder) ?
true : false;
1031 $showMove = ($aMailbox['RIGHTS'] != 'READ-ONLY') ?
true : false;
1032 $showExpunge = (!$aMailbox['AUTO_EXPUNGE'] && $aMailbox['RIGHTS'] != 'READ-ONLY' &&
1033 in_array('\\deleted',$aMailbox['PERMANENTFLAGS'], true)) ?
true : false;
1034 $aImapControl = array (
1035 'markUnflagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
1036 'markFlagged' => in_array('\\flagged',$aMailbox['PERMANENTFLAGS'], true),
1037 'markRead' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
1038 'markUnread' => in_array('\\seen',$aMailbox['PERMANENTFLAGS'], true),
1040 'delete' => $showDelete,
1041 'undeleteButton'=> $showUndelete,
1042 'bypass_trash' => $showByPassTrash,
1043 'expungeButton' => $showExpunge,
1044 'moveButton' => $showMove
1046 $aButtonStrings = array(
1047 'markUnflagged' => _("Unflag"),
1048 'markFlagged' => _("Flag"),
1049 'markRead' => _("Read"),
1050 'markUnread' => _("Unread"),
1051 'forward' => _("Forward"),
1052 'delete' => _("Delete"),
1053 'undeleteButton' => _("Undelete"),
1054 'bypass_trash' => _("Bypass Trash"),
1055 'expungeButton' => _("Expunge"),
1056 'moveButton' => _("Move")
1061 * Register buttons in order to an array
1062 * The key is the "name", the first element of the value array is the "value", second argument is the type.
1064 $aFormElements = array();
1065 foreach($aAdminControl as $k => $v) {
1066 if ($v & $aUserControl[$k] & $aImapControl[$k]) {
1068 case 'markUnflagged':
1073 case 'undeleteButton':
1074 case 'expungeButton':
1076 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1078 case 'bypass_trash':
1079 $aFormElements[$k] = array($aButtonStrings[$k],'checkbox');
1082 $aFormElements['targetMailbox'] =
1083 array(sqimap_mailbox_option_list($imapConnection, array(strtolower($lastTargetMailbox)), 0, $boxes),'select');
1084 $aFormElements['mailbox'] = array($aMailbox['NAME'],'hidden');
1085 $aFormElements['startMessage'] = array($aMailbox['PAGEOFFSET'],'hidden');
1086 $aFormElements[$k] = array($aButtonStrings[$k],'submit');
1090 $aFormElements['account'] = array($iAccount,'hidden');
1094 * This is the beginning of the message list table.
1095 * It wraps around all messages
1097 $safe_name = preg_replace("/[^0-9A-Za-z_]/", '_', $aMailbox['NAME']);
1098 $form_name = "FormMsgs" . $safe_name;
1100 //if (!sqgetGlobalVar('align',$align,SQ_SESSION)) {
1101 $align = array('left' => 'left', 'right' => 'right');
1103 //sm_print_r($align);
1105 /* finally set the template vars */
1107 // FIX ME, before we support multiple templates we must review the names of the vars
1110 $aTemplate['color'] = $color;
1111 $aTemplate['form_name'] = "FormMsgs" . $safe_name;
1112 $aTemplate['form_id'] = 'mbx_'.$iFormId;
1113 $aTemplate['page_selector'] = $page_selector;
1114 $aTemplate['page_selector_max'] = $page_selector_max;
1115 $aTemplate['messagesPerPage'] = $aMailbox['LIMIT'];
1116 $aTemplate['showall'] = $aMailbox['SHOWALL'][$iSetIndx];
1117 $aTemplate['end_msg'] = $iEnd;
1118 $aTemplate['align'] = $align;
1119 $aTemplate['iNumberOfMessages'] = $iNumberOfMessages;
1120 $aTemplate['aOrder'] = $aOrder;
1121 $aTemplate['aFormElements'] = $aFormElements;
1122 $aTemplate['sort'] = $sort;
1123 $aTemplate['pageOffset'] = $aMailbox['PAGEOFFSET'];
1124 $aTemplate['baseurl'] = $baseurl;
1125 $aTemplate['aMessages'] =& $aMessages;
1126 $aTemplate['trash_folder'] = $trash_folder;
1127 $aTemplate['sent_folder'] = $sent_folder;
1128 $aTemplate['draft_folder'] = $draft_folder;
1129 $aTemplate['thread_link_str'] = $thread_link_str;
1130 $aTemplate['php_self'] = str_replace('&','&',$php_self);
1131 $aTemplate['mailbox'] = $sMailbox;
1132 $aTemplate['javascript_on'] = (isset($aProps['config']['javascript_on'])) ?
$aProps['config']['javascript_on'] : false;
1133 $aTemplate['enablesort'] = (isset($aProps['config']['enablesort'])) ?
$aProps['config']['enablesort'] : false;
1134 $aTemplate['icon_theme'] = (isset($aProps['config']['icon_theme'])) ?
$aProps['config']['icon_theme'] : false;
1135 $aTemplate['use_icons'] = (isset($aProps['config']['use_icons'])) ?
$aProps['config']['use_icons'] : false;
1136 $aTemplate['alt_index_colors'] = (isset($aProps['config']['alt_index_colors'])) ?
$aProps['config']['alt_index_colors'] : false;
1137 $aTemplate['fancy_index_highlite'] = $fancy_index_highlite;
1145 * Truncates a string and take care of html encoded characters
1147 * @param string $s string to truncate
1148 * @param int $iTrimAt Trim at nn characters
1149 * @return string Trimmed string
1151 function truncateWithEntities($s, $iTrimAt) {
1152 global $languages, $squirrelmail_language;
1154 $ent_strlen = strlen($s);
1155 if (($iTrimAt <= 0) ||
($ent_strlen <= $iTrimAt))
1158 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1159 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth')) {
1160 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_strimwidth', $s, $iTrimAt);
1163 * see if this is entities-encoded string
1164 * If so, Iterate through the whole string, find out
1165 * the real number of characters, and if more
1166 * than $iTrimAt, substr with an updated trim value.
1168 $trim_val = $iTrimAt;
1171 while ( $ent_loc < $trim_val && (($ent_loc = strpos($s, '&', $ent_offset)) !== false) &&
1172 (($ent_loc_end = strpos($s, ';', $ent_loc+
3)) !== false) ) {
1173 $trim_val +
= ($ent_loc_end-$ent_loc);
1174 $ent_offset = $ent_loc_end+
1;
1177 if (($trim_val > $iTrimAt) && ($ent_strlen > $trim_val) && (strpos($s,';',$trim_val) < ($trim_val +
6))) {
1178 $i = strpos($s,';',$trim_val);
1180 $trim_val = strpos($s,';',$trim_val)+
1;
1183 // only print '...' when we're actually dropping part of the subject
1184 if ($ent_strlen <= $trim_val)
1187 return substr_replace($s, '...', $trim_val);
1192 * This should go in imap_mailbox.php
1193 * @param string $mailbox
1195 function handleAsSent($mailbox) {
1196 global $handleAsSent_result;
1198 /* First check if this is the sent or draft folder. */
1199 $handleAsSent_result = isSentMailbox($mailbox) ||
isDraftMailbox($mailbox);
1201 /* Then check the result of the handleAsSent hook. */
1202 do_hook('check_handleAsSent_result', $mailbox);
1204 /* And return the result. */
1205 return $handleAsSent_result;
1209 * Process messages list form and handle the cache gracefully. If $sButton and
1210 * $aUid are provided as argument then you can fake a message list submit and
1211 * use it i.e. in read_body.php for del move next and update the cache
1213 * @param resource $imapConnection imap connection
1214 * @param array $aMailbox (reference) cached mailbox
1215 * @param string $sButton fake a submit button
1216 * @param array $aUid fake the $msg array
1217 * @return string $sError error string in case of an error
1219 * @author Marc Groot Koerkamp
1221 function handleMessageListForm($imapConnection,&$aMailbox,$sButton='',$aUid = array()) {
1222 /* incoming formdata */
1223 $sButton = (sqgetGlobalVar('moveButton', $sTmp, SQ_POST
)) ?
'move' : $sButton;
1224 $sButton = (sqgetGlobalVar('expungeButton', $sTmp, SQ_POST
)) ?
'expunge' : $sButton;
1225 $sButton = (sqgetGlobalVar('forward', $sTmp, SQ_POST
)) ?
'forward' : $sButton;
1226 $sButton = (sqgetGlobalVar('delete', $sTmp, SQ_POST
)) ?
'setDeleted' : $sButton;
1227 $sButton = (sqgetGlobalVar('undeleteButton', $sTmp, SQ_POST
)) ?
'unsetDeleted' : $sButton;
1228 $sButton = (sqgetGlobalVar('markRead', $sTmp, SQ_POST
)) ?
'setSeen' : $sButton;
1229 $sButton = (sqgetGlobalVar('markUnread', $sTmp, SQ_POST
)) ?
'unsetSeen' : $sButton;
1230 $sButton = (sqgetGlobalVar('markFlagged', $sTmp, SQ_POST
)) ?
'setFlagged' : $sButton;
1231 $sButton = (sqgetGlobalVar('markUnflagged', $sTmp, SQ_POST
)) ?
'unsetFlagged' : $sButton;
1232 sqgetGlobalVar('targetMailbox', $targetMailbox, SQ_POST
);
1233 sqgetGlobalVar('bypass_trash', $bypass_trash, SQ_POST
);
1234 sqgetGlobalVar('msg', $msg, SQ_POST
);
1235 if (sqgetGlobalVar('account', $iAccount, SQ_POST
) === false) {
1239 $mailbox = $aMailbox['NAME'];
1241 /* retrieve the check boxes */
1242 $aUid = (isset($msg) && is_array($msg)) ?
array_values($msg) : $aUid;
1243 if (count($aUid) && $sButton != 'expunge') {
1244 $aUpdatedMsgs = false;
1248 // check if id exists in case we come from read_body
1249 if (count($aUid) == 1 && is_array($aMailbox['UIDSET'][$aMailbox['SETINDEX']]) &&
1250 !in_array($aUid[0],$aMailbox['UIDSET'][$aMailbox['SETINDEX']])) {
1253 $aUpdatedMsgs = sqimap_msgs_list_delete($imapConnection, $mailbox, $aUid,$bypass_trash);
1257 case 'unsetDeleted':
1261 case 'unsetFlagged':
1263 $sFlag = (substr($sButton,0,3) == 'set') ?
'\\'.substr($sButton,3) : '\\'.substr($sButton,5);
1264 $bSet = (substr($sButton,0,3) == 'set') ?
true : false;
1265 $aUpdatedMsgs = sqimap_toggle_flag($imapConnection, $aUid, $sFlag, $bSet, true);
1268 $aUpdatedMsgs = sqimap_msgs_list_move($imapConnection,$aUid,$targetMailbox);
1269 sqsession_register($targetMailbox,'lastTargetMailbox');
1273 $aMsgHeaders = array();
1274 foreach ($aUid as $iUid) {
1275 $aMsgHeaders[$iUid] = $aMailbox['MSG_HEADERS'][$iUid];
1277 if (count($aMsgHeaders)) {
1278 $composesession = attachSelectedMessages($imapConnection,$aMsgHeaders);
1279 // dirty hack, add info to $aMailbox
1280 $aMailbox['FORWARD_SESSION'] = $composesession;
1284 // Hook for plugin buttons
1285 do_hook_function('mailbox_display_button_action', $aUid);
1289 * Updates messages is an array containing the result of the untagged
1290 * fetch responses send by the imap server due to a flag change. That
1291 * response is parsed in a array with msg arrays by the parseFetch function
1293 if ($aUpdatedMsgs) {
1294 // Update the message headers cache
1295 $aDeleted = array();
1296 foreach ($aUpdatedMsgs as $iUid => $aMsg) {
1297 if (isset($aMsg['FLAGS'])) {
1299 * Only update the cached headers if the header is
1302 if (isset($aMailbox['MSG_HEADERS'][$iUid])) {
1303 $aMailbox['MSG_HEADERS'][$iUid]['FLAGS'] = $aMsg['FLAGS'];
1306 * Count the messages with the \Delete flag set so we can determine
1307 * if the number of expunged messages equals the number of flagged
1308 * messages for deletion.
1310 if (isset($aMsg['FLAGS']['\\deleted']) && $aMsg['FLAGS']['\\deleted']) {
1311 $aDeleted[] = $iUid;
1315 if ($bExpunge && $aMailbox['AUTO_EXPUNGE'] &&
1316 $iExpungedMessages = sqimap_mailbox_expunge($imapConnection, $aMailbox['NAME'], true))
1318 if (count($aDeleted) != $iExpungedMessages) {
1319 // there are more messages deleted permanently then we expected
1320 // invalidate the cache
1321 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = false;
1322 $aMailbox['MSG_HEADERS'] = false;
1324 // remove expunged messages from cache
1325 $aUidSet = $aMailbox['UIDSET'][$aMailbox['SETINDEX']];
1326 if (is_array($aUidSet)) {
1327 // create a UID => array index temp array
1328 $aUidSetDummy = array_flip($aUidSet);
1329 foreach ($aDeleted as $iUid) {
1330 // get the id as well in case of SQM_SORT_NONE
1331 if ($aMailbox['SORT'] == SQSORT_NONE
) {
1332 $aMailbox['ID'] = false;
1333 //$iId = $aMailbox['MSG_HEADERS'][$iUid]['ID'];
1334 //unset($aMailbox['ID'][$iId]);
1336 // unset the UID and message header
1337 unset($aUidSetDummy[$iUid]);
1338 unset($aMailbox['MSG_HEADERS'][$iUid]);
1340 $aMailbox['UIDSET'][$aMailbox['SETINDEX']] = array_keys($aUidSetDummy);
1343 // update EXISTS info
1344 if ($iExpungedMessages) {
1345 $aMailbox['EXISTS'] -= (int) $iExpungedMessages;
1346 $aMailbox['TOTAL'][$aMailbox['SETINDEX']] -= (int) $iExpungedMessages;
1348 if (($aMailbox['PAGEOFFSET']-1) >= $aMailbox['EXISTS']) {
1349 $aMailbox['PAGEOFFSET'] = ($aMailbox['PAGEOFFSET'] > $aMailbox['LIMIT']) ?
1350 $aMailbox['PAGEOFFSET'] - $aMailbox['LIMIT'] : 1;
1351 $aMailbox['OFFSET'] = $aMailbox['PAGEOFFSET'] - 1 ;
1356 if ($sButton == 'expunge') {
1358 * on expunge we do not know which messages will be deleted
1359 * so it's useless to try to sync the cache
1361 * Close the mailbox so we do not need to parse the untagged expunge
1362 * responses which do not contain uid info.
1363 * NB: Closing a mailbox is faster then expunge because the imap
1364 * server does not need to generate the untagged expunge responses
1366 sqimap_run_command($imapConnection,'CLOSE',false,$result,$message);
1367 $aMailbox = sqm_api_mailbox_select($imapConnection,$iAccount, $aMailbox['NAME'],array(),array());
1370 $sError = _("No messages were selected.");
1378 * Attach messages to a compose session
1380 * @param resource $imapConnection imap connection
1381 * @param array $aMsgHeaders
1382 * @return int $composesession unique compose_session_id where the attached messages belong to
1383 * @author Marc Groot Koerkamp
1385 function attachSelectedMessages($imapConnection,$aMsgHeaders) {
1386 global $username, $attachment_dir,
1390 sqgetGlobalVar('composesession', $composesession, SQ_SESSION
);
1391 sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION
);
1392 if (!isset($compose_messages)||
is_null($compose_messages)) {
1393 $compose_messages = array();
1394 sqsession_register($compose_messages,'compose_messages');
1397 if (!$composesession) {
1398 $composesession = 1;
1399 sqsession_register($composesession,'composesession');
1402 sqsession_register($composesession,'composesession');
1405 $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
1407 $composeMessage = new Message();
1408 $rfc822_header = new Rfc822Header();
1409 $composeMessage->rfc822_header
= $rfc822_header;
1410 $composeMessage->reply_rfc822_header
= '';
1412 foreach($aMsgHeaders as $iUid => $aMsgHeader) {
1414 * Retrieve the full message
1416 $body_a = sqimap_run_command($imapConnection, "FETCH $iUid RFC822", true, $response, $readmessage, TRUE);
1417 if ($response == 'OK') {
1419 $subject = (isset($aMsgHeader['subject'])) ?
$aMsgHeader['subject'] : $iUid;
1421 array_shift($body_a);
1423 $body = implode('', $body_a);
1426 $localfilename = GenerateRandomString(32, 'FILE', 7);
1427 $full_localfilename = "$hashed_attachment_dir/$localfilename";
1429 $fp = fopen( $full_localfilename, 'wb');
1430 fwrite ($fp, $body);
1432 $composeMessage->initAttachment('message/rfc822',$subject.'.msg',
1433 $full_localfilename);
1437 $compose_messages[$composesession] = $composeMessage;
1438 sqsession_register($compose_messages,'compose_messages');
1439 return $composesession;