mime.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * Copyright (c) 1999-2002 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This contains the functions necessary to detect and decode MIME
  9. * messages.
  10. *
  11. * $Id$
  12. */
  13. require_once('../functions/imap.php');
  14. require_once('../functions/attachment_common.php');
  15. /* --------------------------------------------------------------------------------- */
  16. /* MIME DECODING */
  17. /* --------------------------------------------------------------------------------- */
  18. /* This function gets the structure of a message and stores it in the "message" class.
  19. * It will return this object for use with all relevant header information and
  20. * fully parsed into the standard "message" object format.
  21. */
  22. function mime_structure ($bodystructure, $flags=array()) {
  23. // isolate the body structure and remove beginning and end parenthesis
  24. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  25. $msg = &new message();
  26. $read = trim(substr ($read, 0, -1));
  27. $res = $msg->parseStructure($read);
  28. $msg = $res[0];
  29. $msg->setEnt('0');
  30. if (count($flags)) {
  31. foreach ($flags as $flag) {
  32. $char = strtoupper($flag{1});
  33. switch ($char) {
  34. case 'S':
  35. if (strtolower($flag) == '\\seen') {
  36. $msg->is_seen = true;
  37. }
  38. break;
  39. case 'A':
  40. if (strtolower($flag) == '\\answered') {
  41. $msg->is_answered = true;
  42. }
  43. break;
  44. case 'D':
  45. if (strtolower($flag) == '\\deleted') {
  46. $msg->is_deleted = true;
  47. }
  48. break;
  49. case 'F':
  50. if (strtolower($flag) == '\\flagged') {
  51. $msg->is_flagged = true;
  52. }
  53. break;
  54. case 'M':
  55. if (strtolower($flag) == '$mdnsent') {
  56. $msg->is_mdnsent = true;
  57. }
  58. break;
  59. default:
  60. break;
  61. }
  62. }
  63. }
  64. // listEntities($msg);
  65. return( $msg );
  66. }
  67. /* this starts the parsing of a particular structure. It is called recursively,
  68. * so it can be passed different structures. It returns an object of type
  69. * $message.
  70. * First, it checks to see if it is a multipart message. If it is, then it
  71. * handles that as it sees is necessary. If it is just a regular entity,
  72. * then it parses it and adds the necessary header information (by calling out
  73. * to mime_get_elements()
  74. */
  75. function mime_fetch_body($imap_stream, $id, $ent_id) {
  76. global $uid_support;
  77. /*
  78. * do a bit of error correction. If we couldn't find the entity id, just guess
  79. * that it is the first one. That is usually the case anyway.
  80. */
  81. if (!$ent_id) {
  82. $ent_id = 1;
  83. }
  84. $cmd = "FETCH $id BODY[$ent_id]";
  85. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
  86. do {
  87. $topline = trim(array_shift( $data ));
  88. } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
  89. $wholemessage = implode('', $data);
  90. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  91. $ret = substr( $wholemessage, 0, $regs[1] );
  92. /*
  93. There is some information in the content info header that could be important
  94. in order to parse html messages. Let's get them here.
  95. */
  96. if ( $ret{0} == '<' ) {
  97. $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
  98. }
  99. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  100. $ret = $regs[1];
  101. } else {
  102. global $where, $what, $mailbox, $passed_id, $startMessage;
  103. $par = 'mailbox=' . urlencode($mailbox) . "&amp;passed_id=$passed_id";
  104. if (isset($where) && isset($what)) {
  105. $par .= '&amp;where='. urlencode($where) . "&amp;what=" . urlencode($what);
  106. } else {
  107. $par .= "&amp;startMessage=$startMessage&amp;show_more=0";
  108. }
  109. $par .= '&amp;response=' . urlencode($response) .
  110. '&amp;message=' . urlencode($message).
  111. '&amp;topline=' . urlencode($topline);
  112. echo '<tt><br>' .
  113. '<table width="80%"><tr>' .
  114. '<tr><td colspan=2>' .
  115. _("Body retrieval error. The reason for this is most probably that the message is malformed. Please help us making future versions better by submitting this message to the developers knowledgebase!") .
  116. " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
  117. _("Submit message") . '</A><BR>&nbsp;' .
  118. '</td></tr>' .
  119. '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  120. '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  121. '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  122. '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  123. "</table><BR></tt></font><hr>";
  124. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
  125. array_shift($data);
  126. $wholemessage = implode('', $data);
  127. $ret = $wholemessage;
  128. }
  129. return( $ret );
  130. }
  131. function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
  132. global $uid_support;
  133. // do a bit of error correction. If we couldn't find the entity id, just guess
  134. // that it is the first one. That is usually the case anyway.
  135. if (!$ent_id) {
  136. $ent_id = 1;
  137. }
  138. $sid = sqimap_session_id($uid_support);
  139. // Don't kill the connection if the browser is over a dialup
  140. // and it would take over 30 seconds to download it.
  141. // don´t call set_time_limit in safe mode.
  142. if (!ini_get("safe_mode")) {
  143. set_time_limit(0);
  144. }
  145. if ($uid_support) {
  146. $sid_s = substr($sid,0,strpos($sid, ' '));
  147. } else {
  148. $sid_s = $sid;
  149. }
  150. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  151. echo decodeBody($body, $encoding);
  152. return;
  153. /*
  154. fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
  155. $cnt = 0;
  156. $continue = true;
  157. $read = fgets ($imap_stream,8192);
  158. // This could be bad -- if the section has sqimap_session_id() . ' OK'
  159. // or similar, it will kill the download.
  160. while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
  161. if (trim($read) == ')==') {
  162. $read1 = $read;
  163. $read = fgets ($imap_stream,4096);
  164. if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
  165. return;
  166. } else {
  167. echo decodeBody($read1, $encoding) .
  168. decodeBody($read, $encoding);
  169. }
  170. } else if ($cnt) {
  171. echo decodeBody($read, $encoding);
  172. }
  173. $read = fgets ($imap_stream,4096);
  174. $cnt++;
  175. // break;
  176. }
  177. */
  178. }
  179. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  180. /* findDisplayEntity
  181. * Checks to see if $message contains content of type $type0/$type1
  182. * returns the first entity number it finds of that type, or NULL if
  183. * none is found. Takes optional argument $start to allow the caller
  184. * to continue where they left off
  185. */
  186. function findDisplayEntity($message, $type0, $type1, $start=0) {
  187. if ($message) {
  188. for ($i = $start;isset($message->entities[$i]); $i++) {
  189. $entity = $message->entities[$i];
  190. if ($entity->type0 == $type0 && $entity->type1 == $type1) {
  191. return $i;
  192. }
  193. }
  194. }
  195. return NULL;
  196. }
  197. // This is here for debugging purposese. It will print out a list
  198. // of all the entity IDs that are in the $message object.
  199. function listEntities ($message) {
  200. if ($message) {
  201. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br>';
  202. for ($i = 0;isset($message->entities[$i]); $i++) {
  203. echo "$i : ";
  204. $msg = listEntities($message->entities[$i]);
  205. if ($msg) {
  206. echo "return: ";
  207. return $msg;
  208. }
  209. }
  210. }
  211. }
  212. function getPriorityStr($priority) {
  213. $priority_level = substr($priority,0,1);
  214. switch($priority_level) {
  215. /* check for a higher then normal priority. */
  216. case '1':
  217. case '2':
  218. $priority_string = _("High");
  219. break;
  220. /* check for a lower then normal priority. */
  221. case '4':
  222. case '5':
  223. $priority_string = _("Low");
  224. break;
  225. /* check for a normal priority. */
  226. case '3':
  227. default:
  228. $priority_level = '3';
  229. $priority_string = _("Normal");
  230. break;
  231. }
  232. return $priority_string;
  233. }
  234. /* returns a $message object for a particular entity id */
  235. function getEntity ($message, $ent_id) {
  236. return $message->getEntity($ent_id);
  237. }
  238. /*
  239. * translateText
  240. * Extracted from strings.php 23/03/2002
  241. */
  242. function translateText(&$body, $wrap_at, $charset) {
  243. global $where, $what; /* from searching */
  244. global $color; /* color theme */
  245. require_once('../functions/url_parser.php');
  246. $body_ary = explode("\n", $body);
  247. $PriorQuotes = 0;
  248. for ($i=0; $i < count($body_ary); $i++) {
  249. $line = $body_ary[$i];
  250. if (strlen($line) - 2 >= $wrap_at) {
  251. sqWordWrap($line, $wrap_at);
  252. }
  253. $line = charset_decode($charset, $line);
  254. $line = str_replace("\t", ' ', $line);
  255. parseUrl ($line);
  256. $Quotes = 0;
  257. $pos = 0;
  258. $j = strlen( $line );
  259. while ( $pos < $j ) {
  260. if ($line[$pos] == ' ') {
  261. $pos ++;
  262. } else if (strpos($line, '&gt;', $pos) === $pos) {
  263. $pos += 4;
  264. $Quotes ++;
  265. } else {
  266. break;
  267. }
  268. }
  269. if ($Quotes > 1) {
  270. if (! isset($color[14])) {
  271. $color[14] = '#FF0000';
  272. }
  273. $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
  274. } elseif ($Quotes) {
  275. if (! isset($color[13])) {
  276. $color[13] = '#800000';
  277. }
  278. $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
  279. }
  280. $body_ary[$i] = $line;
  281. }
  282. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  283. }
  284. /* This returns a parsed string called $body. That string can then
  285. be displayed as the actual message in the HTML. It contains
  286. everything needed, including HTML Tags, Attachments at the
  287. bottom, etc.
  288. */
  289. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
  290. // this if statement checks for the entity to show as the
  291. // primary message. To add more of them, just put them in the
  292. // order that is their priority.
  293. global $startMessage, $username, $key, $imapServerAddress, $imapPort,
  294. $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
  295. $has_unsafe_images= 0;
  296. $body = '';
  297. $urlmailbox = urlencode($mailbox);
  298. $body_message = getEntity($message, $ent_num);
  299. if (($body_message->header->type0 == 'text') ||
  300. ($body_message->header->type0 == 'rfc822')) {
  301. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  302. $body = decodeBody($body, $body_message->header->encoding);
  303. $hookResults = do_hook("message_body", $body);
  304. $body = $hookResults[1];
  305. // If there are other types that shouldn't be formatted, add
  306. // them here
  307. if ($body_message->header->type1 == 'html') {
  308. if ( $show_html_default <> 1 ) {
  309. $body = strip_tags( $body );
  310. translateText($body, $wrap_at,
  311. $body_message->header->getParameter['charset']);
  312. } else {
  313. $body = magicHTML( $body, $id, $message, $mailbox );
  314. }
  315. } else {
  316. translateText($body, $wrap_at,
  317. $body_message->header->getParameter('charset'));
  318. }
  319. if ($has_unsafe_images) {
  320. if ($view_unsafe_images) {
  321. $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;passed_ent_id=".$message->entity_id."&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
  322. } else {
  323. $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;passed_ent_id=".$message->entity_id."&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0&amp;view_unsafe_images=1\">". _("View Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
  324. }
  325. }
  326. }
  327. return ($body);
  328. }
  329. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  330. global $where, $what;
  331. global $startMessage, $color;
  332. static $ShownHTML = 0;
  333. $att_ar = $message->getAttachments($exclude_id);
  334. if (!count($att_ar)) return '';
  335. $attachments = '';
  336. $urlMailbox = urlencode($mailbox);
  337. foreach ($att_ar as $att) {
  338. $ent = urldecode($att->entity_id);
  339. $header = $att->header;
  340. $type0 = strtolower($header->type0);
  341. $type1 = strtolower($header->type1);
  342. $name = '';
  343. $Links['download link']['text'] = _("download");
  344. $Links['download link']['href'] =
  345. "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
  346. $ImageURL = '';
  347. if ($type0 =='message' && $type1 == 'rfc822') {
  348. $default_page = '../src/read_body.php';
  349. $rfc822_header = $att->rfc822_header;
  350. $filename = decodeHeader($rfc822_header->subject);
  351. $from_o = $rfc822_header->from;
  352. if (is_object($from_o)) {
  353. $from_name = $from_o->getAddress(false);
  354. } else {
  355. $from_name = _("Unknown sender");
  356. }
  357. $from_name = decodeHeader(htmlspecialchars($from_name));
  358. $description = $from_name;
  359. } else {
  360. $default_page = '../src/download.php';
  361. $filename = decodeHeader($header->disposition->getProperty('filename'));
  362. if (trim($filename) == '') {
  363. $name = decodeHeader($header->disposition->getProperty('name'));
  364. if (trim($name) == '') {
  365. if ( trim( $header->id ) == '' )
  366. $filename = 'untitled-[' . $ent . ']' ;
  367. else
  368. $filename = 'cid: ' . $header->id;
  369. } else {
  370. $filename = $name;
  371. }
  372. }
  373. if ($header->description) {
  374. $description = htmlspecialchars($header->description);
  375. } else {
  376. $description = '';
  377. }
  378. }
  379. $display_filename = $filename;
  380. $DefaultLink = $default_page . "?startMessage=$startMessage"
  381. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  382. . "&amp;passed_ent_id=$ent";
  383. if ($where && $what) {
  384. $DefaultLink = '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  385. }
  386. /* this executes the attachment hook with a specific MIME-type.
  387. * if that doens't have results, it tries if there's a rule
  388. * for a more generic type. */
  389. $HookResults = do_hook("attachment $type0/$type1", $Links,
  390. $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
  391. $display_filename, $where, $what);
  392. if(count($HookResults[1]) <= 1) {
  393. $HookResults = do_hook("attachment $type0/*", $Links,
  394. $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
  395. $display_filename, $where, $what);
  396. }
  397. $Links = $HookResults[1];
  398. $DefaultLink = $HookResults[6];
  399. $attachments .= '<TR><TD>' .
  400. "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
  401. '<TD><SMALL><b>' . show_readable_size($header->size) .
  402. '</b>&nbsp;&nbsp;</small></TD>' .
  403. "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
  404. '<TD><SMALL>';
  405. $attachments .= '<b>' . $description . '</b>';
  406. $attachments .= '</SMALL></TD><TD><SMALL>&nbsp;';
  407. $SkipSpaces = 1;
  408. foreach ($Links as $Val) {
  409. if ($SkipSpaces) {
  410. $SkipSpaces = 0;
  411. } else {
  412. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  413. }
  414. $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
  415. }
  416. unset($Links);
  417. $attachments .= "</TD></TR>\n";
  418. }
  419. return $attachments;
  420. }
  421. /** this function decodes the body depending on the encoding type. **/
  422. function decodeBody($body, $encoding) {
  423. $body = str_replace("\r\n", "\n", $body);
  424. $encoding = strtolower($encoding);
  425. global $show_html_default;
  426. if ($encoding == 'quoted-printable' ||
  427. $encoding == 'quoted_printable') {
  428. $body = quoted_printable_decode($body);
  429. while (ereg("=\n", $body))
  430. $body = ereg_replace ("=\n", "", $body);
  431. } else if ($encoding == 'base64') {
  432. $body = base64_decode($body);
  433. }
  434. // All other encodings are returned raw.
  435. return $body;
  436. }
  437. /*
  438. * This functions decode strings that is encoded according to
  439. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  440. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  441. */
  442. function decodeHeader ($string, $utfencode=true) {
  443. if (is_array($string)) {
  444. $string = implode("\n", $string);
  445. }
  446. $i = 0;
  447. while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
  448. $string, $res)) {
  449. $prefix = $res[1];
  450. // Ignore white-space between consecutive encoded-words
  451. if (strspn($res[2], " \t") != strlen($res[2])) {
  452. $prefix .= $res[2];
  453. }
  454. if (ucfirst($res[4]) == 'B') {
  455. $replace = base64_decode($res[5]);
  456. } else {
  457. $replace = str_replace('_', ' ', $res[5]);
  458. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  459. $replace);
  460. /* Only encode into entities by default. Some places
  461. don't need the encoding, like the compose form. */
  462. if ($utfencode) {
  463. $replace = charset_decode($res[3], $replace);
  464. }
  465. }
  466. $string = $prefix . $replace . substr($string, strlen($res[0]));
  467. $i = strlen($prefix) + strlen($replace);
  468. }
  469. return( $string );
  470. }
  471. /*
  472. * Encode a string according to RFC 1522 for use in headers if it
  473. * contains 8-bit characters or anything that looks like it should
  474. * be encoded.
  475. */
  476. function encodeHeader ($string) {
  477. global $default_charset;
  478. // Encode only if the string contains 8-bit characters or =?
  479. $j = strlen( $string );
  480. $l = strstr($string, '=?'); // Must be encoded ?
  481. $ret = '';
  482. for( $i=0; $i < $j; ++$i) {
  483. switch( $string{$i} ) {
  484. case '=':
  485. $ret .= '=3D';
  486. break;
  487. case '?':
  488. $ret .= '=3F';
  489. break;
  490. case '_':
  491. $ret .= '=5F';
  492. break;
  493. case ' ':
  494. $ret .= '_';
  495. break;
  496. default:
  497. $k = ord( $string{$i} );
  498. if ( $k > 126 ) {
  499. $ret .= sprintf("=%02X", $k);
  500. $l = TRUE;
  501. } else
  502. $ret .= $string{$i};
  503. }
  504. }
  505. if ( $l ) {
  506. $string = "=?$default_charset?Q?$ret?=";
  507. }
  508. return( $string );
  509. }
  510. /* This function trys to locate the entity_id of a specific mime element */
  511. function find_ent_id( $id, $message ) {
  512. $ret = '';
  513. for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
  514. if ( $message->entities[$i]->header->type0 == 'multipart') {
  515. $ret = find_ent_id( $id, $message->entities[$i] );
  516. } else {
  517. if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
  518. $ret = $message->entities[$i]->entity_id;
  519. }
  520. }
  521. return( $ret );
  522. }
  523. /**
  524. ** HTMLFILTER ROUTINES
  525. */
  526. /**
  527. * This function returns the final tag out of the tag name, an array
  528. * of attributes, and the type of the tag. This function is called by
  529. * sq_sanitize internally.
  530. *
  531. * @param $tagname the name of the tag.
  532. * @param $attary the array of attributes and their values
  533. * @param $tagtype The type of the tag (see in comments).
  534. * @return a string with the final tag representation.
  535. */
  536. function sq_tagprint($tagname, $attary, $tagtype){
  537. $me = "sq_tagprint";
  538. if ($tagtype == 2){
  539. $fulltag = '</' . $tagname . '>';
  540. } else {
  541. $fulltag = '<' . $tagname;
  542. if (is_array($attary) && sizeof($attary)){
  543. $atts = Array();
  544. while (list($attname, $attvalue) = each($attary)){
  545. array_push($atts, "$attname=$attvalue");
  546. }
  547. $fulltag .= ' ' . join(" ", $atts);
  548. }
  549. if ($tagtype == 3){
  550. $fulltag .= " /";
  551. }
  552. $fulltag .= ">";
  553. }
  554. return $fulltag;
  555. }
  556. /**
  557. * A small helper function to use with array_walk. Modifies a by-ref
  558. * value and makes it lowercase.
  559. *
  560. * @param $val a value passed by-ref.
  561. * @return void since it modifies a by-ref value.
  562. */
  563. function sq_casenormalize(&$val){
  564. $val = strtolower($val);
  565. }
  566. /**
  567. * This function skips any whitespace from the current position within
  568. * a string and to the next non-whitespace value.
  569. *
  570. * @param $body the string
  571. * @param $offset the offset within the string where we should start
  572. * looking for the next non-whitespace character.
  573. * @return the location within the $body where the next
  574. * non-whitespace char is located.
  575. */
  576. function sq_skipspace($body, $offset){
  577. $me = "sq_skipspace";
  578. preg_match("/^(\s*)/s", substr($body, $offset), $matches);
  579. if (sizeof($matches{1})){
  580. $count = strlen($matches{1});
  581. $offset += $count;
  582. }
  583. return $offset;
  584. }
  585. /**
  586. * This function looks for the next character within a string. It's
  587. * really just a glorified "strpos", except it catches if failures
  588. * nicely.
  589. *
  590. * @param $body The string to look for needle in.
  591. * @param $offset Start looking from this position.
  592. * @param $needle The character/string to look for.
  593. * @return location of the next occurance of the needle, or
  594. * strlen($body) if needle wasn't found.
  595. */
  596. function sq_findnxstr($body, $offset, $needle){
  597. $me = "sq_findnxstr";
  598. $pos = strpos($body, $needle, $offset);
  599. if ($pos === FALSE){
  600. $pos = strlen($body);
  601. }
  602. return $pos;
  603. }
  604. /**
  605. * This function takes a PCRE-style regexp and tries to match it
  606. * within the string.
  607. *
  608. * @param $body The string to look for needle in.
  609. * @param $offset Start looking from here.
  610. * @param $reg A PCRE-style regex to match.
  611. * @return Returns a false if no matches found, or an array
  612. * with the following members:
  613. * - integer with the location of the match within $body
  614. * - string with whatever content between offset and the match
  615. * - string with whatever it is we matched
  616. */
  617. function sq_findnxreg($body, $offset, $reg){
  618. $me = "sq_findnxreg";
  619. $matches = Array();
  620. $retarr = Array();
  621. preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
  622. if (!$matches{0}){
  623. $retarr = false;
  624. } else {
  625. $retarr{0} = $offset + strlen($matches{1});
  626. $retarr{1} = $matches{1};
  627. $retarr{2} = $matches{2};
  628. }
  629. return $retarr;
  630. }
  631. /**
  632. * This function looks for the next tag.
  633. *
  634. * @param $body String where to look for the next tag.
  635. * @param $offset Start looking from here.
  636. * @return false if no more tags exist in the body, or
  637. * an array with the following members:
  638. * - string with the name of the tag
  639. * - array with attributes and their values
  640. * - integer with tag type (1, 2, or 3)
  641. * - integer where the tag starts (starting "<")
  642. * - integer where the tag ends (ending ">")
  643. * first three members will be false, if the tag is invalid.
  644. */
  645. function sq_getnxtag($body, $offset){
  646. $me = "sq_getnxtag";
  647. if ($offset > strlen($body)){
  648. return false;
  649. }
  650. $lt = sq_findnxstr($body, $offset, "<");
  651. if ($lt == strlen($body)){
  652. return false;
  653. }
  654. /**
  655. * We are here:
  656. * blah blah <tag attribute="value">
  657. * \---------^
  658. */
  659. $pos = sq_skipspace($body, $lt+1);
  660. if ($pos >= strlen($body)){
  661. return Array(false, false, false, $lt, strlen($body));
  662. }
  663. /**
  664. * There are 3 kinds of tags:
  665. * 1. Opening tag, e.g.:
  666. * <a href="blah">
  667. * 2. Closing tag, e.g.:
  668. * </a>
  669. * 3. XHTML-style content-less tag, e.g.:
  670. * <img src="blah"/>
  671. */
  672. $tagtype = false;
  673. switch (substr($body, $pos, 1)){
  674. case "/":
  675. $tagtype = 2;
  676. $pos++;
  677. break;
  678. case "!":
  679. /**
  680. * A comment or an SGML declaration.
  681. */
  682. if (substr($body, $pos+1, 2) == "--"){
  683. $gt = strpos($body, "-->", $pos);
  684. if ($gt === false){
  685. $gt = strlen($body);
  686. } else {
  687. $gt += 2;
  688. }
  689. return Array(false, false, false, $lt, $gt);
  690. } else {
  691. $gt = sq_findnxstr($body, $pos, ">");
  692. return Array(false, false, false, $lt, $gt);
  693. }
  694. break;
  695. default:
  696. /**
  697. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  698. * later.
  699. */
  700. $tagtype = 1;
  701. break;
  702. }
  703. $tag_start = $pos;
  704. $tagname = '';
  705. /**
  706. * Look for next [\W-_], which will indicate the end of the tag name.
  707. */
  708. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  709. if ($regary == false){
  710. return Array(false, false, false, $lt, strlen($body));
  711. }
  712. list($pos, $tagname, $match) = $regary;
  713. $tagname = strtolower($tagname);
  714. /**
  715. * $match can be either of these:
  716. * '>' indicating the end of the tag entirely.
  717. * '\s' indicating the end of the tag name.
  718. * '/' indicating that this is type-3 xhtml tag.
  719. *
  720. * Whatever else we find there indicates an invalid tag.
  721. */
  722. switch ($match){
  723. case "/":
  724. /**
  725. * This is an xhtml-style tag with a closing / at the
  726. * end, like so: <img src="blah"/>. Check if it's followed
  727. * by the closing bracket. If not, then this tag is invalid
  728. */
  729. if (substr($body, $pos, 2) == "/>"){
  730. $pos++;
  731. $tagtype = 3;
  732. } else {
  733. $gt = sq_findnxstr($body, $pos, ">");
  734. $retary = Array(false, false, false, $lt, $gt);
  735. return $retary;
  736. }
  737. case ">":
  738. return Array($tagname, false, $tagtype, $lt, $pos);
  739. break;
  740. default:
  741. /**
  742. * Check if it's whitespace
  743. */
  744. if (preg_match("/\s/", $match)){
  745. } else {
  746. /**
  747. * This is an invalid tag! Look for the next closing ">".
  748. */
  749. $gt = sq_findnxstr($body, $offset, ">");
  750. return Array(false, false, false, $lt, $gt);
  751. }
  752. }
  753. /**
  754. * At this point we're here:
  755. * <tagname attribute='blah'>
  756. * \-------^
  757. *
  758. * At this point we loop in order to find all attributes.
  759. */
  760. $attname = '';
  761. $atttype = false;
  762. $attary = Array();
  763. while ($pos <= strlen($body)){
  764. $pos = sq_skipspace($body, $pos);
  765. if ($pos == strlen($body)){
  766. /**
  767. * Non-closed tag.
  768. */
  769. return Array(false, false, false, $lt, $pos);
  770. }
  771. /**
  772. * See if we arrived at a ">" or "/>", which means that we reached
  773. * the end of the tag.
  774. */
  775. $matches = Array();
  776. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  777. /**
  778. * Yep. So we did.
  779. */
  780. $pos += strlen($matches{1});
  781. if ($matches{2} == "/>"){
  782. $tagtype = 3;
  783. $pos++;
  784. }
  785. return Array($tagname, $attary, $tagtype, $lt, $pos);
  786. }
  787. /**
  788. * There are several types of attributes, with optional
  789. * [:space:] between members.
  790. * Type 1:
  791. * attrname[:space:]=[:space:]'CDATA'
  792. * Type 2:
  793. * attrname[:space:]=[:space:]"CDATA"
  794. * Type 3:
  795. * attr[:space:]=[:space:]CDATA
  796. * Type 4:
  797. * attrname
  798. *
  799. * We leave types 1 and 2 the same, type 3 we check for
  800. * '"' and convert to "&quot" if needed, then wrap in
  801. * double quotes. Type 4 we convert into:
  802. * attrname="yes".
  803. */
  804. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  805. if ($regary == false){
  806. /**
  807. * Looks like body ended before the end of tag.
  808. */
  809. return Array(false, false, false, $lt, strlen($body));
  810. }
  811. list($pos, $attname, $match) = $regary;
  812. $attname = strtolower($attname);
  813. /**
  814. * We arrived at the end of attribute name. Several things possible
  815. * here:
  816. * '>' means the end of the tag and this is attribute type 4
  817. * '/' if followed by '>' means the same thing as above
  818. * '\s' means a lot of things -- look what it's followed by.
  819. * anything else means the attribute is invalid.
  820. */
  821. switch($match){
  822. case "/":
  823. /**
  824. * This is an xhtml-style tag with a closing / at the
  825. * end, like so: <img src="blah"/>. Check if it's followed
  826. * by the closing bracket. If not, then this tag is invalid
  827. */
  828. if (substr($body, $pos, 2) == "/>"){
  829. $pos++;
  830. $tagtype = 3;
  831. } else {
  832. $gt = sq_findnxstr($body, $pos, ">");
  833. $retary = Array(false, false, false, $lt, $gt);
  834. return $retary;
  835. }
  836. case ">":
  837. $attary{$attname} = '"yes"';
  838. return Array($tagname, $attary, $tagtype, $lt, $pos);
  839. break;
  840. default:
  841. /**
  842. * Skip whitespace and see what we arrive at.
  843. */
  844. $pos = sq_skipspace($body, $pos);
  845. $char = substr($body, $pos, 1);
  846. /**
  847. * Two things are valid here:
  848. * '=' means this is attribute type 1 2 or 3.
  849. * \w means this was attribute type 4.
  850. * anything else we ignore and re-loop. End of tag and
  851. * invalid stuff will be caught by our checks at the beginning
  852. * of the loop.
  853. */
  854. if ($char == "="){
  855. $pos++;
  856. $pos = sq_skipspace($body, $pos);
  857. /**
  858. * Here are 3 possibilities:
  859. * "'" attribute type 1
  860. * '"' attribute type 2
  861. * everything else is the content of tag type 3
  862. */
  863. $quot = substr($body, $pos, 1);
  864. if ($quot == "'"){
  865. $regary = sq_findnxreg($body, $pos+1, "\'");
  866. if ($regary == false){
  867. return Array(false, false, false, $lt, strlen($body));
  868. }
  869. list($pos, $attval, $match) = $regary;
  870. $pos++;
  871. $attary{$attname} = "'" . $attval . "'";
  872. } else if ($quot == '"'){
  873. $regary = sq_findnxreg($body, $pos+1, '\"');
  874. if ($regary == false){
  875. return Array(false, false, false, $lt, strlen($body));
  876. }
  877. list($pos, $attval, $match) = $regary;
  878. $pos++;
  879. $attary{$attname} = '"' . $attval . '"';
  880. } else {
  881. /**
  882. * These are hateful. Look for \s, or >.
  883. */
  884. $regary = sq_findnxreg($body, $pos, "[\s>]");
  885. if ($regary == false){
  886. return Array(false, false, false, $lt, strlen($body));
  887. }
  888. list($pos, $attval, $match) = $regary;
  889. /**
  890. * If it's ">" it will be caught at the top.
  891. */
  892. $attval = preg_replace("/\"/s", "&quot;", $attval);
  893. $attary{$attname} = '"' . $attval . '"';
  894. }
  895. } else if (preg_match("|[\w/>]|", $char)) {
  896. /**
  897. * That was attribute type 4.
  898. */
  899. $attary{$attname} = '"yes"';
  900. } else {
  901. /**
  902. * An illegal character. Find next '>' and return.
  903. */
  904. $gt = sq_findnxstr($body, $pos, ">");
  905. return Array(false, false, false, $lt, $gt);
  906. }
  907. }
  908. }
  909. /**
  910. * The fact that we got here indicates that the tag end was never
  911. * found. Return invalid tag indication so it gets stripped.
  912. */
  913. return Array(false, false, false, $lt, strlen($body));
  914. }
  915. /**
  916. * This function checks attribute values for entity-encoded values
  917. * and returns them translated into 8-bit strings so we can run
  918. * checks on them.
  919. *
  920. * @param $attvalue A string to run entity check against.
  921. * @return Translated value.
  922. */
  923. function sq_deent($attvalue){
  924. $me="sq_deent";
  925. /**
  926. * See if we have to run the checks first. All entities must start
  927. * with "&".
  928. */
  929. if (strpos($attvalue, "&") === false){
  930. return $attvalue;
  931. }
  932. /**
  933. * Check named entities first.
  934. */
  935. $trans = get_html_translation_table(HTML_ENTITIES);
  936. /**
  937. * Leave &quot; in, as it can mess us up.
  938. */
  939. $trans = array_flip($trans);
  940. unset($trans{"&quot;"});
  941. while (list($ent, $val) = each($trans)){
  942. $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
  943. }
  944. /**
  945. * Now translate numbered entities from 1 to 255 if needed.
  946. */
  947. if (strpos($attvalue, "#") !== false){
  948. $omit = Array(34, 39);
  949. for ($asc=1; $asc<256; $asc++){
  950. if (!in_array($asc, $omit)){
  951. $chr = chr($asc);
  952. $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
  953. $attvalue);
  954. $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
  955. "$chr\\1", $attvalue);
  956. }
  957. }
  958. }
  959. return $attvalue;
  960. }
  961. /**
  962. * This function runs various checks against the attributes.
  963. *
  964. * @param $tagname String with the name of the tag.
  965. * @param $attary Array with all tag attributes.
  966. * @param $rm_attnames See description for sq_sanitize
  967. * @param $bad_attvals See description for sq_sanitize
  968. * @param $add_attr_to_tag See description for sq_sanitize
  969. * @param $message message object
  970. * @param $id message id
  971. * @return Array with modified attributes.
  972. */
  973. function sq_fixatts($tagname,
  974. $attary,
  975. $rm_attnames,
  976. $bad_attvals,
  977. $add_attr_to_tag,
  978. $message,
  979. $id,
  980. $mailbox
  981. ){
  982. $me = "sq_fixatts";
  983. while (list($attname, $attvalue) = each($attary)){
  984. /**
  985. * See if this attribute should be removed.
  986. */
  987. foreach ($rm_attnames as $matchtag=>$matchattrs){
  988. if (preg_match($matchtag, $tagname)){
  989. foreach ($matchattrs as $matchattr){
  990. if (preg_match($matchattr, $attname)){
  991. unset($attary{$attname});
  992. continue;
  993. }
  994. }
  995. }
  996. }
  997. /**
  998. * Remove any entities.
  999. */
  1000. $attvalue = sq_deent($attvalue);
  1001. /**
  1002. * Now let's run checks on the attvalues.
  1003. * I don't expect anyone to comprehend this. If you do,
  1004. * get in touch with me so I can drive to where you live and
  1005. * shake your hand personally. :)
  1006. */
  1007. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1008. if (preg_match($matchtag, $tagname)){
  1009. foreach ($matchattrs as $matchattr=>$valary){
  1010. if (preg_match($matchattr, $attname)){
  1011. /**
  1012. * There are two arrays in valary.
  1013. * First is matches.
  1014. * Second one is replacements
  1015. */
  1016. list($valmatch, $valrepl) = $valary;
  1017. $newvalue =
  1018. preg_replace($valmatch, $valrepl, $attvalue);
  1019. if ($newvalue != $attvalue){
  1020. $attary{$attname} = $newvalue;
  1021. }
  1022. }
  1023. }
  1024. }
  1025. }
  1026. /**
  1027. * Turn cid: urls into http-friendly ones.
  1028. */
  1029. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1030. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1031. }
  1032. }
  1033. /**
  1034. * See if we need to append any attributes to this tag.
  1035. */
  1036. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1037. if (preg_match($matchtag, $tagname)){
  1038. $attary = array_merge($attary, $addattary);
  1039. }
  1040. }
  1041. return $attary;
  1042. }
  1043. /**
  1044. * This function edits the style definition to make them friendly and
  1045. * usable in squirrelmail.
  1046. *
  1047. * @param $message the message object
  1048. * @param $id the message id
  1049. * @param $content a string with whatever is between <style> and </style>
  1050. * @return a string with edited content.
  1051. */
  1052. function sq_fixstyle($message, $id, $content){
  1053. global $view_unsafe_images;
  1054. $me = "sq_fixstyle";
  1055. /**
  1056. * First look for general BODY style declaration, which would be
  1057. * like so:
  1058. * body {background: blah-blah}
  1059. * and change it to .bodyclass so we can just assign it to a <div>
  1060. */
  1061. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1062. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1063. /**
  1064. * Fix url('blah') declarations.
  1065. */
  1066. $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
  1067. "url(\\1$secremoveimg\\2)", $content);
  1068. /**
  1069. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1070. * is false.
  1071. */
  1072. if (!$view_unsafe_images){
  1073. $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
  1074. "url(\\1$secremoveimg\\2)", $content);
  1075. }
  1076. /**
  1077. * Fix urls that refer to cid:
  1078. */
  1079. while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
  1080. $matches)){
  1081. $cidurl = $matches{1};
  1082. $httpurl = sq_cid2http($message, $id, $cidurl);
  1083. $content = preg_replace("|url\($cidurl\)|si",
  1084. "url($httpurl)", $content);
  1085. }
  1086. /**
  1087. * Fix stupid css declarations which lead to vulnerabilities
  1088. * in IE.
  1089. */
  1090. $match = Array('/expression/si',
  1091. '/behaviou*r/si',
  1092. '/binding/si');
  1093. $replace = Array('idiocy', 'idiocy', 'idiocy');
  1094. $content = preg_replace($match, $replace, $content);
  1095. return $content;
  1096. }
  1097. /**
  1098. * This function converts cid: url's into the ones that can be viewed in
  1099. * the browser.
  1100. *
  1101. * @param $message the message object
  1102. * @param $id the message id
  1103. * @param $cidurl the cid: url.
  1104. * @return a string with a http-friendly url
  1105. */
  1106. function sq_cid2http($message, $id, $cidurl, $mailbox){
  1107. /**
  1108. * Get rid of quotes.
  1109. */
  1110. $quotchar = substr($cidurl, 0, 1);
  1111. $cidurl = str_replace($quotchar, "", $cidurl);
  1112. $cidurl = substr(trim($cidurl), 4);
  1113. $httpurl = $quotchar . "../src/download.php?absolute_dl=true&amp;" .
  1114. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  1115. "&amp;passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
  1116. return $httpurl;
  1117. }
  1118. /**
  1119. * This function changes the <body> tag into a <div> tag since we
  1120. * can't really have a body-within-body.
  1121. *
  1122. * @param $attary an array of attributes and values of <body>
  1123. * @return a modified array of attributes to be set for <div>
  1124. */
  1125. function sq_body2div($attary){
  1126. $me = "sq_body2div";
  1127. $divattary = Array("class"=>"'bodyclass'");
  1128. $bgcolor="#ffffff";
  1129. $text="#000000";
  1130. $styledef="";
  1131. if (is_array($attary) && sizeof($attary) > 0){
  1132. foreach ($attary as $attname=>$attvalue){
  1133. $quotchar = substr($attvalue, 0, 1);
  1134. $attvalue = str_replace($quotchar, "", $attvalue);
  1135. switch ($attname){
  1136. case "background":
  1137. $styledef .= "background-image: url('$attvalue'); ";
  1138. break;
  1139. case "bgcolor":
  1140. $styledef .= "background-color: $attvalue; ";
  1141. break;
  1142. case "text":
  1143. $styledef .= "color: $attvalue; ";
  1144. }
  1145. }
  1146. if (strlen($styledef) > 0){
  1147. $divattary{"style"} = "\"$styledef\"";
  1148. }
  1149. }
  1150. return $divattary;
  1151. }
  1152. /**
  1153. * This is the main function and the one you should actually be calling.
  1154. * There are several variables you should be aware of an which need
  1155. * special description.
  1156. *
  1157. * Since the description is quite lengthy, see it here:
  1158. * http://www.mricon.com/html/phpfilter.html
  1159. *
  1160. * @param $body the string with HTML you wish to filter
  1161. * @param $tag_list see description above
  1162. * @param $rm_tags_with_content see description above
  1163. * @param $self_closing_tags see description above
  1164. * @param $force_tag_closing see description above
  1165. * @param $rm_attnames see description above
  1166. * @param $bad_attvals see description above
  1167. * @param $add_attr_to_tag see description above
  1168. * @param $message message object
  1169. * @param $id message id
  1170. * @return sanitized html safe to show on your pages.
  1171. */
  1172. function sq_sanitize($body,
  1173. $tag_list,
  1174. $rm_tags_with_content,
  1175. $self_closing_tags,
  1176. $force_tag_closing,
  1177. $rm_attnames,
  1178. $bad_attvals,
  1179. $add_attr_to_tag,
  1180. $message,
  1181. $id,
  1182. $mailbox
  1183. ){
  1184. $me = "sq_sanitize";
  1185. /**
  1186. * Normalize rm_tags and rm_tags_with_content.
  1187. */
  1188. @array_walk($rm_tags, 'sq_casenormalize');
  1189. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1190. @array_walk($self_closing_tags, 'sq_casenormalize');
  1191. /**
  1192. * See if tag_list is of tags to remove or tags to allow.
  1193. * false means remove these tags
  1194. * true means allow these tags
  1195. */
  1196. $rm_tags = array_shift($tag_list);
  1197. $curpos = 0;
  1198. $open_tags = Array();
  1199. $trusted = "<!-- begin sanitized html -->\n";
  1200. $skip_content = false;
  1201. /**
  1202. * Take care of netscape's stupid javascript entities like
  1203. * &{alert('boo')};
  1204. */
  1205. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  1206. while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
  1207. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1208. $free_content = substr($body, $curpos, $lt-$curpos);
  1209. /**
  1210. * Take care of <style>
  1211. */
  1212. if ($tagname == "style" && $tagtype == 2){
  1213. /**
  1214. * This is a closing </style>. Edit the
  1215. * content before we apply it.
  1216. */
  1217. $free_content = sq_fixstyle($message, $id, $free_content);
  1218. }
  1219. if ($skip_content == false){
  1220. $trusted .= $free_content;
  1221. } else {
  1222. }
  1223. if ($tagname != FALSE){
  1224. if ($tagtype == 2){
  1225. if ($skip_content == $tagname){
  1226. /**
  1227. * Got to the end of tag we needed to remove.
  1228. */
  1229. $tagname = false;
  1230. $skip_content = false;
  1231. } else {
  1232. if ($skip_content == false){
  1233. if ($tagname == "body"){
  1234. $tagname = "div";
  1235. } else {
  1236. if (isset($open_tags{$tagname}) &&
  1237. $open_tags{$tagname} > 0){
  1238. $open_tags{$tagname}--;
  1239. } else {
  1240. $tagname = false;
  1241. }
  1242. }
  1243. } else {
  1244. }
  1245. }
  1246. } else {
  1247. /**
  1248. * $rm_tags_with_content
  1249. */
  1250. if ($skip_content == false){
  1251. /**
  1252. * See if this is a self-closing type and change
  1253. * tagtype appropriately.
  1254. */
  1255. if ($tagtype == 1
  1256. && in_array($tagname, $self_closing_tags)){
  1257. $tagtype=3;
  1258. }
  1259. /**
  1260. * See if we should skip this tag and any content
  1261. * inside it.
  1262. */
  1263. if ($tagtype == 1 &&
  1264. in_array($tagname, $rm_tags_with_content)){
  1265. $skip_content = $tagname;
  1266. } else {
  1267. if (($rm_tags == false
  1268. && in_array($tagname, $tag_list)) ||
  1269. ($rm_tags == true &&
  1270. !in_array($tagname, $tag_list))){
  1271. $tagname = false;
  1272. } else {
  1273. if ($tagtype == 1){
  1274. if (isset($open_tags{$tagname})){
  1275. $open_tags{$tagname}++;
  1276. } else {
  1277. $open_tags{$tagname}=1;
  1278. }
  1279. }
  1280. /**
  1281. * This is where we run other checks.
  1282. */
  1283. if (is_array($attary) && sizeof($attary) > 0){
  1284. $attary = sq_fixatts($tagname,
  1285. $attary,
  1286. $rm_attnames,
  1287. $bad_attvals,
  1288. $add_attr_to_tag,
  1289. $message,
  1290. $id,
  1291. $mailbox
  1292. );
  1293. }
  1294. /**
  1295. * Convert body into div.
  1296. */
  1297. if ($tagname == "body"){
  1298. $tagname = "div";
  1299. $attary = sq_body2div($attary, $message, $id);
  1300. }
  1301. }
  1302. }
  1303. } else {
  1304. }
  1305. }
  1306. if ($tagname != false && $skip_content == false){
  1307. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1308. }
  1309. } else {
  1310. }
  1311. $curpos = $gt+1;
  1312. }
  1313. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1314. if ($force_tag_closing == true){
  1315. foreach ($open_tags as $tagname=>$opentimes){
  1316. while ($opentimes > 0){
  1317. $trusted .= '</' . $tagname . '>';
  1318. $opentimes--;
  1319. }
  1320. }
  1321. $trusted .= "\n";
  1322. }
  1323. $trusted .= "<!-- end sanitized html -->\n";
  1324. return $trusted;
  1325. }
  1326. /**
  1327. * This is a wrapper function to call html sanitizing routines.
  1328. *
  1329. * @param $body the body of the message
  1330. * @param $id the id of the message
  1331. * @return a string with html safe to display in the browser.
  1332. */
  1333. function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
  1334. global $attachment_common_show_images, $view_unsafe_images,
  1335. $has_unsafe_images;
  1336. /**
  1337. * Don't display attached images in HTML mode.
  1338. */
  1339. $attachment_common_show_images = false;
  1340. $tag_list = Array(
  1341. false,
  1342. "object",
  1343. "meta",
  1344. "html",
  1345. "head",
  1346. "base",
  1347. "link"
  1348. );
  1349. $rm_tags_with_content = Array(
  1350. "script",
  1351. "applet",
  1352. "embed",
  1353. "title"
  1354. );
  1355. $self_closing_tags = Array(
  1356. "img",
  1357. "br",
  1358. "hr",
  1359. "input"
  1360. );
  1361. $force_tag_closing = false;
  1362. $rm_attnames = Array(
  1363. "/.*/" =>
  1364. Array(
  1365. "/target/si",
  1366. "/^on.*/si",
  1367. "/^dynsrc/si",
  1368. "/^data.*/si"
  1369. )
  1370. );
  1371. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1372. $bad_attvals = Array(
  1373. "/.*/" =>
  1374. Array(
  1375. "/^src|background/i" =>
  1376. Array(
  1377. Array(
  1378. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1379. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1380. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1381. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1382. ),
  1383. Array(
  1384. "\\1$secremoveimg\\2",
  1385. "\\1$secremoveimg\\2",
  1386. "\\1$secremoveimg\\2",
  1387. "\\1$secremoveimg\\2"
  1388. )
  1389. ),
  1390. "/^href|action/i" =>
  1391. Array(
  1392. Array(
  1393. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1394. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1395. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1396. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1397. ),
  1398. Array(
  1399. "\\1#\\2",
  1400. "\\1#\\2",
  1401. "\\1#\\2",
  1402. "\\1#\\2"
  1403. )
  1404. ),
  1405. "/^style/si" =>
  1406. Array(
  1407. Array(
  1408. "/expression/si",
  1409. "/binding/si",
  1410. "/behaviou*r/si",
  1411. "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
  1412. "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
  1413. "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
  1414. "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
  1415. ),
  1416. Array(
  1417. "idiocy",
  1418. "idiocy",
  1419. "idiocy",
  1420. "url(\\1#\\2)",
  1421. "url(\\1#\\2)",
  1422. "url(\\1#\\2)",
  1423. "url(\\1#\\2)"
  1424. )
  1425. )
  1426. )
  1427. );
  1428. if (!$view_unsafe_images){
  1429. /**
  1430. * Remove any references to http/https if view_unsafe_images set
  1431. * to false.
  1432. */
  1433. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  1434. '/^([\'\"])\s*https*:.*([\'\"])/si');
  1435. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  1436. "\\1$secremoveimg\\2");
  1437. array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
  1438. '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
  1439. array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
  1440. "url(\\1$secremoveimg\\2)");
  1441. }
  1442. $add_attr_to_tag = Array(
  1443. "/^a$/si" => Array('target'=>'"_new"')
  1444. );
  1445. $trusted = sq_sanitize($body,
  1446. $tag_list,
  1447. $rm_tags_with_content,
  1448. $self_closing_tags,
  1449. $force_tag_closing,
  1450. $rm_attnames,
  1451. $bad_attvals,
  1452. $add_attr_to_tag,
  1453. $message,
  1454. $id,
  1455. $mailbox
  1456. );
  1457. if (preg_match("|$secremoveimg|si", $trusted)){
  1458. $has_unsafe_images = true;
  1459. }
  1460. return $trusted;
  1461. }
  1462. ?>