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) */
23 * Show a server error.
25 function common_server_error($msg, $code=500)
27 $err = new ServerErrorAction($msg, $code);
34 function common_user_error($msg, $code=400)
36 $err = new ClientErrorAction($msg, $code);
41 * This should only be used at setup; processes switching languages
42 * to send text to other users should use common_switch_locale().
44 * @param string $language Locale language code (optional; empty uses
45 * current user's preference or site default)
46 * @return mixed success
48 function common_init_locale($language=null)
51 $language = common_language();
53 putenv('LANGUAGE='.$language);
54 putenv('LANG='.$language);
55 $ok = setlocale(LC_ALL, $language . ".utf8",
65 * Initialize locale and charset settings and gettext with our message catalog,
66 * using the current user's language preference or the site default.
68 * This should generally only be run at framework initialization; code switching
69 * languages at runtime should call common_switch_language().
73 function common_init_language()
75 mb_internal_encoding('UTF-8');
77 // Note that this setlocale() call may "fail" but this is harmless;
78 // gettext will still select the right language.
79 $language = common_language();
80 $locale_set = common_init_locale($language);
83 // The requested locale doesn't exist on the system.
85 // gettext seems very picky... We first need to setlocale()
86 // to a locale which _does_ exist on the system, and _then_
87 // we can set in another locale that may not be set up
88 // (say, ga_ES for Galego/Galician) it seems to take it.
90 // For some reason C and POSIX which are guaranteed to work
91 // don't do the job. en_US.UTF-8 should be there most of the
92 // time, but not guaranteed.
93 $ok = common_init_locale("en_US");
94 if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
95 // Try to find a complete, working locale on Unix/Linux...
96 // @fixme shelling out feels awfully inefficient
97 // but I don't think there's a more standard way.
99 foreach (explode("\n", $all) as $locale) {
100 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
101 $ok = setlocale(LC_ALL, $locale);
109 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
111 $locale_set = common_init_locale($language);
114 common_init_gettext();
120 function common_init_gettext()
122 setlocale(LC_CTYPE, 'C');
123 // So we do not have to make people install the gettext locales
124 $path = common_config('site','locale_path');
125 bindtextdomain("statusnet", $path);
126 bind_textdomain_codeset("statusnet", "UTF-8");
127 textdomain("statusnet");
131 * Switch locale during runtime, and poke gettext until it cries uncle.
132 * Otherwise, sometimes it doesn't actually switch away from the old language.
134 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
136 function common_switch_locale($language=null)
138 common_init_locale($language);
140 setlocale(LC_CTYPE, 'C');
141 // So we do not have to make people install the gettext locales
142 $path = common_config('site','locale_path');
143 bindtextdomain("statusnet", $path);
144 bind_textdomain_codeset("statusnet", "UTF-8");
145 textdomain("statusnet");
148 function common_timezone()
150 if (common_logged_in()) {
151 $user = common_current_user();
152 if ($user->timezone) {
153 return $user->timezone;
157 return common_config('site', 'timezone');
160 function common_language()
162 // If there is a user logged in and they've set a language preference
163 // then return that one...
164 if (_have_config() && common_logged_in()) {
165 $user = common_current_user();
166 $user_language = $user->language;
168 if ($user->language) {
169 // Validate -- we don't want to end up with a bogus code
170 // left over from some old junk.
171 foreach (common_config('site', 'languages') as $code => $info) {
172 if ($info['lang'] == $user_language) {
173 return $user_language;
179 // Otherwise, find the best match for the languages requested by the
181 if (common_config('site', 'langdetect')) {
182 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
183 if (!empty($httplang)) {
184 $language = client_prefered_language($httplang);
190 // Finally, if none of the above worked, use the site's default...
191 return common_config('site', 'language');
195 * Salted, hashed passwords are stored in the DB.
197 function common_munge_password($password, $id)
199 if (is_object($id) || is_object($password)) {
200 $e = new Exception();
201 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
202 str_replace("\n", " ", $e->getTraceAsString()));
204 return md5($password . $id);
208 * Check if a username exists and has matching password.
210 function common_check_user($nickname, $password)
212 // empty nickname always unacceptable
213 if (empty($nickname)) {
217 $authenticatedUser = false;
219 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
220 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
222 if (!empty($password)) { // never allow login with blank password
223 if (0 == strcmp(common_munge_password($password, $user->id),
225 //internal checking passed
226 $authenticatedUser = $user;
230 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
233 return $authenticatedUser;
237 * Is the current user logged in?
239 function common_logged_in()
241 return (!is_null(common_current_user()));
244 function common_have_session()
246 return (0 != strcmp(session_id(), ''));
249 function common_ensure_session()
252 if (array_key_exists(session_name(), $_COOKIE)) {
253 $c = $_COOKIE[session_name()];
255 if (!common_have_session()) {
256 if (common_config('sessions', 'handle')) {
257 Session::setSaveHandler();
259 if (array_key_exists(session_name(), $_GET)) {
260 $id = $_GET[session_name()];
261 } else if (array_key_exists(session_name(), $_COOKIE)) {
262 $id = $_COOKIE[session_name()];
268 if (!isset($_SESSION['started'])) {
269 $_SESSION['started'] = time();
271 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
272 ' is set but started value is null');
278 // Three kinds of arguments:
283 // Initialize to false; set to null if none found
286 function common_set_user($user)
290 if (is_null($user) && common_have_session()) {
292 unset($_SESSION['userid']);
294 } else if (is_string($user)) {
296 $user = User::staticGet('nickname', $nickname);
297 } else if (!($user instanceof User)) {
302 if (Event::handle('StartSetUser', array(&$user))) {
304 common_ensure_session();
305 $_SESSION['userid'] = $user->id;
307 Event::handle('EndSetUser', array($user));
315 function common_set_cookie($key, $value, $expiration=0)
317 $path = common_config('site', 'path');
318 $server = common_config('site', 'server');
320 if ($path && ($path != '/')) {
321 $cookiepath = '/' . $path . '/';
325 return setcookie($key,
330 common_config('site', 'ssl')=='always');
333 define('REMEMBERME', 'rememberme');
334 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
336 function common_rememberme($user=null)
339 $user = common_current_user();
345 $rm = new Remember_me();
347 $rm->code = common_good_rand(16);
348 $rm->user_id = $user->id;
350 // Wrap the insert in some good ol' fashioned transaction code
354 $result = $rm->insert();
357 common_log_db_error($rm, 'INSERT', __FILE__);
361 $rm->query('COMMIT');
363 $cookieval = $rm->user_id . ':' . $rm->code;
365 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
367 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
372 function common_remembered_user()
376 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
382 list($id, $code) = explode(':', $packed);
384 if (!$id || !$code) {
385 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
390 $rm = Remember_me::staticGet($code);
393 common_log(LOG_WARNING, 'No such remember code: ' . $code);
398 if ($rm->user_id != $id) {
399 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
404 $user = User::staticGet($rm->user_id);
407 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
413 $result = $rm->delete();
416 common_log_db_error($rm, 'DELETE', __FILE__);
417 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
422 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
424 common_set_user($user);
425 common_real_login(false);
427 // We issue a new cookie, so they can log in
428 // automatically again after this session
430 common_rememberme($user);
436 * must be called with a valid user!
438 function common_forgetme()
440 common_set_cookie(REMEMBERME, '', 0);
444 * Who is the current user?
446 function common_current_user()
450 if (!_have_config()) {
454 if ($_cur === false) {
456 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
457 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
458 common_ensure_session();
459 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
461 $user = User::staticGet($id);
469 // that didn't work; try to remember; will init $_cur to null on failure
470 $_cur = common_remembered_user();
473 // XXX: Is this necessary?
474 $_SESSION['userid'] = $_cur->id;
482 * Logins that are 'remembered' aren't 'real' -- they're subject to
483 * cookie-stealing. So, we don't let them do certain things. New reg,
484 * OpenID, and password logins _are_ real.
486 function common_real_login($real=true)
488 common_ensure_session();
489 $_SESSION['real_login'] = $real;
492 function common_is_real_login()
494 return common_logged_in() && $_SESSION['real_login'];
498 * Get a hash portion for HTTP caching Etags and such including
499 * info on the current user's session. If login/logout state changes,
500 * or we've changed accounts, or we've renamed the current user,
501 * we'll get a new hash value.
503 * This should not be considered secure information.
505 * @param User $user (optional; uses common_current_user() if left out)
508 function common_user_cache_hash($user=false)
510 if ($user === false) {
511 $user = common_current_user();
514 return crc32($user->id . ':' . $user->nickname);
521 * get canonical version of nickname for comparison
523 * @param string $nickname
526 * @throws NicknameException on invalid input
527 * @deprecated call Nickname::normalize() directly.
529 function common_canonical_nickname($nickname)
531 return Nickname::normalize($nickname);
535 * get canonical version of email for comparison
537 * @fixme actually normalize
538 * @fixme reject invalid input
540 * @param string $email
543 function common_canonical_email($email)
545 // XXX: canonicalize UTF-8
546 // XXX: lcase the domain part
551 * Partial notice markup rendering step: build links to !group references.
553 * @param string $text partially rendered HTML
554 * @param Notice $notice in whose context we're working
555 * @return string partially rendered HTML
557 function common_render_content($text, $notice)
559 $r = common_render_text($text);
560 $id = $notice->profile_id;
561 $r = common_linkify_mentions($r, $notice);
562 $r = preg_replace('/(^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/e',
563 "'\\1!'.common_group_link($id, '\\2')", $r);
567 function common_linkify_mentions($text, $notice)
569 $mentions = common_find_mentions($text, $notice);
571 // We need to go through in reverse order by position,
572 // so our positions stay valid despite our fudging with the
577 foreach ($mentions as $mention)
579 $points[$mention['position']] = $mention;
584 foreach ($points as $position => $mention) {
586 $linkText = common_linkify_mention($mention);
588 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
594 function common_linkify_mention($mention)
598 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
600 $xs = new XMLStringer(false);
602 $attrs = array('href' => $mention['url'],
605 if (!empty($mention['title'])) {
606 $attrs['title'] = $mention['title'];
609 $xs->elementStart('span', 'vcard');
610 $xs->elementStart('a', $attrs);
611 $xs->element('span', 'fn nickname', $mention['text']);
612 $xs->elementEnd('a');
613 $xs->elementEnd('span');
615 $output = $xs->getString();
617 Event::handle('EndLinkifyMention', array($mention, &$output));
624 * Find @-mentions in the given text, using the given notice object as context.
625 * References will be resolved with common_relative_profile() against the user
626 * who posted the notice.
628 * Note the return data format is internal, to be used for building links and
629 * such. Should not be used directly; rather, call common_linkify_mentions().
631 * @param string $text
632 * @param Notice $notice notice in whose context we're building links
638 function common_find_mentions($text, $notice)
642 $sender = Profile::staticGet('id', $notice->profile_id);
644 if (empty($sender)) {
648 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
649 // Get the context of the original notice, if any
650 $originalAuthor = null;
651 $originalNotice = null;
652 $originalMentions = array();
656 if (!empty($notice) && !empty($notice->reply_to)) {
657 $originalNotice = Notice::staticGet('id', $notice->reply_to);
658 if (!empty($originalNotice)) {
659 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
661 $ids = $originalNotice->getReplies();
663 foreach ($ids as $id) {
664 $repliedTo = Profile::staticGet('id', $id);
665 if (!empty($repliedTo)) {
666 $originalMentions[$repliedTo->nickname] = $repliedTo;
672 preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
675 PREG_OFFSET_CAPTURE);
677 preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
680 PREG_OFFSET_CAPTURE);
682 $matches = array_merge($tmatches[1], $atmatches[1]);
684 foreach ($matches as $match) {
686 $nickname = Nickname::normalize($match[0]);
687 } catch (NicknameException $e) {
688 // Bogus match? Drop it.
692 // Try to get a profile for this nickname.
693 // Start with conversation context, then go to
696 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
697 $mentioned = $originalAuthor;
698 } else if (!empty($originalMentions) &&
699 array_key_exists($nickname, $originalMentions)) {
700 $mentioned = $originalMentions[$nickname];
702 $mentioned = common_relative_profile($sender, $nickname);
705 if (!empty($mentioned)) {
706 $user = User::staticGet('id', $mentioned->id);
709 $url = common_local_url('userbyid', array('id' => $user->id));
711 $url = $mentioned->profileurl;
714 $mention = array('mentioned' => array($mentioned),
716 'position' => $match[1],
719 if (!empty($mentioned->fullname)) {
720 $mention['title'] = $mentioned->fullname;
723 $mentions[] = $mention;
727 // @#tag => mention of all subscriptions tagged 'tag'
729 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
732 PREG_OFFSET_CAPTURE);
734 foreach ($hmatches[1] as $hmatch) {
736 $tag = common_canonical_tag($hmatch[0]);
738 $tagged = Profile_tag::getTagged($sender->id, $tag);
740 $url = common_local_url('subscriptions',
741 array('nickname' => $sender->nickname,
744 $mentions[] = array('mentioned' => $tagged,
745 'text' => $hmatch[0],
746 'position' => $hmatch[1],
750 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
756 function common_render_text($text)
758 $r = htmlspecialchars($text);
760 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
761 $r = common_replace_urls_callback($r, 'common_linkify');
762 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
767 function common_replace_urls_callback($text, $callback, $notice_id = null) {
768 // Start off with a regex
770 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
773 '(?:'. //Known protocols
775 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
777 '(?:(?:mailto|aim|tel|xmpp):)'.
779 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
782 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
784 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
788 '|(?:(?: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
790 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
792 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
793 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
794 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
795 '(?: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)'.
799 '(?:\:\d+)?'. //:port
800 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
801 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
802 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
803 ')(?<![\?\.\,\#\,])'.
806 //preg_match_all($regex,$text,$matches);
808 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
811 function callback_helper($matches, $callback, $notice_id) {
813 $left = strpos($matches[0],$url);
814 $right = $left+strlen($url);
816 $groupSymbolSets=array(
834 $cannotEndWith=array('.','?',',','#');
838 foreach($groupSymbolSets as $groupSymbolSet){
839 if(substr($url,-1)==$groupSymbolSet['right']){
840 $group_left_count = substr_count($url,$groupSymbolSet['left']);
841 $group_right_count = substr_count($url,$groupSymbolSet['right']);
842 if($group_left_count<$group_right_count){
844 $url=substr($url,0,-1);
848 if(in_array(substr($url,-1),$cannotEndWith)){
850 $url=substr($url,0,-1);
852 }while($original_url!=$url);
854 if(empty($notice_id)){
855 $result = call_user_func_array($callback, array($url));
857 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
859 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
862 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
863 // lambda implementation in a separate file; PHP 5.2 won't parse it.
864 require_once INSTALLDIR . "/lib/curry.php";
866 function curry($fn) {
867 $args = func_get_args();
869 $id = uniqid('_partial');
870 $GLOBALS[$id] = array($fn, $args);
871 return create_function('',
872 '$args = func_get_args(); '.
873 'return call_user_func_array('.
874 '$GLOBALS["'.$id.'"][0],'.
877 '$GLOBALS["'.$id.'"][1]));');
881 function common_linkify($url) {
882 // It comes in special'd, so we unspecial it before passing to the stringifying
884 $url = htmlspecialchars_decode($url);
886 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
887 //url is an email address without the mailto: protocol
888 $canon = "mailto:$url";
889 $longurl = "mailto:$url";
892 $canon = File_redirection::_canonUrl($url);
894 $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
895 if (is_array($longurl_data)) {
896 $longurl = $longurl_data['url'];
897 } elseif (is_string($longurl_data)) {
898 $longurl = $longurl_data;
900 // Unable to reach the server to verify contents, etc
901 // Just pass the link on through for now.
902 common_log(LOG_ERR, "Can't linkify url '$url'");
907 $attrs = array('href' => $canon, 'title' => $longurl);
909 $is_attachment = false;
910 $attachment_id = null;
913 // Check to see whether this is a known "attachment" URL.
915 $f = File::staticGet('url', $longurl);
918 if (common_config('attachments', 'process_links')) {
919 // XXX: this writes to the database. :<
920 $f = File::processNew($longurl);
925 if ($f->getEnclosure()) {
926 $is_attachment = true;
927 $attachment_id = $f->id;
929 $thumb = File_thumbnail::staticGet('file_id', $f->id);
930 if (!empty($thumb)) {
937 if ($is_attachment) {
938 $attrs['class'] = 'attachment';
940 $attrs['class'] = 'attachment thumbnail';
942 $attrs['id'] = "attachment-{$attachment_id}";
945 // Whether to nofollow
947 $nf = common_config('nofollow', 'external');
949 if ($nf == 'never') {
950 $attrs['rel'] = 'external';
952 $attrs['rel'] = 'nofollow external';
955 return XMLStringer::estring('a', $attrs, $url);
958 function common_shorten_links($text, $always = false)
960 $maxLength = Notice::maxContent();
961 if (!$always && ($maxLength == 0 || mb_strlen($text) <= $maxLength)) return $text;
962 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
966 * Very basic stripping of invalid UTF-8 input text.
969 * @return mixed string or null if invalid input
971 * @todo ideally we should drop bad chars, and maybe do some of the checks
972 * from common_xml_safe_str. But we can't strip newlines, etc.
973 * @todo Unicode normalization might also be useful, but not needed now.
975 function common_validate_utf8($str)
977 // preg_replace will return NULL on invalid UTF-8 input.
979 // Note: empty regex //u also caused NULL return on some
980 // production machines, but none of our test machines.
982 // This should be replaced with a more reliable check.
983 return preg_replace('/\x00/u', '', $str);
987 * Make sure an arbitrary string is safe for output in XML as a single line.
992 function common_xml_safe_str($str)
994 // Replace common eol and extra whitespace input chars
999 "\0", // null byte eos
1000 "\x0B" // vertical tab
1003 $replacement = array(
1004 ' ', // single space
1011 $str = str_replace($unWelcome, $replacement, $str);
1013 // Neutralize any additional control codes and UTF-16 surrogates
1014 // (Twitter uses '*')
1015 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1018 function common_tag_link($tag)
1020 $canonical = common_canonical_tag($tag);
1021 if (common_config('singleuser', 'enabled')) {
1022 // regular TagAction isn't set up in 1user mode
1023 $user = User::singleUser();
1024 $url = common_local_url('showstream',
1025 array('nickname' => $user->nickname,
1026 'tag' => $canonical));
1028 $url = common_local_url('tag', array('tag' => $canonical));
1030 $xs = new XMLStringer();
1031 $xs->elementStart('span', 'tag');
1032 $xs->element('a', array('href' => $url,
1035 $xs->elementEnd('span');
1036 return $xs->getString();
1039 function common_canonical_tag($tag)
1041 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1042 return str_replace(array('-', '_', '.'), '', $tag);
1045 function common_valid_profile_tag($str)
1047 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1052 * @param <type> $sender_id
1053 * @param <type> $nickname
1057 function common_group_link($sender_id, $nickname)
1059 $sender = Profile::staticGet($sender_id);
1060 $group = User_group::getForNickname($nickname, $sender);
1061 if ($sender && $group && $sender->isMember($group)) {
1062 $attrs = array('href' => $group->permalink(),
1064 if (!empty($group->fullname)) {
1065 $attrs['title'] = $group->getFancyName();
1067 $xs = new XMLStringer();
1068 $xs->elementStart('span', 'vcard');
1069 $xs->elementStart('a', $attrs);
1070 $xs->element('span', 'fn nickname', $nickname);
1071 $xs->elementEnd('a');
1072 $xs->elementEnd('span');
1073 return $xs->getString();
1080 * Resolve an ambiguous profile nickname reference, checking in following order:
1081 * - profiles that $sender subscribes to
1082 * - profiles that subscribe to $sender
1083 * - local user profiles
1085 * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1086 * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1089 * @fixme validate input
1091 * @fixme fix or remove mystery third parameter
1092 * @fixme is $sender a User or Profile?
1094 * @param <type> $sender the user or profile in whose context we're looking
1095 * @param string $nickname validated nickname of
1096 * @param <type> $dt unused mystery parameter.
1098 * @return Profile or null
1100 function common_relative_profile($sender, $nickname, $dt=null)
1102 // Try to find profiles this profile is subscribed to that have this nickname
1103 $recipient = new Profile();
1104 // XXX: use a join instead of a subquery
1105 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
1106 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1107 if ($recipient->find(true)) {
1108 // XXX: should probably differentiate between profiles with
1109 // the same name by date of most recent update
1112 // Try to find profiles that listen to this profile and that have this nickname
1113 $recipient = new Profile();
1114 // XXX: use a join instead of a subquery
1115 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1116 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1117 if ($recipient->find(true)) {
1118 // XXX: should probably differentiate between profiles with
1119 // the same name by date of most recent update
1122 // If this is a local user, try to find a local user with that nickname.
1123 $sender = User::staticGet($sender->id);
1125 $recipient_user = User::staticGet('nickname', $nickname);
1126 if ($recipient_user) {
1127 return $recipient_user->getProfile();
1130 // Otherwise, no links. @messages from local users to remote users,
1131 // or from remote users to other remote users, are just
1132 // outside our ability to make intelligent guesses about
1136 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1139 $path = $r->build($action, $args, $params, $fragment);
1141 $ssl = common_is_sensitive($action);
1143 if (common_config('site','fancy')) {
1144 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1146 if (mb_strpos($path, '/index.php') === 0) {
1147 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1149 $url = common_path('index.php'.$path, $ssl, $addSession);
1155 function common_is_sensitive($action)
1157 static $sensitive = array(
1162 'ApiOauthRequestToken',
1163 'ApiOauthAccessToken',
1164 'ApiOauthAuthorize',
1170 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1171 $ssl = in_array($action, $sensitive);
1177 function common_path($relative, $ssl=false, $addSession=true)
1179 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1181 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1182 || common_config('site', 'ssl') === 'always') {
1184 if (is_string(common_config('site', 'sslserver')) &&
1185 mb_strlen(common_config('site', 'sslserver')) > 0) {
1186 $serverpart = common_config('site', 'sslserver');
1187 } else if (common_config('site', 'server')) {
1188 $serverpart = common_config('site', 'server');
1190 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1194 if (common_config('site', 'server')) {
1195 $serverpart = common_config('site', 'server');
1197 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1202 $relative = common_inject_session($relative, $serverpart);
1205 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1208 function common_inject_session($url, $serverpart = null)
1210 if (common_have_session()) {
1212 if (empty($serverpart)) {
1213 $serverpart = parse_url($url, PHP_URL_HOST);
1216 $currentServer = $_SERVER['HTTP_HOST'];
1218 // Are we pointing to another server (like an SSL server?)
1220 if (!empty($currentServer) &&
1221 0 != strcasecmp($currentServer, $serverpart)) {
1222 // Pass the session ID as a GET parameter
1223 $sesspart = session_name() . '=' . session_id();
1224 $i = strpos($url, '?');
1225 if ($i === false) { // no GET params, just append
1226 $url .= '?' . $sesspart;
1228 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1236 function common_date_string($dt)
1238 // XXX: do some sexy date formatting
1239 // return date(DATE_RFC822, $dt);
1240 $t = strtotime($dt);
1244 if ($now < $t) { // that shouldn't happen!
1245 return common_exact_date($dt);
1246 } else if ($diff < 60) {
1247 // TRANS: Used in notices to indicate when the notice was made compared to now.
1248 return _('a few seconds ago');
1249 } else if ($diff < 92) {
1250 // TRANS: Used in notices to indicate when the notice was made compared to now.
1251 return _('about a minute ago');
1252 } else if ($diff < 3300) {
1253 $minutes = round($diff/60);
1254 // TRANS: Used in notices to indicate when the notice was made compared to now.
1255 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1256 } else if ($diff < 5400) {
1257 // TRANS: Used in notices to indicate when the notice was made compared to now.
1258 return _('about an hour ago');
1259 } else if ($diff < 22 * 3600) {
1260 $hours = round($diff/3600);
1261 // TRANS: Used in notices to indicate when the notice was made compared to now.
1262 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1263 } else if ($diff < 37 * 3600) {
1264 // TRANS: Used in notices to indicate when the notice was made compared to now.
1265 return _('about a day ago');
1266 } else if ($diff < 24 * 24 * 3600) {
1267 $days = round($diff/(24*3600));
1268 // TRANS: Used in notices to indicate when the notice was made compared to now.
1269 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1270 } else if ($diff < 46 * 24 * 3600) {
1271 // TRANS: Used in notices to indicate when the notice was made compared to now.
1272 return _('about a month ago');
1273 } else if ($diff < 330 * 24 * 3600) {
1274 $months = round($diff/(30*24*3600));
1275 // TRANS: Used in notices to indicate when the notice was made compared to now.
1276 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1277 } else if ($diff < 480 * 24 * 3600) {
1278 // TRANS: Used in notices to indicate when the notice was made compared to now.
1279 return _('about a year ago');
1281 return common_exact_date($dt);
1285 function common_exact_date($dt)
1291 $_utc = new DateTimeZone('UTC');
1292 $_siteTz = new DateTimeZone(common_timezone());
1295 $dateStr = date('d F Y H:i:s', strtotime($dt));
1296 $d = new DateTime($dateStr, $_utc);
1297 $d->setTimezone($_siteTz);
1298 return $d->format(DATE_RFC850);
1301 function common_date_w3dtf($dt)
1303 $dateStr = date('d F Y H:i:s', strtotime($dt));
1304 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1305 $d->setTimezone(new DateTimeZone(common_timezone()));
1306 return $d->format(DATE_W3C);
1309 function common_date_rfc2822($dt)
1311 $dateStr = date('d F Y H:i:s', strtotime($dt));
1312 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1313 $d->setTimezone(new DateTimeZone(common_timezone()));
1314 return $d->format('r');
1317 function common_date_iso8601($dt)
1319 $dateStr = date('d F Y H:i:s', strtotime($dt));
1320 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1321 $d->setTimezone(new DateTimeZone(common_timezone()));
1322 return $d->format('c');
1325 function common_sql_now()
1327 return common_sql_date(time());
1330 function common_sql_date($datetime)
1332 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1336 * Return an SQL fragment to calculate an age-based weight from a given
1337 * timestamp or datetime column.
1339 * @param string $column name of field we're comparing against current time
1340 * @param integer $dropoff divisor for age in seconds before exponentiation
1341 * @return string SQL fragment
1343 function common_sql_weight($column, $dropoff)
1345 if (common_config('db', 'type') == 'pgsql') {
1346 // PostgreSQL doesn't support timestampdiff function.
1347 // @fixme will this use the right time zone?
1348 // @fixme does this handle cross-year subtraction correctly?
1349 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1351 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1355 function common_redirect($url, $code=307)
1357 static $status = array(301 => "Moved Permanently",
1360 307 => "Temporary Redirect");
1362 header('HTTP/1.1 '.$code.' '.$status[$code]);
1363 header("Location: $url");
1365 $xo = new XMLOutputter();
1367 '-//W3C//DTD XHTML 1.0 Strict//EN',
1368 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1369 $xo->element('a', array('href' => $url), $url);
1374 function common_broadcast_notice($notice, $remote=false)
1380 * Stick the notice on the queue.
1382 function common_enqueue_notice($notice)
1384 static $localTransports = array('omb',
1387 $transports = array();
1388 if (common_config('sms', 'enabled')) {
1389 $transports[] = 'sms';
1391 if (Event::hasHandler('HandleQueuedNotice')) {
1392 $transports[] = 'plugin';
1395 $xmpp = common_config('xmpp', 'enabled');
1398 $transports[] = 'jabber';
1401 // We can skip these for gatewayed notices.
1402 if ($notice->isLocal()) {
1403 $transports = array_merge($transports, $localTransports);
1405 $transports[] = 'public';
1409 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1411 $qm = QueueManager::get();
1413 foreach ($transports as $transport)
1415 $qm->enqueue($notice, $transport);
1418 Event::handle('EndEnqueueNotice', array($notice, $transports));
1425 * Broadcast profile updates to OMB and other remote subscribers.
1427 * Since this may be slow with a lot of subscribers or bad remote sites,
1428 * this is run through the background queues if possible.
1430 function common_broadcast_profile(Profile $profile)
1432 $qm = QueueManager::get();
1433 $qm->enqueue($profile, "profile");
1437 function common_profile_url($nickname)
1439 return common_local_url('showstream', array('nickname' => $nickname),
1444 * Should make up a reasonable root URL
1446 function common_root_url($ssl=false)
1448 $url = common_path('', $ssl, false);
1449 $i = strpos($url, '?');
1451 $url = substr($url, 0, $i);
1457 * returns $bytes bytes of random data as a hexadecimal string
1458 * "good" here is a goal and not a guarantee
1460 function common_good_rand($bytes)
1462 // XXX: use random.org...?
1463 if (@file_exists('/dev/urandom')) {
1464 return common_urandom($bytes);
1465 } else { // FIXME: this is probably not good enough
1466 return common_mtrand($bytes);
1470 function common_urandom($bytes)
1472 $h = fopen('/dev/urandom', 'rb');
1474 $src = fread($h, $bytes);
1477 for ($i = 0; $i < $bytes; $i++) {
1478 $enc .= sprintf("%02x", (ord($src[$i])));
1483 function common_mtrand($bytes)
1486 for ($i = 0; $i < $bytes; $i++) {
1487 $enc .= sprintf("%02x", mt_rand(0, 255));
1493 * Record the given URL as the return destination for a future
1494 * form submission, to be read by common_get_returnto().
1496 * @param string $url
1498 * @fixme as a session-global setting, this can allow multiple forms
1499 * to conflict and overwrite each others' returnto destinations if
1500 * the user has multiple tabs or windows open.
1502 * Should refactor to index with a token or otherwise only pass the
1503 * data along its intended path.
1505 function common_set_returnto($url)
1507 common_ensure_session();
1508 $_SESSION['returnto'] = $url;
1512 * Fetch a return-destination URL previously recorded by
1513 * common_set_returnto().
1515 * @return mixed URL string or null
1517 * @fixme as a session-global setting, this can allow multiple forms
1518 * to conflict and overwrite each others' returnto destinations if
1519 * the user has multiple tabs or windows open.
1521 * Should refactor to index with a token or otherwise only pass the
1522 * data along its intended path.
1524 function common_get_returnto()
1526 common_ensure_session();
1527 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1530 function common_timestamp()
1532 return date('YmdHis');
1535 function common_ensure_syslog()
1537 static $initialized = false;
1538 if (!$initialized) {
1539 openlog(common_config('syslog', 'appname'), 0,
1540 common_config('syslog', 'facility'));
1541 $initialized = true;
1545 function common_log_line($priority, $msg)
1547 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1548 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1549 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1552 function common_request_id()
1555 $server = common_config('site', 'server');
1556 if (php_sapi_name() == 'cli') {
1557 $script = basename($_SERVER['PHP_SELF']);
1558 return "$server:$script:$pid";
1560 static $req_id = null;
1561 if (!isset($req_id)) {
1562 $req_id = substr(md5(mt_rand()), 0, 8);
1564 if (isset($_SERVER['REQUEST_URI'])) {
1565 $url = $_SERVER['REQUEST_URI'];
1567 $method = $_SERVER['REQUEST_METHOD'];
1568 return "$server:$pid.$req_id $method $url";
1572 function common_log($priority, $msg, $filename=null)
1574 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1575 $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1576 $msg = '[' . common_request_id() . '] ' . $msg;
1577 $logfile = common_config('site', 'logfile');
1579 $log = fopen($logfile, "a");
1581 $output = common_log_line($priority, $msg);
1582 fwrite($log, $output);
1586 common_ensure_syslog();
1587 syslog($priority, $msg);
1589 Event::handle('EndLog', array($priority, $msg, $filename));
1593 function common_debug($msg, $filename=null)
1596 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1598 common_log(LOG_DEBUG, $msg);
1602 function common_log_db_error(&$object, $verb, $filename=null)
1604 $objstr = common_log_objstring($object);
1605 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1606 if (is_object($last_error)) {
1607 $msg = $last_error->message;
1609 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1611 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1614 function common_log_objstring(&$object)
1616 if (is_null($object)) {
1619 if (!($object instanceof DB_DataObject)) {
1622 $arr = $object->toArray();
1624 foreach ($arr as $k => $v) {
1625 if (is_object($v)) {
1626 $fields[] = "$k='".get_class($v)."'";
1628 $fields[] = "$k='$v'";
1631 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1635 function common_valid_http_url($url)
1637 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1640 function common_valid_tag($tag)
1642 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1643 return (Validate::email($matches[1]) ||
1644 preg_match('/^([\w-\.]+)$/', $matches[1]));
1650 * Determine if given domain or address literal is valid
1651 * eg for use in JIDs and URLs. Does not check if the domain
1654 * @param string $domain
1655 * @return boolean valid or not
1657 function common_valid_domain($domain)
1659 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1660 $ipv4 = "(?:$octet(?:\.$octet){3})";
1661 if (preg_match("/^$ipv4$/u", $domain)) return true;
1663 $group = "(?:[0-9a-f]{1,4})";
1664 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1666 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1667 $before = explode(":", $matches[1]);
1668 $zeroes = $matches[2];
1669 $after = explode(":", $matches[3]);
1677 $explicit = count($before) + count($after);
1678 if ($explicit < $min || $explicit > $max) {
1685 require_once "Net/IDNA.php";
1686 $idn = Net_IDNA::getInstance();
1687 $domain = $idn->encode($domain);
1688 } catch (Exception $e) {
1692 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1693 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1695 return preg_match("/^$fqdn$/ui", $domain);
1698 /* Following functions are copied from MediaWiki GlobalFunctions.php
1699 * and written by Evan Prodromou. */
1701 function common_accept_to_prefs($accept, $def = '*/*')
1703 // No arg means accept anything (per HTTP spec)
1705 return array($def => 1);
1710 $parts = explode(',', $accept);
1712 foreach($parts as $part) {
1713 // FIXME: doesn't deal with params like 'text/html; level=1'
1714 @list($value, $qpart) = explode(';', trim($part));
1716 if(!isset($qpart)) {
1718 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1719 $prefs[$value] = $match[1];
1726 function common_mime_type_match($type, $avail)
1728 if(array_key_exists($type, $avail)) {
1731 $parts = explode('/', $type);
1732 if(array_key_exists($parts[0] . '/*', $avail)) {
1733 return $parts[0] . '/*';
1734 } elseif(array_key_exists('*/*', $avail)) {
1742 function common_negotiate_type($cprefs, $sprefs)
1746 foreach(array_keys($sprefs) as $type) {
1747 $parts = explode('/', $type);
1748 if($parts[1] != '*') {
1749 $ckey = common_mime_type_match($type, $cprefs);
1751 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1756 foreach(array_keys($cprefs) as $type) {
1757 $parts = explode('/', $type);
1758 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1759 $skey = common_mime_type_match($type, $sprefs);
1761 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1767 $besttype = 'text/html';
1769 foreach(array_keys($combine) as $type) {
1770 if($combine[$type] > $bestq) {
1772 $bestq = $combine[$type];
1776 if ('text/html' === $besttype) {
1777 return "text/html; charset=utf-8";
1782 function common_config($main, $sub)
1785 return (array_key_exists($main, $config) &&
1786 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1790 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1791 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1793 * @param array $from
1796 function common_copy_args($from)
1799 $strip = get_magic_quotes_gpc();
1800 foreach ($from as $k => $v) {
1802 $to[$k] = common_copy_args($v);
1805 $v = stripslashes($v);
1807 $to[$k] = strval(common_validate_utf8($v));
1814 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1815 * This is used before handing a request off to OAuthRequest::from_request.
1816 * @fixme Doesn't consider vars other than _POST and _GET?
1817 * @fixme Can't be undone and could corrupt data if run twice.
1819 function common_remove_magic_from_request()
1821 if(get_magic_quotes_gpc()) {
1822 $_POST=array_map('stripslashes',$_POST);
1823 $_GET=array_map('stripslashes',$_GET);
1827 function common_user_uri(&$user)
1829 return common_local_url('userbyid', array('id' => $user->id),
1833 function common_notice_uri(&$notice)
1835 return common_local_url('shownotice',
1836 array('notice' => $notice->id),
1840 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1842 function common_confirmation_code($bits)
1844 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1845 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1846 $chars = ceil($bits/5);
1848 for ($i = 0; $i < $chars; $i++) {
1849 // XXX: convert to string and back
1850 $num = hexdec(common_good_rand(1));
1851 // XXX: randomness is too precious to throw away almost
1852 // 40% of the bits we get!
1853 $code .= $codechars[$num%32];
1858 // convert markup to HTML
1860 function common_markup_to_html($c)
1862 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1863 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1864 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1865 return Markdown($c);
1868 function common_profile_uri($profile)
1873 $user = User::staticGet($profile->id);
1878 $remote = Remote_profile::staticGet($profile->id);
1880 return $remote->uri;
1882 // XXX: this is a very bad profile!
1886 function common_canonical_sms($sms)
1889 preg_replace('/\D/', '', $sms);
1893 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1898 case E_COMPILE_ERROR:
1902 case E_RECOVERABLE_ERROR:
1903 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1908 case E_COMPILE_WARNING:
1909 case E_CORE_WARNING:
1910 case E_USER_WARNING:
1911 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1916 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1921 case E_USER_DEPRECATED:
1922 // XXX: config variable to log this stuff, too
1926 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1931 // FIXME: show error page if we're on the Web
1932 /* Don't execute PHP internal error handler */
1936 function common_session_token()
1938 common_ensure_session();
1939 if (!array_key_exists('token', $_SESSION)) {
1940 $_SESSION['token'] = common_good_rand(64);
1942 return $_SESSION['token'];
1945 function common_cache_key($extra)
1947 return Cache::key($extra);
1950 function common_keyize($str)
1952 return Cache::keyize($str);
1955 function common_memcache()
1957 return Cache::instance();
1960 function common_license_terms($uri)
1962 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1963 return explode('-',$matches[1]);
1968 function common_compatible_license($from, $to)
1970 $from_terms = common_license_terms($from);
1971 // public domain and cc-by are compatible with everything
1972 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1975 $to_terms = common_license_terms($to);
1976 // sa is compatible across versions. IANAL
1977 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1978 return count(array_diff($from_terms, $to_terms)) == 0;
1980 // XXX: better compatibility check needed here!
1981 // Should at least normalise URIs
1982 return ($from == $to);
1986 * returns a quoted table name, if required according to config
1988 function common_database_tablename($tablename)
1990 if(common_config('db','quote_identifiers')) {
1991 $tablename = '"'. $tablename .'"';
1993 //table prefixes could be added here later
1998 * Shorten a URL with the current user's configured shortening service,
1999 * or ur1.ca if configured, or not at all if no shortening is set up.
2000 * Length is not considered.
2002 * @param string $long_url
2003 * @return string may return the original URL if shortening failed
2005 * @fixme provide a way to specify a particular shortener
2006 * @fixme provide a way to specify to use a given user's shortening preferences
2008 function common_shorten_url($long_url)
2010 $long_url = trim($long_url);
2011 $user = common_current_user();
2013 // common current user does not find a user when called from the XMPP daemon
2014 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
2015 $shortenerName = 'ur1.ca';
2017 $shortenerName = $user->urlshorteningservice;
2020 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
2021 //URL wasn't shortened, so return the long url
2024 //URL was shortened, so return the result
2025 return trim($shortenedUrl);
2030 * @return mixed array($proxy, $ip) for web requests; proxy may be null
2031 * null if not a web request
2033 * @fixme X-Forwarded-For can be chained by multiple proxies;
2034 we should parse the list and provide a cleaner array
2035 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2036 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2037 * use function to get exact request headers from Apache if possible.
2039 function common_client_ip()
2041 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2045 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2046 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2047 $proxy = $_SERVER['HTTP_CLIENT_IP'];
2049 $proxy = $_SERVER['REMOTE_ADDR'];
2051 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2054 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2055 $ip = $_SERVER['HTTP_CLIENT_IP'];
2057 $ip = $_SERVER['REMOTE_ADDR'];
2061 return array($proxy, $ip);
2064 function common_url_to_nickname($url)
2066 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2068 $parts = parse_url($url);
2070 # If any of these parts exist, this won't work
2072 foreach ($bad as $badpart) {
2073 if (array_key_exists($badpart, $parts)) {
2078 # We just have host and/or path
2080 # If it's just a host...
2081 if (array_key_exists('host', $parts) &&
2082 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2084 $hostparts = explode('.', $parts['host']);
2086 # Try to catch common idiom of nickname.service.tld
2088 if ((count($hostparts) > 2) &&
2089 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2090 (strcmp($hostparts[0], 'www') != 0))
2092 return common_nicknamize($hostparts[0]);
2094 # Do the whole hostname
2095 return common_nicknamize($parts['host']);
2098 if (array_key_exists('path', $parts)) {
2099 # Strip starting, ending slashes
2100 $path = preg_replace('@/$@', '', $parts['path']);
2101 $path = preg_replace('@^/@', '', $path);
2102 $path = basename($path);
2104 // Hack for MediaWiki user pages, in the form:
2105 // http://example.com/wiki/User:Myname
2106 // ('User' may be localized.)
2107 if (strpos($path, ':')) {
2108 $parts = array_filter(explode(':', $path));
2109 $path = $parts[count($parts) - 1];
2113 return common_nicknamize($path);
2121 function common_nicknamize($str)
2123 $str = preg_replace('/\W/', '', $str);
2124 return strtolower($str);