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