]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
Merge branch '0.9.x' of git://gitorious.org/statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, user, files) */
21
22 // Show a server error
23
24 function common_server_error($msg, $code=500)
25 {
26     $err = new ServerErrorAction($msg, $code);
27     $err->showPage();
28 }
29
30 // Show a user error
31 function common_user_error($msg, $code=400)
32 {
33     $err = new ClientErrorAction($msg, $code);
34     $err->showPage();
35 }
36
37 function common_init_locale($language=null)
38 {
39     if(!$language) {
40         $language = common_language();
41     }
42     putenv('LANGUAGE='.$language);
43     putenv('LANG='.$language);
44     return setlocale(LC_ALL, $language . ".utf8",
45                      $language . ".UTF8",
46                      $language . ".utf-8",
47                      $language . ".UTF-8",
48                      $language);
49 }
50
51 function common_init_language()
52 {
53     mb_internal_encoding('UTF-8');
54
55     // gettext seems very picky... We first need to setlocale()
56     // to a locale which _does_ exist on the system, and _then_
57     // we can set in another locale that may not be set up
58     // (say, ga_ES for Galego/Galician) it seems to take it.
59     common_init_locale("en_US");
60
61     $language = common_language();
62     $locale_set = common_init_locale($language);
63     setlocale(LC_CTYPE, 'C');
64     // So we do not have to make people install the gettext locales
65     $path = common_config('site','locale_path');
66     bindtextdomain("statusnet", $path);
67     bind_textdomain_codeset("statusnet", "UTF-8");
68     textdomain("statusnet");
69
70     if(!$locale_set) {
71         common_log(LOG_INFO, 'Language requested:' . $language . ' - locale could not be set. Perhaps that system locale is not installed.', __FILE__);
72     }
73 }
74
75 function common_timezone()
76 {
77     if (common_logged_in()) {
78         $user = common_current_user();
79         if ($user->timezone) {
80             return $user->timezone;
81         }
82     }
83
84     return common_config('site', 'timezone');
85 }
86
87 function common_language()
88 {
89
90     // If there is a user logged in and they've set a language preference
91     // then return that one...
92     if (_have_config() && common_logged_in()) {
93         $user = common_current_user();
94         $user_language = $user->language;
95         if ($user_language)
96           return $user_language;
97     }
98
99     // Otherwise, find the best match for the languages requested by the
100     // user's browser...
101     $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
102     if (!empty($httplang)) {
103         $language = client_prefered_language($httplang);
104         if ($language)
105           return $language;
106     }
107
108     // Finally, if none of the above worked, use the site's default...
109     return common_config('site', 'language');
110 }
111 // salted, hashed passwords are stored in the DB
112
113 function common_munge_password($password, $id)
114 {
115     return md5($password . $id);
116 }
117
118 // check if a username exists and has matching password
119
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         syslog($priority, $msg);
1062     }
1063 }
1064
1065 function common_debug($msg, $filename=null)
1066 {
1067     if ($filename) {
1068         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1069     } else {
1070         common_log(LOG_DEBUG, $msg);
1071     }
1072 }
1073
1074 function common_log_db_error(&$object, $verb, $filename=null)
1075 {
1076     $objstr = common_log_objstring($object);
1077     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1078     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1079 }
1080
1081 function common_log_objstring(&$object)
1082 {
1083     if (is_null($object)) {
1084         return "null";
1085     }
1086     if (!($object instanceof DB_DataObject)) {
1087         return "(unknown)";
1088     }
1089     $arr = $object->toArray();
1090     $fields = array();
1091     foreach ($arr as $k => $v) {
1092         if (is_object($v)) {
1093             $fields[] = "$k='".get_class($v)."'";
1094         } else {
1095             $fields[] = "$k='$v'";
1096         }
1097     }
1098     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1099     return $objstring;
1100 }
1101
1102 function common_valid_http_url($url)
1103 {
1104     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1105 }
1106
1107 function common_valid_tag($tag)
1108 {
1109     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1110         return (Validate::email($matches[1]) ||
1111                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1112     }
1113     return false;
1114 }
1115
1116 /* Following functions are copied from MediaWiki GlobalFunctions.php
1117  * and written by Evan Prodromou. */
1118
1119 function common_accept_to_prefs($accept, $def = '*/*')
1120 {
1121     // No arg means accept anything (per HTTP spec)
1122     if(!$accept) {
1123         return array($def => 1);
1124     }
1125
1126     $prefs = array();
1127
1128     $parts = explode(',', $accept);
1129
1130     foreach($parts as $part) {
1131         // FIXME: doesn't deal with params like 'text/html; level=1'
1132         @list($value, $qpart) = explode(';', trim($part));
1133         $match = array();
1134         if(!isset($qpart)) {
1135             $prefs[$value] = 1;
1136         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1137             $prefs[$value] = $match[1];
1138         }
1139     }
1140
1141     return $prefs;
1142 }
1143
1144 function common_mime_type_match($type, $avail)
1145 {
1146     if(array_key_exists($type, $avail)) {
1147         return $type;
1148     } else {
1149         $parts = explode('/', $type);
1150         if(array_key_exists($parts[0] . '/*', $avail)) {
1151             return $parts[0] . '/*';
1152         } elseif(array_key_exists('*/*', $avail)) {
1153             return '*/*';
1154         } else {
1155             return null;
1156         }
1157     }
1158 }
1159
1160 function common_negotiate_type($cprefs, $sprefs)
1161 {
1162     $combine = array();
1163
1164     foreach(array_keys($sprefs) as $type) {
1165         $parts = explode('/', $type);
1166         if($parts[1] != '*') {
1167             $ckey = common_mime_type_match($type, $cprefs);
1168             if($ckey) {
1169                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1170             }
1171         }
1172     }
1173
1174     foreach(array_keys($cprefs) as $type) {
1175         $parts = explode('/', $type);
1176         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1177             $skey = common_mime_type_match($type, $sprefs);
1178             if($skey) {
1179                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1180             }
1181         }
1182     }
1183
1184     $bestq = 0;
1185     $besttype = 'text/html';
1186
1187     foreach(array_keys($combine) as $type) {
1188         if($combine[$type] > $bestq) {
1189             $besttype = $type;
1190             $bestq = $combine[$type];
1191         }
1192     }
1193
1194     if ('text/html' === $besttype) {
1195         return "text/html; charset=utf-8";
1196     }
1197     return $besttype;
1198 }
1199
1200 function common_config($main, $sub)
1201 {
1202     global $config;
1203     return (array_key_exists($main, $config) &&
1204             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1205 }
1206
1207 function common_copy_args($from)
1208 {
1209     $to = array();
1210     $strip = get_magic_quotes_gpc();
1211     foreach ($from as $k => $v) {
1212         $to[$k] = ($strip) ? stripslashes($v) : $v;
1213     }
1214     return $to;
1215 }
1216
1217 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1218 // This is used before handing a request off to OAuthRequest::from_request.
1219 function common_remove_magic_from_request()
1220 {
1221     if(get_magic_quotes_gpc()) {
1222         $_POST=array_map('stripslashes',$_POST);
1223         $_GET=array_map('stripslashes',$_GET);
1224     }
1225 }
1226
1227 function common_user_uri(&$user)
1228 {
1229     return common_local_url('userbyid', array('id' => $user->id));
1230 }
1231
1232 function common_notice_uri(&$notice)
1233 {
1234     return common_local_url('shownotice',
1235                             array('notice' => $notice->id));
1236 }
1237
1238 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1239
1240 function common_confirmation_code($bits)
1241 {
1242     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1243     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1244     $chars = ceil($bits/5);
1245     $code = '';
1246     for ($i = 0; $i < $chars; $i++) {
1247         // XXX: convert to string and back
1248         $num = hexdec(common_good_rand(1));
1249         // XXX: randomness is too precious to throw away almost
1250         // 40% of the bits we get!
1251         $code .= $codechars[$num%32];
1252     }
1253     return $code;
1254 }
1255
1256 // convert markup to HTML
1257
1258 function common_markup_to_html($c)
1259 {
1260     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1261     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1262     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1263     return Markdown($c);
1264 }
1265
1266 function common_profile_uri($profile)
1267 {
1268     if (!$profile) {
1269         return null;
1270     }
1271     $user = User::staticGet($profile->id);
1272     if ($user) {
1273         return $user->uri;
1274     }
1275
1276     $remote = Remote_profile::staticGet($profile->id);
1277     if ($remote) {
1278         return $remote->uri;
1279     }
1280     // XXX: this is a very bad profile!
1281     return null;
1282 }
1283
1284 function common_canonical_sms($sms)
1285 {
1286     // strip non-digits
1287     preg_replace('/\D/', '', $sms);
1288     return $sms;
1289 }
1290
1291 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1292 {
1293     switch ($errno) {
1294
1295      case E_ERROR:
1296      case E_COMPILE_ERROR:
1297      case E_CORE_ERROR:
1298      case E_USER_ERROR:
1299      case E_PARSE:
1300      case E_RECOVERABLE_ERROR:
1301         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1302         die();
1303         break;
1304
1305      case E_WARNING:
1306      case E_COMPILE_WARNING:
1307      case E_CORE_WARNING:
1308      case E_USER_WARNING:
1309         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1310         break;
1311
1312      case E_NOTICE:
1313      case E_USER_NOTICE:
1314         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1315         break;
1316
1317      case E_STRICT:
1318      case E_DEPRECATED:
1319      case E_USER_DEPRECATED:
1320         // XXX: config variable to log this stuff, too
1321         break;
1322
1323      default:
1324         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1325         die();
1326         break;
1327     }
1328
1329     // FIXME: show error page if we're on the Web
1330     /* Don't execute PHP internal error handler */
1331     return true;
1332 }
1333
1334 function common_session_token()
1335 {
1336     common_ensure_session();
1337     if (!array_key_exists('token', $_SESSION)) {
1338         $_SESSION['token'] = common_good_rand(64);
1339     }
1340     return $_SESSION['token'];
1341 }
1342
1343 function common_cache_key($extra)
1344 {
1345     $base_key = common_config('memcached', 'base');
1346
1347     if (empty($base_key)) {
1348         $base_key = common_keyize(common_config('site', 'name'));
1349     }
1350
1351     return 'statusnet:' . $base_key . ':' . $extra;
1352 }
1353
1354 function common_keyize($str)
1355 {
1356     $str = strtolower($str);
1357     $str = preg_replace('/\s/', '_', $str);
1358     return $str;
1359 }
1360
1361 function common_memcache()
1362 {
1363     static $cache = null;
1364     if (!common_config('memcached', 'enabled')) {
1365         return null;
1366     } else {
1367         if (!$cache) {
1368             $cache = new Memcache();
1369             $servers = common_config('memcached', 'server');
1370             if (is_array($servers)) {
1371                 foreach($servers as $server) {
1372                     $cache->addServer($server);
1373                 }
1374             } else {
1375                 $cache->addServer($servers);
1376             }
1377         }
1378         return $cache;
1379     }
1380 }
1381
1382 function common_license_terms($uri)
1383 {
1384     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1385         return explode('-',$matches[1]);
1386     }
1387     return array($uri);
1388 }
1389
1390 function common_compatible_license($from, $to)
1391 {
1392     $from_terms = common_license_terms($from);
1393     // public domain and cc-by are compatible with everything
1394     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1395         return true;
1396     }
1397     $to_terms = common_license_terms($to);
1398     // sa is compatible across versions. IANAL
1399     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1400         return count(array_diff($from_terms, $to_terms)) == 0;
1401     }
1402     // XXX: better compatibility check needed here!
1403     // Should at least normalise URIs
1404     return ($from == $to);
1405 }
1406
1407 /**
1408  * returns a quoted table name, if required according to config
1409  */
1410 function common_database_tablename($tablename)
1411 {
1412
1413   if(common_config('db','quote_identifiers')) {
1414       $tablename = '"'. $tablename .'"';
1415   }
1416   //table prefixes could be added here later
1417   return $tablename;
1418 }
1419
1420 function common_shorten_url($long_url)
1421 {
1422     $user = common_current_user();
1423     if (empty($user)) {
1424         // common current user does not find a user when called from the XMPP daemon
1425         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1426         $svc = 'ur1.ca';
1427     } else {
1428         $svc = $user->urlshorteningservice;
1429     }
1430     global $_shorteners;
1431     if (!isset($_shorteners[$svc])) {
1432         //the user selected service doesn't exist, so default to ur1.ca
1433         $svc = 'ur1.ca';
1434     }
1435     if (!isset($_shorteners[$svc])) {
1436         // no shortener plugins installed.
1437         return $long_url;
1438     }
1439
1440     $reflectionObj = new ReflectionClass($_shorteners[$svc]['callInfo'][0]);
1441     $short_url_service = $reflectionObj->newInstanceArgs($_shorteners[$svc]['callInfo'][1]);
1442     $short_url = $short_url_service->shorten($long_url);
1443
1444     return $short_url;
1445 }
1446
1447 function common_client_ip()
1448 {
1449     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1450         return null;
1451     }
1452
1453     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1454         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1455             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1456         } else {
1457             $proxy = $_SERVER['REMOTE_ADDR'];
1458         }
1459         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1460     } else {
1461         $proxy = null;
1462         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1463             $ip = $_SERVER['HTTP_CLIENT_IP'];
1464         } else {
1465             $ip = $_SERVER['REMOTE_ADDR'];
1466         }
1467     }
1468
1469     return array($proxy, $ip);
1470 }