mime.php 57 KB

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