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', common_canonical_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()];
183 if (!isset($_SESSION['started'])) {
184 $_SESSION['started'] = time();
186 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
187 ' is set but started value is null');
193 // Three kinds of arguments:
198 // Initialize to false; set to null if none found
202 function common_set_user($user)
207 if (is_null($user) && common_have_session()) {
209 unset($_SESSION['userid']);
211 } else if (is_string($user)) {
213 $user = User::staticGet('nickname', $nickname);
214 } else if (!($user instanceof User)) {
219 if (Event::handle('StartSetUser', array(&$user))) {
221 common_ensure_session();
222 $_SESSION['userid'] = $user->id;
224 Event::handle('EndSetUser', array($user));
232 function common_set_cookie($key, $value, $expiration=0)
234 $path = common_config('site', 'path');
235 $server = common_config('site', 'server');
237 if ($path && ($path != '/')) {
238 $cookiepath = '/' . $path . '/';
242 return setcookie($key,
249 define('REMEMBERME', 'rememberme');
250 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
252 function common_rememberme($user=null)
255 $user = common_current_user();
261 $rm = new Remember_me();
263 $rm->code = common_good_rand(16);
264 $rm->user_id = $user->id;
266 // Wrap the insert in some good ol' fashioned transaction code
270 $result = $rm->insert();
273 common_log_db_error($rm, 'INSERT', __FILE__);
277 $rm->query('COMMIT');
279 $cookieval = $rm->user_id . ':' . $rm->code;
281 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
283 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
288 function common_remembered_user()
293 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
299 list($id, $code) = explode(':', $packed);
301 if (!$id || !$code) {
302 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
307 $rm = Remember_me::staticGet($code);
310 common_log(LOG_WARNING, 'No such remember code: ' . $code);
315 if ($rm->user_id != $id) {
316 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
321 $user = User::staticGet($rm->user_id);
324 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
330 $result = $rm->delete();
333 common_log_db_error($rm, 'DELETE', __FILE__);
334 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
339 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
341 common_set_user($user);
342 common_real_login(false);
344 // We issue a new cookie, so they can log in
345 // automatically again after this session
347 common_rememberme($user);
352 // must be called with a valid user!
354 function common_forgetme()
356 common_set_cookie(REMEMBERME, '', 0);
359 // who is the current user?
360 function common_current_user()
364 if (!_have_config()) {
368 if ($_cur === false) {
370 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
371 || (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 = common_linkify_mentions($id, $r);
430 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
434 function common_linkify_mentions($profile_id, $text)
436 $mentions = common_find_mentions($profile_id, $text);
438 // We need to go through in reverse order by position,
439 // so our positions stay valid despite our fudging with the
444 foreach ($mentions as $mention)
446 $points[$mention['position']] = $mention;
451 foreach ($points as $position => $mention) {
453 $linkText = common_linkify_mention($mention);
455 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
461 function common_linkify_mention($mention)
465 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
467 $xs = new XMLStringer(false);
469 $attrs = array('href' => $mention['url'],
472 if (!empty($mention['title'])) {
473 $attrs['title'] = $mention['title'];
476 $xs->elementStart('span', 'vcard');
477 $xs->elementStart('a', $attrs);
478 $xs->element('span', 'fn nickname', $mention['text']);
479 $xs->elementEnd('a');
480 $xs->elementEnd('span');
482 $output = $xs->getString();
484 Event::handle('EndLinkifyMention', array($mention, &$output));
490 function common_find_mentions($profile_id, $text)
494 $sender = Profile::staticGet('id', $profile_id);
496 if (empty($sender)) {
500 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
502 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
505 PREG_OFFSET_CAPTURE);
507 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
510 PREG_OFFSET_CAPTURE);
512 $matches = array_merge($tmatches[1], $atmatches[1]);
514 foreach ($matches as $match) {
516 $nickname = common_canonical_nickname($match[0]);
517 $mentioned = common_relative_profile($sender, $nickname);
519 if (!empty($mentioned)) {
521 $user = User::staticGet('id', $mentioned->id);
524 $url = common_local_url('userbyid', array('id' => $user->id));
526 $url = $mentioned->profileurl;
529 $mention = array('mentioned' => array($mentioned),
531 'position' => $match[1],
534 if (!empty($mentioned->fullname)) {
535 $mention['title'] = $mentioned->fullname;
538 $mentions[] = $mention;
542 // @#tag => mention of all subscriptions tagged 'tag'
544 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
547 PREG_OFFSET_CAPTURE);
549 foreach ($hmatches[1] as $hmatch) {
551 $tag = common_canonical_tag($hmatch[0]);
553 $tagged = Profile_tag::getTagged($sender->id, $tag);
555 $url = common_local_url('subscriptions',
556 array('nickname' => $sender->nickname,
559 $mentions[] = array('mentioned' => $tagged,
560 'text' => $hmatch[0],
561 'position' => $hmatch[1],
565 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
571 function common_render_text($text)
573 $r = htmlspecialchars($text);
575 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
576 $r = common_replace_urls_callback($r, 'common_linkify');
577 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
582 function common_replace_urls_callback($text, $callback, $notice_id = null) {
583 // Start off with a regex
585 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
588 '(?:'. //Known protocols
590 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
592 '(?:(?:mailto|aim|tel|xmpp):)'.
594 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
597 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
599 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
603 '|(?:(?: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
605 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
607 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
608 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
609 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
610 '(?: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)'.
614 '(?:\:\d+)?'. //:port
615 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
616 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
617 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
618 ')(?<![\?\.\,\#\,])'.
621 //preg_match_all($regex,$text,$matches);
623 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
626 function callback_helper($matches, $callback, $notice_id) {
628 $left = strpos($matches[0],$url);
629 $right = $left+strlen($url);
631 $groupSymbolSets=array(
649 $cannotEndWith=array('.','?',',','#');
653 foreach($groupSymbolSets as $groupSymbolSet){
654 if(substr($url,-1)==$groupSymbolSet['right']){
655 $group_left_count = substr_count($url,$groupSymbolSet['left']);
656 $group_right_count = substr_count($url,$groupSymbolSet['right']);
657 if($group_left_count<$group_right_count){
659 $url=substr($url,0,-1);
663 if(in_array(substr($url,-1),$cannotEndWith)){
665 $url=substr($url,0,-1);
667 }while($original_url!=$url);
669 if(empty($notice_id)){
670 $result = call_user_func_array($callback, array($url));
672 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
674 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
677 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
678 // lambda implementation in a separate file; PHP 5.2 won't parse it.
679 require_once INSTALLDIR . "/lib/curry.php";
681 function curry($fn) {
682 $args = func_get_args();
684 $id = uniqid('_partial');
685 $GLOBALS[$id] = array($fn, $args);
686 return create_function('',
687 '$args = func_get_args(); '.
688 'return call_user_func_array('.
689 '$GLOBALS["'.$id.'"][0],'.
692 '$GLOBALS["'.$id.'"][1]));');
696 function common_linkify($url) {
697 // It comes in special'd, so we unspecial it before passing to the stringifying
699 $url = htmlspecialchars_decode($url);
701 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
702 //url is an email address without the mailto: protocol
703 $canon = "mailto:$url";
704 $longurl = "mailto:$url";
707 $canon = File_redirection::_canonUrl($url);
709 $longurl_data = File_redirection::where($canon);
710 if (is_array($longurl_data)) {
711 $longurl = $longurl_data['url'];
712 } elseif (is_string($longurl_data)) {
713 $longurl = $longurl_data;
715 throw new ServerException("Can't linkify url '$url'");
718 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
720 $is_attachment = false;
721 $attachment_id = null;
724 // Check to see whether this is a known "attachment" URL.
726 $f = File::staticGet('url', $longurl);
729 // XXX: this writes to the database. :<
730 $f = File::processNew($longurl);
734 if ($f->isEnclosure()) {
735 $is_attachment = true;
736 $attachment_id = $f->id;
738 $foe = File_oembed::staticGet('file_id', $f->id);
740 // if it has OEmbed info, it's an attachment, too
741 $is_attachment = true;
742 $attachment_id = $f->id;
744 $thumb = File_thumbnail::staticGet('file_id', $f->id);
745 if (!empty($thumb)) {
753 if ($is_attachment) {
754 $attrs['class'] = 'attachment';
756 $attrs['class'] = 'attachment thumbnail';
758 $attrs['id'] = "attachment-{$attachment_id}";
761 return XMLStringer::estring('a', $attrs, $url);
764 function common_shorten_links($text)
766 $maxLength = Notice::maxContent();
767 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
768 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
771 function common_xml_safe_str($str)
773 // Replace common eol and extra whitespace input chars
778 "\0", // null byte eos
779 "\x0B" // vertical tab
782 $replacement = array(
790 $str = str_replace($unWelcome, $replacement, $str);
792 // Neutralize any additional control codes and UTF-16 surrogates
793 // (Twitter uses '*')
794 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
797 function common_tag_link($tag)
799 $canonical = common_canonical_tag($tag);
800 $url = common_local_url('tag', array('tag' => $canonical));
801 $xs = new XMLStringer();
802 $xs->elementStart('span', 'tag');
803 $xs->element('a', array('href' => $url,
806 $xs->elementEnd('span');
807 return $xs->getString();
810 function common_canonical_tag($tag)
812 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
813 return str_replace(array('-', '_', '.'), '', $tag);
816 function common_valid_profile_tag($str)
818 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
821 function common_group_link($sender_id, $nickname)
823 $sender = Profile::staticGet($sender_id);
824 $group = User_group::getForNickname($nickname);
825 if ($sender && $group && $sender->isMember($group)) {
826 $attrs = array('href' => $group->permalink(),
828 if (!empty($group->fullname)) {
829 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
831 $xs = new XMLStringer();
832 $xs->elementStart('span', 'vcard');
833 $xs->elementStart('a', $attrs);
834 $xs->element('span', 'fn nickname', $nickname);
835 $xs->elementEnd('a');
836 $xs->elementEnd('span');
837 return $xs->getString();
843 function common_relative_profile($sender, $nickname, $dt=null)
845 // Try to find profiles this profile is subscribed to that have this nickname
846 $recipient = new Profile();
847 // XXX: use a join instead of a subquery
848 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
849 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
850 if ($recipient->find(true)) {
851 // XXX: should probably differentiate between profiles with
852 // the same name by date of most recent update
855 // Try to find profiles that listen to this profile and that have this nickname
856 $recipient = new Profile();
857 // XXX: use a join instead of a subquery
858 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
859 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
860 if ($recipient->find(true)) {
861 // XXX: should probably differentiate between profiles with
862 // the same name by date of most recent update
865 // If this is a local user, try to find a local user with that nickname.
866 $sender = User::staticGet($sender->id);
868 $recipient_user = User::staticGet('nickname', $nickname);
869 if ($recipient_user) {
870 return $recipient_user->getProfile();
873 // Otherwise, no links. @messages from local users to remote users,
874 // or from remote users to other remote users, are just
875 // outside our ability to make intelligent guesses about
879 function common_local_url($action, $args=null, $params=null, $fragment=null)
882 $path = $r->build($action, $args, $params, $fragment);
884 $ssl = common_is_sensitive($action);
886 if (common_config('site','fancy')) {
887 $url = common_path(mb_substr($path, 1), $ssl);
889 if (mb_strpos($path, '/index.php') === 0) {
890 $url = common_path(mb_substr($path, 1), $ssl);
892 $url = common_path('index.php'.$path, $ssl);
898 function common_is_sensitive($action)
900 static $sensitive = array('login', 'register', 'passwordsettings',
901 'twittersettings', 'api');
904 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
905 $ssl = in_array($action, $sensitive);
911 function common_path($relative, $ssl=false)
913 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
915 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
916 || common_config('site', 'ssl') === 'always') {
918 if (is_string(common_config('site', 'sslserver')) &&
919 mb_strlen(common_config('site', 'sslserver')) > 0) {
920 $serverpart = common_config('site', 'sslserver');
921 } else if (common_config('site', 'server')) {
922 $serverpart = common_config('site', 'server');
924 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
928 if (common_config('site', 'server')) {
929 $serverpart = common_config('site', 'server');
931 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
935 $relative = common_inject_session($relative, $serverpart);
937 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
940 function common_inject_session($url, $serverpart = null)
942 if (common_have_session()) {
944 if (empty($serverpart)) {
945 $serverpart = parse_url($url, PHP_URL_HOST);
948 $currentServer = $_SERVER['HTTP_HOST'];
950 // Are we pointing to another server (like an SSL server?)
952 if (!empty($currentServer) &&
953 0 != strcasecmp($currentServer, $serverpart)) {
954 // Pass the session ID as a GET parameter
955 $sesspart = session_name() . '=' . session_id();
956 $i = strpos($url, '?');
957 if ($i === false) { // no GET params, just append
958 $url .= '?' . $sesspart;
960 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
968 function common_date_string($dt)
970 // XXX: do some sexy date formatting
971 // return date(DATE_RFC822, $dt);
976 if ($now < $t) { // that shouldn't happen!
977 return common_exact_date($dt);
978 } else if ($diff < 60) {
979 return _('a few seconds ago');
980 } else if ($diff < 92) {
981 return _('about a minute ago');
982 } else if ($diff < 3300) {
983 return sprintf(_('about %d minutes ago'), round($diff/60));
984 } else if ($diff < 5400) {
985 return _('about an hour ago');
986 } else if ($diff < 22 * 3600) {
987 return sprintf(_('about %d hours ago'), round($diff/3600));
988 } else if ($diff < 37 * 3600) {
989 return _('about a day ago');
990 } else if ($diff < 24 * 24 * 3600) {
991 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
992 } else if ($diff < 46 * 24 * 3600) {
993 return _('about a month ago');
994 } else if ($diff < 330 * 24 * 3600) {
995 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
996 } else if ($diff < 480 * 24 * 3600) {
997 return _('about a year ago');
999 return common_exact_date($dt);
1003 function common_exact_date($dt)
1009 $_utc = new DateTimeZone('UTC');
1010 $_siteTz = new DateTimeZone(common_timezone());
1013 $dateStr = date('d F Y H:i:s', strtotime($dt));
1014 $d = new DateTime($dateStr, $_utc);
1015 $d->setTimezone($_siteTz);
1016 return $d->format(DATE_RFC850);
1019 function common_date_w3dtf($dt)
1021 $dateStr = date('d F Y H:i:s', strtotime($dt));
1022 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1023 $d->setTimezone(new DateTimeZone(common_timezone()));
1024 return $d->format(DATE_W3C);
1027 function common_date_rfc2822($dt)
1029 $dateStr = date('d F Y H:i:s', strtotime($dt));
1030 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1031 $d->setTimezone(new DateTimeZone(common_timezone()));
1032 return $d->format('r');
1035 function common_date_iso8601($dt)
1037 $dateStr = date('d F Y H:i:s', strtotime($dt));
1038 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1039 $d->setTimezone(new DateTimeZone(common_timezone()));
1040 return $d->format('c');
1043 function common_sql_now()
1045 return common_sql_date(time());
1048 function common_sql_date($datetime)
1050 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1054 * Return an SQL fragment to calculate an age-based weight from a given
1055 * timestamp or datetime column.
1057 * @param string $column name of field we're comparing against current time
1058 * @param integer $dropoff divisor for age in seconds before exponentiation
1059 * @return string SQL fragment
1061 function common_sql_weight($column, $dropoff)
1063 if (common_config('db', 'type') == 'pgsql') {
1064 // PostgreSQL doesn't support timestampdiff function.
1065 // @fixme will this use the right time zone?
1066 // @fixme does this handle cross-year subtraction correctly?
1067 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1069 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1073 function common_redirect($url, $code=307)
1075 static $status = array(301 => "Moved Permanently",
1078 307 => "Temporary Redirect");
1080 header('HTTP/1.1 '.$code.' '.$status[$code]);
1081 header("Location: $url");
1083 $xo = new XMLOutputter();
1085 '-//W3C//DTD XHTML 1.0 Strict//EN',
1086 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1087 $xo->element('a', array('href' => $url), $url);
1092 function common_broadcast_notice($notice, $remote=false)
1097 // Stick the notice on the queue
1099 function common_enqueue_notice($notice)
1101 static $localTransports = array('omb',
1104 $transports = array();
1105 if (common_config('sms', 'enabled')) {
1106 $transports[] = 'sms';
1108 if (Event::hasHandler('HandleQueuedNotice')) {
1109 $transports[] = 'plugin';
1112 $xmpp = common_config('xmpp', 'enabled');
1115 $transports[] = 'jabber';
1118 // @fixme move these checks into QueueManager and/or individual handlers
1119 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1120 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1121 $transports = array_merge($transports, $localTransports);
1123 $transports[] = 'public';
1127 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1129 $qm = QueueManager::get();
1131 foreach ($transports as $transport)
1133 $qm->enqueue($notice, $transport);
1136 Event::handle('EndEnqueueNotice', array($notice, $transports));
1143 * Broadcast profile updates to OMB and other remote subscribers.
1145 * Since this may be slow with a lot of subscribers or bad remote sites,
1146 * this is run through the background queues if possible.
1148 function common_broadcast_profile(Profile $profile)
1150 $qm = QueueManager::get();
1151 $qm->enqueue($profile, "profile");
1155 function common_profile_url($nickname)
1157 return common_local_url('showstream', array('nickname' => $nickname));
1160 // Should make up a reasonable root URL
1162 function common_root_url($ssl=false)
1164 $url = common_path('', $ssl);
1165 $i = strpos($url, '?');
1167 $url = substr($url, 0, $i);
1172 // returns $bytes bytes of random data as a hexadecimal string
1173 // "good" here is a goal and not a guarantee
1175 function common_good_rand($bytes)
1177 // XXX: use random.org...?
1178 if (@file_exists('/dev/urandom')) {
1179 return common_urandom($bytes);
1180 } else { // FIXME: this is probably not good enough
1181 return common_mtrand($bytes);
1185 function common_urandom($bytes)
1187 $h = fopen('/dev/urandom', 'rb');
1189 $src = fread($h, $bytes);
1192 for ($i = 0; $i < $bytes; $i++) {
1193 $enc .= sprintf("%02x", (ord($src[$i])));
1198 function common_mtrand($bytes)
1201 for ($i = 0; $i < $bytes; $i++) {
1202 $enc .= sprintf("%02x", mt_rand(0, 255));
1207 function common_set_returnto($url)
1209 common_ensure_session();
1210 $_SESSION['returnto'] = $url;
1213 function common_get_returnto()
1215 common_ensure_session();
1216 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1219 function common_timestamp()
1221 return date('YmdHis');
1224 function common_ensure_syslog()
1226 static $initialized = false;
1227 if (!$initialized) {
1228 openlog(common_config('syslog', 'appname'), 0,
1229 common_config('syslog', 'facility'));
1230 $initialized = true;
1234 function common_log_line($priority, $msg)
1236 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1237 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1238 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1241 function common_request_id()
1244 $server = common_config('site', 'server');
1245 if (php_sapi_name() == 'cli') {
1246 $script = basename($_SERVER['PHP_SELF']);
1247 return "$server:$script:$pid";
1249 static $req_id = null;
1250 if (!isset($req_id)) {
1251 $req_id = substr(md5(mt_rand()), 0, 8);
1253 if (isset($_SERVER['REQUEST_URI'])) {
1254 $url = $_SERVER['REQUEST_URI'];
1256 $method = $_SERVER['REQUEST_METHOD'];
1257 return "$server:$pid.$req_id $method $url";
1261 function common_log($priority, $msg, $filename=null)
1263 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1264 $msg = '[' . common_request_id() . '] ' . $msg;
1265 $logfile = common_config('site', 'logfile');
1267 $log = fopen($logfile, "a");
1269 $output = common_log_line($priority, $msg);
1270 fwrite($log, $output);
1274 common_ensure_syslog();
1275 syslog($priority, $msg);
1277 Event::handle('EndLog', array($priority, $msg, $filename));
1281 function common_debug($msg, $filename=null)
1284 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1286 common_log(LOG_DEBUG, $msg);
1290 function common_log_db_error(&$object, $verb, $filename=null)
1292 $objstr = common_log_objstring($object);
1293 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1294 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1297 function common_log_objstring(&$object)
1299 if (is_null($object)) {
1302 if (!($object instanceof DB_DataObject)) {
1305 $arr = $object->toArray();
1307 foreach ($arr as $k => $v) {
1308 if (is_object($v)) {
1309 $fields[] = "$k='".get_class($v)."'";
1311 $fields[] = "$k='$v'";
1314 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1318 function common_valid_http_url($url)
1320 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1323 function common_valid_tag($tag)
1325 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1326 return (Validate::email($matches[1]) ||
1327 preg_match('/^([\w-\.]+)$/', $matches[1]));
1332 /* Following functions are copied from MediaWiki GlobalFunctions.php
1333 * and written by Evan Prodromou. */
1335 function common_accept_to_prefs($accept, $def = '*/*')
1337 // No arg means accept anything (per HTTP spec)
1339 return array($def => 1);
1344 $parts = explode(',', $accept);
1346 foreach($parts as $part) {
1347 // FIXME: doesn't deal with params like 'text/html; level=1'
1348 @list($value, $qpart) = explode(';', trim($part));
1350 if(!isset($qpart)) {
1352 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1353 $prefs[$value] = $match[1];
1360 function common_mime_type_match($type, $avail)
1362 if(array_key_exists($type, $avail)) {
1365 $parts = explode('/', $type);
1366 if(array_key_exists($parts[0] . '/*', $avail)) {
1367 return $parts[0] . '/*';
1368 } elseif(array_key_exists('*/*', $avail)) {
1376 function common_negotiate_type($cprefs, $sprefs)
1380 foreach(array_keys($sprefs) as $type) {
1381 $parts = explode('/', $type);
1382 if($parts[1] != '*') {
1383 $ckey = common_mime_type_match($type, $cprefs);
1385 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1390 foreach(array_keys($cprefs) as $type) {
1391 $parts = explode('/', $type);
1392 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1393 $skey = common_mime_type_match($type, $sprefs);
1395 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1401 $besttype = 'text/html';
1403 foreach(array_keys($combine) as $type) {
1404 if($combine[$type] > $bestq) {
1406 $bestq = $combine[$type];
1410 if ('text/html' === $besttype) {
1411 return "text/html; charset=utf-8";
1416 function common_config($main, $sub)
1419 return (array_key_exists($main, $config) &&
1420 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1423 function common_copy_args($from)
1426 $strip = get_magic_quotes_gpc();
1427 foreach ($from as $k => $v) {
1428 $to[$k] = ($strip) ? stripslashes($v) : $v;
1434 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1435 * This is used before handing a request off to OAuthRequest::from_request.
1436 * @fixme Doesn't consider vars other than _POST and _GET?
1437 * @fixme Can't be undone and could corrupt data if run twice.
1439 function common_remove_magic_from_request()
1441 if(get_magic_quotes_gpc()) {
1442 $_POST=array_map('stripslashes',$_POST);
1443 $_GET=array_map('stripslashes',$_GET);
1447 function common_user_uri(&$user)
1449 return common_local_url('userbyid', array('id' => $user->id));
1452 function common_notice_uri(&$notice)
1454 return common_local_url('shownotice',
1455 array('notice' => $notice->id));
1458 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1460 function common_confirmation_code($bits)
1462 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1463 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1464 $chars = ceil($bits/5);
1466 for ($i = 0; $i < $chars; $i++) {
1467 // XXX: convert to string and back
1468 $num = hexdec(common_good_rand(1));
1469 // XXX: randomness is too precious to throw away almost
1470 // 40% of the bits we get!
1471 $code .= $codechars[$num%32];
1476 // convert markup to HTML
1478 function common_markup_to_html($c)
1480 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1481 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1482 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1483 return Markdown($c);
1486 function common_profile_uri($profile)
1491 $user = User::staticGet($profile->id);
1496 $remote = Remote_profile::staticGet($profile->id);
1498 return $remote->uri;
1500 // XXX: this is a very bad profile!
1504 function common_canonical_sms($sms)
1507 preg_replace('/\D/', '', $sms);
1511 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1516 case E_COMPILE_ERROR:
1520 case E_RECOVERABLE_ERROR:
1521 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1526 case E_COMPILE_WARNING:
1527 case E_CORE_WARNING:
1528 case E_USER_WARNING:
1529 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1534 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1539 case E_USER_DEPRECATED:
1540 // XXX: config variable to log this stuff, too
1544 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1549 // FIXME: show error page if we're on the Web
1550 /* Don't execute PHP internal error handler */
1554 function common_session_token()
1556 common_ensure_session();
1557 if (!array_key_exists('token', $_SESSION)) {
1558 $_SESSION['token'] = common_good_rand(64);
1560 return $_SESSION['token'];
1563 function common_cache_key($extra)
1565 return Cache::key($extra);
1568 function common_keyize($str)
1570 return Cache::keyize($str);
1573 function common_memcache()
1575 return Cache::instance();
1578 function common_license_terms($uri)
1580 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1581 return explode('-',$matches[1]);
1586 function common_compatible_license($from, $to)
1588 $from_terms = common_license_terms($from);
1589 // public domain and cc-by are compatible with everything
1590 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1593 $to_terms = common_license_terms($to);
1594 // sa is compatible across versions. IANAL
1595 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1596 return count(array_diff($from_terms, $to_terms)) == 0;
1598 // XXX: better compatibility check needed here!
1599 // Should at least normalise URIs
1600 return ($from == $to);
1604 * returns a quoted table name, if required according to config
1606 function common_database_tablename($tablename)
1609 if(common_config('db','quote_identifiers')) {
1610 $tablename = '"'. $tablename .'"';
1612 //table prefixes could be added here later
1617 * Shorten a URL with the current user's configured shortening service,
1618 * or ur1.ca if configured, or not at all if no shortening is set up.
1619 * Length is not considered.
1621 * @param string $long_url
1622 * @return string may return the original URL if shortening failed
1624 * @fixme provide a way to specify a particular shortener
1625 * @fixme provide a way to specify to use a given user's shortening preferences
1627 function common_shorten_url($long_url)
1629 $long_url = trim($long_url);
1630 $user = common_current_user();
1632 // common current user does not find a user when called from the XMPP daemon
1633 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1634 $shortenerName = 'ur1.ca';
1636 $shortenerName = $user->urlshorteningservice;
1639 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1640 //URL wasn't shortened, so return the long url
1643 //URL was shortened, so return the result
1644 return trim($shortenedUrl);
1649 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1650 * null if not a web request
1652 * @fixme X-Forwarded-For can be chained by multiple proxies;
1653 we should parse the list and provide a cleaner array
1654 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1655 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1656 * use function to get exact request headers from Apache if possible.
1658 function common_client_ip()
1660 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1664 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1665 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1666 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1668 $proxy = $_SERVER['REMOTE_ADDR'];
1670 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1673 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1674 $ip = $_SERVER['HTTP_CLIENT_IP'];
1676 $ip = $_SERVER['REMOTE_ADDR'];
1680 return array($proxy, $ip);
1683 function common_url_to_nickname($url)
1685 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1687 $parts = parse_url($url);
1689 # If any of these parts exist, this won't work
1691 foreach ($bad as $badpart) {
1692 if (array_key_exists($badpart, $parts)) {
1697 # We just have host and/or path
1699 # If it's just a host...
1700 if (array_key_exists('host', $parts) &&
1701 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1703 $hostparts = explode('.', $parts['host']);
1705 # Try to catch common idiom of nickname.service.tld
1707 if ((count($hostparts) > 2) &&
1708 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1709 (strcmp($hostparts[0], 'www') != 0))
1711 return common_nicknamize($hostparts[0]);
1713 # Do the whole hostname
1714 return common_nicknamize($parts['host']);
1717 if (array_key_exists('path', $parts)) {
1718 # Strip starting, ending slashes
1719 $path = preg_replace('@/$@', '', $parts['path']);
1720 $path = preg_replace('@^/@', '', $path);
1721 $path = basename($path);
1723 return common_nicknamize($path);
1731 function common_nicknamize($str)
1733 $str = preg_replace('/\W/', '', $str);
1734 return strtolower($str);