]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
strip out session ID from root URL
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, user, files) */
21
22 // Show a server error
23
24 function common_server_error($msg, $code=500)
25 {
26     $err = new ServerErrorAction($msg, $code);
27     $err->showPage();
28 }
29
30 // Show a user error
31 function common_user_error($msg, $code=400)
32 {
33     $err = new ClientErrorAction($msg, $code);
34     $err->showPage();
35 }
36
37 function common_init_locale($language=null)
38 {
39     if(!$language) {
40         $language = common_language();
41     }
42     putenv('LANGUAGE='.$language);
43     putenv('LANG='.$language);
44     return setlocale(LC_ALL, $language . ".utf8",
45                      $language . ".UTF8",
46                      $language . ".utf-8",
47                      $language . ".UTF-8",
48                      $language);
49 }
50
51 function common_init_language()
52 {
53     mb_internal_encoding('UTF-8');
54
55     // gettext seems very picky... We first need to setlocale()
56     // to a locale which _does_ exist on the system, and _then_
57     // we can set in another locale that may not be set up
58     // (say, ga_ES for Galego/Galician) it seems to take it.
59     common_init_locale("en_US");
60
61     // Note that this setlocale() call may "fail" but this is harmless;
62     // gettext will still select the right language.
63     $language = common_language();
64     $locale_set = common_init_locale($language);
65
66     setlocale(LC_CTYPE, 'C');
67     // So we do not have to make people install the gettext locales
68     $path = common_config('site','locale_path');
69     bindtextdomain("statusnet", $path);
70     bind_textdomain_codeset("statusnet", "UTF-8");
71     textdomain("statusnet");
72 }
73
74 function common_timezone()
75 {
76     if (common_logged_in()) {
77         $user = common_current_user();
78         if ($user->timezone) {
79             return $user->timezone;
80         }
81     }
82
83     return common_config('site', 'timezone');
84 }
85
86 function common_language()
87 {
88
89     // If there is a user logged in and they've set a language preference
90     // then return that one...
91     if (_have_config() && common_logged_in()) {
92         $user = common_current_user();
93         $user_language = $user->language;
94
95         if ($user->language) {
96             // Validate -- we don't want to end up with a bogus code
97             // left over from some old junk.
98             foreach (common_config('site', 'languages') as $code => $info) {
99                 if ($info['lang'] == $user_language) {
100                     return $user_language;
101                 }
102             }
103         }
104     }
105
106     // Otherwise, find the best match for the languages requested by the
107     // user's browser...
108     $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
109     if (!empty($httplang)) {
110         $language = client_prefered_language($httplang);
111         if ($language)
112           return $language;
113     }
114
115     // Finally, if none of the above worked, use the site's default...
116     return common_config('site', 'language');
117 }
118 // salted, hashed passwords are stored in the DB
119
120 function common_munge_password($password, $id)
121 {
122     return md5($password . $id);
123 }
124
125 // check if a username exists and has matching password
126
127 function common_check_user($nickname, $password)
128 {
129     $authenticatedUser = false;
130
131     if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
132         $user = User::staticGet('nickname', $nickname);
133         if (!empty($user)) {
134             if (!empty($password)) { // never allow login with blank password
135                 if (0 == strcmp(common_munge_password($password, $user->id),
136                                 $user->password)) {
137                     //internal checking passed
138                     $authenticatedUser = $user;
139                 }
140             }
141         }
142         Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
143     }
144
145     return $authenticatedUser;
146 }
147
148 // is the current user logged in?
149 function common_logged_in()
150 {
151     return (!is_null(common_current_user()));
152 }
153
154 function common_have_session()
155 {
156     return (0 != strcmp(session_id(), ''));
157 }
158
159 function common_ensure_session()
160 {
161     $c = null;
162     if (array_key_exists(session_name(), $_COOKIE)) {
163         $c = $_COOKIE[session_name()];
164     }
165     if (!common_have_session()) {
166         if (common_config('sessions', 'handle')) {
167             Session::setSaveHandler();
168         }
169         if (array_key_exists(session_name(), $_GET)) {
170             $id = $_GET[session_name()];
171             common_log(LOG_INFO, 'Setting session from GET parameter: '.$id);
172         } else if (array_key_exists(session_name(), $_COOKIE)) {
173             $id = $_COOKIE[session_name()];
174             common_log(LOG_INFO, 'Setting session from COOKIE: '.$id);
175         }
176         if (isset($id)) {
177             session_id($id);
178             setcookie(session_name(), $id);
179         }
180         @session_start();
181         if (!isset($_SESSION['started'])) {
182             $_SESSION['started'] = time();
183             if (!empty($id)) {
184                 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
185                            ' is set but started value is null');
186             }
187         }
188     }
189     common_debug("Session ID = " . session_id());
190 }
191
192 // Three kinds of arguments:
193 // 1) a user object
194 // 2) a nickname
195 // 3) null to clear
196
197 // Initialize to false; set to null if none found
198
199 $_cur = false;
200
201 function common_set_user($user)
202 {
203
204     global $_cur;
205
206     if (is_null($user) && common_have_session()) {
207         $_cur = null;
208         unset($_SESSION['userid']);
209         return true;
210     } else if (is_string($user)) {
211         $nickname = $user;
212         $user = User::staticGet('nickname', $nickname);
213     } else if (!($user instanceof User)) {
214         return false;
215     }
216
217     if ($user) {
218         if (Event::handle('StartSetUser', array(&$user))) {
219             if($user){
220                 common_ensure_session();
221                 $_SESSION['userid'] = $user->id;
222                 $_cur = $user;
223                 Event::handle('EndSetUser', array($user));
224                 return $_cur;
225             }
226         }
227     }
228     return false;
229 }
230
231 function common_set_cookie($key, $value, $expiration=0)
232 {
233     $path = common_config('site', 'path');
234     $server = common_config('site', 'server');
235
236     if ($path && ($path != '/')) {
237         $cookiepath = '/' . $path . '/';
238     } else {
239         $cookiepath = '/';
240     }
241     return setcookie($key,
242                      $value,
243                      $expiration,
244                      $cookiepath,
245                      $server);
246 }
247
248 define('REMEMBERME', 'rememberme');
249 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
250
251 function common_rememberme($user=null)
252 {
253     if (!$user) {
254         $user = common_current_user();
255         if (!$user) {
256             common_debug('No current user to remember', __FILE__);
257             return false;
258         }
259     }
260
261     $rm = new Remember_me();
262
263     $rm->code = common_good_rand(16);
264     $rm->user_id = $user->id;
265
266     // Wrap the insert in some good ol' fashioned transaction code
267
268     $rm->query('BEGIN');
269
270     $result = $rm->insert();
271
272     if (!$result) {
273         common_log_db_error($rm, 'INSERT', __FILE__);
274         common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
275         return false;
276     }
277
278     $rm->query('COMMIT');
279
280     common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
281
282     $cookieval = $rm->user_id . ':' . $rm->code;
283
284     common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
285
286     common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
287
288     return true;
289 }
290
291 function common_remembered_user()
292 {
293
294     $user = null;
295
296     $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
297
298     if (!$packed) {
299         return null;
300     }
301
302     list($id, $code) = explode(':', $packed);
303
304     if (!$id || !$code) {
305         common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
306         common_forgetme();
307         return null;
308     }
309
310     $rm = Remember_me::staticGet($code);
311
312     if (!$rm) {
313         common_log(LOG_WARNING, 'No such remember code: ' . $code);
314         common_forgetme();
315         return null;
316     }
317
318     if ($rm->user_id != $id) {
319         common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
320         common_forgetme();
321         return null;
322     }
323
324     $user = User::staticGet($rm->user_id);
325
326     if (!$user) {
327         common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
328         common_forgetme();
329         return null;
330     }
331
332     // successful!
333     $result = $rm->delete();
334
335     if (!$result) {
336         common_log_db_error($rm, 'DELETE', __FILE__);
337         common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
338         common_forgetme();
339         return null;
340     }
341
342     common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
343
344     common_set_user($user);
345     common_real_login(false);
346
347     // We issue a new cookie, so they can log in
348     // automatically again after this session
349
350     common_rememberme($user);
351
352     return $user;
353 }
354
355 // must be called with a valid user!
356
357 function common_forgetme()
358 {
359     common_set_cookie(REMEMBERME, '', 0);
360 }
361
362 // who is the current user?
363 function common_current_user()
364 {
365     global $_cur;
366
367     if (!_have_config()) {
368         return null;
369     }
370
371     if ($_cur === false) {
372
373         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
374             common_ensure_session();
375             $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
376             if ($id) {
377                 $user = User::staticGet($id);
378                 if ($user) {
379                         $_cur = $user;
380                         return $_cur;
381                 }
382             }
383         }
384
385         // that didn't work; try to remember; will init $_cur to null on failure
386         $_cur = common_remembered_user();
387
388         if ($_cur) {
389             common_debug("Got User " . $_cur->nickname);
390             common_debug("Faking session on remembered user");
391             // XXX: Is this necessary?
392             $_SESSION['userid'] = $_cur->id;
393         }
394     }
395
396     return $_cur;
397 }
398
399 // Logins that are 'remembered' aren't 'real' -- they're subject to
400 // cookie-stealing. So, we don't let them do certain things. New reg,
401 // OpenID, and password logins _are_ real.
402
403 function common_real_login($real=true)
404 {
405     common_ensure_session();
406     $_SESSION['real_login'] = $real;
407 }
408
409 function common_is_real_login()
410 {
411     return common_logged_in() && $_SESSION['real_login'];
412 }
413
414 // get canonical version of nickname for comparison
415 function common_canonical_nickname($nickname)
416 {
417     // XXX: UTF-8 canonicalization (like combining chars)
418     return strtolower($nickname);
419 }
420
421 // get canonical version of email for comparison
422 function common_canonical_email($email)
423 {
424     // XXX: canonicalize UTF-8
425     // XXX: lcase the domain part
426     return $email;
427 }
428
429 function common_render_content($text, $notice)
430 {
431     $r = common_render_text($text);
432     $id = $notice->profile_id;
433     $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
434     $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
435     $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
436     $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
437     return $r;
438 }
439
440 function common_render_text($text)
441 {
442     $r = htmlspecialchars($text);
443
444     $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
445     $r = common_replace_urls_callback($r, 'common_linkify');
446     $r = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
447     // XXX: machine tags
448     return $r;
449 }
450
451 function common_replace_urls_callback($text, $callback, $notice_id = null) {
452     // Start off with a regex
453     $regex = '#'.
454     '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
455     '('.
456         '(?:'.
457             '(?:'. //Known protocols
458                 '(?:'.
459                     '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
460                     '|'.
461                     '(?:(?:mailto|aim|tel|xmpp):)'.
462                 ')'.
463                 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
464                 '(?:'.
465                     '(?:'.
466                         '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
467                     ')|(?:'.
468                         '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
469                     ')'.
470                 ')'.
471             ')'.
472             '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'. //IPv4
473             '|(?:'. //IPv6
474                 '\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?(?<!:)'.
475             ')|(?:'. //DNS
476                 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
477                 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
478                 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
479                 '(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZW|local|loc|onion)'.
480             ')(?![\pN\pL\-\_])'.
481         ')'.
482         '(?:'.
483             '(?:\:\d+)?'. //:port
484             '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
485             '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
486             '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
487         ')(?<![\?\.\,\#\,])'.
488     ')'.
489     '#ixu';
490     //preg_match_all($regex,$text,$matches);
491     //print_r($matches);
492     return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
493 }
494
495 function callback_helper($matches, $callback, $notice_id) {
496     $url=$matches[1];
497     $left = strpos($matches[0],$url);
498     $right = $left+strlen($url);
499
500     $groupSymbolSets=array(
501         array(
502             'left'=>'(',
503             'right'=>')'
504         ),
505         array(
506             'left'=>'[',
507             'right'=>']'
508         ),
509         array(
510             'left'=>'{',
511             'right'=>'}'
512         ),
513         array(
514             'left'=>'<',
515             'right'=>'>'
516         )
517     );
518     $cannotEndWith=array('.','?',',','#');
519     $original_url=$url;
520     do{
521         $original_url=$url;
522         foreach($groupSymbolSets as $groupSymbolSet){
523             if(substr($url,-1)==$groupSymbolSet['right']){
524                 $group_left_count = substr_count($url,$groupSymbolSet['left']);
525                 $group_right_count = substr_count($url,$groupSymbolSet['right']);
526                 if($group_left_count<$group_right_count){
527                     $right-=1;
528                     $url=substr($url,0,-1);
529                 }
530             }
531         }
532         if(in_array(substr($url,-1),$cannotEndWith)){
533             $right-=1;
534             $url=substr($url,0,-1);
535         }
536     }while($original_url!=$url);
537
538     if(empty($notice_id)){
539         $result = call_user_func_array($callback, array($url));
540     }else{
541         $result = call_user_func_array($callback, array(array($url,$notice_id)) );
542     }
543     return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
544 }
545
546 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
547     // lambda implementation in a separate file; PHP 5.2 won't parse it.
548     require_once INSTALLDIR . "/lib/curry.php";
549 } else {
550     function curry($fn) {
551         $args = func_get_args();
552         array_shift($args);
553         $id = uniqid('_partial');
554         $GLOBALS[$id] = array($fn, $args);
555         return create_function('',
556                                '$args = func_get_args(); '.
557                                'return call_user_func_array('.
558                                '$GLOBALS["'.$id.'"][0],'.
559                                'array_merge('.
560                                '$args,'.
561                                '$GLOBALS["'.$id.'"][1]));');
562     }
563 }
564
565 function common_linkify($url) {
566     // It comes in special'd, so we unspecial it before passing to the stringifying
567     // functions
568     $url = htmlspecialchars_decode($url);
569
570    if(strpos($url, '@') !== false && strpos($url, ':') === false) {
571        //url is an email address without the mailto: protocol
572        $canon = "mailto:$url";
573        $longurl = "mailto:$url";
574    }else{
575
576         $canon = File_redirection::_canonUrl($url);
577
578         $longurl_data = File_redirection::where($canon);
579         if (is_array($longurl_data)) {
580             $longurl = $longurl_data['url'];
581         } elseif (is_string($longurl_data)) {
582             $longurl = $longurl_data;
583         } else {
584             throw new ServerException("Can't linkify url '$url'");
585         }
586     }
587     $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
588
589     $is_attachment = false;
590     $attachment_id = null;
591     $has_thumb = false;
592
593     // Check to see whether this is a known "attachment" URL.
594
595     $f = File::staticGet('url', $longurl);
596
597     if (empty($f)) {
598         // XXX: this writes to the database. :<
599         $f = File::processNew($longurl);
600     }
601
602     if (!empty($f)) {
603         if ($f->isEnclosure()) {
604             $is_attachment = true;
605             $attachment_id = $f->id;
606         } else {
607             $foe = File_oembed::staticGet('file_id', $f->id);
608             if (!empty($foe)) {
609                 // if it has OEmbed info, it's an attachment, too
610                 $is_attachment = true;
611                 $attachment_id = $f->id;
612
613                 $thumb = File_thumbnail::staticGet('file_id', $f->id);
614                 if (!empty($thumb)) {
615                     $has_thumb = true;
616                 }
617             }
618         }
619     }
620
621     // Add clippy
622     if ($is_attachment) {
623         $attrs['class'] = 'attachment';
624         if ($has_thumb) {
625             $attrs['class'] = 'attachment thumbnail';
626         }
627         $attrs['id'] = "attachment-{$attachment_id}";
628     }
629
630     return XMLStringer::estring('a', $attrs, $url);
631 }
632
633 function common_shorten_links($text)
634 {
635     $maxLength = Notice::maxContent();
636     if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
637     return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
638 }
639
640 function common_xml_safe_str($str)
641 {
642     // Neutralize control codes and surrogates
643         return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
644 }
645
646 function common_tag_link($tag)
647 {
648     $canonical = common_canonical_tag($tag);
649     $url = common_local_url('tag', array('tag' => $canonical));
650     $xs = new XMLStringer();
651     $xs->elementStart('span', 'tag');
652     $xs->element('a', array('href' => $url,
653                             'rel' => 'tag'),
654                  $tag);
655     $xs->elementEnd('span');
656     return $xs->getString();
657 }
658
659 function common_canonical_tag($tag)
660 {
661   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
662   return str_replace(array('-', '_', '.'), '', $tag);
663 }
664
665 function common_valid_profile_tag($str)
666 {
667     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
668 }
669
670 function common_at_link($sender_id, $nickname)
671 {
672     $sender = Profile::staticGet($sender_id);
673     $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
674     if ($recipient) {
675         $user = User::staticGet('id', $recipient->id);
676         if ($user) {
677             $url = common_local_url('userbyid', array('id' => $user->id));
678         } else {
679             $url = $recipient->profileurl;
680         }
681         $xs = new XMLStringer(false);
682         $attrs = array('href' => $url,
683                        'class' => 'url');
684         if (!empty($recipient->fullname)) {
685             $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
686         }
687         $xs->elementStart('span', 'vcard');
688         $xs->elementStart('a', $attrs);
689         $xs->element('span', 'fn nickname', $nickname);
690         $xs->elementEnd('a');
691         $xs->elementEnd('span');
692         return $xs->getString();
693     } else {
694         return $nickname;
695     }
696 }
697
698 function common_group_link($sender_id, $nickname)
699 {
700     $sender = Profile::staticGet($sender_id);
701     $group = User_group::getForNickname($nickname);
702     if ($group && $sender->isMember($group)) {
703         $attrs = array('href' => $group->permalink(),
704                        'class' => 'url');
705         if (!empty($group->fullname)) {
706             $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
707         }
708         $xs = new XMLStringer();
709         $xs->elementStart('span', 'vcard');
710         $xs->elementStart('a', $attrs);
711         $xs->element('span', 'fn nickname', $nickname);
712         $xs->elementEnd('a');
713         $xs->elementEnd('span');
714         return $xs->getString();
715     } else {
716         return $nickname;
717     }
718 }
719
720 function common_at_hash_link($sender_id, $tag)
721 {
722     $user = User::staticGet($sender_id);
723     if (!$user) {
724         return $tag;
725     }
726     $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
727     if ($tagged) {
728         $url = common_local_url('subscriptions',
729                                 array('nickname' => $user->nickname,
730                                       'tag' => $tag));
731         $xs = new XMLStringer();
732         $xs->elementStart('span', 'tag');
733         $xs->element('a', array('href' => $url,
734                                 'rel' => $tag),
735                      $tag);
736         $xs->elementEnd('span');
737         return $xs->getString();
738     } else {
739         return $tag;
740     }
741 }
742
743 function common_relative_profile($sender, $nickname, $dt=null)
744 {
745     // Try to find profiles this profile is subscribed to that have this nickname
746     $recipient = new Profile();
747     // XXX: use a join instead of a subquery
748     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
749     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
750     if ($recipient->find(true)) {
751         // XXX: should probably differentiate between profiles with
752         // the same name by date of most recent update
753         return $recipient;
754     }
755     // Try to find profiles that listen to this profile and that have this nickname
756     $recipient = new Profile();
757     // XXX: use a join instead of a subquery
758     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
759     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
760     if ($recipient->find(true)) {
761         // XXX: should probably differentiate between profiles with
762         // the same name by date of most recent update
763         return $recipient;
764     }
765     // If this is a local user, try to find a local user with that nickname.
766     $sender = User::staticGet($sender->id);
767     if ($sender) {
768         $recipient_user = User::staticGet('nickname', $nickname);
769         if ($recipient_user) {
770             return $recipient_user->getProfile();
771         }
772     }
773     // Otherwise, no links. @messages from local users to remote users,
774     // or from remote users to other remote users, are just
775     // outside our ability to make intelligent guesses about
776     return null;
777 }
778
779 function common_local_url($action, $args=null, $params=null, $fragment=null)
780 {
781     $r = Router::get();
782     $path = $r->build($action, $args, $params, $fragment);
783
784     $ssl = common_is_sensitive($action);
785
786     if (common_config('site','fancy')) {
787         $url = common_path(mb_substr($path, 1), $ssl);
788     } else {
789         if (mb_strpos($path, '/index.php') === 0) {
790             $url = common_path(mb_substr($path, 1), $ssl);
791         } else {
792             $url = common_path('index.php'.$path, $ssl);
793         }
794     }
795     return $url;
796 }
797
798 function common_is_sensitive($action)
799 {
800     static $sensitive = array('login', 'register', 'passwordsettings',
801                               'twittersettings', 'api');
802     $ssl = null;
803
804     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
805         $ssl = in_array($action, $sensitive);
806     }
807
808     return $ssl;
809 }
810
811 function common_path($relative, $ssl=false)
812 {
813     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
814
815     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
816         || common_config('site', 'ssl') === 'always') {
817         $proto = 'https';
818         if (is_string(common_config('site', 'sslserver')) &&
819             mb_strlen(common_config('site', 'sslserver')) > 0) {
820             $serverpart = common_config('site', 'sslserver');
821         } else if (common_config('site', 'server')) {
822             $serverpart = common_config('site', 'server');
823         } else {
824             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
825         }
826     } else {
827         $proto = 'http';
828         if (common_config('site', 'server')) {
829             $serverpart = common_config('site', 'server');
830         } else {
831             common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
832         }
833     }
834
835     $relative = common_inject_session($relative, $serverpart);
836
837     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
838 }
839
840 function common_inject_session($url, $serverpart = null)
841 {
842     if (common_have_session()) {
843
844         if (empty($serverpart)) {
845             $serverpart = parse_url($url, PHP_URL_HOST);
846         }
847
848         $currentServer = $_SERVER['HTTP_HOST'];
849
850         // Are we pointing to another server (like an SSL server?)
851
852         if (!empty($currentServer) &&
853             0 != strcasecmp($currentServer, $serverpart)) {
854             // Pass the session ID as a GET parameter
855             $sesspart = session_name() . '=' . session_id();
856             $i = strpos($url, '?');
857             if ($i === false) { // no GET params, just append
858                 $url .= '?' . $sesspart;
859             } else {
860                 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
861             }
862         }
863     }
864
865     return $url;
866 }
867
868 function common_date_string($dt)
869 {
870     // XXX: do some sexy date formatting
871     // return date(DATE_RFC822, $dt);
872     $t = strtotime($dt);
873     $now = time();
874     $diff = $now - $t;
875
876     if ($now < $t) { // that shouldn't happen!
877         return common_exact_date($dt);
878     } else if ($diff < 60) {
879         return _('a few seconds ago');
880     } else if ($diff < 92) {
881         return _('about a minute ago');
882     } else if ($diff < 3300) {
883         return sprintf(_('about %d minutes ago'), round($diff/60));
884     } else if ($diff < 5400) {
885         return _('about an hour ago');
886     } else if ($diff < 22 * 3600) {
887         return sprintf(_('about %d hours ago'), round($diff/3600));
888     } else if ($diff < 37 * 3600) {
889         return _('about a day ago');
890     } else if ($diff < 24 * 24 * 3600) {
891         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
892     } else if ($diff < 46 * 24 * 3600) {
893         return _('about a month ago');
894     } else if ($diff < 330 * 24 * 3600) {
895         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
896     } else if ($diff < 480 * 24 * 3600) {
897         return _('about a year ago');
898     } else {
899         return common_exact_date($dt);
900     }
901 }
902
903 function common_exact_date($dt)
904 {
905     static $_utc;
906     static $_siteTz;
907
908     if (!$_utc) {
909         $_utc = new DateTimeZone('UTC');
910         $_siteTz = new DateTimeZone(common_timezone());
911     }
912
913     $dateStr = date('d F Y H:i:s', strtotime($dt));
914     $d = new DateTime($dateStr, $_utc);
915     $d->setTimezone($_siteTz);
916     return $d->format(DATE_RFC850);
917 }
918
919 function common_date_w3dtf($dt)
920 {
921     $dateStr = date('d F Y H:i:s', strtotime($dt));
922     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
923     $d->setTimezone(new DateTimeZone(common_timezone()));
924     return $d->format(DATE_W3C);
925 }
926
927 function common_date_rfc2822($dt)
928 {
929     $dateStr = date('d F Y H:i:s', strtotime($dt));
930     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
931     $d->setTimezone(new DateTimeZone(common_timezone()));
932     return $d->format('r');
933 }
934
935 function common_date_iso8601($dt)
936 {
937     $dateStr = date('d F Y H:i:s', strtotime($dt));
938     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
939     $d->setTimezone(new DateTimeZone(common_timezone()));
940     return $d->format('c');
941 }
942
943 function common_sql_now()
944 {
945     return common_sql_date(time());
946 }
947
948 function common_sql_date($datetime)
949 {
950     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
951 }
952
953 /**
954  * Return an SQL fragment to calculate an age-based weight from a given
955  * timestamp or datetime column.
956  *
957  * @param string $column name of field we're comparing against current time
958  * @param integer $dropoff divisor for age in seconds before exponentiation
959  * @return string SQL fragment
960  */
961 function common_sql_weight($column, $dropoff)
962 {
963     if (common_config('db', 'type') == 'pgsql') {
964         // PostgreSQL doesn't support timestampdiff function.
965         // @fixme will this use the right time zone?
966         // @fixme does this handle cross-year subtraction correctly?
967         return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
968     } else {
969         return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
970     }
971 }
972
973 function common_redirect($url, $code=307)
974 {
975     static $status = array(301 => "Moved Permanently",
976                            302 => "Found",
977                            303 => "See Other",
978                            307 => "Temporary Redirect");
979
980     header('HTTP/1.1 '.$code.' '.$status[$code]);
981     header("Location: $url");
982
983     $xo = new XMLOutputter();
984     $xo->startXML('a',
985                   '-//W3C//DTD XHTML 1.0 Strict//EN',
986                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
987     $xo->element('a', array('href' => $url), $url);
988     $xo->endXML();
989     exit;
990 }
991
992 function common_broadcast_notice($notice, $remote=false)
993 {
994     return common_enqueue_notice($notice);
995 }
996
997 // Stick the notice on the queue
998
999 function common_enqueue_notice($notice)
1000 {
1001     static $localTransports = array('omb',
1002                                     'ping');
1003
1004     static $allTransports = array('sms', 'plugin');
1005
1006     $transports = $allTransports;
1007
1008     $xmpp = common_config('xmpp', 'enabled');
1009
1010     if ($xmpp) {
1011         $transports[] = 'jabber';
1012     }
1013
1014     if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1015         $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1016         $transports = array_merge($transports, $localTransports);
1017         if ($xmpp) {
1018             $transports[] = 'public';
1019         }
1020     }
1021
1022     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1023
1024         $qm = QueueManager::get();
1025
1026         foreach ($transports as $transport)
1027         {
1028             $qm->enqueue($notice, $transport);
1029         }
1030
1031         Event::handle('EndEnqueueNotice', array($notice, $transports));
1032     }
1033
1034     return true;
1035 }
1036
1037 function common_broadcast_profile($profile)
1038 {
1039     // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1040     require_once(INSTALLDIR.'/lib/omb.php');
1041     omb_broadcast_profile($profile);
1042     // XXX: Other broadcasts...?
1043     return true;
1044 }
1045
1046 function common_profile_url($nickname)
1047 {
1048     return common_local_url('showstream', array('nickname' => $nickname));
1049 }
1050
1051 // Should make up a reasonable root URL
1052
1053 function common_root_url($ssl=false)
1054 {
1055     $url = common_path('', $ssl);
1056     $i = strpos($url, '?');
1057     if ($i !== false) {
1058         $url = substr($url, 0, $i);
1059     }
1060     return $url;
1061 }
1062
1063 // returns $bytes bytes of random data as a hexadecimal string
1064 // "good" here is a goal and not a guarantee
1065
1066 function common_good_rand($bytes)
1067 {
1068     // XXX: use random.org...?
1069     if (@file_exists('/dev/urandom')) {
1070         return common_urandom($bytes);
1071     } else { // FIXME: this is probably not good enough
1072         return common_mtrand($bytes);
1073     }
1074 }
1075
1076 function common_urandom($bytes)
1077 {
1078     $h = fopen('/dev/urandom', 'rb');
1079     // should not block
1080     $src = fread($h, $bytes);
1081     fclose($h);
1082     $enc = '';
1083     for ($i = 0; $i < $bytes; $i++) {
1084         $enc .= sprintf("%02x", (ord($src[$i])));
1085     }
1086     return $enc;
1087 }
1088
1089 function common_mtrand($bytes)
1090 {
1091     $enc = '';
1092     for ($i = 0; $i < $bytes; $i++) {
1093         $enc .= sprintf("%02x", mt_rand(0, 255));
1094     }
1095     return $enc;
1096 }
1097
1098 function common_set_returnto($url)
1099 {
1100     common_ensure_session();
1101     $_SESSION['returnto'] = $url;
1102 }
1103
1104 function common_get_returnto()
1105 {
1106     common_ensure_session();
1107     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1108 }
1109
1110 function common_timestamp()
1111 {
1112     return date('YmdHis');
1113 }
1114
1115 function common_ensure_syslog()
1116 {
1117     static $initialized = false;
1118     if (!$initialized) {
1119         openlog(common_config('syslog', 'appname'), 0,
1120             common_config('syslog', 'facility'));
1121         $initialized = true;
1122     }
1123 }
1124
1125 function common_log_line($priority, $msg)
1126 {
1127     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1128                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1129     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1130 }
1131
1132 function common_request_id()
1133 {
1134     $pid = getmypid();
1135     if (php_sapi_name() == 'cli') {
1136         return $pid;
1137     } else {
1138         static $req_id = null;
1139         if (!isset($req_id)) {
1140             $req_id = substr(md5(mt_rand()), 0, 8);
1141         }
1142         if (isset($_SERVER['REQUEST_URI'])) {
1143             $url = $_SERVER['REQUEST_URI'];
1144         }
1145         $method = $_SERVER['REQUEST_METHOD'];
1146         return "$pid.$req_id $method $url";
1147     }
1148 }
1149
1150 function common_log($priority, $msg, $filename=null)
1151 {
1152     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1153         $msg = '[' . common_request_id() . '] ' . $msg;
1154         $logfile = common_config('site', 'logfile');
1155         if ($logfile) {
1156             $log = fopen($logfile, "a");
1157             if ($log) {
1158                 $output = common_log_line($priority, $msg);
1159                 fwrite($log, $output);
1160                 fclose($log);
1161             }
1162         } else {
1163             common_ensure_syslog();
1164             syslog($priority, $msg);
1165         }
1166         Event::handle('EndLog', array($priority, $msg, $filename));
1167     }
1168 }
1169
1170 function common_debug($msg, $filename=null)
1171 {
1172     if ($filename) {
1173         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1174     } else {
1175         common_log(LOG_DEBUG, $msg);
1176     }
1177 }
1178
1179 function common_log_db_error(&$object, $verb, $filename=null)
1180 {
1181     $objstr = common_log_objstring($object);
1182     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1183     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1184 }
1185
1186 function common_log_objstring(&$object)
1187 {
1188     if (is_null($object)) {
1189         return "null";
1190     }
1191     if (!($object instanceof DB_DataObject)) {
1192         return "(unknown)";
1193     }
1194     $arr = $object->toArray();
1195     $fields = array();
1196     foreach ($arr as $k => $v) {
1197         if (is_object($v)) {
1198             $fields[] = "$k='".get_class($v)."'";
1199         } else {
1200             $fields[] = "$k='$v'";
1201         }
1202     }
1203     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1204     return $objstring;
1205 }
1206
1207 function common_valid_http_url($url)
1208 {
1209     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1210 }
1211
1212 function common_valid_tag($tag)
1213 {
1214     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1215         return (Validate::email($matches[1]) ||
1216                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1217     }
1218     return false;
1219 }
1220
1221 /* Following functions are copied from MediaWiki GlobalFunctions.php
1222  * and written by Evan Prodromou. */
1223
1224 function common_accept_to_prefs($accept, $def = '*/*')
1225 {
1226     // No arg means accept anything (per HTTP spec)
1227     if(!$accept) {
1228         return array($def => 1);
1229     }
1230
1231     $prefs = array();
1232
1233     $parts = explode(',', $accept);
1234
1235     foreach($parts as $part) {
1236         // FIXME: doesn't deal with params like 'text/html; level=1'
1237         @list($value, $qpart) = explode(';', trim($part));
1238         $match = array();
1239         if(!isset($qpart)) {
1240             $prefs[$value] = 1;
1241         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1242             $prefs[$value] = $match[1];
1243         }
1244     }
1245
1246     return $prefs;
1247 }
1248
1249 function common_mime_type_match($type, $avail)
1250 {
1251     if(array_key_exists($type, $avail)) {
1252         return $type;
1253     } else {
1254         $parts = explode('/', $type);
1255         if(array_key_exists($parts[0] . '/*', $avail)) {
1256             return $parts[0] . '/*';
1257         } elseif(array_key_exists('*/*', $avail)) {
1258             return '*/*';
1259         } else {
1260             return null;
1261         }
1262     }
1263 }
1264
1265 function common_negotiate_type($cprefs, $sprefs)
1266 {
1267     $combine = array();
1268
1269     foreach(array_keys($sprefs) as $type) {
1270         $parts = explode('/', $type);
1271         if($parts[1] != '*') {
1272             $ckey = common_mime_type_match($type, $cprefs);
1273             if($ckey) {
1274                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1275             }
1276         }
1277     }
1278
1279     foreach(array_keys($cprefs) as $type) {
1280         $parts = explode('/', $type);
1281         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1282             $skey = common_mime_type_match($type, $sprefs);
1283             if($skey) {
1284                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1285             }
1286         }
1287     }
1288
1289     $bestq = 0;
1290     $besttype = 'text/html';
1291
1292     foreach(array_keys($combine) as $type) {
1293         if($combine[$type] > $bestq) {
1294             $besttype = $type;
1295             $bestq = $combine[$type];
1296         }
1297     }
1298
1299     if ('text/html' === $besttype) {
1300         return "text/html; charset=utf-8";
1301     }
1302     return $besttype;
1303 }
1304
1305 function common_config($main, $sub)
1306 {
1307     global $config;
1308     return (array_key_exists($main, $config) &&
1309             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1310 }
1311
1312 function common_copy_args($from)
1313 {
1314     $to = array();
1315     $strip = get_magic_quotes_gpc();
1316     foreach ($from as $k => $v) {
1317         $to[$k] = ($strip) ? stripslashes($v) : $v;
1318     }
1319     return $to;
1320 }
1321
1322 /**
1323  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1324  * This is used before handing a request off to OAuthRequest::from_request.
1325  * @fixme Doesn't consider vars other than _POST and _GET?
1326  * @fixme Can't be undone and could corrupt data if run twice.
1327  */
1328 function common_remove_magic_from_request()
1329 {
1330     if(get_magic_quotes_gpc()) {
1331         $_POST=array_map('stripslashes',$_POST);
1332         $_GET=array_map('stripslashes',$_GET);
1333     }
1334 }
1335
1336 function common_user_uri(&$user)
1337 {
1338     return common_local_url('userbyid', array('id' => $user->id));
1339 }
1340
1341 function common_notice_uri(&$notice)
1342 {
1343     return common_local_url('shownotice',
1344                             array('notice' => $notice->id));
1345 }
1346
1347 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1348
1349 function common_confirmation_code($bits)
1350 {
1351     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1352     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1353     $chars = ceil($bits/5);
1354     $code = '';
1355     for ($i = 0; $i < $chars; $i++) {
1356         // XXX: convert to string and back
1357         $num = hexdec(common_good_rand(1));
1358         // XXX: randomness is too precious to throw away almost
1359         // 40% of the bits we get!
1360         $code .= $codechars[$num%32];
1361     }
1362     return $code;
1363 }
1364
1365 // convert markup to HTML
1366
1367 function common_markup_to_html($c)
1368 {
1369     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1370     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1371     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1372     return Markdown($c);
1373 }
1374
1375 function common_profile_uri($profile)
1376 {
1377     if (!$profile) {
1378         return null;
1379     }
1380     $user = User::staticGet($profile->id);
1381     if ($user) {
1382         return $user->uri;
1383     }
1384
1385     $remote = Remote_profile::staticGet($profile->id);
1386     if ($remote) {
1387         return $remote->uri;
1388     }
1389     // XXX: this is a very bad profile!
1390     return null;
1391 }
1392
1393 function common_canonical_sms($sms)
1394 {
1395     // strip non-digits
1396     preg_replace('/\D/', '', $sms);
1397     return $sms;
1398 }
1399
1400 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1401 {
1402     switch ($errno) {
1403
1404      case E_ERROR:
1405      case E_COMPILE_ERROR:
1406      case E_CORE_ERROR:
1407      case E_USER_ERROR:
1408      case E_PARSE:
1409      case E_RECOVERABLE_ERROR:
1410         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1411         die();
1412         break;
1413
1414      case E_WARNING:
1415      case E_COMPILE_WARNING:
1416      case E_CORE_WARNING:
1417      case E_USER_WARNING:
1418         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1419         break;
1420
1421      case E_NOTICE:
1422      case E_USER_NOTICE:
1423         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1424         break;
1425
1426      case E_STRICT:
1427      case E_DEPRECATED:
1428      case E_USER_DEPRECATED:
1429         // XXX: config variable to log this stuff, too
1430         break;
1431
1432      default:
1433         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1434         die();
1435         break;
1436     }
1437
1438     // FIXME: show error page if we're on the Web
1439     /* Don't execute PHP internal error handler */
1440     return true;
1441 }
1442
1443 function common_session_token()
1444 {
1445     common_ensure_session();
1446     if (!array_key_exists('token', $_SESSION)) {
1447         $_SESSION['token'] = common_good_rand(64);
1448     }
1449     return $_SESSION['token'];
1450 }
1451
1452 function common_cache_key($extra)
1453 {
1454     return Cache::key($extra);
1455 }
1456
1457 function common_keyize($str)
1458 {
1459     return Cache::keyize($str);
1460 }
1461
1462 function common_memcache()
1463 {
1464     return Cache::instance();
1465 }
1466
1467 function common_license_terms($uri)
1468 {
1469     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1470         return explode('-',$matches[1]);
1471     }
1472     return array($uri);
1473 }
1474
1475 function common_compatible_license($from, $to)
1476 {
1477     $from_terms = common_license_terms($from);
1478     // public domain and cc-by are compatible with everything
1479     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1480         return true;
1481     }
1482     $to_terms = common_license_terms($to);
1483     // sa is compatible across versions. IANAL
1484     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1485         return count(array_diff($from_terms, $to_terms)) == 0;
1486     }
1487     // XXX: better compatibility check needed here!
1488     // Should at least normalise URIs
1489     return ($from == $to);
1490 }
1491
1492 /**
1493  * returns a quoted table name, if required according to config
1494  */
1495 function common_database_tablename($tablename)
1496 {
1497
1498   if(common_config('db','quote_identifiers')) {
1499       $tablename = '"'. $tablename .'"';
1500   }
1501   //table prefixes could be added here later
1502   return $tablename;
1503 }
1504
1505 /**
1506  * Shorten a URL with the current user's configured shortening service,
1507  * or ur1.ca if configured, or not at all if no shortening is set up.
1508  * Length is not considered.
1509  *
1510  * @param string $long_url
1511  * @return string may return the original URL if shortening failed
1512  *
1513  * @fixme provide a way to specify a particular shortener
1514  * @fixme provide a way to specify to use a given user's shortening preferences
1515  */
1516 function common_shorten_url($long_url)
1517 {
1518     $user = common_current_user();
1519     if (empty($user)) {
1520         // common current user does not find a user when called from the XMPP daemon
1521         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1522         $shortenerName = 'ur1.ca';
1523     } else {
1524         $shortenerName = $user->urlshorteningservice;
1525     }
1526
1527     if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1528         //URL wasn't shortened, so return the long url
1529         return $long_url;
1530     }else{
1531         //URL was shortened, so return the result
1532         return $shortenedUrl;
1533     }
1534 }
1535
1536 /**
1537  * @return mixed array($proxy, $ip) for web requests; proxy may be null
1538  *               null if not a web request
1539  *
1540  * @fixme X-Forwarded-For can be chained by multiple proxies;
1541           we should parse the list and provide a cleaner array
1542  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1543  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1544  *        use function to get exact request headers from Apache if possible.
1545  */
1546 function common_client_ip()
1547 {
1548     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1549         return null;
1550     }
1551
1552     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1553         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1554             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1555         } else {
1556             $proxy = $_SERVER['REMOTE_ADDR'];
1557         }
1558         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1559     } else {
1560         $proxy = null;
1561         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1562             $ip = $_SERVER['HTTP_CLIENT_IP'];
1563         } else {
1564             $ip = $_SERVER['REMOTE_ADDR'];
1565         }
1566     }
1567
1568     return array($proxy, $ip);
1569 }