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 if ($user->language) {
96 // Validate -- we don't want to end up with a bogus code
97 // left over from some old junk.
98 foreach (common_config('site', 'languages') as $code => $info) {
99 if ($info['lang'] == $user_language) {
100 return $user_language;
106 // Otherwise, find the best match for the languages requested by the
108 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
109 if (!empty($httplang)) {
110 $language = client_prefered_language($httplang);
115 // Finally, if none of the above worked, use the site's default...
116 return common_config('site', 'language');
118 // salted, hashed passwords are stored in the DB
120 function common_munge_password($password, $id)
122 if (is_object($id) || is_object($password)) {
123 $e = new Exception();
124 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
125 str_replace("\n", " ", $e->getTraceAsString()));
127 return md5($password . $id);
130 // check if a username exists and has matching password
132 function common_check_user($nickname, $password)
134 $authenticatedUser = false;
136 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
137 $user = User::staticGet('nickname', $nickname);
139 if (!empty($password)) { // never allow login with blank password
140 if (0 == strcmp(common_munge_password($password, $user->id),
142 //internal checking passed
143 $authenticatedUser = $user;
147 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
150 return $authenticatedUser;
153 // is the current user logged in?
154 function common_logged_in()
156 return (!is_null(common_current_user()));
159 function common_have_session()
161 return (0 != strcmp(session_id(), ''));
164 function common_ensure_session()
167 if (array_key_exists(session_name(), $_COOKIE)) {
168 $c = $_COOKIE[session_name()];
170 if (!common_have_session()) {
171 if (common_config('sessions', 'handle')) {
172 Session::setSaveHandler();
174 if (array_key_exists(session_name(), $_GET)) {
175 $id = $_GET[session_name()];
176 } else if (array_key_exists(session_name(), $_COOKIE)) {
177 $id = $_COOKIE[session_name()];
181 setcookie(session_name(), $id);
184 if (!isset($_SESSION['started'])) {
185 $_SESSION['started'] = time();
187 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
188 ' is set but started value is null');
194 // Three kinds of arguments:
199 // Initialize to false; set to null if none found
203 function common_set_user($user)
208 if (is_null($user) && common_have_session()) {
210 unset($_SESSION['userid']);
212 } else if (is_string($user)) {
214 $user = User::staticGet('nickname', $nickname);
215 } else if (!($user instanceof User)) {
220 if (Event::handle('StartSetUser', array(&$user))) {
222 common_ensure_session();
223 $_SESSION['userid'] = $user->id;
225 Event::handle('EndSetUser', array($user));
233 function common_set_cookie($key, $value, $expiration=0)
235 $path = common_config('site', 'path');
236 $server = common_config('site', 'server');
238 if ($path && ($path != '/')) {
239 $cookiepath = '/' . $path . '/';
243 return setcookie($key,
250 define('REMEMBERME', 'rememberme');
251 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
253 function common_rememberme($user=null)
256 $user = common_current_user();
262 $rm = new Remember_me();
264 $rm->code = common_good_rand(16);
265 $rm->user_id = $user->id;
267 // Wrap the insert in some good ol' fashioned transaction code
271 $result = $rm->insert();
274 common_log_db_error($rm, 'INSERT', __FILE__);
278 $rm->query('COMMIT');
280 $cookieval = $rm->user_id . ':' . $rm->code;
282 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
284 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
289 function common_remembered_user()
294 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
300 list($id, $code) = explode(':', $packed);
302 if (!$id || !$code) {
303 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
308 $rm = Remember_me::staticGet($code);
311 common_log(LOG_WARNING, 'No such remember code: ' . $code);
316 if ($rm->user_id != $id) {
317 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
322 $user = User::staticGet($rm->user_id);
325 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
331 $result = $rm->delete();
334 common_log_db_error($rm, 'DELETE', __FILE__);
335 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
340 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
342 common_set_user($user);
343 common_real_login(false);
345 // We issue a new cookie, so they can log in
346 // automatically again after this session
348 common_rememberme($user);
353 // must be called with a valid user!
355 function common_forgetme()
357 common_set_cookie(REMEMBERME, '', 0);
360 // who is the current user?
361 function common_current_user()
365 if (!_have_config()) {
369 if ($_cur === false) {
371 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
372 common_ensure_session();
373 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
375 $user = User::staticGet($id);
383 // that didn't work; try to remember; will init $_cur to null on failure
384 $_cur = common_remembered_user();
387 // XXX: Is this necessary?
388 $_SESSION['userid'] = $_cur->id;
395 // Logins that are 'remembered' aren't 'real' -- they're subject to
396 // cookie-stealing. So, we don't let them do certain things. New reg,
397 // OpenID, and password logins _are_ real.
399 function common_real_login($real=true)
401 common_ensure_session();
402 $_SESSION['real_login'] = $real;
405 function common_is_real_login()
407 return common_logged_in() && $_SESSION['real_login'];
410 // get canonical version of nickname for comparison
411 function common_canonical_nickname($nickname)
413 // XXX: UTF-8 canonicalization (like combining chars)
414 return strtolower($nickname);
417 // get canonical version of email for comparison
418 function common_canonical_email($email)
420 // XXX: canonicalize UTF-8
421 // XXX: lcase the domain part
425 function common_render_content($text, $notice)
427 $r = common_render_text($text);
428 $id = $notice->profile_id;
429 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
430 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
431 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
432 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
436 function common_render_text($text)
438 $r = htmlspecialchars($text);
440 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
441 $r = common_replace_urls_callback($r, 'common_linkify');
442 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
447 function common_replace_urls_callback($text, $callback, $notice_id = null) {
448 // Start off with a regex
450 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
453 '(?:'. //Known protocols
455 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
457 '(?:(?:mailto|aim|tel|xmpp):)'.
459 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
462 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
464 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
468 '|(?:(?: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
470 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
472 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
473 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
474 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
475 '(?: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)'.
479 '(?:\:\d+)?'. //:port
480 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
481 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
482 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
483 ')(?<![\?\.\,\#\,])'.
486 //preg_match_all($regex,$text,$matches);
488 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
491 function callback_helper($matches, $callback, $notice_id) {
493 $left = strpos($matches[0],$url);
494 $right = $left+strlen($url);
496 $groupSymbolSets=array(
514 $cannotEndWith=array('.','?',',','#');
518 foreach($groupSymbolSets as $groupSymbolSet){
519 if(substr($url,-1)==$groupSymbolSet['right']){
520 $group_left_count = substr_count($url,$groupSymbolSet['left']);
521 $group_right_count = substr_count($url,$groupSymbolSet['right']);
522 if($group_left_count<$group_right_count){
524 $url=substr($url,0,-1);
528 if(in_array(substr($url,-1),$cannotEndWith)){
530 $url=substr($url,0,-1);
532 }while($original_url!=$url);
534 if(empty($notice_id)){
535 $result = call_user_func_array($callback, array($url));
537 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
539 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
542 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
543 // lambda implementation in a separate file; PHP 5.2 won't parse it.
544 require_once INSTALLDIR . "/lib/curry.php";
546 function curry($fn) {
547 $args = func_get_args();
549 $id = uniqid('_partial');
550 $GLOBALS[$id] = array($fn, $args);
551 return create_function('',
552 '$args = func_get_args(); '.
553 'return call_user_func_array('.
554 '$GLOBALS["'.$id.'"][0],'.
557 '$GLOBALS["'.$id.'"][1]));');
561 function common_linkify($url) {
562 // It comes in special'd, so we unspecial it before passing to the stringifying
564 $url = htmlspecialchars_decode($url);
566 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
567 //url is an email address without the mailto: protocol
568 $canon = "mailto:$url";
569 $longurl = "mailto:$url";
572 $canon = File_redirection::_canonUrl($url);
574 $longurl_data = File_redirection::where($canon);
575 if (is_array($longurl_data)) {
576 $longurl = $longurl_data['url'];
577 } elseif (is_string($longurl_data)) {
578 $longurl = $longurl_data;
580 throw new ServerException("Can't linkify url '$url'");
583 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
585 $is_attachment = false;
586 $attachment_id = null;
589 // Check to see whether this is a known "attachment" URL.
591 $f = File::staticGet('url', $longurl);
594 // XXX: this writes to the database. :<
595 $f = File::processNew($longurl);
599 if ($f->getEnclosure()) {
600 $is_attachment = true;
601 $attachment_id = $f->id;
603 $thumb = File_thumbnail::staticGet('file_id', $f->id);
604 if (!empty($thumb)) {
611 if ($is_attachment) {
612 $attrs['class'] = 'attachment';
614 $attrs['class'] = 'attachment thumbnail';
616 $attrs['id'] = "attachment-{$attachment_id}";
619 return XMLStringer::estring('a', $attrs, $url);
622 function common_shorten_links($text)
624 $maxLength = Notice::maxContent();
625 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
626 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
629 function common_xml_safe_str($str)
631 // Neutralize control codes and surrogates
632 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
635 function common_tag_link($tag)
637 $canonical = common_canonical_tag($tag);
638 $url = common_local_url('tag', array('tag' => $canonical));
639 $xs = new XMLStringer();
640 $xs->elementStart('span', 'tag');
641 $xs->element('a', array('href' => $url,
644 $xs->elementEnd('span');
645 return $xs->getString();
648 function common_canonical_tag($tag)
650 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
651 return str_replace(array('-', '_', '.'), '', $tag);
654 function common_valid_profile_tag($str)
656 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
659 function common_at_link($sender_id, $nickname)
661 $sender = Profile::staticGet($sender_id);
662 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
664 $user = User::staticGet('id', $recipient->id);
666 $url = common_local_url('userbyid', array('id' => $user->id));
668 $url = $recipient->profileurl;
670 $xs = new XMLStringer(false);
671 $attrs = array('href' => $url,
673 if (!empty($recipient->fullname)) {
674 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
676 $xs->elementStart('span', 'vcard');
677 $xs->elementStart('a', $attrs);
678 $xs->element('span', 'fn nickname', $nickname);
679 $xs->elementEnd('a');
680 $xs->elementEnd('span');
681 return $xs->getString();
687 function common_group_link($sender_id, $nickname)
689 $sender = Profile::staticGet($sender_id);
690 $group = User_group::getForNickname($nickname);
691 if ($group && $sender->isMember($group)) {
692 $attrs = array('href' => $group->permalink(),
694 if (!empty($group->fullname)) {
695 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
697 $xs = new XMLStringer();
698 $xs->elementStart('span', 'vcard');
699 $xs->elementStart('a', $attrs);
700 $xs->element('span', 'fn nickname', $nickname);
701 $xs->elementEnd('a');
702 $xs->elementEnd('span');
703 return $xs->getString();
709 function common_at_hash_link($sender_id, $tag)
711 $user = User::staticGet($sender_id);
715 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
717 $url = common_local_url('subscriptions',
718 array('nickname' => $user->nickname,
720 $xs = new XMLStringer();
721 $xs->elementStart('span', 'tag');
722 $xs->element('a', array('href' => $url,
725 $xs->elementEnd('span');
726 return $xs->getString();
732 function common_relative_profile($sender, $nickname, $dt=null)
734 // Try to find profiles this profile is subscribed to that have this nickname
735 $recipient = new Profile();
736 // XXX: use a join instead of a subquery
737 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
738 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
739 if ($recipient->find(true)) {
740 // XXX: should probably differentiate between profiles with
741 // the same name by date of most recent update
744 // Try to find profiles that listen to this profile and that have this nickname
745 $recipient = new Profile();
746 // XXX: use a join instead of a subquery
747 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
748 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
749 if ($recipient->find(true)) {
750 // XXX: should probably differentiate between profiles with
751 // the same name by date of most recent update
754 // If this is a local user, try to find a local user with that nickname.
755 $sender = User::staticGet($sender->id);
757 $recipient_user = User::staticGet('nickname', $nickname);
758 if ($recipient_user) {
759 return $recipient_user->getProfile();
762 // Otherwise, no links. @messages from local users to remote users,
763 // or from remote users to other remote users, are just
764 // outside our ability to make intelligent guesses about
768 function common_local_url($action, $args=null, $params=null, $fragment=null)
771 $path = $r->build($action, $args, $params, $fragment);
773 $ssl = common_is_sensitive($action);
775 if (common_config('site','fancy')) {
776 $url = common_path(mb_substr($path, 1), $ssl);
778 if (mb_strpos($path, '/index.php') === 0) {
779 $url = common_path(mb_substr($path, 1), $ssl);
781 $url = common_path('index.php'.$path, $ssl);
787 function common_is_sensitive($action)
789 static $sensitive = array('login', 'register', 'passwordsettings',
790 'twittersettings', 'api');
793 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
794 $ssl = in_array($action, $sensitive);
800 function common_path($relative, $ssl=false)
802 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
804 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
805 || common_config('site', 'ssl') === 'always') {
807 if (is_string(common_config('site', 'sslserver')) &&
808 mb_strlen(common_config('site', 'sslserver')) > 0) {
809 $serverpart = common_config('site', 'sslserver');
810 } else if (common_config('site', 'server')) {
811 $serverpart = common_config('site', 'server');
813 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
817 if (common_config('site', 'server')) {
818 $serverpart = common_config('site', 'server');
820 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
824 $relative = common_inject_session($relative, $serverpart);
826 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
829 function common_inject_session($url, $serverpart = null)
831 if (common_have_session()) {
833 if (empty($serverpart)) {
834 $serverpart = parse_url($url, PHP_URL_HOST);
837 $currentServer = $_SERVER['HTTP_HOST'];
839 // Are we pointing to another server (like an SSL server?)
841 if (!empty($currentServer) &&
842 0 != strcasecmp($currentServer, $serverpart)) {
843 // Pass the session ID as a GET parameter
844 $sesspart = session_name() . '=' . session_id();
845 $i = strpos($url, '?');
846 if ($i === false) { // no GET params, just append
847 $url .= '?' . $sesspart;
849 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
857 function common_date_string($dt)
859 // XXX: do some sexy date formatting
860 // return date(DATE_RFC822, $dt);
865 if ($now < $t) { // that shouldn't happen!
866 return common_exact_date($dt);
867 } else if ($diff < 60) {
868 return _('a few seconds ago');
869 } else if ($diff < 92) {
870 return _('about a minute ago');
871 } else if ($diff < 3300) {
872 return sprintf(_('about %d minutes ago'), round($diff/60));
873 } else if ($diff < 5400) {
874 return _('about an hour ago');
875 } else if ($diff < 22 * 3600) {
876 return sprintf(_('about %d hours ago'), round($diff/3600));
877 } else if ($diff < 37 * 3600) {
878 return _('about a day ago');
879 } else if ($diff < 24 * 24 * 3600) {
880 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
881 } else if ($diff < 46 * 24 * 3600) {
882 return _('about a month ago');
883 } else if ($diff < 330 * 24 * 3600) {
884 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
885 } else if ($diff < 480 * 24 * 3600) {
886 return _('about a year ago');
888 return common_exact_date($dt);
892 function common_exact_date($dt)
898 $_utc = new DateTimeZone('UTC');
899 $_siteTz = new DateTimeZone(common_timezone());
902 $dateStr = date('d F Y H:i:s', strtotime($dt));
903 $d = new DateTime($dateStr, $_utc);
904 $d->setTimezone($_siteTz);
905 return $d->format(DATE_RFC850);
908 function common_date_w3dtf($dt)
910 $dateStr = date('d F Y H:i:s', strtotime($dt));
911 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
912 $d->setTimezone(new DateTimeZone(common_timezone()));
913 return $d->format(DATE_W3C);
916 function common_date_rfc2822($dt)
918 $dateStr = date('d F Y H:i:s', strtotime($dt));
919 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
920 $d->setTimezone(new DateTimeZone(common_timezone()));
921 return $d->format('r');
924 function common_date_iso8601($dt)
926 $dateStr = date('d F Y H:i:s', strtotime($dt));
927 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
928 $d->setTimezone(new DateTimeZone(common_timezone()));
929 return $d->format('c');
932 function common_sql_now()
934 return common_sql_date(time());
937 function common_sql_date($datetime)
939 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
943 * Return an SQL fragment to calculate an age-based weight from a given
944 * timestamp or datetime column.
946 * @param string $column name of field we're comparing against current time
947 * @param integer $dropoff divisor for age in seconds before exponentiation
948 * @return string SQL fragment
950 function common_sql_weight($column, $dropoff)
952 if (common_config('db', 'type') == 'pgsql') {
953 // PostgreSQL doesn't support timestampdiff function.
954 // @fixme will this use the right time zone?
955 // @fixme does this handle cross-year subtraction correctly?
956 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
958 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
962 function common_redirect($url, $code=307)
964 static $status = array(301 => "Moved Permanently",
967 307 => "Temporary Redirect");
969 header('HTTP/1.1 '.$code.' '.$status[$code]);
970 header("Location: $url");
972 $xo = new XMLOutputter();
974 '-//W3C//DTD XHTML 1.0 Strict//EN',
975 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
976 $xo->element('a', array('href' => $url), $url);
981 function common_broadcast_notice($notice, $remote=false)
983 return common_enqueue_notice($notice);
986 // Stick the notice on the queue
988 function common_enqueue_notice($notice)
990 static $localTransports = array('omb',
993 static $allTransports = array('sms', 'plugin');
995 $transports = $allTransports;
997 $xmpp = common_config('xmpp', 'enabled');
1000 $transports[] = 'jabber';
1003 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1004 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1005 $transports = array_merge($transports, $localTransports);
1007 $transports[] = 'public';
1011 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1013 $qm = QueueManager::get();
1015 foreach ($transports as $transport)
1017 $qm->enqueue($notice, $transport);
1020 Event::handle('EndEnqueueNotice', array($notice, $transports));
1026 function common_broadcast_profile($profile)
1028 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1029 require_once(INSTALLDIR.'/lib/omb.php');
1030 omb_broadcast_profile($profile);
1031 // XXX: Other broadcasts...?
1035 function common_profile_url($nickname)
1037 return common_local_url('showstream', array('nickname' => $nickname));
1040 // Should make up a reasonable root URL
1042 function common_root_url($ssl=false)
1044 $url = common_path('', $ssl);
1045 $i = strpos($url, '?');
1047 $url = substr($url, 0, $i);
1052 // returns $bytes bytes of random data as a hexadecimal string
1053 // "good" here is a goal and not a guarantee
1055 function common_good_rand($bytes)
1057 // XXX: use random.org...?
1058 if (@file_exists('/dev/urandom')) {
1059 return common_urandom($bytes);
1060 } else { // FIXME: this is probably not good enough
1061 return common_mtrand($bytes);
1065 function common_urandom($bytes)
1067 $h = fopen('/dev/urandom', 'rb');
1069 $src = fread($h, $bytes);
1072 for ($i = 0; $i < $bytes; $i++) {
1073 $enc .= sprintf("%02x", (ord($src[$i])));
1078 function common_mtrand($bytes)
1081 for ($i = 0; $i < $bytes; $i++) {
1082 $enc .= sprintf("%02x", mt_rand(0, 255));
1087 function common_set_returnto($url)
1089 common_ensure_session();
1090 $_SESSION['returnto'] = $url;
1093 function common_get_returnto()
1095 common_ensure_session();
1096 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1099 function common_timestamp()
1101 return date('YmdHis');
1104 function common_ensure_syslog()
1106 static $initialized = false;
1107 if (!$initialized) {
1108 openlog(common_config('syslog', 'appname'), 0,
1109 common_config('syslog', 'facility'));
1110 $initialized = true;
1114 function common_log_line($priority, $msg)
1116 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1117 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1118 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1121 function common_request_id()
1124 $server = common_config('site', 'server');
1125 if (php_sapi_name() == 'cli') {
1126 $script = basename($_SERVER['PHP_SELF']);
1127 return "$server:$script:$pid";
1129 static $req_id = null;
1130 if (!isset($req_id)) {
1131 $req_id = substr(md5(mt_rand()), 0, 8);
1133 if (isset($_SERVER['REQUEST_URI'])) {
1134 $url = $_SERVER['REQUEST_URI'];
1136 $method = $_SERVER['REQUEST_METHOD'];
1137 return "$server:$pid.$req_id $method $url";
1141 function common_log($priority, $msg, $filename=null)
1143 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1144 $msg = '[' . common_request_id() . '] ' . $msg;
1145 $logfile = common_config('site', 'logfile');
1147 $log = fopen($logfile, "a");
1149 $output = common_log_line($priority, $msg);
1150 fwrite($log, $output);
1154 common_ensure_syslog();
1155 syslog($priority, $msg);
1157 Event::handle('EndLog', array($priority, $msg, $filename));
1161 function common_debug($msg, $filename=null)
1164 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1166 common_log(LOG_DEBUG, $msg);
1170 function common_log_db_error(&$object, $verb, $filename=null)
1172 $objstr = common_log_objstring($object);
1173 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1174 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1177 function common_log_objstring(&$object)
1179 if (is_null($object)) {
1182 if (!($object instanceof DB_DataObject)) {
1185 $arr = $object->toArray();
1187 foreach ($arr as $k => $v) {
1188 if (is_object($v)) {
1189 $fields[] = "$k='".get_class($v)."'";
1191 $fields[] = "$k='$v'";
1194 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1198 function common_valid_http_url($url)
1200 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1203 function common_valid_tag($tag)
1205 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1206 return (Validate::email($matches[1]) ||
1207 preg_match('/^([\w-\.]+)$/', $matches[1]));
1212 /* Following functions are copied from MediaWiki GlobalFunctions.php
1213 * and written by Evan Prodromou. */
1215 function common_accept_to_prefs($accept, $def = '*/*')
1217 // No arg means accept anything (per HTTP spec)
1219 return array($def => 1);
1224 $parts = explode(',', $accept);
1226 foreach($parts as $part) {
1227 // FIXME: doesn't deal with params like 'text/html; level=1'
1228 @list($value, $qpart) = explode(';', trim($part));
1230 if(!isset($qpart)) {
1232 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1233 $prefs[$value] = $match[1];
1240 function common_mime_type_match($type, $avail)
1242 if(array_key_exists($type, $avail)) {
1245 $parts = explode('/', $type);
1246 if(array_key_exists($parts[0] . '/*', $avail)) {
1247 return $parts[0] . '/*';
1248 } elseif(array_key_exists('*/*', $avail)) {
1256 function common_negotiate_type($cprefs, $sprefs)
1260 foreach(array_keys($sprefs) as $type) {
1261 $parts = explode('/', $type);
1262 if($parts[1] != '*') {
1263 $ckey = common_mime_type_match($type, $cprefs);
1265 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1270 foreach(array_keys($cprefs) as $type) {
1271 $parts = explode('/', $type);
1272 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1273 $skey = common_mime_type_match($type, $sprefs);
1275 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1281 $besttype = 'text/html';
1283 foreach(array_keys($combine) as $type) {
1284 if($combine[$type] > $bestq) {
1286 $bestq = $combine[$type];
1290 if ('text/html' === $besttype) {
1291 return "text/html; charset=utf-8";
1296 function common_config($main, $sub)
1299 return (array_key_exists($main, $config) &&
1300 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1303 function common_copy_args($from)
1306 $strip = get_magic_quotes_gpc();
1307 foreach ($from as $k => $v) {
1308 $to[$k] = ($strip) ? stripslashes($v) : $v;
1314 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1315 * This is used before handing a request off to OAuthRequest::from_request.
1316 * @fixme Doesn't consider vars other than _POST and _GET?
1317 * @fixme Can't be undone and could corrupt data if run twice.
1319 function common_remove_magic_from_request()
1321 if(get_magic_quotes_gpc()) {
1322 $_POST=array_map('stripslashes',$_POST);
1323 $_GET=array_map('stripslashes',$_GET);
1327 function common_user_uri(&$user)
1329 return common_local_url('userbyid', array('id' => $user->id));
1332 function common_notice_uri(&$notice)
1334 return common_local_url('shownotice',
1335 array('notice' => $notice->id));
1338 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1340 function common_confirmation_code($bits)
1342 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1343 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1344 $chars = ceil($bits/5);
1346 for ($i = 0; $i < $chars; $i++) {
1347 // XXX: convert to string and back
1348 $num = hexdec(common_good_rand(1));
1349 // XXX: randomness is too precious to throw away almost
1350 // 40% of the bits we get!
1351 $code .= $codechars[$num%32];
1356 // convert markup to HTML
1358 function common_markup_to_html($c)
1360 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1361 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1362 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1363 return Markdown($c);
1366 function common_profile_uri($profile)
1371 $user = User::staticGet($profile->id);
1376 $remote = Remote_profile::staticGet($profile->id);
1378 return $remote->uri;
1380 // XXX: this is a very bad profile!
1384 function common_canonical_sms($sms)
1387 preg_replace('/\D/', '', $sms);
1391 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1396 case E_COMPILE_ERROR:
1400 case E_RECOVERABLE_ERROR:
1401 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1406 case E_COMPILE_WARNING:
1407 case E_CORE_WARNING:
1408 case E_USER_WARNING:
1409 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1414 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1419 case E_USER_DEPRECATED:
1420 // XXX: config variable to log this stuff, too
1424 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1429 // FIXME: show error page if we're on the Web
1430 /* Don't execute PHP internal error handler */
1434 function common_session_token()
1436 common_ensure_session();
1437 if (!array_key_exists('token', $_SESSION)) {
1438 $_SESSION['token'] = common_good_rand(64);
1440 return $_SESSION['token'];
1443 function common_cache_key($extra)
1445 return Cache::key($extra);
1448 function common_keyize($str)
1450 return Cache::keyize($str);
1453 function common_memcache()
1455 return Cache::instance();
1458 function common_license_terms($uri)
1460 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1461 return explode('-',$matches[1]);
1466 function common_compatible_license($from, $to)
1468 $from_terms = common_license_terms($from);
1469 // public domain and cc-by are compatible with everything
1470 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1473 $to_terms = common_license_terms($to);
1474 // sa is compatible across versions. IANAL
1475 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1476 return count(array_diff($from_terms, $to_terms)) == 0;
1478 // XXX: better compatibility check needed here!
1479 // Should at least normalise URIs
1480 return ($from == $to);
1484 * returns a quoted table name, if required according to config
1486 function common_database_tablename($tablename)
1489 if(common_config('db','quote_identifiers')) {
1490 $tablename = '"'. $tablename .'"';
1492 //table prefixes could be added here later
1497 * Shorten a URL with the current user's configured shortening service,
1498 * or ur1.ca if configured, or not at all if no shortening is set up.
1499 * Length is not considered.
1501 * @param string $long_url
1502 * @return string may return the original URL if shortening failed
1504 * @fixme provide a way to specify a particular shortener
1505 * @fixme provide a way to specify to use a given user's shortening preferences
1507 function common_shorten_url($long_url)
1509 $user = common_current_user();
1511 // common current user does not find a user when called from the XMPP daemon
1512 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1513 $shortenerName = 'ur1.ca';
1515 $shortenerName = $user->urlshorteningservice;
1518 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1519 //URL wasn't shortened, so return the long url
1522 //URL was shortened, so return the result
1523 return $shortenedUrl;
1528 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1529 * null if not a web request
1531 * @fixme X-Forwarded-For can be chained by multiple proxies;
1532 we should parse the list and provide a cleaner array
1533 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1534 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1535 * use function to get exact request headers from Apache if possible.
1537 function common_client_ip()
1539 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1543 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1544 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1545 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1547 $proxy = $_SERVER['REMOTE_ADDR'];
1549 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1552 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1553 $ip = $_SERVER['HTTP_CLIENT_IP'];
1555 $ip = $_SERVER['REMOTE_ADDR'];
1559 return array($proxy, $ip);