PageRenderTime 31ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

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

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

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