mime.php 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * Copyright (c) 1999-2005 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This contains the functions necessary to detect and decode MIME
  9. * messages.
  10. *
  11. * @version $Id$
  12. * @package squirrelmail
  13. */
  14. /** The typical includes... */
  15. require_once(SM_PATH . 'functions/imap.php');
  16. require_once(SM_PATH . 'functions/attachment_common.php');
  17. /* -------------------------------------------------------------------------- */
  18. /* MIME DECODING */
  19. /* -------------------------------------------------------------------------- */
  20. /**
  21. * Get the MIME structure
  22. *
  23. * This function gets the structure of a message and stores it in the "message" class.
  24. * It will return this object for use with all relevant header information and
  25. * fully parsed into the standard "message" object format.
  26. */
  27. function mime_structure ($bodystructure, $flags=array()) {
  28. /* Isolate the body structure and remove beginning and end parenthesis. */
  29. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  30. $read = trim(substr ($read, 0, -1));
  31. $i = 0;
  32. $msg = Message::parseStructure($read,$i);
  33. if (!is_object($msg)) {
  34. include_once(SM_PATH . 'functions/display_messages.php');
  35. global $color, $mailbox;
  36. /* removed urldecode because $_GET is auto urldecoded ??? */
  37. displayPageHeader( $color, $mailbox );
  38. $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
  39. $errormessage .= '<br />'._("the provided bodystructure by your imap-server").':<br /><br />';
  40. $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
  41. plain_error_message( $errormessage, $color );
  42. echo '</body></html>';
  43. exit;
  44. }
  45. if (count($flags)) {
  46. foreach ($flags as $flag) {
  47. $char = strtoupper($flag{1});
  48. switch ($char) {
  49. case 'S':
  50. if (strtolower($flag) == '\\seen') {
  51. $msg->is_seen = true;
  52. }
  53. break;
  54. case 'A':
  55. if (strtolower($flag) == '\\answered') {
  56. $msg->is_answered = true;
  57. }
  58. break;
  59. case 'D':
  60. if (strtolower($flag) == '\\deleted') {
  61. $msg->is_deleted = true;
  62. }
  63. break;
  64. case 'F':
  65. if (strtolower($flag) == '\\flagged') {
  66. $msg->is_flagged = true;
  67. }
  68. break;
  69. case 'M':
  70. if (strtolower($flag) == '$mdnsent') {
  71. $msg->is_mdnsent = true;
  72. }
  73. break;
  74. default:
  75. break;
  76. }
  77. }
  78. }
  79. // listEntities($msg);
  80. return $msg;
  81. }
  82. /* This starts the parsing of a particular structure. It is called recursively,
  83. * so it can be passed different structures. It returns an object of type
  84. * $message.
  85. * First, it checks to see if it is a multipart message. If it is, then it
  86. * handles that as it sees is necessary. If it is just a regular entity,
  87. * then it parses it and adds the necessary header information (by calling out
  88. * to mime_get_elements()
  89. */
  90. function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
  91. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  92. * that it is the first one. That is usually the case anyway.
  93. */
  94. if (!$ent_id) {
  95. $cmd = "FETCH $id BODY[]";
  96. } else {
  97. $cmd = "FETCH $id BODY[$ent_id]";
  98. }
  99. if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
  100. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
  101. do {
  102. $topline = trim(array_shift($data));
  103. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
  104. $wholemessage = implode('', $data);
  105. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  106. $ret = substr($wholemessage, 0, $regs[1]);
  107. /* There is some information in the content info header that could be important
  108. * in order to parse html messages. Let's get them here.
  109. */
  110. // if ($ret{0} == '<') {
  111. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
  112. // }
  113. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  114. $ret = $regs[1];
  115. } else {
  116. global $where, $what, $mailbox, $passed_id, $startMessage;
  117. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  118. if (isset($where) && isset($what)) {
  119. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  120. } else {
  121. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  122. }
  123. $par .= '&amp;response=' . urlencode($response) .
  124. '&amp;message=' . urlencode($message) .
  125. '&amp;topline=' . urlencode($topline);
  126. echo '<tt><br />' .
  127. '<table width="80%"><tr>' .
  128. '<tr><td colspan="2">' .
  129. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  130. '</td></tr>' .
  131. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  132. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  133. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  134. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  135. "</table><br /></tt></font><hr />";
  136. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
  137. array_shift($data);
  138. $wholemessage = implode('', $data);
  139. $ret = $wholemessage;
  140. }
  141. return $ret;
  142. }
  143. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
  144. /* Don't kill the connection if the browser is over a dialup
  145. * and it would take over 30 seconds to download it.
  146. * Don't call set_time_limit in safe mode.
  147. */
  148. if (!ini_get('safe_mode')) {
  149. set_time_limit(0);
  150. }
  151. /* in case of base64 encoded attachments, do not buffer them.
  152. Instead, echo the decoded attachment directly to screen */
  153. if (strtolower($encoding) == 'base64') {
  154. if (!$ent_id) {
  155. $query = "FETCH $id BODY[]";
  156. } else {
  157. $query = "FETCH $id BODY[$ent_id]";
  158. }
  159. sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode','php://stdout',true);
  160. } else {
  161. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  162. echo decodeBody($body, $encoding);
  163. }
  164. /*
  165. TODO, use the same method for quoted printable.
  166. However, I assume that quoted printable attachments aren't that large
  167. so the performancegain / memory usage drop will be minimal.
  168. If we decide to add that then we need to adapt sqimap_fread because
  169. we need to split te result on \n and fread doesn't stop at \n. That
  170. means we also should provide $results from sqimap_fread (by ref) to
  171. te function and set $no_return to false. The $filter function for
  172. quoted printable should handle unsetting of $results.
  173. */
  174. /*
  175. TODO 2: find out how we write to the output stream php://stdout. fwrite
  176. doesn't work because 'php://stdout isn't a stream.
  177. */
  178. return;
  179. /*
  180. fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
  181. $cnt = 0;
  182. $continue = true;
  183. $read = fgets ($imap_stream,8192);
  184. // This could be bad -- if the section has sqimap_session_id() . ' OK'
  185. // or similar, it will kill the download.
  186. while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
  187. if (trim($read) == ')==') {
  188. $read1 = $read;
  189. $read = fgets ($imap_stream,4096);
  190. if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
  191. return;
  192. } else {
  193. echo decodeBody($read1, $encoding) .
  194. decodeBody($read, $encoding);
  195. }
  196. } else if ($cnt) {
  197. echo decodeBody($read, $encoding);
  198. }
  199. $read = fgets ($imap_stream,4096);
  200. $cnt++;
  201. // break;
  202. }
  203. */
  204. }
  205. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  206. /* This is here for debugging purposes. It will print out a list
  207. * of all the entity IDs that are in the $message object.
  208. */
  209. function listEntities ($message) {
  210. if ($message) {
  211. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br />';
  212. for ($i = 0; isset($message->entities[$i]); $i++) {
  213. echo "$i : ";
  214. $msg = listEntities($message->entities[$i]);
  215. if ($msg) {
  216. echo "return: ";
  217. return $msg;
  218. }
  219. }
  220. }
  221. }
  222. function getPriorityStr($priority) {
  223. $priority_level = substr($priority,0,1);
  224. switch($priority_level) {
  225. /* Check for a higher then normal priority. */
  226. case '1':
  227. case '2':
  228. $priority_string = _("High");
  229. break;
  230. /* Check for a lower then normal priority. */
  231. case '4':
  232. case '5':
  233. $priority_string = _("Low");
  234. break;
  235. /* Check for a normal priority. */
  236. case '3':
  237. default:
  238. $priority_level = '3';
  239. $priority_string = _("Normal");
  240. break;
  241. }
  242. return $priority_string;
  243. }
  244. /* returns a $message object for a particular entity id */
  245. function getEntity ($message, $ent_id) {
  246. return $message->getEntity($ent_id);
  247. }
  248. /* translateText
  249. * Extracted from strings.php 23/03/2002
  250. */
  251. function translateText(&$body, $wrap_at, $charset) {
  252. global $where, $what; /* from searching */
  253. global $color; /* color theme */
  254. require_once(SM_PATH . 'functions/url_parser.php');
  255. $body_ary = explode("\n", $body);
  256. for ($i=0; $i < count($body_ary); $i++) {
  257. $line = $body_ary[$i];
  258. if (strlen($line) - 2 >= $wrap_at) {
  259. sqWordWrap($line, $wrap_at, $charset);
  260. }
  261. $line = charset_decode($charset, $line);
  262. $line = str_replace("\t", ' ', $line);
  263. parseUrl ($line);
  264. $quotes = 0;
  265. $pos = 0;
  266. $j = strlen($line);
  267. while ($pos < $j) {
  268. if ($line[$pos] == ' ') {
  269. $pos++;
  270. } else if (strpos($line, '&gt;', $pos) === $pos) {
  271. $pos += 4;
  272. $quotes++;
  273. } else {
  274. break;
  275. }
  276. }
  277. if ($quotes % 2) {
  278. if (!isset($color[13])) {
  279. $color[13] = '#800000';
  280. }
  281. $line = '<font color="' . $color[13] . '">' . $line . '</font>';
  282. } elseif ($quotes) {
  283. if (!isset($color[14])) {
  284. $color[14] = '#FF0000';
  285. }
  286. $line = '<font color="' . $color[14] . '">' . $line . '</font>';
  287. }
  288. $body_ary[$i] = $line;
  289. }
  290. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  291. }
  292. /**
  293. * This returns a parsed string called $body. That string can then
  294. * be displayed as the actual message in the HTML. It contains
  295. * everything needed, including HTML Tags, Attachments at the
  296. * bottom, etc.
  297. * @param clean Do not output stuff that's irrelevant for the printable version.
  298. */
  299. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
  300. /* This if statement checks for the entity to show as the
  301. * primary message. To add more of them, just put them in the
  302. * order that is their priority.
  303. */
  304. global $startMessage, $languages, $squirrelmail_language,
  305. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
  306. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  307. $view_unsafe_images = false;
  308. }
  309. $body = '';
  310. $urlmailbox = urlencode($mailbox);
  311. $body_message = getEntity($message, $ent_num);
  312. if (($body_message->header->type0 == 'text') ||
  313. ($body_message->header->type0 == 'rfc822')) {
  314. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  315. $body = decodeBody($body, $body_message->header->encoding);
  316. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  317. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
  318. if (mb_detect_encoding($body) != 'ASCII') {
  319. $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
  320. }
  321. }
  322. $hookResults = do_hook("message_body", $body);
  323. $body = $hookResults[1];
  324. /* If there are other types that shouldn't be formatted, add
  325. * them here.
  326. */
  327. if ($body_message->header->type1 == 'html') {
  328. if ($show_html_default <> 1) {
  329. $entity_conv = array('&nbsp;' => ' ',
  330. '<p>' => "\n",
  331. '<P>' => "\n",
  332. '<br>' => "\n",
  333. '<BR>' => "\n",
  334. '<br />' => "\n",
  335. '<BR />' => "\n",
  336. '&gt;' => '>',
  337. '&lt;' => '<');
  338. $body = strtr($body, $entity_conv);
  339. $body = strip_tags($body);
  340. $body = trim($body);
  341. translateText($body, $wrap_at,
  342. $body_message->header->getParameter('charset'));
  343. } else {
  344. $body = magicHTML($body, $id, $message, $mailbox);
  345. }
  346. } else {
  347. translateText($body, $wrap_at,
  348. $body_message->header->getParameter('charset'));
  349. }
  350. // if this is the clean display (i.e. printer friendly), stop here.
  351. if ( $clean ) {
  352. return $body;
  353. }
  354. $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
  355. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  356. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  357. if (isset($passed_ent_id)) {
  358. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  359. }
  360. $body .= '<center><small><a href="download.php?absolute_dl=true&amp;' .
  361. $link . '">' . _("Download this as a file") . '</a>';
  362. if ($view_unsafe_images) {
  363. $text = _("Hide Unsafe Images");
  364. } else {
  365. if (isset($has_unsafe_images) && $has_unsafe_images) {
  366. $link .= '&amp;view_unsafe_images=1';
  367. $text = _("View Unsafe Images");
  368. } else {
  369. $text = '';
  370. }
  371. }
  372. if($text != '') {
  373. $body .= '&nbsp;|&nbsp;<a href="read_body.php?' . $link . '">' . $text . '</a>';
  374. }
  375. $body .= '</small></center><br />' . "\n";
  376. }
  377. return $body;
  378. }
  379. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  380. global $where, $what, $startMessage, $color, $passed_ent_id;
  381. $att_ar = $message->getAttachments($exclude_id);
  382. if (!count($att_ar)) return '';
  383. $attachments = '';
  384. $urlMailbox = urlencode($mailbox);
  385. foreach ($att_ar as $att) {
  386. $ent = $att->entity_id;
  387. $header = $att->header;
  388. $type0 = strtolower($header->type0);
  389. $type1 = strtolower($header->type1);
  390. $name = '';
  391. $links['download link']['text'] = _("Download");
  392. $links['download link']['href'] = SM_PATH .
  393. "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  394. if ($type0 =='message' && $type1 == 'rfc822') {
  395. $default_page = SM_PATH . 'src/read_body.php';
  396. $rfc822_header = $att->rfc822_header;
  397. $filename = $rfc822_header->subject;
  398. if (trim( $filename ) == '') {
  399. $filename = 'untitled-[' . $ent . ']' ;
  400. }
  401. $from_o = $rfc822_header->from;
  402. if (is_object($from_o)) {
  403. $from_name = decodeHeader($from_o->getAddress(false));
  404. } else {
  405. $from_name = _("Unknown sender");
  406. }
  407. $description = $from_name;
  408. } else {
  409. $default_page = SM_PATH . 'src/download.php';
  410. if (is_object($header->disposition)) {
  411. $filename = $header->disposition->getProperty('filename');
  412. if (trim($filename) == '') {
  413. $name = decodeHeader($header->disposition->getProperty('name'));
  414. if (trim($name) == '') {
  415. $name = $header->getParameter('name');
  416. if(trim($name) == '') {
  417. if (trim( $header->id ) == '') {
  418. $filename = 'untitled-[' . $ent . ']' ;
  419. } else {
  420. $filename = 'cid: ' . $header->id;
  421. }
  422. } else {
  423. $filename = $name;
  424. }
  425. } else {
  426. $filename = $name;
  427. }
  428. }
  429. } else {
  430. $filename = $header->getParameter('name');
  431. if (!trim($filename)) {
  432. if (trim( $header->id ) == '') {
  433. $filename = 'untitled-[' . $ent . ']' ;
  434. } else {
  435. $filename = 'cid: ' . $header->id;
  436. }
  437. }
  438. }
  439. if ($header->description) {
  440. $description = decodeHeader($header->description);
  441. } else {
  442. $description = '';
  443. }
  444. }
  445. $display_filename = $filename;
  446. if (isset($passed_ent_id)) {
  447. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  448. } else {
  449. $passed_ent_id_link = '';
  450. }
  451. $defaultlink = $default_page . "?startMessage=$startMessage"
  452. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  453. . '&amp;ent_id='.$ent.$passed_ent_id_link;
  454. if ($where && $what) {
  455. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  456. }
  457. /* This executes the attachment hook with a specific MIME-type.
  458. * If that doesn't have results, it tries if there's a rule
  459. * for a more generic type.
  460. */
  461. $hookresults = do_hook("attachment $type0/$type1", $links,
  462. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  463. $display_filename, $where, $what);
  464. if(count($hookresults[1]) <= 1) {
  465. $hookresults = do_hook("attachment $type0/*", $links,
  466. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  467. $display_filename, $where, $what);
  468. }
  469. $links = $hookresults[1];
  470. $defaultlink = $hookresults[6];
  471. $attachments .= '<tr><td>' .
  472. '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a>&nbsp;</td>' .
  473. '<td><small><b>' . show_readable_size($header->size) .
  474. '</b>&nbsp;&nbsp;</small></td>' .
  475. '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ]&nbsp;</small></td>' .
  476. '<td><small>';
  477. $attachments .= '<b>' . $description . '</b>';
  478. $attachments .= '</small></td><td><small>&nbsp;';
  479. $skipspaces = 1;
  480. foreach ($links as $val) {
  481. if ($skipspaces) {
  482. $skipspaces = 0;
  483. } else {
  484. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  485. }
  486. $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
  487. }
  488. unset($links);
  489. $attachments .= "</td></tr>\n";
  490. }
  491. $attachmentadd = do_hook_function('attachments_bottom',$attachments);
  492. if ($attachmentadd != '')
  493. $attachments = $attachmentadd;
  494. return $attachments;
  495. }
  496. function sqimap_base64_decode(&$string) {
  497. // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  498. // fly decoding (to reduce memory usage) you have to check if the
  499. // data has incomplete pairs
  500. // Remove the noise in order to check if the 4 bytes pairs are complete
  501. $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
  502. $sStringRem = '';
  503. $iMod = strlen($string) % 4;
  504. if ($iMod) {
  505. $sStringRem = substr($string,-$iMod);
  506. // Check if $sStringRem contains padding characters
  507. if (substr($sStringRem,-1) != '=') {
  508. $string = substr($string,0,-$iMod);
  509. } else {
  510. $sStringRem = '';
  511. }
  512. }
  513. $string = base64_decode($string);
  514. return $sStringRem;
  515. }
  516. /* This function decodes the body depending on the encoding type. */
  517. function decodeBody($body, $encoding) {
  518. global $show_html_default;
  519. $body = str_replace("\r\n", "\n", $body);
  520. $encoding = strtolower($encoding);
  521. $encoding_handler = do_hook_function('decode_body', $encoding);
  522. // plugins get first shot at decoding the body
  523. //
  524. if (!empty($encoding_handler) && function_exists($encoding_handler)) {
  525. $body = $encoding_handler('decode', $body);
  526. } else if ($encoding == 'quoted-printable' ||
  527. $encoding == 'quoted_printable') {
  528. $body = quoted_printable_decode($body);
  529. while (ereg("=\n", $body)) {
  530. $body = ereg_replace ("=\n", '', $body);
  531. }
  532. } else if ($encoding == 'base64') {
  533. $body = base64_decode($body);
  534. }
  535. // All other encodings are returned raw.
  536. return $body;
  537. }
  538. /**
  539. * Decodes headers
  540. *
  541. * This functions decode strings that is encoded according to
  542. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  543. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  544. *
  545. * @param string $string header string that has to be made readable
  546. * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
  547. * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
  548. * @param boolean $decide decide if string can be utfencoded. defaults to false
  549. * @return string decoded header string
  550. */
  551. function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
  552. global $languages, $squirrelmail_language,$default_charset;
  553. if (is_array($string)) {
  554. $string = implode("\n", $string);
  555. }
  556. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  557. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
  558. $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
  559. // Do we need to return at this point?
  560. // return $string;
  561. }
  562. $i = 0;
  563. $iLastMatch = -2;
  564. $encoded = true;
  565. $aString = explode(' ',$string);
  566. $ret = '';
  567. foreach ($aString as $chunk) {
  568. if ($encoded && $chunk === '') {
  569. continue;
  570. } elseif ($chunk === '') {
  571. $ret .= ' ';
  572. continue;
  573. }
  574. $encoded = false;
  575. /* if encoded words are not separated by a linear-space-white we still catch them */
  576. $j = $i-1;
  577. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  578. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  579. if ($iLastMatch !== $j) {
  580. if ($htmlsave) {
  581. $ret .= '&#32;';
  582. } else {
  583. $ret .= ' ';
  584. }
  585. }
  586. $iLastMatch = $i;
  587. $j = $i;
  588. if ($htmlsave) {
  589. $ret .= htmlspecialchars($res[1]);
  590. } else {
  591. $ret .= $res[1];
  592. }
  593. $encoding = ucfirst($res[3]);
  594. /* decide about valid decoding */
  595. if ($decide && is_conversion_safe($res[2])) {
  596. $utfencode=true;
  597. $can_be_encoded=true;
  598. } else {
  599. $can_be_encoded=false;
  600. }
  601. switch ($encoding)
  602. {
  603. case 'B':
  604. $replace = base64_decode($res[4]);
  605. if ($utfencode) {
  606. if ($can_be_encoded) {
  607. /* convert string to different charset,
  608. * if functions asks for it (usually in compose)
  609. */
  610. $ret .= charset_convert($res[2],$replace,$default_charset);
  611. } else {
  612. // convert string to html codes in order to display it
  613. $ret .= charset_decode($res[2],$replace);
  614. }
  615. } else {
  616. if ($htmlsave) {
  617. $replace = htmlspecialchars($replace);
  618. }
  619. $ret.= $replace;
  620. }
  621. break;
  622. case 'Q':
  623. $replace = str_replace('_', ' ', $res[4]);
  624. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  625. $replace);
  626. if ($utfencode) {
  627. if ($can_be_encoded) {
  628. /* convert string to different charset,
  629. * if functions asks for it (usually in compose)
  630. */
  631. $replace = charset_convert($res[2], $replace,$default_charset);
  632. } else {
  633. // convert string to html codes in order to display it
  634. $replace = charset_decode($res[2], $replace);
  635. }
  636. } else {
  637. if ($htmlsave) {
  638. $replace = htmlspecialchars($replace);
  639. }
  640. }
  641. $ret .= $replace;
  642. break;
  643. default:
  644. break;
  645. }
  646. $chunk = $res[5];
  647. $encoded = true;
  648. }
  649. if (!$encoded) {
  650. if ($htmlsave) {
  651. $ret .= '&#32;';
  652. } else {
  653. $ret .= ' ';
  654. }
  655. }
  656. if (!$encoded && $htmlsave) {
  657. $ret .= htmlspecialchars($chunk);
  658. } else {
  659. $ret .= $chunk;
  660. }
  661. ++$i;
  662. }
  663. /* remove the first added space */
  664. if ($ret) {
  665. if ($htmlsave) {
  666. $ret = substr($ret,5);
  667. } else {
  668. $ret = substr($ret,1);
  669. }
  670. }
  671. return $ret;
  672. }
  673. /**
  674. * Encodes header as quoted-printable
  675. *
  676. * Encode a string according to RFC 1522 for use in headers if it
  677. * contains 8-bit characters or anything that looks like it should
  678. * be encoded.
  679. *
  680. * @param string $string header string, that has to be encoded
  681. * @return string quoted-printable encoded string
  682. */
  683. function encodeHeader ($string) {
  684. global $default_charset, $languages, $squirrelmail_language;
  685. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  686. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
  687. return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
  688. }
  689. // Encode only if the string contains 8-bit characters or =?
  690. $j = strlen($string);
  691. $max_l = 75 - strlen($default_charset) - 7;
  692. $aRet = array();
  693. $ret = '';
  694. $iEncStart = $enc_init = false;
  695. $cur_l = $iOffset = 0;
  696. for($i = 0; $i < $j; ++$i) {
  697. switch($string{$i})
  698. {
  699. case '=':
  700. case '<':
  701. case '>':
  702. case ',':
  703. case '?':
  704. case '_':
  705. if ($iEncStart === false) {
  706. $iEncStart = $i;
  707. }
  708. $cur_l+=3;
  709. if ($cur_l > ($max_l-2)) {
  710. /* if there is an stringpart that doesn't need encoding, add it */
  711. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  712. $aRet[] = "=?$default_charset?Q?$ret?=";
  713. $iOffset = $i;
  714. $cur_l = 0;
  715. $ret = '';
  716. $iEncStart = false;
  717. } else {
  718. $ret .= sprintf("=%02X",ord($string{$i}));
  719. }
  720. break;
  721. case '(':
  722. case ')':
  723. if ($iEncStart !== false) {
  724. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  725. $aRet[] = "=?$default_charset?Q?$ret?=";
  726. $iOffset = $i;
  727. $cur_l = 0;
  728. $ret = '';
  729. $iEncStart = false;
  730. }
  731. break;
  732. case ' ':
  733. if ($iEncStart !== false) {
  734. $cur_l++;
  735. if ($cur_l > $max_l) {
  736. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  737. $aRet[] = "=?$default_charset?Q?$ret?=";
  738. $iOffset = $i;
  739. $cur_l = 0;
  740. $ret = '';
  741. $iEncStart = false;
  742. } else {
  743. $ret .= '_';
  744. }
  745. }
  746. break;
  747. default:
  748. $k = ord($string{$i});
  749. if ($k > 126) {
  750. if ($iEncStart === false) {
  751. // do not start encoding in the middle of a string, also take the rest of the word.
  752. $sLeadString = substr($string,0,$i);
  753. $aLeadString = explode(' ',$sLeadString);
  754. $sToBeEncoded = array_pop($aLeadString);
  755. $iEncStart = $i - strlen($sToBeEncoded);
  756. $ret .= $sToBeEncoded;
  757. $cur_l += strlen($sToBeEncoded);
  758. }
  759. $cur_l += 3;
  760. /* first we add the encoded string that reached it's max size */
  761. if ($cur_l > ($max_l-2)) {
  762. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  763. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  764. $cur_l = 3;
  765. $ret = '';
  766. $iOffset = $i;
  767. $iEncStart = $i;
  768. }
  769. $enc_init = true;
  770. $ret .= sprintf("=%02X", $k);
  771. } else {
  772. if ($iEncStart !== false) {
  773. $cur_l++;
  774. if ($cur_l > $max_l) {
  775. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  776. $aRet[] = "=?$default_charset?Q?$ret?=";
  777. $iEncStart = false;
  778. $iOffset = $i;
  779. $cur_l = 0;
  780. $ret = '';
  781. } else {
  782. $ret .= $string{$i};
  783. }
  784. }
  785. }
  786. break;
  787. }
  788. }
  789. if ($enc_init) {
  790. if ($iEncStart !== false) {
  791. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  792. $aRet[] = "=?$default_charset?Q?$ret?=";
  793. } else {
  794. $aRet[] = substr($string,$iOffset);
  795. }
  796. $string = implode('',$aRet);
  797. }
  798. return $string;
  799. }
  800. /* This function trys to locate the entity_id of a specific mime element */
  801. function find_ent_id($id, $message) {
  802. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  803. if ($message->entities[$i]->header->type0 == 'multipart') {
  804. $ret = find_ent_id($id, $message->entities[$i]);
  805. } else {
  806. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  807. // if (sq_check_save_extension($message->entities[$i])) {
  808. return $message->entities[$i]->entity_id;
  809. // }
  810. }
  811. }
  812. }
  813. return $ret;
  814. }
  815. function sq_check_save_extension($message) {
  816. $filename = $message->getFilename();
  817. $ext = substr($filename, strrpos($filename,'.')+1);
  818. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  819. return in_array($ext, $save_extensions);
  820. }
  821. /**
  822. ** HTMLFILTER ROUTINES
  823. */
  824. /**
  825. * This function is more or less a wrapper around stripslashes. Apparently
  826. * Explorer is stupid enough to just remove the backslashes and then
  827. * execute the content of the attribute as if nothing happened.
  828. * Who does that?
  829. *
  830. * @param attvalue The value of the attribute
  831. * @return attvalue The value of the attribute stripslashed.
  832. */
  833. function sq_unbackslash($attvalue){
  834. /**
  835. * Remove any backslashes. See if there are any first.
  836. */
  837. if (strstr($attvalue, '\\') !== false){
  838. $attvalue = stripslashes($attvalue);
  839. }
  840. return $attvalue;
  841. }
  842. /**
  843. * Kill any tabs, newlines, or carriage returns. Our friends the
  844. * makers of the browser with 95% market value decided that it'd
  845. * be funny to make "java[tab]script" be just as good as "javascript".
  846. *
  847. * @param attvalue The attribute value before extraneous spaces removed.
  848. * @return attvalue The attribute value after extraneous spaces removed.
  849. */
  850. function sq_unspace($attvalue){
  851. if (strcspn($attvalue, "\t\r\n") != strlen($attvalue)){
  852. $attvalue = str_replace(Array("\t", "\r", "\n"), Array('', '', ''),
  853. $attvalue);
  854. }
  855. return $attvalue;
  856. }
  857. /**
  858. * This function returns the final tag out of the tag name, an array
  859. * of attributes, and the type of the tag. This function is called by
  860. * sq_sanitize internally.
  861. *
  862. * @param $tagname the name of the tag.
  863. * @param $attary the array of attributes and their values
  864. * @param $tagtype The type of the tag (see in comments).
  865. * @return a string with the final tag representation.
  866. */
  867. function sq_tagprint($tagname, $attary, $tagtype){
  868. $me = 'sq_tagprint';
  869. if ($tagtype == 2){
  870. $fulltag = '</' . $tagname . '>';
  871. } else {
  872. $fulltag = '<' . $tagname;
  873. if (is_array($attary) && sizeof($attary)){
  874. $atts = Array();
  875. while (list($attname, $attvalue) = each($attary)){
  876. array_push($atts, "$attname=$attvalue");
  877. }
  878. $fulltag .= ' ' . join(" ", $atts);
  879. }
  880. if ($tagtype == 3){
  881. $fulltag .= ' /';
  882. }
  883. $fulltag .= '>';
  884. }
  885. return $fulltag;
  886. }
  887. /**
  888. * A small helper function to use with array_walk. Modifies a by-ref
  889. * value and makes it lowercase.
  890. *
  891. * @param $val a value passed by-ref.
  892. * @return void since it modifies a by-ref value.
  893. */
  894. function sq_casenormalize(&$val){
  895. $val = strtolower($val);
  896. }
  897. /**
  898. * This function skips any whitespace from the current position within
  899. * a string and to the next non-whitespace value.
  900. *
  901. * @param $body the string
  902. * @param $offset the offset within the string where we should start
  903. * looking for the next non-whitespace character.
  904. * @return the location within the $body where the next
  905. * non-whitespace char is located.
  906. */
  907. function sq_skipspace($body, $offset){
  908. $me = 'sq_skipspace';
  909. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  910. if (sizeof($matches{1})){
  911. $count = strlen($matches{1});
  912. $offset += $count;
  913. }
  914. return $offset;
  915. }
  916. /**
  917. * This function looks for the next character within a string. It's
  918. * really just a glorified "strpos", except it catches if failures
  919. * nicely.
  920. *
  921. * @param $body The string to look for needle in.
  922. * @param $offset Start looking from this position.
  923. * @param $needle The character/string to look for.
  924. * @return location of the next occurance of the needle, or
  925. * strlen($body) if needle wasn't found.
  926. */
  927. function sq_findnxstr($body, $offset, $needle){
  928. $me = 'sq_findnxstr';
  929. $pos = strpos($body, $needle, $offset);
  930. if ($pos === FALSE){
  931. $pos = strlen($body);
  932. }
  933. return $pos;
  934. }
  935. /**
  936. * This function takes a PCRE-style regexp and tries to match it
  937. * within the string.
  938. *
  939. * @param $body The string to look for needle in.
  940. * @param $offset Start looking from here.
  941. * @param $reg A PCRE-style regex to match.
  942. * @return Returns a false if no matches found, or an array
  943. * with the following members:
  944. * - integer with the location of the match within $body
  945. * - string with whatever content between offset and the match
  946. * - string with whatever it is we matched
  947. */
  948. function sq_findnxreg($body, $offset, $reg){
  949. $me = 'sq_findnxreg';
  950. $matches = Array();
  951. $retarr = Array();
  952. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  953. if (!isset($matches{0}) || !$matches{0}){
  954. $retarr = false;
  955. } else {
  956. $retarr{0} = $offset + strlen($matches{1});
  957. $retarr{1} = $matches{1};
  958. $retarr{2} = $matches{2};
  959. }
  960. return $retarr;
  961. }
  962. /**
  963. * This function looks for the next tag.
  964. *
  965. * @param $body String where to look for the next tag.
  966. * @param $offset Start looking from here.
  967. * @return false if no more tags exist in the body, or
  968. * an array with the following members:
  969. * - string with the name of the tag
  970. * - array with attributes and their values
  971. * - integer with tag type (1, 2, or 3)
  972. * - integer where the tag starts (starting "<")
  973. * - integer where the tag ends (ending ">")
  974. * first three members will be false, if the tag is invalid.
  975. */
  976. function sq_getnxtag($body, $offset){
  977. $me = 'sq_getnxtag';
  978. if ($offset > strlen($body)){
  979. return false;
  980. }
  981. $lt = sq_findnxstr($body, $offset, "<");
  982. if ($lt == strlen($body)){
  983. return false;
  984. }
  985. /**
  986. * We are here:
  987. * blah blah <tag attribute="value">
  988. * \---------^
  989. */
  990. $pos = sq_skipspace($body, $lt+1);
  991. if ($pos >= strlen($body)){
  992. return Array(false, false, false, $lt, strlen($body));
  993. }
  994. /**
  995. * There are 3 kinds of tags:
  996. * 1. Opening tag, e.g.:
  997. * <a href="blah">
  998. * 2. Closing tag, e.g.:
  999. * </a>
  1000. * 3. XHTML-style content-less tag, e.g.:
  1001. * <img src="blah" />
  1002. */
  1003. $tagtype = false;
  1004. switch (substr($body, $pos, 1)){
  1005. case '/':
  1006. $tagtype = 2;
  1007. $pos++;
  1008. break;
  1009. case '!':
  1010. /**
  1011. * A comment or an SGML declaration.
  1012. */
  1013. if (substr($body, $pos+1, 2) == "--"){
  1014. $gt = strpos($body, "-->", $pos);
  1015. if ($gt === false){
  1016. $gt = strlen($body);
  1017. } else {
  1018. $gt += 2;
  1019. }
  1020. return Array(false, false, false, $lt, $gt);
  1021. } else {
  1022. $gt = sq_findnxstr($body, $pos, ">");
  1023. return Array(false, false, false, $lt, $gt);
  1024. }
  1025. break;
  1026. default:
  1027. /**
  1028. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1029. * later.
  1030. */
  1031. $tagtype = 1;
  1032. break;
  1033. }
  1034. $tagname = '';
  1035. /**
  1036. * Look for next [\W-_], which will indicate the end of the tag name.
  1037. */
  1038. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1039. if ($regary == false){
  1040. return Array(false, false, false, $lt, strlen($body));
  1041. }
  1042. list($pos, $tagname, $match) = $regary;
  1043. $tagname = strtolower($tagname);
  1044. /**
  1045. * $match can be either of these:
  1046. * '>' indicating the end of the tag entirely.
  1047. * '\s' indicating the end of the tag name.
  1048. * '/' indicating that this is type-3 xhtml tag.
  1049. *
  1050. * Whatever else we find there indicates an invalid tag.
  1051. */
  1052. switch ($match){
  1053. case '/':
  1054. /**
  1055. * This is an xhtml-style tag with a closing / at the
  1056. * end, like so: <img src="blah" />. Check if it's followed
  1057. * by the closing bracket. If not, then this tag is invalid
  1058. */
  1059. if (substr($body, $pos, 2) == "/>"){
  1060. $pos++;
  1061. $tagtype = 3;
  1062. } else {
  1063. $gt = sq_findnxstr($body, $pos, ">");
  1064. $retary = Array(false, false, false, $lt, $gt);
  1065. return $retary;
  1066. }
  1067. case '>':
  1068. return Array($tagname, false, $tagtype, $lt, $pos);
  1069. break;
  1070. default:
  1071. /**
  1072. * Check if it's whitespace
  1073. */
  1074. if (!preg_match('/\s/', $match)){
  1075. /**
  1076. * This is an invalid tag! Look for the next closing ">".
  1077. */
  1078. $gt = sq_findnxstr($body, $lt, ">");
  1079. return Array(false, false, false, $lt, $gt);
  1080. }
  1081. break;
  1082. }
  1083. /**
  1084. * At this point we're here:
  1085. * <tagname attribute='blah'>
  1086. * \-------^
  1087. *
  1088. * At this point we loop in order to find all attributes.
  1089. */
  1090. $attname = '';
  1091. $attary = Array();
  1092. while ($pos <= strlen($body)){
  1093. $pos = sq_skipspace($body, $pos);
  1094. if ($pos == strlen($body)){
  1095. /**
  1096. * Non-closed tag.
  1097. */
  1098. return Array(false, false, false, $lt, $pos);
  1099. }
  1100. /**
  1101. * See if we arrived at a ">" or "/>", which means that we reached
  1102. * the end of the tag.
  1103. */
  1104. $matches = Array();
  1105. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  1106. /**
  1107. * Yep. So we did.
  1108. */
  1109. $pos += strlen($matches{1});
  1110. if ($matches{2} == "/>"){
  1111. $tagtype = 3;
  1112. $pos++;
  1113. }
  1114. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1115. }
  1116. /**
  1117. * There are several types of attributes, with optional
  1118. * [:space:] between members.
  1119. * Type 1:
  1120. * attrname[:space:]=[:space:]'CDATA'
  1121. * Type 2:
  1122. * attrname[:space:]=[:space:]"CDATA"
  1123. * Type 3:
  1124. * attr[:space:]=[:space:]CDATA
  1125. * Type 4:
  1126. * attrname
  1127. *
  1128. * We leave types 1 and 2 the same, type 3 we check for
  1129. * '"' and convert to "&quot" if needed, then wrap in
  1130. * double quotes. Type 4 we convert into:
  1131. * attrname="yes".
  1132. */
  1133. $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
  1134. if ($regary == false){
  1135. /**
  1136. * Looks like body ended before the end of tag.
  1137. */
  1138. return Array(false, false, false, $lt, strlen($body));
  1139. }
  1140. list($pos, $attname, $match) = $regary;
  1141. $attname = strtolower($attname);
  1142. /**
  1143. * We arrived at the end of attribute name. Several things possible
  1144. * here:
  1145. * '>' means the end of the tag and this is attribute type 4
  1146. * '/' if followed by '>' means the same thing as above
  1147. * '\s' means a lot of things -- look what it's followed by.
  1148. * anything else means the attribute is invalid.
  1149. */
  1150. switch($match){
  1151. case '/':
  1152. /**
  1153. * This is an xhtml-style tag with a closing / at the
  1154. * end, like so: <img src="blah" />. Check if it's followed
  1155. * by the closing bracket. If not, then this tag is invalid
  1156. */
  1157. if (substr($body, $pos, 2) == "/>"){
  1158. $pos++;
  1159. $tagtype = 3;
  1160. } else {
  1161. $gt = sq_findnxstr($body, $pos, ">");
  1162. $retary = Array(false, false, false, $lt, $gt);
  1163. return $retary;
  1164. }
  1165. case '>':
  1166. $attary{$attname} = '"yes"';
  1167. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1168. break;
  1169. default:
  1170. /**
  1171. * Skip whitespace and see what we arrive at.
  1172. */
  1173. $pos = sq_skipspace($body, $pos);
  1174. $char = substr($body, $pos, 1);
  1175. /**
  1176. * Two things are valid here:
  1177. * '=' means this is attribute type 1 2 or 3.
  1178. * \w means this was attribute type 4.
  1179. * anything else we ignore and re-loop. End of tag and
  1180. * invalid stuff will be caught by our checks at the beginning
  1181. * of the loop.
  1182. */
  1183. if ($char == "="){
  1184. $pos++;
  1185. $pos = sq_skipspace($body, $pos);
  1186. /**
  1187. * Here are 3 possibilities:
  1188. * "'" attribute type 1
  1189. * '"' attribute type 2
  1190. * everything else is the content of tag type 3
  1191. */
  1192. $quot = substr($body, $pos, 1);
  1193. if ($quot == "'"){
  1194. $regary = sq_findnxreg($body, $pos+1, "\'");
  1195. if ($regary == false){
  1196. return Array(false, false, false, $lt, strlen($body));
  1197. }
  1198. list($pos, $attval, $match) = $regary;
  1199. $pos++;
  1200. $attary{$attname} = "'" . $attval . "'";
  1201. } else if ($quot == '"'){
  1202. $regary = sq_findnxreg($body, $pos+1, '\"');
  1203. if ($regary == false){
  1204. return Array(false, false, false, $lt, strlen($body));
  1205. }
  1206. list($pos, $attval, $match) = $regary;
  1207. $pos++;
  1208. $attary{$attname} = '"' . $attval . '"';
  1209. } else {
  1210. /**
  1211. * These are hateful. Look for \s, or >.
  1212. */
  1213. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1214. if ($regary == false){
  1215. return Array(false, false, false, $lt, strlen($body));
  1216. }
  1217. list($pos, $attval, $match) = $regary;
  1218. /**
  1219. * If it's ">" it will be caught at the top.
  1220. */
  1221. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1222. $attary{$attname} = '"' . $attval . '"';
  1223. }
  1224. } else if (preg_match("|[\w/>]|", $char)) {
  1225. /**
  1226. * That was attribute type 4.
  1227. */
  1228. $attary{$attname} = '"yes"';
  1229. } else {
  1230. /**
  1231. * An illegal character. Find next '>' and return.
  1232. */
  1233. $gt = sq_findnxstr($body, $pos, ">");
  1234. return Array(false, false, false, $lt, $gt);
  1235. }
  1236. break;
  1237. }
  1238. }
  1239. /**
  1240. * The fact that we got here indicates that the tag end was never
  1241. * found. Return invalid tag indication so it gets stripped.
  1242. */
  1243. return Array(false, false, false, $lt, strlen($body));
  1244. }
  1245. /**
  1246. * This function checks attribute values for entity-encoded values
  1247. * and returns them translated into 8-bit strings so we can run
  1248. * checks on them.
  1249. *
  1250. * @param $attvalue A string to run entity check against.
  1251. * @return Translated value.
  1252. */
  1253. function sq_deent($attvalue){
  1254. $me = 'sq_deent';
  1255. /**
  1256. * See if we have to run the checks first. All entities must start
  1257. * with "&".
  1258. */
  1259. if (strpos($attvalue, '&') === false){
  1260. return $attvalue;
  1261. }
  1262. /**
  1263. * Check named entities first.
  1264. */
  1265. $trans = get_html_translation_table(HTML_ENTITIES);
  1266. /**
  1267. * Leave &quot; in, as it can mess us up.
  1268. */
  1269. $trans = array_flip($trans);
  1270. unset($trans{'&quot;'});
  1271. while (list($ent, $val) = each($trans)){
  1272. $attvalue = preg_replace('/' . $ent . '*/si', $val, $attvalue);
  1273. }
  1274. /**
  1275. * Now translate numbered entities from 1 to 255 if needed.
  1276. */
  1277. if (strpos($attvalue, '#') !== false){
  1278. $omit = Array(34, 39);
  1279. for ($asc = 256; $asc >= 0; $asc--){
  1280. if (!in_array($asc, $omit)){
  1281. $chr = chr($asc);
  1282. $octrule = '/\&#0*' . $asc . ';*/si';
  1283. $hexrule = '/\&#x0*' . dechex($asc) . ';*/si';
  1284. $attvalue = preg_replace($octrule, $chr, $attvalue);
  1285. $attvalue = preg_replace($hexrule, $chr, $attvalue);
  1286. }
  1287. }
  1288. }
  1289. return $attvalue;
  1290. }
  1291. /**
  1292. * This function runs various checks against the attributes.
  1293. *
  1294. * @param $tagname String with the name of the tag.
  1295. * @param $attary Array with all tag attributes.
  1296. * @param $rm_attnames See description for sq_sanitize
  1297. * @param $bad_attvals See description for sq_sanitize
  1298. * @param $add_attr_to_tag See description for sq_sanitize
  1299. * @param $message message object
  1300. * @param $id message id
  1301. * @return Array with modified attributes.
  1302. */
  1303. function sq_fixatts($tagname,
  1304. $attary,
  1305. $rm_attnames,
  1306. $bad_attvals,
  1307. $add_attr_to_tag,
  1308. $message,
  1309. $id,
  1310. $mailbox
  1311. ){
  1312. $me = 'sq_fixatts';
  1313. while (list($attname, $attvalue) = each($attary)){
  1314. /**
  1315. * See if this attribute should be removed.
  1316. */
  1317. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1318. if (preg_match($matchtag, $tagname)){
  1319. foreach ($matchattrs as $matchattr){
  1320. if (preg_match($matchattr, $attname)){
  1321. unset($attary{$attname});
  1322. continue;
  1323. }
  1324. }
  1325. }
  1326. }
  1327. /**
  1328. * Remove any backslashes, entities, and extraneous whitespace.
  1329. */
  1330. $attvalue = sq_unbackslash($attvalue);
  1331. $attvalue = sq_deent($attvalue);
  1332. $attvalue = sq_unspace($attvalue);
  1333. /**
  1334. * Remove \r \n \t \0 " " "\\"
  1335. */
  1336. $attvalue = str_replace(Array("\r", "\n", "\t", "\0", " ", "\\"),
  1337. Array('', '','','','',''), $attvalue);
  1338. /**
  1339. * Now let's run checks on the attvalues.
  1340. * I don't expect anyone to comprehend this. If you do,
  1341. * get in touch with me so I can drive to where you live and
  1342. * shake your hand personally. :)
  1343. */
  1344. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1345. if (preg_match($matchtag, $tagname)){
  1346. foreach ($matchattrs as $matchattr=>$valary){
  1347. if (preg_match($matchattr, $attname)){
  1348. /**
  1349. * There are two arrays in valary.
  1350. * First is matches.
  1351. * Second one is replacements
  1352. */
  1353. list($valmatch, $valrepl) = $valary;
  1354. $newvalue =
  1355. preg_replace($valmatch, $valrepl, $attvalue);
  1356. if ($newvalue != $attvalue){
  1357. $attary{$attname} = $newvalue;
  1358. }
  1359. }
  1360. }
  1361. }
  1362. }
  1363. /**
  1364. * Turn cid: urls into http-friendly ones.
  1365. */
  1366. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1367. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1368. }
  1369. }
  1370. /**
  1371. * See if we need to append any attributes to this tag.
  1372. */
  1373. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1374. if (preg_match($matchtag, $tagname)){
  1375. $attary = array_merge($attary, $addattary);
  1376. }
  1377. }
  1378. return $attary;
  1379. }
  1380. /**
  1381. * This function edits the style definition to make them friendly and
  1382. * usable in SquirrelMail.
  1383. *
  1384. * @param $message the message object
  1385. * @param $id the message id
  1386. * @param $content a string with whatever is between <style> and </style>
  1387. * @param $mailbox the message mailbox
  1388. * @return a string with edited content.
  1389. */
  1390. function sq_fixstyle($body, $pos, $message, $id, $mailbox){
  1391. global $view_unsafe_images;
  1392. $me = 'sq_fixstyle';
  1393. $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
  1394. if ($ret == FALSE){
  1395. return array(FALSE, strlen($body));
  1396. }
  1397. $newpos = $ret[0] + strlen($ret[2]);
  1398. $content = $ret[1];
  1399. /**
  1400. * First look for general BODY style declaration, which would be
  1401. * like so:
  1402. * body {background: blah-blah}
  1403. * and change it to .bodyclass so we can just assign it to a <div>
  1404. */
  1405. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1406. $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1407. /**
  1408. * Fix url('blah') declarations.
  1409. */
  1410. $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
  1411. "url(\\1$secremoveimg\\2)", $content);
  1412. /**
  1413. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1414. * is false.
  1415. */
  1416. if (!$view_unsafe_images){
  1417. $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
  1418. "url(\\1$secremoveimg\\2)", $content);
  1419. }
  1420. /**
  1421. * Fix urls that refer to cid:
  1422. */
  1423. while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
  1424. $content, $matches)){
  1425. $cidurl = $matches{1};
  1426. $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
  1427. $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
  1428. "url($httpurl)", $content);
  1429. }
  1430. /**
  1431. * Fix stupid css declarations which lead to vulnerabilities
  1432. * in IE.
  1433. */
  1434. $match = Array('/expression/i',
  1435. '/behaviou*r/i',
  1436. '/binding/i',
  1437. '/include-source/i');
  1438. $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
  1439. $content = preg_replace($match, $replace, $content);
  1440. return array($content, $newpos);
  1441. }
  1442. /**
  1443. * This function converts cid: url's into the ones that can be viewed in
  1444. * the browser.
  1445. *
  1446. * @param $message the message object
  1447. * @param $id the message id
  1448. * @param $cidurl the cid: url.
  1449. * @param $mailbox the message mailbox
  1450. * @return a string with a http-friendly url
  1451. */
  1452. function sq_cid2http($message, $id, $cidurl, $mailbox){
  1453. /**
  1454. * Get rid of quotes.
  1455. */
  1456. $quotchar = substr($cidurl, 0, 1);
  1457. if ($quotchar == '"' || $quotchar == "'"){
  1458. $cidurl = str_replace($quotchar, "", $cidurl);
  1459. } else {
  1460. $quotchar = '';
  1461. }
  1462. $cidurl = substr(trim($cidurl), 4);
  1463. $linkurl = find_ent_id($cidurl, $message);
  1464. /* in case of non-save cid links $httpurl should be replaced by a sort of
  1465. unsave link image */
  1466. $httpurl = '';
  1467. if ($linkurl) {
  1468. $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
  1469. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  1470. '&amp;ent_id=' . $linkurl . $quotchar;
  1471. }
  1472. return $httpurl;
  1473. }
  1474. /**
  1475. * This function changes the <body> tag into a <div> tag since we
  1476. * can't really have a body-within-body.
  1477. *
  1478. * @param $attary an array of attributes and values of <body>
  1479. * @param $mailbox mailbox we're currently reading (for cid2http)
  1480. * @param $message current message (for cid2http)
  1481. * @param $id current message id (for cid2http)
  1482. * @return a modified array of attributes to be set for <div>
  1483. */
  1484. function sq_body2div($attary, $mailbox, $message, $id){
  1485. $me = 'sq_body2div';
  1486. $divattary = Array('class' => "'bodyclass'");
  1487. $text = '#000000';
  1488. $has_bgc_stl = $has_txt_stl = false;
  1489. $styledef = '';
  1490. if (is_array($attary) && sizeof($attary) > 0){
  1491. foreach ($attary as $attname=>$attvalue){
  1492. $quotchar = substr($attvalue, 0, 1);
  1493. $attvalue = str_replace($quotchar, "", $attvalue);
  1494. switch ($attname){
  1495. case 'background':
  1496. $attvalue = sq_cid2http($message, $id,
  1497. $attvalue, $mailbox);
  1498. $styledef .= "background-image: url('$attvalue'); ";
  1499. break;
  1500. case 'bgcolor':
  1501. $has_bgc_stl = true;
  1502. $styledef .= "background-color: $attvalue; ";
  1503. break;
  1504. case 'text':
  1505. $has_txt_stl = true;
  1506. $styledef .= "color: $attvalue; ";
  1507. break;
  1508. }
  1509. }
  1510. // Outlook defines a white bgcolor and no text color. This can lead to
  1511. // white text on a white bg with certain themes.
  1512. if ($has_bgc_stl && !$has_txt_stl) {
  1513. $styledef .= "color: $text; ";
  1514. }
  1515. if (strlen($styledef) > 0){
  1516. $divattary{"style"} = "\"$styledef\"";
  1517. }
  1518. }
  1519. return $divattary;
  1520. }
  1521. /**
  1522. * This is the main function and the one you should actually be calling.
  1523. * There are several variables you should be aware of an which need
  1524. * special description.
  1525. *
  1526. * Since the description is quite lengthy, see it here:
  1527. * http://linux.duke.edu/projects/mini/htmlfilter/
  1528. *
  1529. * @param $body the string with HTML you wish to filter
  1530. * @param $tag_list see description above
  1531. * @param $rm_tags_with_content see description above
  1532. * @param $self_closing_tags see description above
  1533. * @param $force_tag_closing see description above
  1534. * @param $rm_attnames see description above
  1535. * @param $bad_attvals see description above
  1536. * @param $add_attr_to_tag see description above
  1537. * @param $message message object
  1538. * @param $id message id
  1539. * @return sanitized html safe to show on your pages.
  1540. */
  1541. function sq_sanitize($body,
  1542. $tag_list,
  1543. $rm_tags_with_content,
  1544. $self_closing_tags,
  1545. $force_tag_closing,
  1546. $rm_attnames,
  1547. $bad_attvals,
  1548. $add_attr_to_tag,
  1549. $message,
  1550. $id,
  1551. $mailbox
  1552. ){
  1553. $me = 'sq_sanitize';
  1554. $rm_tags = array_shift($tag_list);
  1555. /**
  1556. * Normalize rm_tags and rm_tags_with_content.
  1557. */
  1558. @array_walk($tag_list, 'sq_casenormalize');
  1559. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1560. @array_walk($self_closing_tags, 'sq_casenormalize');
  1561. /**
  1562. * See if tag_list is of tags to remove or tags to allow.
  1563. * false means remove these tags
  1564. * true means allow these tags
  1565. */
  1566. $curpos = 0;
  1567. $open_tags = Array();
  1568. $trusted = "\n<!-- begin sanitized html -->\n";
  1569. $skip_content = false;
  1570. /**
  1571. * Take care of netscape's stupid javascript entities like
  1572. * &{alert('boo')};
  1573. */
  1574. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  1575. while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
  1576. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1577. $free_content = substr($body, $curpos, $lt-$curpos);
  1578. /**
  1579. * Take care of <style>
  1580. */
  1581. if ($tagname == "style" && $tagtype == 1){
  1582. list($free_content, $curpos) =
  1583. sq_fixstyle($body, $gt+1, $message, $id, $mailbox);
  1584. if ($free_content != FALSE){
  1585. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1586. $trusted .= $free_content;
  1587. $trusted .= sq_tagprint($tagname, false, 2);
  1588. }
  1589. continue;
  1590. }
  1591. if ($skip_content == false){
  1592. $trusted .= $free_content;
  1593. }
  1594. if ($tagname != FALSE){
  1595. if ($tagtype == 2){
  1596. if ($skip_content == $tagname){
  1597. /**
  1598. * Got to the end of tag we needed to remove.
  1599. */
  1600. $tagname = false;
  1601. $skip_content = false;
  1602. } else {
  1603. if ($skip_content == false){
  1604. if ($tagname == "body"){
  1605. $tagname = "div";
  1606. }
  1607. if (isset($open_tags{$tagname}) &&
  1608. $open_tags{$tagname} > 0){
  1609. $open_tags{$tagname}--;
  1610. } else {
  1611. $tagname = false;
  1612. }
  1613. }
  1614. }
  1615. } else {
  1616. /**
  1617. * $rm_tags_with_content
  1618. */
  1619. if ($skip_content == false){
  1620. /**
  1621. * See if this is a self-closing type and change
  1622. * tagtype appropriately.
  1623. */
  1624. if ($tagtype == 1
  1625. && in_array($tagname, $self_closing_tags)){
  1626. $tagtype = 3;
  1627. }
  1628. /**
  1629. * See if we should skip this tag and any content
  1630. * inside it.
  1631. */
  1632. if ($tagtype == 1 &&
  1633. in_array($tagname, $rm_tags_with_content)){
  1634. $skip_content = $tagname;
  1635. } else {
  1636. if (($rm_tags == false
  1637. && in_array($tagname, $tag_list)) ||
  1638. ($rm_tags == true &&
  1639. !in_array($tagname, $tag_list))){
  1640. $tagname = false;
  1641. } else {
  1642. /**
  1643. * Convert body into div.
  1644. */
  1645. if ($tagname == "body"){
  1646. $tagname = "div";
  1647. $attary = sq_body2div($attary, $mailbox,
  1648. $message, $id);
  1649. }
  1650. if ($tagtype == 1){
  1651. if (isset($open_tags{$tagname})){
  1652. $open_tags{$tagname}++;
  1653. } else {
  1654. $open_tags{$tagname}=1;
  1655. }
  1656. }
  1657. /**
  1658. * This is where we run other checks.
  1659. */
  1660. if (is_array($attary) && sizeof($attary) > 0){
  1661. $attary = sq_fixatts($tagname,
  1662. $attary,
  1663. $rm_attnames,
  1664. $bad_attvals,
  1665. $add_attr_to_tag,
  1666. $message,
  1667. $id,
  1668. $mailbox
  1669. );
  1670. }
  1671. }
  1672. }
  1673. }
  1674. }
  1675. if ($tagname != false && $skip_content == false){
  1676. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1677. }
  1678. }
  1679. $curpos = $gt+1;
  1680. }
  1681. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1682. if ($force_tag_closing == true){
  1683. foreach ($open_tags as $tagname=>$opentimes){
  1684. while ($opentimes > 0){
  1685. $trusted .= '</' . $tagname . '>';
  1686. $opentimes--;
  1687. }
  1688. }
  1689. $trusted .= "\n";
  1690. }
  1691. $trusted .= "<!-- end sanitized html -->\n";
  1692. return $trusted;
  1693. }
  1694. /**
  1695. * This is a wrapper function to call html sanitizing routines.
  1696. *
  1697. * @param $body the body of the message
  1698. * @param $id the id of the message
  1699. * @return a string with html safe to display in the browser.
  1700. */
  1701. function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
  1702. global $attachment_common_show_images, $view_unsafe_images,
  1703. $has_unsafe_images;
  1704. /**
  1705. * Don't display attached images in HTML mode.
  1706. */
  1707. $attachment_common_show_images = false;
  1708. $tag_list = Array(
  1709. false,
  1710. "object",
  1711. "meta",
  1712. "html",
  1713. "head",
  1714. "base",
  1715. "link",
  1716. "frame",
  1717. "iframe",
  1718. "plaintext",
  1719. "marquee"
  1720. );
  1721. $rm_tags_with_content = Array(
  1722. "script",
  1723. "applet",
  1724. "embed",
  1725. "title",
  1726. "frameset",
  1727. "xml"
  1728. );
  1729. $self_closing_tags = Array(
  1730. "img",
  1731. "br",
  1732. "hr",
  1733. "input"
  1734. );
  1735. $force_tag_closing = true;
  1736. $rm_attnames = Array(
  1737. "/.*/" =>
  1738. Array(
  1739. "/target/i",
  1740. "/^on.*/i",
  1741. "/^dynsrc/i",
  1742. "/^data.*/i",
  1743. "/^lowsrc.*/i"
  1744. )
  1745. );
  1746. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1747. $bad_attvals = Array(
  1748. "/.*/" =>
  1749. Array(
  1750. "/^src|background/i" =>
  1751. Array(
  1752. Array(
  1753. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1754. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1755. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1756. ),
  1757. Array(
  1758. "\\1$secremoveimg\\2",
  1759. "\\1$secremoveimg\\2",
  1760. "\\1$secremoveimg\\2",
  1761. "\\1$secremoveimg\\2"
  1762. )
  1763. ),
  1764. "/^href|action/i" =>
  1765. Array(
  1766. Array(
  1767. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1768. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1769. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1770. ),
  1771. Array(
  1772. "\\1#\\1",
  1773. "\\1#\\1",
  1774. "\\1#\\1",
  1775. "\\1#\\1"
  1776. )
  1777. ),
  1778. "/^style/i" =>
  1779. Array(
  1780. Array(
  1781. "/expression/i",
  1782. "/binding/i",
  1783. "/behaviou*r/i",
  1784. "/include-source/i",
  1785. "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
  1786. "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
  1787. "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
  1788. "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
  1789. ),
  1790. Array(
  1791. "idiocy",
  1792. "idiocy",
  1793. "idiocy",
  1794. "idiocy",
  1795. "url(\\1#\\1)",
  1796. "url(\\1#\\1)",
  1797. "url(\\1#\\1)",
  1798. "url(\\1#\\1)",
  1799. "\\1:url(\\2#\\3)"
  1800. )
  1801. )
  1802. )
  1803. );
  1804. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  1805. $view_unsafe_images = false;
  1806. }
  1807. if (!$view_unsafe_images){
  1808. /**
  1809. * Remove any references to http/https if view_unsafe_images set
  1810. * to false.
  1811. */
  1812. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  1813. '/^([\'\"])\s*https*:.*([\'\"])/si');
  1814. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  1815. "\\1$secremoveimg\\1");
  1816. array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  1817. '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
  1818. array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  1819. "url(\\1$secremoveimg\\1)");
  1820. }
  1821. $add_attr_to_tag = Array(
  1822. "/^a$/i" =>
  1823. Array('target'=>'"_new"',
  1824. 'title'=>'"'._("This external link will open in a new window").'"'
  1825. )
  1826. );
  1827. $trusted = sq_sanitize($body,
  1828. $tag_list,
  1829. $rm_tags_with_content,
  1830. $self_closing_tags,
  1831. $force_tag_closing,
  1832. $rm_attnames,
  1833. $bad_attvals,
  1834. $add_attr_to_tag,
  1835. $message,
  1836. $id,
  1837. $mailbox
  1838. );
  1839. if (preg_match("|$secremoveimg|i", $trusted)){
  1840. $has_unsafe_images = true;
  1841. }
  1842. return $trusted;
  1843. }
  1844. /**
  1845. * function SendDownloadHeaders - send file to the browser
  1846. *
  1847. * Original Source: SM core src/download.php
  1848. * moved here to make it available to other code, and separate
  1849. * front end from back end functionality.
  1850. *
  1851. * @param string $type0 first half of mime type
  1852. * @param string $type1 second half of mime type
  1853. * @param string $filename filename to tell the browser for downloaded file
  1854. * @param boolean $force whether to force the download dialog to pop
  1855. * @param optional integer $filesize send the Content-Header and length to the browser
  1856. * @return void
  1857. */
  1858. function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
  1859. global $languages, $squirrelmail_language;
  1860. $isIE = $isIE6 = 0;
  1861. sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER);
  1862. if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
  1863. strstr($HTTP_USER_AGENT, 'Opera') === false) {
  1864. $isIE = 1;
  1865. }
  1866. if (strstr($HTTP_USER_AGENT, 'compatible; MSIE 6') !== false &&
  1867. strstr($HTTP_USER_AGENT, 'Opera') === false) {
  1868. $isIE6 = 1;
  1869. }
  1870. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  1871. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
  1872. $filename =
  1873. call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
  1874. } else {
  1875. $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace('&nbsp;', ' ', $filename));
  1876. }
  1877. // A Pox on Microsoft and it's Internet Explorer!
  1878. //
  1879. // IE has lots of bugs with file downloads.
  1880. // It also has problems with SSL. Both of these cause problems
  1881. // for us in this function.
  1882. //
  1883. // See this article on Cache Control headers and SSL
  1884. // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
  1885. //
  1886. // The best thing you can do for IE is to upgrade to the latest
  1887. // version
  1888. //set all the Cache Control Headers for IE
  1889. if ($isIE) {
  1890. $filename=rawurlencode($filename);
  1891. header ("Pragma: public");
  1892. header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); # HTTP/1.1
  1893. header ("Cache-Control: post-check=0, pre-check=0", false);
  1894. header ("Cache-control: private");
  1895. //set the inline header for IE, we'll add the attachment header later if we need it
  1896. header ("Content-Disposition: inline; filename=$filename");
  1897. }
  1898. if (!$force) {
  1899. // Try to show in browser window
  1900. header ("Content-Disposition: inline; filename=\"$filename\"");
  1901. header ("Content-Type: $type0/$type1; name=\"$filename\"");
  1902. } else {
  1903. // Try to pop up the "save as" box
  1904. // IE makes this hard. It pops up 2 save boxes, or none.
  1905. // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
  1906. // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
  1907. // But, according to Microsoft, it is "RFC compliant but doesn't
  1908. // take into account some deviations that allowed within the
  1909. // specification." Doesn't that mean RFC non-compliant?
  1910. // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
  1911. // all browsers need the application/octet-stream header for this
  1912. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  1913. // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
  1914. // Do not have quotes around filename, but that applied to
  1915. // "attachment"... does it apply to inline too?
  1916. header ("Content-Disposition: attachment; filename=\"$filename\"");
  1917. if ($isIE && !$isIE6) {
  1918. // This combination seems to work mostly. IE 5.5 SP 1 has
  1919. // known issues (see the Microsoft Knowledge Base)
  1920. // This works for most types, but doesn't work with Word files
  1921. header ("Content-Type: application/download; name=\"$filename\"");
  1922. // These are spares, just in case. :-)
  1923. //header("Content-Type: $type0/$type1; name=\"$filename\"");
  1924. //header("Content-Type: application/x-msdownload; name=\"$filename\"");
  1925. //header("Content-Type: application/octet-stream; name=\"$filename\"");
  1926. } else {
  1927. // another application/octet-stream forces download for Netscape
  1928. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  1929. }
  1930. }
  1931. //send the content-length header if the calling function provides it
  1932. if ($filesize > 0) {
  1933. header("Content-Length: $filesize");
  1934. }
  1935. } // end fn SendDownloadHeaders
  1936. ?>