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 return md5($password . $id);
125 // check if a username exists and has matching password
127 function common_check_user($nickname, $password)
129 $authenticatedUser = false;
131 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
132 $user = User::staticGet('nickname', $nickname);
134 if (!empty($password)) { // never allow login with blank password
135 if (0 == strcmp(common_munge_password($password, $user->id),
137 //internal checking passed
138 $authenticatedUser = $user;
142 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
145 return $authenticatedUser;
148 // is the current user logged in?
149 function common_logged_in()
151 return (!is_null(common_current_user()));
154 function common_have_session()
156 return (0 != strcmp(session_id(), ''));
159 function common_ensure_session()
162 if (array_key_exists(session_name(), $_COOKIE)) {
163 $c = $_COOKIE[session_name()];
165 if (!common_have_session()) {
166 if (common_config('sessions', 'handle')) {
167 Session::setSaveHandler();
170 if (!isset($_SESSION['started'])) {
171 $_SESSION['started'] = time();
173 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
174 ' is set but started value is null');
180 // Three kinds of arguments:
185 // Initialize to false; set to null if none found
189 function common_set_user($user)
194 if (is_null($user) && common_have_session()) {
196 unset($_SESSION['userid']);
198 } else if (is_string($user)) {
200 $user = User::staticGet('nickname', $nickname);
201 } else if (!($user instanceof User)) {
206 if (Event::handle('StartSetUser', array(&$user))) {
208 common_ensure_session();
209 $_SESSION['userid'] = $user->id;
211 Event::handle('EndSetUser', array($user));
219 function common_set_cookie($key, $value, $expiration=0)
221 $path = common_config('site', 'path');
222 $server = common_config('site', 'server');
224 if ($path && ($path != '/')) {
225 $cookiepath = '/' . $path . '/';
229 return setcookie($key,
236 define('REMEMBERME', 'rememberme');
237 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
239 function common_rememberme($user=null)
242 $user = common_current_user();
244 common_debug('No current user to remember', __FILE__);
249 $rm = new Remember_me();
251 $rm->code = common_good_rand(16);
252 $rm->user_id = $user->id;
254 // Wrap the insert in some good ol' fashioned transaction code
258 $result = $rm->insert();
261 common_log_db_error($rm, 'INSERT', __FILE__);
262 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
266 $rm->query('COMMIT');
268 common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__);
270 $cookieval = $rm->user_id . ':' . $rm->code;
272 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
274 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
279 function common_remembered_user()
284 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
290 list($id, $code) = explode(':', $packed);
292 if (!$id || !$code) {
293 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
298 $rm = Remember_me::staticGet($code);
301 common_log(LOG_WARNING, 'No such remember code: ' . $code);
306 if ($rm->user_id != $id) {
307 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
312 $user = User::staticGet($rm->user_id);
315 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
321 $result = $rm->delete();
324 common_log_db_error($rm, 'DELETE', __FILE__);
325 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
330 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
332 common_set_user($user);
333 common_real_login(false);
335 // We issue a new cookie, so they can log in
336 // automatically again after this session
338 common_rememberme($user);
343 // must be called with a valid user!
345 function common_forgetme()
347 common_set_cookie(REMEMBERME, '', 0);
350 // who is the current user?
351 function common_current_user()
355 if (!_have_config()) {
359 if ($_cur === false) {
361 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
362 common_ensure_session();
363 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
365 $user = User::staticGet($id);
373 // that didn't work; try to remember; will init $_cur to null on failure
374 $_cur = common_remembered_user();
377 common_debug("Got User " . $_cur->nickname);
378 common_debug("Faking session on remembered user");
379 // XXX: Is this necessary?
380 $_SESSION['userid'] = $_cur->id;
387 // Logins that are 'remembered' aren't 'real' -- they're subject to
388 // cookie-stealing. So, we don't let them do certain things. New reg,
389 // OpenID, and password logins _are_ real.
391 function common_real_login($real=true)
393 common_ensure_session();
394 $_SESSION['real_login'] = $real;
397 function common_is_real_login()
399 return common_logged_in() && $_SESSION['real_login'];
402 // get canonical version of nickname for comparison
403 function common_canonical_nickname($nickname)
405 // XXX: UTF-8 canonicalization (like combining chars)
406 return strtolower($nickname);
409 // get canonical version of email for comparison
410 function common_canonical_email($email)
412 // XXX: canonicalize UTF-8
413 // XXX: lcase the domain part
417 function common_render_content($text, $notice)
419 $r = common_render_text($text);
420 $id = $notice->profile_id;
421 $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
422 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
423 $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r);
424 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
428 function common_render_text($text)
430 $r = htmlspecialchars($text);
432 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
433 $r = common_replace_urls_callback($r, 'common_linkify');
434 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
439 function common_replace_urls_callback($text, $callback, $notice_id = null) {
440 // Start off with a regex
442 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
445 '(?:'. //Known protocols
447 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
449 '(?:(?:mailto|aim|tel|xmpp):)'.
451 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
454 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
456 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
460 '|(?:(?: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
462 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
464 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
465 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
466 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
467 '(?: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)'.
471 '(?:\:\d+)?'. //:port
472 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
473 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
474 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
475 ')(?<![\?\.\,\#\,])'.
478 //preg_match_all($regex,$text,$matches);
480 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
483 function callback_helper($matches, $callback, $notice_id) {
485 $left = strpos($matches[0],$url);
486 $right = $left+strlen($url);
488 $groupSymbolSets=array(
506 $cannotEndWith=array('.','?',',','#');
510 foreach($groupSymbolSets as $groupSymbolSet){
511 if(substr($url,-1)==$groupSymbolSet['right']){
512 $group_left_count = substr_count($url,$groupSymbolSet['left']);
513 $group_right_count = substr_count($url,$groupSymbolSet['right']);
514 if($group_left_count<$group_right_count){
516 $url=substr($url,0,-1);
520 if(in_array(substr($url,-1),$cannotEndWith)){
522 $url=substr($url,0,-1);
524 }while($original_url!=$url);
526 if(empty($notice_id)){
527 $result = call_user_func_array($callback, array($url));
529 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
531 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
534 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
535 // lambda implementation in a separate file; PHP 5.2 won't parse it.
536 require_once INSTALLDIR . "/lib/curry.php";
538 function curry($fn) {
539 $args = func_get_args();
541 $id = uniqid('_partial');
542 $GLOBALS[$id] = array($fn, $args);
543 return create_function('',
544 '$args = func_get_args(); '.
545 'return call_user_func_array('.
546 '$GLOBALS["'.$id.'"][0],'.
549 '$GLOBALS["'.$id.'"][1]));');
553 function common_linkify($url) {
554 // It comes in special'd, so we unspecial it before passing to the stringifying
556 $url = htmlspecialchars_decode($url);
558 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
559 //url is an email address without the mailto: protocol
560 $canon = "mailto:$url";
561 $longurl = "mailto:$url";
564 $canon = File_redirection::_canonUrl($url);
566 $longurl_data = File_redirection::where($canon);
567 if (is_array($longurl_data)) {
568 $longurl = $longurl_data['url'];
569 } elseif (is_string($longurl_data)) {
570 $longurl = $longurl_data;
572 throw new ServerException("Can't linkify url '$url'");
575 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
577 $is_attachment = false;
578 $attachment_id = null;
581 // Check to see whether this is a known "attachment" URL.
583 $f = File::staticGet('url', $longurl);
586 // XXX: this writes to the database. :<
587 $f = File::processNew($longurl);
591 if ($f->isEnclosure()) {
592 $is_attachment = true;
593 $attachment_id = $f->id;
595 $foe = File_oembed::staticGet('file_id', $f->id);
597 // if it has OEmbed info, it's an attachment, too
598 $is_attachment = true;
599 $attachment_id = $f->id;
601 $thumb = File_thumbnail::staticGet('file_id', $f->id);
602 if (!empty($thumb)) {
610 if ($is_attachment) {
611 $attrs['class'] = 'attachment';
613 $attrs['class'] = 'attachment thumbnail';
615 $attrs['id'] = "attachment-{$attachment_id}";
618 return XMLStringer::estring('a', $attrs, $url);
621 function common_shorten_links($text)
623 $maxLength = Notice::maxContent();
624 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
625 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
628 function common_xml_safe_str($str)
630 // Neutralize control codes and surrogates
631 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
634 function common_tag_link($tag)
636 $canonical = common_canonical_tag($tag);
637 $url = common_local_url('tag', array('tag' => $canonical));
638 $xs = new XMLStringer();
639 $xs->elementStart('span', 'tag');
640 $xs->element('a', array('href' => $url,
643 $xs->elementEnd('span');
644 return $xs->getString();
647 function common_canonical_tag($tag)
649 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
650 return str_replace(array('-', '_', '.'), '', $tag);
653 function common_valid_profile_tag($str)
655 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
658 function common_at_link($sender_id, $nickname)
660 $sender = Profile::staticGet($sender_id);
661 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
663 $user = User::staticGet('id', $recipient->id);
665 $url = common_local_url('userbyid', array('id' => $user->id));
667 $url = $recipient->profileurl;
669 $xs = new XMLStringer(false);
670 $attrs = array('href' => $url,
672 if (!empty($recipient->fullname)) {
673 $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')';
675 $xs->elementStart('span', 'vcard');
676 $xs->elementStart('a', $attrs);
677 $xs->element('span', 'fn nickname', $nickname);
678 $xs->elementEnd('a');
679 $xs->elementEnd('span');
680 return $xs->getString();
686 function common_group_link($sender_id, $nickname)
688 $sender = Profile::staticGet($sender_id);
689 $group = User_group::getForNickname($nickname);
690 if ($group && $sender->isMember($group)) {
691 $attrs = array('href' => $group->permalink(),
693 if (!empty($group->fullname)) {
694 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
696 $xs = new XMLStringer();
697 $xs->elementStart('span', 'vcard');
698 $xs->elementStart('a', $attrs);
699 $xs->element('span', 'fn nickname', $nickname);
700 $xs->elementEnd('a');
701 $xs->elementEnd('span');
702 return $xs->getString();
708 function common_at_hash_link($sender_id, $tag)
710 $user = User::staticGet($sender_id);
714 $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag));
716 $url = common_local_url('subscriptions',
717 array('nickname' => $user->nickname,
719 $xs = new XMLStringer();
720 $xs->elementStart('span', 'tag');
721 $xs->element('a', array('href' => $url,
724 $xs->elementEnd('span');
725 return $xs->getString();
731 function common_relative_profile($sender, $nickname, $dt=null)
733 // Try to find profiles this profile is subscribed to that have this nickname
734 $recipient = new Profile();
735 // XXX: use a join instead of a subquery
736 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
737 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
738 if ($recipient->find(true)) {
739 // XXX: should probably differentiate between profiles with
740 // the same name by date of most recent update
743 // Try to find profiles that listen to this profile and that have this nickname
744 $recipient = new Profile();
745 // XXX: use a join instead of a subquery
746 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
747 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
748 if ($recipient->find(true)) {
749 // XXX: should probably differentiate between profiles with
750 // the same name by date of most recent update
753 // If this is a local user, try to find a local user with that nickname.
754 $sender = User::staticGet($sender->id);
756 $recipient_user = User::staticGet('nickname', $nickname);
757 if ($recipient_user) {
758 return $recipient_user->getProfile();
761 // Otherwise, no links. @messages from local users to remote users,
762 // or from remote users to other remote users, are just
763 // outside our ability to make intelligent guesses about
767 function common_local_url($action, $args=null, $params=null, $fragment=null)
770 $path = $r->build($action, $args, $params, $fragment);
772 $ssl = common_is_sensitive($action);
774 if (common_config('site','fancy')) {
775 $url = common_path(mb_substr($path, 1), $ssl);
777 if (mb_strpos($path, '/index.php') === 0) {
778 $url = common_path(mb_substr($path, 1), $ssl);
780 $url = common_path('index.php'.$path, $ssl);
786 function common_is_sensitive($action)
788 static $sensitive = array('login', 'register', 'passwordsettings',
789 'twittersettings', 'api');
792 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
793 $ssl = in_array($action, $sensitive);
799 function common_path($relative, $ssl=false)
801 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
803 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
804 || common_config('site', 'ssl') === 'always') {
806 if (is_string(common_config('site', 'sslserver')) &&
807 mb_strlen(common_config('site', 'sslserver')) > 0) {
808 $serverpart = common_config('site', 'sslserver');
809 } else if (common_config('site', 'server')) {
810 $serverpart = common_config('site', 'server');
812 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
816 if (common_config('site', 'server')) {
817 $serverpart = common_config('site', 'server');
819 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
823 if (common_have_session()) {
825 $currentServer = $_SERVER['HTTP_HOST'];
827 // Are we pointing to another server (like an SSL server?)
829 if (!empty($currentServer) &&
830 0 != strcasecmp($currentServer, $serverpart)) {
831 // Pass the session ID as a GET parameter
832 $sesspart = session_name() . '=' . session_id();
833 $i = strpos($relative, '?');
834 if ($i === false) { // no GET params, just append
835 $relative .= '?' . $sesspart;
837 $relative = substr($relative, 0, $i + 1).$sesspart.'&'.substr($relative, $i + 1);
842 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
845 function common_date_string($dt)
847 // XXX: do some sexy date formatting
848 // return date(DATE_RFC822, $dt);
853 if ($now < $t) { // that shouldn't happen!
854 return common_exact_date($dt);
855 } else if ($diff < 60) {
856 return _('a few seconds ago');
857 } else if ($diff < 92) {
858 return _('about a minute ago');
859 } else if ($diff < 3300) {
860 return sprintf(_('about %d minutes ago'), round($diff/60));
861 } else if ($diff < 5400) {
862 return _('about an hour ago');
863 } else if ($diff < 22 * 3600) {
864 return sprintf(_('about %d hours ago'), round($diff/3600));
865 } else if ($diff < 37 * 3600) {
866 return _('about a day ago');
867 } else if ($diff < 24 * 24 * 3600) {
868 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
869 } else if ($diff < 46 * 24 * 3600) {
870 return _('about a month ago');
871 } else if ($diff < 330 * 24 * 3600) {
872 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
873 } else if ($diff < 480 * 24 * 3600) {
874 return _('about a year ago');
876 return common_exact_date($dt);
880 function common_exact_date($dt)
886 $_utc = new DateTimeZone('UTC');
887 $_siteTz = new DateTimeZone(common_timezone());
890 $dateStr = date('d F Y H:i:s', strtotime($dt));
891 $d = new DateTime($dateStr, $_utc);
892 $d->setTimezone($_siteTz);
893 return $d->format(DATE_RFC850);
896 function common_date_w3dtf($dt)
898 $dateStr = date('d F Y H:i:s', strtotime($dt));
899 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
900 $d->setTimezone(new DateTimeZone(common_timezone()));
901 return $d->format(DATE_W3C);
904 function common_date_rfc2822($dt)
906 $dateStr = date('d F Y H:i:s', strtotime($dt));
907 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
908 $d->setTimezone(new DateTimeZone(common_timezone()));
909 return $d->format('r');
912 function common_date_iso8601($dt)
914 $dateStr = date('d F Y H:i:s', strtotime($dt));
915 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
916 $d->setTimezone(new DateTimeZone(common_timezone()));
917 return $d->format('c');
920 function common_sql_now()
922 return common_sql_date(time());
925 function common_sql_date($datetime)
927 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
931 * Return an SQL fragment to calculate an age-based weight from a given
932 * timestamp or datetime column.
934 * @param string $column name of field we're comparing against current time
935 * @param integer $dropoff divisor for age in seconds before exponentiation
936 * @return string SQL fragment
938 function common_sql_weight($column, $dropoff)
940 if (common_config('db', 'type') == 'pgsql') {
941 // PostgreSQL doesn't support timestampdiff function.
942 // @fixme will this use the right time zone?
943 // @fixme does this handle cross-year subtraction correctly?
944 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
946 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
950 function common_redirect($url, $code=307)
952 static $status = array(301 => "Moved Permanently",
955 307 => "Temporary Redirect");
957 header('HTTP/1.1 '.$code.' '.$status[$code]);
958 header("Location: $url");
960 $xo = new XMLOutputter();
962 '-//W3C//DTD XHTML 1.0 Strict//EN',
963 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
964 $xo->element('a', array('href' => $url), $url);
969 function common_broadcast_notice($notice, $remote=false)
971 return common_enqueue_notice($notice);
974 // Stick the notice on the queue
976 function common_enqueue_notice($notice)
978 static $localTransports = array('omb',
981 static $allTransports = array('sms', 'plugin');
983 $transports = $allTransports;
985 $xmpp = common_config('xmpp', 'enabled');
988 $transports[] = 'jabber';
991 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
992 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
993 $transports = array_merge($transports, $localTransports);
995 $transports[] = 'public';
999 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1001 $qm = QueueManager::get();
1003 foreach ($transports as $transport)
1005 $qm->enqueue($notice, $transport);
1008 Event::handle('EndEnqueueNotice', array($notice, $transports));
1014 function common_broadcast_profile($profile)
1016 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1017 require_once(INSTALLDIR.'/lib/omb.php');
1018 omb_broadcast_profile($profile);
1019 // XXX: Other broadcasts...?
1023 function common_profile_url($nickname)
1025 return common_local_url('showstream', array('nickname' => $nickname));
1028 // Should make up a reasonable root URL
1030 function common_root_url($ssl=false)
1032 return common_path('', $ssl);
1035 // returns $bytes bytes of random data as a hexadecimal string
1036 // "good" here is a goal and not a guarantee
1038 function common_good_rand($bytes)
1040 // XXX: use random.org...?
1041 if (@file_exists('/dev/urandom')) {
1042 return common_urandom($bytes);
1043 } else { // FIXME: this is probably not good enough
1044 return common_mtrand($bytes);
1048 function common_urandom($bytes)
1050 $h = fopen('/dev/urandom', 'rb');
1052 $src = fread($h, $bytes);
1055 for ($i = 0; $i < $bytes; $i++) {
1056 $enc .= sprintf("%02x", (ord($src[$i])));
1061 function common_mtrand($bytes)
1064 for ($i = 0; $i < $bytes; $i++) {
1065 $enc .= sprintf("%02x", mt_rand(0, 255));
1070 function common_set_returnto($url)
1072 common_ensure_session();
1073 $_SESSION['returnto'] = $url;
1076 function common_get_returnto()
1078 common_ensure_session();
1079 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1082 function common_timestamp()
1084 return date('YmdHis');
1087 function common_ensure_syslog()
1089 static $initialized = false;
1090 if (!$initialized) {
1091 openlog(common_config('syslog', 'appname'), 0,
1092 common_config('syslog', 'facility'));
1093 $initialized = true;
1097 function common_log_line($priority, $msg)
1099 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1100 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1101 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1104 function common_request_id()
1107 if (php_sapi_name() == 'cli') {
1110 static $req_id = null;
1111 if (!isset($req_id)) {
1112 $req_id = substr(md5(mt_rand()), 0, 8);
1114 if (isset($_SERVER['REQUEST_URI'])) {
1115 $url = $_SERVER['REQUEST_URI'];
1117 $method = $_SERVER['REQUEST_METHOD'];
1118 return "$pid.$req_id $method $url";
1122 function common_log($priority, $msg, $filename=null)
1124 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1125 $msg = '[' . common_request_id() . '] ' . $msg;
1126 $logfile = common_config('site', 'logfile');
1128 $log = fopen($logfile, "a");
1130 $output = common_log_line($priority, $msg);
1131 fwrite($log, $output);
1135 common_ensure_syslog();
1136 syslog($priority, $msg);
1138 Event::handle('EndLog', array($priority, $msg, $filename));
1142 function common_debug($msg, $filename=null)
1145 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1147 common_log(LOG_DEBUG, $msg);
1151 function common_log_db_error(&$object, $verb, $filename=null)
1153 $objstr = common_log_objstring($object);
1154 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1155 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1158 function common_log_objstring(&$object)
1160 if (is_null($object)) {
1163 if (!($object instanceof DB_DataObject)) {
1166 $arr = $object->toArray();
1168 foreach ($arr as $k => $v) {
1169 if (is_object($v)) {
1170 $fields[] = "$k='".get_class($v)."'";
1172 $fields[] = "$k='$v'";
1175 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1179 function common_valid_http_url($url)
1181 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1184 function common_valid_tag($tag)
1186 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1187 return (Validate::email($matches[1]) ||
1188 preg_match('/^([\w-\.]+)$/', $matches[1]));
1193 /* Following functions are copied from MediaWiki GlobalFunctions.php
1194 * and written by Evan Prodromou. */
1196 function common_accept_to_prefs($accept, $def = '*/*')
1198 // No arg means accept anything (per HTTP spec)
1200 return array($def => 1);
1205 $parts = explode(',', $accept);
1207 foreach($parts as $part) {
1208 // FIXME: doesn't deal with params like 'text/html; level=1'
1209 @list($value, $qpart) = explode(';', trim($part));
1211 if(!isset($qpart)) {
1213 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1214 $prefs[$value] = $match[1];
1221 function common_mime_type_match($type, $avail)
1223 if(array_key_exists($type, $avail)) {
1226 $parts = explode('/', $type);
1227 if(array_key_exists($parts[0] . '/*', $avail)) {
1228 return $parts[0] . '/*';
1229 } elseif(array_key_exists('*/*', $avail)) {
1237 function common_negotiate_type($cprefs, $sprefs)
1241 foreach(array_keys($sprefs) as $type) {
1242 $parts = explode('/', $type);
1243 if($parts[1] != '*') {
1244 $ckey = common_mime_type_match($type, $cprefs);
1246 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1251 foreach(array_keys($cprefs) as $type) {
1252 $parts = explode('/', $type);
1253 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1254 $skey = common_mime_type_match($type, $sprefs);
1256 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1262 $besttype = 'text/html';
1264 foreach(array_keys($combine) as $type) {
1265 if($combine[$type] > $bestq) {
1267 $bestq = $combine[$type];
1271 if ('text/html' === $besttype) {
1272 return "text/html; charset=utf-8";
1277 function common_config($main, $sub)
1280 return (array_key_exists($main, $config) &&
1281 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1284 function common_copy_args($from)
1287 $strip = get_magic_quotes_gpc();
1288 foreach ($from as $k => $v) {
1289 $to[$k] = ($strip) ? stripslashes($v) : $v;
1295 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1296 * This is used before handing a request off to OAuthRequest::from_request.
1297 * @fixme Doesn't consider vars other than _POST and _GET?
1298 * @fixme Can't be undone and could corrupt data if run twice.
1300 function common_remove_magic_from_request()
1302 if(get_magic_quotes_gpc()) {
1303 $_POST=array_map('stripslashes',$_POST);
1304 $_GET=array_map('stripslashes',$_GET);
1308 function common_user_uri(&$user)
1310 return common_local_url('userbyid', array('id' => $user->id));
1313 function common_notice_uri(&$notice)
1315 return common_local_url('shownotice',
1316 array('notice' => $notice->id));
1319 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1321 function common_confirmation_code($bits)
1323 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1324 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1325 $chars = ceil($bits/5);
1327 for ($i = 0; $i < $chars; $i++) {
1328 // XXX: convert to string and back
1329 $num = hexdec(common_good_rand(1));
1330 // XXX: randomness is too precious to throw away almost
1331 // 40% of the bits we get!
1332 $code .= $codechars[$num%32];
1337 // convert markup to HTML
1339 function common_markup_to_html($c)
1341 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1342 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1343 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1344 return Markdown($c);
1347 function common_profile_uri($profile)
1352 $user = User::staticGet($profile->id);
1357 $remote = Remote_profile::staticGet($profile->id);
1359 return $remote->uri;
1361 // XXX: this is a very bad profile!
1365 function common_canonical_sms($sms)
1368 preg_replace('/\D/', '', $sms);
1372 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1377 case E_COMPILE_ERROR:
1381 case E_RECOVERABLE_ERROR:
1382 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1387 case E_COMPILE_WARNING:
1388 case E_CORE_WARNING:
1389 case E_USER_WARNING:
1390 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1395 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1400 case E_USER_DEPRECATED:
1401 // XXX: config variable to log this stuff, too
1405 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1410 // FIXME: show error page if we're on the Web
1411 /* Don't execute PHP internal error handler */
1415 function common_session_token()
1417 common_ensure_session();
1418 if (!array_key_exists('token', $_SESSION)) {
1419 $_SESSION['token'] = common_good_rand(64);
1421 return $_SESSION['token'];
1424 function common_cache_key($extra)
1426 return Cache::key($extra);
1429 function common_keyize($str)
1431 return Cache::keyize($str);
1434 function common_memcache()
1436 return Cache::instance();
1439 function common_license_terms($uri)
1441 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1442 return explode('-',$matches[1]);
1447 function common_compatible_license($from, $to)
1449 $from_terms = common_license_terms($from);
1450 // public domain and cc-by are compatible with everything
1451 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1454 $to_terms = common_license_terms($to);
1455 // sa is compatible across versions. IANAL
1456 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1457 return count(array_diff($from_terms, $to_terms)) == 0;
1459 // XXX: better compatibility check needed here!
1460 // Should at least normalise URIs
1461 return ($from == $to);
1465 * returns a quoted table name, if required according to config
1467 function common_database_tablename($tablename)
1470 if(common_config('db','quote_identifiers')) {
1471 $tablename = '"'. $tablename .'"';
1473 //table prefixes could be added here later
1478 * Shorten a URL with the current user's configured shortening service,
1479 * or ur1.ca if configured, or not at all if no shortening is set up.
1480 * Length is not considered.
1482 * @param string $long_url
1483 * @return string may return the original URL if shortening failed
1485 * @fixme provide a way to specify a particular shortener
1486 * @fixme provide a way to specify to use a given user's shortening preferences
1488 function common_shorten_url($long_url)
1490 $user = common_current_user();
1492 // common current user does not find a user when called from the XMPP daemon
1493 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1494 $shortenerName = 'ur1.ca';
1496 $shortenerName = $user->urlshorteningservice;
1499 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1500 //URL wasn't shortened, so return the long url
1503 //URL was shortened, so return the result
1504 return $shortenedUrl;
1509 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1510 * null if not a web request
1512 * @fixme X-Forwarded-For can be chained by multiple proxies;
1513 we should parse the list and provide a cleaner array
1514 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1515 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1516 * use function to get exact request headers from Apache if possible.
1518 function common_client_ip()
1520 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1524 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1525 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1526 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1528 $proxy = $_SERVER['REMOTE_ADDR'];
1530 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1533 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1534 $ip = $_SERVER['HTTP_CLIENT_IP'];
1536 $ip = $_SERVER['REMOTE_ADDR'];
1540 return array($proxy, $ip);