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');
64 // So we do not have to make people install the gettext locales
65 $path = common_config('site','locale_path');
66 bindtextdomain("statusnet", $path);
67 bind_textdomain_codeset("statusnet", "UTF-8");
68 textdomain("statusnet");
71 common_log(LOG_INFO, 'Language requested:' . $language . ' - locale could not be set. Perhaps that system locale is not installed.', __FILE__);
75 function common_timezone()
77 if (common_logged_in()) {
78 $user = common_current_user();
79 if ($user->timezone) {
80 return $user->timezone;
84 return common_config('site', 'timezone');
87 function common_language()
90 // If there is a user logged in and they've set a language preference
91 // then return that one...
92 if (_have_config() && common_logged_in()) {
93 $user = common_current_user();
94 $user_language = $user->language;
96 return $user_language;
99 // Otherwise, find the best match for the languages requested by the
101 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
102 if (!empty($httplang)) {
103 $language = client_prefered_language($httplang);
108 // Finally, if none of the above worked, use the site's default...
109 return common_config('site', 'language');
111 // salted, hashed passwords are stored in the DB
113 function common_munge_password($password, $id)
115 return md5($password . $id);
118 // check if a username exists and has matching password
120 function common_check_user($nickname, $password)
122 $authenticatedUser = false;
124 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
125 $user = User::staticGet('nickname', $nickname);
127 if (!empty($password)) { // never allow login with blank password
128 if (0 == strcmp(common_munge_password($password, $user->id),
130 //internal checking passed
131 $authenticatedUser =& $user;
135 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
138 return $authenticatedUser;
141 // is the current user logged in?
142 function common_logged_in()
144 return (!is_null(common_current_user()));
147 function common_have_session()
149 return (0 != strcmp(session_id(), ''));
152 function common_ensure_session()
155 if (array_key_exists(session_name(), $_COOKIE)) {
156 $c = $_COOKIE[session_name()];
158 if (!common_have_session()) {
159 if (common_config('sessions', 'handle')) {
160 Session::setSaveHandler();
163 if (!isset($_SESSION['started'])) {
164 $_SESSION['started'] = time();
166 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
167 ' is set but started value is null');
173 // Three kinds of arguments:
178 // Initialize to false; set to null if none found
182 function common_set_user($user)
187 if (is_null($user) && common_have_session()) {
189 unset($_SESSION['userid']);
191 } else if (is_string($user)) {
193 $user = User::staticGet('nickname', $nickname);
194 } else if (!($user instanceof User)) {
199 if (Event::handle('StartSetUser', array(&$user))) {
201 common_ensure_session();
202 $_SESSION['userid'] = $user->id;
204 Event::handle('EndSetUser', array($user));
212 function common_set_cookie($key, $value, $expiration=0)
214 $path = common_config('site', 'path');
215 $server = common_config('site', 'server');
217 if ($path && ($path != '/')) {
218 $cookiepath = '/' . $path . '/';
222 return setcookie($key,
229 define('REMEMBERME', 'rememberme');
230 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
232 function common_rememberme($user=null)
235 $user = common_current_user();
237 common_debug('No current user to remember', __FILE__);
242 $rm = new Remember_me();
244 $rm->code = common_good_rand(16);
245 $rm->user_id = $user->id;
247 // Wrap the insert in some good ol' fashioned transaction code
251 $result = $rm->insert();
254 common_log_db_error($rm, 'INSERT', __FILE__);
255 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
259 $rm->query('COMMIT');
261 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
263 $cookieval = $rm->user_id . ':' . $rm->code;
265 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
267 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
272 function common_remembered_user()
277 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
283 list($id, $code) = explode(':', $packed);
285 if (!$id || !$code) {
286 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
291 $rm = Remember_me::staticGet($code);
294 common_log(LOG_WARNING, 'No such remember code: ' . $code);
299 if ($rm->user_id != $id) {
300 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
305 $user = User::staticGet($rm->user_id);
308 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
314 $result = $rm->delete();
317 common_log_db_error($rm, 'DELETE', __FILE__);
318 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
323 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
325 common_set_user($user);
326 common_real_login(false);
328 // We issue a new cookie, so they can log in
329 // automatically again after this session
331 common_rememberme($user);
336 // must be called with a valid user!
338 function common_forgetme()
340 common_set_cookie(REMEMBERME, '', 0);
343 // who is the current user?
344 function common_current_user()
348 if (!_have_config()) {
352 if ($_cur === false) {
354 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
355 common_ensure_session();
356 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
358 $user = User::staticGet($id);
366 // that didn't work; try to remember; will init $_cur to null on failure
367 $_cur = common_remembered_user();
370 common_debug("Got User " . $_cur->nickname);
371 common_debug("Faking session on remembered user");
372 // XXX: Is this necessary?
373 $_SESSION['userid'] = $_cur->id;
380 // Logins that are 'remembered' aren't 'real' -- they're subject to
381 // cookie-stealing. So, we don't let them do certain things. New reg,
382 // OpenID, and password logins _are_ real.
384 function common_real_login($real=true)
386 common_ensure_session();
387 $_SESSION['real_login'] = $real;
390 function common_is_real_login()
392 return common_logged_in() && $_SESSION['real_login'];
395 // get canonical version of nickname for comparison
396 function common_canonical_nickname($nickname)
398 // XXX: UTF-8 canonicalization (like combining chars)
399 return strtolower($nickname);
402 // get canonical version of email for comparison
403 function common_canonical_email($email)
405 // XXX: canonicalize UTF-8
406 // XXX: lcase the domain part
410 function common_render_content($text, $notice)
412 $r = common_render_text($text);
413 $id = $notice->profile_id;
414 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
415 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
416 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
417 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
421 function common_render_text($text)
423 $r = htmlspecialchars($text);
425 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
426 $r = common_replace_urls_callback($r, 'common_linkify');
427 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
432 function common_replace_urls_callback($text, $callback, $notice_id = null) {
433 // Start off with a regex
435 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
438 '(?:'. //Known protocols
440 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
442 '(?:(?:mailto|aim|tel|xmpp):)'.
444 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
447 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
449 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
453 '|(?:(?: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
455 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
457 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
458 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
459 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
460 '(?: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)'.
464 '(?:\:\d+)?'. //:port
465 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
466 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
467 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
468 ')(?<![\?\.\,\#\,])'.
471 //preg_match_all($regex,$text,$matches);
473 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
476 function callback_helper($matches, $callback, $notice_id) {
478 $left = strpos($matches[0],$url);
479 $right = $left+strlen($url);
481 $groupSymbolSets=array(
499 $cannotEndWith=array('.','?',',','#');
503 foreach($groupSymbolSets as $groupSymbolSet){
504 if(substr($url,-1)==$groupSymbolSet['right']){
505 $group_left_count = substr_count($url,$groupSymbolSet['left']);
506 $group_right_count = substr_count($url,$groupSymbolSet['right']);
507 if($group_left_count<$group_right_count){
509 $url=substr($url,0,-1);
513 if(in_array(substr($url,-1),$cannotEndWith)){
515 $url=substr($url,0,-1);
517 }while($original_url!=$url);
519 if(empty($notice_id)){
520 $result = call_user_func_array($callback, array($url));
522 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
524 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
527 function curry($fn) {
528 //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
529 $args = func_get_args();
531 $id = uniqid('_partial');
532 $GLOBALS[$id] = array($fn, $args);
533 return create_function('',
534 '$args = func_get_args(); '.
535 'return call_user_func_array('.
536 '$GLOBALS["'.$id.'"][0],'.
539 '$GLOBALS["'.$id.'"][1]));');
542 function common_linkify($url) {
543 // It comes in special'd, so we unspecial it before passing to the stringifying
545 $url = htmlspecialchars_decode($url);
547 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
548 //url is an email address without the mailto: protocol
549 $canon = "mailto:$url";
550 $longurl = "mailto:$url";
553 $canon = File_redirection::_canonUrl($url);
555 $longurl_data = File_redirection::where($canon);
556 if (is_array($longurl_data)) {
557 $longurl = $longurl_data['url'];
558 } elseif (is_string($longurl_data)) {
559 $longurl = $longurl_data;
561 throw new ServerException("Can't linkify url '$url'");
564 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
566 $is_attachment = false;
567 $attachment_id = null;
570 // Check to see whether this is a known "attachment" URL.
572 $f = File::staticGet('url', $longurl);
575 // XXX: this writes to the database. :<
576 $f = File::processNew($longurl);
580 if ($f->isEnclosure()) {
581 $is_attachment = true;
582 $attachment_id = $f->id;
584 $foe = File_oembed::staticGet('file_id', $f->id);
586 // if it has OEmbed info, it's an attachment, too
587 $is_attachment = true;
588 $attachment_id = $f->id;
590 $thumb = File_thumbnail::staticGet('file_id', $f->id);
591 if (!empty($thumb)) {
599 if ($is_attachment) {
600 $attrs['class'] = 'attachment';
602 $attrs['class'] = 'attachment thumbnail';
604 $attrs['id'] = "attachment-{$attachment_id}";
607 return XMLStringer::estring('a', $attrs, $url);
610 function common_shorten_links($text)
612 $maxLength = Notice::maxContent();
613 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
614 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
617 function common_xml_safe_str($str)
619 // Neutralize control codes and surrogates
620 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
623 function common_tag_link($tag)
625 $canonical = common_canonical_tag($tag);
626 $url = common_local_url('tag', array('tag' => $canonical));
627 $xs = new XMLStringer();
628 $xs->elementStart('span', 'tag');
629 $xs->element('a', array('href' => $url,
632 $xs->elementEnd('span');
633 return $xs->getString();
636 function common_canonical_tag($tag)
638 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
639 return str_replace(array('-', '_', '.'), '', $tag);
642 function common_valid_profile_tag($str)
644 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
647 function common_at_link($sender_id, $nickname)
649 $sender = Profile::staticGet($sender_id);
650 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
652 $user = User::staticGet('id', $recipient->id);
654 $url = common_local_url('userbyid', array('id' => $user->id));
656 $url = $recipient->profileurl;
658 $xs = new XMLStringer(false);
659 $attrs = array('href' => $url,
661 if (!empty($recipient->fullname)) {
662 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
664 $xs->elementStart('span', 'vcard');
665 $xs->elementStart('a', $attrs);
666 $xs->element('span', 'fn nickname', $nickname);
667 $xs->elementEnd('a');
668 $xs->elementEnd('span');
669 return $xs->getString();
675 function common_group_link($sender_id, $nickname)
677 $sender = Profile::staticGet($sender_id);
678 $group = User_group::getForNickname($nickname);
679 if ($group && $sender->isMember($group)) {
680 $attrs = array('href' => $group->permalink(),
682 if (!empty($group->fullname)) {
683 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
685 $xs = new XMLStringer();
686 $xs->elementStart('span', 'vcard');
687 $xs->elementStart('a', $attrs);
688 $xs->element('span', 'fn nickname', $nickname);
689 $xs->elementEnd('a');
690 $xs->elementEnd('span');
691 return $xs->getString();
697 function common_at_hash_link($sender_id, $tag)
699 $user = User::staticGet($sender_id);
703 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
705 $url = common_local_url('subscriptions',
706 array('nickname' => $user->nickname,
708 $xs = new XMLStringer();
709 $xs->elementStart('span', 'tag');
710 $xs->element('a', array('href' => $url,
713 $xs->elementEnd('span');
714 return $xs->getString();
720 function common_relative_profile($sender, $nickname, $dt=null)
722 // Try to find profiles this profile is subscribed to that have this nickname
723 $recipient = new Profile();
724 // XXX: use a join instead of a subquery
725 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
726 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
727 if ($recipient->find(true)) {
728 // XXX: should probably differentiate between profiles with
729 // the same name by date of most recent update
732 // Try to find profiles that listen to this profile and that have this nickname
733 $recipient = new Profile();
734 // XXX: use a join instead of a subquery
735 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
736 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
737 if ($recipient->find(true)) {
738 // XXX: should probably differentiate between profiles with
739 // the same name by date of most recent update
742 // If this is a local user, try to find a local user with that nickname.
743 $sender = User::staticGet($sender->id);
745 $recipient_user = User::staticGet('nickname', $nickname);
746 if ($recipient_user) {
747 return $recipient_user->getProfile();
750 // Otherwise, no links. @messages from local users to remote users,
751 // or from remote users to other remote users, are just
752 // outside our ability to make intelligent guesses about
756 function common_local_url($action, $args=null, $params=null, $fragment=null)
759 $path = $r->build($action, $args, $params, $fragment);
761 $ssl = common_is_sensitive($action);
763 if (common_config('site','fancy')) {
764 $url = common_path(mb_substr($path, 1), $ssl);
766 if (mb_strpos($path, '/index.php') === 0) {
767 $url = common_path(mb_substr($path, 1), $ssl);
769 $url = common_path('index.php'.$path, $ssl);
775 function common_is_sensitive($action)
777 static $sensitive = array('login', 'register', 'passwordsettings',
778 'twittersettings', 'api');
781 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
782 $ssl = in_array($action, $sensitive);
788 function common_path($relative, $ssl=false)
790 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
792 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
793 || common_config('site', 'ssl') === 'always') {
795 if (is_string(common_config('site', 'sslserver')) &&
796 mb_strlen(common_config('site', 'sslserver')) > 0) {
797 $serverpart = common_config('site', 'sslserver');
798 } else if (common_config('site', 'server')) {
799 $serverpart = common_config('site', 'server');
801 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
805 if (common_config('site', 'server')) {
806 $serverpart = common_config('site', 'server');
808 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
812 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
815 function common_date_string($dt)
817 // XXX: do some sexy date formatting
818 // return date(DATE_RFC822, $dt);
823 if ($now < $t) { // that shouldn't happen!
824 return common_exact_date($dt);
825 } else if ($diff < 60) {
826 return _('a few seconds ago');
827 } else if ($diff < 92) {
828 return _('about a minute ago');
829 } else if ($diff < 3300) {
830 return sprintf(_('about %d minutes ago'), round($diff/60));
831 } else if ($diff < 5400) {
832 return _('about an hour ago');
833 } else if ($diff < 22 * 3600) {
834 return sprintf(_('about %d hours ago'), round($diff/3600));
835 } else if ($diff < 37 * 3600) {
836 return _('about a day ago');
837 } else if ($diff < 24 * 24 * 3600) {
838 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
839 } else if ($diff < 46 * 24 * 3600) {
840 return _('about a month ago');
841 } else if ($diff < 330 * 24 * 3600) {
842 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
843 } else if ($diff < 480 * 24 * 3600) {
844 return _('about a year ago');
846 return common_exact_date($dt);
850 function common_exact_date($dt)
856 $_utc = new DateTimeZone('UTC');
857 $_siteTz = new DateTimeZone(common_timezone());
860 $dateStr = date('d F Y H:i:s', strtotime($dt));
861 $d = new DateTime($dateStr, $_utc);
862 $d->setTimezone($_siteTz);
863 return $d->format(DATE_RFC850);
866 function common_date_w3dtf($dt)
868 $dateStr = date('d F Y H:i:s', strtotime($dt));
869 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
870 $d->setTimezone(new DateTimeZone(common_timezone()));
871 return $d->format(DATE_W3C);
874 function common_date_rfc2822($dt)
876 $dateStr = date('d F Y H:i:s', strtotime($dt));
877 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
878 $d->setTimezone(new DateTimeZone(common_timezone()));
879 return $d->format('r');
882 function common_date_iso8601($dt)
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('c');
890 function common_sql_now()
892 return common_sql_date(time());
895 function common_sql_date($datetime)
897 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
900 function common_redirect($url, $code=307)
902 static $status = array(301 => "Moved Permanently",
905 307 => "Temporary Redirect");
907 header('HTTP/1.1 '.$code.' '.$status[$code]);
908 header("Location: $url");
910 $xo = new XMLOutputter();
912 '-//W3C//DTD XHTML 1.0 Strict//EN',
913 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
914 $xo->element('a', array('href' => $url), $url);
919 function common_broadcast_notice($notice, $remote=false)
921 return common_enqueue_notice($notice);
924 // Stick the notice on the queue
926 function common_enqueue_notice($notice)
928 static $localTransports = array('omb',
931 static $allTransports = array('sms', 'plugin');
933 $transports = $allTransports;
935 $xmpp = common_config('xmpp', 'enabled');
938 $transports[] = 'jabber';
941 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
942 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
943 $transports = array_merge($transports, $localTransports);
945 $transports[] = 'public';
949 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
951 $qm = QueueManager::get();
953 foreach ($transports as $transport)
955 $qm->enqueue($notice, $transport);
958 Event::handle('EndEnqueueNotice', array($notice, $transports));
964 function common_broadcast_profile($profile)
966 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
967 require_once(INSTALLDIR.'/lib/omb.php');
968 omb_broadcast_profile($profile);
969 // XXX: Other broadcasts...?
973 function common_profile_url($nickname)
975 return common_local_url('showstream', array('nickname' => $nickname));
978 // Should make up a reasonable root URL
980 function common_root_url($ssl=false)
982 return common_path('', $ssl);
985 // returns $bytes bytes of random data as a hexadecimal string
986 // "good" here is a goal and not a guarantee
988 function common_good_rand($bytes)
990 // XXX: use random.org...?
991 if (@file_exists('/dev/urandom')) {
992 return common_urandom($bytes);
993 } else { // FIXME: this is probably not good enough
994 return common_mtrand($bytes);
998 function common_urandom($bytes)
1000 $h = fopen('/dev/urandom', 'rb');
1002 $src = fread($h, $bytes);
1005 for ($i = 0; $i < $bytes; $i++) {
1006 $enc .= sprintf("%02x", (ord($src[$i])));
1011 function common_mtrand($bytes)
1014 for ($i = 0; $i < $bytes; $i++) {
1015 $enc .= sprintf("%02x", mt_rand(0, 255));
1020 function common_set_returnto($url)
1022 common_ensure_session();
1023 $_SESSION['returnto'] = $url;
1026 function common_get_returnto()
1028 common_ensure_session();
1029 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1032 function common_timestamp()
1034 return date('YmdHis');
1037 function common_ensure_syslog()
1039 static $initialized = false;
1040 if (!$initialized) {
1041 openlog(common_config('syslog', 'appname'), 0,
1042 common_config('syslog', 'facility'));
1043 $initialized = true;
1047 function common_log_line($priority, $msg)
1049 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1050 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1051 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1054 function common_log($priority, $msg, $filename=null)
1056 $logfile = common_config('site', 'logfile');
1058 $log = fopen($logfile, "a");
1060 $output = common_log_line($priority, $msg);
1061 fwrite($log, $output);
1065 common_ensure_syslog();
1066 syslog($priority, $msg);
1070 function common_debug($msg, $filename=null)
1073 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1075 common_log(LOG_DEBUG, $msg);
1079 function common_log_db_error(&$object, $verb, $filename=null)
1081 $objstr = common_log_objstring($object);
1082 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1083 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1086 function common_log_objstring(&$object)
1088 if (is_null($object)) {
1091 if (!($object instanceof DB_DataObject)) {
1094 $arr = $object->toArray();
1096 foreach ($arr as $k => $v) {
1097 if (is_object($v)) {
1098 $fields[] = "$k='".get_class($v)."'";
1100 $fields[] = "$k='$v'";
1103 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1107 function common_valid_http_url($url)
1109 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1112 function common_valid_tag($tag)
1114 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1115 return (Validate::email($matches[1]) ||
1116 preg_match('/^([\w-\.]+)$/', $matches[1]));
1121 /* Following functions are copied from MediaWiki GlobalFunctions.php
1122 * and written by Evan Prodromou. */
1124 function common_accept_to_prefs($accept, $def = '*/*')
1126 // No arg means accept anything (per HTTP spec)
1128 return array($def => 1);
1133 $parts = explode(',', $accept);
1135 foreach($parts as $part) {
1136 // FIXME: doesn't deal with params like 'text/html; level=1'
1137 @list($value, $qpart) = explode(';', trim($part));
1139 if(!isset($qpart)) {
1141 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1142 $prefs[$value] = $match[1];
1149 function common_mime_type_match($type, $avail)
1151 if(array_key_exists($type, $avail)) {
1154 $parts = explode('/', $type);
1155 if(array_key_exists($parts[0] . '/*', $avail)) {
1156 return $parts[0] . '/*';
1157 } elseif(array_key_exists('*/*', $avail)) {
1165 function common_negotiate_type($cprefs, $sprefs)
1169 foreach(array_keys($sprefs) as $type) {
1170 $parts = explode('/', $type);
1171 if($parts[1] != '*') {
1172 $ckey = common_mime_type_match($type, $cprefs);
1174 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1179 foreach(array_keys($cprefs) as $type) {
1180 $parts = explode('/', $type);
1181 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1182 $skey = common_mime_type_match($type, $sprefs);
1184 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1190 $besttype = 'text/html';
1192 foreach(array_keys($combine) as $type) {
1193 if($combine[$type] > $bestq) {
1195 $bestq = $combine[$type];
1199 if ('text/html' === $besttype) {
1200 return "text/html; charset=utf-8";
1205 function common_config($main, $sub)
1208 return (array_key_exists($main, $config) &&
1209 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1212 function common_copy_args($from)
1215 $strip = get_magic_quotes_gpc();
1216 foreach ($from as $k => $v) {
1217 $to[$k] = ($strip) ? stripslashes($v) : $v;
1222 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1223 // This is used before handing a request off to OAuthRequest::from_request.
1224 function common_remove_magic_from_request()
1226 if(get_magic_quotes_gpc()) {
1227 $_POST=array_map('stripslashes',$_POST);
1228 $_GET=array_map('stripslashes',$_GET);
1232 function common_user_uri(&$user)
1234 return common_local_url('userbyid', array('id' => $user->id));
1237 function common_notice_uri(&$notice)
1239 return common_local_url('shownotice',
1240 array('notice' => $notice->id));
1243 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1245 function common_confirmation_code($bits)
1247 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1248 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1249 $chars = ceil($bits/5);
1251 for ($i = 0; $i < $chars; $i++) {
1252 // XXX: convert to string and back
1253 $num = hexdec(common_good_rand(1));
1254 // XXX: randomness is too precious to throw away almost
1255 // 40% of the bits we get!
1256 $code .= $codechars[$num%32];
1261 // convert markup to HTML
1263 function common_markup_to_html($c)
1265 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1266 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1267 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1268 return Markdown($c);
1271 function common_profile_uri($profile)
1276 $user = User::staticGet($profile->id);
1281 $remote = Remote_profile::staticGet($profile->id);
1283 return $remote->uri;
1285 // XXX: this is a very bad profile!
1289 function common_canonical_sms($sms)
1292 preg_replace('/\D/', '', $sms);
1296 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1301 case E_COMPILE_ERROR:
1305 case E_RECOVERABLE_ERROR:
1306 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1311 case E_COMPILE_WARNING:
1312 case E_CORE_WARNING:
1313 case E_USER_WARNING:
1314 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1319 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1324 case E_USER_DEPRECATED:
1325 // XXX: config variable to log this stuff, too
1329 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1334 // FIXME: show error page if we're on the Web
1335 /* Don't execute PHP internal error handler */
1339 function common_session_token()
1341 common_ensure_session();
1342 if (!array_key_exists('token', $_SESSION)) {
1343 $_SESSION['token'] = common_good_rand(64);
1345 return $_SESSION['token'];
1348 function common_cache_key($extra)
1350 $base_key = common_config('memcached', 'base');
1352 if (empty($base_key)) {
1353 $base_key = common_keyize(common_config('site', 'name'));
1356 return 'statusnet:' . $base_key . ':' . $extra;
1359 function common_keyize($str)
1361 $str = strtolower($str);
1362 $str = preg_replace('/\s/', '_', $str);
1366 function common_memcache()
1368 static $cache = null;
1369 if (!common_config('memcached', 'enabled')) {
1373 $cache = new Memcache();
1374 $servers = common_config('memcached', 'server');
1375 if (is_array($servers)) {
1376 foreach($servers as $server) {
1377 $cache->addServer($server);
1380 $cache->addServer($servers);
1387 function common_license_terms($uri)
1389 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1390 return explode('-',$matches[1]);
1395 function common_compatible_license($from, $to)
1397 $from_terms = common_license_terms($from);
1398 // public domain and cc-by are compatible with everything
1399 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1402 $to_terms = common_license_terms($to);
1403 // sa is compatible across versions. IANAL
1404 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1405 return count(array_diff($from_terms, $to_terms)) == 0;
1407 // XXX: better compatibility check needed here!
1408 // Should at least normalise URIs
1409 return ($from == $to);
1413 * returns a quoted table name, if required according to config
1415 function common_database_tablename($tablename)
1418 if(common_config('db','quote_identifiers')) {
1419 $tablename = '"'. $tablename .'"';
1421 //table prefixes could be added here later
1425 function common_shorten_url($long_url)
1427 $user = common_current_user();
1429 // common current user does not find a user when called from the XMPP daemon
1430 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1431 $shortenerName = 'ur1.ca';
1433 $shortenerName = $user->urlshorteningservice;
1436 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1437 //URL wasn't shortened, so return the long url
1440 //URL was shortened, so return the result
1441 return $shortenedUrl;
1445 function common_client_ip()
1447 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1451 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1452 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1453 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1455 $proxy = $_SERVER['REMOTE_ADDR'];
1457 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1460 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1461 $ip = $_SERVER['HTTP_CLIENT_IP'];
1463 $ip = $_SERVER['REMOTE_ADDR'];
1467 return array($proxy, $ip);