url_parser.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 &copy; 1999-2007 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. $IP_RegExp_Match = '\\[?[0-9]{1,3}(\\.[0-9]{1,3}){3}\\]?';
  36. $Host_RegExp_Match = '(' . $IP_RegExp_Match .
  37. '|[0-9a-z]([-.]?[0-9a-z])*\\.[a-z][a-z]+)';
  38. $atext = '([a-z0-9!#$&%*+/=?^_`{|}~-]|&amp;)';
  39. $dot_atom = $atext . '+(\.' . $atext . '+)*';
  40. $Email_RegExp_Match = $dot_atom . '(%' . $Host_RegExp_Match . ')?@' .
  41. $Host_RegExp_Match;
  42. /**
  43. * Parses a body and converts all found email addresses to clickable links.
  44. *
  45. * @param string body the body to process, by ref
  46. * @return int the number of unique addresses found
  47. */
  48. function parseEmail (&$body) {
  49. global $Email_RegExp_Match;
  50. $sbody = $body;
  51. $addresses = array();
  52. /* Find all the email addresses in the body */
  53. while(eregi($Email_RegExp_Match, $sbody, $regs)) {
  54. $addresses[$regs[0]] = strtr($regs[0], array('&amp;' => '&'));
  55. $start = strpos($sbody, $regs[0]) + strlen($regs[0]);
  56. $sbody = substr($sbody, $start);
  57. }
  58. /* Replace each email address with a compose URL */
  59. foreach ($addresses as $text => $email) {
  60. $comp_uri = makeComposeLink('src/compose.php?send_to='.urlencode($email), $text);
  61. $body = str_replace($text, $comp_uri, $body);
  62. }
  63. /* Return number of unique addresses found */
  64. return count($addresses);
  65. }
  66. /* We don't want to re-initialize this stuff for every line. Save work
  67. * and just do it once here.
  68. */
  69. global $url_parser_url_tokens;
  70. $url_parser_url_tokens = array(
  71. 'http://',
  72. 'https://',
  73. 'ftp://',
  74. 'telnet:', // Special case -- doesn't need the slashes
  75. 'mailto:', // Special case -- doesn't use the slashes
  76. 'gopher://',
  77. 'news://');
  78. global $url_parser_poss_ends;
  79. $url_parser_poss_ends = array(' ', "\n", "\r", '<', '>', ".\r", ".\n",
  80. '.&nbsp;', '&nbsp;', ')', '(', '&quot;', '&lt;', '&gt;', '.<',
  81. ']', '[', '{', '}', "\240", ', ', '. ', ",\n", ",\r");
  82. /**
  83. * rfc 2368 (mailto URL) preg_match() regexp
  84. * @link http://www.ietf.org/rfc/rfc2368.txt
  85. * @global string MailTo_PReg_Match the encapsulated regexp for preg_match()
  86. */
  87. global $MailTo_PReg_Match;
  88. $Mailto_Email_RegExp = '[0-9a-z%]([-_.+%]?[0-9a-z])*(%' . $Host_RegExp_Match . ')?@' . $Host_RegExp_Match;
  89. $MailTo_PReg_Match = '/((?:' . $Mailto_Email_RegExp . ')*)((?:\?(?:to|cc|bcc|subject|body)=[^\s\?&=,()]+)?(?:&amp;(?:to|cc|bcc|subject|body)=[^\s\?&=,()]+)*)/i';
  90. /**
  91. * Parses a body and converts all found URLs to clickable links.
  92. *
  93. * @param string body the body to process, by ref
  94. * @return void
  95. */
  96. function parseUrl (&$body) {
  97. global $url_parser_poss_ends, $url_parser_url_tokens;
  98. $start = 0;
  99. $blength = strlen($body);
  100. while ($start < $blength) {
  101. $target_token = '';
  102. $target_pos = $blength;
  103. /* Find the first token to replace */
  104. foreach ($url_parser_url_tokens as $the_token) {
  105. $pos = strpos(strtolower($body), $the_token, $start);
  106. if (is_int($pos) && $pos < $target_pos) {
  107. $target_pos = $pos;
  108. $target_token = $the_token;
  109. }
  110. }
  111. /* Look for email addresses between $start and $target_pos */
  112. $check_str = substr($body, $start, $target_pos-$start);
  113. if (parseEmail($check_str)) {
  114. replaceBlock($body, $check_str, $start, $target_pos);
  115. $blength = strlen($body);
  116. $target_pos = strlen($check_str) + $start;
  117. }
  118. /* If there was a token to replace, replace it */
  119. if ($target_token == 'mailto:') { // rfc 2368 (mailto URL)
  120. $target_pos += 7; //skip mailto:
  121. $end = $blength;
  122. $mailto = substr($body, $target_pos, $end-$target_pos);
  123. global $MailTo_PReg_Match;
  124. if ((preg_match($MailTo_PReg_Match, $mailto, $regs)) && ($regs[0] != '')) {
  125. //sm_print_r($regs);
  126. $mailto_before = $target_token . $regs[0];
  127. $mailto_params = $regs[10];
  128. if ($regs[1]) { //if there is an email addr before '?', we need to merge it with the params
  129. $to = 'to=' . $regs[1];
  130. if (strpos($mailto_params, 'to=') > -1) //already a 'to='
  131. $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
  132. else {
  133. if ($mailto_params) //already some params, append to them
  134. $mailto_params .= '&amp;' . $to;
  135. else
  136. $mailto_params .= '?' . $to;
  137. }
  138. }
  139. $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
  140. $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
  141. replaceBlock($body, $comp_uri, $target_pos - 7, $target_pos + strlen($regs[0]));
  142. $target_pos += strlen($comp_uri) - 7;
  143. }
  144. }
  145. else
  146. if ($target_token != '') {
  147. /* Find the end of the URL */
  148. $end = $blength;
  149. foreach ($url_parser_poss_ends as $val) {
  150. $enda = strpos($body, $val, $target_pos);
  151. if (is_int($enda) && $enda < $end) {
  152. $end = $enda;
  153. }
  154. }
  155. /* make sure that there are no 8bit chars between $target_pos and suspected end of URL */
  156. if (!is_bool($first8bit=sq_strpos_8bit($body,$target_pos,$end))) {
  157. $end = $first8bit;
  158. }
  159. /* Extract URL */
  160. $url = substr($body, $target_pos, $end-$target_pos);
  161. /* Needed since lines are not passed with \n or \r */
  162. while ( ereg("[,\.]$", $url) ) {
  163. $url = substr( $url, 0, -1 );
  164. $end--;
  165. }
  166. /* Replace URL with HyperLinked Url, requires 1 char in link */
  167. if ($url != '' && $url != $target_token) {
  168. $url_str = "<a href=\"$url\" target=\"_blank\">$url</a>";
  169. replaceBlock($body,$url_str,$target_pos,$end);
  170. $target_pos += strlen($url_str);
  171. }
  172. else {
  173. // Not quite a valid link, skip ahead to next chance
  174. $target_pos += strlen($target_token);
  175. }
  176. }
  177. /* Move forward */
  178. $start = $target_pos;
  179. $blength = strlen($body);
  180. }
  181. }
  182. /**
  183. * Parses a string and returns the first e-mail address found.
  184. *
  185. * @param string string the string to process
  186. * @return string the first e-mail address found
  187. */
  188. function getEmail($string) {
  189. global $Email_RegExp_Match;
  190. $addresses = array();
  191. /* Find all the email addresses in the body */
  192. while (eregi($Email_RegExp_Match, $string, $regs)) {
  193. $addresses[$regs[0]] = strtr($regs[0], array('&amp;' => '&'));
  194. $start = strpos($string, $regs[0]) + strlen($regs[0]);
  195. $string = substr($string, $start);
  196. }
  197. /* Return the first address, or an empty string if no address was found */
  198. $addresses = array_values($addresses);
  199. return (array_key_exists(0, $addresses) ? $addresses[0] : '');
  200. }
  201. /**
  202. * Finds first occurrence of 8bit data in the string
  203. *
  204. * Function finds first 8bit symbol or html entity that represents 8bit character.
  205. * Search start is defined by $offset argument. Search ends at $maxlength position.
  206. * If $maxlength is not defined or bigger than provided string, search ends when
  207. * string ends.
  208. *
  209. * Check returned data type in order to avoid confusion between bool(false)
  210. * (not found) and int(0) (first char in the string).
  211. * @param string $haystack
  212. * @param integer $offset
  213. * @param integer $maxlength
  214. * @return mixed integer with first 8bit character position or boolean false
  215. * @since 1.5.2
  216. */
  217. function sq_strpos_8bit($haystack,$offset=0,$maxlength=false) {
  218. $ret = false;
  219. if ($maxlength===false || strlen($haystack) < $maxlength) {
  220. $maxlength=strlen($haystack);
  221. }
  222. for($i=$offset;$i<$maxlength;$i++) {
  223. /* rh7-8 compatibility. don't use full 8bit range in regexp */
  224. if (preg_match('/[\200-\237]|\240|[\241-\377]/',$haystack[$i])) {
  225. /* we have 8bit char. stop here and return position */
  226. $ret = $i;
  227. break;
  228. } elseif ($haystack[$i]=='&') {
  229. $substring = substr($haystack,$i);
  230. /**
  231. * 1. look for "&#(decimal number);" where decimal_number is bigger than 127
  232. * 2. look for "&x(hexadecimal number);", where hex number is bigger than x7f
  233. * 3. look for any html character entity that is not 7bit html special char. Use
  234. * own sq_get_html_translation_table() function with 'utf-8' character set in
  235. * order to get all html entities.
  236. */
  237. if ((preg_match('/^&#(\d+);/',$substring,$match) && $match[1]>127) ||
  238. (preg_match('/^&x([0-9a-f]+);/i',$substring,$match) && $match[1]>"\x7f") ||
  239. (preg_match('/^&([a-z]+);/i',$substring,$match) &&
  240. !in_array($match[0],get_html_translation_table(HTML_SPECIALCHARS)) &&
  241. in_array($match[0],sq_get_html_translation_table(HTML_ENTITIES,ENT_COMPAT,'utf-8')))) {
  242. $ret = $i;
  243. break;
  244. }
  245. }
  246. }
  247. return $ret;
  248. }