3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
20 /* XXX: break up into separate modules (HTTP, user, files) */
22 // Show a server error
24 function common_server_error($msg, $code=500)
26 $err = new ServerErrorAction($msg, $code);
31 function common_user_error($msg, $code=400)
33 $err = new ClientErrorAction($msg, $code);
37 function common_init_locale($language=null)
40 $language = common_language();
42 putenv('LANGUAGE='.$language);
43 putenv('LANG='.$language);
44 return setlocale(LC_ALL, $language . ".utf8",
51 function common_init_language()
53 mb_internal_encoding('UTF-8');
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");
61 $language = common_language();
62 $locale_set = common_init_locale($language);
63 setlocale(LC_CTYPE, 'C');
65 // So we don't have to make people install the gettext locales
66 $path = common_config('site','locale_path');
67 bindtextdomain("statusnet", $path);
68 bind_textdomain_codeset("statusnet", "UTF-8");
69 textdomain("statusnet");
72 common_log(LOG_INFO, 'Language requested:' . $language . ' - locale could not be set. Perhaps that system locale is not installed.', __FILE__);
76 function common_timezone()
78 if (common_logged_in()) {
79 $user = common_current_user();
80 if ($user->timezone) {
81 return $user->timezone;
85 return common_config('site', 'timezone');
88 function common_language()
91 // If there is a user logged in and they've set a language preference
92 // then return that one...
93 if (_have_config() && common_logged_in()) {
94 $user = common_current_user();
95 $user_language = $user->language;
97 return $user_language;
100 // Otherwise, find the best match for the languages requested by the
102 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
103 if (!empty($httplang)) {
104 $language = client_prefered_language($httplang);
109 // Finally, if none of the above worked, use the site's default...
110 return common_config('site', 'language');
112 // salted, hashed passwords are stored in the DB
114 function common_munge_password($password, $id)
116 return md5($password . $id);
119 // check if a username exists and has matching password
120 function common_check_user($nickname, $password)
122 // NEVER allow blank passwords, even if they match the DB
123 if (mb_strlen($password) == 0) {
126 $user = User::staticGet('nickname', $nickname);
127 if (is_null($user) || $user === false) {
130 if (0 == strcmp(common_munge_password($password, $user->id),
139 // is the current user logged in?
140 function common_logged_in()
142 return (!is_null(common_current_user()));
145 function common_have_session()
147 return (0 != strcmp(session_id(), ''));
150 function common_ensure_session()
153 if (array_key_exists(session_name(), $_COOKIE)) {
154 $c = $_COOKIE[session_name()];
156 if (!common_have_session()) {
157 if (common_config('sessions', 'handle')) {
158 Session::setSaveHandler();
161 if (!isset($_SESSION['started'])) {
162 $_SESSION['started'] = time();
164 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
165 ' is set but started value is null');
171 // Three kinds of arguments:
176 // Initialize to false; set to null if none found
180 function common_set_user($user)
185 if (is_null($user) && common_have_session()) {
187 unset($_SESSION['userid']);
189 } else if (is_string($user)) {
191 $user = User::staticGet('nickname', $nickname);
192 } else if (!($user instanceof User)) {
197 common_ensure_session();
198 $_SESSION['userid'] = $user->id;
205 function common_set_cookie($key, $value, $expiration=0)
207 $path = common_config('site', 'path');
208 $server = common_config('site', 'server');
210 if ($path && ($path != '/')) {
211 $cookiepath = '/' . $path . '/';
215 return setcookie($key,
222 define('REMEMBERME', 'rememberme');
223 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
225 function common_rememberme($user=null)
228 $user = common_current_user();
230 common_debug('No current user to remember', __FILE__);
235 $rm = new Remember_me();
237 $rm->code = common_good_rand(16);
238 $rm->user_id = $user->id;
240 // Wrap the insert in some good ol' fashioned transaction code
244 $result = $rm->insert();
247 common_log_db_error($rm, 'INSERT', __FILE__);
248 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
252 $rm->query('COMMIT');
254 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
256 $cookieval = $rm->user_id . ':' . $rm->code;
258 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
260 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
265 function common_remembered_user()
270 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
276 list($id, $code) = explode(':', $packed);
278 if (!$id || !$code) {
279 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
284 $rm = Remember_me::staticGet($code);
287 common_log(LOG_WARNING, 'No such remember code: ' . $code);
292 if ($rm->user_id != $id) {
293 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
298 $user = User::staticGet($rm->user_id);
301 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
307 $result = $rm->delete();
310 common_log_db_error($rm, 'DELETE', __FILE__);
311 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
316 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
318 common_set_user($user);
319 common_real_login(false);
321 // We issue a new cookie, so they can log in
322 // automatically again after this session
324 common_rememberme($user);
329 // must be called with a valid user!
331 function common_forgetme()
333 common_set_cookie(REMEMBERME, '', 0);
336 // who is the current user?
337 function common_current_user()
341 if (!_have_config()) {
345 if ($_cur === false) {
347 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
348 common_ensure_session();
349 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
351 $_cur = User::staticGet($id);
356 // that didn't work; try to remember; will init $_cur to null on failure
357 $_cur = common_remembered_user();
360 common_debug("Got User " . $_cur->nickname);
361 common_debug("Faking session on remembered user");
362 // XXX: Is this necessary?
363 $_SESSION['userid'] = $_cur->id;
370 // Logins that are 'remembered' aren't 'real' -- they're subject to
371 // cookie-stealing. So, we don't let them do certain things. New reg,
372 // OpenID, and password logins _are_ real.
374 function common_real_login($real=true)
376 common_ensure_session();
377 $_SESSION['real_login'] = $real;
380 function common_is_real_login()
382 return common_logged_in() && $_SESSION['real_login'];
385 // get canonical version of nickname for comparison
386 function common_canonical_nickname($nickname)
388 // XXX: UTF-8 canonicalization (like combining chars)
389 return strtolower($nickname);
392 // get canonical version of email for comparison
393 function common_canonical_email($email)
395 // XXX: canonicalize UTF-8
396 // XXX: lcase the domain part
400 function common_render_content($text, $notice)
402 $r = common_render_text($text);
403 $id = $notice->profile_id;
404 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
405 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
406 $r = preg_replace('/(^|\s+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
407 $r = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
411 function common_render_text($text)
413 $r = htmlspecialchars($text);
415 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
416 $r = common_replace_urls_callback($r, 'common_linkify');
417 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
422 function common_replace_urls_callback($text, $callback, $notice_id = null) {
423 // Start off with a regex
425 '(?:^|[\s\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
428 '(?:'. //Known protocols
430 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
432 '(?:(?:mailto|aim|tel|xmpp):)'.
434 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
437 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
439 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
443 '|(?:(?: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
445 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
447 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
448 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
449 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
450 '(?: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)'.
454 '(?:\:\d+)?'. //:port
455 '(?:/[\pN\pL$\[\]\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\"@]*)?'. // /path
456 '(?:\?[\pN\pL\$\[\]\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\"@\/]*)?'. // ?query string
457 '(?:\#[\pN\pL$\[\]\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\"\@/\?\#]*)?'. // #fragment
458 ')(?<![\?\.\,\#\,])'.
461 //preg_match_all($regex,$text,$matches);
463 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
466 function callback_helper($matches, $callback, $notice_id) {
468 $left = strpos($matches[0],$url);
469 $right = $left+strlen($url);
471 $groupSymbolSets=array(
485 $cannotEndWith=array('.','?',',','#');
489 foreach($groupSymbolSets as $groupSymbolSet){
490 if(substr($url,-1)==$groupSymbolSet['right']){
491 $group_left_count = substr_count($url,$groupSymbolSet['left']);
492 $group_right_count = substr_count($url,$groupSymbolSet['right']);
493 if($group_left_count<$group_right_count){
495 $url=substr($url,0,-1);
499 if(in_array(substr($url,-1),$cannotEndWith)){
501 $url=substr($url,0,-1);
503 }while($original_url!=$url);
505 if(empty($notice_id)){
506 $result = call_user_func_array($callback,$url);
508 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
510 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
513 function curry($fn) {
514 //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
515 $args = func_get_args();
517 $id = uniqid('_partial');
518 $GLOBALS[$id] = array($fn, $args);
519 return create_function('',
520 '$args = func_get_args(); '.
521 'return call_user_func_array('.
522 '$GLOBALS["'.$id.'"][0],'.
525 '$GLOBALS["'.$id.'"][1]));');
528 function common_linkify($url) {
529 // It comes in special'd, so we unspecial it before passing to the stringifying
531 $url = htmlspecialchars_decode($url);
533 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
534 //url is an email address without the mailto: protocol
535 return XMLStringer::estring('a', array('href' => "mailto:$url", 'rel' => 'external'), $url);
538 $canon = File_redirection::_canonUrl($url);
540 $longurl_data = File_redirection::where($url);
541 if (is_array($longurl_data)) {
542 $longurl = $longurl_data['url'];
543 } elseif (is_string($longurl_data)) {
544 $longurl = $longurl_data;
546 throw new ServerException("Can't linkify url '$url'");
549 $attrs = array('href' => $canon, 'rel' => 'external');
551 $is_attachment = false;
552 $attachment_id = null;
555 // Check to see whether this is a known "attachment" URL.
557 $f = File::staticGet('url', $longurl);
560 // XXX: this writes to the database. :<
561 $f = File::processNew($longurl);
565 if ($f->isEnclosure()) {
566 $is_attachment = true;
567 $attachment_id = $f->id;
569 $foe = File_oembed::staticGet('file_id', $f->id);
571 // if it has OEmbed info, it's an attachment, too
572 $is_attachment = true;
573 $attachment_id = $f->id;
575 $thumb = File_thumbnail::staticGet('file_id', $f->id);
576 if (!empty($thumb)) {
584 if ($is_attachment) {
585 $attrs['class'] = 'attachment';
587 $attrs['class'] = 'attachment thumbnail';
589 $attrs['id'] = "attachment-{$attachment_id}";
592 return XMLStringer::estring('a', $attrs, $url);
595 function common_shorten_links($text)
597 if (mb_strlen($text) <= 140) return $text;
598 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
601 function common_xml_safe_str($str)
603 // Neutralize control codes and surrogates
604 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
607 function common_tag_link($tag)
609 $canonical = common_canonical_tag($tag);
610 $url = common_local_url('tag', array('tag' => $canonical));
611 $xs = new XMLStringer();
612 $xs->elementStart('span', 'tag');
613 $xs->element('a', array('href' => $url,
616 $xs->elementEnd('span');
617 return $xs->getString();
620 function common_canonical_tag($tag)
622 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
623 return str_replace(array('-', '_', '.'), '', $tag);
626 function common_valid_profile_tag($str)
628 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
631 function common_at_link($sender_id, $nickname)
633 $sender = Profile::staticGet($sender_id);
634 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
636 $user = User::staticGet('id', $recipient->id);
638 $url = common_local_url('userbyid', array('id' => $user->id));
640 $url = $recipient->profileurl;
642 $xs = new XMLStringer(false);
643 $attrs = array('href' => $url,
645 if (!empty($recipient->fullname)) {
646 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
648 $xs->elementStart('span', 'vcard');
649 $xs->elementStart('a', $attrs);
650 $xs->element('span', 'fn nickname', $nickname);
651 $xs->elementEnd('a');
652 $xs->elementEnd('span');
653 return $xs->getString();
659 function common_group_link($sender_id, $nickname)
661 $sender = Profile::staticGet($sender_id);
662 $group = User_group::getForNickname($nickname);
663 if ($group && $sender->isMember($group)) {
664 $attrs = array('href' => $group->permalink(),
666 if (!empty($group->fullname)) {
667 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
669 $xs = new XMLStringer();
670 $xs->elementStart('span', 'vcard');
671 $xs->elementStart('a', $attrs);
672 $xs->element('span', 'fn nickname', $nickname);
673 $xs->elementEnd('a');
674 $xs->elementEnd('span');
675 return $xs->getString();
681 function common_at_hash_link($sender_id, $tag)
683 $user = User::staticGet($sender_id);
687 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
689 $url = common_local_url('subscriptions',
690 array('nickname' => $user->nickname,
692 $xs = new XMLStringer();
693 $xs->elementStart('span', 'tag');
694 $xs->element('a', array('href' => $url,
697 $xs->elementEnd('span');
698 return $xs->getString();
704 function common_relative_profile($sender, $nickname, $dt=null)
706 // Try to find profiles this profile is subscribed to that have this nickname
707 $recipient = new Profile();
708 // XXX: use a join instead of a subquery
709 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
710 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
711 if ($recipient->find(true)) {
712 // XXX: should probably differentiate between profiles with
713 // the same name by date of most recent update
716 // Try to find profiles that listen to this profile and that have this nickname
717 $recipient = new Profile();
718 // XXX: use a join instead of a subquery
719 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
720 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
721 if ($recipient->find(true)) {
722 // XXX: should probably differentiate between profiles with
723 // the same name by date of most recent update
726 // If this is a local user, try to find a local user with that nickname.
727 $sender = User::staticGet($sender->id);
729 $recipient_user = User::staticGet('nickname', $nickname);
730 if ($recipient_user) {
731 return $recipient_user->getProfile();
734 // Otherwise, no links. @messages from local users to remote users,
735 // or from remote users to other remote users, are just
736 // outside our ability to make intelligent guesses about
740 function common_local_url($action, $args=null, $params=null, $fragment=null)
742 static $sensitive = array('login', 'register', 'passwordsettings',
743 'twittersettings', 'finishopenidlogin',
744 'finishaddopenid', 'api');
747 $path = $r->build($action, $args, $params, $fragment);
749 $ssl = in_array($action, $sensitive);
751 if (common_config('site','fancy')) {
752 $url = common_path(mb_substr($path, 1), $ssl);
754 if (mb_strpos($path, '/index.php') === 0) {
755 $url = common_path(mb_substr($path, 1), $ssl);
757 $url = common_path('index.php'.$path, $ssl);
763 function common_path($relative, $ssl=false)
765 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
767 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
768 || common_config('site', 'ssl') === 'always') {
770 if (is_string(common_config('site', 'sslserver')) &&
771 mb_strlen(common_config('site', 'sslserver')) > 0) {
772 $serverpart = common_config('site', 'sslserver');
774 $serverpart = common_config('site', 'server');
778 $serverpart = common_config('site', 'server');
781 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
784 function common_date_string($dt)
786 // XXX: do some sexy date formatting
787 // return date(DATE_RFC822, $dt);
792 if ($now < $t) { // that shouldn't happen!
793 return common_exact_date($dt);
794 } else if ($diff < 60) {
795 return _('a few seconds ago');
796 } else if ($diff < 92) {
797 return _('about a minute ago');
798 } else if ($diff < 3300) {
799 return sprintf(_('about %d minutes ago'), round($diff/60));
800 } else if ($diff < 5400) {
801 return _('about an hour ago');
802 } else if ($diff < 22 * 3600) {
803 return sprintf(_('about %d hours ago'), round($diff/3600));
804 } else if ($diff < 37 * 3600) {
805 return _('about a day ago');
806 } else if ($diff < 24 * 24 * 3600) {
807 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
808 } else if ($diff < 46 * 24 * 3600) {
809 return _('about a month ago');
810 } else if ($diff < 330 * 24 * 3600) {
811 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
812 } else if ($diff < 480 * 24 * 3600) {
813 return _('about a year ago');
815 return common_exact_date($dt);
819 function common_exact_date($dt)
825 $_utc = new DateTimeZone('UTC');
826 $_siteTz = new DateTimeZone(common_timezone());
829 $dateStr = date('d F Y H:i:s', strtotime($dt));
830 $d = new DateTime($dateStr, $_utc);
831 $d->setTimezone($_siteTz);
832 return $d->format(DATE_RFC850);
835 function common_date_w3dtf($dt)
837 $dateStr = date('d F Y H:i:s', strtotime($dt));
838 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
839 $d->setTimezone(new DateTimeZone(common_timezone()));
840 return $d->format(DATE_W3C);
843 function common_date_rfc2822($dt)
845 $dateStr = date('d F Y H:i:s', strtotime($dt));
846 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
847 $d->setTimezone(new DateTimeZone(common_timezone()));
848 return $d->format('r');
851 function common_date_iso8601($dt)
853 $dateStr = date('d F Y H:i:s', strtotime($dt));
854 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
855 $d->setTimezone(new DateTimeZone(common_timezone()));
856 return $d->format('c');
859 function common_sql_now()
861 return common_sql_date(time());
864 function common_sql_date($datetime)
866 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
869 function common_redirect($url, $code=307)
871 static $status = array(301 => "Moved Permanently",
874 307 => "Temporary Redirect");
876 header('HTTP/1.1 '.$code.' '.$status[$code]);
877 header("Location: $url");
879 $xo = new XMLOutputter();
881 '-//W3C//DTD XHTML 1.0 Strict//EN',
882 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
883 $xo->element('a', array('href' => $url), $url);
888 function common_broadcast_notice($notice, $remote=false)
890 return common_enqueue_notice($notice);
893 // Stick the notice on the queue
895 function common_enqueue_notice($notice)
897 static $localTransports = array('omb',
901 static $allTransports = array('sms');
903 $transports = $allTransports;
905 $xmpp = common_config('xmpp', 'enabled');
908 $transports[] = 'jabber';
911 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
912 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
913 $transports = array_merge($transports, $localTransports);
915 $transports[] = 'public';
919 $qm = QueueManager::get();
921 foreach ($transports as $transport)
923 $qm->enqueue($notice, $transport);
929 function common_broadcast_profile($profile)
931 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
932 require_once(INSTALLDIR.'/lib/omb.php');
933 omb_broadcast_profile($profile);
934 // XXX: Other broadcasts...?
938 function common_profile_url($nickname)
940 return common_local_url('showstream', array('nickname' => $nickname));
943 // Should make up a reasonable root URL
945 function common_root_url($ssl=false)
947 return common_path('', $ssl);
950 // returns $bytes bytes of random data as a hexadecimal string
951 // "good" here is a goal and not a guarantee
953 function common_good_rand($bytes)
955 // XXX: use random.org...?
956 if (@file_exists('/dev/urandom')) {
957 return common_urandom($bytes);
958 } else { // FIXME: this is probably not good enough
959 return common_mtrand($bytes);
963 function common_urandom($bytes)
965 $h = fopen('/dev/urandom', 'rb');
967 $src = fread($h, $bytes);
970 for ($i = 0; $i < $bytes; $i++) {
971 $enc .= sprintf("%02x", (ord($src[$i])));
976 function common_mtrand($bytes)
979 for ($i = 0; $i < $bytes; $i++) {
980 $enc .= sprintf("%02x", mt_rand(0, 255));
985 function common_set_returnto($url)
987 common_ensure_session();
988 $_SESSION['returnto'] = $url;
991 function common_get_returnto()
993 common_ensure_session();
994 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
997 function common_timestamp()
999 return date('YmdHis');
1002 function common_ensure_syslog()
1004 static $initialized = false;
1005 if (!$initialized) {
1006 openlog(common_config('syslog', 'appname'), 0,
1007 common_config('syslog', 'facility'));
1008 $initialized = true;
1012 function common_log_line($priority, $msg)
1014 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1015 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1016 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1019 function common_log($priority, $msg, $filename=null)
1021 $logfile = common_config('site', 'logfile');
1023 $log = fopen($logfile, "a");
1025 $output = common_log_line($priority, $msg);
1026 fwrite($log, $output);
1030 common_ensure_syslog();
1031 syslog($priority, $msg);
1035 function common_debug($msg, $filename=null)
1038 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1040 common_log(LOG_DEBUG, $msg);
1044 function common_log_db_error(&$object, $verb, $filename=null)
1046 $objstr = common_log_objstring($object);
1047 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1048 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1051 function common_log_objstring(&$object)
1053 if (is_null($object)) {
1056 if (!($object instanceof DB_DataObject)) {
1059 $arr = $object->toArray();
1061 foreach ($arr as $k => $v) {
1062 $fields[] = "$k='$v'";
1064 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1068 function common_valid_http_url($url)
1070 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1073 function common_valid_tag($tag)
1075 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1076 return (Validate::email($matches[1]) ||
1077 preg_match('/^([\w-\.]+)$/', $matches[1]));
1082 /* Following functions are copied from MediaWiki GlobalFunctions.php
1083 * and written by Evan Prodromou. */
1085 function common_accept_to_prefs($accept, $def = '*/*')
1087 // No arg means accept anything (per HTTP spec)
1089 return array($def => 1);
1094 $parts = explode(',', $accept);
1096 foreach($parts as $part) {
1097 // FIXME: doesn't deal with params like 'text/html; level=1'
1098 @list($value, $qpart) = explode(';', trim($part));
1100 if(!isset($qpart)) {
1102 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1103 $prefs[$value] = $match[1];
1110 function common_mime_type_match($type, $avail)
1112 if(array_key_exists($type, $avail)) {
1115 $parts = explode('/', $type);
1116 if(array_key_exists($parts[0] . '/*', $avail)) {
1117 return $parts[0] . '/*';
1118 } elseif(array_key_exists('*/*', $avail)) {
1126 function common_negotiate_type($cprefs, $sprefs)
1130 foreach(array_keys($sprefs) as $type) {
1131 $parts = explode('/', $type);
1132 if($parts[1] != '*') {
1133 $ckey = common_mime_type_match($type, $cprefs);
1135 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1140 foreach(array_keys($cprefs) as $type) {
1141 $parts = explode('/', $type);
1142 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1143 $skey = common_mime_type_match($type, $sprefs);
1145 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1151 $besttype = 'text/html';
1153 foreach(array_keys($combine) as $type) {
1154 if($combine[$type] > $bestq) {
1156 $bestq = $combine[$type];
1160 if ('text/html' === $besttype) {
1166 function common_config($main, $sub)
1169 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1172 function common_copy_args($from)
1175 $strip = get_magic_quotes_gpc();
1176 foreach ($from as $k => $v) {
1177 $to[$k] = ($strip) ? stripslashes($v) : $v;
1182 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1183 // This is used before handing a request off to OAuthRequest::from_request.
1184 function common_remove_magic_from_request()
1186 if(get_magic_quotes_gpc()) {
1187 $_POST=array_map('stripslashes',$_POST);
1188 $_GET=array_map('stripslashes',$_GET);
1192 function common_user_uri(&$user)
1194 return common_local_url('userbyid', array('id' => $user->id));
1197 function common_notice_uri(&$notice)
1199 return common_local_url('shownotice',
1200 array('notice' => $notice->id));
1203 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1205 function common_confirmation_code($bits)
1207 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1208 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1209 $chars = ceil($bits/5);
1211 for ($i = 0; $i < $chars; $i++) {
1212 // XXX: convert to string and back
1213 $num = hexdec(common_good_rand(1));
1214 // XXX: randomness is too precious to throw away almost
1215 // 40% of the bits we get!
1216 $code .= $codechars[$num%32];
1221 // convert markup to HTML
1223 function common_markup_to_html($c)
1225 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1226 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1227 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1228 return Markdown($c);
1231 function common_profile_uri($profile)
1236 $user = User::staticGet($profile->id);
1241 $remote = Remote_profile::staticGet($profile->id);
1243 return $remote->uri;
1245 // XXX: this is a very bad profile!
1249 function common_canonical_sms($sms)
1252 preg_replace('/\D/', '', $sms);
1256 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1261 case E_COMPILE_ERROR:
1265 case E_RECOVERABLE_ERROR:
1266 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1271 case E_COMPILE_WARNING:
1272 case E_CORE_WARNING:
1273 case E_USER_WARNING:
1274 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1279 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1284 case E_USER_DEPRECATED:
1285 // XXX: config variable to log this stuff, too
1289 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1294 // FIXME: show error page if we're on the Web
1295 /* Don't execute PHP internal error handler */
1299 function common_session_token()
1301 common_ensure_session();
1302 if (!array_key_exists('token', $_SESSION)) {
1303 $_SESSION['token'] = common_good_rand(64);
1305 return $_SESSION['token'];
1308 function common_cache_key($extra)
1310 $base_key = common_config('memcached', 'base');
1312 if (empty($base_key)) {
1313 $base_key = common_keyize(common_config('site', 'name'));
1316 return 'statusnet:' . $base_key . ':' . $extra;
1319 function common_keyize($str)
1321 $str = strtolower($str);
1322 $str = preg_replace('/\s/', '_', $str);
1326 function common_memcache()
1328 static $cache = null;
1329 if (!common_config('memcached', 'enabled')) {
1333 $cache = new Memcache();
1334 $servers = common_config('memcached', 'server');
1335 if (is_array($servers)) {
1336 foreach($servers as $server) {
1337 $cache->addServer($server);
1340 $cache->addServer($servers);
1347 function common_compatible_license($from, $to)
1349 // XXX: better compatibility check needed here!
1350 return ($from == $to);
1354 * returns a quoted table name, if required according to config
1356 function common_database_tablename($tablename)
1359 if(common_config('db','quote_identifiers')) {
1360 $tablename = '"'. $tablename .'"';
1362 //table prefixes could be added here later
1366 function common_shorten_url($long_url)
1368 $user = common_current_user();
1370 // common current user does not find a user when called from the XMPP daemon
1371 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1374 $svc = $user->urlshorteningservice;
1377 $curlh = curl_init();
1378 curl_setopt($curlh, CURLOPT_CONNECTTIMEOUT, 20); // # seconds to wait
1379 curl_setopt($curlh, CURLOPT_USERAGENT, 'StatusNet');
1380 curl_setopt($curlh, CURLOPT_RETURNTRANSFER, true);
1384 require_once INSTALLDIR.'/lib/Shorturl_api.php';
1385 $short_url_service = new LilUrl;
1386 $short_url = $short_url_service->shorten($long_url);
1390 $short_url_service = new TightUrl;
1391 require_once INSTALLDIR.'/lib/Shorturl_api.php';
1392 $short_url = $short_url_service->shorten($long_url);
1396 require_once INSTALLDIR.'/lib/Shorturl_api.php';
1397 $short_url_service = new PtitUrl;
1398 $short_url = $short_url_service->shorten($long_url);
1402 curl_setopt($curlh, CURLOPT_URL, 'http://bit.ly/api?method=shorten&long_url='.urlencode($long_url));
1403 $short_url = current(json_decode(curl_exec($curlh))->results)->hashUrl;
1407 curl_setopt($curlh, CURLOPT_URL, 'http://is.gd/api.php?longurl='.urlencode($long_url));
1408 $short_url = curl_exec($curlh);
1411 curl_setopt($curlh, CURLOPT_URL, 'http://snipr.com/site/snip?r=simple&link='.urlencode($long_url));
1412 $short_url = curl_exec($curlh);
1414 case 'metamark.net':
1415 curl_setopt($curlh, CURLOPT_URL, 'http://metamark.net/api/rest/simple?long_url='.urlencode($long_url));
1416 $short_url = curl_exec($curlh);
1419 curl_setopt($curlh, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.urlencode($long_url));
1420 $short_url = curl_exec($curlh);
1431 function common_client_ip()
1433 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1437 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1438 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1439 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1441 $proxy = $_SERVER['REMOTE_ADDR'];
1443 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1446 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1447 $ip = $_SERVER['HTTP_CLIENT_IP'];
1449 $ip = $_SERVER['REMOTE_ADDR'];
1453 return array($proxy, $ip);