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 common_ensure_session();
305 $_SESSION['userid'] = $user->id;
307 Event::handle('EndSetUser', array($user));
315 function common_set_cookie($key, $value, $expiration=0)
317 $path = common_config('site', 'path');
318 $server = common_config('site', 'server');
320 if ($path && ($path != '/')) {
321 $cookiepath = '/' . $path . '/';
325 return setcookie($key,
332 define('REMEMBERME', 'rememberme');
333 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
335 function common_rememberme($user=null)
338 $user = common_current_user();
344 $rm = new Remember_me();
346 $rm->code = common_good_rand(16);
347 $rm->user_id = $user->id;
349 // Wrap the insert in some good ol' fashioned transaction code
353 $result = $rm->insert();
356 common_log_db_error($rm, 'INSERT', __FILE__);
360 $rm->query('COMMIT');
362 $cookieval = $rm->user_id . ':' . $rm->code;
364 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
366 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
371 function common_remembered_user()
375 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
381 list($id, $code) = explode(':', $packed);
383 if (!$id || !$code) {
384 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
389 $rm = Remember_me::staticGet($code);
392 common_log(LOG_WARNING, 'No such remember code: ' . $code);
397 if ($rm->user_id != $id) {
398 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
403 $user = User::staticGet($rm->user_id);
406 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
412 $result = $rm->delete();
415 common_log_db_error($rm, 'DELETE', __FILE__);
416 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
421 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
423 common_set_user($user);
424 common_real_login(false);
426 // We issue a new cookie, so they can log in
427 // automatically again after this session
429 common_rememberme($user);
435 * must be called with a valid user!
437 function common_forgetme()
439 common_set_cookie(REMEMBERME, '', 0);
443 * Who is the current user?
445 function common_current_user()
449 if (!_have_config()) {
453 if ($_cur === false) {
455 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
456 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
457 common_ensure_session();
458 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
460 $user = User::staticGet($id);
468 // that didn't work; try to remember; will init $_cur to null on failure
469 $_cur = common_remembered_user();
472 // XXX: Is this necessary?
473 $_SESSION['userid'] = $_cur->id;
481 * Logins that are 'remembered' aren't 'real' -- they're subject to
482 * cookie-stealing. So, we don't let them do certain things. New reg,
483 * OpenID, and password logins _are_ real.
485 function common_real_login($real=true)
487 common_ensure_session();
488 $_SESSION['real_login'] = $real;
491 function common_is_real_login()
493 return common_logged_in() && $_SESSION['real_login'];
497 * Get a hash portion for HTTP caching Etags and such including
498 * info on the current user's session. If login/logout state changes,
499 * or we've changed accounts, or we've renamed the current user,
500 * we'll get a new hash value.
502 * This should not be considered secure information.
504 * @param User $user (optional; uses common_current_user() if left out)
507 function common_user_cache_hash($user=false)
509 if ($user === false) {
510 $user = common_current_user();
513 return crc32($user->id . ':' . $user->nickname);
519 // get canonical version of nickname for comparison
520 function common_canonical_nickname($nickname)
522 // XXX: UTF-8 canonicalization (like combining chars)
523 return strtolower($nickname);
526 // get canonical version of email for comparison
527 function common_canonical_email($email)
529 // XXX: canonicalize UTF-8
530 // XXX: lcase the domain part
534 function common_render_content($text, $notice)
536 $r = common_render_text($text);
537 $id = $notice->profile_id;
538 $r = common_linkify_mentions($r, $notice);
539 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
543 function common_linkify_mentions($text, $notice)
545 $mentions = common_find_mentions($text, $notice);
547 // We need to go through in reverse order by position,
548 // so our positions stay valid despite our fudging with the
553 foreach ($mentions as $mention)
555 $points[$mention['position']] = $mention;
560 foreach ($points as $position => $mention) {
562 $linkText = common_linkify_mention($mention);
564 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
570 function common_linkify_mention($mention)
574 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
576 $xs = new XMLStringer(false);
578 $attrs = array('href' => $mention['url'],
581 if (!empty($mention['title'])) {
582 $attrs['title'] = $mention['title'];
585 $xs->elementStart('span', 'vcard');
586 $xs->elementStart('a', $attrs);
587 $xs->element('span', 'fn nickname', $mention['text']);
588 $xs->elementEnd('a');
589 $xs->elementEnd('span');
591 $output = $xs->getString();
593 Event::handle('EndLinkifyMention', array($mention, &$output));
599 function common_find_mentions($text, $notice)
603 $sender = Profile::staticGet('id', $notice->profile_id);
605 if (empty($sender)) {
609 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
610 // Get the context of the original notice, if any
611 $originalAuthor = null;
612 $originalNotice = null;
613 $originalMentions = array();
617 if (!empty($notice) && !empty($notice->reply_to)) {
618 $originalNotice = Notice::staticGet('id', $notice->reply_to);
619 if (!empty($originalNotice)) {
620 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
622 $ids = $originalNotice->getReplies();
624 foreach ($ids as $id) {
625 $repliedTo = Profile::staticGet('id', $id);
626 if (!empty($repliedTo)) {
627 $originalMentions[$repliedTo->nickname] = $repliedTo;
633 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
636 PREG_OFFSET_CAPTURE);
638 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
641 PREG_OFFSET_CAPTURE);
643 $matches = array_merge($tmatches[1], $atmatches[1]);
645 foreach ($matches as $match) {
646 $nickname = common_canonical_nickname($match[0]);
648 // Try to get a profile for this nickname.
649 // Start with conversation context, then go to
652 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
653 $mentioned = $originalAuthor;
654 } else if (!empty($originalMentions) &&
655 array_key_exists($nickname, $originalMentions)) {
656 $mentioned = $originalMentions[$nickname];
658 $mentioned = common_relative_profile($sender, $nickname);
661 if (!empty($mentioned)) {
662 $user = User::staticGet('id', $mentioned->id);
665 $url = common_local_url('userbyid', array('id' => $user->id));
667 $url = $mentioned->profileurl;
670 $mention = array('mentioned' => array($mentioned),
672 'position' => $match[1],
675 if (!empty($mentioned->fullname)) {
676 $mention['title'] = $mentioned->fullname;
679 $mentions[] = $mention;
683 // @#tag => mention of all subscriptions tagged 'tag'
685 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
688 PREG_OFFSET_CAPTURE);
690 foreach ($hmatches[1] as $hmatch) {
692 $tag = common_canonical_tag($hmatch[0]);
694 $tagged = Profile_tag::getTagged($sender->id, $tag);
696 $url = common_local_url('subscriptions',
697 array('nickname' => $sender->nickname,
700 $mentions[] = array('mentioned' => $tagged,
701 'text' => $hmatch[0],
702 'position' => $hmatch[1],
706 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
712 function common_render_text($text)
714 $r = htmlspecialchars($text);
716 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
717 $r = common_replace_urls_callback($r, 'common_linkify');
718 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
723 function common_replace_urls_callback($text, $callback, $notice_id = null) {
724 // Start off with a regex
726 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
729 '(?:'. //Known protocols
731 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
733 '(?:(?:mailto|aim|tel|xmpp):)'.
735 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
738 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
740 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
744 '|(?:(?: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
746 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
748 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
749 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
750 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
751 '(?: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)'.
755 '(?:\:\d+)?'. //:port
756 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
757 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
758 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
759 ')(?<![\?\.\,\#\,])'.
762 //preg_match_all($regex,$text,$matches);
764 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
767 function callback_helper($matches, $callback, $notice_id) {
769 $left = strpos($matches[0],$url);
770 $right = $left+strlen($url);
772 $groupSymbolSets=array(
790 $cannotEndWith=array('.','?',',','#');
794 foreach($groupSymbolSets as $groupSymbolSet){
795 if(substr($url,-1)==$groupSymbolSet['right']){
796 $group_left_count = substr_count($url,$groupSymbolSet['left']);
797 $group_right_count = substr_count($url,$groupSymbolSet['right']);
798 if($group_left_count<$group_right_count){
800 $url=substr($url,0,-1);
804 if(in_array(substr($url,-1),$cannotEndWith)){
806 $url=substr($url,0,-1);
808 }while($original_url!=$url);
810 if(empty($notice_id)){
811 $result = call_user_func_array($callback, array($url));
813 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
815 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
818 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
819 // lambda implementation in a separate file; PHP 5.2 won't parse it.
820 require_once INSTALLDIR . "/lib/curry.php";
822 function curry($fn) {
823 $args = func_get_args();
825 $id = uniqid('_partial');
826 $GLOBALS[$id] = array($fn, $args);
827 return create_function('',
828 '$args = func_get_args(); '.
829 'return call_user_func_array('.
830 '$GLOBALS["'.$id.'"][0],'.
833 '$GLOBALS["'.$id.'"][1]));');
837 function common_linkify($url) {
838 // It comes in special'd, so we unspecial it before passing to the stringifying
840 $url = htmlspecialchars_decode($url);
842 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
843 //url is an email address without the mailto: protocol
844 $canon = "mailto:$url";
845 $longurl = "mailto:$url";
848 $canon = File_redirection::_canonUrl($url);
850 $longurl_data = File_redirection::where($canon);
851 if (is_array($longurl_data)) {
852 $longurl = $longurl_data['url'];
853 } elseif (is_string($longurl_data)) {
854 $longurl = $longurl_data;
856 // Unable to reach the server to verify contents, etc
857 // Just pass the link on through for now.
858 common_log(LOG_ERR, "Can't linkify url '$url'");
863 $attrs = array('href' => $canon, 'title' => $longurl);
865 $is_attachment = false;
866 $attachment_id = null;
869 // Check to see whether this is a known "attachment" URL.
871 $f = File::staticGet('url', $longurl);
874 // XXX: this writes to the database. :<
875 $f = File::processNew($longurl);
879 if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
880 $is_attachment = true;
881 $attachment_id = $f->id;
883 $thumb = File_thumbnail::staticGet('file_id', $f->id);
884 if (!empty($thumb)) {
891 if ($is_attachment) {
892 $attrs['class'] = 'attachment';
894 $attrs['class'] = 'attachment thumbnail';
896 $attrs['id'] = "attachment-{$attachment_id}";
899 // Whether to nofollow
901 $nf = common_config('nofollow', 'external');
903 if ($nf == 'never') {
904 $attrs['rel'] = 'external';
906 $attrs['rel'] = 'nofollow external';
909 return XMLStringer::estring('a', $attrs, $url);
912 function common_shorten_links($text, $always = false)
914 $maxLength = Notice::maxContent();
915 if (!$always && ($maxLength == 0 || mb_strlen($text) <= $maxLength)) return $text;
916 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
920 * Very basic stripping of invalid UTF-8 input text.
923 * @return mixed string or null if invalid input
925 * @todo ideally we should drop bad chars, and maybe do some of the checks
926 * from common_xml_safe_str. But we can't strip newlines, etc.
927 * @todo Unicode normalization might also be useful, but not needed now.
929 function common_validate_utf8($str)
931 // preg_replace will return NULL on invalid UTF-8 input.
933 // Note: empty regex //u also caused NULL return on some
934 // production machines, but none of our test machines.
936 // This should be replaced with a more reliable check.
937 return preg_replace('/\x00/u', '', $str);
941 * Make sure an arbitrary string is safe for output in XML as a single line.
946 function common_xml_safe_str($str)
948 // Replace common eol and extra whitespace input chars
953 "\0", // null byte eos
954 "\x0B" // vertical tab
957 $replacement = array(
965 $str = str_replace($unWelcome, $replacement, $str);
967 // Neutralize any additional control codes and UTF-16 surrogates
968 // (Twitter uses '*')
969 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
972 function common_tag_link($tag)
974 $canonical = common_canonical_tag($tag);
975 if (common_config('singleuser', 'enabled')) {
976 // regular TagAction isn't set up in 1user mode
977 $user = User::singleUser();
978 $url = common_local_url('showstream',
979 array('nickname' => $user->nickname,
980 'tag' => $canonical));
982 $url = common_local_url('tag', array('tag' => $canonical));
984 $xs = new XMLStringer();
985 $xs->elementStart('span', 'tag');
986 $xs->element('a', array('href' => $url,
989 $xs->elementEnd('span');
990 return $xs->getString();
993 function common_canonical_tag($tag)
995 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
996 return str_replace(array('-', '_', '.'), '', $tag);
999 function common_valid_profile_tag($str)
1001 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1004 function common_group_link($sender_id, $nickname)
1006 $sender = Profile::staticGet($sender_id);
1007 $group = User_group::getForNickname($nickname, $sender);
1008 if ($sender && $group && $sender->isMember($group)) {
1009 $attrs = array('href' => $group->permalink(),
1011 if (!empty($group->fullname)) {
1012 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
1014 $xs = new XMLStringer();
1015 $xs->elementStart('span', 'vcard');
1016 $xs->elementStart('a', $attrs);
1017 $xs->element('span', 'fn nickname', $nickname);
1018 $xs->elementEnd('a');
1019 $xs->elementEnd('span');
1020 return $xs->getString();
1026 function common_relative_profile($sender, $nickname, $dt=null)
1028 // Try to find profiles this profile is subscribed to that have this nickname
1029 $recipient = new Profile();
1030 // XXX: use a join instead of a subquery
1031 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
1032 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1033 if ($recipient->find(true)) {
1034 // XXX: should probably differentiate between profiles with
1035 // the same name by date of most recent update
1038 // Try to find profiles that listen to this profile and that have this nickname
1039 $recipient = new Profile();
1040 // XXX: use a join instead of a subquery
1041 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1042 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1043 if ($recipient->find(true)) {
1044 // XXX: should probably differentiate between profiles with
1045 // the same name by date of most recent update
1048 // If this is a local user, try to find a local user with that nickname.
1049 $sender = User::staticGet($sender->id);
1051 $recipient_user = User::staticGet('nickname', $nickname);
1052 if ($recipient_user) {
1053 return $recipient_user->getProfile();
1056 // Otherwise, no links. @messages from local users to remote users,
1057 // or from remote users to other remote users, are just
1058 // outside our ability to make intelligent guesses about
1062 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1065 $path = $r->build($action, $args, $params, $fragment);
1067 $ssl = common_is_sensitive($action);
1069 if (common_config('site','fancy')) {
1070 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1072 if (mb_strpos($path, '/index.php') === 0) {
1073 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1075 $url = common_path('index.php'.$path, $ssl, $addSession);
1081 function common_is_sensitive($action)
1083 static $sensitive = array(
1088 'ApiOauthRequestToken',
1089 'ApiOauthAccessToken',
1090 'ApiOauthAuthorize',
1096 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1097 $ssl = in_array($action, $sensitive);
1103 function common_path($relative, $ssl=false, $addSession=true)
1105 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1107 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1108 || common_config('site', 'ssl') === 'always') {
1110 if (is_string(common_config('site', 'sslserver')) &&
1111 mb_strlen(common_config('site', 'sslserver')) > 0) {
1112 $serverpart = common_config('site', 'sslserver');
1113 } else if (common_config('site', 'server')) {
1114 $serverpart = common_config('site', 'server');
1116 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1120 if (common_config('site', 'server')) {
1121 $serverpart = common_config('site', 'server');
1123 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1128 $relative = common_inject_session($relative, $serverpart);
1131 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1134 function common_inject_session($url, $serverpart = null)
1136 if (common_have_session()) {
1138 if (empty($serverpart)) {
1139 $serverpart = parse_url($url, PHP_URL_HOST);
1142 $currentServer = $_SERVER['HTTP_HOST'];
1144 // Are we pointing to another server (like an SSL server?)
1146 if (!empty($currentServer) &&
1147 0 != strcasecmp($currentServer, $serverpart)) {
1148 // Pass the session ID as a GET parameter
1149 $sesspart = session_name() . '=' . session_id();
1150 $i = strpos($url, '?');
1151 if ($i === false) { // no GET params, just append
1152 $url .= '?' . $sesspart;
1154 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1162 function common_date_string($dt)
1164 // XXX: do some sexy date formatting
1165 // return date(DATE_RFC822, $dt);
1166 $t = strtotime($dt);
1170 if ($now < $t) { // that shouldn't happen!
1171 return common_exact_date($dt);
1172 } else if ($diff < 60) {
1173 // TRANS: Used in notices to indicate when the notice was made compared to now.
1174 return _('a few seconds ago');
1175 } else if ($diff < 92) {
1176 // TRANS: Used in notices to indicate when the notice was made compared to now.
1177 return _('about a minute ago');
1178 } else if ($diff < 3300) {
1179 $minutes = round($diff/60);
1180 // TRANS: Used in notices to indicate when the notice was made compared to now.
1181 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1182 } else if ($diff < 5400) {
1183 // TRANS: Used in notices to indicate when the notice was made compared to now.
1184 return _('about an hour ago');
1185 } else if ($diff < 22 * 3600) {
1186 $hours = round($diff/3600);
1187 // TRANS: Used in notices to indicate when the notice was made compared to now.
1188 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1189 } else if ($diff < 37 * 3600) {
1190 // TRANS: Used in notices to indicate when the notice was made compared to now.
1191 return _('about a day ago');
1192 } else if ($diff < 24 * 24 * 3600) {
1193 $days = round($diff/(24*3600));
1194 // TRANS: Used in notices to indicate when the notice was made compared to now.
1195 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1196 } else if ($diff < 46 * 24 * 3600) {
1197 // TRANS: Used in notices to indicate when the notice was made compared to now.
1198 return _('about a month ago');
1199 } else if ($diff < 330 * 24 * 3600) {
1200 $months = round($diff/(30*24*3600));
1201 // TRANS: Used in notices to indicate when the notice was made compared to now.
1202 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1203 } else if ($diff < 480 * 24 * 3600) {
1204 // TRANS: Used in notices to indicate when the notice was made compared to now.
1205 return _('about a year ago');
1207 return common_exact_date($dt);
1211 function common_exact_date($dt)
1217 $_utc = new DateTimeZone('UTC');
1218 $_siteTz = new DateTimeZone(common_timezone());
1221 $dateStr = date('d F Y H:i:s', strtotime($dt));
1222 $d = new DateTime($dateStr, $_utc);
1223 $d->setTimezone($_siteTz);
1224 return $d->format(DATE_RFC850);
1227 function common_date_w3dtf($dt)
1229 $dateStr = date('d F Y H:i:s', strtotime($dt));
1230 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1231 $d->setTimezone(new DateTimeZone(common_timezone()));
1232 return $d->format(DATE_W3C);
1235 function common_date_rfc2822($dt)
1237 $dateStr = date('d F Y H:i:s', strtotime($dt));
1238 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1239 $d->setTimezone(new DateTimeZone(common_timezone()));
1240 return $d->format('r');
1243 function common_date_iso8601($dt)
1245 $dateStr = date('d F Y H:i:s', strtotime($dt));
1246 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1247 $d->setTimezone(new DateTimeZone(common_timezone()));
1248 return $d->format('c');
1251 function common_sql_now()
1253 return common_sql_date(time());
1256 function common_sql_date($datetime)
1258 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1262 * Return an SQL fragment to calculate an age-based weight from a given
1263 * timestamp or datetime column.
1265 * @param string $column name of field we're comparing against current time
1266 * @param integer $dropoff divisor for age in seconds before exponentiation
1267 * @return string SQL fragment
1269 function common_sql_weight($column, $dropoff)
1271 if (common_config('db', 'type') == 'pgsql') {
1272 // PostgreSQL doesn't support timestampdiff function.
1273 // @fixme will this use the right time zone?
1274 // @fixme does this handle cross-year subtraction correctly?
1275 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1277 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1281 function common_redirect($url, $code=307)
1283 static $status = array(301 => "Moved Permanently",
1286 307 => "Temporary Redirect");
1288 header('HTTP/1.1 '.$code.' '.$status[$code]);
1289 header("Location: $url");
1291 $xo = new XMLOutputter();
1293 '-//W3C//DTD XHTML 1.0 Strict//EN',
1294 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1295 $xo->element('a', array('href' => $url), $url);
1300 function common_broadcast_notice($notice, $remote=false)
1306 * Stick the notice on the queue.
1308 function common_enqueue_notice($notice)
1310 static $localTransports = array('omb',
1313 $transports = array();
1314 if (common_config('sms', 'enabled')) {
1315 $transports[] = 'sms';
1317 if (Event::hasHandler('HandleQueuedNotice')) {
1318 $transports[] = 'plugin';
1321 $xmpp = common_config('xmpp', 'enabled');
1324 $transports[] = 'jabber';
1327 // We can skip these for gatewayed notices.
1328 if ($notice->isLocal()) {
1329 $transports = array_merge($transports, $localTransports);
1331 $transports[] = 'public';
1335 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1337 $qm = QueueManager::get();
1339 foreach ($transports as $transport)
1341 $qm->enqueue($notice, $transport);
1344 Event::handle('EndEnqueueNotice', array($notice, $transports));
1351 * Broadcast profile updates to OMB and other remote subscribers.
1353 * Since this may be slow with a lot of subscribers or bad remote sites,
1354 * this is run through the background queues if possible.
1356 function common_broadcast_profile(Profile $profile)
1358 $qm = QueueManager::get();
1359 $qm->enqueue($profile, "profile");
1363 function common_profile_url($nickname)
1365 return common_local_url('showstream', array('nickname' => $nickname),
1370 * Should make up a reasonable root URL
1372 function common_root_url($ssl=false)
1374 $url = common_path('', $ssl, false);
1375 $i = strpos($url, '?');
1377 $url = substr($url, 0, $i);
1383 * returns $bytes bytes of random data as a hexadecimal string
1384 * "good" here is a goal and not a guarantee
1386 function common_good_rand($bytes)
1388 // XXX: use random.org...?
1389 if (@file_exists('/dev/urandom')) {
1390 return common_urandom($bytes);
1391 } else { // FIXME: this is probably not good enough
1392 return common_mtrand($bytes);
1396 function common_urandom($bytes)
1398 $h = fopen('/dev/urandom', 'rb');
1400 $src = fread($h, $bytes);
1403 for ($i = 0; $i < $bytes; $i++) {
1404 $enc .= sprintf("%02x", (ord($src[$i])));
1409 function common_mtrand($bytes)
1412 for ($i = 0; $i < $bytes; $i++) {
1413 $enc .= sprintf("%02x", mt_rand(0, 255));
1419 * Record the given URL as the return destination for a future
1420 * form submission, to be read by common_get_returnto().
1422 * @param string $url
1424 * @fixme as a session-global setting, this can allow multiple forms
1425 * to conflict and overwrite each others' returnto destinations if
1426 * the user has multiple tabs or windows open.
1428 * Should refactor to index with a token or otherwise only pass the
1429 * data along its intended path.
1431 function common_set_returnto($url)
1433 common_ensure_session();
1434 $_SESSION['returnto'] = $url;
1438 * Fetch a return-destination URL previously recorded by
1439 * common_set_returnto().
1441 * @return mixed URL string or null
1443 * @fixme as a session-global setting, this can allow multiple forms
1444 * to conflict and overwrite each others' returnto destinations if
1445 * the user has multiple tabs or windows open.
1447 * Should refactor to index with a token or otherwise only pass the
1448 * data along its intended path.
1450 function common_get_returnto()
1452 common_ensure_session();
1453 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1456 function common_timestamp()
1458 return date('YmdHis');
1461 function common_ensure_syslog()
1463 static $initialized = false;
1464 if (!$initialized) {
1465 openlog(common_config('syslog', 'appname'), 0,
1466 common_config('syslog', 'facility'));
1467 $initialized = true;
1471 function common_log_line($priority, $msg)
1473 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1474 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1475 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1478 function common_request_id()
1481 $server = common_config('site', 'server');
1482 if (php_sapi_name() == 'cli') {
1483 $script = basename($_SERVER['PHP_SELF']);
1484 return "$server:$script:$pid";
1486 static $req_id = null;
1487 if (!isset($req_id)) {
1488 $req_id = substr(md5(mt_rand()), 0, 8);
1490 if (isset($_SERVER['REQUEST_URI'])) {
1491 $url = $_SERVER['REQUEST_URI'];
1493 $method = $_SERVER['REQUEST_METHOD'];
1494 return "$server:$pid.$req_id $method $url";
1498 function common_log($priority, $msg, $filename=null)
1500 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1501 $msg = '[' . common_request_id() . '] ' . $msg;
1502 $logfile = common_config('site', 'logfile');
1504 $log = fopen($logfile, "a");
1506 $output = common_log_line($priority, $msg);
1507 fwrite($log, $output);
1511 common_ensure_syslog();
1512 syslog($priority, $msg);
1514 Event::handle('EndLog', array($priority, $msg, $filename));
1518 function common_debug($msg, $filename=null)
1521 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1523 common_log(LOG_DEBUG, $msg);
1527 function common_log_db_error(&$object, $verb, $filename=null)
1529 $objstr = common_log_objstring($object);
1530 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1531 if (is_object($last_error)) {
1532 $msg = $last_error->message;
1534 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1536 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1539 function common_log_objstring(&$object)
1541 if (is_null($object)) {
1544 if (!($object instanceof DB_DataObject)) {
1547 $arr = $object->toArray();
1549 foreach ($arr as $k => $v) {
1550 if (is_object($v)) {
1551 $fields[] = "$k='".get_class($v)."'";
1553 $fields[] = "$k='$v'";
1556 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1560 function common_valid_http_url($url)
1562 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1565 function common_valid_tag($tag)
1567 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1568 return (Validate::email($matches[1]) ||
1569 preg_match('/^([\w-\.]+)$/', $matches[1]));
1575 * Determine if given domain or address literal is valid
1576 * eg for use in JIDs and URLs. Does not check if the domain
1579 * @param string $domain
1580 * @return boolean valid or not
1582 function common_valid_domain($domain)
1584 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1585 $ipv4 = "(?:$octet(?:\.$octet){3})";
1586 if (preg_match("/^$ipv4$/u", $domain)) return true;
1588 $group = "(?:[0-9a-f]{1,4})";
1589 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1591 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1592 $before = explode(":", $matches[1]);
1593 $zeroes = $matches[2];
1594 $after = explode(":", $matches[3]);
1602 $explicit = count($before) + count($after);
1603 if ($explicit < $min || $explicit > $max) {
1610 require_once "Net/IDNA.php";
1611 $idn = Net_IDNA::getInstance();
1612 $domain = $idn->encode($domain);
1613 } catch (Exception $e) {
1617 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1618 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1620 return preg_match("/^$fqdn$/ui", $domain);
1623 /* Following functions are copied from MediaWiki GlobalFunctions.php
1624 * and written by Evan Prodromou. */
1626 function common_accept_to_prefs($accept, $def = '*/*')
1628 // No arg means accept anything (per HTTP spec)
1630 return array($def => 1);
1635 $parts = explode(',', $accept);
1637 foreach($parts as $part) {
1638 // FIXME: doesn't deal with params like 'text/html; level=1'
1639 @list($value, $qpart) = explode(';', trim($part));
1641 if(!isset($qpart)) {
1643 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1644 $prefs[$value] = $match[1];
1651 function common_mime_type_match($type, $avail)
1653 if(array_key_exists($type, $avail)) {
1656 $parts = explode('/', $type);
1657 if(array_key_exists($parts[0] . '/*', $avail)) {
1658 return $parts[0] . '/*';
1659 } elseif(array_key_exists('*/*', $avail)) {
1667 function common_negotiate_type($cprefs, $sprefs)
1671 foreach(array_keys($sprefs) as $type) {
1672 $parts = explode('/', $type);
1673 if($parts[1] != '*') {
1674 $ckey = common_mime_type_match($type, $cprefs);
1676 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1681 foreach(array_keys($cprefs) as $type) {
1682 $parts = explode('/', $type);
1683 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1684 $skey = common_mime_type_match($type, $sprefs);
1686 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1692 $besttype = 'text/html';
1694 foreach(array_keys($combine) as $type) {
1695 if($combine[$type] > $bestq) {
1697 $bestq = $combine[$type];
1701 if ('text/html' === $besttype) {
1702 return "text/html; charset=utf-8";
1707 function common_config($main, $sub)
1710 return (array_key_exists($main, $config) &&
1711 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1715 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1716 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1718 * @param array $from
1721 function common_copy_args($from)
1724 $strip = get_magic_quotes_gpc();
1725 foreach ($from as $k => $v) {
1727 $to[$k] = common_copy_args($v);
1730 $v = stripslashes($v);
1732 $to[$k] = strval(common_validate_utf8($v));
1739 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1740 * This is used before handing a request off to OAuthRequest::from_request.
1741 * @fixme Doesn't consider vars other than _POST and _GET?
1742 * @fixme Can't be undone and could corrupt data if run twice.
1744 function common_remove_magic_from_request()
1746 if(get_magic_quotes_gpc()) {
1747 $_POST=array_map('stripslashes',$_POST);
1748 $_GET=array_map('stripslashes',$_GET);
1752 function common_user_uri(&$user)
1754 return common_local_url('userbyid', array('id' => $user->id),
1758 function common_notice_uri(&$notice)
1760 return common_local_url('shownotice',
1761 array('notice' => $notice->id),
1765 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1767 function common_confirmation_code($bits)
1769 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1770 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1771 $chars = ceil($bits/5);
1773 for ($i = 0; $i < $chars; $i++) {
1774 // XXX: convert to string and back
1775 $num = hexdec(common_good_rand(1));
1776 // XXX: randomness is too precious to throw away almost
1777 // 40% of the bits we get!
1778 $code .= $codechars[$num%32];
1783 // convert markup to HTML
1785 function common_markup_to_html($c)
1787 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1788 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1789 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1790 return Markdown($c);
1793 function common_profile_uri($profile)
1798 $user = User::staticGet($profile->id);
1803 $remote = Remote_profile::staticGet($profile->id);
1805 return $remote->uri;
1807 // XXX: this is a very bad profile!
1811 function common_canonical_sms($sms)
1814 preg_replace('/\D/', '', $sms);
1818 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1823 case E_COMPILE_ERROR:
1827 case E_RECOVERABLE_ERROR:
1828 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1833 case E_COMPILE_WARNING:
1834 case E_CORE_WARNING:
1835 case E_USER_WARNING:
1836 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1841 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1846 case E_USER_DEPRECATED:
1847 // XXX: config variable to log this stuff, too
1851 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1856 // FIXME: show error page if we're on the Web
1857 /* Don't execute PHP internal error handler */
1861 function common_session_token()
1863 common_ensure_session();
1864 if (!array_key_exists('token', $_SESSION)) {
1865 $_SESSION['token'] = common_good_rand(64);
1867 return $_SESSION['token'];
1870 function common_cache_key($extra)
1872 return Cache::key($extra);
1875 function common_keyize($str)
1877 return Cache::keyize($str);
1880 function common_memcache()
1882 return Cache::instance();
1885 function common_license_terms($uri)
1887 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1888 return explode('-',$matches[1]);
1893 function common_compatible_license($from, $to)
1895 $from_terms = common_license_terms($from);
1896 // public domain and cc-by are compatible with everything
1897 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1900 $to_terms = common_license_terms($to);
1901 // sa is compatible across versions. IANAL
1902 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1903 return count(array_diff($from_terms, $to_terms)) == 0;
1905 // XXX: better compatibility check needed here!
1906 // Should at least normalise URIs
1907 return ($from == $to);
1911 * returns a quoted table name, if required according to config
1913 function common_database_tablename($tablename)
1915 if(common_config('db','quote_identifiers')) {
1916 $tablename = '"'. $tablename .'"';
1918 //table prefixes could be added here later
1923 * Shorten a URL with the current user's configured shortening service,
1924 * or ur1.ca if configured, or not at all if no shortening is set up.
1925 * Length is not considered.
1927 * @param string $long_url
1928 * @return string may return the original URL if shortening failed
1930 * @fixme provide a way to specify a particular shortener
1931 * @fixme provide a way to specify to use a given user's shortening preferences
1933 function common_shorten_url($long_url)
1935 $long_url = trim($long_url);
1936 $user = common_current_user();
1938 // common current user does not find a user when called from the XMPP daemon
1939 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1940 $shortenerName = 'ur1.ca';
1942 $shortenerName = $user->urlshorteningservice;
1945 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1946 //URL wasn't shortened, so return the long url
1949 //URL was shortened, so return the result
1950 return trim($shortenedUrl);
1955 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1956 * null if not a web request
1958 * @fixme X-Forwarded-For can be chained by multiple proxies;
1959 we should parse the list and provide a cleaner array
1960 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1961 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1962 * use function to get exact request headers from Apache if possible.
1964 function common_client_ip()
1966 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1970 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1971 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1972 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1974 $proxy = $_SERVER['REMOTE_ADDR'];
1976 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1979 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1980 $ip = $_SERVER['HTTP_CLIENT_IP'];
1982 $ip = $_SERVER['REMOTE_ADDR'];
1986 return array($proxy, $ip);
1989 function common_url_to_nickname($url)
1991 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1993 $parts = parse_url($url);
1995 # If any of these parts exist, this won't work
1997 foreach ($bad as $badpart) {
1998 if (array_key_exists($badpart, $parts)) {
2003 # We just have host and/or path
2005 # If it's just a host...
2006 if (array_key_exists('host', $parts) &&
2007 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2009 $hostparts = explode('.', $parts['host']);
2011 # Try to catch common idiom of nickname.service.tld
2013 if ((count($hostparts) > 2) &&
2014 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2015 (strcmp($hostparts[0], 'www') != 0))
2017 return common_nicknamize($hostparts[0]);
2019 # Do the whole hostname
2020 return common_nicknamize($parts['host']);
2023 if (array_key_exists('path', $parts)) {
2024 # Strip starting, ending slashes
2025 $path = preg_replace('@/$@', '', $parts['path']);
2026 $path = preg_replace('@^/@', '', $path);
2027 $path = basename($path);
2029 // Hack for MediaWiki user pages, in the form:
2030 // http://example.com/wiki/User:Myname
2031 // ('User' may be localized.)
2032 if (strpos($path, ':')) {
2033 $parts = array_filter(explode(':', $path));
2034 $path = $parts[count($parts) - 1];
2038 return common_nicknamize($path);
2046 function common_nicknamize($str)
2048 $str = preg_replace('/\W/', '', $str);
2049 return strtolower($str);