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