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