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