PageRenderTime 72ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1_4_10a/functions/mime.php

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