3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, user, files) */
23 * Show a server error.
25 function common_server_error($msg, $code=500)
27 $err = new ServerErrorAction($msg, $code);
34 function common_user_error($msg, $code=400)
36 $err = new ClientErrorAction($msg, $code);
41 * This should only be used at setup; processes switching languages
42 * to send text to other users should use common_switch_locale().
44 * @param string $language Locale language code (optional; empty uses
45 * current user's preference or site default)
46 * @return mixed success
48 function common_init_locale($language=null)
51 $language = common_language();
53 putenv('LANGUAGE='.$language);
54 putenv('LANG='.$language);
55 $ok = setlocale(LC_ALL, $language . ".utf8",
65 * Initialize locale and charset settings and gettext with our message catalog,
66 * using the current user's language preference or the site default.
68 * This should generally only be run at framework initialization; code switching
69 * languages at runtime should call common_switch_language().
73 function common_init_language()
75 mb_internal_encoding('UTF-8');
77 // Note that this setlocale() call may "fail" but this is harmless;
78 // gettext will still select the right language.
79 $language = common_language();
80 $locale_set = common_init_locale($language);
83 // The requested locale doesn't exist on the system.
85 // gettext seems very picky... We first need to setlocale()
86 // to a locale which _does_ exist on the system, and _then_
87 // we can set in another locale that may not be set up
88 // (say, ga_ES for Galego/Galician) it seems to take it.
90 // For some reason C and POSIX which are guaranteed to work
91 // don't do the job. en_US.UTF-8 should be there most of the
92 // time, but not guaranteed.
93 $ok = common_init_locale("en_US");
94 if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
95 // Try to find a complete, working locale on Unix/Linux...
96 // @fixme shelling out feels awfully inefficient
97 // but I don't think there's a more standard way.
99 foreach (explode("\n", $all) as $locale) {
100 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
101 $ok = setlocale(LC_ALL, $locale);
109 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
111 $locale_set = common_init_locale($language);
114 common_init_gettext();
120 function common_init_gettext()
122 setlocale(LC_CTYPE, 'C');
123 // So we do not have to make people install the gettext locales
124 $path = common_config('site','locale_path');
125 bindtextdomain("statusnet", $path);
126 bind_textdomain_codeset("statusnet", "UTF-8");
127 textdomain("statusnet");
131 * Switch locale during runtime, and poke gettext until it cries uncle.
132 * Otherwise, sometimes it doesn't actually switch away from the old language.
134 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
136 function common_switch_locale($language=null)
138 common_init_locale($language);
140 setlocale(LC_CTYPE, 'C');
141 // So we do not have to make people install the gettext locales
142 $path = common_config('site','locale_path');
143 bindtextdomain("statusnet", $path);
144 bind_textdomain_codeset("statusnet", "UTF-8");
145 textdomain("statusnet");
148 function common_timezone()
150 if (common_logged_in()) {
151 $user = common_current_user();
152 if ($user->timezone) {
153 return $user->timezone;
157 return common_config('site', 'timezone');
160 function common_valid_language($lang)
163 // Validate -- we don't want to end up with a bogus code
164 // left over from some old junk.
165 foreach (common_config('site', 'languages') as $code => $info) {
166 if ($info['lang'] == $lang) {
174 function common_language()
176 // Allow ?uselang=xx override, very useful for debugging
177 // and helping translators check usage and context.
178 if (isset($_GET['uselang'])) {
179 $uselang = strval($_GET['uselang']);
180 if (common_valid_language($uselang)) {
185 // If there is a user logged in and they've set a language preference
186 // then return that one...
187 if (_have_config() && common_logged_in()) {
188 $user = common_current_user();
190 if (common_valid_language($user->language)) {
191 return $user->language;
195 // Otherwise, find the best match for the languages requested by the
197 if (common_config('site', 'langdetect')) {
198 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
199 if (!empty($httplang)) {
200 $language = client_prefered_language($httplang);
206 // Finally, if none of the above worked, use the site's default...
207 return common_config('site', 'language');
211 * Salted, hashed passwords are stored in the DB.
213 function common_munge_password($password, $id)
215 if (is_object($id) || is_object($password)) {
216 $e = new Exception();
217 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
218 str_replace("\n", " ", $e->getTraceAsString()));
220 return md5($password . $id);
224 * Check if a username exists and has matching password.
226 function common_check_user($nickname, $password)
228 // empty nickname always unacceptable
229 if (empty($nickname)) {
233 $authenticatedUser = false;
235 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
237 if (common_is_email($nickname)) {
238 $user = User::getKV('email', common_canonical_email($nickname));
240 $user = User::getKV('nickname', common_canonical_nickname($nickname));
244 if (!empty($password)) { // never allow login with blank password
245 if (0 == strcmp(common_munge_password($password, $user->id),
247 //internal checking passed
248 $authenticatedUser = $user;
252 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
255 return $authenticatedUser;
259 * Is the current user logged in?
261 function common_logged_in()
263 return (!is_null(common_current_user()));
266 function common_have_session()
268 return (0 != strcmp(session_id(), ''));
271 function common_ensure_session()
274 if (array_key_exists(session_name(), $_COOKIE)) {
275 $c = $_COOKIE[session_name()];
277 if (!common_have_session()) {
278 if (common_config('sessions', 'handle')) {
279 Session::setSaveHandler();
281 if (array_key_exists(session_name(), $_GET)) {
282 $id = $_GET[session_name()];
283 } else if (array_key_exists(session_name(), $_COOKIE)) {
284 $id = $_COOKIE[session_name()];
290 if (!isset($_SESSION['started'])) {
291 $_SESSION['started'] = time();
293 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
294 ' is set but started value is null');
300 // Three kinds of arguments:
305 // Initialize to false; set to null if none found
308 function common_set_user($user)
312 if (is_null($user) && common_have_session()) {
314 unset($_SESSION['userid']);
316 } else if (is_string($user)) {
318 $user = User::getKV('nickname', $nickname);
319 } else if (!($user instanceof User)) {
324 if (Event::handle('StartSetUser', array(&$user))) {
326 if (!$user->hasRight(Right::WEBLOGIN)) {
327 // TRANS: Authorisation exception thrown when a user a not allowed to login.
328 throw new AuthorizationException(_('Not allowed to log in.'));
330 common_ensure_session();
331 $_SESSION['userid'] = $user->id;
333 Event::handle('EndSetUser', array($user));
341 function common_set_cookie($key, $value, $expiration=0)
343 $path = common_config('site', 'path');
344 $server = common_config('site', 'server');
346 if ($path && ($path != '/')) {
347 $cookiepath = '/' . $path . '/';
351 return setcookie($key,
356 common_config('site', 'ssl')=='always');
359 define('REMEMBERME', 'rememberme');
360 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
362 function common_rememberme($user=null)
365 $user = common_current_user();
371 $rm = new Remember_me();
373 $rm->code = common_good_rand(16);
374 $rm->user_id = $user->id;
376 // Wrap the insert in some good ol' fashioned transaction code
380 $result = $rm->insert();
383 common_log_db_error($rm, 'INSERT', __FILE__);
387 $rm->query('COMMIT');
389 $cookieval = $rm->user_id . ':' . $rm->code;
391 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
393 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
398 function common_remembered_user()
402 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
408 list($id, $code) = explode(':', $packed);
410 if (!$id || !$code) {
411 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
416 $rm = Remember_me::getKV('code', $code);
419 common_log(LOG_WARNING, 'No such remember code: ' . $code);
424 if ($rm->user_id != $id) {
425 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
430 $user = User::getKV('id', $rm->user_id);
433 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
439 $result = $rm->delete();
442 common_log_db_error($rm, 'DELETE', __FILE__);
443 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
448 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
450 common_set_user($user);
451 common_real_login(false);
453 // We issue a new cookie, so they can log in
454 // automatically again after this session
456 common_rememberme($user);
462 * must be called with a valid user!
464 function common_forgetme()
466 common_set_cookie(REMEMBERME, '', 0);
470 * Who is the current user?
472 function common_current_user()
476 if (!_have_config()) {
480 if ($_cur === false) {
482 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
483 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
484 common_ensure_session();
485 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
487 $user = User::getKV($id);
495 // that didn't work; try to remember; will init $_cur to null on failure
496 $_cur = common_remembered_user();
499 // XXX: Is this necessary?
500 $_SESSION['userid'] = $_cur->id;
508 * Logins that are 'remembered' aren't 'real' -- they're subject to
509 * cookie-stealing. So, we don't let them do certain things. New reg,
510 * OpenID, and password logins _are_ real.
512 function common_real_login($real=true)
514 common_ensure_session();
515 $_SESSION['real_login'] = $real;
518 function common_is_real_login()
520 return common_logged_in() && $_SESSION['real_login'];
524 * Get a hash portion for HTTP caching Etags and such including
525 * info on the current user's session. If login/logout state changes,
526 * or we've changed accounts, or we've renamed the current user,
527 * we'll get a new hash value.
529 * This should not be considered secure information.
531 * @param User $user (optional; uses common_current_user() if left out)
534 function common_user_cache_hash($user=false)
536 if ($user === false) {
537 $user = common_current_user();
540 return crc32($user->id . ':' . $user->nickname);
547 * get canonical version of nickname for comparison
549 * @param string $nickname
552 * @throws NicknameException on invalid input
553 * @deprecated call Nickname::normalize() directly.
555 function common_canonical_nickname($nickname)
557 return Nickname::normalize($nickname);
561 * get canonical version of email for comparison
563 * @fixme actually normalize
564 * @fixme reject invalid input
566 * @param string $email
569 function common_canonical_email($email)
571 // XXX: canonicalize UTF-8
572 // XXX: lcase the domain part
577 * Partial notice markup rendering step: build links to !group references.
579 * @param string $text partially rendered HTML
580 * @param Notice $notice in whose context we're working
581 * @return string partially rendered HTML
583 function common_render_content($text, $notice)
585 $r = common_render_text($text);
586 $id = $notice->profile_id;
587 $r = common_linkify_mentions($r, $notice);
588 $r = preg_replace_callback('/(^|[\s\.\,\:\;]+)!(' . Nickname::DISPLAY_FMT . ')/',
589 function ($m) { return "{$m[1]}!".common_group_link($id, $m[2]); }, $r);
594 * Finds @-mentions within the partially-rendered text section and
595 * turns them into live links.
597 * Should generally not be called except from common_render_content().
599 * @param string $text partially-rendered HTML
600 * @param Notice $notice in-progress or complete Notice object for context
601 * @return string partially-rendered HTML
603 function common_linkify_mentions($text, $notice)
605 $mentions = common_find_mentions($text, $notice);
607 // We need to go through in reverse order by position,
608 // so our positions stay valid despite our fudging with the
613 foreach ($mentions as $mention)
615 $points[$mention['position']] = $mention;
620 foreach ($points as $position => $mention) {
622 $linkText = common_linkify_mention($mention);
624 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
630 function common_linkify_mention($mention)
634 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
636 $xs = new XMLStringer(false);
638 $attrs = array('href' => $mention['url'],
641 if (!empty($mention['title'])) {
642 $attrs['title'] = $mention['title'];
645 $xs->elementStart('span', 'vcard');
646 $xs->elementStart('a', $attrs);
647 $xs->element('span', 'fn nickname mention', $mention['text']);
648 $xs->elementEnd('a');
649 $xs->elementEnd('span');
651 $output = $xs->getString();
653 Event::handle('EndLinkifyMention', array($mention, &$output));
660 * Find @-mentions in the given text, using the given notice object as context.
661 * References will be resolved with common_relative_profile() against the user
662 * who posted the notice.
664 * Note the return data format is internal, to be used for building links and
665 * such. Should not be used directly; rather, call common_linkify_mentions().
667 * @param string $text
668 * @param Notice $notice notice in whose context we're building links
674 function common_find_mentions($text, $notice)
678 $sender = Profile::getKV('id', $notice->profile_id);
680 if (empty($sender)) {
684 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
685 // Get the context of the original notice, if any
686 $originalAuthor = null;
687 $originalNotice = null;
688 $originalMentions = array();
692 if (!empty($notice) && !empty($notice->reply_to)) {
693 $originalNotice = Notice::getKV('id', $notice->reply_to);
694 if (!empty($originalNotice)) {
695 $originalAuthor = Profile::getKV('id', $originalNotice->profile_id);
697 $ids = $originalNotice->getReplies();
699 foreach ($ids as $id) {
700 $repliedTo = Profile::getKV('id', $id);
701 if (!empty($repliedTo)) {
702 $originalMentions[$repliedTo->nickname] = $repliedTo;
708 $matches = common_find_mentions_raw($text);
710 foreach ($matches as $match) {
712 $nickname = Nickname::normalize($match[0]);
713 } catch (NicknameException $e) {
714 // Bogus match? Drop it.
718 // Try to get a profile for this nickname.
719 // Start with conversation context, then go to
722 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
723 $mentioned = $originalAuthor;
724 } else if (!empty($originalMentions) &&
725 array_key_exists($nickname, $originalMentions)) {
726 $mentioned = $originalMentions[$nickname];
728 $mentioned = common_relative_profile($sender, $nickname);
731 if (!empty($mentioned)) {
732 $user = User::getKV('id', $mentioned->id);
735 $url = common_local_url('userbyid', array('id' => $user->id));
737 $url = $mentioned->profileurl;
740 $mention = array('mentioned' => array($mentioned),
742 'position' => $match[1],
745 if (!empty($mentioned->fullname)) {
746 $mention['title'] = $mentioned->fullname;
749 $mentions[] = $mention;
753 // @#tag => mention of all subscriptions tagged 'tag'
755 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
758 PREG_OFFSET_CAPTURE);
760 foreach ($hmatches[1] as $hmatch) {
762 $tag = common_canonical_tag($hmatch[0]);
763 $plist = Profile_list::getByTaggerAndTag($sender->id, $tag);
764 if (!empty($plist) && !$plist->private) {
765 $tagged = $sender->getTaggedSubscribers($tag);
767 $url = common_local_url('showprofiletag',
768 array('tagger' => $sender->nickname,
771 $mentions[] = array('mentioned' => $tagged,
772 'text' => $hmatch[0],
773 'position' => $hmatch[1],
778 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
785 * Does the actual regex pulls to find @-mentions in text.
786 * Should generally not be called directly; for use in common_find_mentions.
788 * @param string $text
789 * @return array of PCRE match arrays
791 function common_find_mentions_raw($text)
794 preg_match_all('/^T (' . Nickname::DISPLAY_FMT . ') /',
797 PREG_OFFSET_CAPTURE);
799 $atmatches = array();
800 preg_match_all('/(?:^|\s+)@(' . Nickname::DISPLAY_FMT . ')\b/',
803 PREG_OFFSET_CAPTURE);
805 $matches = array_merge($tmatches[1], $atmatches[1]);
809 function common_render_text($text)
811 $r = htmlspecialchars($text);
813 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
814 $r = common_replace_urls_callback($r, 'common_linkify');
815 $r = preg_replace_callback('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/u',
816 function ($m) { return "{$m[1]}#".common_tag_link($m[2]); }, $r);
822 * Find links in the given text and pass them to the given callback function.
824 * @param string $text
825 * @param function($text, $arg) $callback: return replacement text
826 * @param mixed $arg: optional argument will be passed on to the callback
828 function common_replace_urls_callback($text, $callback, $arg = null) {
829 // Start off with a regex
831 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
834 '(?:'. //Known protocols
836 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
838 '(?:(?:mailto|aim|tel|xmpp):)'.
840 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
843 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
845 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
849 '|(?:(?: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
851 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
853 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
854 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
855 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
856 '(?: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)'.
860 '(?:\:\d+)?'. //:port
861 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
862 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
863 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
864 ')(?<![\?\.\,\#\,])'.
867 //preg_match_all($regex,$text,$matches);
869 return preg_replace_callback($regex, curry('callback_helper',$callback,$arg) ,$text);
873 * Intermediate callback for common_replace_links(), helps resolve some
874 * ambiguous link forms before passing on to the final callback.
876 * @param array $matches
877 * @param callable $callback
878 * @param mixed $arg optional argument to pass on as second param to callback
883 function callback_helper($matches, $callback, $arg=null) {
885 $left = strpos($matches[0],$url);
886 $right = $left+strlen($url);
888 $groupSymbolSets=array(
906 $cannotEndWith=array('.','?',',','#');
910 foreach($groupSymbolSets as $groupSymbolSet){
911 if(substr($url,-1)==$groupSymbolSet['right']){
912 $group_left_count = substr_count($url,$groupSymbolSet['left']);
913 $group_right_count = substr_count($url,$groupSymbolSet['right']);
914 if($group_left_count<$group_right_count){
916 $url=substr($url,0,-1);
920 if(in_array(substr($url,-1),$cannotEndWith)){
922 $url=substr($url,0,-1);
924 }while($original_url!=$url);
926 $result = call_user_func_array($callback, array($url, $arg));
927 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
930 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
931 // lambda implementation in a separate file; PHP 5.2 won't parse it.
932 require_once INSTALLDIR . "/lib/curry.php";
934 function curry($fn) {
935 $args = func_get_args();
937 $id = uniqid('_partial');
938 $GLOBALS[$id] = array($fn, $args);
939 return create_function('',
940 '$args = func_get_args(); '.
941 'return call_user_func_array('.
942 '$GLOBALS["'.$id.'"][0],'.
945 '$GLOBALS["'.$id.'"][1]));');
949 function common_linkify($url) {
950 // It comes in special'd, so we unspecial it before passing to the stringifying
952 $url = htmlspecialchars_decode($url);
954 if (strpos($url, '@') !== false && strpos($url, ':') === false && Validate::email($url)) {
955 //url is an email address without the mailto: protocol
956 $canon = "mailto:$url";
957 $longurl = "mailto:$url";
960 $canon = File_redirection::_canonUrl($url);
962 $longurl_data = File_redirection::where($canon, common_config('attachments', 'process_links'));
963 if (is_array($longurl_data)) {
964 $longurl = $longurl_data['url'];
965 } elseif (is_string($longurl_data)) {
966 $longurl = $longurl_data;
968 // Unable to reach the server to verify contents, etc
969 // Just pass the link on through for now.
970 common_log(LOG_ERR, "Can't linkify url '$url'");
975 $attrs = array('href' => $canon, 'title' => $longurl);
977 $is_attachment = false;
978 $attachment_id = null;
981 // Check to see whether this is a known "attachment" URL.
983 $f = File::getKV('url', $longurl);
986 if (common_config('attachments', 'process_links')) {
987 // XXX: this writes to the database. :<
988 $f = File::processNew($longurl);
993 if ($f->getEnclosure()) {
994 $is_attachment = true;
995 $attachment_id = $f->id;
997 $thumb = File_thumbnail::getKV('file_id', $f->id);
998 if (!empty($thumb)) {
1005 if ($is_attachment) {
1006 $attrs['class'] = 'attachment';
1008 $attrs['class'] = 'attachment thumbnail';
1010 $attrs['id'] = "attachment-{$attachment_id}";
1013 // Whether to nofollow
1015 $nf = common_config('nofollow', 'external');
1017 if ($nf == 'never') {
1018 $attrs['rel'] = 'external';
1020 $attrs['rel'] = 'nofollow external';
1023 return XMLStringer::estring('a', $attrs, $url);
1027 * Find and shorten links in a given chunk of text if it's longer than the
1028 * configured notice content limit (or unconditionally).
1030 * Side effects: may save file and file_redirection records for referenced URLs.
1032 * Pass the $user option or call $user->shortenLinks($text) to ensure the proper
1033 * user's options are used; otherwise the current web session user's setitngs
1034 * will be used or ur1.ca if there is no active web login.
1036 * @param string $text
1037 * @param boolean $always (optional)
1038 * @param User $user (optional)
1042 function common_shorten_links($text, $always = false, User $user=null)
1044 if ($user === null) {
1045 $user = common_current_user();
1048 $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
1050 if ($always || ($maxLength != -1 && mb_strlen($text) > $maxLength)) {
1051 return common_replace_urls_callback($text, array('File_redirection', 'forceShort'), $user);
1053 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'), $user);
1058 * Very basic stripping of invalid UTF-8 input text.
1060 * @param string $str
1061 * @return mixed string or null if invalid input
1063 * @todo ideally we should drop bad chars, and maybe do some of the checks
1064 * from common_xml_safe_str. But we can't strip newlines, etc.
1065 * @todo Unicode normalization might also be useful, but not needed now.
1067 function common_validate_utf8($str)
1069 // preg_replace will return NULL on invalid UTF-8 input.
1071 // Note: empty regex //u also caused NULL return on some
1072 // production machines, but none of our test machines.
1074 // This should be replaced with a more reliable check.
1075 return preg_replace('/\x00/u', '', $str);
1079 * Make sure an arbitrary string is safe for output in XML as a single line.
1081 * @param string $str
1084 function common_xml_safe_str($str)
1086 // Replace common eol and extra whitespace input chars
1091 "\0", // null byte eos
1092 "\x0B" // vertical tab
1095 $replacement = array(
1096 ' ', // single space
1103 $str = str_replace($unWelcome, $replacement, $str);
1105 // Neutralize any additional control codes and UTF-16 surrogates
1106 // (Twitter uses '*')
1107 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1110 function common_tag_link($tag)
1112 $canonical = common_canonical_tag($tag);
1113 if (common_config('singleuser', 'enabled')) {
1114 // regular TagAction isn't set up in 1user mode
1115 $nickname = User::singleUserNickname();
1116 $url = common_local_url('showstream',
1117 array('nickname' => $nickname,
1118 'tag' => $canonical));
1120 $url = common_local_url('tag', array('tag' => $canonical));
1122 $xs = new XMLStringer();
1123 $xs->elementStart('span', 'tag');
1124 $xs->element('a', array('href' => $url,
1127 $xs->elementEnd('span');
1128 return $xs->getString();
1131 function common_canonical_tag($tag)
1134 $tag = preg_replace('/[^\pL\pN]/u', '', $tag);
1135 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1136 $tag = substr($tag, 0, 64);
1140 function common_valid_profile_tag($str)
1142 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1147 * @param <type> $sender_id
1148 * @param <type> $nickname
1152 function common_group_link($sender_id, $nickname)
1154 $sender = Profile::getKV($sender_id);
1155 $group = User_group::getForNickname($nickname, $sender);
1156 if ($sender && $group && $sender->isMember($group)) {
1157 $attrs = array('href' => $group->permalink(),
1159 if (!empty($group->fullname)) {
1160 $attrs['title'] = $group->getFancyName();
1162 $xs = new XMLStringer();
1163 $xs->elementStart('span', 'vcard');
1164 $xs->elementStart('a', $attrs);
1165 $xs->element('span', 'fn nickname group', $nickname);
1166 $xs->elementEnd('a');
1167 $xs->elementEnd('span');
1168 return $xs->getString();
1175 * Resolve an ambiguous profile nickname reference, checking in following order:
1176 * - profiles that $sender subscribes to
1177 * - profiles that subscribe to $sender
1178 * - local user profiles
1180 * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED
1181 * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT
1184 * @fixme validate input
1186 * @fixme fix or remove mystery third parameter
1187 * @fixme is $sender a User or Profile?
1189 * @param <type> $sender the user or profile in whose context we're looking
1190 * @param string $nickname validated nickname of
1191 * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed.
1193 * @return Profile or null
1195 function common_relative_profile($sender, $nickname, $dt=null)
1197 // Will throw exception on invalid input.
1198 $nickname = Nickname::normalize($nickname);
1200 // Try to find profiles this profile is subscribed to that have this nickname
1201 $recipient = new Profile();
1202 // XXX: use a join instead of a subquery
1203 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.intval($sender->id).' and subscribed = id)', 'AND');
1204 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1205 if ($recipient->find(true)) {
1206 // XXX: should probably differentiate between profiles with
1207 // the same name by date of most recent update
1210 // Try to find profiles that listen to this profile and that have this nickname
1211 $recipient = new Profile();
1212 // XXX: use a join instead of a subquery
1213 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.intval($sender->id).' and subscriber = id)', 'AND');
1214 $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND');
1215 if ($recipient->find(true)) {
1216 // XXX: should probably differentiate between profiles with
1217 // the same name by date of most recent update
1220 // If this is a local user, try to find a local user with that nickname.
1221 $sender = User::getKV($sender->id);
1223 $recipient_user = User::getKV('nickname', $nickname);
1224 if ($recipient_user) {
1225 return $recipient_user->getProfile();
1228 // Otherwise, no links. @messages from local users to remote users,
1229 // or from remote users to other remote users, are just
1230 // outside our ability to make intelligent guesses about
1234 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1236 if (Event::handle('StartLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url))) {
1238 $path = $r->build($action, $args, $params, $fragment);
1240 $ssl = StatusNet::isHTTPS() || common_is_sensitive($action);
1242 if (common_config('site','fancy')) {
1243 $url = common_path($path, $ssl, $addSession);
1245 if (mb_strpos($path, '/index.php') === 0) {
1246 $url = common_path($path, $ssl, $addSession);
1248 $url = common_path('index.php/'.$path, $ssl, $addSession);
1251 Event::handle('EndLocalURL', array(&$action, &$params, &$fragment, &$addSession, &$url));
1256 function common_is_sensitive($action)
1258 static $sensitive = array(
1263 'ApiOAuthRequestToken',
1264 'ApiOAuthAccessToken',
1265 'ApiOAuthAuthorize',
1271 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1272 $ssl = in_array($action, $sensitive);
1278 function common_path($relative, $ssl=false, $addSession=true)
1280 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1282 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1283 || common_config('site', 'ssl') === 'always') {
1285 if (is_string(common_config('site', 'sslserver')) &&
1286 mb_strlen(common_config('site', 'sslserver')) > 0) {
1287 $serverpart = common_config('site', 'sslserver');
1288 } else if (common_config('site', 'server')) {
1289 $serverpart = common_config('site', 'server');
1291 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1295 if (common_config('site', 'server')) {
1296 $serverpart = common_config('site', 'server');
1298 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1303 $relative = common_inject_session($relative, $serverpart);
1306 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1309 function common_inject_session($url, $serverpart = null)
1311 if (common_have_session()) {
1313 if (empty($serverpart)) {
1314 $serverpart = parse_url($url, PHP_URL_HOST);
1317 $currentServer = (array_key_exists('HTTP_HOST', $_SERVER)) ? $_SERVER['HTTP_HOST'] : null;
1319 // Are we pointing to another server (like an SSL server?)
1321 if (!empty($currentServer) &&
1322 0 != strcasecmp($currentServer, $serverpart)) {
1323 // Pass the session ID as a GET parameter
1324 $sesspart = session_name() . '=' . session_id();
1325 $i = strpos($url, '?');
1326 if ($i === false) { // no GET params, just append
1327 $url .= '?' . $sesspart;
1329 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1337 function common_date_string($dt)
1339 // XXX: do some sexy date formatting
1340 // return date(DATE_RFC822, $dt);
1341 $t = strtotime($dt);
1345 if ($now < $t) { // that shouldn't happen!
1346 return common_exact_date($dt);
1347 } else if ($diff < 60) {
1348 // TRANS: Used in notices to indicate when the notice was made compared to now.
1349 return _('a few seconds ago');
1350 } else if ($diff < 92) {
1351 // TRANS: Used in notices to indicate when the notice was made compared to now.
1352 return _('about a minute ago');
1353 } else if ($diff < 3300) {
1354 $minutes = round($diff/60);
1355 // TRANS: Used in notices to indicate when the notice was made compared to now.
1356 return sprintf( _m('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1357 } else if ($diff < 5400) {
1358 // TRANS: Used in notices to indicate when the notice was made compared to now.
1359 return _('about an hour ago');
1360 } else if ($diff < 22 * 3600) {
1361 $hours = round($diff/3600);
1362 // TRANS: Used in notices to indicate when the notice was made compared to now.
1363 return sprintf( _m('about one hour ago', 'about %d hours ago', $hours), $hours);
1364 } else if ($diff < 37 * 3600) {
1365 // TRANS: Used in notices to indicate when the notice was made compared to now.
1366 return _('about a day ago');
1367 } else if ($diff < 24 * 24 * 3600) {
1368 $days = round($diff/(24*3600));
1369 // TRANS: Used in notices to indicate when the notice was made compared to now.
1370 return sprintf( _m('about one day ago', 'about %d days ago', $days), $days);
1371 } else if ($diff < 46 * 24 * 3600) {
1372 // TRANS: Used in notices to indicate when the notice was made compared to now.
1373 return _('about a month ago');
1374 } else if ($diff < 330 * 24 * 3600) {
1375 $months = round($diff/(30*24*3600));
1376 // TRANS: Used in notices to indicate when the notice was made compared to now.
1377 return sprintf( _m('about one month ago', 'about %d months ago',$months), $months);
1378 } else if ($diff < 480 * 24 * 3600) {
1379 // TRANS: Used in notices to indicate when the notice was made compared to now.
1380 return _('about a year ago');
1382 return common_exact_date($dt);
1386 function common_exact_date($dt)
1392 $_utc = new DateTimeZone('UTC');
1393 $_siteTz = new DateTimeZone(common_timezone());
1396 $dateStr = date('d F Y H:i:s', strtotime($dt));
1397 $d = new DateTime($dateStr, $_utc);
1398 $d->setTimezone($_siteTz);
1399 return $d->format(DATE_RFC850);
1402 function common_date_w3dtf($dt)
1404 $dateStr = date('d F Y H:i:s', strtotime($dt));
1405 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1406 $d->setTimezone(new DateTimeZone(common_timezone()));
1407 return $d->format(DATE_W3C);
1410 function common_date_rfc2822($dt)
1412 $dateStr = date('d F Y H:i:s', strtotime($dt));
1413 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1414 $d->setTimezone(new DateTimeZone(common_timezone()));
1415 return $d->format('r');
1418 function common_date_iso8601($dt)
1420 $dateStr = date('d F Y H:i:s', strtotime($dt));
1421 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1422 $d->setTimezone(new DateTimeZone(common_timezone()));
1423 return $d->format('c');
1426 function common_sql_now()
1428 return common_sql_date(time());
1431 function common_sql_date($datetime)
1433 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1437 * Return an SQL fragment to calculate an age-based weight from a given
1438 * timestamp or datetime column.
1440 * @param string $column name of field we're comparing against current time
1441 * @param integer $dropoff divisor for age in seconds before exponentiation
1442 * @return string SQL fragment
1444 function common_sql_weight($column, $dropoff)
1446 if (common_config('db', 'type') == 'pgsql') {
1447 // PostgreSQL doesn't support timestampdiff function.
1448 // @fixme will this use the right time zone?
1449 // @fixme does this handle cross-year subtraction correctly?
1450 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1452 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1456 function common_redirect($url, $code=307)
1458 static $status = array(301 => "Moved Permanently",
1461 307 => "Temporary Redirect");
1463 header('HTTP/1.1 '.$code.' '.$status[$code]);
1464 header("Location: $url");
1465 header("Connection: close");
1467 $xo = new XMLOutputter();
1469 '-//W3C//DTD XHTML 1.0 Strict//EN',
1470 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1471 $xo->element('a', array('href' => $url), $url);
1476 // Stick the notice on the queue
1478 function common_enqueue_notice($notice)
1480 static $localTransports = array('ping');
1482 $transports = array();
1483 if (common_config('sms', 'enabled')) {
1484 $transports[] = 'sms';
1486 if (Event::hasHandler('HandleQueuedNotice')) {
1487 $transports[] = 'plugin';
1490 // We can skip these for gatewayed notices.
1491 if ($notice->isLocal()) {
1492 $transports = array_merge($transports, $localTransports);
1495 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1497 $qm = QueueManager::get();
1499 foreach ($transports as $transport)
1501 $qm->enqueue($notice, $transport);
1504 Event::handle('EndEnqueueNotice', array($notice, $transports));
1511 * Legacy function to broadcast profile updates to OMB remote subscribers.
1513 * XXX: This probably needs killing, but there are several bits of code
1514 * that broadcast profile changes that need to be dealt with. AFAIK
1515 * this function is only used for OMB. -z
1517 * Since this may be slow with a lot of subscribers or bad remote sites,
1518 * this is run through the background queues if possible.
1520 function common_broadcast_profile(Profile $profile)
1522 Event::handle('BroadcastProfile', array($profile));
1525 function common_profile_url($nickname)
1527 return common_local_url('showstream', array('nickname' => $nickname),
1532 * Should make up a reasonable root URL
1534 function common_root_url($ssl=false)
1536 $url = common_path('', $ssl, false);
1537 $i = strpos($url, '?');
1539 $url = substr($url, 0, $i);
1545 * returns $bytes bytes of random data as a hexadecimal string
1546 * "good" here is a goal and not a guarantee
1548 function common_good_rand($bytes)
1550 // XXX: use random.org...?
1551 if (@file_exists('/dev/urandom')) {
1552 return common_urandom($bytes);
1553 } else { // FIXME: this is probably not good enough
1554 return common_mtrand($bytes);
1558 function common_urandom($bytes)
1560 $h = fopen('/dev/urandom', 'rb');
1562 $src = fread($h, $bytes);
1565 for ($i = 0; $i < $bytes; $i++) {
1566 $enc .= sprintf("%02x", (ord($src[$i])));
1571 function common_mtrand($bytes)
1574 for ($i = 0; $i < $bytes; $i++) {
1575 $enc .= sprintf("%02x", mt_rand(0, 255));
1581 * Record the given URL as the return destination for a future
1582 * form submission, to be read by common_get_returnto().
1584 * @param string $url
1586 * @fixme as a session-global setting, this can allow multiple forms
1587 * to conflict and overwrite each others' returnto destinations if
1588 * the user has multiple tabs or windows open.
1590 * Should refactor to index with a token or otherwise only pass the
1591 * data along its intended path.
1593 function common_set_returnto($url)
1595 common_ensure_session();
1596 $_SESSION['returnto'] = $url;
1600 * Fetch a return-destination URL previously recorded by
1601 * common_set_returnto().
1603 * @return mixed URL string or null
1605 * @fixme as a session-global setting, this can allow multiple forms
1606 * to conflict and overwrite each others' returnto destinations if
1607 * the user has multiple tabs or windows open.
1609 * Should refactor to index with a token or otherwise only pass the
1610 * data along its intended path.
1612 function common_get_returnto()
1614 common_ensure_session();
1615 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1618 function common_timestamp()
1620 return date('YmdHis');
1623 function common_ensure_syslog()
1625 static $initialized = false;
1626 if (!$initialized) {
1627 openlog(common_config('syslog', 'appname'), 0,
1628 common_config('syslog', 'facility'));
1629 $initialized = true;
1633 function common_log_line($priority, $msg)
1635 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1636 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1637 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1640 function common_request_id()
1643 $server = common_config('site', 'server');
1644 if (php_sapi_name() == 'cli') {
1645 $script = basename($_SERVER['PHP_SELF']);
1646 return "$server:$script:$pid";
1648 static $req_id = null;
1649 if (!isset($req_id)) {
1650 $req_id = substr(md5(mt_rand()), 0, 8);
1652 if (isset($_SERVER['REQUEST_URI'])) {
1653 $url = $_SERVER['REQUEST_URI'];
1655 $method = $_SERVER['REQUEST_METHOD'];
1656 return "$server:$pid.$req_id $method $url";
1660 function common_log($priority, $msg, $filename=null)
1662 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1663 $msg = (empty($filename)) ? $msg : basename($filename) . ' - ' . $msg;
1664 $msg = '[' . common_request_id() . '] ' . $msg;
1665 $logfile = common_config('site', 'logfile');
1667 $log = fopen($logfile, "a");
1669 $output = common_log_line($priority, $msg);
1670 fwrite($log, $output);
1674 common_ensure_syslog();
1675 syslog($priority, $msg);
1677 Event::handle('EndLog', array($priority, $msg, $filename));
1681 function common_debug($msg, $filename=null)
1684 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1686 common_log(LOG_DEBUG, $msg);
1690 function common_log_db_error(&$object, $verb, $filename=null)
1692 $objstr = common_log_objstring($object);
1693 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1694 if (is_object($last_error)) {
1695 $msg = $last_error->message;
1697 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1699 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1702 function common_log_objstring(&$object)
1704 if (is_null($object)) {
1707 if (!($object instanceof DB_DataObject)) {
1710 $arr = $object->toArray();
1712 foreach ($arr as $k => $v) {
1713 if (is_object($v)) {
1714 $fields[] = "$k='".get_class($v)."'";
1716 $fields[] = "$k='$v'";
1719 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1723 function common_valid_http_url($url, $secure=false)
1725 // If $secure is true, only allow https URLs to pass
1726 // (if false, we use '?' in 'https?' to say the 's' is optional)
1727 $regex = $secure ? '/^https$/' : '/^https?$/';
1728 return filter_var($url, FILTER_VALIDATE_URL)
1729 && preg_match($regex, parse_url($url, PHP_URL_SCHEME));
1732 function common_valid_tag($tag)
1734 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1735 return (Validate::email($matches[1]) ||
1736 preg_match('/^([\w-\.]+)$/', $matches[1]));
1742 * Determine if given domain or address literal is valid
1743 * eg for use in JIDs and URLs. Does not check if the domain
1746 * @param string $domain
1747 * @return boolean valid or not
1749 function common_valid_domain($domain)
1751 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1752 $ipv4 = "(?:$octet(?:\.$octet){3})";
1753 if (preg_match("/^$ipv4$/u", $domain)) return true;
1755 $group = "(?:[0-9a-f]{1,4})";
1756 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1758 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1759 $before = explode(":", $matches[1]);
1760 $zeroes = $matches[2];
1761 $after = explode(":", $matches[3]);
1769 $explicit = count($before) + count($after);
1770 if ($explicit < $min || $explicit > $max) {
1777 require_once "Net/IDNA.php";
1778 $idn = Net_IDNA::getInstance();
1779 $domain = $idn->encode($domain);
1780 } catch (Exception $e) {
1784 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1785 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1787 return preg_match("/^$fqdn$/ui", $domain);
1790 /* Following functions are copied from MediaWiki GlobalFunctions.php
1791 * and written by Evan Prodromou. */
1793 function common_accept_to_prefs($accept, $def = '*/*')
1795 // No arg means accept anything (per HTTP spec)
1797 return array($def => 1);
1802 $parts = explode(',', $accept);
1804 foreach($parts as $part) {
1805 // FIXME: doesn't deal with params like 'text/html; level=1'
1806 @list($value, $qpart) = explode(';', trim($part));
1808 if(!isset($qpart)) {
1810 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1811 $prefs[$value] = $match[1];
1818 function common_mime_type_match($type, $avail)
1820 if(array_key_exists($type, $avail)) {
1823 $parts = explode('/', $type);
1824 if(array_key_exists($parts[0] . '/*', $avail)) {
1825 return $parts[0] . '/*';
1826 } elseif(array_key_exists('*/*', $avail)) {
1834 function common_negotiate_type($cprefs, $sprefs)
1838 foreach(array_keys($sprefs) as $type) {
1839 $parts = explode('/', $type);
1840 if($parts[1] != '*') {
1841 $ckey = common_mime_type_match($type, $cprefs);
1843 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1848 foreach(array_keys($cprefs) as $type) {
1849 $parts = explode('/', $type);
1850 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1851 $skey = common_mime_type_match($type, $sprefs);
1853 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1859 $besttype = 'text/html';
1861 foreach(array_keys($combine) as $type) {
1862 if($combine[$type] > $bestq) {
1864 $bestq = $combine[$type];
1868 if ('text/html' === $besttype) {
1869 return "text/html; charset=utf-8";
1874 function common_config($main, $sub)
1877 return (array_key_exists($main, $config) &&
1878 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1881 function common_config_set($main, $sub, $value)
1884 if (!array_key_exists($main, $config)) {
1885 $config[$main] = array();
1887 $config[$main][$sub] = $value;
1890 function common_config_append($main, $sub, $value)
1893 if (!array_key_exists($main, $config)) {
1894 $config[$main] = array();
1896 if (!array_key_exists($sub, $config[$main])) {
1897 $config[$main][$sub] = array();
1899 if (!is_array($config[$main][$sub])) {
1900 $config[$main][$sub] = array($config[$main][$sub]);
1902 array_push($config[$main][$sub], $value);
1906 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1907 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1909 * @param array $from
1912 function common_copy_args($from)
1915 $strip = get_magic_quotes_gpc();
1916 foreach ($from as $k => $v) {
1918 $to[$k] = common_copy_args($v);
1921 $v = stripslashes($v);
1923 $to[$k] = strval(common_validate_utf8($v));
1930 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1931 * This is used before handing a request off to OAuthRequest::from_request.
1932 * @fixme Doesn't consider vars other than _POST and _GET?
1933 * @fixme Can't be undone and could corrupt data if run twice.
1935 function common_remove_magic_from_request()
1937 if(get_magic_quotes_gpc()) {
1938 $_POST=array_map('stripslashes',$_POST);
1939 $_GET=array_map('stripslashes',$_GET);
1943 function common_user_uri(&$user)
1945 return common_local_url('userbyid', array('id' => $user->id),
1949 function common_notice_uri(&$notice)
1951 return common_local_url('shownotice',
1952 array('notice' => $notice->id),
1956 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1958 function common_confirmation_code($bits)
1960 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1961 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1962 $chars = ceil($bits/5);
1964 for ($i = 0; $i < $chars; $i++) {
1965 // XXX: convert to string and back
1966 $num = hexdec(common_good_rand(1));
1967 // XXX: randomness is too precious to throw away almost
1968 // 40% of the bits we get!
1969 $code .= $codechars[$num%32];
1974 // convert markup to HTML
1976 function common_markup_to_html($c, $args=null)
1978 if (is_null($args)) {
1982 // XXX: not very efficient
1984 foreach ($args as $name => $value) {
1985 $c = preg_replace('/%%arg.'.$name.'%%/', $value, $c);
1988 $c = preg_replace_callback('/%%user.(\w+)%%/', function ($m) { return common_user_property($m[1]); }, $c);
1989 $c = preg_replace_callback('/%%action.(\w+)%%/', function ($m) { return common_local_url($m[1]); }, $c);
1990 $c = preg_replace_callback('/%%doc.(\w+)%%/', function ($m) { return common_local_url('doc', array('title'=>$m[1])); }, $c);
1991 $c = preg_replace_callback('/%%(\w+).(\w+)%%/', function ($m) { return common_config($m[1], $m[2]); }, $c);
1992 return Markdown($c);
1995 function common_user_property($property)
1997 $profile = Profile::current();
1999 if (empty($profile)) {
2003 switch ($property) {
2009 return $profile->$property;
2013 return $profile->getAvatar(AVATAR_STREAM_SIZE);
2014 } catch (Exception $e) {
2019 return $profile->getBestName();
2026 function common_profile_uri($profile)
2030 if (!empty($profile)) {
2031 if (Event::handle('StartCommonProfileURI', array($profile, &$uri))) {
2032 $user = User::getKV($profile->id);
2033 if (!empty($user)) {
2036 Event::handle('EndCommonProfileURI', array($profile, &$uri));
2040 // XXX: this is a very bad profile!
2044 function common_canonical_sms($sms)
2047 preg_replace('/\D/', '', $sms);
2051 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
2056 case E_COMPILE_ERROR:
2060 case E_RECOVERABLE_ERROR:
2061 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
2066 case E_COMPILE_WARNING:
2067 case E_CORE_WARNING:
2068 case E_USER_WARNING:
2069 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
2074 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
2079 case E_USER_DEPRECATED:
2080 // XXX: config variable to log this stuff, too
2084 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
2089 // FIXME: show error page if we're on the Web
2090 /* Don't execute PHP internal error handler */
2094 function common_session_token()
2096 common_ensure_session();
2097 if (!array_key_exists('token', $_SESSION)) {
2098 $_SESSION['token'] = common_good_rand(64);
2100 return $_SESSION['token'];
2103 function common_license_terms($uri)
2105 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
2106 return explode('-',$matches[1]);
2111 function common_compatible_license($from, $to)
2113 $from_terms = common_license_terms($from);
2114 // public domain and cc-by are compatible with everything
2115 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
2118 $to_terms = common_license_terms($to);
2119 // sa is compatible across versions. IANAL
2120 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
2121 return count(array_diff($from_terms, $to_terms)) == 0;
2123 // XXX: better compatibility check needed here!
2124 // Should at least normalise URIs
2125 return ($from == $to);
2129 * returns a quoted table name, if required according to config
2131 function common_database_tablename($tablename)
2133 if(common_config('db','quote_identifiers')) {
2134 $tablename = '"'. $tablename .'"';
2136 //table prefixes could be added here later
2141 * Shorten a URL with the current user's configured shortening service,
2142 * or ur1.ca if configured, or not at all if no shortening is set up.
2144 * @param string $long_url original URL
2145 * @param User $user to specify a particular user's options
2146 * @param boolean $force Force shortening (used when notice is too long)
2147 * @return string may return the original URL if shortening failed
2149 * @fixme provide a way to specify a particular shortener
2151 function common_shorten_url($long_url, User $user=null, $force = false)
2153 $long_url = trim($long_url);
2155 $user = common_current_user();
2157 $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
2159 // $force forces shortening even if it's not strictly needed
2160 // I doubt URL shortening is ever 'strictly' needed. - ESP
2162 if (($maxUrlLength == -1 || mb_strlen($long_url) < $maxUrlLength) && !$force) {
2166 $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
2168 if (Event::handle('StartShortenUrl',
2169 array($long_url, $shortenerName, &$shortenedUrl))) {
2170 if ($shortenerName == 'internal') {
2171 $f = File::processNew($long_url);
2175 $shortenedUrl = common_local_url('redirecturl',
2176 array('id' => $f->id));
2177 if ((mb_strlen($shortenedUrl) < mb_strlen($long_url)) || $force) {
2178 return $shortenedUrl;
2187 //URL was shortened, so return the result
2188 return trim($shortenedUrl);
2193 * @return mixed array($proxy, $ip) for web requests; proxy may be null
2194 * null if not a web request
2196 * @fixme X-Forwarded-For can be chained by multiple proxies;
2197 we should parse the list and provide a cleaner array
2198 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
2199 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
2200 * use function to get exact request headers from Apache if possible.
2202 function common_client_ip()
2204 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
2208 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
2209 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2210 $proxy = $_SERVER['HTTP_CLIENT_IP'];
2212 $proxy = $_SERVER['REMOTE_ADDR'];
2214 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
2217 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
2218 $ip = $_SERVER['HTTP_CLIENT_IP'];
2220 $ip = $_SERVER['REMOTE_ADDR'];
2224 return array($proxy, $ip);
2227 function common_url_to_nickname($url)
2229 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2231 $parts = parse_url($url);
2233 // If any of these parts exist, this won't work
2235 foreach ($bad as $badpart) {
2236 if (array_key_exists($badpart, $parts)) {
2241 // We just have host and/or path
2243 // If it's just a host...
2244 if (array_key_exists('host', $parts) &&
2245 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2247 $hostparts = explode('.', $parts['host']);
2249 // Try to catch common idiom of nickname.service.tld
2251 if ((count($hostparts) > 2) &&
2252 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2253 (strcmp($hostparts[0], 'www') != 0))
2255 return common_nicknamize($hostparts[0]);
2257 // Do the whole hostname
2258 return common_nicknamize($parts['host']);
2261 if (array_key_exists('path', $parts)) {
2262 // Strip starting, ending slashes
2263 $path = preg_replace('@/$@', '', $parts['path']);
2264 $path = preg_replace('@^/@', '', $path);
2265 $path = basename($path);
2267 // Hack for MediaWiki user pages, in the form:
2268 // http://example.com/wiki/User:Myname
2269 // ('User' may be localized.)
2270 if (strpos($path, ':')) {
2271 $parts = array_filter(explode(':', $path));
2272 $path = $parts[count($parts) - 1];
2276 return common_nicknamize($path);
2284 function common_nicknamize($str)
2286 $str = preg_replace('/\W/', '', $str);
2287 return strtolower($str);
2290 function common_perf_counter($key, $val=null)
2292 global $_perfCounters;
2293 if (isset($_perfCounters)) {
2294 if (common_config('site', 'logperf')) {
2295 if (array_key_exists($key, $_perfCounters)) {
2296 $_perfCounters[$key][] = $val;
2298 $_perfCounters[$key] = array($val);
2300 if (common_config('site', 'logperf_detail')) {
2301 common_log(LOG_DEBUG, "PERF COUNTER HIT: $key $val");
2307 function common_log_perf_counters()
2309 if (common_config('site', 'logperf')) {
2310 global $_startTime, $_perfCounters;
2312 if (isset($_startTime)) {
2313 $endTime = microtime(true);
2314 $diff = round(($endTime - $_startTime) * 1000);
2315 common_log(LOG_DEBUG, "PERF runtime: ${diff}ms");
2317 $counters = $_perfCounters;
2319 foreach ($counters as $key => $values) {
2320 $count = count($values);
2321 $unique = count(array_unique($values));
2322 common_log(LOG_DEBUG, "PERF COUNTER: $key $count ($unique unique)");
2327 function common_is_email($str)
2329 return (strpos($str, '@') !== false);
2332 function common_init_stats()
2336 $_mem = memory_get_usage(true);
2337 $_ts = microtime(true);
2340 function common_log_delta($comment=null)
2347 $_mem = memory_get_usage(true);
2348 $_ts = microtime(true);
2350 $mtotal = $_mem - $mold;
2351 $ttotal = $_ts - $told;
2353 if (empty($comment)) {
2357 common_debug(sprintf("%s: %d %d", $comment, $mtotal, round($ttotal * 1000000)));