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 // Note that this setlocale() call may "fail" but this is harmless;
62 // gettext will still select the right language.
63 $language = common_language();
64 $locale_set = common_init_locale($language);
66 setlocale(LC_CTYPE, 'C');
67 // So we do not have to make people install the gettext locales
68 $path = common_config('site','locale_path');
69 bindtextdomain("statusnet", $path);
70 bind_textdomain_codeset("statusnet", "UTF-8");
71 textdomain("statusnet");
74 function common_timezone()
76 if (common_logged_in()) {
77 $user = common_current_user();
78 if ($user->timezone) {
79 return $user->timezone;
83 return common_config('site', 'timezone');
86 function common_language()
89 // If there is a user logged in and they've set a language preference
90 // then return that one...
91 if (_have_config() && common_logged_in()) {
92 $user = common_current_user();
93 $user_language = $user->language;
95 return $user_language;
98 // Otherwise, find the best match for the languages requested by the
100 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
101 if (!empty($httplang)) {
102 $language = client_prefered_language($httplang);
107 // Finally, if none of the above worked, use the site's default...
108 return common_config('site', 'language');
110 // salted, hashed passwords are stored in the DB
112 function common_munge_password($password, $id)
114 return md5($password . $id);
117 // check if a username exists and has matching password
119 function common_check_user($nickname, $password)
121 $authenticatedUser = false;
123 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
124 $user = User::staticGet('nickname', $nickname);
126 if (!empty($password)) { // never allow login with blank password
127 if (0 == strcmp(common_munge_password($password, $user->id),
129 //internal checking passed
130 $authenticatedUser = $user;
134 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
137 return $authenticatedUser;
140 // is the current user logged in?
141 function common_logged_in()
143 return (!is_null(common_current_user()));
146 function common_have_session()
148 return (0 != strcmp(session_id(), ''));
151 function common_ensure_session()
154 if (array_key_exists(session_name(), $_COOKIE)) {
155 $c = $_COOKIE[session_name()];
157 if (!common_have_session()) {
158 if (common_config('sessions', 'handle')) {
159 Session::setSaveHandler();
162 if (!isset($_SESSION['started'])) {
163 $_SESSION['started'] = time();
165 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
166 ' is set but started value is null');
172 // Three kinds of arguments:
177 // Initialize to false; set to null if none found
181 function common_set_user($user)
186 if (is_null($user) && common_have_session()) {
188 unset($_SESSION['userid']);
190 } else if (is_string($user)) {
192 $user = User::staticGet('nickname', $nickname);
193 } else if (!($user instanceof User)) {
198 if (Event::handle('StartSetUser', array(&$user))) {
200 common_ensure_session();
201 $_SESSION['userid'] = $user->id;
203 Event::handle('EndSetUser', array($user));
211 function common_set_cookie($key, $value, $expiration=0)
213 $path = common_config('site', 'path');
214 $server = common_config('site', 'server');
216 if ($path && ($path != '/')) {
217 $cookiepath = '/' . $path . '/';
221 return setcookie($key,
228 define('REMEMBERME', 'rememberme');
229 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
231 function common_rememberme($user=null)
234 $user = common_current_user();
236 common_debug('No current user to remember', __FILE__);
241 $rm = new Remember_me();
243 $rm->code = common_good_rand(16);
244 $rm->user_id = $user->id;
246 // Wrap the insert in some good ol' fashioned transaction code
250 $result = $rm->insert();
253 common_log_db_error($rm, 'INSERT', __FILE__);
254 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
258 $rm->query('COMMIT');
260 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
262 $cookieval = $rm->user_id . ':' . $rm->code;
264 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
266 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
271 function common_remembered_user()
276 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
282 list($id, $code) = explode(':', $packed);
284 if (!$id || !$code) {
285 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
290 $rm = Remember_me::staticGet($code);
293 common_log(LOG_WARNING, 'No such remember code: ' . $code);
298 if ($rm->user_id != $id) {
299 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
304 $user = User::staticGet($rm->user_id);
307 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
313 $result = $rm->delete();
316 common_log_db_error($rm, 'DELETE', __FILE__);
317 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
322 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
324 common_set_user($user);
325 common_real_login(false);
327 // We issue a new cookie, so they can log in
328 // automatically again after this session
330 common_rememberme($user);
335 // must be called with a valid user!
337 function common_forgetme()
339 common_set_cookie(REMEMBERME, '', 0);
342 // who is the current user?
343 function common_current_user()
347 if (!_have_config()) {
351 if ($_cur === false) {
353 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
354 common_ensure_session();
355 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
357 $user = User::staticGet($id);
365 // that didn't work; try to remember; will init $_cur to null on failure
366 $_cur = common_remembered_user();
369 common_debug("Got User " . $_cur->nickname);
370 common_debug("Faking session on remembered user");
371 // XXX: Is this necessary?
372 $_SESSION['userid'] = $_cur->id;
379 // Logins that are 'remembered' aren't 'real' -- they're subject to
380 // cookie-stealing. So, we don't let them do certain things. New reg,
381 // OpenID, and password logins _are_ real.
383 function common_real_login($real=true)
385 common_ensure_session();
386 $_SESSION['real_login'] = $real;
389 function common_is_real_login()
391 return common_logged_in() && $_SESSION['real_login'];
394 // get canonical version of nickname for comparison
395 function common_canonical_nickname($nickname)
397 // XXX: UTF-8 canonicalization (like combining chars)
398 return strtolower($nickname);
401 // get canonical version of email for comparison
402 function common_canonical_email($email)
404 // XXX: canonicalize UTF-8
405 // XXX: lcase the domain part
409 function common_render_content($text, $notice)
411 $r = common_render_text($text);
412 $id = $notice->profile_id;
413 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
414 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
415 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
416 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
420 function common_render_text($text)
422 $r = htmlspecialchars($text);
424 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
425 $r = common_replace_urls_callback($r, 'common_linkify');
426 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
431 function common_replace_urls_callback($text, $callback, $notice_id = null) {
432 // Start off with a regex
434 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
437 '(?:'. //Known protocols
439 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
441 '(?:(?:mailto|aim|tel|xmpp):)'.
443 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
446 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
448 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
452 '|(?:(?: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
454 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
456 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
457 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
458 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
459 '(?: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)'.
463 '(?:\:\d+)?'. //:port
464 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
465 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
466 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
467 ')(?<![\?\.\,\#\,])'.
470 //preg_match_all($regex,$text,$matches);
472 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
475 function callback_helper($matches, $callback, $notice_id) {
477 $left = strpos($matches[0],$url);
478 $right = $left+strlen($url);
480 $groupSymbolSets=array(
498 $cannotEndWith=array('.','?',',','#');
502 foreach($groupSymbolSets as $groupSymbolSet){
503 if(substr($url,-1)==$groupSymbolSet['right']){
504 $group_left_count = substr_count($url,$groupSymbolSet['left']);
505 $group_right_count = substr_count($url,$groupSymbolSet['right']);
506 if($group_left_count<$group_right_count){
508 $url=substr($url,0,-1);
512 if(in_array(substr($url,-1),$cannotEndWith)){
514 $url=substr($url,0,-1);
516 }while($original_url!=$url);
518 if(empty($notice_id)){
519 $result = call_user_func_array($callback, array($url));
521 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
523 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
526 function curry($fn) {
527 //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used
528 $args = func_get_args();
530 $id = uniqid('_partial');
531 $GLOBALS[$id] = array($fn, $args);
532 return create_function('',
533 '$args = func_get_args(); '.
534 'return call_user_func_array('.
535 '$GLOBALS["'.$id.'"][0],'.
538 '$GLOBALS["'.$id.'"][1]));');
541 function common_linkify($url) {
542 // It comes in special'd, so we unspecial it before passing to the stringifying
544 $url = htmlspecialchars_decode($url);
546 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
547 //url is an email address without the mailto: protocol
548 $canon = "mailto:$url";
549 $longurl = "mailto:$url";
552 $canon = File_redirection::_canonUrl($url);
554 $longurl_data = File_redirection::where($canon);
555 if (is_array($longurl_data)) {
556 $longurl = $longurl_data['url'];
557 } elseif (is_string($longurl_data)) {
558 $longurl = $longurl_data;
560 throw new ServerException("Can't linkify url '$url'");
563 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
565 $is_attachment = false;
566 $attachment_id = null;
569 // Check to see whether this is a known "attachment" URL.
571 $f = File::staticGet('url', $longurl);
574 // XXX: this writes to the database. :<
575 $f = File::processNew($longurl);
579 if ($f->isEnclosure()) {
580 $is_attachment = true;
581 $attachment_id = $f->id;
583 $foe = File_oembed::staticGet('file_id', $f->id);
585 // if it has OEmbed info, it's an attachment, too
586 $is_attachment = true;
587 $attachment_id = $f->id;
589 $thumb = File_thumbnail::staticGet('file_id', $f->id);
590 if (!empty($thumb)) {
598 if ($is_attachment) {
599 $attrs['class'] = 'attachment';
601 $attrs['class'] = 'attachment thumbnail';
603 $attrs['id'] = "attachment-{$attachment_id}";
606 return XMLStringer::estring('a', $attrs, $url);
609 function common_shorten_links($text)
611 $maxLength = Notice::maxContent();
612 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
613 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
616 function common_xml_safe_str($str)
618 // Neutralize control codes and surrogates
619 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
622 function common_tag_link($tag)
624 $canonical = common_canonical_tag($tag);
625 $url = common_local_url('tag', array('tag' => $canonical));
626 $xs = new XMLStringer();
627 $xs->elementStart('span', 'tag');
628 $xs->element('a', array('href' => $url,
631 $xs->elementEnd('span');
632 return $xs->getString();
635 function common_canonical_tag($tag)
637 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
638 return str_replace(array('-', '_', '.'), '', $tag);
641 function common_valid_profile_tag($str)
643 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
646 function common_at_link($sender_id, $nickname)
648 $sender = Profile::staticGet($sender_id);
649 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
651 $user = User::staticGet('id', $recipient->id);
653 $url = common_local_url('userbyid', array('id' => $user->id));
655 $url = $recipient->profileurl;
657 $xs = new XMLStringer(false);
658 $attrs = array('href' => $url,
660 if (!empty($recipient->fullname)) {
661 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
663 $xs->elementStart('span', 'vcard');
664 $xs->elementStart('a', $attrs);
665 $xs->element('span', 'fn nickname', $nickname);
666 $xs->elementEnd('a');
667 $xs->elementEnd('span');
668 return $xs->getString();
674 function common_group_link($sender_id, $nickname)
676 $sender = Profile::staticGet($sender_id);
677 $group = User_group::getForNickname($nickname);
678 if ($group && $sender->isMember($group)) {
679 $attrs = array('href' => $group->permalink(),
681 if (!empty($group->fullname)) {
682 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
684 $xs = new XMLStringer();
685 $xs->elementStart('span', 'vcard');
686 $xs->elementStart('a', $attrs);
687 $xs->element('span', 'fn nickname', $nickname);
688 $xs->elementEnd('a');
689 $xs->elementEnd('span');
690 return $xs->getString();
696 function common_at_hash_link($sender_id, $tag)
698 $user = User::staticGet($sender_id);
702 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
704 $url = common_local_url('subscriptions',
705 array('nickname' => $user->nickname,
707 $xs = new XMLStringer();
708 $xs->elementStart('span', 'tag');
709 $xs->element('a', array('href' => $url,
712 $xs->elementEnd('span');
713 return $xs->getString();
719 function common_relative_profile($sender, $nickname, $dt=null)
721 // Try to find profiles this profile is subscribed to that have this nickname
722 $recipient = new Profile();
723 // XXX: use a join instead of a subquery
724 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
725 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
726 if ($recipient->find(true)) {
727 // XXX: should probably differentiate between profiles with
728 // the same name by date of most recent update
731 // Try to find profiles that listen to this profile and that have this nickname
732 $recipient = new Profile();
733 // XXX: use a join instead of a subquery
734 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
735 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
736 if ($recipient->find(true)) {
737 // XXX: should probably differentiate between profiles with
738 // the same name by date of most recent update
741 // If this is a local user, try to find a local user with that nickname.
742 $sender = User::staticGet($sender->id);
744 $recipient_user = User::staticGet('nickname', $nickname);
745 if ($recipient_user) {
746 return $recipient_user->getProfile();
749 // Otherwise, no links. @messages from local users to remote users,
750 // or from remote users to other remote users, are just
751 // outside our ability to make intelligent guesses about
755 function common_local_url($action, $args=null, $params=null, $fragment=null)
758 $path = $r->build($action, $args, $params, $fragment);
760 $ssl = common_is_sensitive($action);
762 if (common_config('site','fancy')) {
763 $url = common_path(mb_substr($path, 1), $ssl);
765 if (mb_strpos($path, '/index.php') === 0) {
766 $url = common_path(mb_substr($path, 1), $ssl);
768 $url = common_path('index.php'.$path, $ssl);
774 function common_is_sensitive($action)
776 static $sensitive = array('login', 'register', 'passwordsettings',
777 'twittersettings', 'api');
780 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
781 $ssl = in_array($action, $sensitive);
787 function common_path($relative, $ssl=false)
789 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
791 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
792 || common_config('site', 'ssl') === 'always') {
794 if (is_string(common_config('site', 'sslserver')) &&
795 mb_strlen(common_config('site', 'sslserver')) > 0) {
796 $serverpart = common_config('site', 'sslserver');
797 } else 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 if (common_config('site', 'server')) {
805 $serverpart = common_config('site', 'server');
807 common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.');
811 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
814 function common_date_string($dt)
816 // XXX: do some sexy date formatting
817 // return date(DATE_RFC822, $dt);
822 if ($now < $t) { // that shouldn't happen!
823 return common_exact_date($dt);
824 } else if ($diff < 60) {
825 return _('a few seconds ago');
826 } else if ($diff < 92) {
827 return _('about a minute ago');
828 } else if ($diff < 3300) {
829 return sprintf(_('about %d minutes ago'), round($diff/60));
830 } else if ($diff < 5400) {
831 return _('about an hour ago');
832 } else if ($diff < 22 * 3600) {
833 return sprintf(_('about %d hours ago'), round($diff/3600));
834 } else if ($diff < 37 * 3600) {
835 return _('about a day ago');
836 } else if ($diff < 24 * 24 * 3600) {
837 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
838 } else if ($diff < 46 * 24 * 3600) {
839 return _('about a month ago');
840 } else if ($diff < 330 * 24 * 3600) {
841 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
842 } else if ($diff < 480 * 24 * 3600) {
843 return _('about a year ago');
845 return common_exact_date($dt);
849 function common_exact_date($dt)
855 $_utc = new DateTimeZone('UTC');
856 $_siteTz = new DateTimeZone(common_timezone());
859 $dateStr = date('d F Y H:i:s', strtotime($dt));
860 $d = new DateTime($dateStr, $_utc);
861 $d->setTimezone($_siteTz);
862 return $d->format(DATE_RFC850);
865 function common_date_w3dtf($dt)
867 $dateStr = date('d F Y H:i:s', strtotime($dt));
868 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
869 $d->setTimezone(new DateTimeZone(common_timezone()));
870 return $d->format(DATE_W3C);
873 function common_date_rfc2822($dt)
875 $dateStr = date('d F Y H:i:s', strtotime($dt));
876 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
877 $d->setTimezone(new DateTimeZone(common_timezone()));
878 return $d->format('r');
881 function common_date_iso8601($dt)
883 $dateStr = date('d F Y H:i:s', strtotime($dt));
884 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
885 $d->setTimezone(new DateTimeZone(common_timezone()));
886 return $d->format('c');
889 function common_sql_now()
891 return common_sql_date(time());
894 function common_sql_date($datetime)
896 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
899 function common_redirect($url, $code=307)
901 static $status = array(301 => "Moved Permanently",
904 307 => "Temporary Redirect");
906 header('HTTP/1.1 '.$code.' '.$status[$code]);
907 header("Location: $url");
909 $xo = new XMLOutputter();
911 '-//W3C//DTD XHTML 1.0 Strict//EN',
912 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
913 $xo->element('a', array('href' => $url), $url);
918 function common_broadcast_notice($notice, $remote=false)
920 return common_enqueue_notice($notice);
923 // Stick the notice on the queue
925 function common_enqueue_notice($notice)
927 static $localTransports = array('omb',
930 static $allTransports = array('sms', 'plugin');
932 $transports = $allTransports;
934 $xmpp = common_config('xmpp', 'enabled');
937 $transports[] = 'jabber';
940 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
941 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
942 $transports = array_merge($transports, $localTransports);
944 $transports[] = 'public';
948 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
950 $qm = QueueManager::get();
952 foreach ($transports as $transport)
954 $qm->enqueue($notice, $transport);
957 Event::handle('EndEnqueueNotice', array($notice, $transports));
963 function common_broadcast_profile($profile)
965 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
966 require_once(INSTALLDIR.'/lib/omb.php');
967 omb_broadcast_profile($profile);
968 // XXX: Other broadcasts...?
972 function common_profile_url($nickname)
974 return common_local_url('showstream', array('nickname' => $nickname));
977 // Should make up a reasonable root URL
979 function common_root_url($ssl=false)
981 return common_path('', $ssl);
984 // returns $bytes bytes of random data as a hexadecimal string
985 // "good" here is a goal and not a guarantee
987 function common_good_rand($bytes)
989 // XXX: use random.org...?
990 if (@file_exists('/dev/urandom')) {
991 return common_urandom($bytes);
992 } else { // FIXME: this is probably not good enough
993 return common_mtrand($bytes);
997 function common_urandom($bytes)
999 $h = fopen('/dev/urandom', 'rb');
1001 $src = fread($h, $bytes);
1004 for ($i = 0; $i < $bytes; $i++) {
1005 $enc .= sprintf("%02x", (ord($src[$i])));
1010 function common_mtrand($bytes)
1013 for ($i = 0; $i < $bytes; $i++) {
1014 $enc .= sprintf("%02x", mt_rand(0, 255));
1019 function common_set_returnto($url)
1021 common_ensure_session();
1022 $_SESSION['returnto'] = $url;
1025 function common_get_returnto()
1027 common_ensure_session();
1028 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1031 function common_timestamp()
1033 return date('YmdHis');
1036 function common_ensure_syslog()
1038 static $initialized = false;
1039 if (!$initialized) {
1040 openlog(common_config('syslog', 'appname'), 0,
1041 common_config('syslog', 'facility'));
1042 $initialized = true;
1046 function common_log_line($priority, $msg)
1048 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1049 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1050 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1053 function common_request_id()
1056 if (php_sapi_name() == 'cli') {
1059 static $req_id = null;
1060 if (!isset($req_id)) {
1061 $req_id = substr(md5(mt_rand()), 0, 8);
1063 if (isset($_SERVER['REQUEST_URI'])) {
1064 $url = $_SERVER['REQUEST_URI'];
1066 $method = $_SERVER['REQUEST_METHOD'];
1067 return "$pid.$req_id $method $url";
1071 function common_log($priority, $msg, $filename=null)
1073 $msg = '[' . common_request_id() . '] ' . $msg;
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 if (is_object($v)) {
1116 $fields[] = "$k='".get_class($v)."'";
1118 $fields[] = "$k='$v'";
1121 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1125 function common_valid_http_url($url)
1127 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1130 function common_valid_tag($tag)
1132 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1133 return (Validate::email($matches[1]) ||
1134 preg_match('/^([\w-\.]+)$/', $matches[1]));
1139 /* Following functions are copied from MediaWiki GlobalFunctions.php
1140 * and written by Evan Prodromou. */
1142 function common_accept_to_prefs($accept, $def = '*/*')
1144 // No arg means accept anything (per HTTP spec)
1146 return array($def => 1);
1151 $parts = explode(',', $accept);
1153 foreach($parts as $part) {
1154 // FIXME: doesn't deal with params like 'text/html; level=1'
1155 @list($value, $qpart) = explode(';', trim($part));
1157 if(!isset($qpart)) {
1159 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1160 $prefs[$value] = $match[1];
1167 function common_mime_type_match($type, $avail)
1169 if(array_key_exists($type, $avail)) {
1172 $parts = explode('/', $type);
1173 if(array_key_exists($parts[0] . '/*', $avail)) {
1174 return $parts[0] . '/*';
1175 } elseif(array_key_exists('*/*', $avail)) {
1183 function common_negotiate_type($cprefs, $sprefs)
1187 foreach(array_keys($sprefs) as $type) {
1188 $parts = explode('/', $type);
1189 if($parts[1] != '*') {
1190 $ckey = common_mime_type_match($type, $cprefs);
1192 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1197 foreach(array_keys($cprefs) as $type) {
1198 $parts = explode('/', $type);
1199 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1200 $skey = common_mime_type_match($type, $sprefs);
1202 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1208 $besttype = 'text/html';
1210 foreach(array_keys($combine) as $type) {
1211 if($combine[$type] > $bestq) {
1213 $bestq = $combine[$type];
1217 if ('text/html' === $besttype) {
1218 return "text/html; charset=utf-8";
1223 function common_config($main, $sub)
1226 return (array_key_exists($main, $config) &&
1227 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1230 function common_copy_args($from)
1233 $strip = get_magic_quotes_gpc();
1234 foreach ($from as $k => $v) {
1235 $to[$k] = ($strip) ? stripslashes($v) : $v;
1240 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1241 // This is used before handing a request off to OAuthRequest::from_request.
1242 function common_remove_magic_from_request()
1244 if(get_magic_quotes_gpc()) {
1245 $_POST=array_map('stripslashes',$_POST);
1246 $_GET=array_map('stripslashes',$_GET);
1250 function common_user_uri(&$user)
1252 return common_local_url('userbyid', array('id' => $user->id));
1255 function common_notice_uri(&$notice)
1257 return common_local_url('shownotice',
1258 array('notice' => $notice->id));
1261 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1263 function common_confirmation_code($bits)
1265 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1266 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1267 $chars = ceil($bits/5);
1269 for ($i = 0; $i < $chars; $i++) {
1270 // XXX: convert to string and back
1271 $num = hexdec(common_good_rand(1));
1272 // XXX: randomness is too precious to throw away almost
1273 // 40% of the bits we get!
1274 $code .= $codechars[$num%32];
1279 // convert markup to HTML
1281 function common_markup_to_html($c)
1283 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1284 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1285 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1286 return Markdown($c);
1289 function common_profile_uri($profile)
1294 $user = User::staticGet($profile->id);
1299 $remote = Remote_profile::staticGet($profile->id);
1301 return $remote->uri;
1303 // XXX: this is a very bad profile!
1307 function common_canonical_sms($sms)
1310 preg_replace('/\D/', '', $sms);
1314 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1319 case E_COMPILE_ERROR:
1323 case E_RECOVERABLE_ERROR:
1324 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1329 case E_COMPILE_WARNING:
1330 case E_CORE_WARNING:
1331 case E_USER_WARNING:
1332 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1337 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1342 case E_USER_DEPRECATED:
1343 // XXX: config variable to log this stuff, too
1347 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1352 // FIXME: show error page if we're on the Web
1353 /* Don't execute PHP internal error handler */
1357 function common_session_token()
1359 common_ensure_session();
1360 if (!array_key_exists('token', $_SESSION)) {
1361 $_SESSION['token'] = common_good_rand(64);
1363 return $_SESSION['token'];
1366 function common_cache_key($extra)
1368 $base_key = common_config('memcached', 'base');
1370 if (empty($base_key)) {
1371 $base_key = common_keyize(common_config('site', 'name'));
1374 return 'statusnet:' . $base_key . ':' . $extra;
1377 function common_keyize($str)
1379 $str = strtolower($str);
1380 $str = preg_replace('/\s/', '_', $str);
1384 function common_memcache()
1386 static $cache = null;
1387 if (!common_config('memcached', 'enabled')) {
1391 $cache = new Memcache();
1392 $servers = common_config('memcached', 'server');
1393 if (is_array($servers)) {
1394 foreach($servers as $server) {
1395 $cache->addServer($server);
1398 $cache->addServer($servers);
1405 function common_license_terms($uri)
1407 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1408 return explode('-',$matches[1]);
1413 function common_compatible_license($from, $to)
1415 $from_terms = common_license_terms($from);
1416 // public domain and cc-by are compatible with everything
1417 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1420 $to_terms = common_license_terms($to);
1421 // sa is compatible across versions. IANAL
1422 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1423 return count(array_diff($from_terms, $to_terms)) == 0;
1425 // XXX: better compatibility check needed here!
1426 // Should at least normalise URIs
1427 return ($from == $to);
1431 * returns a quoted table name, if required according to config
1433 function common_database_tablename($tablename)
1436 if(common_config('db','quote_identifiers')) {
1437 $tablename = '"'. $tablename .'"';
1439 //table prefixes could be added here later
1443 function common_shorten_url($long_url)
1445 $user = common_current_user();
1447 // common current user does not find a user when called from the XMPP daemon
1448 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1449 $shortenerName = 'ur1.ca';
1451 $shortenerName = $user->urlshorteningservice;
1454 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1455 //URL wasn't shortened, so return the long url
1458 //URL was shortened, so return the result
1459 return $shortenedUrl;
1463 function common_client_ip()
1465 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1469 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1470 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1471 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1473 $proxy = $_SERVER['REMOTE_ADDR'];
1475 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1478 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1479 $ip = $_SERVER['HTTP_CLIENT_IP'];
1481 $ip = $_SERVER['REMOTE_ADDR'];
1485 return array($proxy, $ip);