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
119 function common_check_user($nickname, $password)
121 $authenticated = false;
122 $eventResult = Event::handle('CheckPassword', array($nickname, $password, &$authenticated));
123 $user = User::staticGet('nickname', $nickname);
124 if (is_null($user) || $user === false) {
125 //user does not exist
127 //a handler said these are valid credentials, so see if a plugin wants to auto register the user
128 if(Event::handle('AutoRegister', array($nickname))){
129 //no handler registered the user
132 $user = User::staticGet('nickname', $nickname);
133 if (is_null($user) || $user === false) {
134 common_log(LOG_WARNING, "A plugin handled the AutoRegister event, but did not actually register the user, nickname: $nickname");
141 //no handler indicated the credentials were valid, and we know their not valid because the user isn't in the database
145 if($eventResult && ! $authenticated){
146 //no handler was authoritative
147 if (mb_strlen($password) == 0) {
148 // NEVER allow blank passwords, even if they match the DB
151 if (0 == strcmp(common_munge_password($password, $user->id),
153 //internal checking passed
154 $authenticated = true;
166 // is the current user logged in?
167 function common_logged_in()
169 return (!is_null(common_current_user()));
172 function common_have_session()
174 return (0 != strcmp(session_id(), ''));
177 function common_ensure_session()
180 if (array_key_exists(session_name(), $_COOKIE)) {
181 $c = $_COOKIE[session_name()];
183 if (!common_have_session()) {
184 if (common_config('sessions', 'handle')) {
185 Session::setSaveHandler();
188 if (!isset($_SESSION['started'])) {
189 $_SESSION['started'] = time();
191 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
192 ' is set but started value is null');
198 // Three kinds of arguments:
203 // Initialize to false; set to null if none found
207 function common_set_user($user)
212 if (is_null($user) && common_have_session()) {
214 unset($_SESSION['userid']);
216 } else if (is_string($user)) {
218 $user = User::staticGet('nickname', $nickname);
219 } else if (!($user instanceof User)) {
224 common_ensure_session();
225 $_SESSION['userid'] = $user->id;
232 function common_set_cookie($key, $value, $expiration=0)
234 $path = common_config('site', 'path');
235 $server = common_config('site', 'server');
237 if ($path && ($path != '/')) {
238 $cookiepath = '/' . $path . '/';
242 return setcookie($key,
249 define('REMEMBERME', 'rememberme');
250 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
252 function common_rememberme($user=null)
255 $user = common_current_user();
257 common_debug('No current user to remember', __FILE__);
262 $rm = new Remember_me();
264 $rm->code = common_good_rand(16);
265 $rm->user_id = $user->id;
267 // Wrap the insert in some good ol' fashioned transaction code
271 $result = $rm->insert();
274 common_log_db_error($rm, 'INSERT', __FILE__);
275 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
279 $rm->query('COMMIT');
281 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
283 $cookieval = $rm->user_id . ':' . $rm->code;
285 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
287 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
292 function common_remembered_user()
297 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
303 list($id, $code) = explode(':', $packed);
305 if (!$id || !$code) {
306 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
311 $rm = Remember_me::staticGet($code);
314 common_log(LOG_WARNING, 'No such remember code: ' . $code);
319 if ($rm->user_id != $id) {
320 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
325 $user = User::staticGet($rm->user_id);
328 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
334 $result = $rm->delete();
337 common_log_db_error($rm, 'DELETE', __FILE__);
338 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
343 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
345 common_set_user($user);
346 common_real_login(false);
348 // We issue a new cookie, so they can log in
349 // automatically again after this session
351 common_rememberme($user);
356 // must be called with a valid user!
358 function common_forgetme()
360 common_set_cookie(REMEMBERME, '', 0);
363 // who is the current user?
364 function common_current_user()
368 if (!_have_config()) {
372 if ($_cur === false) {
374 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
375 common_ensure_session();
376 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
378 $_cur = User::staticGet($id);
383 // that didn't work; try to remember; will init $_cur to null on failure
384 $_cur = common_remembered_user();
387 common_debug("Got User " . $_cur->nickname);
388 common_debug("Faking session on remembered user");
389 // XXX: Is this necessary?
390 $_SESSION['userid'] = $_cur->id;
397 // Logins that are 'remembered' aren't 'real' -- they're subject to
398 // cookie-stealing. So, we don't let them do certain things. New reg,
399 // OpenID, and password logins _are_ real.
401 function common_real_login($real=true)
403 common_ensure_session();
404 $_SESSION['real_login'] = $real;
407 function common_is_real_login()
409 return common_logged_in() && $_SESSION['real_login'];
412 // get canonical version of nickname for comparison
413 function common_canonical_nickname($nickname)
415 // XXX: UTF-8 canonicalization (like combining chars)
416 return strtolower($nickname);
419 // get canonical version of email for comparison
420 function common_canonical_email($email)
422 // XXX: canonicalize UTF-8
423 // XXX: lcase the domain part
427 function common_render_content($text, $notice)
429 $r = common_render_text($text);
430 $id = $notice->profile_id;
431 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
432 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
433 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
434 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
438 function common_render_text($text)
440 $r = htmlspecialchars($text);
442 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
443 $r = common_replace_urls_callback($r, 'common_linkify');
444 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
449 function common_replace_urls_callback($text, $callback, $notice_id = null) {
450 // Start off with a regex
452 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
455 '(?:'. //Known protocols
457 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
459 '(?:(?:mailto|aim|tel|xmpp):)'.
461 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
464 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
466 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
470 '|(?:(?: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
472 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
474 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
475 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
476 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
477 '(?: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)'.
481 '(?:\:\d+)?'. //:port
482 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
483 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
484 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
485 ')(?<![\?\.\,\#\,])'.
488 //preg_match_all($regex,$text,$matches);
490 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
493 function callback_helper($matches, $callback, $notice_id) {
495 $left = strpos($matches[0],$url);
496 $right = $left+strlen($url);
498 $groupSymbolSets=array(
516 $cannotEndWith=array('.','?',',','#');
520 foreach($groupSymbolSets as $groupSymbolSet){
521 if(substr($url,-1)==$groupSymbolSet['right']){
522 $group_left_count = substr_count($url,$groupSymbolSet['left']);
523 $group_right_count = substr_count($url,$groupSymbolSet['right']);
524 if($group_left_count<$group_right_count){
526 $url=substr($url,0,-1);
530 if(in_array(substr($url,-1),$cannotEndWith)){
532 $url=substr($url,0,-1);
534 }while($original_url!=$url);
536 if(empty($notice_id)){
537 $result = call_user_func_array($callback, array($url));
539 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
541 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
544 function curry($fn) {
545 //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
546 $args = func_get_args();
548 $id = uniqid('_partial');
549 $GLOBALS[$id] = array($fn, $args);
550 return create_function('',
551 '$args = func_get_args(); '.
552 'return call_user_func_array('.
553 '$GLOBALS["'.$id.'"][0],'.
556 '$GLOBALS["'.$id.'"][1]));');
559 function common_linkify($url) {
560 // It comes in special'd, so we unspecial it before passing to the stringifying
562 $url = htmlspecialchars_decode($url);
564 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
565 //url is an email address without the mailto: protocol
566 $canon = "mailto:$url";
567 $longurl = "mailto:$url";
570 $canon = File_redirection::_canonUrl($url);
572 $longurl_data = File_redirection::where($canon);
573 if (is_array($longurl_data)) {
574 $longurl = $longurl_data['url'];
575 } elseif (is_string($longurl_data)) {
576 $longurl = $longurl_data;
578 throw new ServerException("Can't linkify url '$url'");
581 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
583 $is_attachment = false;
584 $attachment_id = null;
587 // Check to see whether this is a known "attachment" URL.
589 $f = File::staticGet('url', $longurl);
592 // XXX: this writes to the database. :<
593 $f = File::processNew($longurl);
597 if ($f->isEnclosure()) {
598 $is_attachment = true;
599 $attachment_id = $f->id;
601 $foe = File_oembed::staticGet('file_id', $f->id);
603 // if it has OEmbed info, it's an attachment, too
604 $is_attachment = true;
605 $attachment_id = $f->id;
607 $thumb = File_thumbnail::staticGet('file_id', $f->id);
608 if (!empty($thumb)) {
616 if ($is_attachment) {
617 $attrs['class'] = 'attachment';
619 $attrs['class'] = 'attachment thumbnail';
621 $attrs['id'] = "attachment-{$attachment_id}";
624 return XMLStringer::estring('a', $attrs, $url);
627 function common_shorten_links($text)
629 $maxLength = Notice::maxContent();
630 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
631 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
634 function common_xml_safe_str($str)
636 // Neutralize control codes and surrogates
637 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
640 function common_tag_link($tag)
642 $canonical = common_canonical_tag($tag);
643 $url = common_local_url('tag', array('tag' => $canonical));
644 $xs = new XMLStringer();
645 $xs->elementStart('span', 'tag');
646 $xs->element('a', array('href' => $url,
649 $xs->elementEnd('span');
650 return $xs->getString();
653 function common_canonical_tag($tag)
655 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
656 return str_replace(array('-', '_', '.'), '', $tag);
659 function common_valid_profile_tag($str)
661 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
664 function common_at_link($sender_id, $nickname)
666 $sender = Profile::staticGet($sender_id);
667 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
669 $user = User::staticGet('id', $recipient->id);
671 $url = common_local_url('userbyid', array('id' => $user->id));
673 $url = $recipient->profileurl;
675 $xs = new XMLStringer(false);
676 $attrs = array('href' => $url,
678 if (!empty($recipient->fullname)) {
679 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
681 $xs->elementStart('span', 'vcard');
682 $xs->elementStart('a', $attrs);
683 $xs->element('span', 'fn nickname', $nickname);
684 $xs->elementEnd('a');
685 $xs->elementEnd('span');
686 return $xs->getString();
692 function common_group_link($sender_id, $nickname)
694 $sender = Profile::staticGet($sender_id);
695 $group = User_group::getForNickname($nickname);
696 if ($group && $sender->isMember($group)) {
697 $attrs = array('href' => $group->permalink(),
699 if (!empty($group->fullname)) {
700 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
702 $xs = new XMLStringer();
703 $xs->elementStart('span', 'vcard');
704 $xs->elementStart('a', $attrs);
705 $xs->element('span', 'fn nickname', $nickname);
706 $xs->elementEnd('a');
707 $xs->elementEnd('span');
708 return $xs->getString();
714 function common_at_hash_link($sender_id, $tag)
716 $user = User::staticGet($sender_id);
720 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
722 $url = common_local_url('subscriptions',
723 array('nickname' => $user->nickname,
725 $xs = new XMLStringer();
726 $xs->elementStart('span', 'tag');
727 $xs->element('a', array('href' => $url,
730 $xs->elementEnd('span');
731 return $xs->getString();
737 function common_relative_profile($sender, $nickname, $dt=null)
739 // Try to find profiles this profile is subscribed to that have this nickname
740 $recipient = new Profile();
741 // XXX: use a join instead of a subquery
742 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
743 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
744 if ($recipient->find(true)) {
745 // XXX: should probably differentiate between profiles with
746 // the same name by date of most recent update
749 // Try to find profiles that listen to this profile and that have this nickname
750 $recipient = new Profile();
751 // XXX: use a join instead of a subquery
752 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
753 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
754 if ($recipient->find(true)) {
755 // XXX: should probably differentiate between profiles with
756 // the same name by date of most recent update
759 // If this is a local user, try to find a local user with that nickname.
760 $sender = User::staticGet($sender->id);
762 $recipient_user = User::staticGet('nickname', $nickname);
763 if ($recipient_user) {
764 return $recipient_user->getProfile();
767 // Otherwise, no links. @messages from local users to remote users,
768 // or from remote users to other remote users, are just
769 // outside our ability to make intelligent guesses about
773 function common_local_url($action, $args=null, $params=null, $fragment=null)
776 $path = $r->build($action, $args, $params, $fragment);
778 $ssl = common_is_sensitive($action);
780 if (common_config('site','fancy')) {
781 $url = common_path(mb_substr($path, 1), $ssl);
783 if (mb_strpos($path, '/index.php') === 0) {
784 $url = common_path(mb_substr($path, 1), $ssl);
786 $url = common_path('index.php'.$path, $ssl);
792 function common_is_sensitive($action)
794 static $sensitive = array('login', 'register', 'passwordsettings',
795 'twittersettings', 'api');
798 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
799 $ssl = in_array($action, $sensitive);
805 function common_path($relative, $ssl=false)
807 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
809 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
810 || common_config('site', 'ssl') === 'always') {
812 if (is_string(common_config('site', 'sslserver')) &&
813 mb_strlen(common_config('site', 'sslserver')) > 0) {
814 $serverpart = common_config('site', 'sslserver');
815 } else if (common_config('site', 'server')) {
816 $serverpart = common_config('site', 'server');
818 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
822 if (common_config('site', 'server')) {
823 $serverpart = common_config('site', 'server');
825 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
829 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
832 function common_date_string($dt)
834 // XXX: do some sexy date formatting
835 // return date(DATE_RFC822, $dt);
840 if ($now < $t) { // that shouldn't happen!
841 return common_exact_date($dt);
842 } else if ($diff < 60) {
843 return _('a few seconds ago');
844 } else if ($diff < 92) {
845 return _('about a minute ago');
846 } else if ($diff < 3300) {
847 return sprintf(_('about %d minutes ago'), round($diff/60));
848 } else if ($diff < 5400) {
849 return _('about an hour ago');
850 } else if ($diff < 22 * 3600) {
851 return sprintf(_('about %d hours ago'), round($diff/3600));
852 } else if ($diff < 37 * 3600) {
853 return _('about a day ago');
854 } else if ($diff < 24 * 24 * 3600) {
855 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
856 } else if ($diff < 46 * 24 * 3600) {
857 return _('about a month ago');
858 } else if ($diff < 330 * 24 * 3600) {
859 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
860 } else if ($diff < 480 * 24 * 3600) {
861 return _('about a year ago');
863 return common_exact_date($dt);
867 function common_exact_date($dt)
873 $_utc = new DateTimeZone('UTC');
874 $_siteTz = new DateTimeZone(common_timezone());
877 $dateStr = date('d F Y H:i:s', strtotime($dt));
878 $d = new DateTime($dateStr, $_utc);
879 $d->setTimezone($_siteTz);
880 return $d->format(DATE_RFC850);
883 function common_date_w3dtf($dt)
885 $dateStr = date('d F Y H:i:s', strtotime($dt));
886 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
887 $d->setTimezone(new DateTimeZone(common_timezone()));
888 return $d->format(DATE_W3C);
891 function common_date_rfc2822($dt)
893 $dateStr = date('d F Y H:i:s', strtotime($dt));
894 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
895 $d->setTimezone(new DateTimeZone(common_timezone()));
896 return $d->format('r');
899 function common_date_iso8601($dt)
901 $dateStr = date('d F Y H:i:s', strtotime($dt));
902 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
903 $d->setTimezone(new DateTimeZone(common_timezone()));
904 return $d->format('c');
907 function common_sql_now()
909 return common_sql_date(time());
912 function common_sql_date($datetime)
914 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
917 function common_redirect($url, $code=307)
919 static $status = array(301 => "Moved Permanently",
922 307 => "Temporary Redirect");
924 header('HTTP/1.1 '.$code.' '.$status[$code]);
925 header("Location: $url");
927 $xo = new XMLOutputter();
929 '-//W3C//DTD XHTML 1.0 Strict//EN',
930 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
931 $xo->element('a', array('href' => $url), $url);
936 function common_broadcast_notice($notice, $remote=false)
938 return common_enqueue_notice($notice);
941 // Stick the notice on the queue
943 function common_enqueue_notice($notice)
945 static $localTransports = array('omb',
948 static $allTransports = array('sms', 'plugin');
950 $transports = $allTransports;
952 $xmpp = common_config('xmpp', 'enabled');
955 $transports[] = 'jabber';
958 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
959 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
960 $transports = array_merge($transports, $localTransports);
962 $transports[] = 'public';
966 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
968 $qm = QueueManager::get();
970 foreach ($transports as $transport)
972 $qm->enqueue($notice, $transport);
975 Event::handle('EndEnqueueNotice', array($notice, $transports));
981 function common_broadcast_profile($profile)
983 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
984 require_once(INSTALLDIR.'/lib/omb.php');
985 omb_broadcast_profile($profile);
986 // XXX: Other broadcasts...?
990 function common_profile_url($nickname)
992 return common_local_url('showstream', array('nickname' => $nickname));
995 // Should make up a reasonable root URL
997 function common_root_url($ssl=false)
999 return common_path('', $ssl);
1002 // returns $bytes bytes of random data as a hexadecimal string
1003 // "good" here is a goal and not a guarantee
1005 function common_good_rand($bytes)
1007 // XXX: use random.org...?
1008 if (@file_exists('/dev/urandom')) {
1009 return common_urandom($bytes);
1010 } else { // FIXME: this is probably not good enough
1011 return common_mtrand($bytes);
1015 function common_urandom($bytes)
1017 $h = fopen('/dev/urandom', 'rb');
1019 $src = fread($h, $bytes);
1022 for ($i = 0; $i < $bytes; $i++) {
1023 $enc .= sprintf("%02x", (ord($src[$i])));
1028 function common_mtrand($bytes)
1031 for ($i = 0; $i < $bytes; $i++) {
1032 $enc .= sprintf("%02x", mt_rand(0, 255));
1037 function common_set_returnto($url)
1039 common_ensure_session();
1040 $_SESSION['returnto'] = $url;
1043 function common_get_returnto()
1045 common_ensure_session();
1046 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1049 function common_timestamp()
1051 return date('YmdHis');
1054 function common_ensure_syslog()
1056 static $initialized = false;
1057 if (!$initialized) {
1058 openlog(common_config('syslog', 'appname'), 0,
1059 common_config('syslog', 'facility'));
1060 $initialized = true;
1064 function common_log_line($priority, $msg)
1066 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1067 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1068 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1071 function common_log($priority, $msg, $filename=null)
1073 $logfile = common_config('site', 'logfile');
1075 $log = fopen($logfile, "a");
1077 $output = common_log_line($priority, $msg);
1078 fwrite($log, $output);
1082 common_ensure_syslog();
1083 syslog($priority, $msg);
1087 function common_debug($msg, $filename=null)
1090 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1092 common_log(LOG_DEBUG, $msg);
1096 function common_log_db_error(&$object, $verb, $filename=null)
1098 $objstr = common_log_objstring($object);
1099 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1100 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1103 function common_log_objstring(&$object)
1105 if (is_null($object)) {
1108 if (!($object instanceof DB_DataObject)) {
1111 $arr = $object->toArray();
1113 foreach ($arr as $k => $v) {
1114 if (is_object($v)) {
1115 $fields[] = "$k='".get_class($v)."'";
1117 $fields[] = "$k='$v'";
1120 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1124 function common_valid_http_url($url)
1126 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1129 function common_valid_tag($tag)
1131 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1132 return (Validate::email($matches[1]) ||
1133 preg_match('/^([\w-\.]+)$/', $matches[1]));
1138 /* Following functions are copied from MediaWiki GlobalFunctions.php
1139 * and written by Evan Prodromou. */
1141 function common_accept_to_prefs($accept, $def = '*/*')
1143 // No arg means accept anything (per HTTP spec)
1145 return array($def => 1);
1150 $parts = explode(',', $accept);
1152 foreach($parts as $part) {
1153 // FIXME: doesn't deal with params like 'text/html; level=1'
1154 @list($value, $qpart) = explode(';', trim($part));
1156 if(!isset($qpart)) {
1158 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1159 $prefs[$value] = $match[1];
1166 function common_mime_type_match($type, $avail)
1168 if(array_key_exists($type, $avail)) {
1171 $parts = explode('/', $type);
1172 if(array_key_exists($parts[0] . '/*', $avail)) {
1173 return $parts[0] . '/*';
1174 } elseif(array_key_exists('*/*', $avail)) {
1182 function common_negotiate_type($cprefs, $sprefs)
1186 foreach(array_keys($sprefs) as $type) {
1187 $parts = explode('/', $type);
1188 if($parts[1] != '*') {
1189 $ckey = common_mime_type_match($type, $cprefs);
1191 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1196 foreach(array_keys($cprefs) as $type) {
1197 $parts = explode('/', $type);
1198 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1199 $skey = common_mime_type_match($type, $sprefs);
1201 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1207 $besttype = 'text/html';
1209 foreach(array_keys($combine) as $type) {
1210 if($combine[$type] > $bestq) {
1212 $bestq = $combine[$type];
1216 if ('text/html' === $besttype) {
1217 return "text/html; charset=utf-8";
1222 function common_config($main, $sub)
1225 return (array_key_exists($main, $config) &&
1226 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1229 function common_copy_args($from)
1232 $strip = get_magic_quotes_gpc();
1233 foreach ($from as $k => $v) {
1234 $to[$k] = ($strip) ? stripslashes($v) : $v;
1239 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1240 // This is used before handing a request off to OAuthRequest::from_request.
1241 function common_remove_magic_from_request()
1243 if(get_magic_quotes_gpc()) {
1244 $_POST=array_map('stripslashes',$_POST);
1245 $_GET=array_map('stripslashes',$_GET);
1249 function common_user_uri(&$user)
1251 return common_local_url('userbyid', array('id' => $user->id));
1254 function common_notice_uri(&$notice)
1256 return common_local_url('shownotice',
1257 array('notice' => $notice->id));
1260 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1262 function common_confirmation_code($bits)
1264 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1265 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1266 $chars = ceil($bits/5);
1268 for ($i = 0; $i < $chars; $i++) {
1269 // XXX: convert to string and back
1270 $num = hexdec(common_good_rand(1));
1271 // XXX: randomness is too precious to throw away almost
1272 // 40% of the bits we get!
1273 $code .= $codechars[$num%32];
1278 // convert markup to HTML
1280 function common_markup_to_html($c)
1282 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1283 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1284 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1285 return Markdown($c);
1288 function common_profile_uri($profile)
1293 $user = User::staticGet($profile->id);
1298 $remote = Remote_profile::staticGet($profile->id);
1300 return $remote->uri;
1302 // XXX: this is a very bad profile!
1306 function common_canonical_sms($sms)
1309 preg_replace('/\D/', '', $sms);
1313 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1318 case E_COMPILE_ERROR:
1322 case E_RECOVERABLE_ERROR:
1323 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1328 case E_COMPILE_WARNING:
1329 case E_CORE_WARNING:
1330 case E_USER_WARNING:
1331 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1336 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1341 case E_USER_DEPRECATED:
1342 // XXX: config variable to log this stuff, too
1346 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1351 // FIXME: show error page if we're on the Web
1352 /* Don't execute PHP internal error handler */
1356 function common_session_token()
1358 common_ensure_session();
1359 if (!array_key_exists('token', $_SESSION)) {
1360 $_SESSION['token'] = common_good_rand(64);
1362 return $_SESSION['token'];
1365 function common_cache_key($extra)
1367 $base_key = common_config('memcached', 'base');
1369 if (empty($base_key)) {
1370 $base_key = common_keyize(common_config('site', 'name'));
1373 return 'statusnet:' . $base_key . ':' . $extra;
1376 function common_keyize($str)
1378 $str = strtolower($str);
1379 $str = preg_replace('/\s/', '_', $str);
1383 function common_memcache()
1385 static $cache = null;
1386 if (!common_config('memcached', 'enabled')) {
1390 $cache = new Memcache();
1391 $servers = common_config('memcached', 'server');
1392 if (is_array($servers)) {
1393 foreach($servers as $server) {
1394 $cache->addServer($server);
1397 $cache->addServer($servers);
1404 function common_license_terms($uri)
1406 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1407 return explode('-',$matches[1]);
1412 function common_compatible_license($from, $to)
1414 $from_terms = common_license_terms($from);
1415 // public domain and cc-by are compatible with everything
1416 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1419 $to_terms = common_license_terms($to);
1420 // sa is compatible across versions. IANAL
1421 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1422 return count(array_diff($from_terms, $to_terms)) == 0;
1424 // XXX: better compatibility check needed here!
1425 // Should at least normalise URIs
1426 return ($from == $to);
1430 * returns a quoted table name, if required according to config
1432 function common_database_tablename($tablename)
1435 if(common_config('db','quote_identifiers')) {
1436 $tablename = '"'. $tablename .'"';
1438 //table prefixes could be added here later
1442 function common_shorten_url($long_url)
1444 $user = common_current_user();
1446 // common current user does not find a user when called from the XMPP daemon
1447 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1450 $svc = $user->urlshorteningservice;
1452 global $_shorteners;
1453 if (!isset($_shorteners[$svc])) {
1454 //the user selected service doesn't exist, so default to ur1.ca
1457 if (!isset($_shorteners[$svc])) {
1458 // no shortener plugins installed.
1462 $reflectionObj = new ReflectionClass($_shorteners[$svc]['callInfo'][0]);
1463 $short_url_service = $reflectionObj->newInstanceArgs($_shorteners[$svc]['callInfo'][1]);
1464 $short_url = $short_url_service->shorten($long_url);
1469 function common_client_ip()
1471 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1475 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1476 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1477 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1479 $proxy = $_SERVER['REMOTE_ADDR'];
1481 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1484 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1485 $ip = $_SERVER['HTTP_CLIENT_IP'];
1487 $ip = $_SERVER['REMOTE_ADDR'];
1491 return array($proxy, $ip);