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