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 $user = User::staticGet($id);
361 // that didn't work; try to remember; will init $_cur to null on failure
362 $_cur = common_remembered_user();
365 common_debug("Got User " . $_cur->nickname);
366 common_debug("Faking session on remembered user");
367 // XXX: Is this necessary?
368 $_SESSION['userid'] = $_cur->id;
375 // Logins that are 'remembered' aren't 'real' -- they're subject to
376 // cookie-stealing. So, we don't let them do certain things. New reg,
377 // OpenID, and password logins _are_ real.
379 function common_real_login($real=true)
381 common_ensure_session();
382 $_SESSION['real_login'] = $real;
385 function common_is_real_login()
387 return common_logged_in() && $_SESSION['real_login'];
390 // get canonical version of nickname for comparison
391 function common_canonical_nickname($nickname)
393 // XXX: UTF-8 canonicalization (like combining chars)
394 return strtolower($nickname);
397 // get canonical version of email for comparison
398 function common_canonical_email($email)
400 // XXX: canonicalize UTF-8
401 // XXX: lcase the domain part
405 function common_render_content($text, $notice)
407 $r = common_render_text($text);
408 $id = $notice->profile_id;
409 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
410 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
411 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
412 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
416 function common_render_text($text)
418 $r = htmlspecialchars($text);
420 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
421 $r = common_replace_urls_callback($r, 'common_linkify');
422 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
427 function common_replace_urls_callback($text, $callback, $notice_id = null) {
428 // Start off with a regex
430 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
433 '(?:'. //Known protocols
435 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
437 '(?:(?:mailto|aim|tel|xmpp):)'.
439 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
442 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
444 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
448 '|(?:(?: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
450 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
452 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
453 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
454 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
455 '(?: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)'.
459 '(?:\:\d+)?'. //:port
460 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
461 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
462 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
463 ')(?<![\?\.\,\#\,])'.
466 //preg_match_all($regex,$text,$matches);
468 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
471 function callback_helper($matches, $callback, $notice_id) {
473 $left = strpos($matches[0],$url);
474 $right = $left+strlen($url);
476 $groupSymbolSets=array(
494 $cannotEndWith=array('.','?',',','#');
498 foreach($groupSymbolSets as $groupSymbolSet){
499 if(substr($url,-1)==$groupSymbolSet['right']){
500 $group_left_count = substr_count($url,$groupSymbolSet['left']);
501 $group_right_count = substr_count($url,$groupSymbolSet['right']);
502 if($group_left_count<$group_right_count){
504 $url=substr($url,0,-1);
508 if(in_array(substr($url,-1),$cannotEndWith)){
510 $url=substr($url,0,-1);
512 }while($original_url!=$url);
514 if(empty($notice_id)){
515 $result = call_user_func_array($callback, array($url));
517 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
519 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
522 function curry($fn) {
523 //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
524 $args = func_get_args();
526 $id = uniqid('_partial');
527 $GLOBALS[$id] = array($fn, $args);
528 return create_function('',
529 '$args = func_get_args(); '.
530 'return call_user_func_array('.
531 '$GLOBALS["'.$id.'"][0],'.
534 '$GLOBALS["'.$id.'"][1]));');
537 function common_linkify($url) {
538 // It comes in special'd, so we unspecial it before passing to the stringifying
540 $url = htmlspecialchars_decode($url);
542 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
543 //url is an email address without the mailto: protocol
544 $canon = "mailto:$url";
545 $longurl = "mailto:$url";
548 $canon = File_redirection::_canonUrl($url);
550 $longurl_data = File_redirection::where($canon);
551 if (is_array($longurl_data)) {
552 $longurl = $longurl_data['url'];
553 } elseif (is_string($longurl_data)) {
554 $longurl = $longurl_data;
556 throw new ServerException("Can't linkify url '$url'");
559 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
561 $is_attachment = false;
562 $attachment_id = null;
565 // Check to see whether this is a known "attachment" URL.
567 $f = File::staticGet('url', $longurl);
570 // XXX: this writes to the database. :<
571 $f = File::processNew($longurl);
575 if ($f->isEnclosure()) {
576 $is_attachment = true;
577 $attachment_id = $f->id;
579 $foe = File_oembed::staticGet('file_id', $f->id);
581 // if it has OEmbed info, it's an attachment, too
582 $is_attachment = true;
583 $attachment_id = $f->id;
585 $thumb = File_thumbnail::staticGet('file_id', $f->id);
586 if (!empty($thumb)) {
594 if ($is_attachment) {
595 $attrs['class'] = 'attachment';
597 $attrs['class'] = 'attachment thumbnail';
599 $attrs['id'] = "attachment-{$attachment_id}";
602 return XMLStringer::estring('a', $attrs, $url);
605 function common_shorten_links($text)
607 $maxLength = Notice::maxContent();
608 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
609 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
612 function common_xml_safe_str($str)
614 // Neutralize control codes and surrogates
615 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
618 function common_tag_link($tag)
620 $canonical = common_canonical_tag($tag);
621 $url = common_local_url('tag', array('tag' => $canonical));
622 $xs = new XMLStringer();
623 $xs->elementStart('span', 'tag');
624 $xs->element('a', array('href' => $url,
627 $xs->elementEnd('span');
628 return $xs->getString();
631 function common_canonical_tag($tag)
633 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
634 return str_replace(array('-', '_', '.'), '', $tag);
637 function common_valid_profile_tag($str)
639 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
642 function common_at_link($sender_id, $nickname)
644 $sender = Profile::staticGet($sender_id);
645 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
647 $user = User::staticGet('id', $recipient->id);
649 $url = common_local_url('userbyid', array('id' => $user->id));
651 $url = $recipient->profileurl;
653 $xs = new XMLStringer(false);
654 $attrs = array('href' => $url,
656 if (!empty($recipient->fullname)) {
657 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
659 $xs->elementStart('span', 'vcard');
660 $xs->elementStart('a', $attrs);
661 $xs->element('span', 'fn nickname', $nickname);
662 $xs->elementEnd('a');
663 $xs->elementEnd('span');
664 return $xs->getString();
670 function common_group_link($sender_id, $nickname)
672 $sender = Profile::staticGet($sender_id);
673 $group = User_group::getForNickname($nickname);
674 if ($group && $sender->isMember($group)) {
675 $attrs = array('href' => $group->permalink(),
677 if (!empty($group->fullname)) {
678 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
680 $xs = new XMLStringer();
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_at_hash_link($sender_id, $tag)
694 $user = User::staticGet($sender_id);
698 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
700 $url = common_local_url('subscriptions',
701 array('nickname' => $user->nickname,
703 $xs = new XMLStringer();
704 $xs->elementStart('span', 'tag');
705 $xs->element('a', array('href' => $url,
708 $xs->elementEnd('span');
709 return $xs->getString();
715 function common_relative_profile($sender, $nickname, $dt=null)
717 // Try to find profiles this profile is subscribed to that have this nickname
718 $recipient = new Profile();
719 // XXX: use a join instead of a subquery
720 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
721 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
722 if ($recipient->find(true)) {
723 // XXX: should probably differentiate between profiles with
724 // the same name by date of most recent update
727 // Try to find profiles that listen to this profile and that have this nickname
728 $recipient = new Profile();
729 // XXX: use a join instead of a subquery
730 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
731 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
732 if ($recipient->find(true)) {
733 // XXX: should probably differentiate between profiles with
734 // the same name by date of most recent update
737 // If this is a local user, try to find a local user with that nickname.
738 $sender = User::staticGet($sender->id);
740 $recipient_user = User::staticGet('nickname', $nickname);
741 if ($recipient_user) {
742 return $recipient_user->getProfile();
745 // Otherwise, no links. @messages from local users to remote users,
746 // or from remote users to other remote users, are just
747 // outside our ability to make intelligent guesses about
751 function common_local_url($action, $args=null, $params=null, $fragment=null)
754 $path = $r->build($action, $args, $params, $fragment);
756 $ssl = common_is_sensitive($action);
758 if (common_config('site','fancy')) {
759 $url = common_path(mb_substr($path, 1), $ssl);
761 if (mb_strpos($path, '/index.php') === 0) {
762 $url = common_path(mb_substr($path, 1), $ssl);
764 $url = common_path('index.php'.$path, $ssl);
770 function common_is_sensitive($action)
772 static $sensitive = array('login', 'register', 'passwordsettings',
773 'twittersettings', 'api');
776 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
777 $ssl = in_array($action, $sensitive);
783 function common_path($relative, $ssl=false)
785 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
787 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
788 || common_config('site', 'ssl') === 'always') {
790 if (is_string(common_config('site', 'sslserver')) &&
791 mb_strlen(common_config('site', 'sslserver')) > 0) {
792 $serverpart = common_config('site', 'sslserver');
793 } else if (common_config('site', 'server')) {
794 $serverpart = common_config('site', 'server');
796 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
800 if (common_config('site', 'server')) {
801 $serverpart = common_config('site', 'server');
803 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
807 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
810 function common_date_string($dt)
812 // XXX: do some sexy date formatting
813 // return date(DATE_RFC822, $dt);
818 if ($now < $t) { // that shouldn't happen!
819 return common_exact_date($dt);
820 } else if ($diff < 60) {
821 return _('a few seconds ago');
822 } else if ($diff < 92) {
823 return _('about a minute ago');
824 } else if ($diff < 3300) {
825 return sprintf(_('about %d minutes ago'), round($diff/60));
826 } else if ($diff < 5400) {
827 return _('about an hour ago');
828 } else if ($diff < 22 * 3600) {
829 return sprintf(_('about %d hours ago'), round($diff/3600));
830 } else if ($diff < 37 * 3600) {
831 return _('about a day ago');
832 } else if ($diff < 24 * 24 * 3600) {
833 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
834 } else if ($diff < 46 * 24 * 3600) {
835 return _('about a month ago');
836 } else if ($diff < 330 * 24 * 3600) {
837 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
838 } else if ($diff < 480 * 24 * 3600) {
839 return _('about a year ago');
841 return common_exact_date($dt);
845 function common_exact_date($dt)
851 $_utc = new DateTimeZone('UTC');
852 $_siteTz = new DateTimeZone(common_timezone());
855 $dateStr = date('d F Y H:i:s', strtotime($dt));
856 $d = new DateTime($dateStr, $_utc);
857 $d->setTimezone($_siteTz);
858 return $d->format(DATE_RFC850);
861 function common_date_w3dtf($dt)
863 $dateStr = date('d F Y H:i:s', strtotime($dt));
864 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
865 $d->setTimezone(new DateTimeZone(common_timezone()));
866 return $d->format(DATE_W3C);
869 function common_date_rfc2822($dt)
871 $dateStr = date('d F Y H:i:s', strtotime($dt));
872 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
873 $d->setTimezone(new DateTimeZone(common_timezone()));
874 return $d->format('r');
877 function common_date_iso8601($dt)
879 $dateStr = date('d F Y H:i:s', strtotime($dt));
880 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
881 $d->setTimezone(new DateTimeZone(common_timezone()));
882 return $d->format('c');
885 function common_sql_now()
887 return common_sql_date(time());
890 function common_sql_date($datetime)
892 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
895 function common_redirect($url, $code=307)
897 static $status = array(301 => "Moved Permanently",
900 307 => "Temporary Redirect");
902 header('HTTP/1.1 '.$code.' '.$status[$code]);
903 header("Location: $url");
905 $xo = new XMLOutputter();
907 '-//W3C//DTD XHTML 1.0 Strict//EN',
908 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
909 $xo->element('a', array('href' => $url), $url);
914 function common_broadcast_notice($notice, $remote=false)
916 return common_enqueue_notice($notice);
919 // Stick the notice on the queue
921 function common_enqueue_notice($notice)
923 static $localTransports = array('omb',
926 static $allTransports = array('sms', 'plugin');
928 $transports = $allTransports;
930 $xmpp = common_config('xmpp', 'enabled');
933 $transports[] = 'jabber';
936 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
937 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
938 $transports = array_merge($transports, $localTransports);
940 $transports[] = 'public';
944 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
946 $qm = QueueManager::get();
948 foreach ($transports as $transport)
950 $qm->enqueue($notice, $transport);
953 Event::handle('EndEnqueueNotice', array($notice, $transports));
959 function common_broadcast_profile($profile)
961 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
962 require_once(INSTALLDIR.'/lib/omb.php');
963 omb_broadcast_profile($profile);
964 // XXX: Other broadcasts...?
968 function common_profile_url($nickname)
970 return common_local_url('showstream', array('nickname' => $nickname));
973 // Should make up a reasonable root URL
975 function common_root_url($ssl=false)
977 return common_path('', $ssl);
980 // returns $bytes bytes of random data as a hexadecimal string
981 // "good" here is a goal and not a guarantee
983 function common_good_rand($bytes)
985 // XXX: use random.org...?
986 if (@file_exists('/dev/urandom')) {
987 return common_urandom($bytes);
988 } else { // FIXME: this is probably not good enough
989 return common_mtrand($bytes);
993 function common_urandom($bytes)
995 $h = fopen('/dev/urandom', 'rb');
997 $src = fread($h, $bytes);
1000 for ($i = 0; $i < $bytes; $i++) {
1001 $enc .= sprintf("%02x", (ord($src[$i])));
1006 function common_mtrand($bytes)
1009 for ($i = 0; $i < $bytes; $i++) {
1010 $enc .= sprintf("%02x", mt_rand(0, 255));
1015 function common_set_returnto($url)
1017 common_ensure_session();
1018 $_SESSION['returnto'] = $url;
1021 function common_get_returnto()
1023 common_ensure_session();
1024 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1027 function common_timestamp()
1029 return date('YmdHis');
1032 function common_ensure_syslog()
1034 static $initialized = false;
1035 if (!$initialized) {
1036 openlog(common_config('syslog', 'appname'), 0,
1037 common_config('syslog', 'facility'));
1038 $initialized = true;
1042 function common_log_line($priority, $msg)
1044 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1045 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1046 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1049 function common_log($priority, $msg, $filename=null)
1051 $logfile = common_config('site', 'logfile');
1053 $log = fopen($logfile, "a");
1055 $output = common_log_line($priority, $msg);
1056 fwrite($log, $output);
1060 common_ensure_syslog();
1061 syslog($priority, $msg);
1065 function common_debug($msg, $filename=null)
1068 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1070 common_log(LOG_DEBUG, $msg);
1074 function common_log_db_error(&$object, $verb, $filename=null)
1076 $objstr = common_log_objstring($object);
1077 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1078 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1081 function common_log_objstring(&$object)
1083 if (is_null($object)) {
1086 if (!($object instanceof DB_DataObject)) {
1089 $arr = $object->toArray();
1091 foreach ($arr as $k => $v) {
1092 if (is_object($v)) {
1093 $fields[] = "$k='".get_class($v)."'";
1095 $fields[] = "$k='$v'";
1098 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1102 function common_valid_http_url($url)
1104 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1107 function common_valid_tag($tag)
1109 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1110 return (Validate::email($matches[1]) ||
1111 preg_match('/^([\w-\.]+)$/', $matches[1]));
1116 /* Following functions are copied from MediaWiki GlobalFunctions.php
1117 * and written by Evan Prodromou. */
1119 function common_accept_to_prefs($accept, $def = '*/*')
1121 // No arg means accept anything (per HTTP spec)
1123 return array($def => 1);
1128 $parts = explode(',', $accept);
1130 foreach($parts as $part) {
1131 // FIXME: doesn't deal with params like 'text/html; level=1'
1132 @list($value, $qpart) = explode(';', trim($part));
1134 if(!isset($qpart)) {
1136 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1137 $prefs[$value] = $match[1];
1144 function common_mime_type_match($type, $avail)
1146 if(array_key_exists($type, $avail)) {
1149 $parts = explode('/', $type);
1150 if(array_key_exists($parts[0] . '/*', $avail)) {
1151 return $parts[0] . '/*';
1152 } elseif(array_key_exists('*/*', $avail)) {
1160 function common_negotiate_type($cprefs, $sprefs)
1164 foreach(array_keys($sprefs) as $type) {
1165 $parts = explode('/', $type);
1166 if($parts[1] != '*') {
1167 $ckey = common_mime_type_match($type, $cprefs);
1169 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1174 foreach(array_keys($cprefs) as $type) {
1175 $parts = explode('/', $type);
1176 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1177 $skey = common_mime_type_match($type, $sprefs);
1179 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1185 $besttype = 'text/html';
1187 foreach(array_keys($combine) as $type) {
1188 if($combine[$type] > $bestq) {
1190 $bestq = $combine[$type];
1194 if ('text/html' === $besttype) {
1195 return "text/html; charset=utf-8";
1200 function common_config($main, $sub)
1203 return (array_key_exists($main, $config) &&
1204 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1207 function common_copy_args($from)
1210 $strip = get_magic_quotes_gpc();
1211 foreach ($from as $k => $v) {
1212 $to[$k] = ($strip) ? stripslashes($v) : $v;
1217 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1218 // This is used before handing a request off to OAuthRequest::from_request.
1219 function common_remove_magic_from_request()
1221 if(get_magic_quotes_gpc()) {
1222 $_POST=array_map('stripslashes',$_POST);
1223 $_GET=array_map('stripslashes',$_GET);
1227 function common_user_uri(&$user)
1229 return common_local_url('userbyid', array('id' => $user->id));
1232 function common_notice_uri(&$notice)
1234 return common_local_url('shownotice',
1235 array('notice' => $notice->id));
1238 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1240 function common_confirmation_code($bits)
1242 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1243 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1244 $chars = ceil($bits/5);
1246 for ($i = 0; $i < $chars; $i++) {
1247 // XXX: convert to string and back
1248 $num = hexdec(common_good_rand(1));
1249 // XXX: randomness is too precious to throw away almost
1250 // 40% of the bits we get!
1251 $code .= $codechars[$num%32];
1256 // convert markup to HTML
1258 function common_markup_to_html($c)
1260 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1261 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1262 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1263 return Markdown($c);
1266 function common_profile_uri($profile)
1271 $user = User::staticGet($profile->id);
1276 $remote = Remote_profile::staticGet($profile->id);
1278 return $remote->uri;
1280 // XXX: this is a very bad profile!
1284 function common_canonical_sms($sms)
1287 preg_replace('/\D/', '', $sms);
1291 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1296 case E_COMPILE_ERROR:
1300 case E_RECOVERABLE_ERROR:
1301 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1306 case E_COMPILE_WARNING:
1307 case E_CORE_WARNING:
1308 case E_USER_WARNING:
1309 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1314 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1319 case E_USER_DEPRECATED:
1320 // XXX: config variable to log this stuff, too
1324 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1329 // FIXME: show error page if we're on the Web
1330 /* Don't execute PHP internal error handler */
1334 function common_session_token()
1336 common_ensure_session();
1337 if (!array_key_exists('token', $_SESSION)) {
1338 $_SESSION['token'] = common_good_rand(64);
1340 return $_SESSION['token'];
1343 function common_cache_key($extra)
1345 $base_key = common_config('memcached', 'base');
1347 if (empty($base_key)) {
1348 $base_key = common_keyize(common_config('site', 'name'));
1351 return 'statusnet:' . $base_key . ':' . $extra;
1354 function common_keyize($str)
1356 $str = strtolower($str);
1357 $str = preg_replace('/\s/', '_', $str);
1361 function common_memcache()
1363 static $cache = null;
1364 if (!common_config('memcached', 'enabled')) {
1368 $cache = new Memcache();
1369 $servers = common_config('memcached', 'server');
1370 if (is_array($servers)) {
1371 foreach($servers as $server) {
1372 $cache->addServer($server);
1375 $cache->addServer($servers);
1382 function common_license_terms($uri)
1384 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1385 return explode('-',$matches[1]);
1390 function common_compatible_license($from, $to)
1392 $from_terms = common_license_terms($from);
1393 // public domain and cc-by are compatible with everything
1394 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1397 $to_terms = common_license_terms($to);
1398 // sa is compatible across versions. IANAL
1399 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1400 return count(array_diff($from_terms, $to_terms)) == 0;
1402 // XXX: better compatibility check needed here!
1403 // Should at least normalise URIs
1404 return ($from == $to);
1408 * returns a quoted table name, if required according to config
1410 function common_database_tablename($tablename)
1413 if(common_config('db','quote_identifiers')) {
1414 $tablename = '"'. $tablename .'"';
1416 //table prefixes could be added here later
1420 function common_shorten_url($long_url)
1422 $user = common_current_user();
1424 // common current user does not find a user when called from the XMPP daemon
1425 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1426 $shortenerName = 'ur1.ca';
1428 $shortenerName = $user->urlshorteningservice;
1431 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1432 //URL wasn't shortened, so return the long url
1435 //URL was shortened, so return the result
1436 return $shortenedUrl;
1440 function common_client_ip()
1442 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1446 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1447 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1448 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1450 $proxy = $_SERVER['REMOTE_ADDR'];
1452 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1455 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1456 $ip = $_SERVER['HTTP_CLIENT_IP'];
1458 $ip = $_SERVER['REMOTE_ADDR'];
1462 return array($proxy, $ip);