mime.php 80 KB

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