mime.php 74 KB

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