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