]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
If user is sharing their location (based on profile setting), then
[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 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
535     // lambda implementation in a separate file; PHP 5.2 won't parse it.
536     require_once INSTALLDIR . "/lib/curry.php";
537 } else {
538     function curry($fn) {
539         $args = func_get_args();
540         array_shift($args);
541         $id = uniqid('_partial');
542         $GLOBALS[$id] = array($fn, $args);
543         return create_function('',
544                                '$args = func_get_args(); '.
545                                'return call_user_func_array('.
546                                '$GLOBALS["'.$id.'"][0],'.
547                                'array_merge('.
548                                '$args,'.
549                                '$GLOBALS["'.$id.'"][1]));');
550     }
551 }
552
553 function common_linkify($url) {
554     // It comes in special'd, so we unspecial it before passing to the stringifying
555     // functions
556     $url = htmlspecialchars_decode($url);
557
558    if(strpos($url, '@') !== false && strpos($url, ':') === false) {
559        //url is an email address without the mailto: protocol
560        $canon = "mailto:$url";
561        $longurl = "mailto:$url";
562    }else{
563
564         $canon = File_redirection::_canonUrl($url);
565
566         $longurl_data = File_redirection::where($canon);
567         if (is_array($longurl_data)) {
568             $longurl = $longurl_data['url'];
569         } elseif (is_string($longurl_data)) {
570             $longurl = $longurl_data;
571         } else {
572             throw new ServerException("Can't linkify url '$url'");
573         }
574     }
575     $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
576
577     $is_attachment = false;
578     $attachment_id = null;
579     $has_thumb = false;
580
581     // Check to see whether this is a known "attachment" URL.
582
583     $f = File::staticGet('url', $longurl);
584
585     if (empty($f)) {
586         // XXX: this writes to the database. :<
587         $f = File::processNew($longurl);
588     }
589
590     if (!empty($f)) {
591         if ($f->isEnclosure()) {
592             $is_attachment = true;
593             $attachment_id = $f->id;
594         } else {
595             $foe = File_oembed::staticGet('file_id', $f->id);
596             if (!empty($foe)) {
597                 // if it has OEmbed info, it's an attachment, too
598                 $is_attachment = true;
599                 $attachment_id = $f->id;
600
601                 $thumb = File_thumbnail::staticGet('file_id', $f->id);
602                 if (!empty($thumb)) {
603                     $has_thumb = true;
604                 }
605             }
606         }
607     }
608
609     // Add clippy
610     if ($is_attachment) {
611         $attrs['class'] = 'attachment';
612         if ($has_thumb) {
613             $attrs['class'] = 'attachment thumbnail';
614         }
615         $attrs['id'] = "attachment-{$attachment_id}";
616     }
617
618     return XMLStringer::estring('a', $attrs, $url);
619 }
620
621 function common_shorten_links($text)
622 {
623     $maxLength = Notice::maxContent();
624     if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
625     return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
626 }
627
628 function common_xml_safe_str($str)
629 {
630     // Neutralize control codes and surrogates
631         return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
632 }
633
634 function common_tag_link($tag)
635 {
636     $canonical = common_canonical_tag($tag);
637     $url = common_local_url('tag', array('tag' => $canonical));
638     $xs = new XMLStringer();
639     $xs->elementStart('span', 'tag');
640     $xs->element('a', array('href' => $url,
641                             'rel' => 'tag'),
642                  $tag);
643     $xs->elementEnd('span');
644     return $xs->getString();
645 }
646
647 function common_canonical_tag($tag)
648 {
649   $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
650   return str_replace(array('-', '_', '.'), '', $tag);
651 }
652
653 function common_valid_profile_tag($str)
654 {
655     return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
656 }
657
658 function common_at_link($sender_id, $nickname)
659 {
660     $sender = Profile::staticGet($sender_id);
661     $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
662     if ($recipient) {
663         $user = User::staticGet('id', $recipient->id);
664         if ($user) {
665             $url = common_local_url('userbyid', array('id' => $user->id));
666         } else {
667             $url = $recipient->profileurl;
668         }
669         $xs = new XMLStringer(false);
670         $attrs = array('href' => $url,
671                        'class' => 'url');
672         if (!empty($recipient->fullname)) {
673             $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
674         }
675         $xs->elementStart('span', 'vcard');
676         $xs->elementStart('a', $attrs);
677         $xs->element('span', 'fn nickname', $nickname);
678         $xs->elementEnd('a');
679         $xs->elementEnd('span');
680         return $xs->getString();
681     } else {
682         return $nickname;
683     }
684 }
685
686 function common_group_link($sender_id, $nickname)
687 {
688     $sender = Profile::staticGet($sender_id);
689     $group = User_group::getForNickname($nickname);
690     if ($group && $sender->isMember($group)) {
691         $attrs = array('href' => $group->permalink(),
692                        'class' => 'url');
693         if (!empty($group->fullname)) {
694             $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
695         }
696         $xs = new XMLStringer();
697         $xs->elementStart('span', 'vcard');
698         $xs->elementStart('a', $attrs);
699         $xs->element('span', 'fn nickname', $nickname);
700         $xs->elementEnd('a');
701         $xs->elementEnd('span');
702         return $xs->getString();
703     } else {
704         return $nickname;
705     }
706 }
707
708 function common_at_hash_link($sender_id, $tag)
709 {
710     $user = User::staticGet($sender_id);
711     if (!$user) {
712         return $tag;
713     }
714     $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
715     if ($tagged) {
716         $url = common_local_url('subscriptions',
717                                 array('nickname' => $user->nickname,
718                                       'tag' => $tag));
719         $xs = new XMLStringer();
720         $xs->elementStart('span', 'tag');
721         $xs->element('a', array('href' => $url,
722                                 'rel' => $tag),
723                      $tag);
724         $xs->elementEnd('span');
725         return $xs->getString();
726     } else {
727         return $tag;
728     }
729 }
730
731 function common_relative_profile($sender, $nickname, $dt=null)
732 {
733     // Try to find profiles this profile is subscribed to that have this nickname
734     $recipient = new Profile();
735     // XXX: use a join instead of a subquery
736     $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
737     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
738     if ($recipient->find(true)) {
739         // XXX: should probably differentiate between profiles with
740         // the same name by date of most recent update
741         return $recipient;
742     }
743     // Try to find profiles that listen to this profile and that have this nickname
744     $recipient = new Profile();
745     // XXX: use a join instead of a subquery
746     $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
747     $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
748     if ($recipient->find(true)) {
749         // XXX: should probably differentiate between profiles with
750         // the same name by date of most recent update
751         return $recipient;
752     }
753     // If this is a local user, try to find a local user with that nickname.
754     $sender = User::staticGet($sender->id);
755     if ($sender) {
756         $recipient_user = User::staticGet('nickname', $nickname);
757         if ($recipient_user) {
758             return $recipient_user->getProfile();
759         }
760     }
761     // Otherwise, no links. @messages from local users to remote users,
762     // or from remote users to other remote users, are just
763     // outside our ability to make intelligent guesses about
764     return null;
765 }
766
767 function common_local_url($action, $args=null, $params=null, $fragment=null)
768 {
769     $r = Router::get();
770     $path = $r->build($action, $args, $params, $fragment);
771
772     $ssl = common_is_sensitive($action);
773
774     if (common_config('site','fancy')) {
775         $url = common_path(mb_substr($path, 1), $ssl);
776     } else {
777         if (mb_strpos($path, '/index.php') === 0) {
778             $url = common_path(mb_substr($path, 1), $ssl);
779         } else {
780             $url = common_path('index.php'.$path, $ssl);
781         }
782     }
783     return $url;
784 }
785
786 function common_is_sensitive($action)
787 {
788     static $sensitive = array('login', 'register', 'passwordsettings',
789                               'twittersettings', 'api');
790     $ssl = null;
791
792     if (Event::handle('SensitiveAction', array($action, &$ssl))) {
793         $ssl = in_array($action, $sensitive);
794     }
795
796     return $ssl;
797 }
798
799 function common_path($relative, $ssl=false)
800 {
801     $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
802
803     if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
804         || common_config('site', 'ssl') === 'always') {
805         $proto = 'https';
806         if (is_string(common_config('site', 'sslserver')) &&
807             mb_strlen(common_config('site', 'sslserver')) > 0) {
808             $serverpart = common_config('site', 'sslserver');
809         } else if (common_config('site', 'server')) {
810             $serverpart = common_config('site', 'server');
811         } else {
812             common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
813         }
814     } else {
815         $proto = 'http';
816         if (common_config('site', 'server')) {
817             $serverpart = common_config('site', 'server');
818         } else {
819             common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
820         }
821     }
822
823     return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
824 }
825
826 function common_date_string($dt)
827 {
828     // XXX: do some sexy date formatting
829     // return date(DATE_RFC822, $dt);
830     $t = strtotime($dt);
831     $now = time();
832     $diff = $now - $t;
833
834     if ($now < $t) { // that shouldn't happen!
835         return common_exact_date($dt);
836     } else if ($diff < 60) {
837         return _('a few seconds ago');
838     } else if ($diff < 92) {
839         return _('about a minute ago');
840     } else if ($diff < 3300) {
841         return sprintf(_('about %d minutes ago'), round($diff/60));
842     } else if ($diff < 5400) {
843         return _('about an hour ago');
844     } else if ($diff < 22 * 3600) {
845         return sprintf(_('about %d hours ago'), round($diff/3600));
846     } else if ($diff < 37 * 3600) {
847         return _('about a day ago');
848     } else if ($diff < 24 * 24 * 3600) {
849         return sprintf(_('about %d days ago'), round($diff/(24*3600)));
850     } else if ($diff < 46 * 24 * 3600) {
851         return _('about a month ago');
852     } else if ($diff < 330 * 24 * 3600) {
853         return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
854     } else if ($diff < 480 * 24 * 3600) {
855         return _('about a year ago');
856     } else {
857         return common_exact_date($dt);
858     }
859 }
860
861 function common_exact_date($dt)
862 {
863     static $_utc;
864     static $_siteTz;
865
866     if (!$_utc) {
867         $_utc = new DateTimeZone('UTC');
868         $_siteTz = new DateTimeZone(common_timezone());
869     }
870
871     $dateStr = date('d F Y H:i:s', strtotime($dt));
872     $d = new DateTime($dateStr, $_utc);
873     $d->setTimezone($_siteTz);
874     return $d->format(DATE_RFC850);
875 }
876
877 function common_date_w3dtf($dt)
878 {
879     $dateStr = date('d F Y H:i:s', strtotime($dt));
880     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
881     $d->setTimezone(new DateTimeZone(common_timezone()));
882     return $d->format(DATE_W3C);
883 }
884
885 function common_date_rfc2822($dt)
886 {
887     $dateStr = date('d F Y H:i:s', strtotime($dt));
888     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
889     $d->setTimezone(new DateTimeZone(common_timezone()));
890     return $d->format('r');
891 }
892
893 function common_date_iso8601($dt)
894 {
895     $dateStr = date('d F Y H:i:s', strtotime($dt));
896     $d = new DateTime($dateStr, new DateTimeZone('UTC'));
897     $d->setTimezone(new DateTimeZone(common_timezone()));
898     return $d->format('c');
899 }
900
901 function common_sql_now()
902 {
903     return common_sql_date(time());
904 }
905
906 function common_sql_date($datetime)
907 {
908     return strftime('%Y-%m-%d %H:%M:%S', $datetime);
909 }
910
911 function common_redirect($url, $code=307)
912 {
913     static $status = array(301 => "Moved Permanently",
914                            302 => "Found",
915                            303 => "See Other",
916                            307 => "Temporary Redirect");
917
918     header('HTTP/1.1 '.$code.' '.$status[$code]);
919     header("Location: $url");
920
921     $xo = new XMLOutputter();
922     $xo->startXML('a',
923                   '-//W3C//DTD XHTML 1.0 Strict//EN',
924                   'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
925     $xo->element('a', array('href' => $url), $url);
926     $xo->endXML();
927     exit;
928 }
929
930 function common_broadcast_notice($notice, $remote=false)
931 {
932     return common_enqueue_notice($notice);
933 }
934
935 // Stick the notice on the queue
936
937 function common_enqueue_notice($notice)
938 {
939     static $localTransports = array('omb',
940                                     'ping');
941
942     static $allTransports = array('sms', 'plugin');
943
944     $transports = $allTransports;
945
946     $xmpp = common_config('xmpp', 'enabled');
947
948     if ($xmpp) {
949         $transports[] = 'jabber';
950     }
951
952     if ($notice->is_local == Notice::LOCAL_PUBLIC ||
953         $notice->is_local == Notice::LOCAL_NONPUBLIC) {
954         $transports = array_merge($transports, $localTransports);
955         if ($xmpp) {
956             $transports[] = 'public';
957         }
958     }
959
960     if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
961
962         $qm = QueueManager::get();
963
964         foreach ($transports as $transport)
965         {
966             $qm->enqueue($notice, $transport);
967         }
968
969         Event::handle('EndEnqueueNotice', array($notice, $transports));
970     }
971
972     return true;
973 }
974
975 function common_broadcast_profile($profile)
976 {
977     // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
978     require_once(INSTALLDIR.'/lib/omb.php');
979     omb_broadcast_profile($profile);
980     // XXX: Other broadcasts...?
981     return true;
982 }
983
984 function common_profile_url($nickname)
985 {
986     return common_local_url('showstream', array('nickname' => $nickname));
987 }
988
989 // Should make up a reasonable root URL
990
991 function common_root_url($ssl=false)
992 {
993     return common_path('', $ssl);
994 }
995
996 // returns $bytes bytes of random data as a hexadecimal string
997 // "good" here is a goal and not a guarantee
998
999 function common_good_rand($bytes)
1000 {
1001     // XXX: use random.org...?
1002     if (@file_exists('/dev/urandom')) {
1003         return common_urandom($bytes);
1004     } else { // FIXME: this is probably not good enough
1005         return common_mtrand($bytes);
1006     }
1007 }
1008
1009 function common_urandom($bytes)
1010 {
1011     $h = fopen('/dev/urandom', 'rb');
1012     // should not block
1013     $src = fread($h, $bytes);
1014     fclose($h);
1015     $enc = '';
1016     for ($i = 0; $i < $bytes; $i++) {
1017         $enc .= sprintf("%02x", (ord($src[$i])));
1018     }
1019     return $enc;
1020 }
1021
1022 function common_mtrand($bytes)
1023 {
1024     $enc = '';
1025     for ($i = 0; $i < $bytes; $i++) {
1026         $enc .= sprintf("%02x", mt_rand(0, 255));
1027     }
1028     return $enc;
1029 }
1030
1031 function common_set_returnto($url)
1032 {
1033     common_ensure_session();
1034     $_SESSION['returnto'] = $url;
1035 }
1036
1037 function common_get_returnto()
1038 {
1039     common_ensure_session();
1040     return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1041 }
1042
1043 function common_timestamp()
1044 {
1045     return date('YmdHis');
1046 }
1047
1048 function common_ensure_syslog()
1049 {
1050     static $initialized = false;
1051     if (!$initialized) {
1052         openlog(common_config('syslog', 'appname'), 0,
1053             common_config('syslog', 'facility'));
1054         $initialized = true;
1055     }
1056 }
1057
1058 function common_log_line($priority, $msg)
1059 {
1060     static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1061                                       'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1062     return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1063 }
1064
1065 function common_request_id()
1066 {
1067     $pid = getmypid();
1068     if (php_sapi_name() == 'cli') {
1069         return $pid;
1070     } else {
1071         static $req_id = null;
1072         if (!isset($req_id)) {
1073             $req_id = substr(md5(mt_rand()), 0, 8);
1074         }
1075         if (isset($_SERVER['REQUEST_URI'])) {
1076             $url = $_SERVER['REQUEST_URI'];
1077         }
1078         $method = $_SERVER['REQUEST_METHOD'];
1079         return "$pid.$req_id $method $url";
1080     }
1081 }
1082
1083 function common_log($priority, $msg, $filename=null)
1084 {
1085     if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1086         $msg = '[' . common_request_id() . '] ' . $msg;
1087         $logfile = common_config('site', 'logfile');
1088         if ($logfile) {
1089             $log = fopen($logfile, "a");
1090             if ($log) {
1091                 $output = common_log_line($priority, $msg);
1092                 fwrite($log, $output);
1093                 fclose($log);
1094             }
1095         } else {
1096             common_ensure_syslog();
1097             syslog($priority, $msg);
1098         }
1099         Event::handle('EndLog', array($priority, $msg, $filename));
1100     }
1101 }
1102
1103 function common_debug($msg, $filename=null)
1104 {
1105     if ($filename) {
1106         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1107     } else {
1108         common_log(LOG_DEBUG, $msg);
1109     }
1110 }
1111
1112 function common_log_db_error(&$object, $verb, $filename=null)
1113 {
1114     $objstr = common_log_objstring($object);
1115     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1116     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1117 }
1118
1119 function common_log_objstring(&$object)
1120 {
1121     if (is_null($object)) {
1122         return "null";
1123     }
1124     if (!($object instanceof DB_DataObject)) {
1125         return "(unknown)";
1126     }
1127     $arr = $object->toArray();
1128     $fields = array();
1129     foreach ($arr as $k => $v) {
1130         if (is_object($v)) {
1131             $fields[] = "$k='".get_class($v)."'";
1132         } else {
1133             $fields[] = "$k='$v'";
1134         }
1135     }
1136     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1137     return $objstring;
1138 }
1139
1140 function common_valid_http_url($url)
1141 {
1142     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1143 }
1144
1145 function common_valid_tag($tag)
1146 {
1147     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1148         return (Validate::email($matches[1]) ||
1149                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1150     }
1151     return false;
1152 }
1153
1154 /* Following functions are copied from MediaWiki GlobalFunctions.php
1155  * and written by Evan Prodromou. */
1156
1157 function common_accept_to_prefs($accept, $def = '*/*')
1158 {
1159     // No arg means accept anything (per HTTP spec)
1160     if(!$accept) {
1161         return array($def => 1);
1162     }
1163
1164     $prefs = array();
1165
1166     $parts = explode(',', $accept);
1167
1168     foreach($parts as $part) {
1169         // FIXME: doesn't deal with params like 'text/html; level=1'
1170         @list($value, $qpart) = explode(';', trim($part));
1171         $match = array();
1172         if(!isset($qpart)) {
1173             $prefs[$value] = 1;
1174         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1175             $prefs[$value] = $match[1];
1176         }
1177     }
1178
1179     return $prefs;
1180 }
1181
1182 function common_mime_type_match($type, $avail)
1183 {
1184     if(array_key_exists($type, $avail)) {
1185         return $type;
1186     } else {
1187         $parts = explode('/', $type);
1188         if(array_key_exists($parts[0] . '/*', $avail)) {
1189             return $parts[0] . '/*';
1190         } elseif(array_key_exists('*/*', $avail)) {
1191             return '*/*';
1192         } else {
1193             return null;
1194         }
1195     }
1196 }
1197
1198 function common_negotiate_type($cprefs, $sprefs)
1199 {
1200     $combine = array();
1201
1202     foreach(array_keys($sprefs) as $type) {
1203         $parts = explode('/', $type);
1204         if($parts[1] != '*') {
1205             $ckey = common_mime_type_match($type, $cprefs);
1206             if($ckey) {
1207                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1208             }
1209         }
1210     }
1211
1212     foreach(array_keys($cprefs) as $type) {
1213         $parts = explode('/', $type);
1214         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1215             $skey = common_mime_type_match($type, $sprefs);
1216             if($skey) {
1217                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1218             }
1219         }
1220     }
1221
1222     $bestq = 0;
1223     $besttype = 'text/html';
1224
1225     foreach(array_keys($combine) as $type) {
1226         if($combine[$type] > $bestq) {
1227             $besttype = $type;
1228             $bestq = $combine[$type];
1229         }
1230     }
1231
1232     if ('text/html' === $besttype) {
1233         return "text/html; charset=utf-8";
1234     }
1235     return $besttype;
1236 }
1237
1238 function common_config($main, $sub)
1239 {
1240     global $config;
1241     return (array_key_exists($main, $config) &&
1242             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1243 }
1244
1245 function common_copy_args($from)
1246 {
1247     $to = array();
1248     $strip = get_magic_quotes_gpc();
1249     foreach ($from as $k => $v) {
1250         $to[$k] = ($strip) ? stripslashes($v) : $v;
1251     }
1252     return $to;
1253 }
1254
1255 /**
1256  * Neutralise the evil effects of magic_quotes_gpc in the current request.
1257  * This is used before handing a request off to OAuthRequest::from_request.
1258  * @fixme Doesn't consider vars other than _POST and _GET?
1259  * @fixme Can't be undone and could corrupt data if run twice.
1260  */
1261 function common_remove_magic_from_request()
1262 {
1263     if(get_magic_quotes_gpc()) {
1264         $_POST=array_map('stripslashes',$_POST);
1265         $_GET=array_map('stripslashes',$_GET);
1266     }
1267 }
1268
1269 function common_user_uri(&$user)
1270 {
1271     return common_local_url('userbyid', array('id' => $user->id));
1272 }
1273
1274 function common_notice_uri(&$notice)
1275 {
1276     return common_local_url('shownotice',
1277                             array('notice' => $notice->id));
1278 }
1279
1280 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1281
1282 function common_confirmation_code($bits)
1283 {
1284     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1285     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1286     $chars = ceil($bits/5);
1287     $code = '';
1288     for ($i = 0; $i < $chars; $i++) {
1289         // XXX: convert to string and back
1290         $num = hexdec(common_good_rand(1));
1291         // XXX: randomness is too precious to throw away almost
1292         // 40% of the bits we get!
1293         $code .= $codechars[$num%32];
1294     }
1295     return $code;
1296 }
1297
1298 // convert markup to HTML
1299
1300 function common_markup_to_html($c)
1301 {
1302     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1303     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1304     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1305     return Markdown($c);
1306 }
1307
1308 function common_profile_uri($profile)
1309 {
1310     if (!$profile) {
1311         return null;
1312     }
1313     $user = User::staticGet($profile->id);
1314     if ($user) {
1315         return $user->uri;
1316     }
1317
1318     $remote = Remote_profile::staticGet($profile->id);
1319     if ($remote) {
1320         return $remote->uri;
1321     }
1322     // XXX: this is a very bad profile!
1323     return null;
1324 }
1325
1326 function common_canonical_sms($sms)
1327 {
1328     // strip non-digits
1329     preg_replace('/\D/', '', $sms);
1330     return $sms;
1331 }
1332
1333 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1334 {
1335     switch ($errno) {
1336
1337      case E_ERROR:
1338      case E_COMPILE_ERROR:
1339      case E_CORE_ERROR:
1340      case E_USER_ERROR:
1341      case E_PARSE:
1342      case E_RECOVERABLE_ERROR:
1343         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1344         die();
1345         break;
1346
1347      case E_WARNING:
1348      case E_COMPILE_WARNING:
1349      case E_CORE_WARNING:
1350      case E_USER_WARNING:
1351         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1352         break;
1353
1354      case E_NOTICE:
1355      case E_USER_NOTICE:
1356         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1357         break;
1358
1359      case E_STRICT:
1360      case E_DEPRECATED:
1361      case E_USER_DEPRECATED:
1362         // XXX: config variable to log this stuff, too
1363         break;
1364
1365      default:
1366         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1367         die();
1368         break;
1369     }
1370
1371     // FIXME: show error page if we're on the Web
1372     /* Don't execute PHP internal error handler */
1373     return true;
1374 }
1375
1376 function common_session_token()
1377 {
1378     common_ensure_session();
1379     if (!array_key_exists('token', $_SESSION)) {
1380         $_SESSION['token'] = common_good_rand(64);
1381     }
1382     return $_SESSION['token'];
1383 }
1384
1385 function common_cache_key($extra)
1386 {
1387     $base_key = common_config('memcached', 'base');
1388
1389     if (empty($base_key)) {
1390         $base_key = common_keyize(common_config('site', 'name'));
1391     }
1392
1393     return 'statusnet:' . $base_key . ':' . $extra;
1394 }
1395
1396 function common_keyize($str)
1397 {
1398     $str = strtolower($str);
1399     $str = preg_replace('/\s/', '_', $str);
1400     return $str;
1401 }
1402
1403 function common_memcache()
1404 {
1405     static $cache = null;
1406     if (!common_config('memcached', 'enabled')) {
1407         return null;
1408     } else {
1409         if (!$cache) {
1410             $cache = new Memcache();
1411             $servers = common_config('memcached', 'server');
1412             if (is_array($servers)) {
1413                 foreach($servers as $server) {
1414                     $cache->addServer($server);
1415                 }
1416             } else {
1417                 $cache->addServer($servers);
1418             }
1419         }
1420         return $cache;
1421     }
1422 }
1423
1424 function common_license_terms($uri)
1425 {
1426     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1427         return explode('-',$matches[1]);
1428     }
1429     return array($uri);
1430 }
1431
1432 function common_compatible_license($from, $to)
1433 {
1434     $from_terms = common_license_terms($from);
1435     // public domain and cc-by are compatible with everything
1436     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1437         return true;
1438     }
1439     $to_terms = common_license_terms($to);
1440     // sa is compatible across versions. IANAL
1441     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1442         return count(array_diff($from_terms, $to_terms)) == 0;
1443     }
1444     // XXX: better compatibility check needed here!
1445     // Should at least normalise URIs
1446     return ($from == $to);
1447 }
1448
1449 /**
1450  * returns a quoted table name, if required according to config
1451  */
1452 function common_database_tablename($tablename)
1453 {
1454
1455   if(common_config('db','quote_identifiers')) {
1456       $tablename = '"'. $tablename .'"';
1457   }
1458   //table prefixes could be added here later
1459   return $tablename;
1460 }
1461
1462 /**
1463  * Shorten a URL with the current user's configured shortening service,
1464  * or ur1.ca if configured, or not at all if no shortening is set up.
1465  * Length is not considered.
1466  *
1467  * @param string $long_url
1468  * @return string may return the original URL if shortening failed
1469  *
1470  * @fixme provide a way to specify a particular shortener
1471  * @fixme provide a way to specify to use a given user's shortening preferences
1472  */
1473 function common_shorten_url($long_url)
1474 {
1475     $user = common_current_user();
1476     if (empty($user)) {
1477         // common current user does not find a user when called from the XMPP daemon
1478         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1479         $shortenerName = 'ur1.ca';
1480     } else {
1481         $shortenerName = $user->urlshorteningservice;
1482     }
1483
1484     if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1485         //URL wasn't shortened, so return the long url
1486         return $long_url;
1487     }else{
1488         //URL was shortened, so return the result
1489         return $shortenedUrl;
1490     }
1491 }
1492
1493 /**
1494  * @return mixed array($proxy, $ip) for web requests; proxy may be null
1495  *               null if not a web request
1496  *
1497  * @fixme X-Forwarded-For can be chained by multiple proxies;
1498           we should parse the list and provide a cleaner array
1499  * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1500  * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1501  *        use function to get exact request headers from Apache if possible.
1502  */
1503 function common_client_ip()
1504 {
1505     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1506         return null;
1507     }
1508
1509     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1510         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1511             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1512         } else {
1513             $proxy = $_SERVER['REMOTE_ADDR'];
1514         }
1515         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1516     } else {
1517         $proxy = null;
1518         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1519             $ip = $_SERVER['HTTP_CLIENT_IP'];
1520         } else {
1521             $ip = $_SERVER['REMOTE_ADDR'];
1522         }
1523     }
1524
1525     return array($proxy, $ip);
1526 }