url_parser.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. /**
  3. * url_parser.php
  4. *
  5. * This code provides various string manipulation functions that are
  6. * used by the rest of the SquirrelMail code.
  7. *
  8. * @copyright 1999-2025 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id$
  11. * @package squirrelmail
  12. */
  13. /**
  14. * Undocumented - complain, then patch.
  15. */
  16. function replaceBlock (&$in, $replace, $start, $end) {
  17. $begin = substr($in,0,$start);
  18. $end = substr($in,$end,strlen($in)-$end);
  19. $in = $begin.$replace.$end;
  20. }
  21. /* Having this defined in just one spot could help when changes need
  22. * to be made to the pattern
  23. * Make sure that the expression is evaluated case insensitively
  24. *
  25. * RFC2822 (and RFC822) defines the left side of an email address as (roughly):
  26. * 1*atext *("." 1*atext)
  27. * where atext is: a-zA-Z0-9!#$%&'*+-/=?^_`{|}~
  28. *
  29. * Here's pretty sophisticated IP matching:
  30. * $IPMatch = '(2[0-5][0-9]|1?[0-9]{1,2})';
  31. * $IPMatch = '\[?' . $IPMatch . '(\.' . $IPMatch . '){3}\]?';
  32. */
  33. /* Here's enough: */
  34. global $IP_RegExp_Match, $Host_RegExp_Match, $Email_RegExp_Match;
  35. //FIXME: these were written for use in an ereg().... they are now being used in preg()... we need to run some tests to make sure they are fully working still
  36. $IP_RegExp_Match = '\\[?[0-9]{1,3}(\\.[0-9]{1,3}){3}\\]?';
  37. $Host_RegExp_Match = '(' . $IP_RegExp_Match .
  38. '|[0-9a-z]([-.]?[0-9a-z])*\\.[a-z][a-z]+)';
  39. // NB: the backslash in the following line escapes the forward slash, which assumes that the regular expression will be enclosed in /.../
  40. $atext = '([a-z0-9!#$&%*+\/=?^_`{|}~-]|&amp;)';
  41. $dot_atom = $atext . '+(\.' . $atext . '+)*';
  42. $Email_RegExp_Match = $dot_atom . '(%' . $Host_RegExp_Match . ')?@' .
  43. $Host_RegExp_Match;
  44. /**
  45. * Parses a body and converts all found email addresses to clickable links.
  46. *
  47. * @param string body the body to process, by ref
  48. * @return int the number of unique addresses found
  49. */
  50. function parseEmail (&$body) {
  51. global $Email_RegExp_Match;
  52. $sbody = $body;
  53. $addresses = array();
  54. /* Find all the email addresses in the body */
  55. while (preg_match('/' . $Email_RegExp_Match . '/i', $sbody, $regs)) {
  56. $addresses[$regs[0]] = strtr($regs[0], array('&amp;' => '&'));
  57. $start = strpos($sbody, $regs[0]) + strlen($regs[0]);
  58. $sbody = substr($sbody, $start);
  59. }
  60. /* Replace each email address with a compose URL */
  61. foreach ($addresses as $text => $email) {
  62. $comp_uri = makeComposeLink('src/compose.php?send_to='.urlencode($email), $text);
  63. $body = str_replace($text, $comp_uri, $body);
  64. }
  65. /* Return number of unique addresses found */
  66. return count($addresses);
  67. }
  68. /* We don't want to re-initialize this stuff for every line. Save work
  69. * and just do it once here.
  70. */
  71. global $url_parser_url_tokens;
  72. $url_parser_url_tokens = array(
  73. 'http://',
  74. 'https://',
  75. 'ftp://',
  76. 'telnet:', // Special case -- doesn't need the slashes
  77. 'mailto:', // Special case -- doesn't use the slashes
  78. 'gopher://',
  79. 'news://');
  80. global $url_parser_poss_ends;
  81. $url_parser_poss_ends = array(' ', "\n", "\r", '<', '>', ".\r", ".\n",
  82. '.&nbsp;', '&nbsp;', ')', '(', '&quot;', '&lt;', '&gt;', '.<',
  83. ']', '[', '{', '}', "\240", ', ', '. ', ",\n", ",\r");
  84. /**
  85. * rfc 2368 (mailto URL) preg_match() regexp
  86. * @link http://www.ietf.org/rfc/rfc2368.txt
  87. * @global string MailTo_PReg_Match the encapsulated regexp for preg_match()
  88. */
  89. global $MailTo_PReg_Match;
  90. $Mailto_Email_RegExp = '[0-9a-z%]([-_.+%]?[0-9a-z])*(%' . $Host_RegExp_Match . ')?@' . $Host_RegExp_Match;
  91. $MailTo_PReg_Match = '/((?:' . $Mailto_Email_RegExp . ')*)((?:\?(?:to|cc|bcc|subject|body)=[^\s\?&=,()]+)?(?:&amp;(?:to|cc|bcc|subject|body)=[^\s\?&=,()]+)*)/i';
  92. /**
  93. * Parses a body and converts all found URLs to clickable links.
  94. *
  95. * @param string body the body to process, by ref
  96. * @return void
  97. */
  98. function parseUrl (&$body) {
  99. global $url_parser_poss_ends, $url_parser_url_tokens;
  100. $start = 0;
  101. $blength = strlen($body);
  102. while ($start < $blength) {
  103. $target_token = '';
  104. $target_pos = $blength;
  105. /* Find the first token to replace */
  106. foreach ($url_parser_url_tokens as $the_token) {
  107. $pos = strpos(strtolower($body), $the_token, $start);
  108. if (is_int($pos) && $pos < $target_pos) {
  109. $target_pos = $pos;
  110. $target_token = $the_token;
  111. }
  112. }
  113. /* Look for email addresses between $start and $target_pos */
  114. $check_str = substr($body, $start, $target_pos-$start);
  115. if (parseEmail($check_str)) {
  116. replaceBlock($body, $check_str, $start, $target_pos);
  117. $blength = strlen($body);
  118. $target_pos = strlen($check_str) + $start;
  119. }
  120. // rfc 2368 (mailto URL)
  121. if ($target_token == 'mailto:') {
  122. $target_pos += 7; //skip mailto:
  123. $end = $blength;
  124. $mailto = substr($body, $target_pos, $end-$target_pos);
  125. global $MailTo_PReg_Match;
  126. if ((preg_match($MailTo_PReg_Match, $mailto, $regs)) && ($regs[0] != '')) {
  127. //sm_print_r($regs);
  128. $mailto_before = $target_token . $regs[0];
  129. /**
  130. * '+' characters in a mailto URI don't need to be percent-encoded.
  131. * However, when mailto URI data is transported via HTTP, '+' must
  132. * be percent-encoded as %2B so that when the HTTP data is
  133. * percent-decoded, you get '+' back and not a space.
  134. */
  135. $mailto_params = str_replace("+", "%2B", $regs[10]);
  136. if ($regs[1]) { //if there is an email addr before '?', we need to merge it with the params
  137. $to = 'to=' . str_replace("+", "%2B", $regs[1]);
  138. if (strpos($mailto_params, 'to=') > -1) //already a 'to='
  139. $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
  140. else {
  141. if ($mailto_params) //already some params, append to them
  142. $mailto_params .= '&amp;' . $to;
  143. else
  144. $mailto_params .= '?' . $to;
  145. }
  146. }
  147. $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
  148. $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
  149. replaceBlock($body, $comp_uri, $target_pos - 7, $target_pos + strlen($regs[0]));
  150. $target_pos += strlen($comp_uri) - 7;
  151. }
  152. }
  153. else
  154. /* If there was a token to replace, replace it */
  155. if ($target_token != '') {
  156. /* Find the end of the URL */
  157. $end = $blength;
  158. foreach ($url_parser_poss_ends as $val) {
  159. $enda = strpos($body, $val, $target_pos);
  160. if (is_int($enda) && $enda < $end) {
  161. $end = $enda;
  162. }
  163. }
  164. /* make sure that there are no 8bit chars between $target_pos and suspected end of URL */
  165. if (!is_bool($first8bit=sq_strpos_8bit($body,$target_pos,$end))) {
  166. $end = $first8bit;
  167. }
  168. /* Extract URL */
  169. $url = substr($body, $target_pos, $end-$target_pos);
  170. /* Needed since lines are not passed with \n or \r */
  171. while ( preg_match('/[,.]$/', $url) ) {
  172. $url = substr( $url, 0, -1 );
  173. $end--;
  174. }
  175. /* Replace URL with HyperLinked Url, requires 1 char in link */
  176. if ($url != '' && $url != $target_token) {
  177. $url_str = "<a href=\"$url\" target=\"_blank\">$url</a>";
  178. replaceBlock($body,$url_str,$target_pos,$end);
  179. $target_pos += strlen($url_str);
  180. }
  181. else {
  182. // Not quite a valid link, skip ahead to next chance
  183. $target_pos += strlen($target_token);
  184. }
  185. }
  186. /* Move forward */
  187. $start = $target_pos;
  188. $blength = strlen($body);
  189. }
  190. }
  191. /**
  192. * Parses a string and returns the first e-mail address found.
  193. *
  194. * @param string string the string to process
  195. * @return string the first e-mail address found
  196. */
  197. function getEmail($string) {
  198. global $Email_RegExp_Match;
  199. $addresses = array();
  200. /* Find all the email addresses in the body */
  201. while (preg_match('/' . $Email_RegExp_Match . '/i', $string, $regs)) {
  202. $addresses[$regs[0]] = strtr($regs[0], array('&amp;' => '&'));
  203. $start = strpos($string, $regs[0]) + strlen($regs[0]);
  204. $string = substr($string, $start);
  205. }
  206. /* Return the first address, or an empty string if no address was found */
  207. $addresses = array_values($addresses);
  208. return (array_key_exists(0, $addresses) ? $addresses[0] : '');
  209. }
  210. /**
  211. * Finds first occurrence of 8bit data in the string
  212. *
  213. * Function finds first 8bit symbol or html entity that represents 8bit character.
  214. * Search start is defined by $offset argument. Search ends at $maxlength position.
  215. * If $maxlength is not defined or bigger than provided string, search ends when
  216. * string ends.
  217. *
  218. * Check returned data type in order to avoid confusion between bool(false)
  219. * (not found) and int(0) (first char in the string).
  220. * @param string $haystack
  221. * @param integer $offset
  222. * @param integer $maxlength
  223. * @return mixed integer with first 8bit character position or boolean false
  224. * @since 1.5.2
  225. */
  226. function sq_strpos_8bit($haystack,$offset=0,$maxlength=false) {
  227. $ret = false;
  228. if ($maxlength===false || strlen($haystack) < $maxlength) {
  229. $maxlength=strlen($haystack);
  230. }
  231. for($i=$offset;$i<$maxlength;$i++) {
  232. /* rh7-8 compatibility. don't use full 8bit range in regexp */
  233. if (preg_match('/[\200-\237]|\240|[\241-\377]/',$haystack[$i])) {
  234. /* we have 8bit char. stop here and return position */
  235. $ret = $i;
  236. break;
  237. } elseif ($haystack[$i]=='&') {
  238. $substring = substr($haystack,$i);
  239. /**
  240. * 1. look for "&#(decimal number);" where decimal_number is bigger than 127
  241. * 2. look for "&x(hexadecimal number);", where hex number is bigger than x7f
  242. * 3. look for any html character entity that is not 7bit html special char. Use
  243. * own sq_get_html_translation_table() function with 'utf-8' character set in
  244. * order to get all html entities.
  245. */
  246. if ((preg_match('/^&#(\d+);/',$substring,$match) && $match[1]>127) ||
  247. (preg_match('/^&x([0-9a-f]+);/i',$substring,$match) && $match[1]>"\x7f") ||
  248. (preg_match('/^&([a-z]+);/i',$substring,$match) &&
  249. !in_array($match[0],get_html_translation_table(HTML_SPECIALCHARS)) &&
  250. in_array($match[0],sq_get_html_translation_table(HTML_ENTITIES,ENT_COMPAT,'utf-8')))) {
  251. $ret = $i;
  252. break;
  253. }
  254. }
  255. }
  256. return $ret;
  257. }