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