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_valid_language($lang)
163 // Validate -- we don't want to end up with a bogus code
164 // left over from some old junk.
165 foreach (common_config('site', 'languages') as $code => $info) {
166 if ($info['lang'] == $lang) {
174 function common_language()
176 // Allow ?uselang=xx override, very useful for debugging
177 // and helping translators check usage and context.
178 if (isset($_GET['uselang'])) {
179 $uselang = strval($_GET['uselang']);
180 if (common_valid_language($uselang)) {
185 // If there is a user logged in and they've set a language preference
186 // then return that one...
187 if (_have_config() && common_logged_in()) {
188 $user = common_current_user();
190 if (common_valid_language($user->language)) {
191 return $user->language;
195 // Otherwise, find the best match for the languages requested by the
197 if (common_config('site', 'langdetect')) {
198 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
199 if (!empty($httplang)) {
200 $language = client_prefered_language($httplang);
206 // Finally, if none of the above worked, use the site's default...
207 return common_config('site', 'language');
211 * Salted, hashed passwords are stored in the DB.
213 function common_munge_password($password, $id)
215 if (is_object($id) || is_object($password)) {
216 $e = new Exception();
217 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
218 str_replace("\n", " ", $e->getTraceAsString()));
220 return md5($password . $id);
224 * Check if a username exists and has matching password.
226 function common_check_user($nickname, $password)
228 // empty nickname always unacceptable
229 if (empty($nickname)) {
233 $authenticatedUser = false;
235 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
236 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
238 if (!empty($password)) { // never allow login with blank password
239 if (0 == strcmp(common_munge_password($password, $user->id),
241 //internal checking passed
242 $authenticatedUser = $user;
246 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
249 return $authenticatedUser;
253 * Is the current user logged in?
255 function common_logged_in()
257 return (!is_null(common_current_user()));
260 function common_have_session()
262 return (0 != strcmp(session_id(), ''));
265 function common_ensure_session()
268 if (array_key_exists(session_name(), $_COOKIE)) {
269 $c = $_COOKIE[session_name()];
271 if (!common_have_session()) {
272 if (common_config('sessions', 'handle')) {
273 Session::setSaveHandler();
275 if (array_key_exists(session_name(), $_GET)) {
276 $id = $_GET[session_name()];
277 } else if (array_key_exists(session_name(), $_COOKIE)) {
278 $id = $_COOKIE[session_name()];
284 if (!isset($_SESSION['started'])) {
285 $_SESSION['started'] = time();
287 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
288 ' is set but started value is null');
294 // Three kinds of arguments:
299 // Initialize to false; set to null if none found
302 function common_set_user($user)
306 if (is_null($user) && common_have_session()) {
308 unset($_SESSION['userid']);
310 } else if (is_string($user)) {
312 $user = User::staticGet('nickname', $nickname);
313 } else if (!($user instanceof User)) {
318 if (Event::handle('StartSetUser', array(&$user))) {
320 common_ensure_session();
321 $_SESSION['userid'] = $user->id;
323 Event::handle('EndSetUser', array($user));
331 function common_set_cookie($key, $value, $expiration=0)
333 $path = common_config('site', 'path');
334 $server = common_config('site', 'server');
336 if ($path && ($path != '/')) {
337 $cookiepath = '/' . $path . '/';
341 return setcookie($key,
346 common_config('site', 'ssl')=='always');
349 define('REMEMBERME', 'rememberme');
350 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
352 function common_rememberme($user=null)
355 $user = common_current_user();
361 $rm = new Remember_me();
363 $rm->code = common_good_rand(16);
364 $rm->user_id = $user->id;
366 // Wrap the insert in some good ol' fashioned transaction code
370 $result = $rm->insert();
373 common_log_db_error($rm, 'INSERT', __FILE__);
377 $rm->query('COMMIT');
379 $cookieval = $rm->user_id . ':' . $rm->code;
381 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
383 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
388 function common_remembered_user()
392 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
398 list($id, $code) = explode(':', $packed);
400 if (!$id || !$code) {
401 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
406 $rm = Remember_me::staticGet($code);
409 common_log(LOG_WARNING, 'No such remember code: ' . $code);
414 if ($rm->user_id != $id) {
415 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
420 $user = User::staticGet($rm->user_id);
423 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
429 $result = $rm->delete();
432 common_log_db_error($rm, 'DELETE', __FILE__);
433 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
438 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
440 common_set_user($user);
441 common_real_login(false);
443 // We issue a new cookie, so they can log in
444 // automatically again after this session
446 common_rememberme($user);
452 * must be called with a valid user!
454 function common_forgetme()
456 common_set_cookie(REMEMBERME, '', 0);
460 * Who is the current user?
462 function common_current_user()
466 if (!_have_config()) {
470 if ($_cur === false) {
472 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
473 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
474 common_ensure_session();
475 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
477 $user = User::staticGet($id);
485 // that didn't work; try to remember; will init $_cur to null on failure
486 $_cur = common_remembered_user();
489 // XXX: Is this necessary?
490 $_SESSION['userid'] = $_cur->id;
498 * Logins that are 'remembered' aren't 'real' -- they're subject to
499 * cookie-stealing. So, we don't let them do certain things. New reg,
500 * OpenID, and password logins _are_ real.
502 function common_real_login($real=true)
504 common_ensure_session();
505 $_SESSION['real_login'] = $real;
508 function common_is_real_login()
510 return common_logged_in() && $_SESSION['real_login'];
514 * Get a hash portion for HTTP caching Etags and such including
515 * info on the current user's session. If login/logout state changes,
516 * or we've changed accounts, or we've renamed the current user,
517 * we'll get a new hash value.
519 * This should not be considered secure information.
521 * @param User $user (optional; uses common_current_user() if left out)
524 function common_user_cache_hash($user=false)
526 if ($user === false) {
527 $user = common_current_user();
530 return crc32($user->id . ':' . $user->nickname);
537 * get canonical version of nickname for comparison
539 * @param string $nickname
542 * @throws NicknameException on invalid input
543 * @deprecated call Nickname::normalize() directly.
545 function common_canonical_nickname($nickname)
547 return Nickname::normalize($nickname);
551 * get canonical version of email for comparison
553 * @fixme actually normalize
554 * @fixme reject invalid input
556 * @param string $email
559 function common_canonical_email($email)
561 // XXX: canonicalize UTF-8
562 // XXX: lcase the domain part
567 * Partial notice markup rendering step: build links to !group references.
569 * @param string $text partially rendered HTML
570 * @param Notice $notice in whose context we're working
571 * @return string partially rendered HTML
573 function common_render_content($text, $notice)
575 $r = common_render_text($text);
576 $id = $notice->profile_id;
577 $r = common_linkify_mentions($r, $notice);
578 $r = preg_replace('/(^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/e',
579 "'\\1!'.common_group_link($id, '\\2')", $r);
584 * Finds @-mentions within the partially-rendered text section and
585 * turns them into live links.
587 * Should generally not be called except from common_render_content().
589 * @param string $text partially-rendered HTML
590 * @param Notice $notice in-progress or complete Notice object for context
591 * @return string partially-rendered HTML
593 function common_linkify_mentions($text, $notice)
595 $mentions = common_find_mentions($text, $notice);
597 // We need to go through in reverse order by position,
598 // so our positions stay valid despite our fudging with the
603 foreach ($mentions as $mention)
605 $points[$mention['position']] = $mention;
610 foreach ($points as $position => $mention) {
612 $linkText = common_linkify_mention($mention);
614 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
620 function common_linkify_mention($mention)
624 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
626 $xs = new XMLStringer(false);
628 $attrs = array('href' => $mention['url'],
631 if (!empty($mention['title'])) {
632 $attrs['title'] = $mention['title'];
635 $xs->elementStart('span', 'vcard');
636 $xs->elementStart('a', $attrs);
637 $xs->element('span', 'fn nickname', $mention['text']);
638 $xs->elementEnd('a');
639 $xs->elementEnd('span');
641 $output = $xs->getString();
643 Event::handle('EndLinkifyMention', array($mention, &$output));
650 * Find @-mentions in the given text, using the given notice object as context.
651 * References will be resolved with common_relative_profile() against the user
652 * who posted the notice.
654 * Note the return data format is internal, to be used for building links and
655 * such. Should not be used directly; rather, call common_linkify_mentions().
657 * @param string $text
658 * @param Notice $notice notice in whose context we're building links
664 function common_find_mentions($text, $notice)
668 $sender = Profile::staticGet('id', $notice->profile_id);
670 if (empty($sender)) {
674 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
675 // Get the context of the original notice, if any
676 $originalAuthor = null;
677 $originalNotice = null;
678 $originalMentions = array();
682 if (!empty($notice) && !empty($notice->reply_to)) {
683 $originalNotice = Notice::staticGet('id', $notice->reply_to);
684 if (!empty($originalNotice)) {
685 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
687 $ids = $originalNotice->getReplies();
689 foreach ($ids as $id) {
690 $repliedTo = Profile::staticGet('id', $id);
691 if (!empty($repliedTo)) {
692 $originalMentions[$repliedTo->nickname] = $repliedTo;
698 $matches = common_find_mentions_raw($text);
700 foreach ($matches as $match) {
702 $nickname = Nickname::normalize($match[0]);
703 } catch (NicknameException $e) {
704 // Bogus match? Drop it.
708 // Try to get a profile for this nickname.
709 // Start with conversation context, then go to
712 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
713 $mentioned = $originalAuthor;
714 } else if (!empty($originalMentions) &&
715 array_key_exists($nickname, $originalMentions)) {
716 $mentioned = $originalMentions[$nickname];
718 $mentioned = common_relative_profile($sender, $nickname);
721 if (!empty($mentioned)) {
722 $user = User::staticGet('id', $mentioned->id);
725 $url = common_local_url('userbyid', array('id' => $user->id));
727 $url = $mentioned->profileurl;
730 $mention = array('mentioned' => array($mentioned),
732 'position' => $match[1],
735 if (!empty($mentioned->fullname)) {
736 $mention['title'] = $mentioned->fullname;
739 $mentions[] = $mention;
743 // @#tag => mention of all subscriptions tagged 'tag'
745 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
748 PREG_OFFSET_CAPTURE);
750 foreach ($hmatches[1] as $hmatch) {
752 $tag = common_canonical_tag($hmatch[0]);
754 $tagged = Profile_tag::getTagged($sender->id, $tag);
756 $url = common_local_url('subscriptions',
757 array('nickname' => $sender->nickname,
760 $mentions[] = array('mentioned' => $tagged,
761 'text' => $hmatch[0],
762 'position' => $hmatch[1],
766 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
773 * Does the actual regex pulls to find @-mentions in text.
774 * Should generally not be called directly; for use in common_find_mentions.
776 * @param string $text
777 * @return array of PCRE match arrays
779 function common_find_mentions_raw($text)
782 preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
785 PREG_OFFSET_CAPTURE);
787 $atmatches = array();
788 preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
791 PREG_OFFSET_CAPTURE);
793 $matches = array_merge($tmatches[1], $atmatches[1]);
797 function common_render_text($text)
799 $r = htmlspecialchars($text);
801 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
802 $r = common_replace_urls_callback($r, 'common_linkify');
803 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
809 * Find links in the given text and pass them to the given callback function.
811 * @param string $text
812 * @param function($text, $arg) $callback: return replacement text
813 * @param mixed $arg: optional argument will be passed on to the callback
815 function common_replace_urls_callback($text, $callback, $arg = null) {
816 // Start off with a regex
818 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
821 '(?:'. //Known protocols
823 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
825 '(?:(?:mailto|aim|tel|xmpp):)'.
827 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
830 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
832 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
836 '|(?:(?: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
838 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
840 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
841 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
842 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
843 '(?: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)'.
847 '(?:\:\d+)?'. //:port
848 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
849 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
850 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
851 ')(?<![\?\.\,\#\,])'.
854 //preg_match_all($regex,$text,$matches);
856 return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
860 * Intermediate callback for common_replace_links(), helps resolve some
861 * ambiguous link forms before passing on to the final callback.
863 * @param array $matches
864 * @param callable $callback
865 * @param mixed $arg optional argument to pass on as second param to callback
870 function callback_helper($matches, $callback, $arg=null) {
872 $left = strpos($matches[0],$url);
873 $right = $left+strlen($url);
875 $groupSymbolSets=array(
893 $cannotEndWith=array('.','?',',','#');
897 foreach($groupSymbolSets as $groupSymbolSet){
898 if(substr($url,-1)==$groupSymbolSet['right']){
899 $group_left_count = substr_count($url,$groupSymbolSet['left']);
900 $group_right_count = substr_count($url,$groupSymbolSet['right']);
901 if($group_left_count<$group_right_count){
903 $url=substr($url,0,-1);
907 if(in_array(substr($url,-1),$cannotEndWith)){
909 $url=substr($url,0,-1);
911 }while($original_url!=$url);
913 $result = call_user_func_array($callback, array($url, $arg));
914 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
917 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
918 // lambda implementation in a separate file; PHP 5.2 won't parse it.
919 require_once INSTALLDIR . "/lib/curry.php";
921 function curry($fn) {
922 $args = func_get_args();
924 $id = uniqid('_partial');
925 $GLOBALS[$id] = array($fn, $args);
926 return create_function('',
927 '$args = func_get_args(); '.
928 'return call_user_func_array('.
929 '$GLOBALS["'.$id.'"][0],'.
932 '$GLOBALS["'.$id.'"][1]));');
936 function common_linkify($url) {
937 // It comes in special'd, so we unspecial it before passing to the stringifying
939 $url = htmlspecialchars_decode($url);
941 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
942 //url is an email address without the mailto: protocol
943 $canon = "mailto:$url";
944 $longurl = "mailto:$url";
947 $canon = File_redirection::_canonUrl($url);
949 $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
950 if (is_array($longurl_data)) {
951 $longurl = $longurl_data['url'];
952 } elseif (is_string($longurl_data)) {
953 $longurl = $longurl_data;
955 // Unable to reach the server to verify contents, etc
956 // Just pass the link on through for now.
957 common_log(LOG_ERR, "Can't linkify url '$url'");
962 $attrs = array('href' => $canon, 'title' => $longurl);
964 $is_attachment = false;
965 $attachment_id = null;
968 // Check to see whether this is a known "attachment" URL.
970 $f = File::staticGet('url', $longurl);
973 if (common_config('attachments', 'process_links')) {
974 // XXX: this writes to the database. :<
975 $f = File::processNew($longurl);
980 if ($f->getEnclosure()) {
981 $is_attachment = true;
982 $attachment_id = $f->id;
984 $thumb = File_thumbnail::staticGet('file_id', $f->id);
985 if (!empty($thumb)) {
992 if ($is_attachment) {
993 $attrs['class'] = 'attachment';
995 $attrs['class'] = 'attachment thumbnail';
997 $attrs['id'] = "attachment-{$attachment_id}";
1000 // Whether to nofollow
1002 $nf = common_config('nofollow', 'external');
1004 if ($nf == 'never') {
1005 $attrs['rel'] = 'external';
1007 $attrs['rel'] = 'nofollow external';
1010 return XMLStringer::estring('a', $attrs, $url);
1014 * Find and shorten links in a given chunk of text if it's longer than the
1015 * configured notice content limit (or unconditionally).
1017 * Side effects: may save file and file_redirection records for referenced URLs.
1019 * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
1020 * user's options are used; otherwise the current web session user's setitngs
1021 * will be used or ur1.ca if there is no active web login.
1023 * @param string $text
1024 * @param boolean $always (optional)
1025 * @param User $user (optional)
1029 function common_shorten_links($text, $always = false, User $user=null)
1031 common_debug("common_shorten_links() called");
1033 $user = common_current_user();
1035 $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
1037 common_debug("maxLength = $maxLength");
1039 if ($always || mb_strlen($text) > $maxLength) {
1040 common_debug("Forcing shortening");
1041 return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
1043 common_debug("Not forcing shortening");
1044 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
1049 * Very basic stripping of invalid UTF-8 input text.
1051 * @param string $str
1052 * @return mixed string or null if invalid input
1054 * @todo ideally we should drop bad chars, and maybe do some of the checks
1055 * from common_xml_safe_str. But we can't strip newlines, etc.
1056 * @todo Unicode normalization might also be useful, but not needed now.
1058 function common_validate_utf8($str)
1060 // preg_replace will return NULL on invalid UTF-8 input.
1062 // Note: empty regex //u also caused NULL return on some
1063 // production machines, but none of our test machines.
1065 // This should be replaced with a more reliable check.
1066 return preg_replace('/\x00/u', '', $str);
1070 * Make sure an arbitrary string is safe for output in XML as a single line.
1072 * @param string $str
1075 function common_xml_safe_str($str)
1077 // Replace common eol and extra whitespace input chars
1082 "\0", // null byte eos
1083 "\x0B" // vertical tab
1086 $replacement = array(
1087 ' ', // single space
1094 $str = str_replace($unWelcome, $replacement, $str);
1096 // Neutralize any additional control codes and UTF-16 surrogates
1097 // (Twitter uses '*')
1098 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1101 function common_tag_link($tag)
1103 $canonical = common_canonical_tag($tag);
1104 if (common_config('singleuser', 'enabled')) {
1105 // regular TagAction isn't set up in 1user mode
1106 $nickname = User::singleUserNickname();
1107 $url = common_local_url('showstream',
1108 array('nickname' => $nickname,
1109 'tag' => $canonical));
1111 $url = common_local_url('tag', array('tag' => $canonical));
1113 $xs = new XMLStringer();
1114 $xs->elementStart('span', 'tag');
1115 $xs->element('a', array('href' => $url,
1118 $xs->elementEnd('span');
1119 return $xs->getString();
1122 function common_canonical_tag($tag)
1124 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1125 return str_replace(array('-', '_', '.'), '', $tag);
1128 function common_valid_profile_tag($str)
1130 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1135 * @param <type> $sender_id
1136 * @param <type> $nickname
1140 function common_group_link($sender_id, $nickname)
1142 $sender = Profile::staticGet($sender_id);
1143 $group = User_group::getForNickname($nickname, $sender);
1144 if ($sender && $group && $sender->isMember($group)) {
1145 $attrs = array('href' => $group->permalink(),
1147 if (!empty($group->fullname)) {
1148 $attrs['title'] = $group->getFancyName();
1150 $xs = new XMLStringer();
1151 $xs->elementStart('span', 'vcard');
1152 $xs->elementStart('a', $attrs);
1153 $xs->element('span', 'fn nickname', $nickname);
1154 $xs->elementEnd('a');
1155 $xs->elementEnd('span');
1156 return $xs->getString();
1163 * Resolve an ambiguous profile nickname reference, checking in following order:
1164 * - profiles that $sender subscribes to
1165 * - profiles that subscribe to $sender
1166 * - local user profiles
1168 * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1169 * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1172 * @fixme validate input
1174 * @fixme fix or remove mystery third parameter
1175 * @fixme is $sender a User or Profile?
1177 * @param <type> $sender the user or profile in whose context we're looking
1178 * @param string $nickname validated nickname of
1179 * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1181 * @return Profile or null
1183 function common_relative_profile($sender, $nickname, $dt=null)
1185 // Will throw exception on invalid input.
1186 $nickname = Nickname::normalize($nickname);
1188 // Try to find profiles this profile is subscribed to that have this nickname
1189 $recipient = new Profile();
1190 // XXX: use a join instead of a subquery
1191 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1192 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1193 if ($recipient->find(true)) {
1194 // XXX: should probably differentiate between profiles with
1195 // the same name by date of most recent update
1198 // Try to find profiles that listen to this profile and that have this nickname
1199 $recipient = new Profile();
1200 // XXX: use a join instead of a subquery
1201 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1202 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1203 if ($recipient->find(true)) {
1204 // XXX: should probably differentiate between profiles with
1205 // the same name by date of most recent update
1208 // If this is a local user, try to find a local user with that nickname.
1209 $sender = User::staticGet($sender->id);
1211 $recipient_user = User::staticGet('nickname', $nickname);
1212 if ($recipient_user) {
1213 return $recipient_user->getProfile();
1216 // Otherwise, no links. @messages from local users to remote users,
1217 // or from remote users to other remote users, are just
1218 // outside our ability to make intelligent guesses about
1222 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1225 $path = $r->build($action, $args, $params, $fragment);
1227 $ssl = common_is_sensitive($action);
1229 if (common_config('site','fancy')) {
1230 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1232 if (mb_strpos($path, '/index.php') === 0) {
1233 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1235 $url = common_path('index.php'.$path, $ssl, $addSession);
1241 function common_is_sensitive($action)
1243 static $sensitive = array(
1248 'ApiOauthRequestToken',
1249 'ApiOauthAccessToken',
1250 'ApiOauthAuthorize',
1256 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1257 $ssl = in_array($action, $sensitive);
1263 function common_path($relative, $ssl=false, $addSession=true)
1265 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1267 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1268 || common_config('site', 'ssl') === 'always') {
1270 if (is_string(common_config('site', 'sslserver')) &&
1271 mb_strlen(common_config('site', 'sslserver')) > 0) {
1272 $serverpart = common_config('site', 'sslserver');
1273 } else if (common_config('site', 'server')) {
1274 $serverpart = common_config('site', 'server');
1276 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1280 if (common_config('site', 'server')) {
1281 $serverpart = common_config('site', 'server');
1283 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1288 $relative = common_inject_session($relative, $serverpart);
1291 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1294 function common_inject_session($url, $serverpart = null)
1296 if (common_have_session()) {
1298 if (empty($serverpart)) {
1299 $serverpart = parse_url($url, PHP_URL_HOST);
1302 $currentServer = $_SERVER['HTTP_HOST'];
1304 // Are we pointing to another server (like an SSL server?)
1306 if (!empty($currentServer) &&
1307 0 != strcasecmp($currentServer, $serverpart)) {
1308 // Pass the session ID as a GET parameter
1309 $sesspart = session_name() . '=' . session_id();
1310 $i = strpos($url, '?');
1311 if ($i === false) { // no GET params, just append
1312 $url .= '?' . $sesspart;
1314 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1322 function common_date_string($dt)
1324 // XXX: do some sexy date formatting
1325 // return date(DATE_RFC822, $dt);
1326 $t = strtotime($dt);
1330 if ($now < $t) { // that shouldn't happen!
1331 return common_exact_date($dt);
1332 } else if ($diff < 60) {
1333 // TRANS: Used in notices to indicate when the notice was made compared to now.
1334 return _('a few seconds ago');
1335 } else if ($diff < 92) {
1336 // TRANS: Used in notices to indicate when the notice was made compared to now.
1337 return _('about a minute ago');
1338 } else if ($diff < 3300) {
1339 $minutes = round($diff/60);
1340 // TRANS: Used in notices to indicate when the notice was made compared to now.
1341 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1342 } else if ($diff < 5400) {
1343 // TRANS: Used in notices to indicate when the notice was made compared to now.
1344 return _('about an hour ago');
1345 } else if ($diff < 22 * 3600) {
1346 $hours = round($diff/3600);
1347 // TRANS: Used in notices to indicate when the notice was made compared to now.
1348 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1349 } else if ($diff < 37 * 3600) {
1350 // TRANS: Used in notices to indicate when the notice was made compared to now.
1351 return _('about a day ago');
1352 } else if ($diff < 24 * 24 * 3600) {
1353 $days = round($diff/(24*3600));
1354 // TRANS: Used in notices to indicate when the notice was made compared to now.
1355 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1356 } else if ($diff < 46 * 24 * 3600) {
1357 // TRANS: Used in notices to indicate when the notice was made compared to now.
1358 return _('about a month ago');
1359 } else if ($diff < 330 * 24 * 3600) {
1360 $months = round($diff/(30*24*3600));
1361 // TRANS: Used in notices to indicate when the notice was made compared to now.
1362 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1363 } else if ($diff < 480 * 24 * 3600) {
1364 // TRANS: Used in notices to indicate when the notice was made compared to now.
1365 return _('about a year ago');
1367 return common_exact_date($dt);
1371 function common_exact_date($dt)
1377 $_utc = new DateTimeZone('UTC');
1378 $_siteTz = new DateTimeZone(common_timezone());
1381 $dateStr = date('d F Y H:i:s', strtotime($dt));
1382 $d = new DateTime($dateStr, $_utc);
1383 $d->setTimezone($_siteTz);
1384 return $d->format(DATE_RFC850);
1387 function common_date_w3dtf($dt)
1389 $dateStr = date('d F Y H:i:s', strtotime($dt));
1390 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1391 $d->setTimezone(new DateTimeZone(common_timezone()));
1392 return $d->format(DATE_W3C);
1395 function common_date_rfc2822($dt)
1397 $dateStr = date('d F Y H:i:s', strtotime($dt));
1398 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1399 $d->setTimezone(new DateTimeZone(common_timezone()));
1400 return $d->format('r');
1403 function common_date_iso8601($dt)
1405 $dateStr = date('d F Y H:i:s', strtotime($dt));
1406 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1407 $d->setTimezone(new DateTimeZone(common_timezone()));
1408 return $d->format('c');
1411 function common_sql_now()
1413 return common_sql_date(time());
1416 function common_sql_date($datetime)
1418 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1422 * Return an SQL fragment to calculate an age-based weight from a given
1423 * timestamp or datetime column.
1425 * @param string $column name of field we're comparing against current time
1426 * @param integer $dropoff divisor for age in seconds before exponentiation
1427 * @return string SQL fragment
1429 function common_sql_weight($column, $dropoff)
1431 if (common_config('db', 'type') == 'pgsql') {
1432 // PostgreSQL doesn't support timestampdiff function.
1433 // @fixme will this use the right time zone?
1434 // @fixme does this handle cross-year subtraction correctly?
1435 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1437 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1441 function common_redirect($url, $code=307)
1443 static $status = array(301 => "Moved Permanently",
1446 307 => "Temporary Redirect");
1448 header('HTTP/1.1 '.$code.' '.$status[$code]);
1449 header("Location: $url");
1451 $xo = new XMLOutputter();
1453 '-//W3C//DTD XHTML 1.0 Strict//EN',
1454 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1455 $xo->element('a', array('href' => $url), $url);
1460 // Stick the notice on the queue
1462 function common_enqueue_notice($notice)
1464 static $localTransports = array('omb',
1467 $transports = array();
1468 if (common_config('sms', 'enabled')) {
1469 $transports[] = 'sms';
1471 if (Event::hasHandler('HandleQueuedNotice')) {
1472 $transports[] = 'plugin';
1475 // We can skip these for gatewayed notices.
1476 if ($notice->isLocal()) {
1477 $transports = array_merge($transports, $localTransports);
1480 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1482 $qm = QueueManager::get();
1484 foreach ($transports as $transport)
1486 $qm->enqueue($notice, $transport);
1489 Event::handle('EndEnqueueNotice', array($notice, $transports));
1496 * Broadcast profile updates to OMB and other remote subscribers.
1498 * Since this may be slow with a lot of subscribers or bad remote sites,
1499 * this is run through the background queues if possible.
1501 function common_broadcast_profile(Profile $profile)
1503 $qm = QueueManager::get();
1504 $qm->enqueue($profile, "profile");
1508 function common_profile_url($nickname)
1510 return common_local_url('showstream', array('nickname' => $nickname),
1515 * Should make up a reasonable root URL
1517 function common_root_url($ssl=false)
1519 $url = common_path('', $ssl, false);
1520 $i = strpos($url, '?');
1522 $url = substr($url, 0, $i);
1528 * returns $bytes bytes of random data as a hexadecimal string
1529 * "good" here is a goal and not a guarantee
1531 function common_good_rand($bytes)
1533 // XXX: use random.org...?
1534 if (@file_exists('/dev/urandom')) {
1535 return common_urandom($bytes);
1536 } else { // FIXME: this is probably not good enough
1537 return common_mtrand($bytes);
1541 function common_urandom($bytes)
1543 $h = fopen('/dev/urandom', 'rb');
1545 $src = fread($h, $bytes);
1548 for ($i = 0; $i < $bytes; $i++) {
1549 $enc .= sprintf("%02x", (ord($src[$i])));
1554 function common_mtrand($bytes)
1557 for ($i = 0; $i < $bytes; $i++) {
1558 $enc .= sprintf("%02x", mt_rand(0, 255));
1564 * Record the given URL as the return destination for a future
1565 * form submission, to be read by common_get_returnto().
1567 * @param string $url
1569 * @fixme as a session-global setting, this can allow multiple forms
1570 * to conflict and overwrite each others' returnto destinations if
1571 * the user has multiple tabs or windows open.
1573 * Should refactor to index with a token or otherwise only pass the
1574 * data along its intended path.
1576 function common_set_returnto($url)
1578 common_ensure_session();
1579 $_SESSION['returnto'] = $url;
1583 * Fetch a return-destination URL previously recorded by
1584 * common_set_returnto().
1586 * @return mixed URL string or null
1588 * @fixme as a session-global setting, this can allow multiple forms
1589 * to conflict and overwrite each others' returnto destinations if
1590 * the user has multiple tabs or windows open.
1592 * Should refactor to index with a token or otherwise only pass the
1593 * data along its intended path.
1595 function common_get_returnto()
1597 common_ensure_session();
1598 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1601 function common_timestamp()
1603 return date('YmdHis');
1606 function common_ensure_syslog()
1608 static $initialized = false;
1609 if (!$initialized) {
1610 openlog(common_config('syslog', 'appname'), 0,
1611 common_config('syslog', 'facility'));
1612 $initialized = true;
1616 function common_log_line($priority, $msg)
1618 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1619 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1620 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1623 function common_request_id()
1626 $server = common_config('site', 'server');
1627 if (php_sapi_name() == 'cli') {
1628 $script = basename($_SERVER['PHP_SELF']);
1629 return "$server:$script:$pid";
1631 static $req_id = null;
1632 if (!isset($req_id)) {
1633 $req_id = substr(md5(mt_rand()), 0, 8);
1635 if (isset($_SERVER['REQUEST_URI'])) {
1636 $url = $_SERVER['REQUEST_URI'];
1638 $method = $_SERVER['REQUEST_METHOD'];
1639 return "$server:$pid.$req_id $method $url";
1643 function common_log($priority, $msg, $filename=null)
1645 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1646 $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1647 $msg = '[' . common_request_id() . '] ' . $msg;
1648 $logfile = common_config('site', 'logfile');
1650 $log = fopen($logfile, "a");
1652 $output = common_log_line($priority, $msg);
1653 fwrite($log, $output);
1657 common_ensure_syslog();
1658 syslog($priority, $msg);
1660 Event::handle('EndLog', array($priority, $msg, $filename));
1664 function common_debug($msg, $filename=null)
1667 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1669 common_log(LOG_DEBUG, $msg);
1673 function common_log_db_error(&$object, $verb, $filename=null)
1675 $objstr = common_log_objstring($object);
1676 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1677 if (is_object($last_error)) {
1678 $msg = $last_error->message;
1680 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1682 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1685 function common_log_objstring(&$object)
1687 if (is_null($object)) {
1690 if (!($object instanceof DB_DataObject)) {
1693 $arr = $object->toArray();
1695 foreach ($arr as $k => $v) {
1696 if (is_object($v)) {
1697 $fields[] = "$k='".get_class($v)."'";
1699 $fields[] = "$k='$v'";
1702 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1706 function common_valid_http_url($url)
1708 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1711 function common_valid_tag($tag)
1713 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1714 return (Validate::email($matches[1]) ||
1715 preg_match('/^([\w-\.]+)$/', $matches[1]));
1721 * Determine if given domain or address literal is valid
1722 * eg for use in JIDs and URLs. Does not check if the domain
1725 * @param string $domain
1726 * @return boolean valid or not
1728 function common_valid_domain($domain)
1730 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1731 $ipv4 = "(?:$octet(?:\.$octet){3})";
1732 if (preg_match("/^$ipv4$/u", $domain)) return true;
1734 $group = "(?:[0-9a-f]{1,4})";
1735 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1737 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1738 $before = explode(":", $matches[1]);
1739 $zeroes = $matches[2];
1740 $after = explode(":", $matches[3]);
1748 $explicit = count($before) + count($after);
1749 if ($explicit < $min || $explicit > $max) {
1756 require_once "Net/IDNA.php";
1757 $idn = Net_IDNA::getInstance();
1758 $domain = $idn->encode($domain);
1759 } catch (Exception $e) {
1763 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1764 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1766 return preg_match("/^$fqdn$/ui", $domain);
1769 /* Following functions are copied from MediaWiki GlobalFunctions.php
1770 * and written by Evan Prodromou. */
1772 function common_accept_to_prefs($accept, $def = '*/*')
1774 // No arg means accept anything (per HTTP spec)
1776 return array($def => 1);
1781 $parts = explode(',', $accept);
1783 foreach($parts as $part) {
1784 // FIXME: doesn't deal with params like 'text/html; level=1'
1785 @list($value, $qpart) = explode(';', trim($part));
1787 if(!isset($qpart)) {
1789 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1790 $prefs[$value] = $match[1];
1797 function common_mime_type_match($type, $avail)
1799 if(array_key_exists($type, $avail)) {
1802 $parts = explode('/', $type);
1803 if(array_key_exists($parts[0] . '/*', $avail)) {
1804 return $parts[0] . '/*';
1805 } elseif(array_key_exists('*/*', $avail)) {
1813 function common_negotiate_type($cprefs, $sprefs)
1817 foreach(array_keys($sprefs) as $type) {
1818 $parts = explode('/', $type);
1819 if($parts[1] != '*') {
1820 $ckey = common_mime_type_match($type, $cprefs);
1822 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1827 foreach(array_keys($cprefs) as $type) {
1828 $parts = explode('/', $type);
1829 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1830 $skey = common_mime_type_match($type, $sprefs);
1832 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1838 $besttype = 'text/html';
1840 foreach(array_keys($combine) as $type) {
1841 if($combine[$type] > $bestq) {
1843 $bestq = $combine[$type];
1847 if ('text/html' === $besttype) {
1848 return "text/html; charset=utf-8";
1853 function common_config($main, $sub)
1856 return (array_key_exists($main, $config) &&
1857 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1861 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1862 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1864 * @param array $from
1867 function common_copy_args($from)
1870 $strip = get_magic_quotes_gpc();
1871 foreach ($from as $k => $v) {
1873 $to[$k] = common_copy_args($v);
1876 $v = stripslashes($v);
1878 $to[$k] = strval(common_validate_utf8($v));
1885 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1886 * This is used before handing a request off to OAuthRequest::from_request.
1887 * @fixme Doesn't consider vars other than _POST and _GET?
1888 * @fixme Can't be undone and could corrupt data if run twice.
1890 function common_remove_magic_from_request()
1892 if(get_magic_quotes_gpc()) {
1893 $_POST=array_map('stripslashes',$_POST);
1894 $_GET=array_map('stripslashes',$_GET);
1898 function common_user_uri(&$user)
1900 return common_local_url('userbyid', array('id' => $user->id),
1904 function common_notice_uri(&$notice)
1906 return common_local_url('shownotice',
1907 array('notice' => $notice->id),
1911 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1913 function common_confirmation_code($bits)
1915 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1916 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1917 $chars = ceil($bits/5);
1919 for ($i = 0; $i < $chars; $i++) {
1920 // XXX: convert to string and back
1921 $num = hexdec(common_good_rand(1));
1922 // XXX: randomness is too precious to throw away almost
1923 // 40% of the bits we get!
1924 $code .= $codechars[$num%32];
1929 // convert markup to HTML
1931 function common_markup_to_html($c)
1933 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1934 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1935 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1936 return Markdown($c);
1939 function common_profile_uri($profile)
1944 $user = User::staticGet($profile->id);
1949 $remote = Remote_profile::staticGet($profile->id);
1951 return $remote->uri;
1953 // XXX: this is a very bad profile!
1957 function common_canonical_sms($sms)
1960 preg_replace('/\D/', '', $sms);
1964 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1969 case E_COMPILE_ERROR:
1973 case E_RECOVERABLE_ERROR:
1974 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1979 case E_COMPILE_WARNING:
1980 case E_CORE_WARNING:
1981 case E_USER_WARNING:
1982 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1987 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1992 case E_USER_DEPRECATED:
1993 // XXX: config variable to log this stuff, too
1997 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
2002 // FIXME: show error page if we're on the Web
2003 /* Don't execute PHP internal error handler */
2007 function common_session_token()
2009 common_ensure_session();
2010 if (!array_key_exists('token', $_SESSION)) {
2011 $_SESSION['token'] = common_good_rand(64);
2013 return $_SESSION['token'];
2016 function common_license_terms($uri)
2018 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2019 return explode('-',$matches[1]);
2024 function common_compatible_license($from, $to)
2026 $from_terms = common_license_terms($from);
2027 // public domain and cc-by are compatible with everything
2028 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2031 $to_terms = common_license_terms($to);
2032 // sa is compatible across versions. IANAL
2033 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2034 return count(array_diff($from_terms, $to_terms)) == 0;
2036 // XXX: better compatibility check needed here!
2037 // Should at least normalise URIs
2038 return ($from == $to);
2042 * returns a quoted table name, if required according to config
2044 function common_database_tablename($tablename)
2046 if(common_config('db','quote_identifiers')) {
2047 $tablename = '"'. $tablename .'"';
2049 //table prefixes could be added here later
2054 * Shorten a URL with the current user's configured shortening service,
2055 * or ur1.ca if configured, or not at all if no shortening is set up.
2057 * @param string $long_url original URL
2058 * @param User $user to specify a particular user's options
2059 * @param boolean $force Force shortening (used when notice is too long)
2060 * @return string may return the original URL if shortening failed
2062 * @fixme provide a way to specify a particular shortener
2064 function common_shorten_url($long_url, User $user=null, $force = false)
2066 common_debug("Shortening URL '$long_url' (force = $force)");
2068 $long_url = trim($long_url);
2070 $user = common_current_user();
2072 $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
2073 common_debug("maxUrlLength = $maxUrlLength");
2075 // $force forces shortening even if it's not strictly needed
2076 // I doubt URL shortening is ever 'strictly' needed. - ESP
2078 if (mb_strlen($long_url) < $maxUrlLength && !$force) {
2079 common_debug("Skipped shortening URL.");
2083 $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
2085 common_debug("Shortener name = '$shortenerName'");
2087 if (Event::handle('StartShortenUrl',
2088 array($long_url, $shortenerName, &$shortenedUrl))) {
2089 if ($shortenerName == 'internal') {
2090 $f = File::processNew($long_url);
2094 $shortenedUrl = common_local_url('redirecturl',
2095 array('id' => $f->id));
2096 return $shortenedUrl;
2102 //URL was shortened, so return the result
2103 return trim($shortenedUrl);
2108 * @return mixed array($proxy, $ip) for web requests; proxy may be null
2109 * null if not a web request
2111 * @fixme X-Forwarded-For can be chained by multiple proxies;
2112 we should parse the list and provide a cleaner array
2113 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2114 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2115 * use function to get exact request headers from Apache if possible.
2117 function common_client_ip()
2119 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2123 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2124 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2125 $proxy = $_SERVER['HTTP_CLIENT_IP'];
2127 $proxy = $_SERVER['REMOTE_ADDR'];
2129 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2132 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2133 $ip = $_SERVER['HTTP_CLIENT_IP'];
2135 $ip = $_SERVER['REMOTE_ADDR'];
2139 return array($proxy, $ip);
2142 function common_url_to_nickname($url)
2144 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2146 $parts = parse_url($url);
2148 # If any of these parts exist, this won't work
2150 foreach ($bad as $badpart) {
2151 if (array_key_exists($badpart, $parts)) {
2156 # We just have host and/or path
2158 # If it's just a host...
2159 if (array_key_exists('host', $parts) &&
2160 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2162 $hostparts = explode('.', $parts['host']);
2164 # Try to catch common idiom of nickname.service.tld
2166 if ((count($hostparts) > 2) &&
2167 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2168 (strcmp($hostparts[0], 'www') != 0))
2170 return common_nicknamize($hostparts[0]);
2172 # Do the whole hostname
2173 return common_nicknamize($parts['host']);
2176 if (array_key_exists('path', $parts)) {
2177 # Strip starting, ending slashes
2178 $path = preg_replace('@/$@', '', $parts['path']);
2179 $path = preg_replace('@^/@', '', $path);
2180 $path = basename($path);
2182 // Hack for MediaWiki user pages, in the form:
2183 // http://example.com/wiki/User:Myname
2184 // ('User' may be localized.)
2185 if (strpos($path, ':')) {
2186 $parts = array_filter(explode(':', $path));
2187 $path = $parts[count($parts) - 1];
2191 return common_nicknamize($path);
2199 function common_nicknamize($str)
2201 $str = preg_replace('/\W/', '', $str);
2202 return strtolower($str);