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