PageRenderTime 65ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/webmail-release-1_4_22/functions/mime.php

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

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