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