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