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

/tags/test-1_4_8utf8_1/squirrelmail/functions/mime.php

#
PHP | 2187 lines | 1341 code | 149 blank | 697 comment | 319 complexity | 790361cb4355773972ebdb8965397ce7 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0

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

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

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