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