mime.php 73 KB

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