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 common_ensure_session();
200 $_SESSION['userid'] = $user->id;
207 function common_set_cookie($key, $value, $expiration=0)
209 $path = common_config('site', 'path');
210 $server = common_config('site', 'server');
212 if ($path && ($path != '/')) {
213 $cookiepath = '/' . $path . '/';
217 return setcookie($key,
224 define('REMEMBERME', 'rememberme');
225 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
227 function common_rememberme($user=null)
230 $user = common_current_user();
232 common_debug('No current user to remember', __FILE__);
237 $rm = new Remember_me();
239 $rm->code = common_good_rand(16);
240 $rm->user_id = $user->id;
242 // Wrap the insert in some good ol' fashioned transaction code
246 $result = $rm->insert();
249 common_log_db_error($rm, 'INSERT', __FILE__);
250 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
254 $rm->query('COMMIT');
256 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
258 $cookieval = $rm->user_id . ':' . $rm->code;
260 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
262 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
267 function common_remembered_user()
272 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
278 list($id, $code) = explode(':', $packed);
280 if (!$id || !$code) {
281 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
286 $rm = Remember_me::staticGet($code);
289 common_log(LOG_WARNING, 'No such remember code: ' . $code);
294 if ($rm->user_id != $id) {
295 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
300 $user = User::staticGet($rm->user_id);
303 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
309 $result = $rm->delete();
312 common_log_db_error($rm, 'DELETE', __FILE__);
313 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
318 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
320 common_set_user($user);
321 common_real_login(false);
323 // We issue a new cookie, so they can log in
324 // automatically again after this session
326 common_rememberme($user);
331 // must be called with a valid user!
333 function common_forgetme()
335 common_set_cookie(REMEMBERME, '', 0);
338 // who is the current user?
339 function common_current_user()
343 if (!_have_config()) {
347 if ($_cur === false) {
349 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
350 common_ensure_session();
351 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
353 $_cur = User::staticGet($id);
358 // that didn't work; try to remember; will init $_cur to null on failure
359 $_cur = common_remembered_user();
362 common_debug("Got User " . $_cur->nickname);
363 common_debug("Faking session on remembered user");
364 // XXX: Is this necessary?
365 $_SESSION['userid'] = $_cur->id;
372 // Logins that are 'remembered' aren't 'real' -- they're subject to
373 // cookie-stealing. So, we don't let them do certain things. New reg,
374 // OpenID, and password logins _are_ real.
376 function common_real_login($real=true)
378 common_ensure_session();
379 $_SESSION['real_login'] = $real;
382 function common_is_real_login()
384 return common_logged_in() && $_SESSION['real_login'];
387 // get canonical version of nickname for comparison
388 function common_canonical_nickname($nickname)
390 // XXX: UTF-8 canonicalization (like combining chars)
391 return strtolower($nickname);
394 // get canonical version of email for comparison
395 function common_canonical_email($email)
397 // XXX: canonicalize UTF-8
398 // XXX: lcase the domain part
402 function common_render_content($text, $notice)
404 $r = common_render_text($text);
405 $id = $notice->profile_id;
406 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
407 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
408 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
409 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
413 function common_render_text($text)
415 $r = htmlspecialchars($text);
417 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
418 $r = common_replace_urls_callback($r, 'common_linkify');
419 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
424 function common_replace_urls_callback($text, $callback, $notice_id = null) {
425 // Start off with a regex
427 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
430 '(?:'. //Known protocols
432 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
434 '(?:(?:mailto|aim|tel|xmpp):)'.
436 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
439 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
441 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
445 '|(?:(?: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
447 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
449 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
450 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
451 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
452 '(?: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)'.
456 '(?:\:\d+)?'. //:port
457 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
458 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
459 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
460 ')(?<![\?\.\,\#\,])'.
463 //preg_match_all($regex,$text,$matches);
465 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
468 function callback_helper($matches, $callback, $notice_id) {
470 $left = strpos($matches[0],$url);
471 $right = $left+strlen($url);
473 $groupSymbolSets=array(
491 $cannotEndWith=array('.','?',',','#');
495 foreach($groupSymbolSets as $groupSymbolSet){
496 if(substr($url,-1)==$groupSymbolSet['right']){
497 $group_left_count = substr_count($url,$groupSymbolSet['left']);
498 $group_right_count = substr_count($url,$groupSymbolSet['right']);
499 if($group_left_count<$group_right_count){
501 $url=substr($url,0,-1);
505 if(in_array(substr($url,-1),$cannotEndWith)){
507 $url=substr($url,0,-1);
509 }while($original_url!=$url);
511 if(empty($notice_id)){
512 $result = call_user_func_array($callback, array($url));
514 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
516 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
519 function curry($fn) {
520 //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
521 $args = func_get_args();
523 $id = uniqid('_partial');
524 $GLOBALS[$id] = array($fn, $args);
525 return create_function('',
526 '$args = func_get_args(); '.
527 'return call_user_func_array('.
528 '$GLOBALS["'.$id.'"][0],'.
531 '$GLOBALS["'.$id.'"][1]));');
534 function common_linkify($url) {
535 // It comes in special'd, so we unspecial it before passing to the stringifying
537 $url = htmlspecialchars_decode($url);
539 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
540 //url is an email address without the mailto: protocol
541 $canon = "mailto:$url";
542 $longurl = "mailto:$url";
545 $canon = File_redirection::_canonUrl($url);
547 $longurl_data = File_redirection::where($canon);
548 if (is_array($longurl_data)) {
549 $longurl = $longurl_data['url'];
550 } elseif (is_string($longurl_data)) {
551 $longurl = $longurl_data;
553 throw new ServerException("Can't linkify url '$url'");
556 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
558 $is_attachment = false;
559 $attachment_id = null;
562 // Check to see whether this is a known "attachment" URL.
564 $f = File::staticGet('url', $longurl);
567 // XXX: this writes to the database. :<
568 $f = File::processNew($longurl);
572 if ($f->isEnclosure()) {
573 $is_attachment = true;
574 $attachment_id = $f->id;
576 $foe = File_oembed::staticGet('file_id', $f->id);
578 // if it has OEmbed info, it's an attachment, too
579 $is_attachment = true;
580 $attachment_id = $f->id;
582 $thumb = File_thumbnail::staticGet('file_id', $f->id);
583 if (!empty($thumb)) {
591 if ($is_attachment) {
592 $attrs['class'] = 'attachment';
594 $attrs['class'] = 'attachment thumbnail';
596 $attrs['id'] = "attachment-{$attachment_id}";
599 return XMLStringer::estring('a', $attrs, $url);
602 function common_shorten_links($text)
604 $maxLength = Notice::maxContent();
605 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
606 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
609 function common_xml_safe_str($str)
611 // Neutralize control codes and surrogates
612 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
615 function common_tag_link($tag)
617 $canonical = common_canonical_tag($tag);
618 $url = common_local_url('tag', array('tag' => $canonical));
619 $xs = new XMLStringer();
620 $xs->elementStart('span', 'tag');
621 $xs->element('a', array('href' => $url,
624 $xs->elementEnd('span');
625 return $xs->getString();
628 function common_canonical_tag($tag)
630 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
631 return str_replace(array('-', '_', '.'), '', $tag);
634 function common_valid_profile_tag($str)
636 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
639 function common_at_link($sender_id, $nickname)
641 $sender = Profile::staticGet($sender_id);
642 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
644 $user = User::staticGet('id', $recipient->id);
646 $url = common_local_url('userbyid', array('id' => $user->id));
648 $url = $recipient->profileurl;
650 $xs = new XMLStringer(false);
651 $attrs = array('href' => $url,
653 if (!empty($recipient->fullname)) {
654 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
656 $xs->elementStart('span', 'vcard');
657 $xs->elementStart('a', $attrs);
658 $xs->element('span', 'fn nickname', $nickname);
659 $xs->elementEnd('a');
660 $xs->elementEnd('span');
661 return $xs->getString();
667 function common_group_link($sender_id, $nickname)
669 $sender = Profile::staticGet($sender_id);
670 $group = User_group::getForNickname($nickname);
671 if ($group && $sender->isMember($group)) {
672 $attrs = array('href' => $group->permalink(),
674 if (!empty($group->fullname)) {
675 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
677 $xs = new XMLStringer();
678 $xs->elementStart('span', 'vcard');
679 $xs->elementStart('a', $attrs);
680 $xs->element('span', 'fn nickname', $nickname);
681 $xs->elementEnd('a');
682 $xs->elementEnd('span');
683 return $xs->getString();
689 function common_at_hash_link($sender_id, $tag)
691 $user = User::staticGet($sender_id);
695 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
697 $url = common_local_url('subscriptions',
698 array('nickname' => $user->nickname,
700 $xs = new XMLStringer();
701 $xs->elementStart('span', 'tag');
702 $xs->element('a', array('href' => $url,
705 $xs->elementEnd('span');
706 return $xs->getString();
712 function common_relative_profile($sender, $nickname, $dt=null)
714 // Try to find profiles this profile is subscribed to that have this nickname
715 $recipient = new Profile();
716 // XXX: use a join instead of a subquery
717 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
718 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
719 if ($recipient->find(true)) {
720 // XXX: should probably differentiate between profiles with
721 // the same name by date of most recent update
724 // Try to find profiles that listen to this profile and that have this nickname
725 $recipient = new Profile();
726 // XXX: use a join instead of a subquery
727 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
728 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
729 if ($recipient->find(true)) {
730 // XXX: should probably differentiate between profiles with
731 // the same name by date of most recent update
734 // If this is a local user, try to find a local user with that nickname.
735 $sender = User::staticGet($sender->id);
737 $recipient_user = User::staticGet('nickname', $nickname);
738 if ($recipient_user) {
739 return $recipient_user->getProfile();
742 // Otherwise, no links. @messages from local users to remote users,
743 // or from remote users to other remote users, are just
744 // outside our ability to make intelligent guesses about
748 function common_local_url($action, $args=null, $params=null, $fragment=null)
751 $path = $r->build($action, $args, $params, $fragment);
753 $ssl = common_is_sensitive($action);
755 if (common_config('site','fancy')) {
756 $url = common_path(mb_substr($path, 1), $ssl);
758 if (mb_strpos($path, '/index.php') === 0) {
759 $url = common_path(mb_substr($path, 1), $ssl);
761 $url = common_path('index.php'.$path, $ssl);
767 function common_is_sensitive($action)
769 static $sensitive = array('login', 'register', 'passwordsettings',
770 'twittersettings', 'api');
773 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
774 $ssl = in_array($action, $sensitive);
780 function common_path($relative, $ssl=false)
782 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
784 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
785 || common_config('site', 'ssl') === 'always') {
787 if (is_string(common_config('site', 'sslserver')) &&
788 mb_strlen(common_config('site', 'sslserver')) > 0) {
789 $serverpart = common_config('site', 'sslserver');
790 } else if (common_config('site', 'server')) {
791 $serverpart = common_config('site', 'server');
793 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
797 if (common_config('site', 'server')) {
798 $serverpart = common_config('site', 'server');
800 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
804 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
807 function common_date_string($dt)
809 // XXX: do some sexy date formatting
810 // return date(DATE_RFC822, $dt);
815 if ($now < $t) { // that shouldn't happen!
816 return common_exact_date($dt);
817 } else if ($diff < 60) {
818 return _('a few seconds ago');
819 } else if ($diff < 92) {
820 return _('about a minute ago');
821 } else if ($diff < 3300) {
822 return sprintf(_('about %d minutes ago'), round($diff/60));
823 } else if ($diff < 5400) {
824 return _('about an hour ago');
825 } else if ($diff < 22 * 3600) {
826 return sprintf(_('about %d hours ago'), round($diff/3600));
827 } else if ($diff < 37 * 3600) {
828 return _('about a day ago');
829 } else if ($diff < 24 * 24 * 3600) {
830 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
831 } else if ($diff < 46 * 24 * 3600) {
832 return _('about a month ago');
833 } else if ($diff < 330 * 24 * 3600) {
834 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
835 } else if ($diff < 480 * 24 * 3600) {
836 return _('about a year ago');
838 return common_exact_date($dt);
842 function common_exact_date($dt)
848 $_utc = new DateTimeZone('UTC');
849 $_siteTz = new DateTimeZone(common_timezone());
852 $dateStr = date('d F Y H:i:s', strtotime($dt));
853 $d = new DateTime($dateStr, $_utc);
854 $d->setTimezone($_siteTz);
855 return $d->format(DATE_RFC850);
858 function common_date_w3dtf($dt)
860 $dateStr = date('d F Y H:i:s', strtotime($dt));
861 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
862 $d->setTimezone(new DateTimeZone(common_timezone()));
863 return $d->format(DATE_W3C);
866 function common_date_rfc2822($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('r');
874 function common_date_iso8601($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('c');
882 function common_sql_now()
884 return common_sql_date(time());
887 function common_sql_date($datetime)
889 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
892 function common_redirect($url, $code=307)
894 static $status = array(301 => "Moved Permanently",
897 307 => "Temporary Redirect");
899 header('HTTP/1.1 '.$code.' '.$status[$code]);
900 header("Location: $url");
902 $xo = new XMLOutputter();
904 '-//W3C//DTD XHTML 1.0 Strict//EN',
905 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
906 $xo->element('a', array('href' => $url), $url);
911 function common_broadcast_notice($notice, $remote=false)
913 return common_enqueue_notice($notice);
916 // Stick the notice on the queue
918 function common_enqueue_notice($notice)
920 static $localTransports = array('omb',
923 static $allTransports = array('sms', 'plugin');
925 $transports = $allTransports;
927 $xmpp = common_config('xmpp', 'enabled');
930 $transports[] = 'jabber';
933 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
934 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
935 $transports = array_merge($transports, $localTransports);
937 $transports[] = 'public';
941 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
943 $qm = QueueManager::get();
945 foreach ($transports as $transport)
947 $qm->enqueue($notice, $transport);
950 Event::handle('EndEnqueueNotice', array($notice, $transports));
956 function common_broadcast_profile($profile)
958 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
959 require_once(INSTALLDIR.'/lib/omb.php');
960 omb_broadcast_profile($profile);
961 // XXX: Other broadcasts...?
965 function common_profile_url($nickname)
967 return common_local_url('showstream', array('nickname' => $nickname));
970 // Should make up a reasonable root URL
972 function common_root_url($ssl=false)
974 return common_path('', $ssl);
977 // returns $bytes bytes of random data as a hexadecimal string
978 // "good" here is a goal and not a guarantee
980 function common_good_rand($bytes)
982 // XXX: use random.org...?
983 if (@file_exists('/dev/urandom')) {
984 return common_urandom($bytes);
985 } else { // FIXME: this is probably not good enough
986 return common_mtrand($bytes);
990 function common_urandom($bytes)
992 $h = fopen('/dev/urandom', 'rb');
994 $src = fread($h, $bytes);
997 for ($i = 0; $i < $bytes; $i++) {
998 $enc .= sprintf("%02x", (ord($src[$i])));
1003 function common_mtrand($bytes)
1006 for ($i = 0; $i < $bytes; $i++) {
1007 $enc .= sprintf("%02x", mt_rand(0, 255));
1012 function common_set_returnto($url)
1014 common_ensure_session();
1015 $_SESSION['returnto'] = $url;
1018 function common_get_returnto()
1020 common_ensure_session();
1021 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1024 function common_timestamp()
1026 return date('YmdHis');
1029 function common_ensure_syslog()
1031 static $initialized = false;
1032 if (!$initialized) {
1033 openlog(common_config('syslog', 'appname'), 0,
1034 common_config('syslog', 'facility'));
1035 $initialized = true;
1039 function common_log_line($priority, $msg)
1041 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1042 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1043 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1046 function common_log($priority, $msg, $filename=null)
1048 $logfile = common_config('site', 'logfile');
1050 $log = fopen($logfile, "a");
1052 $output = common_log_line($priority, $msg);
1053 fwrite($log, $output);
1057 common_ensure_syslog();
1058 syslog($priority, $msg);
1062 function common_debug($msg, $filename=null)
1065 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1067 common_log(LOG_DEBUG, $msg);
1071 function common_log_db_error(&$object, $verb, $filename=null)
1073 $objstr = common_log_objstring($object);
1074 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1075 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1078 function common_log_objstring(&$object)
1080 if (is_null($object)) {
1083 if (!($object instanceof DB_DataObject)) {
1086 $arr = $object->toArray();
1088 foreach ($arr as $k => $v) {
1089 if (is_object($v)) {
1090 $fields[] = "$k='".get_class($v)."'";
1092 $fields[] = "$k='$v'";
1095 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1099 function common_valid_http_url($url)
1101 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1104 function common_valid_tag($tag)
1106 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1107 return (Validate::email($matches[1]) ||
1108 preg_match('/^([\w-\.]+)$/', $matches[1]));
1113 /* Following functions are copied from MediaWiki GlobalFunctions.php
1114 * and written by Evan Prodromou. */
1116 function common_accept_to_prefs($accept, $def = '*/*')
1118 // No arg means accept anything (per HTTP spec)
1120 return array($def => 1);
1125 $parts = explode(',', $accept);
1127 foreach($parts as $part) {
1128 // FIXME: doesn't deal with params like 'text/html; level=1'
1129 @list($value, $qpart) = explode(';', trim($part));
1131 if(!isset($qpart)) {
1133 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1134 $prefs[$value] = $match[1];
1141 function common_mime_type_match($type, $avail)
1143 if(array_key_exists($type, $avail)) {
1146 $parts = explode('/', $type);
1147 if(array_key_exists($parts[0] . '/*', $avail)) {
1148 return $parts[0] . '/*';
1149 } elseif(array_key_exists('*/*', $avail)) {
1157 function common_negotiate_type($cprefs, $sprefs)
1161 foreach(array_keys($sprefs) as $type) {
1162 $parts = explode('/', $type);
1163 if($parts[1] != '*') {
1164 $ckey = common_mime_type_match($type, $cprefs);
1166 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1171 foreach(array_keys($cprefs) as $type) {
1172 $parts = explode('/', $type);
1173 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1174 $skey = common_mime_type_match($type, $sprefs);
1176 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1182 $besttype = 'text/html';
1184 foreach(array_keys($combine) as $type) {
1185 if($combine[$type] > $bestq) {
1187 $bestq = $combine[$type];
1191 if ('text/html' === $besttype) {
1192 return "text/html; charset=utf-8";
1197 function common_config($main, $sub)
1200 return (array_key_exists($main, $config) &&
1201 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1204 function common_copy_args($from)
1207 $strip = get_magic_quotes_gpc();
1208 foreach ($from as $k => $v) {
1209 $to[$k] = ($strip) ? stripslashes($v) : $v;
1214 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1215 // This is used before handing a request off to OAuthRequest::from_request.
1216 function common_remove_magic_from_request()
1218 if(get_magic_quotes_gpc()) {
1219 $_POST=array_map('stripslashes',$_POST);
1220 $_GET=array_map('stripslashes',$_GET);
1224 function common_user_uri(&$user)
1226 return common_local_url('userbyid', array('id' => $user->id));
1229 function common_notice_uri(&$notice)
1231 return common_local_url('shownotice',
1232 array('notice' => $notice->id));
1235 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1237 function common_confirmation_code($bits)
1239 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1240 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1241 $chars = ceil($bits/5);
1243 for ($i = 0; $i < $chars; $i++) {
1244 // XXX: convert to string and back
1245 $num = hexdec(common_good_rand(1));
1246 // XXX: randomness is too precious to throw away almost
1247 // 40% of the bits we get!
1248 $code .= $codechars[$num%32];
1253 // convert markup to HTML
1255 function common_markup_to_html($c)
1257 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1258 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1259 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1260 return Markdown($c);
1263 function common_profile_uri($profile)
1268 $user = User::staticGet($profile->id);
1273 $remote = Remote_profile::staticGet($profile->id);
1275 return $remote->uri;
1277 // XXX: this is a very bad profile!
1281 function common_canonical_sms($sms)
1284 preg_replace('/\D/', '', $sms);
1288 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1293 case E_COMPILE_ERROR:
1297 case E_RECOVERABLE_ERROR:
1298 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1303 case E_COMPILE_WARNING:
1304 case E_CORE_WARNING:
1305 case E_USER_WARNING:
1306 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1311 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1316 case E_USER_DEPRECATED:
1317 // XXX: config variable to log this stuff, too
1321 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1326 // FIXME: show error page if we're on the Web
1327 /* Don't execute PHP internal error handler */
1331 function common_session_token()
1333 common_ensure_session();
1334 if (!array_key_exists('token', $_SESSION)) {
1335 $_SESSION['token'] = common_good_rand(64);
1337 return $_SESSION['token'];
1340 function common_cache_key($extra)
1342 $base_key = common_config('memcached', 'base');
1344 if (empty($base_key)) {
1345 $base_key = common_keyize(common_config('site', 'name'));
1348 return 'statusnet:' . $base_key . ':' . $extra;
1351 function common_keyize($str)
1353 $str = strtolower($str);
1354 $str = preg_replace('/\s/', '_', $str);
1358 function common_memcache()
1360 static $cache = null;
1361 if (!common_config('memcached', 'enabled')) {
1365 $cache = new Memcache();
1366 $servers = common_config('memcached', 'server');
1367 if (is_array($servers)) {
1368 foreach($servers as $server) {
1369 $cache->addServer($server);
1372 $cache->addServer($servers);
1379 function common_license_terms($uri)
1381 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1382 return explode('-',$matches[1]);
1387 function common_compatible_license($from, $to)
1389 $from_terms = common_license_terms($from);
1390 // public domain and cc-by are compatible with everything
1391 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1394 $to_terms = common_license_terms($to);
1395 // sa is compatible across versions. IANAL
1396 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1397 return count(array_diff($from_terms, $to_terms)) == 0;
1399 // XXX: better compatibility check needed here!
1400 // Should at least normalise URIs
1401 return ($from == $to);
1405 * returns a quoted table name, if required according to config
1407 function common_database_tablename($tablename)
1410 if(common_config('db','quote_identifiers')) {
1411 $tablename = '"'. $tablename .'"';
1413 //table prefixes could be added here later
1417 function common_shorten_url($long_url)
1419 $user = common_current_user();
1421 // common current user does not find a user when called from the XMPP daemon
1422 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1425 $svc = $user->urlshorteningservice;
1427 global $_shorteners;
1428 if (!isset($_shorteners[$svc])) {
1429 //the user selected service doesn't exist, so default to ur1.ca
1432 if (!isset($_shorteners[$svc])) {
1433 // no shortener plugins installed.
1437 $reflectionObj = new ReflectionClass($_shorteners[$svc]['callInfo'][0]);
1438 $short_url_service = $reflectionObj->newInstanceArgs($_shorteners[$svc]['callInfo'][1]);
1439 $short_url = $short_url_service->shorten($long_url);
1444 function common_client_ip()
1446 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1450 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1451 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1452 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1454 $proxy = $_SERVER['REMOTE_ADDR'];
1456 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1459 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1460 $ip = $_SERVER['HTTP_CLIENT_IP'];
1462 $ip = $_SERVER['REMOTE_ADDR'];
1466 return array($proxy, $ip);