PageRenderTime 56ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/rel-1_5_1/squirrelmail/functions/mime.php

#
PHP | 2390 lines | 1392 code | 166 blank | 832 comment | 337 complexity | 29c9622efa4f8a1b9f4e3b42b0a07f8f MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * This contains the functions necessary to detect and decode MIME
  6. * messages.
  7. *
  8. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id: mime.php 10703 2006-02-11 11:13:05Z stekkel $
  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. /** add sqm_baseuri()*/
  17. include_once(SM_PATH . 'functions/display_messages.php');
  18. /* -------------------------------------------------------------------------- */
  19. /* MIME DECODING */
  20. /* -------------------------------------------------------------------------- */
  21. /**
  22. * Get the MIME structure
  23. *
  24. * This function gets the structure of a message and stores it in the "message" class.
  25. * It will return this object for use with all relevant header information and
  26. * fully parsed into the standard "message" object format.
  27. */
  28. function mime_structure ($bodystructure, $flags=array()) {
  29. /* Isolate the body structure and remove beginning and end parenthesis. */
  30. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  31. $read = trim(substr ($read, 0, -1));
  32. $i = 0;
  33. $msg = Message::parseStructure($read,$i);
  34. if (!is_object($msg)) {
  35. include_once(SM_PATH . 'functions/display_messages.php');
  36. global $color, $mailbox;
  37. /* removed urldecode because $_GET is auto urldecoded ??? */
  38. displayPageHeader( $color, $mailbox );
  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 .= '<pre>' . htmlspecialchars($read) . '</pre>';
  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. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  93. * that it is the first one. That is usually the case anyway.
  94. */
  95. if (!$ent_id) {
  96. $cmd = "FETCH $id BODY[]";
  97. } else {
  98. $cmd = "FETCH $id BODY[$ent_id]";
  99. }
  100. if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
  101. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
  102. do {
  103. $topline = trim(array_shift($data));
  104. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
  105. $wholemessage = implode('', $data);
  106. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  107. $ret = substr($wholemessage, 0, $regs[1]);
  108. /* There is some information in the content info header that could be important
  109. * in order to parse html messages. Let's get them here.
  110. */
  111. // if ($ret{0} == '<') {
  112. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
  113. // }
  114. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  115. $ret = $regs[1];
  116. } else {
  117. global $where, $what, $mailbox, $passed_id, $startMessage;
  118. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  119. if (isset($where) && isset($what)) {
  120. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  121. } else {
  122. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  123. }
  124. $par .= '&amp;response=' . urlencode($response) .
  125. '&amp;message=' . urlencode($message) .
  126. '&amp;topline=' . urlencode($topline);
  127. echo '<tt><br />' .
  128. '<table width="80%"><tr>' .
  129. '<tr><td colspan="2">' .
  130. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  131. '</td></tr>' .
  132. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  133. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  134. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  135. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  136. "</table><br /></tt></font><hr />";
  137. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
  138. array_shift($data);
  139. $wholemessage = implode('', $data);
  140. $ret = $wholemessage;
  141. }
  142. return $ret;
  143. }
  144. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
  145. /* Don't kill the connection if the browser is over a dialup
  146. * and it would take over 30 seconds to download it.
  147. * Don't call set_time_limit in safe mode.
  148. */
  149. if (!ini_get('safe_mode')) {
  150. set_time_limit(0);
  151. }
  152. /* in case of base64 encoded attachments, do not buffer them.
  153. Instead, echo the decoded attachment directly to screen */
  154. if (strtolower($encoding) == 'base64') {
  155. if (!$ent_id) {
  156. $query = "FETCH $id BODY[]";
  157. } else {
  158. $query = "FETCH $id BODY[$ent_id]";
  159. }
  160. sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
  161. } else {
  162. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  163. if (is_resource($rStream)) {
  164. fputs($rStream,decodeBody($body,$encoding));
  165. } else {
  166. echo decodeBody($body, $encoding);
  167. }
  168. }
  169. /*
  170. TODO, use the same method for quoted printable.
  171. However, I assume that quoted printable attachments aren't that large
  172. so the performancegain / memory usage drop will be minimal.
  173. If we decide to add that then we need to adapt sqimap_fread because
  174. we need to split te result on \n and fread doesn't stop at \n. That
  175. means we also should provide $results from sqimap_fread (by ref) to
  176. te function and set $no_return to false. The $filter function for
  177. quoted printable should handle unsetting of $results.
  178. */
  179. /*
  180. TODO 2: find out how we write to the output stream php://stdout. fwrite
  181. doesn't work because 'php://stdout isn't a stream.
  182. */
  183. return;
  184. }
  185. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  186. /* This is here for debugging purposes. It will print out a list
  187. * of all the entity IDs that are in the $message object.
  188. */
  189. function listEntities ($message) {
  190. if ($message) {
  191. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br />';
  192. for ($i = 0; isset($message->entities[$i]); $i++) {
  193. echo "$i : ";
  194. $msg = listEntities($message->entities[$i]);
  195. if ($msg) {
  196. echo "return: ";
  197. return $msg;
  198. }
  199. }
  200. }
  201. }
  202. function getPriorityStr($priority) {
  203. $priority_level = substr($priority,0,1);
  204. switch($priority_level) {
  205. /* Check for a higher then normal priority. */
  206. case '1':
  207. case '2':
  208. $priority_string = _("High");
  209. break;
  210. /* Check for a lower then normal priority. */
  211. case '4':
  212. case '5':
  213. $priority_string = _("Low");
  214. break;
  215. /* Check for a normal priority. */
  216. case '3':
  217. default:
  218. $priority_level = '3';
  219. $priority_string = _("Normal");
  220. break;
  221. }
  222. return $priority_string;
  223. }
  224. /* returns a $message object for a particular entity id */
  225. function getEntity ($message, $ent_id) {
  226. return $message->getEntity($ent_id);
  227. }
  228. /* translateText
  229. * Extracted from strings.php 23/03/2002
  230. */
  231. function translateText(&$body, $wrap_at, $charset) {
  232. global $where, $what; /* from searching */
  233. global $color; /* color theme */
  234. require_once(SM_PATH . 'functions/url_parser.php');
  235. $body_ary = explode("\n", $body);
  236. for ($i=0; $i < count($body_ary); $i++) {
  237. $line = $body_ary[$i];
  238. if (strlen($line) - 2 >= $wrap_at) {
  239. sqWordWrap($line, $wrap_at, $charset);
  240. }
  241. $line = charset_decode($charset, $line);
  242. $line = str_replace("\t", ' ', $line);
  243. parseUrl ($line);
  244. $quotes = 0;
  245. $pos = 0;
  246. $j = strlen($line);
  247. while ($pos < $j) {
  248. if ($line[$pos] == ' ') {
  249. $pos++;
  250. } else if (strpos($line, '&gt;', $pos) === $pos) {
  251. $pos += 4;
  252. $quotes++;
  253. } else {
  254. break;
  255. }
  256. }
  257. if ($quotes % 2) {
  258. if (!isset($color[13])) {
  259. $color[13] = '#800000';
  260. }
  261. $line = '<font color="' . $color[13] . '">' . $line . '</font>';
  262. } elseif ($quotes) {
  263. if (!isset($color[14])) {
  264. $color[14] = '#FF0000';
  265. }
  266. $line = '<font color="' . $color[14] . '">' . $line . '</font>';
  267. }
  268. $body_ary[$i] = $line;
  269. }
  270. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  271. }
  272. /**
  273. * This returns a parsed string called $body. That string can then
  274. * be displayed as the actual message in the HTML. It contains
  275. * everything needed, including HTML Tags, Attachments at the
  276. * bottom, etc.
  277. *
  278. * Since 1.2.0 function uses message_body hook.
  279. * Till 1.3.0 function included output of formatAttachments().
  280. *
  281. * @param resource $imap_stream imap connection resource
  282. * @param object $message squirrelmail message object
  283. * @param array $color squirrelmail color theme array
  284. * @param integer $wrap_at number of characters per line
  285. * @param string $ent_num (since 1.3.0) message part id
  286. * @param integer $id (since 1.3.0) message id
  287. * @param string $mailbox (since 1.3.0) imap folder name
  288. * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
  289. * @return string html formated message text
  290. */
  291. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
  292. /* This if statement checks for the entity to show as the
  293. * primary message. To add more of them, just put them in the
  294. * order that is their priority.
  295. */
  296. global $startMessage, $languages, $squirrelmail_language,
  297. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id,
  298. $use_iframe, $iframe_height, $download_and_unsafe_link;
  299. // workaround for not updated config.php
  300. if (! isset($use_iframe)) $use_iframe = false;
  301. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  302. $view_unsafe_images = false;
  303. }
  304. $body = '';
  305. $urlmailbox = urlencode($mailbox);
  306. $body_message = getEntity($message, $ent_num);
  307. if (($body_message->header->type0 == 'text') ||
  308. ($body_message->header->type0 == 'rfc822')) {
  309. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  310. $body = decodeBody($body, $body_message->header->encoding);
  311. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  312. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
  313. if (mb_detect_encoding($body) != 'ASCII') {
  314. $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
  315. }
  316. }
  317. $hookResults = do_hook("message_body", $body);
  318. $body = $hookResults[1];
  319. /* If there are other types that shouldn't be formatted, add
  320. * them here.
  321. */
  322. if ($body_message->header->type1 == 'html') {
  323. if ($show_html_default <> 1) {
  324. $entity_conv = array('&nbsp;' => ' ',
  325. '<p>' => "\n",
  326. '<P>' => "\n",
  327. '<br>' => "\n",
  328. '<BR>' => "\n",
  329. '<br />' => "\n",
  330. '<BR />' => "\n",
  331. '&gt;' => '>',
  332. '&lt;' => '<');
  333. $body = strtr($body, $entity_conv);
  334. $body = strip_tags($body);
  335. $body = trim($body);
  336. translateText($body, $wrap_at,
  337. $body_message->header->getParameter('charset'));
  338. } elseif ($use_iframe && ! $clean) {
  339. // $clean is used to remove iframe in printable view.
  340. /**
  341. * If we don't add html message between iframe tags,
  342. * we must detect unsafe images and modify $has_unsafe_images.
  343. */
  344. $html_body = magicHTML($body, $id, $message, $mailbox);
  345. // Convert character set in order to display html mails in different character set
  346. $html_body = charset_decode($body_message->header->getParameter('charset'),$html_body,false,true);
  347. // creating iframe url
  348. $iframeurl=sqm_baseuri().'src/view_html.php?'
  349. . 'mailbox=' . $urlmailbox
  350. . '&amp;passed_id=' . $id
  351. . '&amp;ent_id=' . $ent_num
  352. . '&amp;view_unsafe_images=' . (int) $view_unsafe_images;
  353. // adding warning message
  354. $body = html_tag('div',_("Viewing HTML formatted email"),'center');
  355. /**
  356. * height can't be set to 100%, because it does not work as expected when
  357. * iframe is inside the table. Browsers do not create full height objects
  358. * even when iframe is not nested. Maybe there is some way to get full size
  359. * with CSS. Tested in firefox 1.02 and opera 7.53
  360. *
  361. * width="100%" does not work as expected, when table width is not set (automatic)
  362. *
  363. * tokul: I think <iframe> are safer sandbox than <object>. Objects might
  364. * need special handling for IE and IE6SP2.
  365. */
  366. $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
  367. .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
  368. // Message for browsers without iframe support
  369. //$body.= _("Your browser does not support inline frames.
  370. // You can view HTML formated message by following below link.");
  371. //$body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
  372. // if browser can't render iframe, it renders html message.
  373. $body.= $html_body;
  374. // close iframe
  375. $body.="</iframe></div>\n";
  376. } else {
  377. // old way of html rendering
  378. $body = magicHTML($body, $id, $message, $mailbox);
  379. /**
  380. * convert character set. charset_decode does not remove html special chars
  381. * applied by magicHTML functions and does not sanitize them second time if
  382. * fourth argument is true.
  383. */
  384. $body = charset_decode($body_message->header->getParameter('charset'),$body,false,true);
  385. }
  386. } else {
  387. translateText($body, $wrap_at,
  388. $body_message->header->getParameter('charset'));
  389. }
  390. // if this is the clean display (i.e. printer friendly), stop here.
  391. if ( $clean ) {
  392. return $body;
  393. }
  394. $download_and_unsafe_link = '';
  395. $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
  396. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  397. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  398. if (isset($passed_ent_id)) {
  399. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  400. }
  401. $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="download.php?absolute_dl=true&amp;' .
  402. $link . '">' . _("Download this as a file") . '</a>';
  403. if ($view_unsafe_images) {
  404. $text = _("Hide Unsafe Images");
  405. } else {
  406. if (isset($has_unsafe_images) && $has_unsafe_images) {
  407. $link .= '&amp;view_unsafe_images=1';
  408. $text = _("View Unsafe Images");
  409. } else {
  410. $text = '';
  411. }
  412. }
  413. if($text != '') {
  414. $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="read_body.php?' . $link . '">' . $text . '</a>';
  415. }
  416. }
  417. return $body;
  418. }
  419. /**
  420. * Displays attachment links and information
  421. *
  422. * Since 1.3.0 function is not included in formatBody() call.
  423. *
  424. * Since 1.0.2 uses attachment $type0/$type1 hook.
  425. * Since 1.2.5 uses attachment $type0/* hook.
  426. * Since 1.5.0 uses attachments_bottom hook.
  427. *
  428. * @param object $message SquirrelMail message object
  429. * @param array $exclude_id message parts that are not attachments.
  430. * @param string $mailbox mailbox name
  431. * @param integer $id message id
  432. * @return string html formated attachment information.
  433. */
  434. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  435. global $where, $what, $startMessage, $color, $passed_ent_id;
  436. $att_ar = $message->getAttachments($exclude_id);
  437. if (!count($att_ar)) return '';
  438. $attachments = '';
  439. $urlMailbox = urlencode($mailbox);
  440. foreach ($att_ar as $att) {
  441. $ent = $att->entity_id;
  442. $header = $att->header;
  443. $type0 = strtolower($header->type0);
  444. $type1 = strtolower($header->type1);
  445. $name = '';
  446. $links['download link']['text'] = _("Download");
  447. $links['download link']['href'] = sqm_baseuri() .
  448. "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  449. if ($type0 =='message' && $type1 == 'rfc822') {
  450. $default_page = sqm_baseuri() . 'src/read_body.php';
  451. $rfc822_header = $att->rfc822_header;
  452. $filename = $rfc822_header->subject;
  453. if (trim( $filename ) == '') {
  454. $filename = 'untitled-[' . $ent . ']' ;
  455. }
  456. $from_o = $rfc822_header->from;
  457. if (is_object($from_o)) {
  458. $from_name = decodeHeader($from_o->getAddress(false));
  459. } elseif (is_array($from_o) && count($from_o) && is_object($from_o[0])) {
  460. // something weird happens when a digest message is opened and you return to the digest
  461. // now the from object is part of an array. Probably the parseHeader call overwrites the info
  462. // retrieved from the bodystructure in a different way. We need to fix this later.
  463. // possible starting point, do not fetch header we already have and inspect how
  464. // the rfc822_header object behaves.
  465. $from_name = decodeHeader($from_o[0]->getAddress(false));
  466. } else {
  467. $from_name = _("Unknown sender");
  468. }
  469. $description = $from_name;
  470. } else {
  471. $default_page = sqm_baseuri() . 'src/download.php';
  472. $filename = $att->getFilename();
  473. if ($header->description) {
  474. $description = decodeHeader($header->description);
  475. } else {
  476. $description = '';
  477. }
  478. }
  479. $display_filename = $filename;
  480. if (isset($passed_ent_id)) {
  481. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  482. } else {
  483. $passed_ent_id_link = '';
  484. }
  485. $defaultlink = $default_page . "?startMessage=$startMessage"
  486. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  487. . '&amp;ent_id='.$ent.$passed_ent_id_link;
  488. if ($where && $what) {
  489. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  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.
  494. */
  495. $hookresults = do_hook("attachment $type0/$type1", $links,
  496. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  497. $display_filename, $where, $what);
  498. if(count($hookresults[1]) <= 1) {
  499. $hookresults = do_hook("attachment $type0/*", $links,
  500. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  501. $display_filename, $where, $what);
  502. }
  503. $links = $hookresults[1];
  504. $defaultlink = $hookresults[6];
  505. $attachments .= '<tr><td>' .
  506. '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a>&nbsp;</td>' .
  507. '<td><small><b>' . show_readable_size($header->size) .
  508. '</b>&nbsp;&nbsp;</small></td>' .
  509. '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ]&nbsp;</small></td>' .
  510. '<td><small>';
  511. $attachments .= '<b>' . $description . '</b>';
  512. $attachments .= '</small></td><td><small>&nbsp;';
  513. $skipspaces = 1;
  514. foreach ($links as $val) {
  515. if ($skipspaces) {
  516. $skipspaces = 0;
  517. } else {
  518. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  519. }
  520. $attachments .= '<a href="' . $val['href'] . '">'
  521. . (isset($val['text']) && !empty($val['text']) ? $val['text'] : '')
  522. . (isset($val['extra']) && !empty($val['extra']) ? $val['extra'] : '')
  523. . '</a>';
  524. }
  525. unset($links);
  526. $attachments .= "</td></tr>\n";
  527. }
  528. $attachmentadd = do_hook_function('attachments_bottom',$attachments);
  529. if ($attachmentadd != '')
  530. $attachments = $attachmentadd;
  531. return $attachments;
  532. }
  533. function sqimap_base64_decode(&$string) {
  534. // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  535. // fly decoding (to reduce memory usage) you have to check if the
  536. // data has incomplete pairs
  537. // Remove the noise in order to check if the 4 bytes pairs are complete
  538. $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
  539. $sStringRem = '';
  540. $iMod = strlen($string) % 4;
  541. if ($iMod) {
  542. $sStringRem = substr($string,-$iMod);
  543. // Check if $sStringRem contains padding characters
  544. if (substr($sStringRem,-1) != '=') {
  545. $string = substr($string,0,-$iMod);
  546. } else {
  547. $sStringRem = '';
  548. }
  549. }
  550. $string = base64_decode($string);
  551. return $sStringRem;
  552. }
  553. /**
  554. * Decodes encoded message body
  555. *
  556. * This function decodes the body depending on the encoding type.
  557. * Currently quoted-printable and base64 encodings are supported.
  558. * decode_body hook was added to this function in 1.4.2/1.5.0
  559. * @param string $body encoded message body
  560. * @param string $encoding used encoding
  561. * @return string decoded string
  562. * @since 1.0
  563. */
  564. function decodeBody($body, $encoding) {
  565. $body = str_replace("\r\n", "\n", $body);
  566. $encoding = strtolower($encoding);
  567. $encoding_handler = do_hook_function('decode_body', $encoding);
  568. // plugins get first shot at decoding the body
  569. //
  570. if (!empty($encoding_handler) && function_exists($encoding_handler)) {
  571. $body = $encoding_handler('decode', $body);
  572. } elseif ($encoding == 'quoted-printable' ||
  573. $encoding == 'quoted_printable') {
  574. /**
  575. * quoted_printable_decode() function is broken in older
  576. * php versions. Text with \r\n decoding was fixed only
  577. * in php 4.3.0. Minimal code requirement 4.0.4 +
  578. * str_replace("\r\n", "\n", $body); call.
  579. */
  580. $body = quoted_printable_decode($body);
  581. } elseif ($encoding == 'base64') {
  582. $body = base64_decode($body);
  583. }
  584. // All other encodings are returned raw.
  585. return $body;
  586. }
  587. /**
  588. * Decodes headers
  589. *
  590. * This functions decode strings that is encoded according to
  591. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  592. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  593. *
  594. * @param string $string header string that has to be made readable
  595. * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
  596. * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
  597. * @param boolean $decide decide if string can be utfencoded. defaults to false
  598. * @return string decoded header string
  599. */
  600. function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
  601. global $languages, $squirrelmail_language,$default_charset;
  602. if (is_array($string)) {
  603. $string = implode("\n", $string);
  604. }
  605. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  606. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
  607. $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
  608. // Do we need to return at this point?
  609. // return $string;
  610. }
  611. $i = 0;
  612. $iLastMatch = -2;
  613. $encoded = true;
  614. $aString = explode(' ',$string);
  615. $ret = '';
  616. foreach ($aString as $chunk) {
  617. if ($encoded && $chunk === '') {
  618. continue;
  619. } elseif ($chunk === '') {
  620. $ret .= ' ';
  621. continue;
  622. }
  623. $encoded = false;
  624. /* if encoded words are not separated by a linear-space-white we still catch them */
  625. $j = $i-1;
  626. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  627. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  628. if ($iLastMatch !== $j) {
  629. if ($htmlsave) {
  630. $ret .= '&#32;';
  631. } else {
  632. $ret .= ' ';
  633. }
  634. }
  635. $iLastMatch = $i;
  636. $j = $i;
  637. if ($htmlsave) {
  638. $ret .= htmlspecialchars($res[1]);
  639. } else {
  640. $ret .= $res[1];
  641. }
  642. $encoding = ucfirst($res[3]);
  643. /* decide about valid decoding */
  644. if ($decide && is_conversion_safe($res[2])) {
  645. $utfencode=true;
  646. $can_be_encoded=true;
  647. } else {
  648. $can_be_encoded=false;
  649. }
  650. switch ($encoding)
  651. {
  652. case 'B':
  653. $replace = base64_decode($res[4]);
  654. if ($utfencode) {
  655. if ($can_be_encoded) {
  656. /* convert string to different charset,
  657. * if functions asks for it (usually in compose)
  658. */
  659. $ret .= charset_convert($res[2],$replace,$default_charset);
  660. } else {
  661. // convert string to html codes in order to display it
  662. $ret .= charset_decode($res[2],$replace);
  663. }
  664. } else {
  665. if ($htmlsave) {
  666. $replace = htmlspecialchars($replace);
  667. }
  668. $ret.= $replace;
  669. }
  670. break;
  671. case 'Q':
  672. $replace = str_replace('_', ' ', $res[4]);
  673. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  674. $replace);
  675. if ($utfencode) {
  676. if ($can_be_encoded) {
  677. /* convert string to different charset,
  678. * if functions asks for it (usually in compose)
  679. */
  680. $replace = charset_convert($res[2], $replace,$default_charset);
  681. } else {
  682. // convert string to html codes in order to display it
  683. $replace = charset_decode($res[2], $replace);
  684. }
  685. } else {
  686. if ($htmlsave) {
  687. $replace = htmlspecialchars($replace);
  688. }
  689. }
  690. $ret .= $replace;
  691. break;
  692. default:
  693. break;
  694. }
  695. $chunk = $res[5];
  696. $encoded = true;
  697. }
  698. if (!$encoded) {
  699. if ($htmlsave) {
  700. $ret .= '&#32;';
  701. } else {
  702. $ret .= ' ';
  703. }
  704. }
  705. if (!$encoded && $htmlsave) {
  706. $ret .= htmlspecialchars($chunk);
  707. } else {
  708. $ret .= $chunk;
  709. }
  710. ++$i;
  711. }
  712. /* remove the first added space */
  713. if ($ret) {
  714. if ($htmlsave) {
  715. $ret = substr($ret,5);
  716. } else {
  717. $ret = substr($ret,1);
  718. }
  719. }
  720. return $ret;
  721. }
  722. /**
  723. * Encodes header
  724. *
  725. * Function uses XTRA_CODE _encodeheader function, if such function exists.
  726. *
  727. * Function uses Q encoding by default and encodes a string according to RFC
  728. * 1522 for use in headers if it contains 8-bit characters or anything that
  729. * looks like it should be encoded.
  730. *
  731. * Function switches to B encoding and encodeHeaderBase64() function, if
  732. * string is 8bit and multibyte character set supported by mbstring extension
  733. * is used. It can cause E_USER_NOTICE errors, if interface is used with
  734. * multibyte character set unsupported by mbstring extension.
  735. *
  736. * @param string $string header string, that has to be encoded
  737. * @return string quoted-printable encoded string
  738. * @todo make $mb_charsets system wide constant
  739. */
  740. function encodeHeader ($string) {
  741. global $default_charset, $languages, $squirrelmail_language;
  742. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  743. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
  744. return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
  745. }
  746. // Use B encoding for multibyte charsets
  747. $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
  748. if (in_array($default_charset,$mb_charsets) &&
  749. in_array($default_charset,sq_mb_list_encodings()) &&
  750. sq_is8bit($string)) {
  751. return encodeHeaderBase64($string,$default_charset);
  752. } elseif (in_array($default_charset,$mb_charsets) &&
  753. sq_is8bit($string) &&
  754. ! in_array($default_charset,sq_mb_list_encodings())) {
  755. // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
  756. // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
  757. }
  758. // Encode only if the string contains 8-bit characters or =?
  759. $j = strlen($string);
  760. $max_l = 75 - strlen($default_charset) - 7;
  761. $aRet = array();
  762. $ret = '';
  763. $iEncStart = $enc_init = false;
  764. $cur_l = $iOffset = 0;
  765. for($i = 0; $i < $j; ++$i) {
  766. switch($string{$i})
  767. {
  768. case '=':
  769. case '<':
  770. case '>':
  771. case ',':
  772. case '?':
  773. case '_':
  774. if ($iEncStart === false) {
  775. $iEncStart = $i;
  776. }
  777. $cur_l+=3;
  778. if ($cur_l > ($max_l-2)) {
  779. /* if there is an stringpart that doesn't need encoding, add it */
  780. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  781. $aRet[] = "=?$default_charset?Q?$ret?=";
  782. $iOffset = $i;
  783. $cur_l = 0;
  784. $ret = '';
  785. $iEncStart = false;
  786. } else {
  787. $ret .= sprintf("=%02X",ord($string{$i}));
  788. }
  789. break;
  790. case '(':
  791. case ')':
  792. if ($iEncStart !== false) {
  793. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  794. $aRet[] = "=?$default_charset?Q?$ret?=";
  795. $iOffset = $i;
  796. $cur_l = 0;
  797. $ret = '';
  798. $iEncStart = false;
  799. }
  800. break;
  801. case ' ':
  802. if ($iEncStart !== false) {
  803. $cur_l++;
  804. if ($cur_l > $max_l) {
  805. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  806. $aRet[] = "=?$default_charset?Q?$ret?=";
  807. $iOffset = $i;
  808. $cur_l = 0;
  809. $ret = '';
  810. $iEncStart = false;
  811. } else {
  812. $ret .= '_';
  813. }
  814. }
  815. break;
  816. default:
  817. $k = ord($string{$i});
  818. if ($k > 126) {
  819. if ($iEncStart === false) {
  820. // do not start encoding in the middle of a string, also take the rest of the word.
  821. $sLeadString = substr($string,0,$i);
  822. $aLeadString = explode(' ',$sLeadString);
  823. $sToBeEncoded = array_pop($aLeadString);
  824. $iEncStart = $i - strlen($sToBeEncoded);
  825. $ret .= $sToBeEncoded;
  826. $cur_l += strlen($sToBeEncoded);
  827. }
  828. $cur_l += 3;
  829. /* first we add the encoded string that reached it's max size */
  830. if ($cur_l > ($max_l-2)) {
  831. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  832. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  833. $cur_l = 3;
  834. $ret = '';
  835. $iOffset = $i;
  836. $iEncStart = $i;
  837. }
  838. $enc_init = true;
  839. $ret .= sprintf("=%02X", $k);
  840. } else {
  841. if ($iEncStart !== false) {
  842. $cur_l++;
  843. if ($cur_l > $max_l) {
  844. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  845. $aRet[] = "=?$default_charset?Q?$ret?=";
  846. $iEncStart = false;
  847. $iOffset = $i;
  848. $cur_l = 0;
  849. $ret = '';
  850. } else {
  851. $ret .= $string{$i};
  852. }
  853. }
  854. }
  855. break;
  856. }
  857. }
  858. if ($enc_init) {
  859. if ($iEncStart !== false) {
  860. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  861. $aRet[] = "=?$default_charset?Q?$ret?=";
  862. } else {
  863. $aRet[] = substr($string,$iOffset);
  864. }
  865. $string = implode('',$aRet);
  866. }
  867. return $string;
  868. }
  869. /**
  870. * Encodes string according to rfc2047 B encoding header formating rules
  871. *
  872. * It is recommended way to encode headers with character sets that store
  873. * symbols in more than one byte.
  874. *
  875. * Function requires mbstring support. If required mbstring functions are missing,
  876. * function returns false and sets E_USER_WARNING level error message.
  877. *
  878. * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
  879. * that mbstring functions will generate E_WARNING errors, if unsupported
  880. * character set is used. mb_encode_mimeheader function provided by php
  881. * mbstring extension is not used in order to get better control of header
  882. * encoding.
  883. *
  884. * Used php code functions - function_exists(), trigger_error(), strlen()
  885. * (is used with charset names and base64 strings). Used php mbstring
  886. * functions - mb_strlen and mb_substr.
  887. *
  888. * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
  889. * encoding), rfc 2822 (header folding)
  890. *
  891. * @param string $string header string that must be encoded
  892. * @param string $charset character set. Must be supported by mbstring extension.
  893. * Use sq_mb_list_encodings() to detect supported charsets.
  894. * @return string string encoded according to rfc2047 B encoding formating rules
  895. * @since 1.5.1
  896. * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
  897. * @todo Do we want to control max length of header?
  898. * @todo Do we want to control EOL (end-of-line) marker?
  899. * @todo Do we want to translate error message?
  900. */
  901. function encodeHeaderBase64($string,$charset) {
  902. /**
  903. * Check mbstring function requirements.
  904. */
  905. if (! function_exists('mb_strlen') ||
  906. ! function_exists('mb_substr')) {
  907. // set E_USER_WARNING
  908. trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
  909. // return false
  910. return false;
  911. }
  912. // initial return array
  913. $aRet = array();
  914. /**
  915. * header length = 75 symbols max (same as in encodeHeader)
  916. * remove $charset length
  917. * remove =? ? ?= (5 chars)
  918. * remove 2 more chars (\r\n ?)
  919. */
  920. $iMaxLength = 75 - strlen($charset) - 7;
  921. // set first character position
  922. $iStartCharNum = 0;
  923. // loop through all characters. count characters and not bytes.
  924. for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++) {
  925. // encode string from starting character to current character.
  926. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  927. // Check encoded string length
  928. if(strlen($encoded_string)>$iMaxLength) {
  929. // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
  930. $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
  931. // set new starting character
  932. $iStartCharNum = $iCharNum-1;
  933. // encode last char (in case it is last character in string)
  934. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  935. } // if string is shorter than max length - add next character
  936. }
  937. // add last encoded string to array
  938. $aRet[] = $encoded_string;
  939. // set initial return string
  940. $sRet = '';
  941. // loop through encoded strings
  942. foreach($aRet as $string) {
  943. // TODO: Do we want to control EOL (end-of-line) marker
  944. if ($sRet!='') $sRet.= " ";
  945. // add header tags and encoded string to return string
  946. $sRet.= '=?'.$charset.'?B?'.$string.'?=';
  947. }
  948. return $sRet;
  949. }
  950. /* This function trys to locate the entity_id of a specific mime element */
  951. function find_ent_id($id, $message) {
  952. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  953. if ($message->entities[$i]->header->type0 == 'multipart') {
  954. $ret = find_ent_id($id, $message->entities[$i]);
  955. } else {
  956. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  957. // if (sq_check_save_extension($message->entities[$i])) {
  958. return $message->entities[$i]->entity_id;
  959. // }
  960. } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
  961. /**
  962. * This is part of a fix for Outlook Express 6.x generating
  963. * cid URLs without creating content-id headers
  964. * @@JA - 20050207
  965. */
  966. if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
  967. return $message->entities[$i]->entity_id;
  968. }
  969. }
  970. }
  971. }
  972. return $ret;
  973. }
  974. function sq_check_save_extension($message) {
  975. $filename = $message->getFilename();
  976. $ext = substr($filename, strrpos($filename,'.')+1);
  977. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  978. return in_array($ext, $save_extensions);
  979. }
  980. /**
  981. ** HTMLFILTER ROUTINES
  982. */
  983. /**
  984. * This function checks attribute values for entity-encoded values
  985. * and returns them translated into 8-bit strings so we can run
  986. * checks on them.
  987. *
  988. * @param $attvalue A string to run entity check against.
  989. * @return Nothing, modifies a reference value.
  990. */
  991. function sq_defang(&$attvalue){
  992. $me = 'sq_defang';
  993. /**
  994. * Skip this if there aren't ampersands or backslashes.
  995. */
  996. if (strpos($attvalue, '&') === false
  997. && strpos($attvalue, '\\') === false){
  998. return;
  999. }
  1000. $m = false;
  1001. do {
  1002. $m = false;
  1003. $m = $m || sq_deent($attvalue, '/\&#0*(\d+);*/s');
  1004. $m = $m || sq_deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
  1005. $m = $m || sq_deent($attvalue, '/\\\\(\d+)/s', true);
  1006. } while ($m == true);
  1007. $attvalue = stripslashes($attvalue);
  1008. }
  1009. /**
  1010. * Kill any tabs, newlines, or carriage returns. Our friends the
  1011. * makers of the browser with 95% market value decided that it'd
  1012. * be funny to make "java[tab]script" be just as good as "javascript".
  1013. *
  1014. * @param attvalue The attribute value before extraneous spaces removed.
  1015. * @return attvalue Nothing, modifies a reference value.
  1016. */
  1017. function sq_unspace(&$attvalue){
  1018. $me = 'sq_unspace';
  1019. if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
  1020. $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
  1021. Array('', '', '', '', ''), $attvalue);
  1022. }
  1023. }
  1024. /**
  1025. * This function returns the final tag out of the tag name, an array
  1026. * of attributes, and the type of the tag. This function is called by
  1027. * sq_sanitize internally.
  1028. *
  1029. * @param $tagname the name of the tag.
  1030. * @param $attary the array of attributes and their values
  1031. * @param $tagtype The type of the tag (see in comments).
  1032. * @return a string with the final tag representation.
  1033. */
  1034. function sq_tagprint($tagname, $attary, $tagtype){
  1035. $me = 'sq_tagprint';
  1036. if ($tagtype == 2){
  1037. $fulltag = '</' . $tagname . '>';
  1038. } else {
  1039. $fulltag = '<' . $tagname;
  1040. if (is_array($attary) && sizeof($attary)){
  1041. $atts = Array();
  1042. while (list($attname, $attvalue) = each($attary)){
  1043. array_push($atts, "$attname=$attvalue");
  1044. }
  1045. $fulltag .= ' ' . join(" ", $atts);
  1046. }
  1047. if ($tagtype == 3){
  1048. $fulltag .= ' /';
  1049. }
  1050. $fulltag .= '>';
  1051. }
  1052. return $fulltag;
  1053. }
  1054. /**
  1055. * A small helper function to use with array_walk. Modifies a by-ref
  1056. * value and makes it lowercase.
  1057. *
  1058. * @param $val a value passed by-ref.
  1059. * @return void since it modifies a by-ref value.
  1060. */
  1061. function sq_casenormalize(&$val){
  1062. $val = strtolower($val);
  1063. }
  1064. /**
  1065. * This function skips any whitespace from the current position within
  1066. * a string and to the next non-whitespace value.
  1067. *
  1068. * @param $body the string
  1069. * @param $offset the offset within the string where we should start
  1070. * looking for the next non-whitespace character.
  1071. * @return the location within the $body where the next
  1072. * non-whitespace char is located.
  1073. */
  1074. function sq_skipspace($body, $offset){
  1075. $me = 'sq_skipspace';
  1076. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  1077. if (sizeof($matches{1})){
  1078. $count = strlen($matches{1});
  1079. $offset += $count;
  1080. }
  1081. return $offset;
  1082. }
  1083. /**
  1084. * This function looks for the next character within a string. It's
  1085. * really just a glorified "strpos", except it catches if failures
  1086. * nicely.
  1087. *
  1088. * @param $body The string to look for needle in.
  1089. * @param $offset Start looking from this position.
  1090. * @param $needle The character/string to look for.
  1091. * @return location of the next occurance of the needle, or
  1092. * strlen($body) if needle wasn't found.
  1093. */
  1094. function sq_findnxstr($body, $offset, $needle){
  1095. $me = 'sq_findnxstr';
  1096. $pos = strpos($body, $needle, $offset);
  1097. if ($pos === FALSE){
  1098. $pos = strlen($body);
  1099. }
  1100. return $pos;
  1101. }
  1102. /**
  1103. * This function takes a PCRE-style regexp and tries to match it
  1104. * within the string.
  1105. *
  1106. * @param $body The string to look for needle in.
  1107. * @param $offset Start looking from here.
  1108. * @param $reg A PCRE-style regex to match.
  1109. * @return Returns a false if no matches found, or an array
  1110. * with the following members:
  1111. * - integer with the location of the match within $body
  1112. * - string with whatever content between offset and the match
  1113. * - string with whatever it is we matched
  1114. */
  1115. function sq_findnxreg($body, $offset, $reg){
  1116. $me = 'sq_findnxreg';
  1117. $matches = Array();
  1118. $retarr = Array();
  1119. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  1120. if (!isset($matches{0}) || !$matches{0}){
  1121. $retarr = false;
  1122. } else {
  1123. $retarr{0} = $offset + strlen($matches{1});
  1124. $retarr{1} = $matches{1};
  1125. $retarr{2} = $matches{2};
  1126. }
  1127. return $retarr;
  1128. }
  1129. /**
  1130. * This function looks for the next tag.
  1131. *
  1132. * @param $body String where to look for the next tag.
  1133. * @param $offset Start looking from here.
  1134. * @return false if no more tags exist in the body, or
  1135. * an array with the following members:
  1136. * - string with the name of the tag
  1137. * - array with attributes and their values
  1138. * - integer with tag type (1, 2, or 3)
  1139. * - integer where the tag starts (starting "<")
  1140. * - integer where the tag ends (ending ">")
  1141. * first three members will be false, if the tag is invalid.
  1142. */
  1143. function sq_getnxtag($body, $offset){
  1144. $me = 'sq_getnxtag';
  1145. if ($offset > strlen($body)){
  1146. return false;
  1147. }
  1148. $lt = sq_findnxstr($body, $offset, "<");
  1149. if ($lt == strlen($body)){
  1150. return false;
  1151. }
  1152. /**
  1153. * We are here:
  1154. * blah blah <tag attribute="value">
  1155. * \---------^
  1156. */
  1157. $pos = sq_skipspace($body, $lt+1);
  1158. if ($pos >= strlen($body)){
  1159. return Array(false, false, false, $lt, strlen($body));
  1160. }
  1161. /**
  1162. * There are 3 kinds of tags:
  1163. * 1. Opening tag, e.g.:
  1164. * <a href="blah">
  1165. * 2. Closing tag, e.g.:
  1166. * </a>
  1167. * 3. XHTML-style content-less tag, e.g.:
  1168. * <img src="blah" />
  1169. */
  1170. $tagtype = false;
  1171. switch (substr($body, $pos, 1)){
  1172. case '/':
  1173. $tagtype = 2;
  1174. $pos++;
  1175. break;
  1176. case '!':
  1177. /**
  1178. * A comment or an SGML declaration.
  1179. */
  1180. if (substr($body, $pos+1, 2) == "--"){
  1181. $gt = strpos($body, "-->", $pos);
  1182. if ($gt === false){
  1183. $gt = strlen($body);
  1184. } else {
  1185. $gt += 2;
  1186. }
  1187. return Array(false, false, false, $lt, $gt);
  1188. } else {
  1189. $gt = sq_findnxstr($body, $pos, ">");
  1190. return Array(false, false, false, $lt, $gt);
  1191. }
  1192. break;
  1193. default:
  1194. /**
  1195. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1196. * later.
  1197. */
  1198. $tagtype = 1;
  1199. break;
  1200. }
  1201. $tag_start = $pos;
  1202. $tagname = '';
  1203. /**
  1204. * Look for next [\W-_], which will indicate the end of the tag name.
  1205. */
  1206. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1207. if ($regary == false){
  1208. return Array(false, false, false, $lt, strlen($body));
  1209. }
  1210. list($pos, $tagname, $match) = $regary;
  1211. $tagname = strtolower($tagname);
  1212. /**
  1213. * $match can be either of these:
  1214. * '>' indicating the end of the tag entirely.
  1215. * '\s' indicating the end of the tag name.
  1216. * '/' indicating that this is type-3 xhtml tag.
  1217. *
  1218. * Whatever else we find thereā€¦

Large files files are truncated, but you can click here to view the full file