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 // TRANS: Authorisation exception thrown when a user a not allowed to login.
322 throw new AuthorizationException(_('Not allowed to log in.'));
324 common_ensure_session();
325 $_SESSION['userid'] = $user->id;
327 Event::handle('EndSetUser', array($user));
335 function common_set_cookie($key, $value, $expiration=0)
337 $path = common_config('site', 'path');
338 $server = common_config('site', 'server');
340 if ($path && ($path != '/')) {
341 $cookiepath = '/' . $path . '/';
345 return setcookie($key,
350 common_config('site', 'ssl')=='always');
353 define('REMEMBERME', 'rememberme');
354 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
356 function common_rememberme($user=null)
359 $user = common_current_user();
365 $rm = new Remember_me();
367 $rm->code = common_good_rand(16);
368 $rm->user_id = $user->id;
370 // Wrap the insert in some good ol' fashioned transaction code
374 $result = $rm->insert();
377 common_log_db_error($rm, 'INSERT', __FILE__);
381 $rm->query('COMMIT');
383 $cookieval = $rm->user_id . ':' . $rm->code;
385 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
387 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
392 function common_remembered_user()
396 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
402 list($id, $code) = explode(':', $packed);
404 if (!$id || !$code) {
405 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
410 $rm = Remember_me::staticGet($code);
413 common_log(LOG_WARNING, 'No such remember code: ' . $code);
418 if ($rm->user_id != $id) {
419 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
424 $user = User::staticGet($rm->user_id);
427 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
433 $result = $rm->delete();
436 common_log_db_error($rm, 'DELETE', __FILE__);
437 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
442 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
444 common_set_user($user);
445 common_real_login(false);
447 // We issue a new cookie, so they can log in
448 // automatically again after this session
450 common_rememberme($user);
456 * must be called with a valid user!
458 function common_forgetme()
460 common_set_cookie(REMEMBERME, '', 0);
464 * Who is the current user?
466 function common_current_user()
470 if (!_have_config()) {
474 if ($_cur === false) {
476 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
477 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
478 common_ensure_session();
479 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
481 $user = User::staticGet($id);
489 // that didn't work; try to remember; will init $_cur to null on failure
490 $_cur = common_remembered_user();
493 // XXX: Is this necessary?
494 $_SESSION['userid'] = $_cur->id;
502 * Logins that are 'remembered' aren't 'real' -- they're subject to
503 * cookie-stealing. So, we don't let them do certain things. New reg,
504 * OpenID, and password logins _are_ real.
506 function common_real_login($real=true)
508 common_ensure_session();
509 $_SESSION['real_login'] = $real;
512 function common_is_real_login()
514 return common_logged_in() && $_SESSION['real_login'];
518 * Get a hash portion for HTTP caching Etags and such including
519 * info on the current user's session. If login/logout state changes,
520 * or we've changed accounts, or we've renamed the current user,
521 * we'll get a new hash value.
523 * This should not be considered secure information.
525 * @param User $user (optional; uses common_current_user() if left out)
528 function common_user_cache_hash($user=false)
530 if ($user === false) {
531 $user = common_current_user();
534 return crc32($user->id . ':' . $user->nickname);
541 * get canonical version of nickname for comparison
543 * @param string $nickname
546 * @throws NicknameException on invalid input
547 * @deprecated call Nickname::normalize() directly.
549 function common_canonical_nickname($nickname)
551 return Nickname::normalize($nickname);
555 * get canonical version of email for comparison
557 * @fixme actually normalize
558 * @fixme reject invalid input
560 * @param string $email
563 function common_canonical_email($email)
565 // XXX: canonicalize UTF-8
566 // XXX: lcase the domain part
571 * Partial notice markup rendering step: build links to !group references.
573 * @param string $text partially rendered HTML
574 * @param Notice $notice in whose context we're working
575 * @return string partially rendered HTML
577 function common_render_content($text, $notice)
579 $r = common_render_text($text);
580 $id = $notice->profile_id;
581 $r = common_linkify_mentions($r, $notice);
582 $r = preg_replace('/(^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/e',
583 "'\\1!'.common_group_link($id, '\\2')", $r);
588 * Finds @-mentions within the partially-rendered text section and
589 * turns them into live links.
591 * Should generally not be called except from common_render_content().
593 * @param string $text partially-rendered HTML
594 * @param Notice $notice in-progress or complete Notice object for context
595 * @return string partially-rendered HTML
597 function common_linkify_mentions($text, $notice)
599 $mentions = common_find_mentions($text, $notice);
601 // We need to go through in reverse order by position,
602 // so our positions stay valid despite our fudging with the
607 foreach ($mentions as $mention)
609 $points[$mention['position']] = $mention;
614 foreach ($points as $position => $mention) {
616 $linkText = common_linkify_mention($mention);
618 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
624 function common_linkify_mention($mention)
628 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
630 $xs = new XMLStringer(false);
632 $attrs = array('href' => $mention['url'],
635 if (!empty($mention['title'])) {
636 $attrs['title'] = $mention['title'];
639 $xs->elementStart('span', 'vcard');
640 $xs->elementStart('a', $attrs);
641 $xs->element('span', 'fn nickname profile', $mention['text']);
642 $xs->elementEnd('a');
643 $xs->elementEnd('span');
645 $output = $xs->getString();
647 Event::handle('EndLinkifyMention', array($mention, &$output));
654 * Find @-mentions in the given text, using the given notice object as context.
655 * References will be resolved with common_relative_profile() against the user
656 * who posted the notice.
658 * Note the return data format is internal, to be used for building links and
659 * such. Should not be used directly; rather, call common_linkify_mentions().
661 * @param string $text
662 * @param Notice $notice notice in whose context we're building links
668 function common_find_mentions($text, $notice)
672 $sender = Profile::staticGet('id', $notice->profile_id);
674 if (empty($sender)) {
678 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
679 // Get the context of the original notice, if any
680 $originalAuthor = null;
681 $originalNotice = null;
682 $originalMentions = array();
686 if (!empty($notice) && !empty($notice->reply_to)) {
687 $originalNotice = Notice::staticGet('id', $notice->reply_to);
688 if (!empty($originalNotice)) {
689 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
691 $ids = $originalNotice->getReplies();
693 foreach ($ids as $id) {
694 $repliedTo = Profile::staticGet('id', $id);
695 if (!empty($repliedTo)) {
696 $originalMentions[$repliedTo->nickname] = $repliedTo;
702 $matches = common_find_mentions_raw($text);
704 foreach ($matches as $match) {
706 $nickname = Nickname::normalize($match[0]);
707 } catch (NicknameException $e) {
708 // Bogus match? Drop it.
712 // Try to get a profile for this nickname.
713 // Start with conversation context, then go to
716 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
717 $mentioned = $originalAuthor;
718 } else if (!empty($originalMentions) &&
719 array_key_exists($nickname, $originalMentions)) {
720 $mentioned = $originalMentions[$nickname];
722 $mentioned = common_relative_profile($sender, $nickname);
725 if (!empty($mentioned)) {
726 $user = User::staticGet('id', $mentioned->id);
729 $url = common_local_url('userbyid', array('id' => $user->id));
731 $url = $mentioned->profileurl;
734 $mention = array('mentioned' => array($mentioned),
736 'position' => $match[1],
739 if (!empty($mentioned->fullname)) {
740 $mention['title'] = $mentioned->fullname;
743 $mentions[] = $mention;
747 // @#tag => mention of all subscriptions tagged 'tag'
749 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
752 PREG_OFFSET_CAPTURE);
754 foreach ($hmatches[1] as $hmatch) {
756 $tag = common_canonical_tag($hmatch[0]);
758 $tagged = Profile_tag::getTagged($sender->id, $tag);
760 $url = common_local_url('subscriptions',
761 array('nickname' => $sender->nickname,
764 $mentions[] = array('mentioned' => $tagged,
765 'text' => $hmatch[0],
766 'position' => $hmatch[1],
770 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
777 * Does the actual regex pulls to find @-mentions in text.
778 * Should generally not be called directly; for use in common_find_mentions.
780 * @param string $text
781 * @return array of PCRE match arrays
783 function common_find_mentions_raw($text)
786 preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
789 PREG_OFFSET_CAPTURE);
791 $atmatches = array();
792 preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
795 PREG_OFFSET_CAPTURE);
797 $matches = array_merge($tmatches[1], $atmatches[1]);
801 function common_render_text($text)
803 $r = htmlspecialchars($text);
805 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
806 $r = common_replace_urls_callback($r, 'common_linkify');
807 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/ue', "'\\1#'.common_tag_link('\\2')", $r);
813 * Find links in the given text and pass them to the given callback function.
815 * @param string $text
816 * @param function($text, $arg) $callback: return replacement text
817 * @param mixed $arg: optional argument will be passed on to the callback
819 function common_replace_urls_callback($text, $callback, $arg = null) {
820 // Start off with a regex
822 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
825 '(?:'. //Known protocols
827 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
829 '(?:(?:mailto|aim|tel|xmpp):)'.
831 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
834 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
836 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
840 '|(?:(?: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
842 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
844 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
845 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
846 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
847 '(?: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)'.
851 '(?:\:\d+)?'. //:port
852 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
853 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
854 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
855 ')(?<![\?\.\,\#\,])'.
858 //preg_match_all($regex,$text,$matches);
860 return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
864 * Intermediate callback for common_replace_links(), helps resolve some
865 * ambiguous link forms before passing on to the final callback.
867 * @param array $matches
868 * @param callable $callback
869 * @param mixed $arg optional argument to pass on as second param to callback
874 function callback_helper($matches, $callback, $arg=null) {
876 $left = strpos($matches[0],$url);
877 $right = $left+strlen($url);
879 $groupSymbolSets=array(
897 $cannotEndWith=array('.','?',',','#');
901 foreach($groupSymbolSets as $groupSymbolSet){
902 if(substr($url,-1)==$groupSymbolSet['right']){
903 $group_left_count = substr_count($url,$groupSymbolSet['left']);
904 $group_right_count = substr_count($url,$groupSymbolSet['right']);
905 if($group_left_count<$group_right_count){
907 $url=substr($url,0,-1);
911 if(in_array(substr($url,-1),$cannotEndWith)){
913 $url=substr($url,0,-1);
915 }while($original_url!=$url);
917 $result = call_user_func_array($callback, array($url, $arg));
918 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
921 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
922 // lambda implementation in a separate file; PHP 5.2 won't parse it.
923 require_once INSTALLDIR . "/lib/curry.php";
925 function curry($fn) {
926 $args = func_get_args();
928 $id = uniqid('_partial');
929 $GLOBALS[$id] = array($fn, $args);
930 return create_function('',
931 '$args = func_get_args(); '.
932 'return call_user_func_array('.
933 '$GLOBALS["'.$id.'"][0],'.
936 '$GLOBALS["'.$id.'"][1]));');
940 function common_linkify($url) {
941 // It comes in special'd, so we unspecial it before passing to the stringifying
943 $url = htmlspecialchars_decode($url);
945 if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
946 //url is an email address without the mailto: protocol
947 $canon = "mailto:$url";
948 $longurl = "mailto:$url";
951 $canon = File_redirection::_canonUrl($url);
953 $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
954 if (is_array($longurl_data)) {
955 $longurl = $longurl_data['url'];
956 } elseif (is_string($longurl_data)) {
957 $longurl = $longurl_data;
959 // Unable to reach the server to verify contents, etc
960 // Just pass the link on through for now.
961 common_log(LOG_ERR, "Can't linkify url '$url'");
966 $attrs = array('href' => $canon, 'title' => $longurl);
968 $is_attachment = false;
969 $attachment_id = null;
972 // Check to see whether this is a known "attachment" URL.
974 $f = File::staticGet('url', $longurl);
977 if (common_config('attachments', 'process_links')) {
978 // XXX: this writes to the database. :<
979 $f = File::processNew($longurl);
984 if ($f->getEnclosure()) {
985 $is_attachment = true;
986 $attachment_id = $f->id;
988 $thumb = File_thumbnail::staticGet('file_id', $f->id);
989 if (!empty($thumb)) {
996 if ($is_attachment) {
997 $attrs['class'] = 'attachment';
999 $attrs['class'] = 'attachment thumbnail';
1001 $attrs['id'] = "attachment-{$attachment_id}";
1004 // Whether to nofollow
1006 $nf = common_config('nofollow', 'external');
1008 if ($nf == 'never') {
1009 $attrs['rel'] = 'external';
1011 $attrs['rel'] = 'nofollow external';
1014 return XMLStringer::estring('a', $attrs, $url);
1018 * Find and shorten links in a given chunk of text if it's longer than the
1019 * configured notice content limit (or unconditionally).
1021 * Side effects: may save file and file_redirection records for referenced URLs.
1023 * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
1024 * user's options are used; otherwise the current web session user's setitngs
1025 * will be used or ur1.ca if there is no active web login.
1027 * @param string $text
1028 * @param boolean $always (optional)
1029 * @param User $user (optional)
1033 function common_shorten_links($text, $always = false, User $user=null)
1035 $user = common_current_user();
1037 $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
1039 if ($always || mb_strlen($text) > $maxLength) {
1040 return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
1042 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
1047 * Very basic stripping of invalid UTF-8 input text.
1049 * @param string $str
1050 * @return mixed string or null if invalid input
1052 * @todo ideally we should drop bad chars, and maybe do some of the checks
1053 * from common_xml_safe_str. But we can't strip newlines, etc.
1054 * @todo Unicode normalization might also be useful, but not needed now.
1056 function common_validate_utf8($str)
1058 // preg_replace will return NULL on invalid UTF-8 input.
1060 // Note: empty regex //u also caused NULL return on some
1061 // production machines, but none of our test machines.
1063 // This should be replaced with a more reliable check.
1064 return preg_replace('/\x00/u', '', $str);
1068 * Make sure an arbitrary string is safe for output in XML as a single line.
1070 * @param string $str
1073 function common_xml_safe_str($str)
1075 // Replace common eol and extra whitespace input chars
1080 "\0", // null byte eos
1081 "\x0B" // vertical tab
1084 $replacement = array(
1085 ' ', // single space
1092 $str = str_replace($unWelcome, $replacement, $str);
1094 // Neutralize any additional control codes and UTF-16 surrogates
1095 // (Twitter uses '*')
1096 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1099 function common_tag_link($tag)
1101 $canonical = common_canonical_tag($tag);
1102 if (common_config('singleuser', 'enabled')) {
1103 // regular TagAction isn't set up in 1user mode
1104 $nickname = User::singleUserNickname();
1105 $url = common_local_url('showstream',
1106 array('nickname' => $nickname,
1107 'tag' => $canonical));
1109 $url = common_local_url('tag', array('tag' => $canonical));
1111 $xs = new XMLStringer();
1112 $xs->elementStart('span', 'tag');
1113 $xs->element('a', array('href' => $url,
1116 $xs->elementEnd('span');
1117 return $xs->getString();
1120 function common_canonical_tag($tag)
1122 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1123 return str_replace(array('-', '_', '.'), '', $tag);
1126 function common_valid_profile_tag($str)
1128 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1133 * @param <type> $sender_id
1134 * @param <type> $nickname
1138 function common_group_link($sender_id, $nickname)
1140 $sender = Profile::staticGet($sender_id);
1141 $group = User_group::getForNickname($nickname, $sender);
1142 if ($sender && $group && $sender->isMember($group)) {
1143 $attrs = array('href' => $group->permalink(),
1145 if (!empty($group->fullname)) {
1146 $attrs['title'] = $group->getFancyName();
1148 $xs = new XMLStringer();
1149 $xs->elementStart('span', 'vcard');
1150 $xs->elementStart('a', $attrs);
1151 $xs->element('span', 'fn nickname group', $nickname);
1152 $xs->elementEnd('a');
1153 $xs->elementEnd('span');
1154 return $xs->getString();
1161 * Resolve an ambiguous profile nickname reference, checking in following order:
1162 * - profiles that $sender subscribes to
1163 * - profiles that subscribe to $sender
1164 * - local user profiles
1166 * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1167 * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1170 * @fixme validate input
1172 * @fixme fix or remove mystery third parameter
1173 * @fixme is $sender a User or Profile?
1175 * @param <type> $sender the user or profile in whose context we're looking
1176 * @param string $nickname validated nickname of
1177 * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1179 * @return Profile or null
1181 function common_relative_profile($sender, $nickname, $dt=null)
1183 // Will throw exception on invalid input.
1184 $nickname = Nickname::normalize($nickname);
1186 // Try to find profiles this profile is subscribed to that have this nickname
1187 $recipient = new Profile();
1188 // XXX: use a join instead of a subquery
1189 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1190 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1191 if ($recipient->find(true)) {
1192 // XXX: should probably differentiate between profiles with
1193 // the same name by date of most recent update
1196 // Try to find profiles that listen to this profile and that have this nickname
1197 $recipient = new Profile();
1198 // XXX: use a join instead of a subquery
1199 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1200 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1201 if ($recipient->find(true)) {
1202 // XXX: should probably differentiate between profiles with
1203 // the same name by date of most recent update
1206 // If this is a local user, try to find a local user with that nickname.
1207 $sender = User::staticGet($sender->id);
1209 $recipient_user = User::staticGet('nickname', $nickname);
1210 if ($recipient_user) {
1211 return $recipient_user->getProfile();
1214 // Otherwise, no links. @messages from local users to remote users,
1215 // or from remote users to other remote users, are just
1216 // outside our ability to make intelligent guesses about
1220 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1223 $path = $r->build($action, $args, $params, $fragment);
1225 $ssl = common_is_sensitive($action);
1227 if (common_config('site','fancy')) {
1228 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1230 if (mb_strpos($path, '/index.php') === 0) {
1231 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1233 $url = common_path('index.php'.$path, $ssl, $addSession);
1239 function common_is_sensitive($action)
1241 static $sensitive = array(
1246 'ApiOauthRequestToken',
1247 'ApiOauthAccessToken',
1248 'ApiOauthAuthorize',
1254 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1255 $ssl = in_array($action, $sensitive);
1261 function common_path($relative, $ssl=false, $addSession=true)
1263 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1265 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1266 || common_config('site', 'ssl') === 'always') {
1268 if (is_string(common_config('site', 'sslserver')) &&
1269 mb_strlen(common_config('site', 'sslserver')) > 0) {
1270 $serverpart = common_config('site', 'sslserver');
1271 } else if (common_config('site', 'server')) {
1272 $serverpart = common_config('site', 'server');
1274 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1278 if (common_config('site', 'server')) {
1279 $serverpart = common_config('site', 'server');
1281 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1286 $relative = common_inject_session($relative, $serverpart);
1289 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1292 function common_inject_session($url, $serverpart = null)
1294 if (common_have_session()) {
1296 if (empty($serverpart)) {
1297 $serverpart = parse_url($url, PHP_URL_HOST);
1300 $currentServer = $_SERVER['HTTP_HOST'];
1302 // Are we pointing to another server (like an SSL server?)
1304 if (!empty($currentServer) &&
1305 0 != strcasecmp($currentServer, $serverpart)) {
1306 // Pass the session ID as a GET parameter
1307 $sesspart = session_name() . '=' . session_id();
1308 $i = strpos($url, '?');
1309 if ($i === false) { // no GET params, just append
1310 $url .= '?' . $sesspart;
1312 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1320 function common_date_string($dt)
1322 // XXX: do some sexy date formatting
1323 // return date(DATE_RFC822, $dt);
1324 $t = strtotime($dt);
1328 if ($now < $t) { // that shouldn't happen!
1329 return common_exact_date($dt);
1330 } else if ($diff < 60) {
1331 // TRANS: Used in notices to indicate when the notice was made compared to now.
1332 return _('a few seconds ago');
1333 } else if ($diff < 92) {
1334 // TRANS: Used in notices to indicate when the notice was made compared to now.
1335 return _('about a minute ago');
1336 } else if ($diff < 3300) {
1337 $minutes = round($diff/60);
1338 // TRANS: Used in notices to indicate when the notice was made compared to now.
1339 return sprintf( _m('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1340 } else if ($diff < 5400) {
1341 // TRANS: Used in notices to indicate when the notice was made compared to now.
1342 return _('about an hour ago');
1343 } else if ($diff < 22 * 3600) {
1344 $hours = round($diff/3600);
1345 // TRANS: Used in notices to indicate when the notice was made compared to now.
1346 return sprintf( _m('about one hour ago', 'about %d hours ago', $hours), $hours);
1347 } else if ($diff < 37 * 3600) {
1348 // TRANS: Used in notices to indicate when the notice was made compared to now.
1349 return _('about a day ago');
1350 } else if ($diff < 24 * 24 * 3600) {
1351 $days = round($diff/(24*3600));
1352 // TRANS: Used in notices to indicate when the notice was made compared to now.
1353 return sprintf( _m('about one day ago', 'about %d days ago', $days), $days);
1354 } else if ($diff < 46 * 24 * 3600) {
1355 // TRANS: Used in notices to indicate when the notice was made compared to now.
1356 return _('about a month ago');
1357 } else if ($diff < 330 * 24 * 3600) {
1358 $months = round($diff/(30*24*3600));
1359 // TRANS: Used in notices to indicate when the notice was made compared to now.
1360 return sprintf( _m('about one month ago', 'about %d months ago',$months), $months);
1361 } else if ($diff < 480 * 24 * 3600) {
1362 // TRANS: Used in notices to indicate when the notice was made compared to now.
1363 return _('about a year ago');
1365 return common_exact_date($dt);
1369 function common_exact_date($dt)
1375 $_utc = new DateTimeZone('UTC');
1376 $_siteTz = new DateTimeZone(common_timezone());
1379 $dateStr = date('d F Y H:i:s', strtotime($dt));
1380 $d = new DateTime($dateStr, $_utc);
1381 $d->setTimezone($_siteTz);
1382 return $d->format(DATE_RFC850);
1385 function common_date_w3dtf($dt)
1387 $dateStr = date('d F Y H:i:s', strtotime($dt));
1388 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1389 $d->setTimezone(new DateTimeZone(common_timezone()));
1390 return $d->format(DATE_W3C);
1393 function common_date_rfc2822($dt)
1395 $dateStr = date('d F Y H:i:s', strtotime($dt));
1396 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1397 $d->setTimezone(new DateTimeZone(common_timezone()));
1398 return $d->format('r');
1401 function common_date_iso8601($dt)
1403 $dateStr = date('d F Y H:i:s', strtotime($dt));
1404 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1405 $d->setTimezone(new DateTimeZone(common_timezone()));
1406 return $d->format('c');
1409 function common_sql_now()
1411 return common_sql_date(time());
1414 function common_sql_date($datetime)
1416 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1420 * Return an SQL fragment to calculate an age-based weight from a given
1421 * timestamp or datetime column.
1423 * @param string $column name of field we're comparing against current time
1424 * @param integer $dropoff divisor for age in seconds before exponentiation
1425 * @return string SQL fragment
1427 function common_sql_weight($column, $dropoff)
1429 if (common_config('db', 'type') == 'pgsql') {
1430 // PostgreSQL doesn't support timestampdiff function.
1431 // @fixme will this use the right time zone?
1432 // @fixme does this handle cross-year subtraction correctly?
1433 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1435 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1439 function common_redirect($url, $code=307)
1441 static $status = array(301 => "Moved Permanently",
1444 307 => "Temporary Redirect");
1446 header('HTTP/1.1 '.$code.' '.$status[$code]);
1447 header("Location: $url");
1449 $xo = new XMLOutputter();
1451 '-//W3C//DTD XHTML 1.0 Strict//EN',
1452 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1453 $xo->element('a', array('href' => $url), $url);
1458 // Stick the notice on the queue
1460 function common_enqueue_notice($notice)
1462 static $localTransports = array('omb',
1465 $transports = array();
1466 if (common_config('sms', 'enabled')) {
1467 $transports[] = 'sms';
1469 if (Event::hasHandler('HandleQueuedNotice')) {
1470 $transports[] = 'plugin';
1473 // We can skip these for gatewayed notices.
1474 if ($notice->isLocal()) {
1475 $transports = array_merge($transports, $localTransports);
1478 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1480 $qm = QueueManager::get();
1482 foreach ($transports as $transport)
1484 $qm->enqueue($notice, $transport);
1487 Event::handle('EndEnqueueNotice', array($notice, $transports));
1494 * Broadcast profile updates to OMB and other remote subscribers.
1496 * Since this may be slow with a lot of subscribers or bad remote sites,
1497 * this is run through the background queues if possible.
1499 function common_broadcast_profile(Profile $profile)
1501 $qm = QueueManager::get();
1502 $qm->enqueue($profile, "profile");
1506 function common_profile_url($nickname)
1508 return common_local_url('showstream', array('nickname' => $nickname),
1513 * Should make up a reasonable root URL
1515 function common_root_url($ssl=false)
1517 $url = common_path('', $ssl, false);
1518 $i = strpos($url, '?');
1520 $url = substr($url, 0, $i);
1526 * returns $bytes bytes of random data as a hexadecimal string
1527 * "good" here is a goal and not a guarantee
1529 function common_good_rand($bytes)
1531 // XXX: use random.org...?
1532 if (@file_exists('/dev/urandom')) {
1533 return common_urandom($bytes);
1534 } else { // FIXME: this is probably not good enough
1535 return common_mtrand($bytes);
1539 function common_urandom($bytes)
1541 $h = fopen('/dev/urandom', 'rb');
1543 $src = fread($h, $bytes);
1546 for ($i = 0; $i < $bytes; $i++) {
1547 $enc .= sprintf("%02x", (ord($src[$i])));
1552 function common_mtrand($bytes)
1555 for ($i = 0; $i < $bytes; $i++) {
1556 $enc .= sprintf("%02x", mt_rand(0, 255));
1562 * Record the given URL as the return destination for a future
1563 * form submission, to be read by common_get_returnto().
1565 * @param string $url
1567 * @fixme as a session-global setting, this can allow multiple forms
1568 * to conflict and overwrite each others' returnto destinations if
1569 * the user has multiple tabs or windows open.
1571 * Should refactor to index with a token or otherwise only pass the
1572 * data along its intended path.
1574 function common_set_returnto($url)
1576 common_ensure_session();
1577 $_SESSION['returnto'] = $url;
1581 * Fetch a return-destination URL previously recorded by
1582 * common_set_returnto().
1584 * @return mixed URL string or null
1586 * @fixme as a session-global setting, this can allow multiple forms
1587 * to conflict and overwrite each others' returnto destinations if
1588 * the user has multiple tabs or windows open.
1590 * Should refactor to index with a token or otherwise only pass the
1591 * data along its intended path.
1593 function common_get_returnto()
1595 common_ensure_session();
1596 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1599 function common_timestamp()
1601 return date('YmdHis');
1604 function common_ensure_syslog()
1606 static $initialized = false;
1607 if (!$initialized) {
1608 openlog(common_config('syslog', 'appname'), 0,
1609 common_config('syslog', 'facility'));
1610 $initialized = true;
1614 function common_log_line($priority, $msg)
1616 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1617 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1618 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1621 function common_request_id()
1624 $server = common_config('site', 'server');
1625 if (php_sapi_name() == 'cli') {
1626 $script = basename($_SERVER['PHP_SELF']);
1627 return "$server:$script:$pid";
1629 static $req_id = null;
1630 if (!isset($req_id)) {
1631 $req_id = substr(md5(mt_rand()), 0, 8);
1633 if (isset($_SERVER['REQUEST_URI'])) {
1634 $url = $_SERVER['REQUEST_URI'];
1636 $method = $_SERVER['REQUEST_METHOD'];
1637 return "$server:$pid.$req_id $method $url";
1641 function common_log($priority, $msg, $filename=null)
1643 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1644 $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1645 $msg = '[' . common_request_id() . '] ' . $msg;
1646 $logfile = common_config('site', 'logfile');
1648 $log = fopen($logfile, "a");
1650 $output = common_log_line($priority, $msg);
1651 fwrite($log, $output);
1655 common_ensure_syslog();
1656 syslog($priority, $msg);
1658 Event::handle('EndLog', array($priority, $msg, $filename));
1662 function common_debug($msg, $filename=null)
1665 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1667 common_log(LOG_DEBUG, $msg);
1671 function common_log_db_error(&$object, $verb, $filename=null)
1673 $objstr = common_log_objstring($object);
1674 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1675 if (is_object($last_error)) {
1676 $msg = $last_error->message;
1678 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1680 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1683 function common_log_objstring(&$object)
1685 if (is_null($object)) {
1688 if (!($object instanceof DB_DataObject)) {
1691 $arr = $object->toArray();
1693 foreach ($arr as $k => $v) {
1694 if (is_object($v)) {
1695 $fields[] = "$k='".get_class($v)."'";
1697 $fields[] = "$k='$v'";
1700 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1704 function common_valid_http_url($url)
1706 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1709 function common_valid_tag($tag)
1711 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1712 return (Validate::email($matches[1]) ||
1713 preg_match('/^([\w-\.]+)$/', $matches[1]));
1719 * Determine if given domain or address literal is valid
1720 * eg for use in JIDs and URLs. Does not check if the domain
1723 * @param string $domain
1724 * @return boolean valid or not
1726 function common_valid_domain($domain)
1728 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1729 $ipv4 = "(?:$octet(?:\.$octet){3})";
1730 if (preg_match("/^$ipv4$/u", $domain)) return true;
1732 $group = "(?:[0-9a-f]{1,4})";
1733 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1735 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1736 $before = explode(":", $matches[1]);
1737 $zeroes = $matches[2];
1738 $after = explode(":", $matches[3]);
1746 $explicit = count($before) + count($after);
1747 if ($explicit < $min || $explicit > $max) {
1754 require_once "Net/IDNA.php";
1755 $idn = Net_IDNA::getInstance();
1756 $domain = $idn->encode($domain);
1757 } catch (Exception $e) {
1761 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1762 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1764 return preg_match("/^$fqdn$/ui", $domain);
1767 /* Following functions are copied from MediaWiki GlobalFunctions.php
1768 * and written by Evan Prodromou. */
1770 function common_accept_to_prefs($accept, $def = '*/*')
1772 // No arg means accept anything (per HTTP spec)
1774 return array($def => 1);
1779 $parts = explode(',', $accept);
1781 foreach($parts as $part) {
1782 // FIXME: doesn't deal with params like 'text/html; level=1'
1783 @list($value, $qpart) = explode(';', trim($part));
1785 if(!isset($qpart)) {
1787 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1788 $prefs[$value] = $match[1];
1795 function common_mime_type_match($type, $avail)
1797 if(array_key_exists($type, $avail)) {
1800 $parts = explode('/', $type);
1801 if(array_key_exists($parts[0] . '/*', $avail)) {
1802 return $parts[0] . '/*';
1803 } elseif(array_key_exists('*/*', $avail)) {
1811 function common_negotiate_type($cprefs, $sprefs)
1815 foreach(array_keys($sprefs) as $type) {
1816 $parts = explode('/', $type);
1817 if($parts[1] != '*') {
1818 $ckey = common_mime_type_match($type, $cprefs);
1820 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1825 foreach(array_keys($cprefs) as $type) {
1826 $parts = explode('/', $type);
1827 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1828 $skey = common_mime_type_match($type, $sprefs);
1830 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1836 $besttype = 'text/html';
1838 foreach(array_keys($combine) as $type) {
1839 if($combine[$type] > $bestq) {
1841 $bestq = $combine[$type];
1845 if ('text/html' === $besttype) {
1846 return "text/html; charset=utf-8";
1851 function common_config($main, $sub)
1854 return (array_key_exists($main, $config) &&
1855 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1859 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1860 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1862 * @param array $from
1865 function common_copy_args($from)
1868 $strip = get_magic_quotes_gpc();
1869 foreach ($from as $k => $v) {
1871 $to[$k] = common_copy_args($v);
1874 $v = stripslashes($v);
1876 $to[$k] = strval(common_validate_utf8($v));
1883 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1884 * This is used before handing a request off to OAuthRequest::from_request.
1885 * @fixme Doesn't consider vars other than _POST and _GET?
1886 * @fixme Can't be undone and could corrupt data if run twice.
1888 function common_remove_magic_from_request()
1890 if(get_magic_quotes_gpc()) {
1891 $_POST=array_map('stripslashes',$_POST);
1892 $_GET=array_map('stripslashes',$_GET);
1896 function common_user_uri(&$user)
1898 return common_local_url('userbyid', array('id' => $user->id),
1902 function common_notice_uri(&$notice)
1904 return common_local_url('shownotice',
1905 array('notice' => $notice->id),
1909 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1911 function common_confirmation_code($bits)
1913 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1914 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1915 $chars = ceil($bits/5);
1917 for ($i = 0; $i < $chars; $i++) {
1918 // XXX: convert to string and back
1919 $num = hexdec(common_good_rand(1));
1920 // XXX: randomness is too precious to throw away almost
1921 // 40% of the bits we get!
1922 $code .= $codechars[$num%32];
1927 // convert markup to HTML
1929 function common_markup_to_html($c)
1931 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1932 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1933 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1934 return Markdown($c);
1937 function common_profile_uri($profile)
1942 $user = User::staticGet($profile->id);
1947 $remote = Remote_profile::staticGet($profile->id);
1949 return $remote->uri;
1951 // XXX: this is a very bad profile!
1955 function common_canonical_sms($sms)
1958 preg_replace('/\D/', '', $sms);
1962 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1967 case E_COMPILE_ERROR:
1971 case E_RECOVERABLE_ERROR:
1972 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1977 case E_COMPILE_WARNING:
1978 case E_CORE_WARNING:
1979 case E_USER_WARNING:
1980 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1985 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1990 case E_USER_DEPRECATED:
1991 // XXX: config variable to log this stuff, too
1995 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
2000 // FIXME: show error page if we're on the Web
2001 /* Don't execute PHP internal error handler */
2005 function common_session_token()
2007 common_ensure_session();
2008 if (!array_key_exists('token', $_SESSION)) {
2009 $_SESSION['token'] = common_good_rand(64);
2011 return $_SESSION['token'];
2014 function common_license_terms($uri)
2016 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2017 return explode('-',$matches[1]);
2022 function common_compatible_license($from, $to)
2024 $from_terms = common_license_terms($from);
2025 // public domain and cc-by are compatible with everything
2026 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2029 $to_terms = common_license_terms($to);
2030 // sa is compatible across versions. IANAL
2031 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2032 return count(array_diff($from_terms, $to_terms)) == 0;
2034 // XXX: better compatibility check needed here!
2035 // Should at least normalise URIs
2036 return ($from == $to);
2040 * returns a quoted table name, if required according to config
2042 function common_database_tablename($tablename)
2044 if(common_config('db','quote_identifiers')) {
2045 $tablename = '"'. $tablename .'"';
2047 //table prefixes could be added here later
2052 * Shorten a URL with the current user's configured shortening service,
2053 * or ur1.ca if configured, or not at all if no shortening is set up.
2055 * @param string $long_url original URL
2056 * @param User $user to specify a particular user's options
2057 * @param boolean $force Force shortening (used when notice is too long)
2058 * @return string may return the original URL if shortening failed
2060 * @fixme provide a way to specify a particular shortener
2062 function common_shorten_url($long_url, User $user=null, $force = false)
2064 $long_url = trim($long_url);
2066 $user = common_current_user();
2068 $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
2070 // $force forces shortening even if it's not strictly needed
2071 // I doubt URL shortening is ever 'strictly' needed. - ESP
2073 if (mb_strlen($long_url) < $maxUrlLength && !$force) {
2077 $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
2079 if (Event::handle('StartShortenUrl',
2080 array($long_url, $shortenerName, &$shortenedUrl))) {
2081 if ($shortenerName == 'internal') {
2082 $f = File::processNew($long_url);
2086 $shortenedUrl = common_local_url('redirecturl',
2087 array('id' => $f->id));
2088 return $shortenedUrl;
2094 //URL was shortened, so return the result
2095 return trim($shortenedUrl);
2100 * @return mixed array($proxy, $ip) for web requests; proxy may be null
2101 * null if not a web request
2103 * @fixme X-Forwarded-For can be chained by multiple proxies;
2104 we should parse the list and provide a cleaner array
2105 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2106 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2107 * use function to get exact request headers from Apache if possible.
2109 function common_client_ip()
2111 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2115 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2116 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2117 $proxy = $_SERVER['HTTP_CLIENT_IP'];
2119 $proxy = $_SERVER['REMOTE_ADDR'];
2121 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2124 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2125 $ip = $_SERVER['HTTP_CLIENT_IP'];
2127 $ip = $_SERVER['REMOTE_ADDR'];
2131 return array($proxy, $ip);
2134 function common_url_to_nickname($url)
2136 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2138 $parts = parse_url($url);
2140 // If any of these parts exist, this won't work
2142 foreach ($bad as $badpart) {
2143 if (array_key_exists($badpart, $parts)) {
2148 // We just have host and/or path
2150 // If it's just a host...
2151 if (array_key_exists('host', $parts) &&
2152 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2154 $hostparts = explode('.', $parts['host']);
2156 // Try to catch common idiom of nickname.service.tld
2158 if ((count($hostparts) > 2) &&
2159 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2160 (strcmp($hostparts[0], 'www') != 0))
2162 return common_nicknamize($hostparts[0]);
2164 // Do the whole hostname
2165 return common_nicknamize($parts['host']);
2168 if (array_key_exists('path', $parts)) {
2169 // Strip starting, ending slashes
2170 $path = preg_replace('@/$@', '', $parts['path']);
2171 $path = preg_replace('@^/@', '', $path);
2172 $path = basename($path);
2174 // Hack for MediaWiki user pages, in the form:
2175 // http://example.com/wiki/User:Myname
2176 // ('User' may be localized.)
2177 if (strpos($path, ':')) {
2178 $parts = array_filter(explode(':', $path));
2179 $path = $parts[count($parts) - 1];
2183 return common_nicknamize($path);
2191 function common_nicknamize($str)
2193 $str = preg_replace('/\W/', '', $str);
2194 return strtolower($str);
2197 function common_perf_counter($key, $val=null)
2199 global $_perfCounters;
2200 if (isset($_perfCounters)) {
2201 if (common_config('site', 'logperf')) {
2202 if (array_key_exists($key, $_perfCounters)) {
2203 $_perfCounters[$key][] = $val;
2205 $_perfCounters[$key] = array($val);
2207 if (common_config('site', 'logperf_detail')) {
2208 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2214 function common_log_perf_counters()
2216 if (common_config('site', 'logperf')) {
2217 global $_startTime, $_perfCounters;
2219 if (isset($_startTime)) {
2220 $endTime = microtime(true);
2221 $diff = round(($endTime - $_startTime) * 1000);
2222 common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2224 $counters = $_perfCounters;
2226 foreach ($counters as $key => $values) {
2227 $count = count($values);
2228 $unique = count(array_unique($values));
2229 common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");