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

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

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

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