mailbox_display.php 59 KB

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