PageRenderTime 67ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

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

#
PHP | 2601 lines | 1642 code | 176 blank | 783 comment | 406 complexity | 77235179fc27f3414b2a101855a037b6 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 13338 2008-12-04 04:17:47Z 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 (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 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 . ']' ;
  420. } else {
  421. $filename = 'cid: ' . $header->id;
  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 . ']' ;
  435. } else {
  436. $filename = 'cid: ' . $header->id;
  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. if(count($hookresults[1]) <= 1) {
  472. $hookresults = do_hook("attachment $type0/*", $links,
  473. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  474. $display_filename, $where, $what);
  475. }
  476. $hookresults = do_hook("attachment */*", $hookresults[1],
  477. $startMessage, $id, $urlMailbox, $ent, $hookresults[6],
  478. $display_filename, $where, $what);
  479. $links = $hookresults[1];
  480. $defaultlink = $hookresults[6];
  481. $attachments .= '<tr><td>' .
  482. '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a>&nbsp;</td>' .
  483. '<td><small><b>' . show_readable_size($header->size) .
  484. '</b>&nbsp;&nbsp;</small></td>' .
  485. '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ]&nbsp;</small></td>' .
  486. '<td><small>';
  487. $attachments .= '<b>' . $description . '</b>';
  488. $attachments .= '</small></td><td><small>&nbsp;';
  489. $skipspaces = 1;
  490. foreach ($links as $val) {
  491. if ($skipspaces) {
  492. $skipspaces = 0;
  493. } else {
  494. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  495. }
  496. $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
  497. }
  498. unset($links);
  499. $attachments .= "</td></tr>\n";
  500. }
  501. return $attachments;
  502. }
  503. function sqimap_base64_decode(&$string) {
  504. // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  505. // fly decoding (to reduce memory usage) you have to check if the
  506. // data has incomplete pairs
  507. // Remove the noise in order to check if the 4 bytes pairs are complete
  508. $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
  509. $sStringRem = '';
  510. $iMod = strlen($string) % 4;
  511. if ($iMod) {
  512. $sStringRem = substr($string,-$iMod);
  513. // Check if $sStringRem contains padding characters
  514. if (substr($sStringRem,-1) != '=') {
  515. $string = substr($string,0,-$iMod);
  516. } else {
  517. $sStringRem = '';
  518. }
  519. }
  520. $string = base64_decode($string);
  521. return $sStringRem;
  522. }
  523. /**
  524. * Decodes encoded message body
  525. *
  526. * This function decodes the body depending on the encoding type.
  527. * Currently quoted-printable and base64 encodings are supported.
  528. * decode_body hook was added to this function in 1.4.2/1.5.0
  529. * @param string $body encoded message body
  530. * @param string $encoding used encoding
  531. * @return string decoded string
  532. * @since 1.0
  533. */
  534. function decodeBody($body, $encoding) {
  535. $body = str_replace("\r\n", "\n", $body);
  536. $encoding = strtolower($encoding);
  537. $encoding_handler = do_hook_function('decode_body', $encoding);
  538. // plugins get first shot at decoding the body
  539. if (!empty($encoding_handler) && function_exists($encoding_handler)) {
  540. $body = $encoding_handler('decode', $body);
  541. } elseif ($encoding == 'quoted-printable' ||
  542. $encoding == 'quoted_printable') {
  543. /**
  544. * quoted_printable_decode() function is broken in older
  545. * php versions. Text with \r\n decoding was fixed only
  546. * in php 4.3.0. Minimal code requirement 4.0.4 +
  547. * str_replace("\r\n", "\n", $body); call.
  548. */
  549. $body = quoted_printable_decode($body);
  550. } elseif ($encoding == 'base64') {
  551. $body = base64_decode($body);
  552. }
  553. // All other encodings are returned raw.
  554. return $body;
  555. }
  556. /**
  557. * Decodes headers
  558. *
  559. * This functions decode strings that is encoded according to
  560. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  561. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  562. */
  563. function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
  564. global $languages, $squirrelmail_language,$default_charset;
  565. if (is_array($string)) {
  566. $string = implode("\n", $string);
  567. }
  568. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  569. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  570. $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
  571. // Do we need to return at this point?
  572. // return $string;
  573. }
  574. $i = 0;
  575. $iLastMatch = -2;
  576. $encoded = false;
  577. $aString = explode(' ',$string);
  578. $ret = '';
  579. foreach ($aString as $chunk) {
  580. if ($encoded && $chunk === '') {
  581. continue;
  582. } elseif ($chunk === '') {
  583. $ret .= ' ';
  584. continue;
  585. }
  586. $encoded = false;
  587. /* if encoded words are not separated by a linear-space-white we still catch them */
  588. $j = $i-1;
  589. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  590. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  591. if ($iLastMatch !== $j) {
  592. if ($htmlsave) {
  593. $ret .= '&#32;';
  594. } else {
  595. $ret .= ' ';
  596. }
  597. }
  598. $iLastMatch = $i;
  599. $j = $i;
  600. if ($htmlsave) {
  601. $ret .= htmlspecialchars($res[1]);
  602. } else {
  603. $ret .= $res[1];
  604. }
  605. $encoding = ucfirst($res[3]);
  606. /* decide about valid decoding */
  607. if ($decide && is_conversion_safe($res[2])) {
  608. $can_be_encoded=true;
  609. } else {
  610. $can_be_encoded=false;
  611. }
  612. switch ($encoding)
  613. {
  614. case 'B':
  615. $replace = base64_decode($res[4]);
  616. if ($can_be_encoded) {
  617. // string is converted from one charset to another. sanitizing depends on $htmlsave
  618. $replace = charset_convert($res[2],$replace,$default_charset,$htmlsave);
  619. } elseif ($utfencode) {
  620. // string is converted to htmlentities and sanitized
  621. $replace = charset_decode($res[2],$replace);
  622. } elseif ($htmlsave) {
  623. // string is not converted, but still sanitized
  624. $replace = htmlspecialchars($replace);
  625. }
  626. $ret.= $replace;
  627. break;
  628. case 'Q':
  629. $replace = str_replace('_', ' ', $res[4]);
  630. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  631. $replace);
  632. if ($can_be_encoded) {
  633. // string is converted from one charset to another. sanitizing depends on $htmlsave
  634. $replace = charset_convert($res[2], $replace,$default_charset,$htmlsave);
  635. } elseif ($utfencode) {
  636. // string is converted to html entities and sanitized
  637. $replace = charset_decode($res[2], $replace);
  638. } elseif ($htmlsave) {
  639. // string is not converted, but still sanizited
  640. $replace = htmlspecialchars($replace);
  641. }
  642. $ret .= $replace;
  643. break;
  644. default:
  645. break;
  646. }
  647. $chunk = $res[5];
  648. $encoded = true;
  649. }
  650. if (!$encoded) {
  651. if ($htmlsave) {
  652. $ret .= '&#32;';
  653. } else {
  654. $ret .= ' ';
  655. }
  656. }
  657. if (!$encoded && $htmlsave) {
  658. $ret .= htmlspecialchars($chunk);
  659. } else {
  660. $ret .= $chunk;
  661. }
  662. ++$i;
  663. }
  664. /* remove the first added space */
  665. if ($ret) {
  666. if ($htmlsave) {
  667. $ret = substr($ret,5);
  668. } else {
  669. $ret = substr($ret,1);
  670. }
  671. }
  672. return $ret;
  673. }
  674. /**
  675. * Encodes header as quoted-printable
  676. *
  677. * Encode a string according to RFC 1522 for use in headers if it
  678. * contains 8-bit characters or anything that looks like it should
  679. * be encoded.
  680. */
  681. function encodeHeader ($string) {
  682. global $default_charset, $languages, $squirrelmail_language;
  683. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  684. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  685. return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
  686. }
  687. // Use B encoding for multibyte charsets
  688. $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
  689. if (in_array($default_charset,$mb_charsets) &&
  690. in_array($default_charset,sq_mb_list_encodings()) &&
  691. sq_is8bit($string)) {
  692. return encodeHeaderBase64($string,$default_charset);
  693. } elseif (in_array($default_charset,$mb_charsets) &&
  694. sq_is8bit($string) &&
  695. ! in_array($default_charset,sq_mb_list_encodings())) {
  696. // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
  697. // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
  698. }
  699. // Encode only if the string contains 8-bit characters or =?
  700. $j = strlen($string);
  701. $max_l = 75 - strlen($default_charset) - 7;
  702. $aRet = array();
  703. $ret = '';
  704. $iEncStart = $enc_init = false;
  705. $cur_l = $iOffset = 0;
  706. for($i = 0; $i < $j; ++$i) {
  707. switch($string{$i})
  708. {
  709. case '=':
  710. case '<':
  711. case '>':
  712. case ',':
  713. case '?':
  714. case '_':
  715. if ($iEncStart === false) {
  716. $iEncStart = $i;
  717. }
  718. $cur_l+=3;
  719. if ($cur_l > ($max_l-2)) {
  720. /* if there is an stringpart that doesn't need encoding, add it */
  721. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  722. $aRet[] = "=?$default_charset?Q?$ret?=";
  723. $iOffset = $i;
  724. $cur_l = 0;
  725. $ret = '';
  726. $iEncStart = false;
  727. } else {
  728. $ret .= sprintf("=%02X",ord($string{$i}));
  729. }
  730. break;
  731. case '(':
  732. case ')':
  733. if ($iEncStart !== false) {
  734. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  735. $aRet[] = "=?$default_charset?Q?$ret?=";
  736. $iOffset = $i;
  737. $cur_l = 0;
  738. $ret = '';
  739. $iEncStart = false;
  740. }
  741. break;
  742. case ' ':
  743. if ($iEncStart !== false) {
  744. $cur_l++;
  745. if ($cur_l > $max_l) {
  746. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  747. $aRet[] = "=?$default_charset?Q?$ret?=";
  748. $iOffset = $i;
  749. $cur_l = 0;
  750. $ret = '';
  751. $iEncStart = false;
  752. } else {
  753. $ret .= '_';
  754. }
  755. }
  756. break;
  757. default:
  758. $k = ord($string{$i});
  759. if ($k > 126) {
  760. if ($iEncStart === false) {
  761. // do not start encoding in the middle of a string, also take the rest of the word.
  762. $sLeadString = substr($string,0,$i);
  763. $aLeadString = explode(' ',$sLeadString);
  764. $sToBeEncoded = array_pop($aLeadString);
  765. $iEncStart = $i - strlen($sToBeEncoded);
  766. $ret .= $sToBeEncoded;
  767. $cur_l += strlen($sToBeEncoded);
  768. }
  769. $cur_l += 3;
  770. /* first we add the encoded string that reached it's max size */
  771. if ($cur_l > ($max_l-2)) {
  772. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  773. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  774. $cur_l = 3;
  775. $ret = '';
  776. $iOffset = $i;
  777. $iEncStart = $i;
  778. }
  779. $enc_init = true;
  780. $ret .= sprintf("=%02X", $k);
  781. } else {
  782. if ($iEncStart !== false) {
  783. $cur_l++;
  784. if ($cur_l > $max_l) {
  785. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  786. $aRet[] = "=?$default_charset?Q?$ret?=";
  787. $iEncStart = false;
  788. $iOffset = $i;
  789. $cur_l = 0;
  790. $ret = '';
  791. } else {
  792. $ret .= $string{$i};
  793. }
  794. }
  795. }
  796. break;
  797. }
  798. }
  799. if ($enc_init) {
  800. if ($iEncStart !== false) {
  801. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  802. $aRet[] = "=?$default_charset?Q?$ret?=";
  803. } else {
  804. $aRet[] = substr($string,$iOffset);
  805. }
  806. $string = implode('',$aRet);
  807. }
  808. return $string;
  809. }
  810. /**
  811. * Encodes string according to rfc2047 B encoding header formating rules
  812. *
  813. * It is recommended way to encode headers with character sets that store
  814. * symbols in more than one byte.
  815. *
  816. * Function requires mbstring support. If required mbstring functions are missing,
  817. * function returns false and sets E_USER_WARNING level error message.
  818. *
  819. * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
  820. * that mbstring functions will generate E_WARNING errors, if unsupported
  821. * character set is used. mb_encode_mimeheader function provided by php
  822. * mbstring extension is not used in order to get better control of header
  823. * encoding.
  824. *
  825. * Used php code functions - function_exists(), trigger_error(), strlen()
  826. * (is used with charset names and base64 strings). Used php mbstring
  827. * functions - mb_strlen and mb_substr.
  828. *
  829. * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
  830. * encoding), rfc 2822 (header folding)
  831. *
  832. * @param string $string header string that must be encoded
  833. * @param string $charset character set. Must be supported by mbstring extension.
  834. * Use sq_mb_list_encodings() to detect supported charsets.
  835. * @return string string encoded according to rfc2047 B encoding formating rules
  836. * @since 1.5.1 and 1.4.6
  837. */
  838. function encodeHeaderBase64($string,$charset) {
  839. /**
  840. * Check mbstring function requirements.
  841. */
  842. if (! function_exists('mb_strlen') ||
  843. ! function_exists('mb_substr')) {
  844. // set E_USER_WARNING
  845. trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
  846. // return false
  847. return false;
  848. }
  849. // initial return array
  850. $aRet = array();
  851. /**
  852. * header length = 75 symbols max (same as in encodeHeader)
  853. * remove $charset length
  854. * remove =? ? ?= (5 chars)
  855. * remove 2 more chars (\r\n ?)
  856. */
  857. $iMaxLength = 75 - strlen($charset) - 7;
  858. // set first character position
  859. $iStartCharNum = 0;
  860. // loop through all characters. count characters and not bytes.
  861. for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++) {
  862. // encode string from starting character to current character.
  863. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  864. // Check encoded string length
  865. if(strlen($encoded_string)>$iMaxLength) {
  866. // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
  867. $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
  868. // set new starting character
  869. $iStartCharNum = $iCharNum-1;
  870. // encode last char (in case it is last character in string)
  871. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  872. } // if string is shorter than max length - add next character
  873. }
  874. // add last encoded string to array
  875. $aRet[] = $encoded_string;
  876. // set initial return string
  877. $sRet = '';
  878. // loop through encoded strings
  879. foreach($aRet as $string) {
  880. // TODO: Do we want to control EOL (end-of-line) marker
  881. if ($sRet!='') $sRet.= " ";
  882. // add header tags and encoded string to return string
  883. $sRet.= '=?'.$charset.'?B?'.$string.'?=';
  884. }
  885. return $sRet;
  886. }
  887. /* This function trys to locate the entity_id of a specific mime element */
  888. function find_ent_id($id, $message) {
  889. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  890. if ($message->entities[$i]->header->type0 == 'multipart') {
  891. $ret = find_ent_id($id, $message->entities[$i]);
  892. } else {
  893. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  894. // if (sq_check_save_extension($message->entities[$i])) {
  895. return $message->entities[$i]->entity_id;
  896. // }
  897. } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
  898. /**
  899. * This is part of a fix for Outlook Express 6.x generating
  900. * cid URLs without creating content-id headers
  901. * @@JA - 20050207
  902. */
  903. if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
  904. return $message->entities[$i]->entity_id;
  905. }
  906. }
  907. }
  908. }
  909. return $ret;
  910. }
  911. function sq_check_save_extension($message) {
  912. $filename = $message->getFilename();
  913. $ext = substr($filename, strrpos($filename,'.')+1);
  914. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  915. return in_array($ext, $save_extensions);
  916. }
  917. /**
  918. ** HTMLFILTER ROUTINES
  919. */
  920. /**
  921. * This function checks attribute values for entity-encoded values
  922. * and returns them translated into 8-bit strings so we can run
  923. * checks on them.
  924. *
  925. * @param $attvalue A string to run entity check against.
  926. * @return Nothing, modifies a reference value.
  927. */
  928. function sq_defang(&$attvalue){
  929. $me = 'sq_defang';
  930. /**
  931. * Skip this if there aren't ampersands or backslashes.
  932. */
  933. if (strpos($attvalue, '&') === false
  934. && strpos($attvalue, '\\') === false){
  935. return;
  936. }
  937. $m = false;
  938. do {
  939. $m = false;
  940. $m = $m || sq_deent($attvalue, '/\&#0*(\d+);*/s');
  941. $m = $m || sq_deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
  942. $m = $m || sq_deent($attvalue, '/\\\\(\d+)/s', true);
  943. } while ($m == true);
  944. $attvalue = stripslashes($attvalue);
  945. }
  946. /**
  947. * Kill any tabs, newlines, or carriage returns. Our friends the
  948. * makers of the browser with 95% market value decided that it'd
  949. * be funny to make "java[tab]script" be just as good as "javascript".
  950. *
  951. * @param attvalue The attribute value before extraneous spaces removed.
  952. * @return attvalue Nothing, modifies a reference value.
  953. */
  954. function sq_unspace(&$attvalue){
  955. $me = 'sq_unspace';
  956. if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
  957. $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
  958. Array('', '', '', '', ''), $attvalue);
  959. }
  960. }
  961. /**
  962. * Translate all dangerous Unicode or Shift_JIS characters which are accepted by
  963. * IE as regular characters.
  964. *
  965. * @param attvalue The attribute value before dangerous characters are translated.
  966. * @return attvalue Nothing, modifies a reference value.
  967. * @author Marc Groot Koerkamp.
  968. */
  969. function sq_fixIE_idiocy(&$attvalue) {
  970. // remove NUL
  971. $attvalue = str_replace("\0", "", $attvalue);
  972. // remove comments
  973. $attvalue = preg_replace("/(\/\*.*?\*\/)/","",$attvalue);
  974. // IE has the evil habit of accepting every possible value for the attribute expression.
  975. // The table below contains characters which are parsed by IE if they are used in the "expression"
  976. // attribute value.
  977. $aDangerousCharsReplacementTable = array(
  978. array('&#x029F;', '&#0671;' ,/* L UNICODE IPA Extension */
  979. '&#x0280;', '&#0640;' ,/* R UNICODE IPA Extension */
  980. '&#x0274;', '&#0628;' ,/* N UNICODE IPA Extension */
  981. '&#xFF25;', '&#65317;' ,/* Unicode FULLWIDTH LATIN CAPITAL LETTER E */
  982. '&#xFF45;', '&#65349;' ,/* Unicode FULLWIDTH LATIN SMALL LETTER E */
  983. '&#xFF38;', '&#65336;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER X */
  984. '&#xFF58;', '&#65368;',/* Unicode FULLWIDTH LATIN SMALL LETTER X */
  985. '&#xFF30;', '&#65328;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER P */
  986. '&#xFF50;', '&#65360;',/* Unicode FULLWIDTH LATIN SMALL LETTER P */
  987. '&#xFF32;', '&#65330;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER R */
  988. '&#xFF52;', '&#65362;',/* Unicode FULLWIDTH LATIN SMALL LETTER R */
  989. '&#xFF33;', '&#65331;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER S */
  990. '&#xFF53;', '&#65363;',/* Unicode FULLWIDTH LATIN SMALL LETTER S */
  991. '&#xFF29;', '&#65321;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER I */
  992. '&#xFF49;', '&#65353;',/* Unicode FULLWIDTH LATIN SMALL LETTER I */
  993. '&#xFF2F;', '&#65327;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER O */
  994. '&#xFF4F;', '&#65359;',/* Unicode FULLWIDTH LATIN SMALL LETTER O */
  995. '&#xFF2E;', '&#65326;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER N */
  996. '&#xFF4E;', '&#65358;',/* Unicode FULLWIDTH LATIN SMALL LETTER N */
  997. '&#xFF2C;', '&#65324;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER L */
  998. '&#xFF4C;', '&#65356;',/* Unicode FULLWIDTH LATIN SMALL LETTER L */
  999. '&#xFF35;', '&#65333;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER U */
  1000. '&#xFF55;', '&#65365;',/* Unicode FULLWIDTH LATIN SMALL LETTER U */
  1001. '&#x207F;', '&#8319;' ,/* Unicode SUPERSCRIPT LATIN SMALL LETTER N */
  1002. "\xEF\xBC\xA5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER E */ // in unicode this is some Chinese char range
  1003. "\xEF\xBD\x85", /* Shift JIS FULLWIDTH LATIN SMALL LETTER E */
  1004. "\xEF\xBC\xB8", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER X */
  1005. "\xEF\xBD\x98", /* Shift JIS FULLWIDTH LATIN SMALL LETTER X */
  1006. "\xEF\xBC\xB0", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER P */
  1007. "\xEF\xBD\x90", /* Shift JIS FULLWIDTH LATIN SMALL LETTER P */
  1008. "\xEF\xBC\xB2", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER R */
  1009. "\xEF\xBD\x92", /* Shift JIS FULLWIDTH LATIN SMALL LETTER R */
  1010. "\xEF\xBC\xB3", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER S */
  1011. "\xEF\xBD\x93", /* Shift JIS FULLWIDTH LATIN SMALL LETTER S */
  1012. "\xEF\xBC\xA9", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER I */
  1013. "\xEF\xBD\x89", /* Shift JIS FULLWIDTH LATIN SMALL LETTER I */
  1014. "\xEF\xBC\xAF", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER O */
  1015. "\xEF\xBD\x8F", /* Shift JIS FULLWIDTH LATIN SMALL LETTER O */
  1016. "\xEF\xBC\xAE", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER N */
  1017. "\xEF\xBD\x8E", /* Shift JIS FULLWIDTH LATIN SMALL LETTER N */
  1018. "\xEF\xBC\xAC", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER L */
  1019. "\xEF\xBD\x8C", /* Shift JIS FULLWIDTH LATIN SMALL LETTER L */
  1020. "\xEF\xBC\xB5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER U */
  1021. "\xEF\xBD\x95", /* Shift JIS FULLWIDTH LATIN SMALL LETTER U */
  1022. "\xE2\x81\xBF", /* Shift JIS FULLWIDTH SUPERSCRIPT N */
  1023. "\xCA\x9F", /* L UNICODE IPA Extension */
  1024. "\xCA\x80", /* R UNICODE IPA Extension */
  1025. "\xC9\xB4"), /* N UNICODE IPA Extension */
  1026. array('l', 'l', 'r','r','n','n',
  1027. 'E','E','e','e','X','X','x','x','P','P','p','p','R','R','r','r','S','S','s','s','I','I',
  1028. 'i','i','O','O','o','o','N','N','n','n','L','L','l','l','U','U','u','u','n','n',
  1029. 'E','e','X','x','P','p','R','r','S','s','I','i','O','o','N','n','L','l','U','u','n','l','r','n'));
  1030. $attvalue = str_replace($aDangerousCharsReplacementTable[0],$aDangerousCharsReplacementTable[1],$attvalue);
  1031. // Escapes are useful for special characters like "{}[]()'&. In other cases they are
  1032. // used for XSS.
  1033. $attvalue = preg_replace("/(\\\\)([a-zA-Z]{1})/",'$2',$attvalue);
  1034. }
  1035. /**
  1036. * This function returns the final tag out of the tag name, an array
  1037. * of attributes, and the type of the tag. This function is called by
  1038. * sq_sanitize internally.
  1039. *
  1040. * @param $tagname the name of the tag.
  1041. * @param $attary the array of attributes and their values
  1042. * @param $tagtype The type of the tag (see in comments).
  1043. * @return a string with the final tag representation.
  1044. */
  1045. function sq_tagprint($tagname, $attary, $tagtype){
  1046. $me = 'sq_tagprint';
  1047. if ($tagtype == 2){
  1048. $fulltag = '</' . $tagname . '>';
  1049. } else {
  1050. $fulltag = '<' . $tagname;
  1051. if (is_array($attary) && sizeof($attary)){
  1052. $atts = Array();
  1053. while (list($attname, $attvalue) = each($attary)){
  1054. array_push($atts, "$attname=$attvalue");
  1055. }
  1056. $fulltag .= ' ' . join(" ", $atts);
  1057. }
  1058. if ($tagtype == 3){
  1059. $fulltag .= ' /';
  1060. }
  1061. $fulltag .= '>';
  1062. }
  1063. return $fulltag;
  1064. }
  1065. /**
  1066. * A small helper function to use with array_walk. Modifies a by-ref
  1067. * value and makes it lowercase.
  1068. *
  1069. * @param $val a value passed by-ref.
  1070. * @return void since it modifies a by-ref value.
  1071. */
  1072. function sq_casenormalize(&$val){
  1073. $val = strtolower($val);
  1074. }
  1075. /**
  1076. * This function skips any whitespace from the current position within
  1077. * a string and to the next non-whitespace value.
  1078. *
  1079. * @param $body the string
  1080. * @param $offset the offset within the string where we should start
  1081. * looking for the next non-whitespace character.
  1082. * @return the location within the $body where the next
  1083. * non-whitespace char is located.
  1084. */
  1085. function sq_skipspace($body, $offset){
  1086. $me = 'sq_skipspace';
  1087. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  1088. if (sizeof($matches{1})){
  1089. $count = strlen($matches{1});
  1090. $offset += $count;
  1091. }
  1092. return $offset;
  1093. }
  1094. /**
  1095. * This function looks for the next character within a string. It's
  1096. * really just a glorified "strpos", except it catches if failures
  1097. * nicely.
  1098. *
  1099. * @param $body The string to look for needle in.
  1100. * @param $offset Start looking from this position.
  1101. * @param $needle The character/string to look for.
  1102. * @return location of the next occurance of the needle, or
  1103. * strlen($body) if needle wasn't found.
  1104. */
  1105. function sq_findnxstr($body, $offset, $needle){
  1106. $me = 'sq_findnxstr';
  1107. $pos = strpos($body, $needle, $offset);
  1108. if ($pos === FALSE){
  1109. $pos = strlen($body);
  1110. }
  1111. return $pos;
  1112. }
  1113. /**
  1114. * This function takes a PCRE-style regexp and tries to match it
  1115. * within the string.
  1116. *
  1117. * @param $body The string to look for needle in.
  1118. * @param $offset Start looking from here.
  1119. * @param $reg A PCRE-style regex to match.
  1120. * @return Returns a false if no matches found, or an array
  1121. * with the following members:
  1122. * - integer with the location of the match within $body
  1123. * - string with whatever content between offset and the match
  1124. * - string with whatever it is we matched
  1125. */
  1126. function sq_findnxreg($body, $offset, $reg){
  1127. $me = 'sq_findnxreg';
  1128. $matches = Array();
  1129. $retarr = Array();
  1130. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  1131. if (!isset($matches{0}) || !$matches{0}){
  1132. $retarr = false;
  1133. } else {
  1134. $retarr{0} = $offset + strlen($matches{1});
  1135. $retarr{1} = $matches{1};
  1136. $retarr{2} = $matches{2};
  1137. }
  1138. return $retarr;
  1139. }
  1140. /**
  1141. * This function looks for the next tag.
  1142. *
  1143. * @param $body String where to look for the next tag.
  1144. * @param $offset Start looking from here.
  1145. * @return false if no more tags exist in the body, or
  1146. * an array with the following members:
  1147. * - string with the na…

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