mime.php 73 KB

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