PageRenderTime 74ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/test-1_4_8utf8_1/squirrelmail/functions/mime.php

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