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