3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, user, files) */
23 * Show a server error.
25 function common_server_error($msg, $code=500)
27 $err = new ServerErrorAction($msg, $code);
34 function common_user_error($msg, $code=400)
36 $err = new ClientErrorAction($msg, $code);
41 * This should only be used at setup; processes switching languages
42 * to send text to other users should use common_switch_locale().
44 * @param string $language Locale language code (optional; empty uses
45 * current user's preference or site default)
46 * @return mixed success
48 function common_init_locale($language=null)
51 $language = common_language();
53 putenv('LANGUAGE='.$language);
54 putenv('LANG='.$language);
55 $ok = setlocale(LC_ALL, $language . ".utf8",
65 * Initialize locale and charset settings and gettext with our message catalog,
66 * using the current user's language preference or the site default.
68 * This should generally only be run at framework initialization; code switching
69 * languages at runtime should call common_switch_language().
73 function common_init_language()
75 mb_internal_encoding('UTF-8');
77 // Note that this setlocale() call may "fail" but this is harmless;
78 // gettext will still select the right language.
79 $language = common_language();
80 $locale_set = common_init_locale($language);
83 // The requested locale doesn't exist on the system.
85 // gettext seems very picky... We first need to setlocale()
86 // to a locale which _does_ exist on the system, and _then_
87 // we can set in another locale that may not be set up
88 // (say, ga_ES for Galego/Galician) it seems to take it.
90 // For some reason C and POSIX which are guaranteed to work
91 // don't do the job. en_US.UTF-8 should be there most of the
92 // time, but not guaranteed.
93 $ok = common_init_locale("en_US");
94 if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
95 // Try to find a complete, working locale on Unix/Linux...
96 // @fixme shelling out feels awfully inefficient
97 // but I don't think there's a more standard way.
99 foreach (explode("\n", $all) as $locale) {
100 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
101 $ok = setlocale(LC_ALL, $locale);
109 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
111 $locale_set = common_init_locale($language);
114 common_init_gettext();
120 function common_init_gettext()
122 setlocale(LC_CTYPE, 'C');
123 // So we do not have to make people install the gettext locales
124 $path = common_config('site','locale_path');
125 bindtextdomain("statusnet", $path);
126 bind_textdomain_codeset("statusnet", "UTF-8");
127 textdomain("statusnet");
131 * Switch locale during runtime, and poke gettext until it cries uncle.
132 * Otherwise, sometimes it doesn't actually switch away from the old language.
134 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
136 function common_switch_locale($language=null)
138 common_init_locale($language);
140 setlocale(LC_CTYPE, 'C');
141 // So we do not have to make people install the gettext locales
142 $path = common_config('site','locale_path');
143 bindtextdomain("statusnet", $path);
144 bind_textdomain_codeset("statusnet", "UTF-8");
145 textdomain("statusnet");
148 function common_timezone()
150 if (common_logged_in()) {
151 $user = common_current_user();
152 if ($user->timezone) {
153 return $user->timezone;
157 return common_config('site', 'timezone');
160 function common_language()
162 // If there is a user logged in and they've set a language preference
163 // then return that one...
164 if (_have_config() && common_logged_in()) {
165 $user = common_current_user();
166 $user_language = $user->language;
168 if ($user->language) {
169 // Validate -- we don't want to end up with a bogus code
170 // left over from some old junk.
171 foreach (common_config('site', 'languages') as $code => $info) {
172 if ($info['lang'] == $user_language) {
173 return $user_language;
179 // Otherwise, find the best match for the languages requested by the
181 if (common_config('site', 'langdetect')) {
182 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
183 if (!empty($httplang)) {
184 $language = client_prefered_language($httplang);
190 // Finally, if none of the above worked, use the site's default...
191 return common_config('site', 'language');
195 * Salted, hashed passwords are stored in the DB.
197 function common_munge_password($password, $id)
199 if (is_object($id) || is_object($password)) {
200 $e = new Exception();
201 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
202 str_replace("\n", " ", $e->getTraceAsString()));
204 return md5($password . $id);
208 * Check if a username exists and has matching password.
210 function common_check_user($nickname, $password)
212 // empty nickname always unacceptable
213 if (empty($nickname)) {
217 $authenticatedUser = false;
219 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
220 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
222 if (!empty($password)) { // never allow login with blank password
223 if (0 == strcmp(common_munge_password($password, $user->id),
225 //internal checking passed
226 $authenticatedUser = $user;
230 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
233 return $authenticatedUser;
237 * Is the current user logged in?
239 function common_logged_in()
241 return (!is_null(common_current_user()));
244 function common_have_session()
246 return (0 != strcmp(session_id(), ''));
249 function common_ensure_session()
252 if (array_key_exists(session_name(), $_COOKIE)) {
253 $c = $_COOKIE[session_name()];
255 if (!common_have_session()) {
256 if (common_config('sessions', 'handle')) {
257 Session::setSaveHandler();
259 if (array_key_exists(session_name(), $_GET)) {
260 $id = $_GET[session_name()];
261 } else if (array_key_exists(session_name(), $_COOKIE)) {
262 $id = $_COOKIE[session_name()];
268 if (!isset($_SESSION['started'])) {
269 $_SESSION['started'] = time();
271 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
272 ' is set but started value is null');
278 // Three kinds of arguments:
283 // Initialize to false; set to null if none found
286 function common_set_user($user)
290 if (is_null($user) && common_have_session()) {
292 unset($_SESSION['userid']);
294 } else if (is_string($user)) {
296 $user = User::staticGet('nickname', $nickname);
297 } else if (!($user instanceof User)) {
302 if (Event::handle('StartSetUser', array(&$user))) {
304 if (!$user->hasRight(Right::WEBLOGIN)) {
305 throw new AuthorizationException(_('Not allowed to log in.'));
307 common_ensure_session();
308 $_SESSION['userid'] = $user->id;
310 Event::handle('EndSetUser', array($user));
318 function common_set_cookie($key, $value, $expiration=0)
320 $path = common_config('site', 'path');
321 $server = common_config('site', 'server');
323 if ($path && ($path != '/')) {
324 $cookiepath = '/' . $path . '/';
328 return setcookie($key,
333 common_config('site', 'ssl')=='always');
336 define('REMEMBERME', 'rememberme');
337 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
339 function common_rememberme($user=null)
342 $user = common_current_user();
348 $rm = new Remember_me();
350 $rm->code = common_good_rand(16);
351 $rm->user_id = $user->id;
353 // Wrap the insert in some good ol' fashioned transaction code
357 $result = $rm->insert();
360 common_log_db_error($rm, 'INSERT', __FILE__);
364 $rm->query('COMMIT');
366 $cookieval = $rm->user_id . ':' . $rm->code;
368 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
370 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
375 function common_remembered_user()
379 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
385 list($id, $code) = explode(':', $packed);
387 if (!$id || !$code) {
388 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
393 $rm = Remember_me::staticGet($code);
396 common_log(LOG_WARNING, 'No such remember code: ' . $code);
401 if ($rm->user_id != $id) {
402 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
407 $user = User::staticGet($rm->user_id);
410 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
416 $result = $rm->delete();
419 common_log_db_error($rm, 'DELETE', __FILE__);
420 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
425 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
427 common_set_user($user);
428 common_real_login(false);
430 // We issue a new cookie, so they can log in
431 // automatically again after this session
433 common_rememberme($user);
439 * must be called with a valid user!
441 function common_forgetme()
443 common_set_cookie(REMEMBERME, '', 0);
447 * Who is the current user?
449 function common_current_user()
453 if (!_have_config()) {
457 if ($_cur === false) {
459 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
460 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
461 common_ensure_session();
462 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
464 $user = User::staticGet($id);
472 // that didn't work; try to remember; will init $_cur to null on failure
473 $_cur = common_remembered_user();
476 // XXX: Is this necessary?
477 $_SESSION['userid'] = $_cur->id;
485 * Logins that are 'remembered' aren't 'real' -- they're subject to
486 * cookie-stealing. So, we don't let them do certain things. New reg,
487 * OpenID, and password logins _are_ real.
489 function common_real_login($real=true)
491 common_ensure_session();
492 $_SESSION['real_login'] = $real;
495 function common_is_real_login()
497 return common_logged_in() && $_SESSION['real_login'];
501 * Get a hash portion for HTTP caching Etags and such including
502 * info on the current user's session. If login/logout state changes,
503 * or we've changed accounts, or we've renamed the current user,
504 * we'll get a new hash value.
506 * This should not be considered secure information.
508 * @param User $user (optional; uses common_current_user() if left out)
511 function common_user_cache_hash($user=false)
513 if ($user === false) {
514 $user = common_current_user();
517 return crc32($user->id . ':' . $user->nickname);
524 * get canonical version of nickname for comparison
526 * @param string $nickname
529 * @throws NicknameException on invalid input
530 * @deprecated call Nickname::normalize() directly.
532 function common_canonical_nickname($nickname)
534 return Nickname::normalize($nickname);
538 * get canonical version of email for comparison
540 * @fixme actually normalize
541 * @fixme reject invalid input
543 * @param string $email
546 function common_canonical_email($email)
548 // XXX: canonicalize UTF-8
549 // XXX: lcase the domain part
554 * Partial notice markup rendering step: build links to !group references.
556 * @param string $text partially rendered HTML
557 * @param Notice $notice in whose context we're working
558 * @return string partially rendered HTML
560 function common_render_content($text, $notice)
562 $r = common_render_text($text);
563 $id = $notice->profile_id;
564 $r = common_linkify_mentions($r, $notice);
565 $r = preg_replace('/(^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/e',
566 "'\\1!'.common_group_link($id, '\\2')", $r);
571 * Finds @-mentions within the partially-rendered text section and
572 * turns them into live links.
574 * Should generally not be called except from common_render_content().
576 * @param string $text partially-rendered HTML
577 * @param Notice $notice in-progress or complete Notice object for context
578 * @return string partially-rendered HTML
580 function common_linkify_mentions($text, $notice)
582 $mentions = common_find_mentions($text, $notice);
584 // We need to go through in reverse order by position,
585 // so our positions stay valid despite our fudging with the
590 foreach ($mentions as $mention)
592 $points[$mention['position']] = $mention;
597 foreach ($points as $position => $mention) {
599 $linkText = common_linkify_mention($mention);
601 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
607 function common_linkify_mention($mention)
611 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
613 $xs = new XMLStringer(false);
615 $attrs = array('href' => $mention['url'],
618 if (!empty($mention['title'])) {
619 $attrs['title'] = $mention['title'];
622 $xs->elementStart('span', 'vcard');
623 $xs->elementStart('a', $attrs);
624 $xs->element('span', 'fn nickname', $mention['text']);
625 $xs->elementEnd('a');
626 $xs->elementEnd('span');
628 $output = $xs->getString();
630 Event::handle('EndLinkifyMention', array($mention, &$output));
637 * Find @-mentions in the given text, using the given notice object as context.
638 * References will be resolved with common_relative_profile() against the user
639 * who posted the notice.
641 * Note the return data format is internal, to be used for building links and
642 * such. Should not be used directly; rather, call common_linkify_mentions().
644 * @param string $text
645 * @param Notice $notice notice in whose context we're building links
651 function common_find_mentions($text, $notice)
655 $sender = Profile::staticGet('id', $notice->profile_id);
657 if (empty($sender)) {
661 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
662 // Get the context of the original notice, if any
663 $originalAuthor = null;
664 $originalNotice = null;
665 $originalMentions = array();
669 if (!empty($notice) && !empty($notice->reply_to)) {
670 $originalNotice = Notice::staticGet('id', $notice->reply_to);
671 if (!empty($originalNotice)) {
672 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
674 $ids = $originalNotice->getReplies();
676 foreach ($ids as $id) {
677 $repliedTo = Profile::staticGet('id', $id);
678 if (!empty($repliedTo)) {
679 $originalMentions[$repliedTo->nickname] = $repliedTo;
685 $matches = common_find_mentions_raw($text);
687 foreach ($matches as $match) {
689 $nickname = Nickname::normalize($match[0]);
690 } catch (NicknameException $e) {
691 // Bogus match? Drop it.
695 // Try to get a profile for this nickname.
696 // Start with conversation context, then go to
699 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
700 $mentioned = $originalAuthor;
701 } else if (!empty($originalMentions) &&
702 array_key_exists($nickname, $originalMentions)) {
703 $mentioned = $originalMentions[$nickname];
705 $mentioned = common_relative_profile($sender, $nickname);
708 if (!empty($mentioned)) {
709 $user = User::staticGet('id', $mentioned->id);
712 $url = common_local_url('userbyid', array('id' => $user->id));
714 $url = $mentioned->profileurl;
717 $mention = array('mentioned' => array($mentioned),
719 'position' => $match[1],
722 if (!empty($mentioned->fullname)) {
723 $mention['title'] = $mentioned->fullname;
726 $mentions[] = $mention;
730 // @#tag => mention of all subscriptions tagged 'tag'
732 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
735 PREG_OFFSET_CAPTURE);
737 foreach ($hmatches[1] as $hmatch) {
739 $tag = common_canonical_tag($hmatch[0]);
741 $tagged = Profile_tag::getTagged($sender->id, $tag);
743 $url = common_local_url('subscriptions',
744 array('nickname' => $sender->nickname,
747 $mentions[] = array('mentioned' => $tagged,
748 'text' => $hmatch[0],
749 'position' => $hmatch[1],
753 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
760 * Does the actual regex pulls to find @-mentions in text.
761 * Should generally not be called directly; for use in common_find_mentions.
763 * @param string $text
764 * @return array of PCRE match arrays
766 function common_find_mentions_raw($text)
769 preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
772 PREG_OFFSET_CAPTURE);
774 $atmatches = array();
775 preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
778 PREG_OFFSET_CAPTURE);
780 $matches = array_merge($tmatches[1], $atmatches[1]);
784 function common_render_text($text)
786 $r = htmlspecialchars($text);
788 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
789 $r = common_replace_urls_callback($r, 'common_linkify');
790 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/ue', "'\\1#'.common_tag_link('\\2')", $r);
796 * Find links in the given text and pass them to the given callback function.
798 * @param string $text
799 * @param function($text, $arg) $callback: return replacement text
800 * @param mixed $arg: optional argument will be passed on to the callback
802 function common_replace_urls_callback($text, $callback, $arg = null) {
803 // Start off with a regex
805 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
808 '(?:'. //Known protocols
810 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
812 '(?:(?:mailto|aim|tel|xmpp):)'.
814 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
817 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
819 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
823 '|(?:(?: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
825 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
827 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
828 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
829 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
830 '(?: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)'.
834 '(?:\:\d+)?'. //:port
835 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
836 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
837 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
838 ')(?<![\?\.\,\#\,])'.
841 //preg_match_all($regex,$text,$matches);
843 return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
847 * Intermediate callback for common_replace_links(), helps resolve some
848 * ambiguous link forms before passing on to the final callback.
850 * @param array $matches
851 * @param callable $callback
852 * @param mixed $arg optional argument to pass on as second param to callback
857 function callback_helper($matches, $callback, $arg=null) {
859 $left = strpos($matches[0],$url);
860 $right = $left+strlen($url);
862 $groupSymbolSets=array(
880 $cannotEndWith=array('.','?',',','#');
884 foreach($groupSymbolSets as $groupSymbolSet){
885 if(substr($url,-1)==$groupSymbolSet['right']){
886 $group_left_count = substr_count($url,$groupSymbolSet['left']);
887 $group_right_count = substr_count($url,$groupSymbolSet['right']);
888 if($group_left_count<$group_right_count){
890 $url=substr($url,0,-1);
894 if(in_array(substr($url,-1),$cannotEndWith)){
896 $url=substr($url,0,-1);
898 }while($original_url!=$url);
900 $result = call_user_func_array($callback, array($url, $arg));
901 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
904 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
905 // lambda implementation in a separate file; PHP 5.2 won't parse it.
906 require_once INSTALLDIR . "/lib/curry.php";
908 function curry($fn) {
909 $args = func_get_args();
911 $id = uniqid('_partial');
912 $GLOBALS[$id] = array($fn, $args);
913 return create_function('',
914 '$args = func_get_args(); '.
915 'return call_user_func_array('.
916 '$GLOBALS["'.$id.'"][0],'.
919 '$GLOBALS["'.$id.'"][1]));');
923 function common_linkify($url) {
924 // It comes in special'd, so we unspecial it before passing to the stringifying
926 $url = htmlspecialchars_decode($url);
928 if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
929 //url is an email address without the mailto: protocol
930 $canon = "mailto:$url";
931 $longurl = "mailto:$url";
934 $canon = File_redirection::_canonUrl($url);
936 $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
937 if (is_array($longurl_data)) {
938 $longurl = $longurl_data['url'];
939 } elseif (is_string($longurl_data)) {
940 $longurl = $longurl_data;
942 // Unable to reach the server to verify contents, etc
943 // Just pass the link on through for now.
944 common_log(LOG_ERR, "Can't linkify url '$url'");
949 $attrs = array('href' => $canon, 'title' => $longurl);
951 $is_attachment = false;
952 $attachment_id = null;
955 // Check to see whether this is a known "attachment" URL.
957 $f = File::staticGet('url', $longurl);
960 if (common_config('attachments', 'process_links')) {
961 // XXX: this writes to the database. :<
962 $f = File::processNew($longurl);
967 if ($f->getEnclosure()) {
968 $is_attachment = true;
969 $attachment_id = $f->id;
971 $thumb = File_thumbnail::staticGet('file_id', $f->id);
972 if (!empty($thumb)) {
979 if ($is_attachment) {
980 $attrs['class'] = 'attachment';
982 $attrs['class'] = 'attachment thumbnail';
984 $attrs['id'] = "attachment-{$attachment_id}";
987 // Whether to nofollow
989 $nf = common_config('nofollow', 'external');
991 if ($nf == 'never') {
992 $attrs['rel'] = 'external';
994 $attrs['rel'] = 'nofollow external';
997 return XMLStringer::estring('a', $attrs, $url);
1001 * Find and shorten links in a given chunk of text if it's longer than the
1002 * configured notice content limit (or unconditionally).
1004 * Side effects: may save file and file_redirection records for referenced URLs.
1006 * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
1007 * user's options are used; otherwise the current web session user's setitngs
1008 * will be used or ur1.ca if there is no active web login.
1010 * @param string $text
1011 * @param boolean $always (optional)
1012 * @param User $user (optional)
1016 function common_shorten_links($text, $always = false, User $user=null)
1018 $maxLength = Notice::maxContent();
1019 if (!$always && ($maxLength == 0 || mb_strlen($text) <= $maxLength)) return $text;
1020 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
1024 * Very basic stripping of invalid UTF-8 input text.
1026 * @param string $str
1027 * @return mixed string or null if invalid input
1029 * @todo ideally we should drop bad chars, and maybe do some of the checks
1030 * from common_xml_safe_str. But we can't strip newlines, etc.
1031 * @todo Unicode normalization might also be useful, but not needed now.
1033 function common_validate_utf8($str)
1035 // preg_replace will return NULL on invalid UTF-8 input.
1037 // Note: empty regex //u also caused NULL return on some
1038 // production machines, but none of our test machines.
1040 // This should be replaced with a more reliable check.
1041 return preg_replace('/\x00/u', '', $str);
1045 * Make sure an arbitrary string is safe for output in XML as a single line.
1047 * @param string $str
1050 function common_xml_safe_str($str)
1052 // Replace common eol and extra whitespace input chars
1057 "\0", // null byte eos
1058 "\x0B" // vertical tab
1061 $replacement = array(
1062 ' ', // single space
1069 $str = str_replace($unWelcome, $replacement, $str);
1071 // Neutralize any additional control codes and UTF-16 surrogates
1072 // (Twitter uses '*')
1073 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1076 function common_tag_link($tag)
1078 $canonical = common_canonical_tag($tag);
1079 if (common_config('singleuser', 'enabled')) {
1080 // regular TagAction isn't set up in 1user mode
1081 $nickname = User::singleUserNickname();
1082 $url = common_local_url('showstream',
1083 array('nickname' => $nickname,
1084 'tag' => $canonical));
1086 $url = common_local_url('tag', array('tag' => $canonical));
1088 $xs = new XMLStringer();
1089 $xs->elementStart('span', 'tag');
1090 $xs->element('a', array('href' => $url,
1093 $xs->elementEnd('span');
1094 return $xs->getString();
1097 function common_canonical_tag($tag)
1099 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1100 return str_replace(array('-', '_', '.'), '', $tag);
1103 function common_valid_profile_tag($str)
1105 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1110 * @param <type> $sender_id
1111 * @param <type> $nickname
1115 function common_group_link($sender_id, $nickname)
1117 $sender = Profile::staticGet($sender_id);
1118 $group = User_group::getForNickname($nickname, $sender);
1119 if ($sender && $group && $sender->isMember($group)) {
1120 $attrs = array('href' => $group->permalink(),
1122 if (!empty($group->fullname)) {
1123 $attrs['title'] = $group->getFancyName();
1125 $xs = new XMLStringer();
1126 $xs->elementStart('span', 'vcard');
1127 $xs->elementStart('a', $attrs);
1128 $xs->element('span', 'fn nickname', $nickname);
1129 $xs->elementEnd('a');
1130 $xs->elementEnd('span');
1131 return $xs->getString();
1138 * Resolve an ambiguous profile nickname reference, checking in following order:
1139 * - profiles that $sender subscribes to
1140 * - profiles that subscribe to $sender
1141 * - local user profiles
1143 * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1144 * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1147 * @fixme validate input
1149 * @fixme fix or remove mystery third parameter
1150 * @fixme is $sender a User or Profile?
1152 * @param <type> $sender the user or profile in whose context we're looking
1153 * @param string $nickname validated nickname of
1154 * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1156 * @return Profile or null
1158 function common_relative_profile($sender, $nickname, $dt=null)
1160 // Will throw exception on invalid input.
1161 $nickname = Nickname::normalize($nickname);
1163 // Try to find profiles this profile is subscribed to that have this nickname
1164 $recipient = new Profile();
1165 // XXX: use a join instead of a subquery
1166 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1167 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1168 if ($recipient->find(true)) {
1169 // XXX: should probably differentiate between profiles with
1170 // the same name by date of most recent update
1173 // Try to find profiles that listen to this profile and that have this nickname
1174 $recipient = new Profile();
1175 // XXX: use a join instead of a subquery
1176 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1177 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1178 if ($recipient->find(true)) {
1179 // XXX: should probably differentiate between profiles with
1180 // the same name by date of most recent update
1183 // If this is a local user, try to find a local user with that nickname.
1184 $sender = User::staticGet($sender->id);
1186 $recipient_user = User::staticGet('nickname', $nickname);
1187 if ($recipient_user) {
1188 return $recipient_user->getProfile();
1191 // Otherwise, no links. @messages from local users to remote users,
1192 // or from remote users to other remote users, are just
1193 // outside our ability to make intelligent guesses about
1197 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1200 $path = $r->build($action, $args, $params, $fragment);
1202 $ssl = common_is_sensitive($action);
1204 if (common_config('site','fancy')) {
1205 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1207 if (mb_strpos($path, '/index.php') === 0) {
1208 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1210 $url = common_path('index.php'.$path, $ssl, $addSession);
1216 function common_is_sensitive($action)
1218 static $sensitive = array(
1223 'ApiOauthRequestToken',
1224 'ApiOauthAccessToken',
1225 'ApiOauthAuthorize',
1231 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1232 $ssl = in_array($action, $sensitive);
1238 function common_path($relative, $ssl=false, $addSession=true)
1240 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1242 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1243 || common_config('site', 'ssl') === 'always') {
1245 if (is_string(common_config('site', 'sslserver')) &&
1246 mb_strlen(common_config('site', 'sslserver')) > 0) {
1247 $serverpart = common_config('site', 'sslserver');
1248 } else if (common_config('site', 'server')) {
1249 $serverpart = common_config('site', 'server');
1251 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1255 if (common_config('site', 'server')) {
1256 $serverpart = common_config('site', 'server');
1258 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1263 $relative = common_inject_session($relative, $serverpart);
1266 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1269 function common_inject_session($url, $serverpart = null)
1271 if (common_have_session()) {
1273 if (empty($serverpart)) {
1274 $serverpart = parse_url($url, PHP_URL_HOST);
1277 $currentServer = $_SERVER['HTTP_HOST'];
1279 // Are we pointing to another server (like an SSL server?)
1281 if (!empty($currentServer) &&
1282 0 != strcasecmp($currentServer, $serverpart)) {
1283 // Pass the session ID as a GET parameter
1284 $sesspart = session_name() . '=' . session_id();
1285 $i = strpos($url, '?');
1286 if ($i === false) { // no GET params, just append
1287 $url .= '?' . $sesspart;
1289 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1297 function common_date_string($dt)
1299 // XXX: do some sexy date formatting
1300 // return date(DATE_RFC822, $dt);
1301 $t = strtotime($dt);
1305 if ($now < $t) { // that shouldn't happen!
1306 return common_exact_date($dt);
1307 } else if ($diff < 60) {
1308 // TRANS: Used in notices to indicate when the notice was made compared to now.
1309 return _('a few seconds ago');
1310 } else if ($diff < 92) {
1311 // TRANS: Used in notices to indicate when the notice was made compared to now.
1312 return _('about a minute ago');
1313 } else if ($diff < 3300) {
1314 $minutes = round($diff/60);
1315 // TRANS: Used in notices to indicate when the notice was made compared to now.
1316 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1317 } else if ($diff < 5400) {
1318 // TRANS: Used in notices to indicate when the notice was made compared to now.
1319 return _('about an hour ago');
1320 } else if ($diff < 22 * 3600) {
1321 $hours = round($diff/3600);
1322 // TRANS: Used in notices to indicate when the notice was made compared to now.
1323 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1324 } else if ($diff < 37 * 3600) {
1325 // TRANS: Used in notices to indicate when the notice was made compared to now.
1326 return _('about a day ago');
1327 } else if ($diff < 24 * 24 * 3600) {
1328 $days = round($diff/(24*3600));
1329 // TRANS: Used in notices to indicate when the notice was made compared to now.
1330 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1331 } else if ($diff < 46 * 24 * 3600) {
1332 // TRANS: Used in notices to indicate when the notice was made compared to now.
1333 return _('about a month ago');
1334 } else if ($diff < 330 * 24 * 3600) {
1335 $months = round($diff/(30*24*3600));
1336 // TRANS: Used in notices to indicate when the notice was made compared to now.
1337 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1338 } else if ($diff < 480 * 24 * 3600) {
1339 // TRANS: Used in notices to indicate when the notice was made compared to now.
1340 return _('about a year ago');
1342 return common_exact_date($dt);
1346 function common_exact_date($dt)
1352 $_utc = new DateTimeZone('UTC');
1353 $_siteTz = new DateTimeZone(common_timezone());
1356 $dateStr = date('d F Y H:i:s', strtotime($dt));
1357 $d = new DateTime($dateStr, $_utc);
1358 $d->setTimezone($_siteTz);
1359 return $d->format(DATE_RFC850);
1362 function common_date_w3dtf($dt)
1364 $dateStr = date('d F Y H:i:s', strtotime($dt));
1365 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1366 $d->setTimezone(new DateTimeZone(common_timezone()));
1367 return $d->format(DATE_W3C);
1370 function common_date_rfc2822($dt)
1372 $dateStr = date('d F Y H:i:s', strtotime($dt));
1373 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1374 $d->setTimezone(new DateTimeZone(common_timezone()));
1375 return $d->format('r');
1378 function common_date_iso8601($dt)
1380 $dateStr = date('d F Y H:i:s', strtotime($dt));
1381 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1382 $d->setTimezone(new DateTimeZone(common_timezone()));
1383 return $d->format('c');
1386 function common_sql_now()
1388 return common_sql_date(time());
1391 function common_sql_date($datetime)
1393 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1397 * Return an SQL fragment to calculate an age-based weight from a given
1398 * timestamp or datetime column.
1400 * @param string $column name of field we're comparing against current time
1401 * @param integer $dropoff divisor for age in seconds before exponentiation
1402 * @return string SQL fragment
1404 function common_sql_weight($column, $dropoff)
1406 if (common_config('db', 'type') == 'pgsql') {
1407 // PostgreSQL doesn't support timestampdiff function.
1408 // @fixme will this use the right time zone?
1409 // @fixme does this handle cross-year subtraction correctly?
1410 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1412 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1416 function common_redirect($url, $code=307)
1418 static $status = array(301 => "Moved Permanently",
1421 307 => "Temporary Redirect");
1423 header('HTTP/1.1 '.$code.' '.$status[$code]);
1424 header("Location: $url");
1426 $xo = new XMLOutputter();
1428 '-//W3C//DTD XHTML 1.0 Strict//EN',
1429 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1430 $xo->element('a', array('href' => $url), $url);
1435 function common_broadcast_notice($notice, $remote=false)
1441 * Stick the notice on the queue.
1443 function common_enqueue_notice($notice)
1445 static $localTransports = array('omb',
1448 $transports = array();
1449 if (common_config('sms', 'enabled')) {
1450 $transports[] = 'sms';
1452 if (Event::hasHandler('HandleQueuedNotice')) {
1453 $transports[] = 'plugin';
1456 $xmpp = common_config('xmpp', 'enabled');
1459 $transports[] = 'jabber';
1462 // We can skip these for gatewayed notices.
1463 if ($notice->isLocal()) {
1464 $transports = array_merge($transports, $localTransports);
1466 $transports[] = 'public';
1470 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1472 $qm = QueueManager::get();
1474 foreach ($transports as $transport)
1476 $qm->enqueue($notice, $transport);
1479 Event::handle('EndEnqueueNotice', array($notice, $transports));
1486 * Broadcast profile updates to OMB and other remote subscribers.
1488 * Since this may be slow with a lot of subscribers or bad remote sites,
1489 * this is run through the background queues if possible.
1491 function common_broadcast_profile(Profile $profile)
1493 $qm = QueueManager::get();
1494 $qm->enqueue($profile, "profile");
1498 function common_profile_url($nickname)
1500 return common_local_url('showstream', array('nickname' => $nickname),
1505 * Should make up a reasonable root URL
1507 function common_root_url($ssl=false)
1509 $url = common_path('', $ssl, false);
1510 $i = strpos($url, '?');
1512 $url = substr($url, 0, $i);
1518 * returns $bytes bytes of random data as a hexadecimal string
1519 * "good" here is a goal and not a guarantee
1521 function common_good_rand($bytes)
1523 // XXX: use random.org...?
1524 if (@file_exists('/dev/urandom')) {
1525 return common_urandom($bytes);
1526 } else { // FIXME: this is probably not good enough
1527 return common_mtrand($bytes);
1531 function common_urandom($bytes)
1533 $h = fopen('/dev/urandom', 'rb');
1535 $src = fread($h, $bytes);
1538 for ($i = 0; $i < $bytes; $i++) {
1539 $enc .= sprintf("%02x", (ord($src[$i])));
1544 function common_mtrand($bytes)
1547 for ($i = 0; $i < $bytes; $i++) {
1548 $enc .= sprintf("%02x", mt_rand(0, 255));
1554 * Record the given URL as the return destination for a future
1555 * form submission, to be read by common_get_returnto().
1557 * @param string $url
1559 * @fixme as a session-global setting, this can allow multiple forms
1560 * to conflict and overwrite each others' returnto destinations if
1561 * the user has multiple tabs or windows open.
1563 * Should refactor to index with a token or otherwise only pass the
1564 * data along its intended path.
1566 function common_set_returnto($url)
1568 common_ensure_session();
1569 $_SESSION['returnto'] = $url;
1573 * Fetch a return-destination URL previously recorded by
1574 * common_set_returnto().
1576 * @return mixed URL string or null
1578 * @fixme as a session-global setting, this can allow multiple forms
1579 * to conflict and overwrite each others' returnto destinations if
1580 * the user has multiple tabs or windows open.
1582 * Should refactor to index with a token or otherwise only pass the
1583 * data along its intended path.
1585 function common_get_returnto()
1587 common_ensure_session();
1588 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1591 function common_timestamp()
1593 return date('YmdHis');
1596 function common_ensure_syslog()
1598 static $initialized = false;
1599 if (!$initialized) {
1600 openlog(common_config('syslog', 'appname'), 0,
1601 common_config('syslog', 'facility'));
1602 $initialized = true;
1606 function common_log_line($priority, $msg)
1608 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1609 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1610 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1613 function common_request_id()
1616 $server = common_config('site', 'server');
1617 if (php_sapi_name() == 'cli') {
1618 $script = basename($_SERVER['PHP_SELF']);
1619 return "$server:$script:$pid";
1621 static $req_id = null;
1622 if (!isset($req_id)) {
1623 $req_id = substr(md5(mt_rand()), 0, 8);
1625 if (isset($_SERVER['REQUEST_URI'])) {
1626 $url = $_SERVER['REQUEST_URI'];
1628 $method = $_SERVER['REQUEST_METHOD'];
1629 return "$server:$pid.$req_id $method $url";
1633 function common_log($priority, $msg, $filename=null)
1635 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1636 $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1637 $msg = '[' . common_request_id() . '] ' . $msg;
1638 $logfile = common_config('site', 'logfile');
1640 $log = fopen($logfile, "a");
1642 $output = common_log_line($priority, $msg);
1643 fwrite($log, $output);
1647 common_ensure_syslog();
1648 syslog($priority, $msg);
1650 Event::handle('EndLog', array($priority, $msg, $filename));
1654 function common_debug($msg, $filename=null)
1657 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1659 common_log(LOG_DEBUG, $msg);
1663 function common_log_db_error(&$object, $verb, $filename=null)
1665 $objstr = common_log_objstring($object);
1666 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1667 if (is_object($last_error)) {
1668 $msg = $last_error->message;
1670 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1672 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1675 function common_log_objstring(&$object)
1677 if (is_null($object)) {
1680 if (!($object instanceof DB_DataObject)) {
1683 $arr = $object->toArray();
1685 foreach ($arr as $k => $v) {
1686 if (is_object($v)) {
1687 $fields[] = "$k='".get_class($v)."'";
1689 $fields[] = "$k='$v'";
1692 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1696 function common_valid_http_url($url)
1698 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1701 function common_valid_tag($tag)
1703 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1704 return (Validate::email($matches[1]) ||
1705 preg_match('/^([\w-\.]+)$/', $matches[1]));
1711 * Determine if given domain or address literal is valid
1712 * eg for use in JIDs and URLs. Does not check if the domain
1715 * @param string $domain
1716 * @return boolean valid or not
1718 function common_valid_domain($domain)
1720 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1721 $ipv4 = "(?:$octet(?:\.$octet){3})";
1722 if (preg_match("/^$ipv4$/u", $domain)) return true;
1724 $group = "(?:[0-9a-f]{1,4})";
1725 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1727 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1728 $before = explode(":", $matches[1]);
1729 $zeroes = $matches[2];
1730 $after = explode(":", $matches[3]);
1738 $explicit = count($before) + count($after);
1739 if ($explicit < $min || $explicit > $max) {
1746 require_once "Net/IDNA.php";
1747 $idn = Net_IDNA::getInstance();
1748 $domain = $idn->encode($domain);
1749 } catch (Exception $e) {
1753 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1754 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1756 return preg_match("/^$fqdn$/ui", $domain);
1759 /* Following functions are copied from MediaWiki GlobalFunctions.php
1760 * and written by Evan Prodromou. */
1762 function common_accept_to_prefs($accept, $def = '*/*')
1764 // No arg means accept anything (per HTTP spec)
1766 return array($def => 1);
1771 $parts = explode(',', $accept);
1773 foreach($parts as $part) {
1774 // FIXME: doesn't deal with params like 'text/html; level=1'
1775 @list($value, $qpart) = explode(';', trim($part));
1777 if(!isset($qpart)) {
1779 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1780 $prefs[$value] = $match[1];
1787 function common_mime_type_match($type, $avail)
1789 if(array_key_exists($type, $avail)) {
1792 $parts = explode('/', $type);
1793 if(array_key_exists($parts[0] . '/*', $avail)) {
1794 return $parts[0] . '/*';
1795 } elseif(array_key_exists('*/*', $avail)) {
1803 function common_negotiate_type($cprefs, $sprefs)
1807 foreach(array_keys($sprefs) as $type) {
1808 $parts = explode('/', $type);
1809 if($parts[1] != '*') {
1810 $ckey = common_mime_type_match($type, $cprefs);
1812 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1817 foreach(array_keys($cprefs) as $type) {
1818 $parts = explode('/', $type);
1819 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1820 $skey = common_mime_type_match($type, $sprefs);
1822 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1828 $besttype = 'text/html';
1830 foreach(array_keys($combine) as $type) {
1831 if($combine[$type] > $bestq) {
1833 $bestq = $combine[$type];
1837 if ('text/html' === $besttype) {
1838 return "text/html; charset=utf-8";
1843 function common_config($main, $sub)
1846 return (array_key_exists($main, $config) &&
1847 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1851 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1852 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1854 * @param array $from
1857 function common_copy_args($from)
1860 $strip = get_magic_quotes_gpc();
1861 foreach ($from as $k => $v) {
1863 $to[$k] = common_copy_args($v);
1866 $v = stripslashes($v);
1868 $to[$k] = strval(common_validate_utf8($v));
1875 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1876 * This is used before handing a request off to OAuthRequest::from_request.
1877 * @fixme Doesn't consider vars other than _POST and _GET?
1878 * @fixme Can't be undone and could corrupt data if run twice.
1880 function common_remove_magic_from_request()
1882 if(get_magic_quotes_gpc()) {
1883 $_POST=array_map('stripslashes',$_POST);
1884 $_GET=array_map('stripslashes',$_GET);
1888 function common_user_uri(&$user)
1890 return common_local_url('userbyid', array('id' => $user->id),
1894 function common_notice_uri(&$notice)
1896 return common_local_url('shownotice',
1897 array('notice' => $notice->id),
1901 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1903 function common_confirmation_code($bits)
1905 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1906 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1907 $chars = ceil($bits/5);
1909 for ($i = 0; $i < $chars; $i++) {
1910 // XXX: convert to string and back
1911 $num = hexdec(common_good_rand(1));
1912 // XXX: randomness is too precious to throw away almost
1913 // 40% of the bits we get!
1914 $code .= $codechars[$num%32];
1919 // convert markup to HTML
1921 function common_markup_to_html($c)
1923 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1924 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1925 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1926 return Markdown($c);
1929 function common_profile_uri($profile)
1934 $user = User::staticGet($profile->id);
1939 $remote = Remote_profile::staticGet($profile->id);
1941 return $remote->uri;
1943 // XXX: this is a very bad profile!
1947 function common_canonical_sms($sms)
1950 preg_replace('/\D/', '', $sms);
1954 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1959 case E_COMPILE_ERROR:
1963 case E_RECOVERABLE_ERROR:
1964 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1969 case E_COMPILE_WARNING:
1970 case E_CORE_WARNING:
1971 case E_USER_WARNING:
1972 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1977 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1982 case E_USER_DEPRECATED:
1983 // XXX: config variable to log this stuff, too
1987 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1992 // FIXME: show error page if we're on the Web
1993 /* Don't execute PHP internal error handler */
1997 function common_session_token()
1999 common_ensure_session();
2000 if (!array_key_exists('token', $_SESSION)) {
2001 $_SESSION['token'] = common_good_rand(64);
2003 return $_SESSION['token'];
2006 function common_cache_key($extra)
2008 return Cache::key($extra);
2011 function common_keyize($str)
2013 return Cache::keyize($str);
2016 function common_memcache()
2018 return Cache::instance();
2021 function common_license_terms($uri)
2023 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2024 return explode('-',$matches[1]);
2029 function common_compatible_license($from, $to)
2031 $from_terms = common_license_terms($from);
2032 // public domain and cc-by are compatible with everything
2033 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2036 $to_terms = common_license_terms($to);
2037 // sa is compatible across versions. IANAL
2038 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2039 return count(array_diff($from_terms, $to_terms)) == 0;
2041 // XXX: better compatibility check needed here!
2042 // Should at least normalise URIs
2043 return ($from == $to);
2047 * returns a quoted table name, if required according to config
2049 function common_database_tablename($tablename)
2051 if(common_config('db','quote_identifiers')) {
2052 $tablename = '"'. $tablename .'"';
2054 //table prefixes could be added here later
2059 * Shorten a URL with the current user's configured shortening service,
2060 * or ur1.ca if configured, or not at all if no shortening is set up.
2061 * Length is not considered.
2063 * @param string $long_url
2064 * @param User $user to specify a particular user's options
2065 * @return string may return the original URL if shortening failed
2067 * @fixme provide a way to specify a particular shortener
2069 function common_shorten_url($long_url, User $user=null)
2071 $long_url = trim($long_url);
2073 // Current web session
2074 $user = common_current_user();
2077 // common current user does not find a user when called from the XMPP daemon
2078 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
2079 $shortenerName = 'ur1.ca';
2081 $shortenerName = $user->urlshorteningservice;
2084 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
2085 //URL wasn't shortened, so return the long url
2088 //URL was shortened, so return the result
2089 return trim($shortenedUrl);
2094 * @return mixed array($proxy, $ip) for web requests; proxy may be null
2095 * null if not a web request
2097 * @fixme X-Forwarded-For can be chained by multiple proxies;
2098 we should parse the list and provide a cleaner array
2099 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2100 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2101 * use function to get exact request headers from Apache if possible.
2103 function common_client_ip()
2105 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2109 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2110 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2111 $proxy = $_SERVER['HTTP_CLIENT_IP'];
2113 $proxy = $_SERVER['REMOTE_ADDR'];
2115 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2118 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2119 $ip = $_SERVER['HTTP_CLIENT_IP'];
2121 $ip = $_SERVER['REMOTE_ADDR'];
2125 return array($proxy, $ip);
2128 function common_url_to_nickname($url)
2130 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2132 $parts = parse_url($url);
2134 # If any of these parts exist, this won't work
2136 foreach ($bad as $badpart) {
2137 if (array_key_exists($badpart, $parts)) {
2142 # We just have host and/or path
2144 # If it's just a host...
2145 if (array_key_exists('host', $parts) &&
2146 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2148 $hostparts = explode('.', $parts['host']);
2150 # Try to catch common idiom of nickname.service.tld
2152 if ((count($hostparts) > 2) &&
2153 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2154 (strcmp($hostparts[0], 'www') != 0))
2156 return common_nicknamize($hostparts[0]);
2158 # Do the whole hostname
2159 return common_nicknamize($parts['host']);
2162 if (array_key_exists('path', $parts)) {
2163 # Strip starting, ending slashes
2164 $path = preg_replace('@/$@', '', $parts['path']);
2165 $path = preg_replace('@^/@', '', $path);
2166 $path = basename($path);
2168 // Hack for MediaWiki user pages, in the form:
2169 // http://example.com/wiki/User:Myname
2170 // ('User' may be localized.)
2171 if (strpos($path, ':')) {
2172 $parts = array_filter(explode(':', $path));
2173 $path = $parts[count($parts) - 1];
2177 return common_nicknamize($path);
2185 function common_nicknamize($str)
2187 $str = preg_replace('/\W/', '', $str);
2188 return strtolower($str);
2191 function common_perf_counter($key, $val=null)
2193 global $_perfCounters;
2194 if (isset($_perfCounters)) {
2195 if (common_config('site', 'logperf')) {
2196 if (array_key_exists($key, $_perfCounters)) {
2197 $_perfCounters[$key][] = $val;
2199 $_perfCounters[$key] = array($val);
2201 if (common_config('site', 'logperf_detail')) {
2202 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2208 function common_log_perf_counters()
2210 if (common_config('site', 'logperf')) {
2211 global $_startTime, $_perfCounters;
2213 if (isset($_startTime)) {
2214 $endTime = microtime(true);
2215 $diff = round(($endTime - $_startTime) * 1000);
2216 common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2218 $counters = $_perfCounters;
2220 foreach ($counters as $key => $values) {
2221 $count = count($values);
2222 $unique = count(array_unique($values));
2223 common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");