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