]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
99a0a1db30fee5c9fd73f38ced66699445e7e57b
[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 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_request_id()
1054 {
1055     $pid = getmypid();
1056     if (php_sapi_name() == 'cli') {
1057         return $pid;
1058     } else {
1059         static $req_id = null;
1060         if (!isset($req_id)) {
1061             $req_id = substr(md5(mt_rand()), 0, 8);
1062         }
1063         if (isset($_SERVER['REQUEST_URI'])) {
1064             $url = $_SERVER['REQUEST_URI'];
1065         }
1066         $method = $_SERVER['REQUEST_METHOD'];
1067         return "$pid.$req_id $method $url";
1068     }
1069 }
1070
1071 function common_log($priority, $msg, $filename=null)
1072 {
1073     $msg = '[' . common_request_id() . '] ' . $msg;
1074     $logfile = common_config('site', 'logfile');
1075     if ($logfile) {
1076         $log = fopen($logfile, "a");
1077         if ($log) {
1078             $output = common_log_line($priority, $msg);
1079             fwrite($log, $output);
1080             fclose($log);
1081         }
1082     } else {
1083         common_ensure_syslog();
1084         syslog($priority, $msg);
1085     }
1086 }
1087
1088 function common_debug($msg, $filename=null)
1089 {
1090     if ($filename) {
1091         common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1092     } else {
1093         common_log(LOG_DEBUG, $msg);
1094     }
1095 }
1096
1097 function common_log_db_error(&$object, $verb, $filename=null)
1098 {
1099     $objstr = common_log_objstring($object);
1100     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1101     common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1102 }
1103
1104 function common_log_objstring(&$object)
1105 {
1106     if (is_null($object)) {
1107         return "null";
1108     }
1109     if (!($object instanceof DB_DataObject)) {
1110         return "(unknown)";
1111     }
1112     $arr = $object->toArray();
1113     $fields = array();
1114     foreach ($arr as $k => $v) {
1115         if (is_object($v)) {
1116             $fields[] = "$k='".get_class($v)."'";
1117         } else {
1118             $fields[] = "$k='$v'";
1119         }
1120     }
1121     $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1122     return $objstring;
1123 }
1124
1125 function common_valid_http_url($url)
1126 {
1127     return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1128 }
1129
1130 function common_valid_tag($tag)
1131 {
1132     if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1133         return (Validate::email($matches[1]) ||
1134                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1135     }
1136     return false;
1137 }
1138
1139 /* Following functions are copied from MediaWiki GlobalFunctions.php
1140  * and written by Evan Prodromou. */
1141
1142 function common_accept_to_prefs($accept, $def = '*/*')
1143 {
1144     // No arg means accept anything (per HTTP spec)
1145     if(!$accept) {
1146         return array($def => 1);
1147     }
1148
1149     $prefs = array();
1150
1151     $parts = explode(',', $accept);
1152
1153     foreach($parts as $part) {
1154         // FIXME: doesn't deal with params like 'text/html; level=1'
1155         @list($value, $qpart) = explode(';', trim($part));
1156         $match = array();
1157         if(!isset($qpart)) {
1158             $prefs[$value] = 1;
1159         } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1160             $prefs[$value] = $match[1];
1161         }
1162     }
1163
1164     return $prefs;
1165 }
1166
1167 function common_mime_type_match($type, $avail)
1168 {
1169     if(array_key_exists($type, $avail)) {
1170         return $type;
1171     } else {
1172         $parts = explode('/', $type);
1173         if(array_key_exists($parts[0] . '/*', $avail)) {
1174             return $parts[0] . '/*';
1175         } elseif(array_key_exists('*/*', $avail)) {
1176             return '*/*';
1177         } else {
1178             return null;
1179         }
1180     }
1181 }
1182
1183 function common_negotiate_type($cprefs, $sprefs)
1184 {
1185     $combine = array();
1186
1187     foreach(array_keys($sprefs) as $type) {
1188         $parts = explode('/', $type);
1189         if($parts[1] != '*') {
1190             $ckey = common_mime_type_match($type, $cprefs);
1191             if($ckey) {
1192                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1193             }
1194         }
1195     }
1196
1197     foreach(array_keys($cprefs) as $type) {
1198         $parts = explode('/', $type);
1199         if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1200             $skey = common_mime_type_match($type, $sprefs);
1201             if($skey) {
1202                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1203             }
1204         }
1205     }
1206
1207     $bestq = 0;
1208     $besttype = 'text/html';
1209
1210     foreach(array_keys($combine) as $type) {
1211         if($combine[$type] > $bestq) {
1212             $besttype = $type;
1213             $bestq = $combine[$type];
1214         }
1215     }
1216
1217     if ('text/html' === $besttype) {
1218         return "text/html; charset=utf-8";
1219     }
1220     return $besttype;
1221 }
1222
1223 function common_config($main, $sub)
1224 {
1225     global $config;
1226     return (array_key_exists($main, $config) &&
1227             array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1228 }
1229
1230 function common_copy_args($from)
1231 {
1232     $to = array();
1233     $strip = get_magic_quotes_gpc();
1234     foreach ($from as $k => $v) {
1235         $to[$k] = ($strip) ? stripslashes($v) : $v;
1236     }
1237     return $to;
1238 }
1239
1240 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1241 // This is used before handing a request off to OAuthRequest::from_request.
1242 function common_remove_magic_from_request()
1243 {
1244     if(get_magic_quotes_gpc()) {
1245         $_POST=array_map('stripslashes',$_POST);
1246         $_GET=array_map('stripslashes',$_GET);
1247     }
1248 }
1249
1250 function common_user_uri(&$user)
1251 {
1252     return common_local_url('userbyid', array('id' => $user->id));
1253 }
1254
1255 function common_notice_uri(&$notice)
1256 {
1257     return common_local_url('shownotice',
1258                             array('notice' => $notice->id));
1259 }
1260
1261 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1262
1263 function common_confirmation_code($bits)
1264 {
1265     // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1266     static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1267     $chars = ceil($bits/5);
1268     $code = '';
1269     for ($i = 0; $i < $chars; $i++) {
1270         // XXX: convert to string and back
1271         $num = hexdec(common_good_rand(1));
1272         // XXX: randomness is too precious to throw away almost
1273         // 40% of the bits we get!
1274         $code .= $codechars[$num%32];
1275     }
1276     return $code;
1277 }
1278
1279 // convert markup to HTML
1280
1281 function common_markup_to_html($c)
1282 {
1283     $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1284     $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1285     $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1286     return Markdown($c);
1287 }
1288
1289 function common_profile_uri($profile)
1290 {
1291     if (!$profile) {
1292         return null;
1293     }
1294     $user = User::staticGet($profile->id);
1295     if ($user) {
1296         return $user->uri;
1297     }
1298
1299     $remote = Remote_profile::staticGet($profile->id);
1300     if ($remote) {
1301         return $remote->uri;
1302     }
1303     // XXX: this is a very bad profile!
1304     return null;
1305 }
1306
1307 function common_canonical_sms($sms)
1308 {
1309     // strip non-digits
1310     preg_replace('/\D/', '', $sms);
1311     return $sms;
1312 }
1313
1314 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1315 {
1316     switch ($errno) {
1317
1318      case E_ERROR:
1319      case E_COMPILE_ERROR:
1320      case E_CORE_ERROR:
1321      case E_USER_ERROR:
1322      case E_PARSE:
1323      case E_RECOVERABLE_ERROR:
1324         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1325         die();
1326         break;
1327
1328      case E_WARNING:
1329      case E_COMPILE_WARNING:
1330      case E_CORE_WARNING:
1331      case E_USER_WARNING:
1332         common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1333         break;
1334
1335      case E_NOTICE:
1336      case E_USER_NOTICE:
1337         common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1338         break;
1339
1340      case E_STRICT:
1341      case E_DEPRECATED:
1342      case E_USER_DEPRECATED:
1343         // XXX: config variable to log this stuff, too
1344         break;
1345
1346      default:
1347         common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1348         die();
1349         break;
1350     }
1351
1352     // FIXME: show error page if we're on the Web
1353     /* Don't execute PHP internal error handler */
1354     return true;
1355 }
1356
1357 function common_session_token()
1358 {
1359     common_ensure_session();
1360     if (!array_key_exists('token', $_SESSION)) {
1361         $_SESSION['token'] = common_good_rand(64);
1362     }
1363     return $_SESSION['token'];
1364 }
1365
1366 function common_cache_key($extra)
1367 {
1368     $base_key = common_config('memcached', 'base');
1369
1370     if (empty($base_key)) {
1371         $base_key = common_keyize(common_config('site', 'name'));
1372     }
1373
1374     return 'statusnet:' . $base_key . ':' . $extra;
1375 }
1376
1377 function common_keyize($str)
1378 {
1379     $str = strtolower($str);
1380     $str = preg_replace('/\s/', '_', $str);
1381     return $str;
1382 }
1383
1384 function common_memcache()
1385 {
1386     static $cache = null;
1387     if (!common_config('memcached', 'enabled')) {
1388         return null;
1389     } else {
1390         if (!$cache) {
1391             $cache = new Memcache();
1392             $servers = common_config('memcached', 'server');
1393             if (is_array($servers)) {
1394                 foreach($servers as $server) {
1395                     $cache->addServer($server);
1396                 }
1397             } else {
1398                 $cache->addServer($servers);
1399             }
1400         }
1401         return $cache;
1402     }
1403 }
1404
1405 function common_license_terms($uri)
1406 {
1407     if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1408         return explode('-',$matches[1]);
1409     }
1410     return array($uri);
1411 }
1412
1413 function common_compatible_license($from, $to)
1414 {
1415     $from_terms = common_license_terms($from);
1416     // public domain and cc-by are compatible with everything
1417     if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1418         return true;
1419     }
1420     $to_terms = common_license_terms($to);
1421     // sa is compatible across versions. IANAL
1422     if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1423         return count(array_diff($from_terms, $to_terms)) == 0;
1424     }
1425     // XXX: better compatibility check needed here!
1426     // Should at least normalise URIs
1427     return ($from == $to);
1428 }
1429
1430 /**
1431  * returns a quoted table name, if required according to config
1432  */
1433 function common_database_tablename($tablename)
1434 {
1435
1436   if(common_config('db','quote_identifiers')) {
1437       $tablename = '"'. $tablename .'"';
1438   }
1439   //table prefixes could be added here later
1440   return $tablename;
1441 }
1442
1443 function common_shorten_url($long_url)
1444 {
1445     $user = common_current_user();
1446     if (empty($user)) {
1447         // common current user does not find a user when called from the XMPP daemon
1448         // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1449         $shortenerName = 'ur1.ca';
1450     } else {
1451         $shortenerName = $user->urlshorteningservice;
1452     }
1453
1454     if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1455         //URL wasn't shortened, so return the long url
1456         return $long_url;
1457     }else{
1458         //URL was shortened, so return the result
1459         return $shortenedUrl;
1460     }
1461 }
1462
1463 function common_client_ip()
1464 {
1465     if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1466         return null;
1467     }
1468
1469     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1470         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1471             $proxy = $_SERVER['HTTP_CLIENT_IP'];
1472         } else {
1473             $proxy = $_SERVER['REMOTE_ADDR'];
1474         }
1475         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1476     } else {
1477         $proxy = null;
1478         if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1479             $ip = $_SERVER['HTTP_CLIENT_IP'];
1480         } else {
1481             $ip = $_SERVER['REMOTE_ADDR'];
1482         }
1483     }
1484
1485     return array($proxy, $ip);
1486 }