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