mailbox_display.php 68 KB

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