mime.php 72 KB

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