mime.php 55 KB

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