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)
1100 $tag = preg_replace('/[^\pL\pN]/u', '', $tag);
1101 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1102 $tag = substr($tag, 0, 64);
1106 function common_valid_profile_tag($str)
1108 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1113 * @param <type> $sender_id
1114 * @param <type> $nickname
1118 function common_group_link($sender_id, $nickname)
1120 $sender = Profile::staticGet($sender_id);
1121 $group = User_group::getForNickname($nickname, $sender);
1122 if ($sender && $group && $sender->isMember($group)) {
1123 $attrs = array('href' => $group->permalink(),
1125 if (!empty($group->fullname)) {
1126 $attrs['title'] = $group->getFancyName();
1128 $xs = new XMLStringer();
1129 $xs->elementStart('span', 'vcard');
1130 $xs->elementStart('a', $attrs);
1131 $xs->element('span', 'fn nickname', $nickname);
1132 $xs->elementEnd('a');
1133 $xs->elementEnd('span');
1134 return $xs->getString();
1141 * Resolve an ambiguous profile nickname reference, checking in following order:
1142 * - profiles that $sender subscribes to
1143 * - profiles that subscribe to $sender
1144 * - local user profiles
1146 * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1147 * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1150 * @fixme validate input
1152 * @fixme fix or remove mystery third parameter
1153 * @fixme is $sender a User or Profile?
1155 * @param <type> $sender the user or profile in whose context we're looking
1156 * @param string $nickname validated nickname of
1157 * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1159 * @return Profile or null
1161 function common_relative_profile($sender, $nickname, $dt=null)
1163 // Will throw exception on invalid input.
1164 $nickname = Nickname::normalize($nickname);
1166 // Try to find profiles this profile is subscribed to that have this nickname
1167 $recipient = new Profile();
1168 // XXX: use a join instead of a subquery
1169 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1170 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1171 if ($recipient->find(true)) {
1172 // XXX: should probably differentiate between profiles with
1173 // the same name by date of most recent update
1176 // Try to find profiles that listen to this profile and that have this nickname
1177 $recipient = new Profile();
1178 // XXX: use a join instead of a subquery
1179 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1180 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1181 if ($recipient->find(true)) {
1182 // XXX: should probably differentiate between profiles with
1183 // the same name by date of most recent update
1186 // If this is a local user, try to find a local user with that nickname.
1187 $sender = User::staticGet($sender->id);
1189 $recipient_user = User::staticGet('nickname', $nickname);
1190 if ($recipient_user) {
1191 return $recipient_user->getProfile();
1194 // Otherwise, no links. @messages from local users to remote users,
1195 // or from remote users to other remote users, are just
1196 // outside our ability to make intelligent guesses about
1200 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1203 $path = $r->build($action, $args, $params, $fragment);
1205 $ssl = common_is_sensitive($action);
1207 if (common_config('site','fancy')) {
1208 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1210 if (mb_strpos($path, '/index.php') === 0) {
1211 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1213 $url = common_path('index.php'.$path, $ssl, $addSession);
1219 function common_is_sensitive($action)
1221 static $sensitive = array(
1226 'ApiOauthRequestToken',
1227 'ApiOauthAccessToken',
1228 'ApiOauthAuthorize',
1234 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1235 $ssl = in_array($action, $sensitive);
1241 function common_path($relative, $ssl=false, $addSession=true)
1243 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1245 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1246 || common_config('site', 'ssl') === 'always') {
1248 if (is_string(common_config('site', 'sslserver')) &&
1249 mb_strlen(common_config('site', 'sslserver')) > 0) {
1250 $serverpart = common_config('site', 'sslserver');
1251 } else if (common_config('site', 'server')) {
1252 $serverpart = common_config('site', 'server');
1254 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1258 if (common_config('site', 'server')) {
1259 $serverpart = common_config('site', 'server');
1261 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1266 $relative = common_inject_session($relative, $serverpart);
1269 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1272 function common_inject_session($url, $serverpart = null)
1274 if (common_have_session()) {
1276 if (empty($serverpart)) {
1277 $serverpart = parse_url($url, PHP_URL_HOST);
1280 $currentServer = $_SERVER['HTTP_HOST'];
1282 // Are we pointing to another server (like an SSL server?)
1284 if (!empty($currentServer) &&
1285 0 != strcasecmp($currentServer, $serverpart)) {
1286 // Pass the session ID as a GET parameter
1287 $sesspart = session_name() . '=' . session_id();
1288 $i = strpos($url, '?');
1289 if ($i === false) { // no GET params, just append
1290 $url .= '?' . $sesspart;
1292 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1300 function common_date_string($dt)
1302 // XXX: do some sexy date formatting
1303 // return date(DATE_RFC822, $dt);
1304 $t = strtotime($dt);
1308 if ($now < $t) { // that shouldn't happen!
1309 return common_exact_date($dt);
1310 } else if ($diff < 60) {
1311 // TRANS: Used in notices to indicate when the notice was made compared to now.
1312 return _('a few seconds ago');
1313 } else if ($diff < 92) {
1314 // TRANS: Used in notices to indicate when the notice was made compared to now.
1315 return _('about a minute ago');
1316 } else if ($diff < 3300) {
1317 $minutes = round($diff/60);
1318 // TRANS: Used in notices to indicate when the notice was made compared to now.
1319 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1320 } else if ($diff < 5400) {
1321 // TRANS: Used in notices to indicate when the notice was made compared to now.
1322 return _('about an hour ago');
1323 } else if ($diff < 22 * 3600) {
1324 $hours = round($diff/3600);
1325 // TRANS: Used in notices to indicate when the notice was made compared to now.
1326 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1327 } else if ($diff < 37 * 3600) {
1328 // TRANS: Used in notices to indicate when the notice was made compared to now.
1329 return _('about a day ago');
1330 } else if ($diff < 24 * 24 * 3600) {
1331 $days = round($diff/(24*3600));
1332 // TRANS: Used in notices to indicate when the notice was made compared to now.
1333 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1334 } else if ($diff < 46 * 24 * 3600) {
1335 // TRANS: Used in notices to indicate when the notice was made compared to now.
1336 return _('about a month ago');
1337 } else if ($diff < 330 * 24 * 3600) {
1338 $months = round($diff/(30*24*3600));
1339 // TRANS: Used in notices to indicate when the notice was made compared to now.
1340 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1341 } else if ($diff < 480 * 24 * 3600) {
1342 // TRANS: Used in notices to indicate when the notice was made compared to now.
1343 return _('about a year ago');
1345 return common_exact_date($dt);
1349 function common_exact_date($dt)
1355 $_utc = new DateTimeZone('UTC');
1356 $_siteTz = new DateTimeZone(common_timezone());
1359 $dateStr = date('d F Y H:i:s', strtotime($dt));
1360 $d = new DateTime($dateStr, $_utc);
1361 $d->setTimezone($_siteTz);
1362 return $d->format(DATE_RFC850);
1365 function common_date_w3dtf($dt)
1367 $dateStr = date('d F Y H:i:s', strtotime($dt));
1368 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1369 $d->setTimezone(new DateTimeZone(common_timezone()));
1370 return $d->format(DATE_W3C);
1373 function common_date_rfc2822($dt)
1375 $dateStr = date('d F Y H:i:s', strtotime($dt));
1376 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1377 $d->setTimezone(new DateTimeZone(common_timezone()));
1378 return $d->format('r');
1381 function common_date_iso8601($dt)
1383 $dateStr = date('d F Y H:i:s', strtotime($dt));
1384 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1385 $d->setTimezone(new DateTimeZone(common_timezone()));
1386 return $d->format('c');
1389 function common_sql_now()
1391 return common_sql_date(time());
1394 function common_sql_date($datetime)
1396 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1400 * Return an SQL fragment to calculate an age-based weight from a given
1401 * timestamp or datetime column.
1403 * @param string $column name of field we're comparing against current time
1404 * @param integer $dropoff divisor for age in seconds before exponentiation
1405 * @return string SQL fragment
1407 function common_sql_weight($column, $dropoff)
1409 if (common_config('db', 'type') == 'pgsql') {
1410 // PostgreSQL doesn't support timestampdiff function.
1411 // @fixme will this use the right time zone?
1412 // @fixme does this handle cross-year subtraction correctly?
1413 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1415 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1419 function common_redirect($url, $code=307)
1421 static $status = array(301 => "Moved Permanently",
1424 307 => "Temporary Redirect");
1426 header('HTTP/1.1 '.$code.' '.$status[$code]);
1427 header("Location: $url");
1428 header("Connection: close");
1430 $xo = new XMLOutputter();
1432 '-//W3C//DTD XHTML 1.0 Strict//EN',
1433 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1434 $xo->element('a', array('href' => $url), $url);
1439 function common_broadcast_notice($notice, $remote=false)
1445 * Stick the notice on the queue.
1447 function common_enqueue_notice($notice)
1449 static $localTransports = array('omb',
1452 $transports = array();
1453 if (common_config('sms', 'enabled')) {
1454 $transports[] = 'sms';
1456 if (Event::hasHandler('HandleQueuedNotice')) {
1457 $transports[] = 'plugin';
1460 $xmpp = common_config('xmpp', 'enabled');
1463 $transports[] = 'jabber';
1466 // We can skip these for gatewayed notices.
1467 if ($notice->isLocal()) {
1468 $transports = array_merge($transports, $localTransports);
1470 $transports[] = 'public';
1474 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1476 $qm = QueueManager::get();
1478 foreach ($transports as $transport)
1480 $qm->enqueue($notice, $transport);
1483 Event::handle('EndEnqueueNotice', array($notice, $transports));
1490 * Broadcast profile updates to OMB and other remote subscribers.
1492 * Since this may be slow with a lot of subscribers or bad remote sites,
1493 * this is run through the background queues if possible.
1495 function common_broadcast_profile(Profile $profile)
1497 $qm = QueueManager::get();
1498 $qm->enqueue($profile, "profile");
1502 function common_profile_url($nickname)
1504 return common_local_url('showstream', array('nickname' => $nickname),
1509 * Should make up a reasonable root URL
1511 function common_root_url($ssl=false)
1513 $url = common_path('', $ssl, false);
1514 $i = strpos($url, '?');
1516 $url = substr($url, 0, $i);
1522 * returns $bytes bytes of random data as a hexadecimal string
1523 * "good" here is a goal and not a guarantee
1525 function common_good_rand($bytes)
1527 // XXX: use random.org...?
1528 if (@file_exists('/dev/urandom')) {
1529 return common_urandom($bytes);
1530 } else { // FIXME: this is probably not good enough
1531 return common_mtrand($bytes);
1535 function common_urandom($bytes)
1537 $h = fopen('/dev/urandom', 'rb');
1539 $src = fread($h, $bytes);
1542 for ($i = 0; $i < $bytes; $i++) {
1543 $enc .= sprintf("%02x", (ord($src[$i])));
1548 function common_mtrand($bytes)
1551 for ($i = 0; $i < $bytes; $i++) {
1552 $enc .= sprintf("%02x", mt_rand(0, 255));
1558 * Record the given URL as the return destination for a future
1559 * form submission, to be read by common_get_returnto().
1561 * @param string $url
1563 * @fixme as a session-global setting, this can allow multiple forms
1564 * to conflict and overwrite each others' returnto destinations if
1565 * the user has multiple tabs or windows open.
1567 * Should refactor to index with a token or otherwise only pass the
1568 * data along its intended path.
1570 function common_set_returnto($url)
1572 common_ensure_session();
1573 $_SESSION['returnto'] = $url;
1577 * Fetch a return-destination URL previously recorded by
1578 * common_set_returnto().
1580 * @return mixed URL string or null
1582 * @fixme as a session-global setting, this can allow multiple forms
1583 * to conflict and overwrite each others' returnto destinations if
1584 * the user has multiple tabs or windows open.
1586 * Should refactor to index with a token or otherwise only pass the
1587 * data along its intended path.
1589 function common_get_returnto()
1591 common_ensure_session();
1592 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1595 function common_timestamp()
1597 return date('YmdHis');
1600 function common_ensure_syslog()
1602 static $initialized = false;
1603 if (!$initialized) {
1604 openlog(common_config('syslog', 'appname'), 0,
1605 common_config('syslog', 'facility'));
1606 $initialized = true;
1610 function common_log_line($priority, $msg)
1612 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1613 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1614 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1617 function common_request_id()
1620 $server = common_config('site', 'server');
1621 if (php_sapi_name() == 'cli') {
1622 $script = basename($_SERVER['PHP_SELF']);
1623 return "$server:$script:$pid";
1625 static $req_id = null;
1626 if (!isset($req_id)) {
1627 $req_id = substr(md5(mt_rand()), 0, 8);
1629 if (isset($_SERVER['REQUEST_URI'])) {
1630 $url = $_SERVER['REQUEST_URI'];
1632 $method = $_SERVER['REQUEST_METHOD'];
1633 return "$server:$pid.$req_id $method $url";
1637 function common_log($priority, $msg, $filename=null)
1639 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1640 $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1641 $msg = '[' . common_request_id() . '] ' . $msg;
1642 $logfile = common_config('site', 'logfile');
1644 $log = fopen($logfile, "a");
1646 $output = common_log_line($priority, $msg);
1647 fwrite($log, $output);
1651 common_ensure_syslog();
1652 syslog($priority, $msg);
1654 Event::handle('EndLog', array($priority, $msg, $filename));
1658 function common_debug($msg, $filename=null)
1661 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1663 common_log(LOG_DEBUG, $msg);
1667 function common_log_db_error(&$object, $verb, $filename=null)
1669 $objstr = common_log_objstring($object);
1670 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1671 if (is_object($last_error)) {
1672 $msg = $last_error->message;
1674 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1676 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1679 function common_log_objstring(&$object)
1681 if (is_null($object)) {
1684 if (!($object instanceof DB_DataObject)) {
1687 $arr = $object->toArray();
1689 foreach ($arr as $k => $v) {
1690 if (is_object($v)) {
1691 $fields[] = "$k='".get_class($v)."'";
1693 $fields[] = "$k='$v'";
1696 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1700 function common_valid_http_url($url)
1702 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1705 function common_valid_tag($tag)
1707 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1708 return (Validate::email($matches[1]) ||
1709 preg_match('/^([\w-\.]+)$/', $matches[1]));
1715 * Determine if given domain or address literal is valid
1716 * eg for use in JIDs and URLs. Does not check if the domain
1719 * @param string $domain
1720 * @return boolean valid or not
1722 function common_valid_domain($domain)
1724 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1725 $ipv4 = "(?:$octet(?:\.$octet){3})";
1726 if (preg_match("/^$ipv4$/u", $domain)) return true;
1728 $group = "(?:[0-9a-f]{1,4})";
1729 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1731 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1732 $before = explode(":", $matches[1]);
1733 $zeroes = $matches[2];
1734 $after = explode(":", $matches[3]);
1742 $explicit = count($before) + count($after);
1743 if ($explicit < $min || $explicit > $max) {
1750 require_once "Net/IDNA.php";
1751 $idn = Net_IDNA::getInstance();
1752 $domain = $idn->encode($domain);
1753 } catch (Exception $e) {
1757 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1758 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1760 return preg_match("/^$fqdn$/ui", $domain);
1763 /* Following functions are copied from MediaWiki GlobalFunctions.php
1764 * and written by Evan Prodromou. */
1766 function common_accept_to_prefs($accept, $def = '*/*')
1768 // No arg means accept anything (per HTTP spec)
1770 return array($def => 1);
1775 $parts = explode(',', $accept);
1777 foreach($parts as $part) {
1778 // FIXME: doesn't deal with params like 'text/html; level=1'
1779 @list($value, $qpart) = explode(';', trim($part));
1781 if(!isset($qpart)) {
1783 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1784 $prefs[$value] = $match[1];
1791 function common_mime_type_match($type, $avail)
1793 if(array_key_exists($type, $avail)) {
1796 $parts = explode('/', $type);
1797 if(array_key_exists($parts[0] . '/*', $avail)) {
1798 return $parts[0] . '/*';
1799 } elseif(array_key_exists('*/*', $avail)) {
1807 function common_negotiate_type($cprefs, $sprefs)
1811 foreach(array_keys($sprefs) as $type) {
1812 $parts = explode('/', $type);
1813 if($parts[1] != '*') {
1814 $ckey = common_mime_type_match($type, $cprefs);
1816 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1821 foreach(array_keys($cprefs) as $type) {
1822 $parts = explode('/', $type);
1823 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1824 $skey = common_mime_type_match($type, $sprefs);
1826 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1832 $besttype = 'text/html';
1834 foreach(array_keys($combine) as $type) {
1835 if($combine[$type] > $bestq) {
1837 $bestq = $combine[$type];
1841 if ('text/html' === $besttype) {
1842 return "text/html; charset=utf-8";
1847 function common_config($main, $sub)
1850 return (array_key_exists($main, $config) &&
1851 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1855 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1856 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1858 * @param array $from
1861 function common_copy_args($from)
1864 $strip = get_magic_quotes_gpc();
1865 foreach ($from as $k => $v) {
1867 $to[$k] = common_copy_args($v);
1870 $v = stripslashes($v);
1872 $to[$k] = strval(common_validate_utf8($v));
1879 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1880 * This is used before handing a request off to OAuthRequest::from_request.
1881 * @fixme Doesn't consider vars other than _POST and _GET?
1882 * @fixme Can't be undone and could corrupt data if run twice.
1884 function common_remove_magic_from_request()
1886 if(get_magic_quotes_gpc()) {
1887 $_POST=array_map('stripslashes',$_POST);
1888 $_GET=array_map('stripslashes',$_GET);
1892 function common_user_uri(&$user)
1894 return common_local_url('userbyid', array('id' => $user->id),
1898 function common_notice_uri(&$notice)
1900 return common_local_url('shownotice',
1901 array('notice' => $notice->id),
1905 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1907 function common_confirmation_code($bits)
1909 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1910 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1911 $chars = ceil($bits/5);
1913 for ($i = 0; $i < $chars; $i++) {
1914 // XXX: convert to string and back
1915 $num = hexdec(common_good_rand(1));
1916 // XXX: randomness is too precious to throw away almost
1917 // 40% of the bits we get!
1918 $code .= $codechars[$num%32];
1923 // convert markup to HTML
1925 function common_markup_to_html($c)
1927 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1928 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1929 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1930 return Markdown($c);
1933 function common_profile_uri($profile)
1938 $user = User::staticGet($profile->id);
1943 $remote = Remote_profile::staticGet($profile->id);
1945 return $remote->uri;
1947 // XXX: this is a very bad profile!
1951 function common_canonical_sms($sms)
1954 preg_replace('/\D/', '', $sms);
1958 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1963 case E_COMPILE_ERROR:
1967 case E_RECOVERABLE_ERROR:
1968 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1973 case E_COMPILE_WARNING:
1974 case E_CORE_WARNING:
1975 case E_USER_WARNING:
1976 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1981 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1986 case E_USER_DEPRECATED:
1987 // XXX: config variable to log this stuff, too
1991 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1996 // FIXME: show error page if we're on the Web
1997 /* Don't execute PHP internal error handler */
2001 function common_session_token()
2003 common_ensure_session();
2004 if (!array_key_exists('token', $_SESSION)) {
2005 $_SESSION['token'] = common_good_rand(64);
2007 return $_SESSION['token'];
2010 function common_cache_key($extra)
2012 return Cache::key($extra);
2015 function common_keyize($str)
2017 return Cache::keyize($str);
2020 function common_memcache()
2022 return Cache::instance();
2025 function common_license_terms($uri)
2027 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2028 return explode('-',$matches[1]);
2033 function common_compatible_license($from, $to)
2035 $from_terms = common_license_terms($from);
2036 // public domain and cc-by are compatible with everything
2037 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2040 $to_terms = common_license_terms($to);
2041 // sa is compatible across versions. IANAL
2042 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2043 return count(array_diff($from_terms, $to_terms)) == 0;
2045 // XXX: better compatibility check needed here!
2046 // Should at least normalise URIs
2047 return ($from == $to);
2051 * returns a quoted table name, if required according to config
2053 function common_database_tablename($tablename)
2055 if(common_config('db','quote_identifiers')) {
2056 $tablename = '"'. $tablename .'"';
2058 //table prefixes could be added here later
2063 * Shorten a URL with the current user's configured shortening service,
2064 * or ur1.ca if configured, or not at all if no shortening is set up.
2065 * Length is not considered.
2067 * @param string $long_url
2068 * @param User $user to specify a particular user's options
2069 * @return string may return the original URL if shortening failed
2071 * @fixme provide a way to specify a particular shortener
2073 function common_shorten_url($long_url, User $user=null)
2075 $long_url = trim($long_url);
2077 // Current web session
2078 $user = common_current_user();
2081 // common current user does not find a user when called from the XMPP daemon
2082 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
2083 $shortenerName = 'ur1.ca';
2085 $shortenerName = $user->urlshorteningservice;
2088 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
2089 //URL wasn't shortened, so return the long url
2092 //URL was shortened, so return the result
2093 return trim($shortenedUrl);
2098 * @return mixed array($proxy, $ip) for web requests; proxy may be null
2099 * null if not a web request
2101 * @fixme X-Forwarded-For can be chained by multiple proxies;
2102 we should parse the list and provide a cleaner array
2103 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2104 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2105 * use function to get exact request headers from Apache if possible.
2107 function common_client_ip()
2109 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2113 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2114 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2115 $proxy = $_SERVER['HTTP_CLIENT_IP'];
2117 $proxy = $_SERVER['REMOTE_ADDR'];
2119 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2122 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2123 $ip = $_SERVER['HTTP_CLIENT_IP'];
2125 $ip = $_SERVER['REMOTE_ADDR'];
2129 return array($proxy, $ip);
2132 function common_url_to_nickname($url)
2134 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2136 $parts = parse_url($url);
2138 # If any of these parts exist, this won't work
2140 foreach ($bad as $badpart) {
2141 if (array_key_exists($badpart, $parts)) {
2146 # We just have host and/or path
2148 # If it's just a host...
2149 if (array_key_exists('host', $parts) &&
2150 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2152 $hostparts = explode('.', $parts['host']);
2154 # Try to catch common idiom of nickname.service.tld
2156 if ((count($hostparts) > 2) &&
2157 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2158 (strcmp($hostparts[0], 'www') != 0))
2160 return common_nicknamize($hostparts[0]);
2162 # Do the whole hostname
2163 return common_nicknamize($parts['host']);
2166 if (array_key_exists('path', $parts)) {
2167 # Strip starting, ending slashes
2168 $path = preg_replace('@/$@', '', $parts['path']);
2169 $path = preg_replace('@^/@', '', $path);
2170 $path = basename($path);
2172 // Hack for MediaWiki user pages, in the form:
2173 // http://example.com/wiki/User:Myname
2174 // ('User' may be localized.)
2175 if (strpos($path, ':')) {
2176 $parts = array_filter(explode(':', $path));
2177 $path = $parts[count($parts) - 1];
2181 return common_nicknamize($path);
2189 function common_nicknamize($str)
2191 $str = preg_replace('/\W/', '', $str);
2192 return strtolower($str);
2195 function common_perf_counter($key, $val=null)
2197 global $_perfCounters;
2198 if (isset($_perfCounters)) {
2199 if (common_config('site', 'logperf')) {
2200 if (array_key_exists($key, $_perfCounters)) {
2201 $_perfCounters[$key][] = $val;
2203 $_perfCounters[$key] = array($val);
2205 if (common_config('site', 'logperf_detail')) {
2206 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2212 function common_log_perf_counters()
2214 if (common_config('site', 'logperf')) {
2215 global $_startTime, $_perfCounters;
2217 if (isset($_startTime)) {
2218 $endTime = microtime(true);
2219 $diff = round(($endTime - $_startTime) * 1000);
2220 common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2222 $counters = $_perfCounters;
2224 foreach ($counters as $key => $values) {
2225 $count = count($values);
2226 $unique = count(array_unique($values));
2227 common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");