PageRenderTime 60ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

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

#
PHP | 2451 lines | 1615 code | 160 blank | 676 comment | 385 complexity | 022af079ad4cf0c442dc12889b24bdbe MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0

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

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