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 $authenticated = false;
123 $eventResult = Event::handle('CheckPassword', array($nickname, $password, &$authenticated));
124 $user = User::staticGet('nickname', $nickname);
125 if (is_null($user) || $user === false) {
126 //user does not exist
128 //a handler said these are valid credentials, so see if a plugin wants to auto register the user
129 if(Event::handle('AutoRegister', array($nickname))){
130 //no handler registered the user
133 $user = User::staticGet('nickname', $nickname);
134 if (is_null($user) || $user === false) {
135 common_log(LOG_WARNING, "A plugin handled the AutoRegister event, but did not actually register the user, nickname: $nickname");
142 //no handler indicated the credentials were valid, and we know their not valid because the user isn't in the database
146 if($eventResult && ! $authenticated){
147 //no handler was authoritative
148 if (mb_strlen($password) == 0) {
149 // NEVER allow blank passwords, even if they match the DB
152 if (0 == strcmp(common_munge_password($password, $user->id),
154 //internal checking passed
155 $authenticated = true;
167 // is the current user logged in?
168 function common_logged_in()
170 return (!is_null(common_current_user()));
173 function common_have_session()
175 return (0 != strcmp(session_id(), ''));
178 function common_ensure_session()
181 if (array_key_exists(session_name(), $_COOKIE)) {
182 $c = $_COOKIE[session_name()];
184 if (!common_have_session()) {
185 if (common_config('sessions', 'handle')) {
186 Session::setSaveHandler();
189 if (!isset($_SESSION['started'])) {
190 $_SESSION['started'] = time();
192 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
193 ' is set but started value is null');
199 // Three kinds of arguments:
204 // Initialize to false; set to null if none found
208 function common_set_user($user)
213 if (is_null($user) && common_have_session()) {
215 unset($_SESSION['userid']);
217 } else if (is_string($user)) {
219 $user = User::staticGet('nickname', $nickname);
220 } else if (!($user instanceof User)) {
225 common_ensure_session();
226 $_SESSION['userid'] = $user->id;
233 function common_set_cookie($key, $value, $expiration=0)
235 $path = common_config('site', 'path');
236 $server = common_config('site', 'server');
238 if ($path && ($path != '/')) {
239 $cookiepath = '/' . $path . '/';
243 return setcookie($key,
250 define('REMEMBERME', 'rememberme');
251 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
253 function common_rememberme($user=null)
256 $user = common_current_user();
258 common_debug('No current user to remember', __FILE__);
263 $rm = new Remember_me();
265 $rm->code = common_good_rand(16);
266 $rm->user_id = $user->id;
268 // Wrap the insert in some good ol' fashioned transaction code
272 $result = $rm->insert();
275 common_log_db_error($rm, 'INSERT', __FILE__);
276 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
280 $rm->query('COMMIT');
282 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
284 $cookieval = $rm->user_id . ':' . $rm->code;
286 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
288 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
293 function common_remembered_user()
298 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
304 list($id, $code) = explode(':', $packed);
306 if (!$id || !$code) {
307 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
312 $rm = Remember_me::staticGet($code);
315 common_log(LOG_WARNING, 'No such remember code: ' . $code);
320 if ($rm->user_id != $id) {
321 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
326 $user = User::staticGet($rm->user_id);
329 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
335 $result = $rm->delete();
338 common_log_db_error($rm, 'DELETE', __FILE__);
339 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
344 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
346 common_set_user($user);
347 common_real_login(false);
349 // We issue a new cookie, so they can log in
350 // automatically again after this session
352 common_rememberme($user);
357 // must be called with a valid user!
359 function common_forgetme()
361 common_set_cookie(REMEMBERME, '', 0);
364 // who is the current user?
365 function common_current_user()
369 if (!_have_config()) {
373 if ($_cur === false) {
375 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
376 common_ensure_session();
377 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
379 $_cur = User::staticGet($id);
384 // that didn't work; try to remember; will init $_cur to null on failure
385 $_cur = common_remembered_user();
388 common_debug("Got User " . $_cur->nickname);
389 common_debug("Faking session on remembered user");
390 // XXX: Is this necessary?
391 $_SESSION['userid'] = $_cur->id;
398 // Logins that are 'remembered' aren't 'real' -- they're subject to
399 // cookie-stealing. So, we don't let them do certain things. New reg,
400 // OpenID, and password logins _are_ real.
402 function common_real_login($real=true)
404 common_ensure_session();
405 $_SESSION['real_login'] = $real;
408 function common_is_real_login()
410 return common_logged_in() && $_SESSION['real_login'];
413 // get canonical version of nickname for comparison
414 function common_canonical_nickname($nickname)
416 // XXX: UTF-8 canonicalization (like combining chars)
417 return strtolower($nickname);
420 // get canonical version of email for comparison
421 function common_canonical_email($email)
423 // XXX: canonicalize UTF-8
424 // XXX: lcase the domain part
428 function common_render_content($text, $notice)
430 $r = common_render_text($text);
431 $id = $notice->profile_id;
432 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
433 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
434 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
435 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
439 function common_render_text($text)
441 $r = htmlspecialchars($text);
443 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
444 $r = common_replace_urls_callback($r, 'common_linkify');
445 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
450 function common_replace_urls_callback($text, $callback, $notice_id = null) {
451 // Start off with a regex
453 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
456 '(?:'. //Known protocols
458 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
460 '(?:(?:mailto|aim|tel|xmpp):)'.
462 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
465 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
467 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
471 '|(?:(?: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
473 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
475 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
476 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
477 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
478 '(?: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)'.
482 '(?:\:\d+)?'. //:port
483 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
484 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
485 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
486 ')(?<![\?\.\,\#\,])'.
489 //preg_match_all($regex,$text,$matches);
491 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
494 function callback_helper($matches, $callback, $notice_id) {
496 $left = strpos($matches[0],$url);
497 $right = $left+strlen($url);
499 $groupSymbolSets=array(
517 $cannotEndWith=array('.','?',',','#');
521 foreach($groupSymbolSets as $groupSymbolSet){
522 if(substr($url,-1)==$groupSymbolSet['right']){
523 $group_left_count = substr_count($url,$groupSymbolSet['left']);
524 $group_right_count = substr_count($url,$groupSymbolSet['right']);
525 if($group_left_count<$group_right_count){
527 $url=substr($url,0,-1);
531 if(in_array(substr($url,-1),$cannotEndWith)){
533 $url=substr($url,0,-1);
535 }while($original_url!=$url);
537 if(empty($notice_id)){
538 $result = call_user_func_array($callback, array($url));
540 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
542 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
545 function curry($fn) {
546 //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
547 $args = func_get_args();
549 $id = uniqid('_partial');
550 $GLOBALS[$id] = array($fn, $args);
551 return create_function('',
552 '$args = func_get_args(); '.
553 'return call_user_func_array('.
554 '$GLOBALS["'.$id.'"][0],'.
557 '$GLOBALS["'.$id.'"][1]));');
560 function common_linkify($url) {
561 // It comes in special'd, so we unspecial it before passing to the stringifying
563 $url = htmlspecialchars_decode($url);
565 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
566 //url is an email address without the mailto: protocol
567 $canon = "mailto:$url";
568 $longurl = "mailto:$url";
571 $canon = File_redirection::_canonUrl($url);
573 $longurl_data = File_redirection::where($canon);
574 if (is_array($longurl_data)) {
575 $longurl = $longurl_data['url'];
576 } elseif (is_string($longurl_data)) {
577 $longurl = $longurl_data;
579 throw new ServerException("Cannot linkify url '$url'");
582 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
584 $is_attachment = false;
585 $attachment_id = null;
588 // Check to see whether this is a known "attachment" URL.
590 $f = File::staticGet('url', $longurl);
593 // XXX: this writes to the database. :<
594 $f = File::processNew($longurl);
598 if ($f->isEnclosure()) {
599 $is_attachment = true;
600 $attachment_id = $f->id;
602 $foe = File_oembed::staticGet('file_id', $f->id);
604 // if it has OEmbed info, it's an attachment, too
605 $is_attachment = true;
606 $attachment_id = $f->id;
608 $thumb = File_thumbnail::staticGet('file_id', $f->id);
609 if (!empty($thumb)) {
617 if ($is_attachment) {
618 $attrs['class'] = 'attachment';
620 $attrs['class'] = 'attachment thumbnail';
622 $attrs['id'] = "attachment-{$attachment_id}";
625 return XMLStringer::estring('a', $attrs, $url);
628 function common_shorten_links($text)
630 $maxLength = Notice::maxContent();
631 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
632 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
635 function common_xml_safe_str($str)
637 // Neutralize control codes and surrogates
638 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
641 function common_tag_link($tag)
643 $canonical = common_canonical_tag($tag);
644 $url = common_local_url('tag', array('tag' => $canonical));
645 $xs = new XMLStringer();
646 $xs->elementStart('span', 'tag');
647 $xs->element('a', array('href' => $url,
650 $xs->elementEnd('span');
651 return $xs->getString();
654 function common_canonical_tag($tag)
656 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
657 return str_replace(array('-', '_', '.'), '', $tag);
660 function common_valid_profile_tag($str)
662 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
665 function common_at_link($sender_id, $nickname)
667 $sender = Profile::staticGet($sender_id);
668 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
670 $user = User::staticGet('id', $recipient->id);
672 $url = common_local_url('userbyid', array('id' => $user->id));
674 $url = $recipient->profileurl;
676 $xs = new XMLStringer(false);
677 $attrs = array('href' => $url,
679 if (!empty($recipient->fullname)) {
680 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
682 $xs->elementStart('span', 'vcard');
683 $xs->elementStart('a', $attrs);
684 $xs->element('span', 'fn nickname', $nickname);
685 $xs->elementEnd('a');
686 $xs->elementEnd('span');
687 return $xs->getString();
693 function common_group_link($sender_id, $nickname)
695 $sender = Profile::staticGet($sender_id);
696 $group = User_group::getForNickname($nickname);
697 if ($group && $sender->isMember($group)) {
698 $attrs = array('href' => $group->permalink(),
700 if (!empty($group->fullname)) {
701 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
703 $xs = new XMLStringer();
704 $xs->elementStart('span', 'vcard');
705 $xs->elementStart('a', $attrs);
706 $xs->element('span', 'fn nickname', $nickname);
707 $xs->elementEnd('a');
708 $xs->elementEnd('span');
709 return $xs->getString();
715 function common_at_hash_link($sender_id, $tag)
717 $user = User::staticGet($sender_id);
721 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
723 $url = common_local_url('subscriptions',
724 array('nickname' => $user->nickname,
726 $xs = new XMLStringer();
727 $xs->elementStart('span', 'tag');
728 $xs->element('a', array('href' => $url,
731 $xs->elementEnd('span');
732 return $xs->getString();
738 function common_relative_profile($sender, $nickname, $dt=null)
740 // Try to find profiles this profile is subscribed to that have this nickname
741 $recipient = new Profile();
742 // XXX: use a join instead of a subquery
743 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
744 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
745 if ($recipient->find(true)) {
746 // XXX: should probably differentiate between profiles with
747 // the same name by date of most recent update
750 // Try to find profiles that listen to this profile and that have this nickname
751 $recipient = new Profile();
752 // XXX: use a join instead of a subquery
753 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
754 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
755 if ($recipient->find(true)) {
756 // XXX: should probably differentiate between profiles with
757 // the same name by date of most recent update
760 // If this is a local user, try to find a local user with that nickname.
761 $sender = User::staticGet($sender->id);
763 $recipient_user = User::staticGet('nickname', $nickname);
764 if ($recipient_user) {
765 return $recipient_user->getProfile();
768 // Otherwise, no links. @messages from local users to remote users,
769 // or from remote users to other remote users, are just
770 // outside our ability to make intelligent guesses about
774 function common_local_url($action, $args=null, $params=null, $fragment=null)
777 $path = $r->build($action, $args, $params, $fragment);
779 $ssl = common_is_sensitive($action);
781 if (common_config('site','fancy')) {
782 $url = common_path(mb_substr($path, 1), $ssl);
784 if (mb_strpos($path, '/index.php') === 0) {
785 $url = common_path(mb_substr($path, 1), $ssl);
787 $url = common_path('index.php'.$path, $ssl);
793 function common_is_sensitive($action)
795 static $sensitive = array('login', 'register', 'passwordsettings',
796 'twittersettings', 'api');
799 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
800 $ssl = in_array($action, $sensitive);
806 function common_path($relative, $ssl=false)
808 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
810 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
811 || common_config('site', 'ssl') === 'always') {
813 if (is_string(common_config('site', 'sslserver')) &&
814 mb_strlen(common_config('site', 'sslserver')) > 0) {
815 $serverpart = common_config('site', 'sslserver');
816 } else if (common_config('site', 'server')) {
817 $serverpart = common_config('site', 'server');
819 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
823 if (common_config('site', 'server')) {
824 $serverpart = common_config('site', 'server');
826 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
830 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
833 function common_date_string($dt)
835 // XXX: do some sexy date formatting
836 // return date(DATE_RFC822, $dt);
841 if ($now < $t) { // that shouldn't happen!
842 return common_exact_date($dt);
843 } else if ($diff < 60) {
844 return _('a few seconds ago');
845 } else if ($diff < 92) {
846 return _('about a minute ago');
847 } else if ($diff < 3300) {
848 return sprintf(_('about %d minutes ago'), round($diff/60));
849 } else if ($diff < 5400) {
850 return _('about an hour ago');
851 } else if ($diff < 22 * 3600) {
852 return sprintf(_('about %d hours ago'), round($diff/3600));
853 } else if ($diff < 37 * 3600) {
854 return _('about a day ago');
855 } else if ($diff < 24 * 24 * 3600) {
856 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
857 } else if ($diff < 46 * 24 * 3600) {
858 return _('about a month ago');
859 } else if ($diff < 330 * 24 * 3600) {
860 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
861 } else if ($diff < 480 * 24 * 3600) {
862 return _('about a year ago');
864 return common_exact_date($dt);
868 function common_exact_date($dt)
874 $_utc = new DateTimeZone('UTC');
875 $_siteTz = new DateTimeZone(common_timezone());
878 $dateStr = date('d F Y H:i:s', strtotime($dt));
879 $d = new DateTime($dateStr, $_utc);
880 $d->setTimezone($_siteTz);
881 return $d->format(DATE_RFC850);
884 function common_date_w3dtf($dt)
886 $dateStr = date('d F Y H:i:s', strtotime($dt));
887 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
888 $d->setTimezone(new DateTimeZone(common_timezone()));
889 return $d->format(DATE_W3C);
892 function common_date_rfc2822($dt)
894 $dateStr = date('d F Y H:i:s', strtotime($dt));
895 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
896 $d->setTimezone(new DateTimeZone(common_timezone()));
897 return $d->format('r');
900 function common_date_iso8601($dt)
902 $dateStr = date('d F Y H:i:s', strtotime($dt));
903 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
904 $d->setTimezone(new DateTimeZone(common_timezone()));
905 return $d->format('c');
908 function common_sql_now()
910 return common_sql_date(time());
913 function common_sql_date($datetime)
915 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
918 function common_redirect($url, $code=307)
920 static $status = array(301 => "Moved Permanently",
923 307 => "Temporary Redirect");
925 header('HTTP/1.1 '.$code.' '.$status[$code]);
926 header("Location: $url");
928 $xo = new XMLOutputter();
930 '-//W3C//DTD XHTML 1.0 Strict//EN',
931 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
932 $xo->element('a', array('href' => $url), $url);
937 function common_broadcast_notice($notice, $remote=false)
939 return common_enqueue_notice($notice);
942 // Stick the notice on the queue
944 function common_enqueue_notice($notice)
946 static $localTransports = array('omb',
949 static $allTransports = array('sms', 'plugin');
951 $transports = $allTransports;
953 $xmpp = common_config('xmpp', 'enabled');
956 $transports[] = 'jabber';
959 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
960 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
961 $transports = array_merge($transports, $localTransports);
963 $transports[] = 'public';
967 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
969 $qm = QueueManager::get();
971 foreach ($transports as $transport)
973 $qm->enqueue($notice, $transport);
976 Event::handle('EndEnqueueNotice', array($notice, $transports));
982 function common_broadcast_profile($profile)
984 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
985 require_once(INSTALLDIR.'/lib/omb.php');
986 omb_broadcast_profile($profile);
987 // XXX: Other broadcasts...?
991 function common_profile_url($nickname)
993 return common_local_url('showstream', array('nickname' => $nickname));
996 // Should make up a reasonable root URL
998 function common_root_url($ssl=false)
1000 return common_path('', $ssl);
1003 // returns $bytes bytes of random data as a hexadecimal string
1004 // "good" here is a goal and not a guarantee
1006 function common_good_rand($bytes)
1008 // XXX: use random.org...?
1009 if (@file_exists('/dev/urandom')) {
1010 return common_urandom($bytes);
1011 } else { // FIXME: this is probably not good enough
1012 return common_mtrand($bytes);
1016 function common_urandom($bytes)
1018 $h = fopen('/dev/urandom', 'rb');
1020 $src = fread($h, $bytes);
1023 for ($i = 0; $i < $bytes; $i++) {
1024 $enc .= sprintf("%02x", (ord($src[$i])));
1029 function common_mtrand($bytes)
1032 for ($i = 0; $i < $bytes; $i++) {
1033 $enc .= sprintf("%02x", mt_rand(0, 255));
1038 function common_set_returnto($url)
1040 common_ensure_session();
1041 $_SESSION['returnto'] = $url;
1044 function common_get_returnto()
1046 common_ensure_session();
1047 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1050 function common_timestamp()
1052 return date('YmdHis');
1055 function common_ensure_syslog()
1057 static $initialized = false;
1058 if (!$initialized) {
1059 openlog(common_config('syslog', 'appname'), 0,
1060 common_config('syslog', 'facility'));
1061 $initialized = true;
1065 function common_log_line($priority, $msg)
1067 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1068 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1069 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1072 function common_log($priority, $msg, $filename=null)
1074 $logfile = common_config('site', 'logfile');
1076 $log = fopen($logfile, "a");
1078 $output = common_log_line($priority, $msg);
1079 fwrite($log, $output);
1083 common_ensure_syslog();
1084 syslog($priority, $msg);
1088 function common_debug($msg, $filename=null)
1091 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1093 common_log(LOG_DEBUG, $msg);
1097 function common_log_db_error(&$object, $verb, $filename=null)
1099 $objstr = common_log_objstring($object);
1100 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1101 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1104 function common_log_objstring(&$object)
1106 if (is_null($object)) {
1109 if (!($object instanceof DB_DataObject)) {
1112 $arr = $object->toArray();
1114 foreach ($arr as $k => $v) {
1115 $fields[] = "$k='$v'";
1117 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1121 function common_valid_http_url($url)
1123 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1126 function common_valid_tag($tag)
1128 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1129 return (Validate::email($matches[1]) ||
1130 preg_match('/^([\w-\.]+)$/', $matches[1]));
1135 /* Following functions are copied from MediaWiki GlobalFunctions.php
1136 * and written by Evan Prodromou. */
1138 function common_accept_to_prefs($accept, $def = '*/*')
1140 // No arg means accept anything (per HTTP spec)
1142 return array($def => 1);
1147 $parts = explode(',', $accept);
1149 foreach($parts as $part) {
1150 // FIXME: doesn't deal with params like 'text/html; level=1'
1151 @list($value, $qpart) = explode(';', trim($part));
1153 if(!isset($qpart)) {
1155 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1156 $prefs[$value] = $match[1];
1163 function common_mime_type_match($type, $avail)
1165 if(array_key_exists($type, $avail)) {
1168 $parts = explode('/', $type);
1169 if(array_key_exists($parts[0] . '/*', $avail)) {
1170 return $parts[0] . '/*';
1171 } elseif(array_key_exists('*/*', $avail)) {
1179 function common_negotiate_type($cprefs, $sprefs)
1183 foreach(array_keys($sprefs) as $type) {
1184 $parts = explode('/', $type);
1185 if($parts[1] != '*') {
1186 $ckey = common_mime_type_match($type, $cprefs);
1188 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1193 foreach(array_keys($cprefs) as $type) {
1194 $parts = explode('/', $type);
1195 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1196 $skey = common_mime_type_match($type, $sprefs);
1198 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1204 $besttype = 'text/html';
1206 foreach(array_keys($combine) as $type) {
1207 if($combine[$type] > $bestq) {
1209 $bestq = $combine[$type];
1213 if ('text/html' === $besttype) {
1214 return "text/html; charset=utf-8";
1219 function common_config($main, $sub)
1222 return (array_key_exists($main, $config) &&
1223 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1226 function common_copy_args($from)
1229 $strip = get_magic_quotes_gpc();
1230 foreach ($from as $k => $v) {
1231 $to[$k] = ($strip) ? stripslashes($v) : $v;
1236 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1237 // This is used before handing a request off to OAuthRequest::from_request.
1238 function common_remove_magic_from_request()
1240 if(get_magic_quotes_gpc()) {
1241 $_POST=array_map('stripslashes',$_POST);
1242 $_GET=array_map('stripslashes',$_GET);
1246 function common_user_uri(&$user)
1248 return common_local_url('userbyid', array('id' => $user->id));
1251 function common_notice_uri(&$notice)
1253 return common_local_url('shownotice',
1254 array('notice' => $notice->id));
1257 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1259 function common_confirmation_code($bits)
1261 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1262 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1263 $chars = ceil($bits/5);
1265 for ($i = 0; $i < $chars; $i++) {
1266 // XXX: convert to string and back
1267 $num = hexdec(common_good_rand(1));
1268 // XXX: randomness is too precious to throw away almost
1269 // 40% of the bits we get!
1270 $code .= $codechars[$num%32];
1275 // convert markup to HTML
1277 function common_markup_to_html($c)
1279 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1280 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1281 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1282 return Markdown($c);
1285 function common_profile_uri($profile)
1290 $user = User::staticGet($profile->id);
1295 $remote = Remote_profile::staticGet($profile->id);
1297 return $remote->uri;
1299 // XXX: this is a very bad profile!
1303 function common_canonical_sms($sms)
1306 preg_replace('/\D/', '', $sms);
1310 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1315 case E_COMPILE_ERROR:
1319 case E_RECOVERABLE_ERROR:
1320 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1325 case E_COMPILE_WARNING:
1326 case E_CORE_WARNING:
1327 case E_USER_WARNING:
1328 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1333 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1338 case E_USER_DEPRECATED:
1339 // XXX: config variable to log this stuff, too
1343 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1348 // FIXME: show error page if we're on the Web
1349 /* Don't execute PHP internal error handler */
1353 function common_session_token()
1355 common_ensure_session();
1356 if (!array_key_exists('token', $_SESSION)) {
1357 $_SESSION['token'] = common_good_rand(64);
1359 return $_SESSION['token'];
1362 function common_cache_key($extra)
1364 $base_key = common_config('memcached', 'base');
1366 if (empty($base_key)) {
1367 $base_key = common_keyize(common_config('site', 'name'));
1370 return 'statusnet:' . $base_key . ':' . $extra;
1373 function common_keyize($str)
1375 $str = strtolower($str);
1376 $str = preg_replace('/\s/', '_', $str);
1380 function common_memcache()
1382 static $cache = null;
1383 if (!common_config('memcached', 'enabled')) {
1387 $cache = new Memcache();
1388 $servers = common_config('memcached', 'server');
1389 if (is_array($servers)) {
1390 foreach($servers as $server) {
1391 $cache->addServer($server);
1394 $cache->addServer($servers);
1401 function common_license_terms($uri)
1403 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1404 return explode('-',$matches[1]);
1409 function common_compatible_license($from, $to)
1411 $from_terms = common_license_terms($from);
1412 // public domain and cc-by are compatible with everything
1413 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1416 $to_terms = common_license_terms($to);
1417 // sa is compatible across versions. IANAL
1418 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1419 return count(array_diff($from_terms, $to_terms)) == 0;
1421 // XXX: better compatibility check needed here!
1422 // Should at least normalise URIs
1423 return ($from == $to);
1427 * returns a quoted table name, if required according to config
1429 function common_database_tablename($tablename)
1432 if(common_config('db','quote_identifiers')) {
1433 $tablename = '"'. $tablename .'"';
1435 //table prefixes could be added here later
1439 function common_shorten_url($long_url)
1441 $user = common_current_user();
1443 // common current user does not find a user when called from the XMPP daemon
1444 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1447 $svc = $user->urlshorteningservice;
1449 global $_shorteners;
1450 if (!isset($_shorteners[$svc])) {
1451 //the user selected service doesn't exist, so default to ur1.ca
1454 if (!isset($_shorteners[$svc])) {
1455 // no shortener plugins installed.
1459 $reflectionObj = new ReflectionClass($_shorteners[$svc]['callInfo'][0]);
1460 $short_url_service = $reflectionObj->newInstanceArgs($_shorteners[$svc]['callInfo'][1]);
1461 $short_url = $short_url_service->shorten($long_url);
1466 function common_client_ip()
1468 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1472 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1473 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1474 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1476 $proxy = $_SERVER['REMOTE_ADDR'];
1478 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1481 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1482 $ip = $_SERVER['HTTP_CLIENT_IP'];
1484 $ip = $_SERVER['REMOTE_ADDR'];
1488 return array($proxy, $ip);