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 if (!$user->hasRight(Right::WEBLOGIN)) {
321 throw new AuthorizationException(_('Not allowed to log in.'));
323 common_ensure_session();
324 $_SESSION['userid'] = $user->id;
326 Event::handle('EndSetUser', array($user));
334 function common_set_cookie($key, $value, $expiration=0)
336 $path = common_config('site', 'path');
337 $server = common_config('site', 'server');
339 if ($path && ($path != '/')) {
340 $cookiepath = '/' . $path . '/';
344 return setcookie($key,
349 common_config('site', 'ssl')=='always');
352 define('REMEMBERME', 'rememberme');
353 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
355 function common_rememberme($user=null)
358 $user = common_current_user();
364 $rm = new Remember_me();
366 $rm->code = common_good_rand(16);
367 $rm->user_id = $user->id;
369 // Wrap the insert in some good ol' fashioned transaction code
373 $result = $rm->insert();
376 common_log_db_error($rm, 'INSERT', __FILE__);
380 $rm->query('COMMIT');
382 $cookieval = $rm->user_id . ':' . $rm->code;
384 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
386 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
391 function common_remembered_user()
395 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
401 list($id, $code) = explode(':', $packed);
403 if (!$id || !$code) {
404 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
409 $rm = Remember_me::staticGet($code);
412 common_log(LOG_WARNING, 'No such remember code: ' . $code);
417 if ($rm->user_id != $id) {
418 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
423 $user = User::staticGet($rm->user_id);
426 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
432 $result = $rm->delete();
435 common_log_db_error($rm, 'DELETE', __FILE__);
436 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
441 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
443 common_set_user($user);
444 common_real_login(false);
446 // We issue a new cookie, so they can log in
447 // automatically again after this session
449 common_rememberme($user);
455 * must be called with a valid user!
457 function common_forgetme()
459 common_set_cookie(REMEMBERME, '', 0);
463 * Who is the current user?
465 function common_current_user()
469 if (!_have_config()) {
473 if ($_cur === false) {
475 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
476 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
477 common_ensure_session();
478 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
480 $user = User::staticGet($id);
488 // that didn't work; try to remember; will init $_cur to null on failure
489 $_cur = common_remembered_user();
492 // XXX: Is this necessary?
493 $_SESSION['userid'] = $_cur->id;
501 * Logins that are 'remembered' aren't 'real' -- they're subject to
502 * cookie-stealing. So, we don't let them do certain things. New reg,
503 * OpenID, and password logins _are_ real.
505 function common_real_login($real=true)
507 common_ensure_session();
508 $_SESSION['real_login'] = $real;
511 function common_is_real_login()
513 return common_logged_in() && $_SESSION['real_login'];
517 * Get a hash portion for HTTP caching Etags and such including
518 * info on the current user's session. If login/logout state changes,
519 * or we've changed accounts, or we've renamed the current user,
520 * we'll get a new hash value.
522 * This should not be considered secure information.
524 * @param User $user (optional; uses common_current_user() if left out)
527 function common_user_cache_hash($user=false)
529 if ($user === false) {
530 $user = common_current_user();
533 return crc32($user->id . ':' . $user->nickname);
540 * get canonical version of nickname for comparison
542 * @param string $nickname
545 * @throws NicknameException on invalid input
546 * @deprecated call Nickname::normalize() directly.
548 function common_canonical_nickname($nickname)
550 return Nickname::normalize($nickname);
554 * get canonical version of email for comparison
556 * @fixme actually normalize
557 * @fixme reject invalid input
559 * @param string $email
562 function common_canonical_email($email)
564 // XXX: canonicalize UTF-8
565 // XXX: lcase the domain part
570 * Partial notice markup rendering step: build links to !group references.
572 * @param string $text partially rendered HTML
573 * @param Notice $notice in whose context we're working
574 * @return string partially rendered HTML
576 function common_render_content($text, $notice)
578 $r = common_render_text($text);
579 $id = $notice->profile_id;
580 $r = common_linkify_mentions($r, $notice);
581 $r = preg_replace('/(^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/e',
582 "'\\1!'.common_group_link($id, '\\2')", $r);
587 * Finds @-mentions within the partially-rendered text section and
588 * turns them into live links.
590 * Should generally not be called except from common_render_content().
592 * @param string $text partially-rendered HTML
593 * @param Notice $notice in-progress or complete Notice object for context
594 * @return string partially-rendered HTML
596 function common_linkify_mentions($text, $notice)
598 $mentions = common_find_mentions($text, $notice);
600 // We need to go through in reverse order by position,
601 // so our positions stay valid despite our fudging with the
606 foreach ($mentions as $mention)
608 $points[$mention['position']] = $mention;
613 foreach ($points as $position => $mention) {
615 $linkText = common_linkify_mention($mention);
617 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
623 function common_linkify_mention($mention)
627 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
629 $xs = new XMLStringer(false);
631 $attrs = array('href' => $mention['url'],
634 if (!empty($mention['title'])) {
635 $attrs['title'] = $mention['title'];
638 $xs->elementStart('span', 'vcard');
639 $xs->elementStart('a', $attrs);
640 $xs->element('span', 'fn nickname', $mention['text']);
641 $xs->elementEnd('a');
642 $xs->elementEnd('span');
644 $output = $xs->getString();
646 Event::handle('EndLinkifyMention', array($mention, &$output));
653 * Find @-mentions in the given text, using the given notice object as context.
654 * References will be resolved with common_relative_profile() against the user
655 * who posted the notice.
657 * Note the return data format is internal, to be used for building links and
658 * such. Should not be used directly; rather, call common_linkify_mentions().
660 * @param string $text
661 * @param Notice $notice notice in whose context we're building links
667 function common_find_mentions($text, $notice)
671 $sender = Profile::staticGet('id', $notice->profile_id);
673 if (empty($sender)) {
677 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
678 // Get the context of the original notice, if any
679 $originalAuthor = null;
680 $originalNotice = null;
681 $originalMentions = array();
685 if (!empty($notice) && !empty($notice->reply_to)) {
686 $originalNotice = Notice::staticGet('id', $notice->reply_to);
687 if (!empty($originalNotice)) {
688 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
690 $ids = $originalNotice->getReplies();
692 foreach ($ids as $id) {
693 $repliedTo = Profile::staticGet('id', $id);
694 if (!empty($repliedTo)) {
695 $originalMentions[$repliedTo->nickname] = $repliedTo;
701 $matches = common_find_mentions_raw($text);
703 foreach ($matches as $match) {
705 $nickname = Nickname::normalize($match[0]);
706 } catch (NicknameException $e) {
707 // Bogus match? Drop it.
711 // Try to get a profile for this nickname.
712 // Start with conversation context, then go to
715 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
716 $mentioned = $originalAuthor;
717 } else if (!empty($originalMentions) &&
718 array_key_exists($nickname, $originalMentions)) {
719 $mentioned = $originalMentions[$nickname];
721 $mentioned = common_relative_profile($sender, $nickname);
724 if (!empty($mentioned)) {
725 $user = User::staticGet('id', $mentioned->id);
728 $url = common_local_url('userbyid', array('id' => $user->id));
730 $url = $mentioned->profileurl;
733 $mention = array('mentioned' => array($mentioned),
735 'position' => $match[1],
738 if (!empty($mentioned->fullname)) {
739 $mention['title'] = $mentioned->fullname;
742 $mentions[] = $mention;
746 // @#tag => mention of all subscriptions tagged 'tag'
748 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
751 PREG_OFFSET_CAPTURE);
753 foreach ($hmatches[1] as $hmatch) {
755 $tag = common_canonical_tag($hmatch[0]);
757 $tagged = Profile_tag::getTagged($sender->id, $tag);
759 $url = common_local_url('subscriptions',
760 array('nickname' => $sender->nickname,
763 $mentions[] = array('mentioned' => $tagged,
764 'text' => $hmatch[0],
765 'position' => $hmatch[1],
769 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
776 * Does the actual regex pulls to find @-mentions in text.
777 * Should generally not be called directly; for use in common_find_mentions.
779 * @param string $text
780 * @return array of PCRE match arrays
782 function common_find_mentions_raw($text)
785 preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
788 PREG_OFFSET_CAPTURE);
790 $atmatches = array();
791 preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
794 PREG_OFFSET_CAPTURE);
796 $matches = array_merge($tmatches[1], $atmatches[1]);
800 function common_render_text($text)
802 $r = htmlspecialchars($text);
804 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
805 $r = common_replace_urls_callback($r, 'common_linkify');
806 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/ue', "'\\1#'.common_tag_link('\\2')", $r);
812 * Find links in the given text and pass them to the given callback function.
814 * @param string $text
815 * @param function($text, $arg) $callback: return replacement text
816 * @param mixed $arg: optional argument will be passed on to the callback
818 function common_replace_urls_callback($text, $callback, $arg = null) {
819 // Start off with a regex
821 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
824 '(?:'. //Known protocols
826 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
828 '(?:(?:mailto|aim|tel|xmpp):)'.
830 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
833 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
835 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
839 '|(?:(?: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
841 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
843 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
844 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
845 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
846 '(?: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)'.
850 '(?:\:\d+)?'. //:port
851 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
852 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
853 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
854 ')(?<![\?\.\,\#\,])'.
857 //preg_match_all($regex,$text,$matches);
859 return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
863 * Intermediate callback for common_replace_links(), helps resolve some
864 * ambiguous link forms before passing on to the final callback.
866 * @param array $matches
867 * @param callable $callback
868 * @param mixed $arg optional argument to pass on as second param to callback
873 function callback_helper($matches, $callback, $arg=null) {
875 $left = strpos($matches[0],$url);
876 $right = $left+strlen($url);
878 $groupSymbolSets=array(
896 $cannotEndWith=array('.','?',',','#');
900 foreach($groupSymbolSets as $groupSymbolSet){
901 if(substr($url,-1)==$groupSymbolSet['right']){
902 $group_left_count = substr_count($url,$groupSymbolSet['left']);
903 $group_right_count = substr_count($url,$groupSymbolSet['right']);
904 if($group_left_count<$group_right_count){
906 $url=substr($url,0,-1);
910 if(in_array(substr($url,-1),$cannotEndWith)){
912 $url=substr($url,0,-1);
914 }while($original_url!=$url);
916 $result = call_user_func_array($callback, array($url, $arg));
917 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
920 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
921 // lambda implementation in a separate file; PHP 5.2 won't parse it.
922 require_once INSTALLDIR . "/lib/curry.php";
924 function curry($fn) {
925 $args = func_get_args();
927 $id = uniqid('_partial');
928 $GLOBALS[$id] = array($fn, $args);
929 return create_function('',
930 '$args = func_get_args(); '.
931 'return call_user_func_array('.
932 '$GLOBALS["'.$id.'"][0],'.
935 '$GLOBALS["'.$id.'"][1]));');
939 function common_linkify($url) {
940 // It comes in special'd, so we unspecial it before passing to the stringifying
942 $url = htmlspecialchars_decode($url);
944 if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
945 //url is an email address without the mailto: protocol
946 $canon = "mailto:$url";
947 $longurl = "mailto:$url";
950 $canon = File_redirection::_canonUrl($url);
952 $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
953 if (is_array($longurl_data)) {
954 $longurl = $longurl_data['url'];
955 } elseif (is_string($longurl_data)) {
956 $longurl = $longurl_data;
958 // Unable to reach the server to verify contents, etc
959 // Just pass the link on through for now.
960 common_log(LOG_ERR, "Can't linkify url '$url'");
965 $attrs = array('href' => $canon, 'title' => $longurl);
967 $is_attachment = false;
968 $attachment_id = null;
971 // Check to see whether this is a known "attachment" URL.
973 $f = File::staticGet('url', $longurl);
976 if (common_config('attachments', 'process_links')) {
977 // XXX: this writes to the database. :<
978 $f = File::processNew($longurl);
983 if ($f->getEnclosure()) {
984 $is_attachment = true;
985 $attachment_id = $f->id;
987 $thumb = File_thumbnail::staticGet('file_id', $f->id);
988 if (!empty($thumb)) {
995 if ($is_attachment) {
996 $attrs['class'] = 'attachment';
998 $attrs['class'] = 'attachment thumbnail';
1000 $attrs['id'] = "attachment-{$attachment_id}";
1003 // Whether to nofollow
1005 $nf = common_config('nofollow', 'external');
1007 if ($nf == 'never') {
1008 $attrs['rel'] = 'external';
1010 $attrs['rel'] = 'nofollow external';
1013 return XMLStringer::estring('a', $attrs, $url);
1017 * Find and shorten links in a given chunk of text if it's longer than the
1018 * configured notice content limit (or unconditionally).
1020 * Side effects: may save file and file_redirection records for referenced URLs.
1022 * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
1023 * user's options are used; otherwise the current web session user's setitngs
1024 * will be used or ur1.ca if there is no active web login.
1026 * @param string $text
1027 * @param boolean $always (optional)
1028 * @param User $user (optional)
1032 function common_shorten_links($text, $always = false, User $user=null)
1034 $user = common_current_user();
1036 $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
1038 if ($always || mb_strlen($text) > $maxLength) {
1039 return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
1041 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
1046 * Very basic stripping of invalid UTF-8 input text.
1048 * @param string $str
1049 * @return mixed string or null if invalid input
1051 * @todo ideally we should drop bad chars, and maybe do some of the checks
1052 * from common_xml_safe_str. But we can't strip newlines, etc.
1053 * @todo Unicode normalization might also be useful, but not needed now.
1055 function common_validate_utf8($str)
1057 // preg_replace will return NULL on invalid UTF-8 input.
1059 // Note: empty regex //u also caused NULL return on some
1060 // production machines, but none of our test machines.
1062 // This should be replaced with a more reliable check.
1063 return preg_replace('/\x00/u', '', $str);
1067 * Make sure an arbitrary string is safe for output in XML as a single line.
1069 * @param string $str
1072 function common_xml_safe_str($str)
1074 // Replace common eol and extra whitespace input chars
1079 "\0", // null byte eos
1080 "\x0B" // vertical tab
1083 $replacement = array(
1084 ' ', // single space
1091 $str = str_replace($unWelcome, $replacement, $str);
1093 // Neutralize any additional control codes and UTF-16 surrogates
1094 // (Twitter uses '*')
1095 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1098 function common_tag_link($tag)
1100 $canonical = common_canonical_tag($tag);
1101 if (common_config('singleuser', 'enabled')) {
1102 // regular TagAction isn't set up in 1user mode
1103 $nickname = User::singleUserNickname();
1104 $url = common_local_url('showstream',
1105 array('nickname' => $nickname,
1106 'tag' => $canonical));
1108 $url = common_local_url('tag', array('tag' => $canonical));
1110 $xs = new XMLStringer();
1111 $xs->elementStart('span', 'tag');
1112 $xs->element('a', array('href' => $url,
1115 $xs->elementEnd('span');
1116 return $xs->getString();
1119 function common_canonical_tag($tag)
1121 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1122 return str_replace(array('-', '_', '.'), '', $tag);
1125 function common_valid_profile_tag($str)
1127 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1132 * @param <type> $sender_id
1133 * @param <type> $nickname
1137 function common_group_link($sender_id, $nickname)
1139 $sender = Profile::staticGet($sender_id);
1140 $group = User_group::getForNickname($nickname, $sender);
1141 if ($sender && $group && $sender->isMember($group)) {
1142 $attrs = array('href' => $group->permalink(),
1144 if (!empty($group->fullname)) {
1145 $attrs['title'] = $group->getFancyName();
1147 $xs = new XMLStringer();
1148 $xs->elementStart('span', 'vcard');
1149 $xs->elementStart('a', $attrs);
1150 $xs->element('span', 'fn nickname', $nickname);
1151 $xs->elementEnd('a');
1152 $xs->elementEnd('span');
1153 return $xs->getString();
1160 * Resolve an ambiguous profile nickname reference, checking in following order:
1161 * - profiles that $sender subscribes to
1162 * - profiles that subscribe to $sender
1163 * - local user profiles
1165 * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1166 * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1169 * @fixme validate input
1171 * @fixme fix or remove mystery third parameter
1172 * @fixme is $sender a User or Profile?
1174 * @param <type> $sender the user or profile in whose context we're looking
1175 * @param string $nickname validated nickname of
1176 * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1178 * @return Profile or null
1180 function common_relative_profile($sender, $nickname, $dt=null)
1182 // Will throw exception on invalid input.
1183 $nickname = Nickname::normalize($nickname);
1185 // Try to find profiles this profile is subscribed to that have this nickname
1186 $recipient = new Profile();
1187 // XXX: use a join instead of a subquery
1188 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1189 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1190 if ($recipient->find(true)) {
1191 // XXX: should probably differentiate between profiles with
1192 // the same name by date of most recent update
1195 // Try to find profiles that listen to this profile and that have this nickname
1196 $recipient = new Profile();
1197 // XXX: use a join instead of a subquery
1198 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1199 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1200 if ($recipient->find(true)) {
1201 // XXX: should probably differentiate between profiles with
1202 // the same name by date of most recent update
1205 // If this is a local user, try to find a local user with that nickname.
1206 $sender = User::staticGet($sender->id);
1208 $recipient_user = User::staticGet('nickname', $nickname);
1209 if ($recipient_user) {
1210 return $recipient_user->getProfile();
1213 // Otherwise, no links. @messages from local users to remote users,
1214 // or from remote users to other remote users, are just
1215 // outside our ability to make intelligent guesses about
1219 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1222 $path = $r->build($action, $args, $params, $fragment);
1224 $ssl = common_is_sensitive($action);
1226 if (common_config('site','fancy')) {
1227 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1229 if (mb_strpos($path, '/index.php') === 0) {
1230 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1232 $url = common_path('index.php'.$path, $ssl, $addSession);
1238 function common_is_sensitive($action)
1240 static $sensitive = array(
1245 'ApiOauthRequestToken',
1246 'ApiOauthAccessToken',
1247 'ApiOauthAuthorize',
1253 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1254 $ssl = in_array($action, $sensitive);
1260 function common_path($relative, $ssl=false, $addSession=true)
1262 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1264 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1265 || common_config('site', 'ssl') === 'always') {
1267 if (is_string(common_config('site', 'sslserver')) &&
1268 mb_strlen(common_config('site', 'sslserver')) > 0) {
1269 $serverpart = common_config('site', 'sslserver');
1270 } else if (common_config('site', 'server')) {
1271 $serverpart = common_config('site', 'server');
1273 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1277 if (common_config('site', 'server')) {
1278 $serverpart = common_config('site', 'server');
1280 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1285 $relative = common_inject_session($relative, $serverpart);
1288 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1291 function common_inject_session($url, $serverpart = null)
1293 if (common_have_session()) {
1295 if (empty($serverpart)) {
1296 $serverpart = parse_url($url, PHP_URL_HOST);
1299 $currentServer = $_SERVER['HTTP_HOST'];
1301 // Are we pointing to another server (like an SSL server?)
1303 if (!empty($currentServer) &&
1304 0 != strcasecmp($currentServer, $serverpart)) {
1305 // Pass the session ID as a GET parameter
1306 $sesspart = session_name() . '=' . session_id();
1307 $i = strpos($url, '?');
1308 if ($i === false) { // no GET params, just append
1309 $url .= '?' . $sesspart;
1311 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1319 function common_date_string($dt)
1321 // XXX: do some sexy date formatting
1322 // return date(DATE_RFC822, $dt);
1323 $t = strtotime($dt);
1327 if ($now < $t) { // that shouldn't happen!
1328 return common_exact_date($dt);
1329 } else if ($diff < 60) {
1330 // TRANS: Used in notices to indicate when the notice was made compared to now.
1331 return _('a few seconds ago');
1332 } else if ($diff < 92) {
1333 // TRANS: Used in notices to indicate when the notice was made compared to now.
1334 return _('about a minute ago');
1335 } else if ($diff < 3300) {
1336 $minutes = round($diff/60);
1337 // TRANS: Used in notices to indicate when the notice was made compared to now.
1338 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1339 } else if ($diff < 5400) {
1340 // TRANS: Used in notices to indicate when the notice was made compared to now.
1341 return _('about an hour ago');
1342 } else if ($diff < 22 * 3600) {
1343 $hours = round($diff/3600);
1344 // TRANS: Used in notices to indicate when the notice was made compared to now.
1345 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1346 } else if ($diff < 37 * 3600) {
1347 // TRANS: Used in notices to indicate when the notice was made compared to now.
1348 return _('about a day ago');
1349 } else if ($diff < 24 * 24 * 3600) {
1350 $days = round($diff/(24*3600));
1351 // TRANS: Used in notices to indicate when the notice was made compared to now.
1352 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1353 } else if ($diff < 46 * 24 * 3600) {
1354 // TRANS: Used in notices to indicate when the notice was made compared to now.
1355 return _('about a month ago');
1356 } else if ($diff < 330 * 24 * 3600) {
1357 $months = round($diff/(30*24*3600));
1358 // TRANS: Used in notices to indicate when the notice was made compared to now.
1359 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1360 } else if ($diff < 480 * 24 * 3600) {
1361 // TRANS: Used in notices to indicate when the notice was made compared to now.
1362 return _('about a year ago');
1364 return common_exact_date($dt);
1368 function common_exact_date($dt)
1374 $_utc = new DateTimeZone('UTC');
1375 $_siteTz = new DateTimeZone(common_timezone());
1378 $dateStr = date('d F Y H:i:s', strtotime($dt));
1379 $d = new DateTime($dateStr, $_utc);
1380 $d->setTimezone($_siteTz);
1381 return $d->format(DATE_RFC850);
1384 function common_date_w3dtf($dt)
1386 $dateStr = date('d F Y H:i:s', strtotime($dt));
1387 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1388 $d->setTimezone(new DateTimeZone(common_timezone()));
1389 return $d->format(DATE_W3C);
1392 function common_date_rfc2822($dt)
1394 $dateStr = date('d F Y H:i:s', strtotime($dt));
1395 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1396 $d->setTimezone(new DateTimeZone(common_timezone()));
1397 return $d->format('r');
1400 function common_date_iso8601($dt)
1402 $dateStr = date('d F Y H:i:s', strtotime($dt));
1403 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1404 $d->setTimezone(new DateTimeZone(common_timezone()));
1405 return $d->format('c');
1408 function common_sql_now()
1410 return common_sql_date(time());
1413 function common_sql_date($datetime)
1415 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1419 * Return an SQL fragment to calculate an age-based weight from a given
1420 * timestamp or datetime column.
1422 * @param string $column name of field we're comparing against current time
1423 * @param integer $dropoff divisor for age in seconds before exponentiation
1424 * @return string SQL fragment
1426 function common_sql_weight($column, $dropoff)
1428 if (common_config('db', 'type') == 'pgsql') {
1429 // PostgreSQL doesn't support timestampdiff function.
1430 // @fixme will this use the right time zone?
1431 // @fixme does this handle cross-year subtraction correctly?
1432 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1434 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1438 function common_redirect($url, $code=307)
1440 static $status = array(301 => "Moved Permanently",
1443 307 => "Temporary Redirect");
1445 header('HTTP/1.1 '.$code.' '.$status[$code]);
1446 header("Location: $url");
1448 $xo = new XMLOutputter();
1450 '-//W3C//DTD XHTML 1.0 Strict//EN',
1451 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1452 $xo->element('a', array('href' => $url), $url);
1457 // Stick the notice on the queue
1459 function common_enqueue_notice($notice)
1461 static $localTransports = array('omb',
1464 $transports = array();
1465 if (common_config('sms', 'enabled')) {
1466 $transports[] = 'sms';
1468 if (Event::hasHandler('HandleQueuedNotice')) {
1469 $transports[] = 'plugin';
1472 // We can skip these for gatewayed notices.
1473 if ($notice->isLocal()) {
1474 $transports = array_merge($transports, $localTransports);
1477 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1479 $qm = QueueManager::get();
1481 foreach ($transports as $transport)
1483 $qm->enqueue($notice, $transport);
1486 Event::handle('EndEnqueueNotice', array($notice, $transports));
1493 * Broadcast profile updates to OMB and other remote subscribers.
1495 * Since this may be slow with a lot of subscribers or bad remote sites,
1496 * this is run through the background queues if possible.
1498 function common_broadcast_profile(Profile $profile)
1500 $qm = QueueManager::get();
1501 $qm->enqueue($profile, "profile");
1505 function common_profile_url($nickname)
1507 return common_local_url('showstream', array('nickname' => $nickname),
1512 * Should make up a reasonable root URL
1514 function common_root_url($ssl=false)
1516 $url = common_path('', $ssl, false);
1517 $i = strpos($url, '?');
1519 $url = substr($url, 0, $i);
1525 * returns $bytes bytes of random data as a hexadecimal string
1526 * "good" here is a goal and not a guarantee
1528 function common_good_rand($bytes)
1530 // XXX: use random.org...?
1531 if (@file_exists('/dev/urandom')) {
1532 return common_urandom($bytes);
1533 } else { // FIXME: this is probably not good enough
1534 return common_mtrand($bytes);
1538 function common_urandom($bytes)
1540 $h = fopen('/dev/urandom', 'rb');
1542 $src = fread($h, $bytes);
1545 for ($i = 0; $i < $bytes; $i++) {
1546 $enc .= sprintf("%02x", (ord($src[$i])));
1551 function common_mtrand($bytes)
1554 for ($i = 0; $i < $bytes; $i++) {
1555 $enc .= sprintf("%02x", mt_rand(0, 255));
1561 * Record the given URL as the return destination for a future
1562 * form submission, to be read by common_get_returnto().
1564 * @param string $url
1566 * @fixme as a session-global setting, this can allow multiple forms
1567 * to conflict and overwrite each others' returnto destinations if
1568 * the user has multiple tabs or windows open.
1570 * Should refactor to index with a token or otherwise only pass the
1571 * data along its intended path.
1573 function common_set_returnto($url)
1575 common_ensure_session();
1576 $_SESSION['returnto'] = $url;
1580 * Fetch a return-destination URL previously recorded by
1581 * common_set_returnto().
1583 * @return mixed URL string or null
1585 * @fixme as a session-global setting, this can allow multiple forms
1586 * to conflict and overwrite each others' returnto destinations if
1587 * the user has multiple tabs or windows open.
1589 * Should refactor to index with a token or otherwise only pass the
1590 * data along its intended path.
1592 function common_get_returnto()
1594 common_ensure_session();
1595 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1598 function common_timestamp()
1600 return date('YmdHis');
1603 function common_ensure_syslog()
1605 static $initialized = false;
1606 if (!$initialized) {
1607 openlog(common_config('syslog', 'appname'), 0,
1608 common_config('syslog', 'facility'));
1609 $initialized = true;
1613 function common_log_line($priority, $msg)
1615 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1616 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1617 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1620 function common_request_id()
1623 $server = common_config('site', 'server');
1624 if (php_sapi_name() == 'cli') {
1625 $script = basename($_SERVER['PHP_SELF']);
1626 return "$server:$script:$pid";
1628 static $req_id = null;
1629 if (!isset($req_id)) {
1630 $req_id = substr(md5(mt_rand()), 0, 8);
1632 if (isset($_SERVER['REQUEST_URI'])) {
1633 $url = $_SERVER['REQUEST_URI'];
1635 $method = $_SERVER['REQUEST_METHOD'];
1636 return "$server:$pid.$req_id $method $url";
1640 function common_log($priority, $msg, $filename=null)
1642 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1643 $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1644 $msg = '[' . common_request_id() . '] ' . $msg;
1645 $logfile = common_config('site', 'logfile');
1647 $log = fopen($logfile, "a");
1649 $output = common_log_line($priority, $msg);
1650 fwrite($log, $output);
1654 common_ensure_syslog();
1655 syslog($priority, $msg);
1657 Event::handle('EndLog', array($priority, $msg, $filename));
1661 function common_debug($msg, $filename=null)
1664 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1666 common_log(LOG_DEBUG, $msg);
1670 function common_log_db_error(&$object, $verb, $filename=null)
1672 $objstr = common_log_objstring($object);
1673 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1674 if (is_object($last_error)) {
1675 $msg = $last_error->message;
1677 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1679 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1682 function common_log_objstring(&$object)
1684 if (is_null($object)) {
1687 if (!($object instanceof DB_DataObject)) {
1690 $arr = $object->toArray();
1692 foreach ($arr as $k => $v) {
1693 if (is_object($v)) {
1694 $fields[] = "$k='".get_class($v)."'";
1696 $fields[] = "$k='$v'";
1699 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1703 function common_valid_http_url($url)
1705 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1708 function common_valid_tag($tag)
1710 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1711 return (Validate::email($matches[1]) ||
1712 preg_match('/^([\w-\.]+)$/', $matches[1]));
1718 * Determine if given domain or address literal is valid
1719 * eg for use in JIDs and URLs. Does not check if the domain
1722 * @param string $domain
1723 * @return boolean valid or not
1725 function common_valid_domain($domain)
1727 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1728 $ipv4 = "(?:$octet(?:\.$octet){3})";
1729 if (preg_match("/^$ipv4$/u", $domain)) return true;
1731 $group = "(?:[0-9a-f]{1,4})";
1732 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1734 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1735 $before = explode(":", $matches[1]);
1736 $zeroes = $matches[2];
1737 $after = explode(":", $matches[3]);
1745 $explicit = count($before) + count($after);
1746 if ($explicit < $min || $explicit > $max) {
1753 require_once "Net/IDNA.php";
1754 $idn = Net_IDNA::getInstance();
1755 $domain = $idn->encode($domain);
1756 } catch (Exception $e) {
1760 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1761 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1763 return preg_match("/^$fqdn$/ui", $domain);
1766 /* Following functions are copied from MediaWiki GlobalFunctions.php
1767 * and written by Evan Prodromou. */
1769 function common_accept_to_prefs($accept, $def = '*/*')
1771 // No arg means accept anything (per HTTP spec)
1773 return array($def => 1);
1778 $parts = explode(',', $accept);
1780 foreach($parts as $part) {
1781 // FIXME: doesn't deal with params like 'text/html; level=1'
1782 @list($value, $qpart) = explode(';', trim($part));
1784 if(!isset($qpart)) {
1786 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1787 $prefs[$value] = $match[1];
1794 function common_mime_type_match($type, $avail)
1796 if(array_key_exists($type, $avail)) {
1799 $parts = explode('/', $type);
1800 if(array_key_exists($parts[0] . '/*', $avail)) {
1801 return $parts[0] . '/*';
1802 } elseif(array_key_exists('*/*', $avail)) {
1810 function common_negotiate_type($cprefs, $sprefs)
1814 foreach(array_keys($sprefs) as $type) {
1815 $parts = explode('/', $type);
1816 if($parts[1] != '*') {
1817 $ckey = common_mime_type_match($type, $cprefs);
1819 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1824 foreach(array_keys($cprefs) as $type) {
1825 $parts = explode('/', $type);
1826 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1827 $skey = common_mime_type_match($type, $sprefs);
1829 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1835 $besttype = 'text/html';
1837 foreach(array_keys($combine) as $type) {
1838 if($combine[$type] > $bestq) {
1840 $bestq = $combine[$type];
1844 if ('text/html' === $besttype) {
1845 return "text/html; charset=utf-8";
1850 function common_config($main, $sub)
1853 return (array_key_exists($main, $config) &&
1854 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1858 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1859 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1861 * @param array $from
1864 function common_copy_args($from)
1867 $strip = get_magic_quotes_gpc();
1868 foreach ($from as $k => $v) {
1870 $to[$k] = common_copy_args($v);
1873 $v = stripslashes($v);
1875 $to[$k] = strval(common_validate_utf8($v));
1882 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1883 * This is used before handing a request off to OAuthRequest::from_request.
1884 * @fixme Doesn't consider vars other than _POST and _GET?
1885 * @fixme Can't be undone and could corrupt data if run twice.
1887 function common_remove_magic_from_request()
1889 if(get_magic_quotes_gpc()) {
1890 $_POST=array_map('stripslashes',$_POST);
1891 $_GET=array_map('stripslashes',$_GET);
1895 function common_user_uri(&$user)
1897 return common_local_url('userbyid', array('id' => $user->id),
1901 function common_notice_uri(&$notice)
1903 return common_local_url('shownotice',
1904 array('notice' => $notice->id),
1908 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1910 function common_confirmation_code($bits)
1912 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1913 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1914 $chars = ceil($bits/5);
1916 for ($i = 0; $i < $chars; $i++) {
1917 // XXX: convert to string and back
1918 $num = hexdec(common_good_rand(1));
1919 // XXX: randomness is too precious to throw away almost
1920 // 40% of the bits we get!
1921 $code .= $codechars[$num%32];
1926 // convert markup to HTML
1928 function common_markup_to_html($c)
1930 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1931 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1932 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1933 return Markdown($c);
1936 function common_profile_uri($profile)
1941 $user = User::staticGet($profile->id);
1946 $remote = Remote_profile::staticGet($profile->id);
1948 return $remote->uri;
1950 // XXX: this is a very bad profile!
1954 function common_canonical_sms($sms)
1957 preg_replace('/\D/', '', $sms);
1961 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1966 case E_COMPILE_ERROR:
1970 case E_RECOVERABLE_ERROR:
1971 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1976 case E_COMPILE_WARNING:
1977 case E_CORE_WARNING:
1978 case E_USER_WARNING:
1979 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1984 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1989 case E_USER_DEPRECATED:
1990 // XXX: config variable to log this stuff, too
1994 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1999 // FIXME: show error page if we're on the Web
2000 /* Don't execute PHP internal error handler */
2004 function common_session_token()
2006 common_ensure_session();
2007 if (!array_key_exists('token', $_SESSION)) {
2008 $_SESSION['token'] = common_good_rand(64);
2010 return $_SESSION['token'];
2013 function common_license_terms($uri)
2015 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2016 return explode('-',$matches[1]);
2021 function common_compatible_license($from, $to)
2023 $from_terms = common_license_terms($from);
2024 // public domain and cc-by are compatible with everything
2025 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2028 $to_terms = common_license_terms($to);
2029 // sa is compatible across versions. IANAL
2030 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2031 return count(array_diff($from_terms, $to_terms)) == 0;
2033 // XXX: better compatibility check needed here!
2034 // Should at least normalise URIs
2035 return ($from == $to);
2039 * returns a quoted table name, if required according to config
2041 function common_database_tablename($tablename)
2043 if(common_config('db','quote_identifiers')) {
2044 $tablename = '"'. $tablename .'"';
2046 //table prefixes could be added here later
2051 * Shorten a URL with the current user's configured shortening service,
2052 * or ur1.ca if configured, or not at all if no shortening is set up.
2054 * @param string $long_url original URL
2055 * @param User $user to specify a particular user's options
2056 * @param boolean $force Force shortening (used when notice is too long)
2057 * @return string may return the original URL if shortening failed
2059 * @fixme provide a way to specify a particular shortener
2061 function common_shorten_url($long_url, User $user=null, $force = false)
2063 $long_url = trim($long_url);
2065 $user = common_current_user();
2067 $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
2069 // $force forces shortening even if it's not strictly needed
2070 // I doubt URL shortening is ever 'strictly' needed. - ESP
2072 if (mb_strlen($long_url) < $maxUrlLength && !$force) {
2076 $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
2078 if (Event::handle('StartShortenUrl',
2079 array($long_url, $shortenerName, &$shortenedUrl))) {
2080 if ($shortenerName == 'internal') {
2081 $f = File::processNew($long_url);
2085 $shortenedUrl = common_local_url('redirecturl',
2086 array('id' => $f->id));
2087 return $shortenedUrl;
2093 //URL was shortened, so return the result
2094 return trim($shortenedUrl);
2099 * @return mixed array($proxy, $ip) for web requests; proxy may be null
2100 * null if not a web request
2102 * @fixme X-Forwarded-For can be chained by multiple proxies;
2103 we should parse the list and provide a cleaner array
2104 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2105 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2106 * use function to get exact request headers from Apache if possible.
2108 function common_client_ip()
2110 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2114 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2115 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2116 $proxy = $_SERVER['HTTP_CLIENT_IP'];
2118 $proxy = $_SERVER['REMOTE_ADDR'];
2120 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2123 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2124 $ip = $_SERVER['HTTP_CLIENT_IP'];
2126 $ip = $_SERVER['REMOTE_ADDR'];
2130 return array($proxy, $ip);
2133 function common_url_to_nickname($url)
2135 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2137 $parts = parse_url($url);
2139 # If any of these parts exist, this won't work
2141 foreach ($bad as $badpart) {
2142 if (array_key_exists($badpart, $parts)) {
2147 # We just have host and/or path
2149 # If it's just a host...
2150 if (array_key_exists('host', $parts) &&
2151 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2153 $hostparts = explode('.', $parts['host']);
2155 # Try to catch common idiom of nickname.service.tld
2157 if ((count($hostparts) > 2) &&
2158 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2159 (strcmp($hostparts[0], 'www') != 0))
2161 return common_nicknamize($hostparts[0]);
2163 # Do the whole hostname
2164 return common_nicknamize($parts['host']);
2167 if (array_key_exists('path', $parts)) {
2168 # Strip starting, ending slashes
2169 $path = preg_replace('@/$@', '', $parts['path']);
2170 $path = preg_replace('@^/@', '', $path);
2171 $path = basename($path);
2173 // Hack for MediaWiki user pages, in the form:
2174 // http://example.com/wiki/User:Myname
2175 // ('User' may be localized.)
2176 if (strpos($path, ':')) {
2177 $parts = array_filter(explode(':', $path));
2178 $path = $parts[count($parts) - 1];
2182 return common_nicknamize($path);
2190 function common_nicknamize($str)
2192 $str = preg_replace('/\W/', '', $str);
2193 return strtolower($str);
2196 function common_perf_counter($key, $val=null)
2198 global $_perfCounters;
2199 if (isset($_perfCounters)) {
2200 if (common_config('site', 'logperf')) {
2201 if (array_key_exists($key, $_perfCounters)) {
2202 $_perfCounters[$key][] = $val;
2204 $_perfCounters[$key] = array($val);
2206 if (common_config('site', 'logperf_detail')) {
2207 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2213 function common_log_perf_counters()
2215 if (common_config('site', 'logperf')) {
2216 global $_startTime, $_perfCounters;
2218 if (isset($_startTime)) {
2219 $endTime = microtime(true);
2220 $diff = round(($endTime - $_startTime) * 1000);
2221 common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2223 $counters = $_perfCounters;
2225 foreach ($counters as $key => $values) {
2226 $count = count($values);
2227 $unique = count(array_unique($values));
2228 common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");