PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/branches/GSoC-config/squirrelmail/functions/mime.php

#
PHP | 1665 lines | 946 code | 123 blank | 596 comment | 224 complexity | 8230f3630bfcc329d94344d646bc1381 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 12450 2007-06-08 20:14:37Z kink $
  11. * @package squirrelmail
  12. */
  13. /**
  14. * dependency information
  15. functions dependency
  16. mime_structure
  17. class/mime/Message.class.php
  18. Message::parseStructure
  19. functions/page_header.php
  20. displayPageHeader
  21. functions/display_messages.php
  22. plain_error_message
  23. mime_fetch_body
  24. functions/imap_general.php
  25. sqimap_run_command
  26. mime_print_body_lines
  27. functions/imap.php
  28. functions/attachment_common.php
  29. functions/display_messages.php
  30. magicHtml => url_parser
  31. translateText => url_parser
  32. */
  33. /* -------------------------------------------------------------------------- */
  34. /* MIME DECODING */
  35. /* -------------------------------------------------------------------------- */
  36. /**
  37. * Get the MIME structure
  38. *
  39. * This function gets the structure of a message and stores it in the "message" class.
  40. * It will return this object for use with all relevant header information and
  41. * fully parsed into the standard "message" object format.
  42. */
  43. function mime_structure ($bodystructure, $flags=array()) {
  44. /* Isolate the body structure and remove beginning and end parenthesis. */
  45. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  46. $read = trim(substr ($read, 0, -1));
  47. $i = 0;
  48. $msg = Message::parseStructure($read,$i);
  49. if (!is_object($msg)) {
  50. global $color, $mailbox;
  51. displayPageHeader( $color, $mailbox );
  52. $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
  53. $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
  54. $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
  55. plain_error_message( $errormessage );
  56. echo '</body></html>';
  57. exit;
  58. }
  59. if (count($flags)) {
  60. foreach ($flags as $flag) {
  61. //FIXME: please document why it is we have to check the first char of the flag but we then go ahead and do a full string comparison anyway. Is this a speed enhancement? If not, let's keep it simple and just compare the full string and forget the switch block.
  62. $char = strtoupper($flag{1});
  63. switch ($char) {
  64. case 'S':
  65. if (strtolower($flag) == '\\seen') {
  66. $msg->is_seen = true;
  67. }
  68. break;
  69. case 'A':
  70. if (strtolower($flag) == '\\answered') {
  71. $msg->is_answered = true;
  72. }
  73. break;
  74. case 'D':
  75. if (strtolower($flag) == '\\deleted') {
  76. $msg->is_deleted = true;
  77. }
  78. break;
  79. case 'F':
  80. if (strtolower($flag) == '\\flagged') {
  81. $msg->is_flagged = true;
  82. }
  83. break;
  84. case 'M':
  85. if (strtolower($flag) == '$mdnsent') {
  86. $msg->is_mdnsent = true;
  87. }
  88. break;
  89. default:
  90. break;
  91. }
  92. }
  93. }
  94. // listEntities($msg);
  95. return $msg;
  96. }
  97. /* This starts the parsing of a particular structure. It is called recursively,
  98. * so it can be passed different structures. It returns an object of type
  99. * $message.
  100. * First, it checks to see if it is a multipart message. If it is, then it
  101. * handles that as it sees is necessary. If it is just a regular entity,
  102. * then it parses it and adds the necessary header information (by calling out
  103. * to mime_get_elements()
  104. */
  105. function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
  106. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  107. * that it is the first one. That is usually the case anyway.
  108. */
  109. if (!$ent_id) {
  110. $cmd = "FETCH $id BODY[]";
  111. } else {
  112. $cmd = "FETCH $id BODY[$ent_id]";
  113. }
  114. if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
  115. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
  116. do {
  117. $topline = trim(array_shift($data));
  118. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
  119. $wholemessage = implode('', $data);
  120. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  121. $ret = substr($wholemessage, 0, $regs[1]);
  122. /* There is some information in the content info header that could be important
  123. * in order to parse html messages. Let's get them here.
  124. */
  125. // if ($ret{0} == '<') {
  126. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
  127. // }
  128. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  129. $ret = $regs[1];
  130. } else {
  131. global $where, $what, $mailbox, $passed_id, $startMessage;
  132. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  133. if (isset($where) && isset($what)) {
  134. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  135. } else {
  136. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  137. }
  138. $par .= '&amp;response=' . urlencode($response) .
  139. '&amp;message=' . urlencode($message) .
  140. '&amp;topline=' . urlencode($topline);
  141. echo '<tt><br />' .
  142. '<table width="80%"><tr>' .
  143. '<tr><td colspan="2">' .
  144. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  145. '</td></tr>' .
  146. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  147. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  148. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  149. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  150. "</table><br /></tt></font><hr />";
  151. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
  152. array_shift($data);
  153. $wholemessage = implode('', $data);
  154. $ret = $wholemessage;
  155. }
  156. return $ret;
  157. }
  158. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
  159. /* Don't kill the connection if the browser is over a dialup
  160. * and it would take over 30 seconds to download it.
  161. * Don't call set_time_limit in safe mode.
  162. */
  163. if (!ini_get('safe_mode')) {
  164. set_time_limit(0);
  165. }
  166. /* in case of base64 encoded attachments, do not buffer them.
  167. Instead, echo the decoded attachment directly to screen */
  168. if (strtolower($encoding) == 'base64') {
  169. if (!$ent_id) {
  170. $query = "FETCH $id BODY[]";
  171. } else {
  172. $query = "FETCH $id BODY[$ent_id]";
  173. }
  174. sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
  175. } else {
  176. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  177. if (is_resource($rStream)) {
  178. fputs($rStream,decodeBody($body,$encoding));
  179. } else {
  180. echo decodeBody($body, $encoding);
  181. }
  182. }
  183. /*
  184. TODO, use the same method for quoted printable.
  185. However, I assume that quoted printable attachments aren't that large
  186. so the performancegain / memory usage drop will be minimal.
  187. If we decide to add that then we need to adapt sqimap_fread because
  188. we need to split te result on \n and fread doesn't stop at \n. That
  189. means we also should provide $results from sqimap_fread (by ref) to
  190. te function and set $no_return to false. The $filter function for
  191. quoted printable should handle unsetting of $results.
  192. */
  193. /*
  194. TODO 2: find out how we write to the output stream php://stdout. fwrite
  195. doesn't work because 'php://stdout isn't a stream.
  196. */
  197. return;
  198. }
  199. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  200. /* This is here for debugging purposes. It will print out a list
  201. * of all the entity IDs that are in the $message object.
  202. */
  203. function listEntities ($message) {
  204. if ($message) {
  205. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br />';
  206. for ($i = 0; isset($message->entities[$i]); $i++) {
  207. echo "$i : ";
  208. $msg = listEntities($message->entities[$i]);
  209. if ($msg) {
  210. echo "return: ";
  211. return $msg;
  212. }
  213. }
  214. }
  215. }
  216. function getPriorityStr($priority) {
  217. $priority_level = substr($priority,0,1);
  218. switch($priority_level) {
  219. /* Check for a higher then normal priority. */
  220. case '1':
  221. case '2':
  222. $priority_string = _("High");
  223. break;
  224. /* Check for a lower then normal priority. */
  225. case '4':
  226. case '5':
  227. $priority_string = _("Low");
  228. break;
  229. /* Check for a normal priority. */
  230. case '3':
  231. default:
  232. $priority_level = '3';
  233. $priority_string = _("Normal");
  234. break;
  235. }
  236. return $priority_string;
  237. }
  238. /* returns a $message object for a particular entity id */
  239. function getEntity ($message, $ent_id) {
  240. return $message->getEntity($ent_id);
  241. }
  242. /* translateText
  243. * Extracted from strings.php 23/03/2002
  244. */
  245. function translateText(&$body, $wrap_at, $charset) {
  246. global $where, $what; /* from searching */
  247. global $color; /* color theme */
  248. // require_once(SM_PATH . 'functions/url_parser.php');
  249. $body_ary = explode("\n", $body);
  250. for ($i=0; $i < count($body_ary); $i++) {
  251. $line = $body_ary[$i];
  252. if (strlen($line) - 2 >= $wrap_at) {
  253. sqWordWrap($line, $wrap_at, $charset);
  254. }
  255. $line = charset_decode($charset, $line);
  256. $line = str_replace("\t", ' ', $line);
  257. parseUrl ($line);
  258. $quotes = 0;
  259. $pos = 0;
  260. $j = strlen($line);
  261. while ($pos < $j) {
  262. if ($line[$pos] == ' ') {
  263. $pos++;
  264. } else if (strpos($line, '&gt;', $pos) === $pos) {
  265. $pos += 4;
  266. $quotes++;
  267. } else {
  268. break;
  269. }
  270. }
  271. if ($quotes % 2) {
  272. $line = '<span class="quote1">' . $line . '</span>';
  273. } elseif ($quotes) {
  274. $line = '<span class="quote2">' . $line . '</span>';
  275. }
  276. $body_ary[$i] = $line;
  277. }
  278. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  279. }
  280. /**
  281. * This returns a parsed string called $body. That string can then
  282. * be displayed as the actual message in the HTML. It contains
  283. * everything needed, including HTML Tags, Attachments at the
  284. * bottom, etc.
  285. *
  286. * Since 1.2.0 function uses message_body hook.
  287. * Till 1.3.0 function included output of formatAttachments().
  288. *
  289. * @param resource $imap_stream imap connection resource
  290. * @param object $message squirrelmail message object
  291. * @param array $color squirrelmail color theme array
  292. * @param integer $wrap_at number of characters per line
  293. * @param string $ent_num (since 1.3.0) message part id
  294. * @param integer $id (since 1.3.0) message id
  295. * @param string $mailbox (since 1.3.0) imap folder name
  296. * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
  297. * @return string html formated message text
  298. */
  299. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
  300. /* This if statement checks for the entity to show as the
  301. * primary message. To add more of them, just put them in the
  302. * order that is their priority.
  303. */
  304. global $startMessage, $languages, $squirrelmail_language,
  305. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id,
  306. $use_iframe, $iframe_height, $download_and_unsafe_link,
  307. $download_href, $unsafe_image_toggle_href, $unsafe_image_toggle_text,
  308. $oTemplate;
  309. $nbsp = $oTemplate->fetch('non_breaking_space.tpl');
  310. // workaround for not updated config.php
  311. if (! isset($use_iframe)) $use_iframe = false;
  312. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  313. $view_unsafe_images = false;
  314. }
  315. $body = '';
  316. $urlmailbox = urlencode($mailbox);
  317. $body_message = getEntity($message, $ent_num);
  318. if (($body_message->header->type0 == 'text') ||
  319. ($body_message->header->type0 == 'rfc822')) {
  320. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  321. $body = decodeBody($body, $body_message->header->encoding);
  322. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  323. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
  324. if (mb_detect_encoding($body) != 'ASCII') {
  325. $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
  326. }
  327. }
  328. /* As of 1.5.2, $body is passed (and modified) by reference */
  329. do_hook('message_body', $body);
  330. /* If there are other types that shouldn't be formatted, add
  331. * them here.
  332. */
  333. if ($body_message->header->type1 == 'html') {
  334. if ($show_html_default <> 1) {
  335. $entity_conv = array('&nbsp;' => ' ',
  336. '<p>' => "\n",
  337. '<P>' => "\n",
  338. '<br>' => "\n",
  339. '<BR>' => "\n",
  340. '<br />' => "\n",
  341. '<BR />' => "\n",
  342. '&gt;' => '>',
  343. '&lt;' => '<');
  344. $body = strtr($body, $entity_conv);
  345. $body = strip_tags($body);
  346. $body = trim($body);
  347. translateText($body, $wrap_at,
  348. $body_message->header->getParameter('charset'));
  349. } elseif ($use_iframe && ! $clean) {
  350. // $clean is used to remove iframe in printable view.
  351. /**
  352. * If we don't add html message between iframe tags,
  353. * we must detect unsafe images and modify $has_unsafe_images.
  354. */
  355. $html_body = magicHTML($body, $id, $message, $mailbox);
  356. // Convert character set in order to display html mails in different character set
  357. $html_body = charset_decode($body_message->header->getParameter('charset'),$html_body,false,true);
  358. // creating iframe url
  359. $iframeurl=sqm_baseuri().'src/view_html.php?'
  360. . 'mailbox=' . $urlmailbox
  361. . '&amp;passed_id=' . $id
  362. . '&amp;ent_id=' . $ent_num
  363. . '&amp;view_unsafe_images=' . (int) $view_unsafe_images;
  364. global $oTemplate;
  365. $oTemplate->assign('iframe_url', $iframeurl);
  366. $oTemplate->assign('html_body', $html_body);
  367. $body = $oTemplate->fetch('read_html_iframe.tpl');
  368. } else {
  369. // old way of html rendering
  370. /**
  371. * convert character set. charset_decode does not remove html special chars
  372. * applied by magicHTML functions and does not sanitize them second time if
  373. * fourth argument is true.
  374. */
  375. $charset = $body_message->header->getParameter('charset');
  376. if (!empty($charset)) {
  377. $body = charset_decode($charset,$body,false,true);
  378. }
  379. $body = magicHTML($body, $id, $message, $mailbox);
  380. }
  381. } else {
  382. translateText($body, $wrap_at,
  383. $body_message->header->getParameter('charset'));
  384. }
  385. // if this is the clean display (i.e. printer friendly), stop here.
  386. if ( $clean ) {
  387. return $body;
  388. }
  389. $download_and_unsafe_link = '';
  390. $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
  391. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  392. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  393. if (isset($passed_ent_id)) {
  394. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  395. }
  396. $download_href = SM_PATH . 'src/download.php?absolute_dl=true&amp;' . $link;
  397. $download_and_unsafe_link .= "$nbsp|$nbsp"
  398. . create_hyperlink($download_href, _("Download this as a file"));
  399. if ($view_unsafe_images) {
  400. $text = _("Hide Unsafe Images");
  401. } else {
  402. if (isset($has_unsafe_images) && $has_unsafe_images) {
  403. $link .= '&amp;view_unsafe_images=1';
  404. $text = _("View Unsafe Images");
  405. } else {
  406. $text = '';
  407. }
  408. }
  409. if($text != '') {
  410. $unsafe_image_toggle_href = SM_PATH . 'src/read_body.php?'.$link;
  411. $unsafe_image_toggle_text = $text;
  412. $download_and_unsafe_link .= "$nbsp|$nbsp"
  413. . create_hyperlink($unsafe_image_toggle_href, $text);
  414. }
  415. }
  416. return $body;
  417. }
  418. /**
  419. * Generate attachments array for passing to templates. Separated from
  420. * formatAttachments() below so that the same array can be given to the
  421. * print-friendly version.
  422. *
  423. * @since 1.5.2
  424. * @param object $message SquirrelMail message object
  425. * @param array $exclude_id message parts that are not attachments.
  426. * @param string $mailbox mailbox name
  427. * @param integer $id message id
  428. */
  429. function buildAttachmentArray($message, $exclude_id, $mailbox, $id) {
  430. global $where, $what, $startMessage, $color, $passed_ent_id, $base_uri;
  431. $att_ar = $message->getAttachments($exclude_id);
  432. $urlMailbox = urlencode($mailbox);
  433. $attachments = array();
  434. foreach ($att_ar as $att) {
  435. $ent = $att->entity_id;
  436. $header = $att->header;
  437. $type0 = strtolower($header->type0);
  438. $type1 = strtolower($header->type1);
  439. $name = '';
  440. $links = array();
  441. $links['download link']['text'] = _("Download");
  442. $links['download link']['href'] = $base_uri .
  443. "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  444. if ($type0 =='message' && $type1 == 'rfc822') {
  445. $default_page = $base_uri . 'src/read_body.php';
  446. $rfc822_header = $att->rfc822_header;
  447. $filename = $rfc822_header->subject;
  448. if (trim( $filename ) == '') {
  449. $filename = 'untitled-[' . $ent . ']' ;
  450. }
  451. $from_o = $rfc822_header->from;
  452. if (is_object($from_o)) {
  453. $from_name = decodeHeader($from_o->getAddress(false));
  454. } elseif (is_array($from_o) && count($from_o) && is_object($from_o[0])) {
  455. // something weird happens when a digest message is opened and you return to the digest
  456. // now the from object is part of an array. Probably the parseHeader call overwrites the info
  457. // retrieved from the bodystructure in a different way. We need to fix this later.
  458. // possible starting point, do not fetch header we already have and inspect how
  459. // the rfc822_header object behaves.
  460. $from_name = decodeHeader($from_o[0]->getAddress(false));
  461. } else {
  462. $from_name = _("Unknown sender");
  463. }
  464. $description = _("From").': '.$from_name;
  465. } else {
  466. $default_page = $base_uri . 'src/download.php';
  467. $filename = $att->getFilename();
  468. if ($header->description) {
  469. $description = decodeHeader($header->description);
  470. } else {
  471. $description = '';
  472. }
  473. }
  474. $display_filename = $filename;
  475. if (isset($passed_ent_id)) {
  476. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  477. } else {
  478. $passed_ent_id_link = '';
  479. }
  480. $defaultlink = $default_page . "?startMessage=$startMessage"
  481. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  482. . '&amp;ent_id='.$ent.$passed_ent_id_link;
  483. if ($where && $what) {
  484. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  485. }
  486. // IE does make use of mime content sniffing. Forcing a download
  487. // prohibit execution of XSS inside an application/octet-stream attachment
  488. if ($type0 == 'application' && $type1 == 'octet-stream') {
  489. $defaultlink .= '&amp;absolute_dl=true';
  490. }
  491. /* This executes the attachment hook with a specific MIME-type.
  492. * If that doesn't have results, it tries if there's a rule
  493. * for a more generic type. Finally, a hook for ALL attachment
  494. * types is run as well.
  495. */
  496. /* The API for this hook has changed as of 1.5.2 so that all plugin
  497. arguments are passed in an array instead of each their own plugin
  498. argument, and arguments are passed by reference, so instead of
  499. returning any changes, changes should simply be made to the original
  500. arguments themselves. */
  501. do_hook("attachment $type0/$type1", $temp=array(&$links,
  502. &$startMessage, &$id, &$urlMailbox, &$ent, &$defaultlink,
  503. &$display_filename, &$where, &$what));
  504. if(count($links) <= 1) {
  505. /* The API for this hook has changed as of 1.5.2 so that all plugin
  506. arguments are passed in an array instead of each their own plugin
  507. argument, and arguments are passed by reference, so instead of
  508. returning any changes, changes should simply be made to the original
  509. arguments themselves. */
  510. do_hook("attachment $type0/*", $temp=array(&$links,
  511. &$startMessage, &$id, &$urlMailbox, &$ent, &$defaultlink,
  512. &$display_filename, &$where, &$what));
  513. }
  514. /* The API for this hook has changed as of 1.5.2 so that all plugin
  515. arguments are passed in an array instead of each their own plugin
  516. argument, and arguments are passed by reference, so instead of
  517. returning any changes, changes should simply be made to the original
  518. arguments themselves. */
  519. do_hook("attachment */*", $temp=array(&$links,
  520. &$startMessage, &$id, &$urlMailbox, &$ent, &$defaultlink,
  521. &$display_filename, &$where, &$what));
  522. $this_attachment = array();
  523. $this_attachment['Name'] = decodeHeader($display_filename);
  524. $this_attachment['Description'] = $description;
  525. $this_attachment['DefaultHREF'] = $defaultlink;
  526. $this_attachment['DownloadHREF'] = $links['download link']['href'];
  527. $this_attachment['ViewHREF'] = isset($links['attachment_common']) ? $links['attachment_common']['href'] : '';
  528. $this_attachment['Size'] = $header->size;
  529. $this_attachment['ContentType'] = htmlspecialchars($type0 .'/'. $type1);
  530. $this_attachment['OtherLinks'] = array();
  531. foreach ($links as $val) {
  532. if ($val['text']==_("Download") || $val['text'] == _("View"))
  533. continue;
  534. if (empty($val['text']) && empty($val['extra']))
  535. continue;
  536. $temp = array();
  537. $temp['HREF'] = $val['href'];
  538. $temp['Text'] = (empty($val['text']) ? '' : $val['text']) . (empty($val['extra']) ? '' : $val['extra']);
  539. $this_attachment['OtherLinks'][] = $temp;
  540. }
  541. $attachments[] = $this_attachment;
  542. unset($links);
  543. }
  544. return $attachments;
  545. }
  546. /**
  547. * Displays attachment links and information
  548. *
  549. * Since 1.3.0 function is not included in formatBody() call.
  550. *
  551. * Since 1.0.2 uses attachment $type0/$type1 hook.
  552. * Since 1.2.5 uses attachment $type0/* hook.
  553. * Since 1.5.0 uses attachments_bottom hook.
  554. * Since 1.5.2 uses templates and does *not* return a value.
  555. *
  556. * @param object $message SquirrelMail message object
  557. * @param array $exclude_id message parts that are not attachments.
  558. * @param string $mailbox mailbox name
  559. * @param integer $id message id
  560. */
  561. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  562. global $oTemplate;
  563. $attach = buildAttachmentArray($message, $exclude_id, $mailbox, $id);
  564. $oTemplate->assign('attachments', $attach);
  565. $oTemplate->display('read_attachments.tpl');
  566. }
  567. function sqimap_base64_decode(&$string) {
  568. // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  569. // fly decoding (to reduce memory usage) you have to check if the
  570. // data has incomplete pairs
  571. // Remove the noise in order to check if the 4 bytes pairs are complete
  572. $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
  573. $sStringRem = '';
  574. $iMod = strlen($string) % 4;
  575. if ($iMod) {
  576. $sStringRem = substr($string,-$iMod);
  577. // Check if $sStringRem contains padding characters
  578. if (substr($sStringRem,-1) != '=') {
  579. $string = substr($string,0,-$iMod);
  580. } else {
  581. $sStringRem = '';
  582. }
  583. }
  584. $string = base64_decode($string);
  585. return $sStringRem;
  586. }
  587. /**
  588. * Decodes encoded message body
  589. *
  590. * This function decodes the body depending on the encoding type.
  591. * Currently quoted-printable and base64 encodings are supported.
  592. * decode_body hook was added to this function in 1.4.2/1.5.0
  593. * @param string $body encoded message body
  594. * @param string $encoding used encoding
  595. * @return string decoded string
  596. * @since 1.0
  597. */
  598. function decodeBody($body, $encoding) {
  599. $body = str_replace("\r\n", "\n", $body);
  600. $encoding = strtolower($encoding);
  601. $encoding_handler = do_hook('decode_body', $encoding);
  602. // plugins get first shot at decoding the body
  603. //
  604. if (!empty($encoding_handler) && function_exists($encoding_handler)) {
  605. $body = $encoding_handler('decode', $body);
  606. } elseif ($encoding == 'quoted-printable' ||
  607. $encoding == 'quoted_printable') {
  608. /**
  609. * quoted_printable_decode() function is broken in older
  610. * php versions. Text with \r\n decoding was fixed only
  611. * in php 4.3.0. Minimal code requirement 4.0.4 +
  612. * str_replace("\r\n", "\n", $body); call.
  613. */
  614. $body = quoted_printable_decode($body);
  615. } elseif ($encoding == 'base64') {
  616. $body = base64_decode($body);
  617. }
  618. // All other encodings are returned raw.
  619. return $body;
  620. }
  621. /**
  622. * Decodes headers
  623. *
  624. * This function decodes strings that are encoded according to
  625. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  626. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  627. *
  628. * @param string $string header string that has to be made readable
  629. * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
  630. * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
  631. * @param boolean $decide decide if string can be utfencoded. defaults to false
  632. * @return string decoded header string
  633. */
  634. function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
  635. global $languages, $squirrelmail_language,$default_charset;
  636. if (is_array($string)) {
  637. $string = implode("\n", $string);
  638. }
  639. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  640. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
  641. $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
  642. // Do we need to return at this point?
  643. // return $string;
  644. }
  645. $i = 0;
  646. $iLastMatch = -2;
  647. $encoded = true;
  648. $aString = explode(' ',$string);
  649. $ret = '';
  650. foreach ($aString as $chunk) {
  651. if ($encoded && $chunk === '') {
  652. continue;
  653. } elseif ($chunk === '') {
  654. $ret .= ' ';
  655. continue;
  656. }
  657. $encoded = false;
  658. /* if encoded words are not separated by a linear-space-white we still catch them */
  659. $j = $i-1;
  660. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  661. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  662. if ($iLastMatch !== $j) {
  663. if ($htmlsave) {
  664. $ret .= '&#32;';
  665. } else {
  666. $ret .= ' ';
  667. }
  668. }
  669. $iLastMatch = $i;
  670. $j = $i;
  671. if ($htmlsave) {
  672. $ret .= htmlspecialchars($res[1]);
  673. } else {
  674. $ret .= $res[1];
  675. }
  676. $encoding = ucfirst($res[3]);
  677. /* decide about valid decoding */
  678. if ($decide && is_conversion_safe($res[2])) {
  679. $utfencode=true;
  680. $can_be_encoded=true;
  681. } else {
  682. $can_be_encoded=false;
  683. }
  684. switch ($encoding)
  685. {
  686. case 'B':
  687. $replace = base64_decode($res[4]);
  688. if ($utfencode) {
  689. if ($can_be_encoded) {
  690. /* convert string to different charset,
  691. * if functions asks for it (usually in compose)
  692. */
  693. $ret .= charset_convert($res[2],$replace,$default_charset,$htmlsave);
  694. } else {
  695. // convert string to html codes in order to display it
  696. $ret .= charset_decode($res[2],$replace);
  697. }
  698. } else {
  699. if ($htmlsave) {
  700. $replace = htmlspecialchars($replace);
  701. }
  702. $ret.= $replace;
  703. }
  704. break;
  705. case 'Q':
  706. $replace = str_replace('_', ' ', $res[4]);
  707. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  708. $replace);
  709. if ($utfencode) {
  710. if ($can_be_encoded) {
  711. /* convert string to different charset,
  712. * if functions asks for it (usually in compose)
  713. */
  714. $replace = charset_convert($res[2], $replace,$default_charset,$htmlsave);
  715. } else {
  716. // convert string to html codes in order to display it
  717. $replace = charset_decode($res[2], $replace);
  718. }
  719. } else {
  720. if ($htmlsave) {
  721. $replace = htmlspecialchars($replace);
  722. }
  723. }
  724. $ret .= $replace;
  725. break;
  726. default:
  727. break;
  728. }
  729. $chunk = $res[5];
  730. $encoded = true;
  731. }
  732. if (!$encoded) {
  733. if ($htmlsave) {
  734. $ret .= '&#32;';
  735. } else {
  736. $ret .= ' ';
  737. }
  738. }
  739. if (!$encoded && $htmlsave) {
  740. $ret .= htmlspecialchars($chunk);
  741. } else {
  742. $ret .= $chunk;
  743. }
  744. ++$i;
  745. }
  746. /* remove the first added space */
  747. if ($ret) {
  748. if ($htmlsave) {
  749. $ret = substr($ret,5);
  750. } else {
  751. $ret = substr($ret,1);
  752. }
  753. }
  754. return $ret;
  755. }
  756. /**
  757. * Encodes header
  758. *
  759. * Function uses XTRA_CODE _encodeheader function, if such function exists.
  760. *
  761. * Function uses Q encoding by default and encodes a string according to RFC
  762. * 1522 for use in headers if it contains 8-bit characters or anything that
  763. * looks like it should be encoded.
  764. *
  765. * Function switches to B encoding and encodeHeaderBase64() function, if
  766. * string is 8bit and multibyte character set supported by mbstring extension
  767. * is used. It can cause E_USER_NOTICE errors, if interface is used with
  768. * multibyte character set unsupported by mbstring extension.
  769. *
  770. * @param string $string header string, that has to be encoded
  771. * @return string quoted-printable encoded string
  772. * @todo make $mb_charsets system wide constant
  773. */
  774. function encodeHeader ($string) {
  775. global $default_charset, $languages, $squirrelmail_language;
  776. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  777. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
  778. return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
  779. }
  780. // Use B encoding for multibyte charsets
  781. $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
  782. if (in_array($default_charset,$mb_charsets) &&
  783. in_array($default_charset,sq_mb_list_encodings()) &&
  784. sq_is8bit($string)) {
  785. return encodeHeaderBase64($string,$default_charset);
  786. } elseif (in_array($default_charset,$mb_charsets) &&
  787. sq_is8bit($string) &&
  788. ! in_array($default_charset,sq_mb_list_encodings())) {
  789. // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
  790. // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
  791. }
  792. // Encode only if the string contains 8-bit characters or =?
  793. $j = strlen($string);
  794. $max_l = 75 - strlen($default_charset) - 7;
  795. $aRet = array();
  796. $ret = '';
  797. $iEncStart = $enc_init = false;
  798. $cur_l = $iOffset = 0;
  799. for($i = 0; $i < $j; ++$i) {
  800. switch($string{$i})
  801. {
  802. case '=':
  803. case '<':
  804. case '>':
  805. case ',':
  806. case '?':
  807. case '_':
  808. if ($iEncStart === false) {
  809. $iEncStart = $i;
  810. }
  811. $cur_l+=3;
  812. if ($cur_l > ($max_l-2)) {
  813. /* if there is an stringpart that doesn't need encoding, add it */
  814. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  815. $aRet[] = "=?$default_charset?Q?$ret?=";
  816. $iOffset = $i;
  817. $cur_l = 0;
  818. $ret = '';
  819. $iEncStart = false;
  820. } else {
  821. $ret .= sprintf("=%02X",ord($string{$i}));
  822. }
  823. break;
  824. case '(':
  825. case ')':
  826. if ($iEncStart !== false) {
  827. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  828. $aRet[] = "=?$default_charset?Q?$ret?=";
  829. $iOffset = $i;
  830. $cur_l = 0;
  831. $ret = '';
  832. $iEncStart = false;
  833. }
  834. break;
  835. case ' ':
  836. if ($iEncStart !== false) {
  837. $cur_l++;
  838. if ($cur_l > $max_l) {
  839. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  840. $aRet[] = "=?$default_charset?Q?$ret?=";
  841. $iOffset = $i;
  842. $cur_l = 0;
  843. $ret = '';
  844. $iEncStart = false;
  845. } else {
  846. $ret .= '_';
  847. }
  848. }
  849. break;
  850. default:
  851. $k = ord($string{$i});
  852. if ($k > 126) {
  853. if ($iEncStart === false) {
  854. // do not start encoding in the middle of a string, also take the rest of the word.
  855. $sLeadString = substr($string,0,$i);
  856. $aLeadString = explode(' ',$sLeadString);
  857. $sToBeEncoded = array_pop($aLeadString);
  858. $iEncStart = $i - strlen($sToBeEncoded);
  859. $ret .= $sToBeEncoded;
  860. $cur_l += strlen($sToBeEncoded);
  861. }
  862. $cur_l += 3;
  863. /* first we add the encoded string that reached it's max size */
  864. if ($cur_l > ($max_l-2)) {
  865. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  866. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  867. $cur_l = 3;
  868. $ret = '';
  869. $iOffset = $i;
  870. $iEncStart = $i;
  871. }
  872. $enc_init = true;
  873. $ret .= sprintf("=%02X", $k);
  874. } else {
  875. if ($iEncStart !== false) {
  876. $cur_l++;
  877. if ($cur_l > $max_l) {
  878. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  879. $aRet[] = "=?$default_charset?Q?$ret?=";
  880. $iEncStart = false;
  881. $iOffset = $i;
  882. $cur_l = 0;
  883. $ret = '';
  884. } else {
  885. $ret .= $string{$i};
  886. }
  887. }
  888. }
  889. break;
  890. }
  891. }
  892. if ($enc_init) {
  893. if ($iEncStart !== false) {
  894. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  895. $aRet[] = "=?$default_charset?Q?$ret?=";
  896. } else {
  897. $aRet[] = substr($string,$iOffset);
  898. }
  899. $string = implode('',$aRet);
  900. }
  901. return $string;
  902. }
  903. /**
  904. * Encodes string according to rfc2047 B encoding header formating rules
  905. *
  906. * It is recommended way to encode headers with character sets that store
  907. * symbols in more than one byte.
  908. *
  909. * Function requires mbstring support. If required mbstring functions are missing,
  910. * function returns false and sets E_USER_WARNING level error message.
  911. *
  912. * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
  913. * that mbstring functions will generate E_WARNING errors, if unsupported
  914. * character set is used. mb_encode_mimeheader function provided by php
  915. * mbstring extension is not used in order to get better control of header
  916. * encoding.
  917. *
  918. * Used php code functions - function_exists(), trigger_error(), strlen()
  919. * (is used with charset names and base64 strings). Used php mbstring
  920. * functions - mb_strlen and mb_substr.
  921. *
  922. * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
  923. * encoding), rfc 2822 (header folding)
  924. *
  925. * @param string $string header string that must be encoded
  926. * @param string $charset character set. Must be supported by mbstring extension.
  927. * Use sq_mb_list_encodings() to detect supported charsets.
  928. * @return string string encoded according to rfc2047 B encoding formating rules
  929. * @since 1.5.1
  930. * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
  931. * @todo Do we want to control max length of header?
  932. * @todo Do we want to control EOL (end-of-line) marker?
  933. * @todo Do we want to translate error message?
  934. */
  935. function encodeHeaderBase64($string,$charset) {
  936. /**
  937. * Check mbstring function requirements.
  938. */
  939. if (! function_exists('mb_strlen') ||
  940. ! function_exists('mb_substr')) {
  941. // set E_USER_WARNING
  942. trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
  943. // return false
  944. return false;
  945. }
  946. // initial return array
  947. $aRet = array();
  948. /**
  949. * header length = 75 symbols max (same as in encodeHeader)
  950. * remove $charset length
  951. * remove =? ? ?= (5 chars)
  952. * remove 2 more chars (\r\n ?)
  953. */
  954. $iMaxLength = 75 - strlen($charset) - 7;
  955. // set first character position
  956. $iStartCharNum = 0;
  957. // loop through all characters. count characters and not bytes.
  958. for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++) {
  959. // encode string from starting character to current character.
  960. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  961. // Check encoded string length
  962. if(strlen($encoded_string)>$iMaxLength) {
  963. // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
  964. $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
  965. // set new starting character
  966. $iStartCharNum = $iCharNum-1;
  967. // encode last char (in case it is last character in string)
  968. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  969. } // if string is shorter than max length - add next character
  970. }
  971. // add last encoded string to array
  972. $aRet[] = $encoded_string;
  973. // set initial return string
  974. $sRet = '';
  975. // loop through encoded strings
  976. foreach($aRet as $string) {
  977. // TODO: Do we want to control EOL (end-of-line) marker
  978. if ($sRet!='') $sRet.= " ";
  979. // add header tags and encoded string to return string
  980. $sRet.= '=?'.$charset.'?B?'.$string.'?=';
  981. }
  982. return $sRet;
  983. }
  984. /* This function trys to locate the entity_id of a specific mime element */
  985. function find_ent_id($id, $message) {
  986. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  987. if ($message->entities[$i]->header->type0 == 'multipart') {
  988. $ret = find_ent_id($id, $message->entities[$i]);
  989. } else {
  990. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  991. // if (sq_check_save_extension($message->entities[$i])) {
  992. return $message->entities[$i]->entity_id;
  993. // }
  994. } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
  995. /**
  996. * This is part of a fix for Outlook Express 6.x generating
  997. * cid URLs without creating content-id headers
  998. * @@JA - 20050207
  999. */
  1000. if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
  1001. return $message->entities[$i]->entity_id;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. return $ret;
  1007. }
  1008. function sq_check_save_extension($message) {
  1009. $filename = $message->getFilename();
  1010. $ext = substr($filename, strrpos($filename,'.')+1);
  1011. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  1012. return in_array($ext, $save_extensions);
  1013. }
  1014. /**
  1015. ** HTMLFILTER ROUTINES
  1016. */
  1017. /**
  1018. * This function checks attribute values for entity-encoded values
  1019. * and returns them translated into 8-bit strings so we can run
  1020. * checks on them.
  1021. *
  1022. * @param $attvalue A string to run entity check against.
  1023. * @return Nothing, modifies a reference value.
  1024. */
  1025. function sq_defang(&$attvalue){
  1026. $me = 'sq_defang';
  1027. /**
  1028. * Skip this if there aren't ampersands or backslashes.
  1029. */
  1030. if (strpos($attvalue, '&') === false
  1031. && strpos($attvalue, '\\') === false){
  1032. return;
  1033. }
  1034. $m = false;
  1035. // before deent, translate the dangerous unicode characters and ... to safe values
  1036. // otherwise the regular expressions do not match.
  1037. do {
  1038. $m = false;
  1039. $m = $m || sq_deent($attvalue, '/\&#0*(\d+);*/s');
  1040. $m = $m || sq_deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
  1041. $m = $m || sq_deent($attvalue, '/\\\\(\d+)/s', true);
  1042. } while ($m == true);
  1043. $attvalue = stripslashes($attvalue);
  1044. }
  1045. /**
  1046. * Kill any tabs, newlines, or carriage returns. Our friends the
  1047. * makers of the browser with 95% market value decided that it'd
  1048. * be funny to make "java[tab]script" be just as good as "javascript".
  1049. *
  1050. * @param attvalue The attribute value before extraneous spaces removed.
  1051. * @return attvalue Nothing, modifies a reference value.
  1052. */
  1053. function sq_unspace(&$attvalue){
  1054. $me = 'sq_unspace';
  1055. if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
  1056. $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
  1057. Array('', '', '', '', ''), $attvalue);
  1058. }
  1059. }
  1060. /**
  1061. * Translate all dangerous Unicode or Shift_JIS characters which are accepted by
  1062. * IE as regular characters.
  1063. *
  1064. * @param attvalue The attribute value before dangerous characters are translated.
  1065. * @return attvalue Nothing, modifies a reference value.
  1066. * @author Marc Groot Koerkamp.
  1067. */
  1068. function sq_fixIE_idiocy(&$attvalue) {
  1069. // remove NUL
  1070. $attvalue = str_replace("\0", "", $attvalue);
  1071. // remove comments
  1072. $attvalue = preg_replace("/(\/\*.*?\*\/)/","",$attvalue);
  1073. // IE has the evil habit of accepting every possible value for the attribute expression.
  1074. // The table below contains characters which are parsed by IE if they are used in the "expression"
  1075. // attribute value.
  1076. $aDangerousCharsReplacementTable = array(
  1077. array('&#x029F;', '&#0671;' ,/* L UNICODE IPA Extension */
  1078. '&#x0280;', '&#0640;' ,/* R UNICODE IPA Extension */
  1079. '&#x0274;', '&#0628;' ,/* N UNICODE IPA Extension */
  1080. '&#xFF25;', '&#65317;' ,/* Unicode FULLWIDTH LATIN CAPITAL LETTER E */
  1081. '&#xFF45;', '&#65349;' ,/* Unicode FULLWIDTH LATIN SMALL LETTER E */
  1082. '&#xFF38;', '&#65336;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER X */
  1083. '&#xFF58;', '&#65368;',/* Unicode FULLWIDTH LATIN SMALL LETTER X */
  1084. '&#xFF30;', '&#65328;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER P */
  1085. '&#xFF50;', '&#65360;',/* Unicode FULLWIDTH LATIN SMALL LETTER P */
  1086. '&#xFF32;', '&#65330;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER R */
  1087. '&#xFF52;', '&#65362;',/* Unicode FULLWIDTH LATIN SMALL LETTER R */
  1088. '&#xFF33;', '&#65331;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER S */
  1089. '&#xFF53;', '&#65363;',/* Unicode FULLWIDTH LATIN SMALL LETTER S */
  1090. '&#xFF29;', '&#65321;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER I */
  1091. '&#xFF49;', '&#65353;',/* Unicode FULLWIDTH LATIN SMALL LETTER I */
  1092. '&#xFF2F;', '&#65327;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER O */
  1093. '&#xFF4F;', '&#65359;',/* Unicode FULLWIDTH LATIN SMALL LETTER O */
  1094. '&#xFF2E;', '&#65326;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER N */
  1095. '&#xFF4E;', '&#65358;',/* Unicode FULLWIDTH LATIN SMALL LETTER N */
  1096. '&#xFF2C;', '&#65324;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER L */
  1097. '&#xFF4C;', '&#65356;',/* Unicode FULLWIDTH LATIN SMALL LETTER L */
  1098. '&#xFF35;', '&#65333;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER U */
  1099. '&#xFF55;', '&#65365;',/* Unicode FULLWIDTH LATIN SMALL LETTER U */
  1100. '&#x207F;', '&#8319;' ,/* Unicode SUPERSCRIPT LATIN SMALL LETTER N */
  1101. "\xEF\xBC\xA5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER E */ // in unicode this is some Chinese char range
  1102. "\xEF\xBD\x85", /* Shift JIS FULLWIDTH LATIN SMALL LETTER E */
  1103. "\xEF\xBC\xB8", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER X */
  1104. "\xEF\xBD\x98", /* Shift JIS FULLWIDTH LATIN SMALL LETTER X */
  1105. "\xEF\xBC\xB0", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER P */
  1106. "\xEF\xBD\x90", /* Shift JIS FULLWIDTH LATIN SMALL LETTER P */
  1107. "\xEF\xBC\xB2", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER R */
  1108. "\xEF\xBD\x92", /* Shift JIS FULLWIDTH LATIN SMALL LETTER R */
  1109. "\xEF\xBC\xB3", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER S */
  1110. "\xEF\xBD\x93", /* Shift JIS FULLWIDTH LATIN SMALL LETTER S */
  1111. "\xEF\xBC\xA9", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER I */
  1112. "\xEF\xBD\x89", /* Shift JIS FULLWIDTH LATIN SMALL LETTER I */
  1113. "\xEF\xBC\xAF", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER O */
  1114. "\xEF\xBD\x8F", /* Shift JIS FULLWIDTH LATIN SMALL LETTER O */
  1115. "\xEF\xBC\xAE", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER N */
  1116. "\xEF\xBD\x8E", /* Shift JIS FULLWIDTH LATIN SMALL LETTER N */
  1117. "\xEF\xBC\xAC", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER L */
  1118. "\xEF\xBD\x8C", /* Shift JIS FULLWIDTH LATIN SMALL LETTER L */
  1119. "\xEF\xBC\xB5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER U */
  1120. "\xEF\xBD\x95", /* Shift JIS FULLWIDTH LATIN SMALL LETTER U */
  1121. "\xE2\x81\xBF", /* Shift JIS FULLWIDTH SUPERSCRIPT N */
  1122. "\xCA\x9F", /* L UNICODE IPA Extension */
  1123. "\xCA\x80", /* R UNICODE IPA Extension */
  1124. "\xC9\xB4"), /* N UNICODE IPA Extension */
  1125. array('l', 'l', 'r','r','n','n',
  1126. 'E','E','e','e','X','X','x','x','P','P','p','p','R','R','r','r','S','S','s','s','I','I',
  1127. 'i','i','O','O','o','o','N','N','n','n','L','L','l','l','U','U','u','u','n','n',
  1128. 'E','e','X','x','P','p','R','r','S','s','I','i','O','o','N','n','L','l','U','u','n','l','r','n'));
  1129. $attvalue = str_replace($aDangerousCharsReplacementTable[0],$aDangerousCharsReplacementTable[1],$attvalue);
  1130. // Escapes are useful for special characters like "{}[]()'&. In other cases they are
  1131. // used for XSS.
  1132. $attvalue = preg_replace("/(\\\\)([a-zA-Z]{1})/",'$2',$attvalue);
  1133. }
  1134. /**
  1135. * This function returns the final tag out of the tag name, an array
  1136. * of attributes, and the type of the tag. This function is called by
  1137. * sq_sanitize internally.
  1138. *
  1139. * @param $tagname the name of the tag.
  1140. * @param $attary the array of attributes and their values
  1141. * @param $tagtype The type of the tag (see in comments).
  1142. * @return a string with the final tag representation.
  1143. */
  1144. function sq_tagprint($tagname, $attary, $tagtype){
  1145. $me = 'sq_tagprint';
  1146. if ($tagtype == 2){
  1147. $fulltag = '</' . $tagname . '>';
  1148. } else {
  1149. $fulltag = '<' . $tagname;
  1150. if (is_array($attary) && sizeof($attary)){
  1151. $atts = Array();
  1152. while (list($attname, $attvalue) = each($attary)){
  1153. array_push($atts, "$attname=$attvalue");
  1154. }
  1155. $fulltag .= ' ' . join(" ", $atts);
  1156. }
  1157. if ($tagtype == 3){
  1158. $fulltag .= ' /';
  1159. }
  1160. $fulltag .= '>';
  1161. }
  1162. return $fulltag;
  1163. }
  1164. /**
  1165. * A small helper function to use with array_walk. Modifies a by-ref
  1166. * value and makes it lowercase.
  1167. *
  1168. * @param $val a value passed by-ref.
  1169. * @return void since it modifies a by-ref value.
  1170. */
  1171. function sq_casenormalize(&$val){
  1172. $val = strtolower($val);
  1173. }
  1174. /**
  1175. * This function skips any whitespace from the current position within
  1176. * a string and to the next non-whitespace value.
  1177. *
  1178. * @param $body the string
  1179. * @param $offset the offset within the string where we should start
  1180. * looking for the next non-whitespace character.
  1181. * @return the location within the $body where the next
  1182. * non-whitespace char is located.
  1183. */
  1184. function sq_skipspace($body, $offset){
  1185. $me = 'sq_skipspace';
  1186. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  1187. if (sizeof($matches{1})){
  1188. $count = strlen($matches{1});
  1189. $offset += $count;
  1190. }
  1191. return $offset;
  1192. }
  1193. /**
  1194. * This function looks for the next character within a string. It's
  1195. * really just a glorified "strpos", except it catches if failures
  1196. * nicely.
  1197. *
  1198. * @param $body The string to look for needle in.
  1199. * @param $offset Start looking from this position.
  1200. * @param $needle The character/string to look for.
  1201. * @return location of the next occurance of the needle, or
  1202. * strlen($body) if needle wasn't found.
  1203. */
  1204. function sq_findnxstr($body, $offset, $needle){
  1205. $me = 'sq_findnxstr';
  1206. $pos = strpos($body, $needle, $offset);
  1207. if ($pos === FALSE){
  1208. $pos = strlen($body);
  1209. }
  1210. return $pos;
  1211. }
  1212. /**
  1213. * This function takes a PCRE-style regexp and tries to match it
  1214. * within the string.
  1215. *
  1216. * @param $body The string to look for needle in.
  1217. * @param $offset Start looking from here.
  1218. * @param $reg A PCRE-style regex to match.
  1219. * @return Returns a false if no matches found, or an array
  1220. * with the following members:
  1221. * - integer with the location of the match within $body
  1222. * - string with whatever content between offset and the match
  1223. * - string with whatever it is we matched
  1224. */
  1225. function sq_findnxreg($body, $offset, $reg){
  1226. $me = 'sq_findnxreg';
  1227. $matches = Array();
  1228. $retarr = Array();
  1229. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  1230. if (!isset($matches{0}) || !$matches{0}){
  1231. $retarr = false;
  1232. } else {
  1233. $retarr{0} = $offset + strlen($matches{1});
  1234. $retarr{1} = $matches{1};
  1235. $retarr{2} = $matches{2};
  1236. }
  1237. return $retarr;
  1238. }
  1239. /**
  1240. * This function looks for the next tag.
  1241. *
  1242. * @param $body String where to look for the next tag.
  1243. * @param $offset Start looking from here.
  1244. * @return false if no more tags exist in the body, or
  1245. * an array with the following members:
  1246. * - string with the name of the tag
  1247. * - array with attributes and their values
  1248. * - integer with tag type (1, 2, or 3)
  1249. * - integer where the tag starts (starting "<")
  1250. * - integer where the tag ends (ending ">")
  1251. * first three members will be false, if the tag is invalid.
  1252. */
  1253. function sq_getnxtag($body, $offset){
  1254. $me = 'sq_getnxtag';
  1255. if ($offset > strlen($body)){
  1256. return false;
  1257. }
  1258. $lt = sq_findnxstr($body, $offset, "<");
  1259. if ($lt == strlen($body)){
  1260. return false;
  1261. }
  1262. /**
  1263. * We are here:
  1264. * blah blah <tag attribute="value">
  1265. * \---------^
  1266. */
  1267. $pos = sq_skipspace($body, $lt+1);
  1268. if ($pos >= strlen($body)){
  1269. return Array(false, false, false, $lt, strlen($body));
  1270. }
  1271. /**
  1272. * There are 3 kinds of tags:
  1273. * 1. Opening tag, e.g.:
  1274. * <a href="blah">
  1275. * 2. Closing tag, e.g.:
  1276. * </a>
  1277. * 3. XHTML-style content-less tag, e.g.:
  1278. * <img src="blah" />
  1279. */
  1280. $tagtype = false;
  1281. switch (substr($body, $pos, 1)){
  1282. case '/':
  1283. $tagtype = 2;
  1284. $pos++;
  1285. break;
  1286. case '!':
  1287. /**
  1288. * A comment or an SGML declaration.
  1289. */
  1290. if (substr($body, $pos+1, 2) == "--"){
  1291. $gt = strpos($body, "-->", $pos);
  1292. if ($gt === false){
  1293. $gt = strlen($body);
  1294. } else {
  1295. $gt += 2;
  1296. }
  1297. return Array(false, false, false, $lt, $gt);
  1298. } else {
  1299. $gt = sq_findnxstr($body, $pos, ">");
  1300. return Array(false, false, false, $lt, $gt);
  1301. }
  1302. break;
  1303. default:
  1304. /**
  1305. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1306. * later.
  1307. */
  1308. $tagtype = 1;
  1309. break;
  1310. }
  1311. $tag_start = $pos;
  1312. $tagname = '';
  1313. /**
  1314. * Look for next [\W-_], which will indicate the end of the tag name.
  1315. */
  1316. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1317. if ($regary == false){
  1318. return Array(false, false, false, $lt, strlen($body));
  1319. }
  1320. list($pos, $tagname, $match) = $regary;
  1321. $tagname = strtolower($tagname);
  1322. /**
  1323. * $match can be either of these:
  1324. * '>' indicating the end of the tag entirely.
  1325. * '\s' indicating the end of the tag name.
  1326. * '/' indicating that this is type-3 xhtml tag.
  1327. *
  1328. * Whatever else we find there indicates an invalid tag.
  1329. */
  1330. switch ($match){
  1331. case '/':
  1332. /**
  1333. * This is an xhtml-style tag with a closing / at the
  1334. * end, like so: <img src="blah" />. Check if it's followed
  1335. * by the closing bracket. If not, then this tag is invalid
  1336. */
  1337. if (substr($body, $pos, 2) == "/>"){
  1338. $pos++;
  1339. $tagtype = 3;
  1340. } else {
  1341. $gt = sq_findnxstr($body, $pos, ">");
  1342. $retary = Array(false, false, false, $lt, $gt);
  1343. return $retary;
  1344. }
  1345. case '>':
  1346. return Array($tagname, false, $tagtype, $lt, $pos);
  1347. break;
  1348. default:
  1349. /**
  1350. * Check if it's whitespace
  1351. */
  1352. if (!preg_match('/\s/', $match)){
  1353. /**
  1354. * This is an invalid tag! Look for the next closing ">".
  1355. */
  1356. $gt = sq_findnxstr($body, $lt, ">");
  1357. return Array(false, false, false, $lt, $gt);
  1358. }
  1359. break;
  1360. }
  1361. /**
  1362. * At this point we're here:
  1363. * <tagname attribute='blah'>
  1364. * \-------^
  1365. *
  1366. * At this point we loop in order to find all attributes.
  1367. */
  1368. $attname = '';
  1369. $atttype = false;
  1370. $attary = Array();
  1371. while ($pos <= strlen($body)){
  1372. $pos = sq_skipspace($body, $pos);
  1373. if ($pos == strlen($body)){
  1374. /**
  1375. * Non-closed tag.
  1376. */
  1377. return Array(false, false, false, $lt, $pos);
  1378. }
  1379. /**
  1380. * See if we arrived at a ">" or "/>", which means that we reached
  1381. * the end of the tag.
  1382. */
  1383. $matches = Array();
  1384. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  1385. /**
  1386. * Yep. So we did.
  1387. */
  1388. $pos += strlen($matches{1});
  1389. if ($matches{2} == "/>"){
  1390. $tagtype = 3;
  1391. $pos++;
  1392. }
  1393. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1394. }
  1395. /**
  1396. * There are several types of attributes, with optional
  1397. * [:space:] between members.
  1398. * Type 1:
  1399. * attrname[:space:]=[:space:]'CDATA'
  1400. * Type 2:
  1401. * attrname[:space:]=[:space:]"CDATA"
  1402. * Type 3:
  1403. * attr[:space:]=[:space:]CDATA
  1404. * Type 4:
  1405. * attrname
  1406. *
  1407. * We leave types 1 and 2 the same, type 3 we check for
  1408. * '"' and convert to "&quot" if needed, then wrap in
  1409. * double quotes. Type 4 we convert into:
  1410. * attrname="yes".
  1411. */
  1412. $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
  1413. if ($regary == false){
  1414. /**
  1415. * Looks like body ended before the end of tag.
  1416. */
  1417. return Array(false, false, false, $lt, strlen($body));
  1418. }
  1419. list($pos, $attname, $match) = $regary;
  1420. $attname = strtolower($attname);
  1421. /**
  1422. * We arrived at the end of attribute name. Several things possible
  1423. * here:
  1424. * '>' means the end of the tag and this is attribute type 4
  1425. * '/' if followed by '>' means the same thing as above
  1426. * '\s' means a lot of things -- look what it's followed by.
  1427. * anything else means the attribute is invalid.
  1428. */
  1429. switch($match){
  1430. case '/':
  1431. /**
  1432. * This is an xhtml-style tag with a closing / at the
  1433. * end, like so: <img src="blah" />. Check if it's followed
  1434. * by the closing bracket. If not, then this tag is invalid
  1435. */
  1436. if (substr($body, $pos, 2) == "/>"){
  1437. $pos++;
  1438. $tagtype = 3;
  1439. } else {
  1440. $gt = sq_findnxstr($body, $pos, ">");
  1441. $retary = Array(false, false, false, $lt, $gt);
  1442. return $retary;
  1443. }
  1444. case '>':
  1445. $attary{$attname} = '"yes"';
  1446. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1447. break;
  1448. default:
  1449. /**
  1450. * Skip whitespace and see what we arrive at.
  1451. */
  1452. $pos = sq_skipspace($body, $pos);
  1453. $char = substr($body, $pos, 1);
  1454. /**
  1455. * Two things are valid here:
  1456. * '=' means this is attribute type 1 2 or 3.
  1457. * \w means this was attribute type 4.
  1458. * anything else we ignore and re-loop. End of tag and
  1459. * invalid stuff will be caught by our checks at the beginning
  1460. * of the loop.
  1461. */
  1462. if ($char == "="){
  1463. $pos++;
  1464. $pos = sq_skipspace($body, $pos);
  1465. /**
  1466. * Here are 3 possibilities:
  1467. * "'" attribute type 1
  1468. * '"' attribute type 2
  1469. * everything else is the content of tag type 3
  1470. */
  1471. $quot = substr($body, $pos, 1);
  1472. if ($quot == "'"){
  1473. $regary = sq_findnxreg($body, $pos+1, "\'");
  1474. if ($regary == false){
  1475. return Array(false, false, false, $lt, strlen($body));
  1476. }
  1477. list($pos, $attval, $match) = $regary;
  1478. $pos++;
  1479. $attary{$attname} = "'" . $attval . "'";
  1480. } else if ($quot == '"'){
  1481. $regary = sq_findnxreg($body, $pos+1, '\"');
  1482. if ($regary == false){
  1483. return Array(false, false, false, $lt, strlen($body));
  1484. }
  1485. list($pos, $attval, $match) = $regary;
  1486. $pos++;
  1487. $attary{$attname} = '"' . $attval . '"';
  1488. } else {
  1489. /**
  1490. * These are hateful. Look for \s, or >.
  1491. */
  1492. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1493. if ($regary == false){
  1494. return Array(false, false, false, $lt, strlen($body));
  1495. }
  1496. list($pos, $attval, $match) = $regary;
  1497. /**
  1498. * If it's ">" it will be caught at the top.
  1499. */
  1500. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1501. $attary{$attname} = '"' . $attval . '"';
  1502. }
  1503. } else if (preg_match("|[\w/>]|", $char)) {
  1504. /**
  1505. * That was attribute type 4.
  1506. */
  1507. $attary{$attname} = '"yes"';
  1508. } else {
  1509. /**
  1510. * An illegal character. Find next '>' and return.
  1511. */
  1512. $gt = sq_findnxstr($body, $pos, ">");
  1513. return Array(false, false, false, $lt, $gt);
  1514. }
  1515. break;
  1516. }
  1517. }
  1518. /**
  1519. * The fact that we got here indicates that the tag end was never
  1520. * found. Return invalid tag indication so it gets stripped.
  1521. */
  1522. return Array(false, false, false, $lt, strlen($body));
  1523. }
  1524. /**
  1525. * Translates entities into literal values so they can be checked.
  1526. *
  1527. * @param $attvalue the by-ref value to check.
  1528. * @param $regex the regular expression to check against.
  1529. * @param $hex whether the entites are hexadecimal