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