3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* XXX: break up into separate modules (HTTP, user, files) */
23 * Show a server error.
25 function common_server_error($msg, $code=500)
27 $err = new ServerErrorAction($msg, $code);
34 function common_user_error($msg, $code=400)
36 $err = new ClientErrorAction($msg, $code);
41 * This should only be used at setup; processes switching languages
42 * to send text to other users should use common_switch_locale().
44 * @param string $language Locale language code (optional; empty uses
45 * current user's preference or site default)
46 * @return mixed success
48 function common_init_locale($language=null)
51 $language = common_language();
53 putenv('LANGUAGE='.$language);
54 putenv('LANG='.$language);
55 $ok = setlocale(LC_ALL, $language . ".utf8",
65 * Initialize locale and charset settings and gettext with our message catalog,
66 * using the current user's language preference or the site default.
68 * This should generally only be run at framework initialization; code switching
69 * languages at runtime should call common_switch_language().
73 function common_init_language()
75 mb_internal_encoding('UTF-8');
77 // Note that this setlocale() call may "fail" but this is harmless;
78 // gettext will still select the right language.
79 $language = common_language();
80 $locale_set = common_init_locale($language);
83 // The requested locale doesn't exist on the system.
85 // gettext seems very picky... We first need to setlocale()
86 // to a locale which _does_ exist on the system, and _then_
87 // we can set in another locale that may not be set up
88 // (say, ga_ES for Galego/Galician) it seems to take it.
90 // For some reason C and POSIX which are guaranteed to work
91 // don't do the job. en_US.UTF-8 should be there most of the
92 // time, but not guaranteed.
93 $ok = common_init_locale("en_US");
94 if (!$ok && strtolower(substr(PHP_OS, 0, 3)) != 'win') {
95 // Try to find a complete, working locale on Unix/Linux...
96 // @fixme shelling out feels awfully inefficient
97 // but I don't think there's a more standard way.
99 foreach (explode("\n", $all) as $locale) {
100 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
101 $ok = setlocale(LC_ALL, $locale);
109 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
111 $locale_set = common_init_locale($language);
114 common_init_gettext();
120 function common_init_gettext()
122 setlocale(LC_CTYPE, 'C');
123 // So we do not have to make people install the gettext locales
124 $path = common_config('site','locale_path');
125 bindtextdomain("statusnet", $path);
126 bind_textdomain_codeset("statusnet", "UTF-8");
127 textdomain("statusnet");
131 * Switch locale during runtime, and poke gettext until it cries uncle.
132 * Otherwise, sometimes it doesn't actually switch away from the old language.
134 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
136 function common_switch_locale($language=null)
138 common_init_locale($language);
140 setlocale(LC_CTYPE, 'C');
141 // So we do not have to make people install the gettext locales
142 $path = common_config('site','locale_path');
143 bindtextdomain("statusnet", $path);
144 bind_textdomain_codeset("statusnet", "UTF-8");
145 textdomain("statusnet");
148 function common_timezone()
150 if (common_logged_in()) {
151 $user = common_current_user();
152 if ($user->timezone) {
153 return $user->timezone;
157 return common_config('site', 'timezone');
160 function common_valid_language($lang)
163 // Validate -- we don't want to end up with a bogus code
164 // left over from some old junk.
165 foreach (common_config('site', 'languages') as $code => $info) {
166 if ($info['lang'] == $lang) {
174 function common_language()
176 // Allow ?uselang=xx override, very useful for debugging
177 // and helping translators check usage and context.
178 if (isset($_GET['uselang'])) {
179 $uselang = strval($_GET['uselang']);
180 if (common_valid_language($uselang)) {
185 // If there is a user logged in and they've set a language preference
186 // then return that one...
187 if (_have_config() && common_logged_in()) {
188 $user = common_current_user();
190 if (common_valid_language($user->language)) {
191 return $user->language;
195 // Otherwise, find the best match for the languages requested by the
197 if (common_config('site', 'langdetect')) {
198 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
199 if (!empty($httplang)) {
200 $language = client_prefered_language($httplang);
206 // Finally, if none of the above worked, use the site's default...
207 return common_config('site', 'language');
211 * Salted, hashed passwords are stored in the DB.
213 function common_munge_password($password, $id)
215 if (is_object($id) || is_object($password)) {
216 $e = new Exception();
217 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
218 str_replace("\n", " ", $e->getTraceAsString()));
220 return md5($password . $id);
224 * Check if a username exists and has matching password.
226 function common_check_user($nickname, $password)
228 // empty nickname always unacceptable
229 if (empty($nickname)) {
233 $authenticatedUser = false;
235 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
236 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
238 if (!empty($password)) { // never allow login with blank password
239 if (0 == strcmp(common_munge_password($password, $user->id),
241 //internal checking passed
242 $authenticatedUser = $user;
246 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
249 return $authenticatedUser;
253 * Is the current user logged in?
255 function common_logged_in()
257 return (!is_null(common_current_user()));
260 function common_have_session()
262 return (0 != strcmp(session_id(), ''));
265 function common_ensure_session()
268 if (array_key_exists(session_name(), $_COOKIE)) {
269 $c = $_COOKIE[session_name()];
271 if (!common_have_session()) {
272 if (common_config('sessions', 'handle')) {
273 Session::setSaveHandler();
275 if (array_key_exists(session_name(), $_GET)) {
276 $id = $_GET[session_name()];
277 } else if (array_key_exists(session_name(), $_COOKIE)) {
278 $id = $_COOKIE[session_name()];
284 if (!isset($_SESSION['started'])) {
285 $_SESSION['started'] = time();
287 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
288 ' is set but started value is null');
294 // Three kinds of arguments:
299 // Initialize to false; set to null if none found
302 function common_set_user($user)
306 if (is_null($user) && common_have_session()) {
308 unset($_SESSION['userid']);
310 } else if (is_string($user)) {
312 $user = User::staticGet('nickname', $nickname);
313 } else if (!($user instanceof User)) {
318 if (Event::handle('StartSetUser', array(&$user))) {
320 common_ensure_session();
321 $_SESSION['userid'] = $user->id;
323 Event::handle('EndSetUser', array($user));
331 function common_set_cookie($key, $value, $expiration=0)
333 $path = common_config('site', 'path');
334 $server = common_config('site', 'server');
336 if ($path && ($path != '/')) {
337 $cookiepath = '/' . $path . '/';
341 return setcookie($key,
348 define('REMEMBERME', 'rememberme');
349 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
351 function common_rememberme($user=null)
354 $user = common_current_user();
360 $rm = new Remember_me();
362 $rm->code = common_good_rand(16);
363 $rm->user_id = $user->id;
365 // Wrap the insert in some good ol' fashioned transaction code
369 $result = $rm->insert();
372 common_log_db_error($rm, 'INSERT', __FILE__);
376 $rm->query('COMMIT');
378 $cookieval = $rm->user_id . ':' . $rm->code;
380 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
382 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
387 function common_remembered_user()
391 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
397 list($id, $code) = explode(':', $packed);
399 if (!$id || !$code) {
400 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
405 $rm = Remember_me::staticGet($code);
408 common_log(LOG_WARNING, 'No such remember code: ' . $code);
413 if ($rm->user_id != $id) {
414 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
419 $user = User::staticGet($rm->user_id);
422 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
428 $result = $rm->delete();
431 common_log_db_error($rm, 'DELETE', __FILE__);
432 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
437 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
439 common_set_user($user);
440 common_real_login(false);
442 // We issue a new cookie, so they can log in
443 // automatically again after this session
445 common_rememberme($user);
451 * must be called with a valid user!
453 function common_forgetme()
455 common_set_cookie(REMEMBERME, '', 0);
459 * Who is the current user?
461 function common_current_user()
465 if (!_have_config()) {
469 if ($_cur === false) {
471 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
472 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
473 common_ensure_session();
474 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
476 $user = User::staticGet($id);
484 // that didn't work; try to remember; will init $_cur to null on failure
485 $_cur = common_remembered_user();
488 // XXX: Is this necessary?
489 $_SESSION['userid'] = $_cur->id;
497 * Logins that are 'remembered' aren't 'real' -- they're subject to
498 * cookie-stealing. So, we don't let them do certain things. New reg,
499 * OpenID, and password logins _are_ real.
501 function common_real_login($real=true)
503 common_ensure_session();
504 $_SESSION['real_login'] = $real;
507 function common_is_real_login()
509 return common_logged_in() && $_SESSION['real_login'];
513 * Get a hash portion for HTTP caching Etags and such including
514 * info on the current user's session. If login/logout state changes,
515 * or we've changed accounts, or we've renamed the current user,
516 * we'll get a new hash value.
518 * This should not be considered secure information.
520 * @param User $user (optional; uses common_current_user() if left out)
523 function common_user_cache_hash($user=false)
525 if ($user === false) {
526 $user = common_current_user();
529 return crc32($user->id . ':' . $user->nickname);
535 // get canonical version of nickname for comparison
536 function common_canonical_nickname($nickname)
538 // XXX: UTF-8 canonicalization (like combining chars)
539 return strtolower($nickname);
542 // get canonical version of email for comparison
543 function common_canonical_email($email)
545 // XXX: canonicalize UTF-8
546 // XXX: lcase the domain part
550 function common_render_content($text, $notice)
552 $r = common_render_text($text);
553 $id = $notice->profile_id;
554 $r = common_linkify_mentions($r, $notice);
555 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
559 function common_linkify_mentions($text, $notice)
561 $mentions = common_find_mentions($text, $notice);
563 // We need to go through in reverse order by position,
564 // so our positions stay valid despite our fudging with the
569 foreach ($mentions as $mention)
571 $points[$mention['position']] = $mention;
576 foreach ($points as $position => $mention) {
578 $linkText = common_linkify_mention($mention);
580 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
586 function common_linkify_mention($mention)
590 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
592 $xs = new XMLStringer(false);
594 $attrs = array('href' => $mention['url'],
597 if (!empty($mention['title'])) {
598 $attrs['title'] = $mention['title'];
601 $xs->elementStart('span', 'vcard');
602 $xs->elementStart('a', $attrs);
603 $xs->element('span', 'fn nickname', $mention['text']);
604 $xs->elementEnd('a');
605 $xs->elementEnd('span');
607 $output = $xs->getString();
609 Event::handle('EndLinkifyMention', array($mention, &$output));
615 function common_find_mentions($text, $notice)
619 $sender = Profile::staticGet('id', $notice->profile_id);
621 if (empty($sender)) {
625 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
626 // Get the context of the original notice, if any
627 $originalAuthor = null;
628 $originalNotice = null;
629 $originalMentions = array();
633 if (!empty($notice) && !empty($notice->reply_to)) {
634 $originalNotice = Notice::staticGet('id', $notice->reply_to);
635 if (!empty($originalNotice)) {
636 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
638 $ids = $originalNotice->getReplies();
640 foreach ($ids as $id) {
641 $repliedTo = Profile::staticGet('id', $id);
642 if (!empty($repliedTo)) {
643 $originalMentions[$repliedTo->nickname] = $repliedTo;
649 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
652 PREG_OFFSET_CAPTURE);
654 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
657 PREG_OFFSET_CAPTURE);
659 $matches = array_merge($tmatches[1], $atmatches[1]);
661 foreach ($matches as $match) {
662 $nickname = common_canonical_nickname($match[0]);
664 // Try to get a profile for this nickname.
665 // Start with conversation context, then go to
668 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
669 $mentioned = $originalAuthor;
670 } else if (!empty($originalMentions) &&
671 array_key_exists($nickname, $originalMentions)) {
672 $mentioned = $originalMentions[$nickname];
674 $mentioned = common_relative_profile($sender, $nickname);
677 if (!empty($mentioned)) {
678 $user = User::staticGet('id', $mentioned->id);
681 $url = common_local_url('userbyid', array('id' => $user->id));
683 $url = $mentioned->profileurl;
686 $mention = array('mentioned' => array($mentioned),
688 'position' => $match[1],
691 if (!empty($mentioned->fullname)) {
692 $mention['title'] = $mentioned->fullname;
695 $mentions[] = $mention;
699 // @#tag => mention of all subscriptions tagged 'tag'
701 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
704 PREG_OFFSET_CAPTURE);
706 foreach ($hmatches[1] as $hmatch) {
708 $tag = common_canonical_tag($hmatch[0]);
710 $tagged = Profile_tag::getTagged($sender->id, $tag);
712 $url = common_local_url('subscriptions',
713 array('nickname' => $sender->nickname,
716 $mentions[] = array('mentioned' => $tagged,
717 'text' => $hmatch[0],
718 'position' => $hmatch[1],
722 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
728 function common_render_text($text)
730 $r = htmlspecialchars($text);
732 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
733 $r = common_replace_urls_callback($r, 'common_linkify');
734 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
739 function common_replace_urls_callback($text, $callback, $notice_id = null) {
740 // Start off with a regex
742 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
745 '(?:'. //Known protocols
747 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
749 '(?:(?:mailto|aim|tel|xmpp):)'.
751 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
754 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
756 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
760 '|(?:(?: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
762 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
764 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
765 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
766 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
767 '(?: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)'.
771 '(?:\:\d+)?'. //:port
772 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
773 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
774 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
775 ')(?<![\?\.\,\#\,])'.
778 //preg_match_all($regex,$text,$matches);
780 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
783 function callback_helper($matches, $callback, $notice_id) {
785 $left = strpos($matches[0],$url);
786 $right = $left+strlen($url);
788 $groupSymbolSets=array(
806 $cannotEndWith=array('.','?',',','#');
810 foreach($groupSymbolSets as $groupSymbolSet){
811 if(substr($url,-1)==$groupSymbolSet['right']){
812 $group_left_count = substr_count($url,$groupSymbolSet['left']);
813 $group_right_count = substr_count($url,$groupSymbolSet['right']);
814 if($group_left_count<$group_right_count){
816 $url=substr($url,0,-1);
820 if(in_array(substr($url,-1),$cannotEndWith)){
822 $url=substr($url,0,-1);
824 }while($original_url!=$url);
826 if(empty($notice_id)){
827 $result = call_user_func_array($callback, array($url));
829 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
831 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
834 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
835 // lambda implementation in a separate file; PHP 5.2 won't parse it.
836 require_once INSTALLDIR . "/lib/curry.php";
838 function curry($fn) {
839 $args = func_get_args();
841 $id = uniqid('_partial');
842 $GLOBALS[$id] = array($fn, $args);
843 return create_function('',
844 '$args = func_get_args(); '.
845 'return call_user_func_array('.
846 '$GLOBALS["'.$id.'"][0],'.
849 '$GLOBALS["'.$id.'"][1]));');
853 function common_linkify($url) {
854 // It comes in special'd, so we unspecial it before passing to the stringifying
856 $url = htmlspecialchars_decode($url);
858 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
859 //url is an email address without the mailto: protocol
860 $canon = "mailto:$url";
861 $longurl = "mailto:$url";
864 $canon = File_redirection::_canonUrl($url);
866 $longurl_data = File_redirection::where($canon);
867 if (is_array($longurl_data)) {
868 $longurl = $longurl_data['url'];
869 } elseif (is_string($longurl_data)) {
870 $longurl = $longurl_data;
872 // Unable to reach the server to verify contents, etc
873 // Just pass the link on through for now.
874 common_log(LOG_ERR, "Can't linkify url '$url'");
879 $attrs = array('href' => $canon, 'title' => $longurl);
881 $is_attachment = false;
882 $attachment_id = null;
885 // Check to see whether this is a known "attachment" URL.
887 $f = File::staticGet('url', $longurl);
890 // XXX: this writes to the database. :<
891 $f = File::processNew($longurl);
895 if ($f->getEnclosure() || File_oembed::staticGet('file_id',$f->id)) {
896 $is_attachment = true;
897 $attachment_id = $f->id;
899 $thumb = File_thumbnail::staticGet('file_id', $f->id);
900 if (!empty($thumb)) {
907 if ($is_attachment) {
908 $attrs['class'] = 'attachment';
910 $attrs['class'] = 'attachment thumbnail';
912 $attrs['id'] = "attachment-{$attachment_id}";
915 // Whether to nofollow
917 $nf = common_config('nofollow', 'external');
919 if ($nf == 'never') {
920 $attrs['rel'] = 'external';
922 $attrs['rel'] = 'nofollow external';
925 return XMLStringer::estring('a', $attrs, $url);
928 function common_shorten_links($text, $always = false)
930 common_debug("common_shorten_links() called");
932 $user = common_current_user();
934 $maxLength = User_urlshortener_prefs::maxNoticeLength($user);
936 common_debug("maxLength = $maxLength");
938 if ($always || mb_strlen($text) > $maxLength) {
939 common_debug("Forcing shortening");
940 return common_replace_urls_callback($text, array('File_redirection', 'forceShort'));
942 common_debug("Not forcing shortening");
943 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
948 * Very basic stripping of invalid UTF-8 input text.
951 * @return mixed string or null if invalid input
953 * @todo ideally we should drop bad chars, and maybe do some of the checks
954 * from common_xml_safe_str. But we can't strip newlines, etc.
955 * @todo Unicode normalization might also be useful, but not needed now.
957 function common_validate_utf8($str)
959 // preg_replace will return NULL on invalid UTF-8 input.
961 // Note: empty regex //u also caused NULL return on some
962 // production machines, but none of our test machines.
964 // This should be replaced with a more reliable check.
965 return preg_replace('/\x00/u', '', $str);
969 * Make sure an arbitrary string is safe for output in XML as a single line.
974 function common_xml_safe_str($str)
976 // Replace common eol and extra whitespace input chars
981 "\0", // null byte eos
982 "\x0B" // vertical tab
985 $replacement = array(
993 $str = str_replace($unWelcome, $replacement, $str);
995 // Neutralize any additional control codes and UTF-16 surrogates
996 // (Twitter uses '*')
997 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
1000 function common_tag_link($tag)
1002 $canonical = common_canonical_tag($tag);
1003 if (common_config('singleuser', 'enabled')) {
1004 // regular TagAction isn't set up in 1user mode
1005 $user = User::singleUser();
1006 $url = common_local_url('showstream',
1007 array('nickname' => $user->nickname,
1008 'tag' => $canonical));
1010 $url = common_local_url('tag', array('tag' => $canonical));
1012 $xs = new XMLStringer();
1013 $xs->elementStart('span', 'tag');
1014 $xs->element('a', array('href' => $url,
1017 $xs->elementEnd('span');
1018 return $xs->getString();
1021 function common_canonical_tag($tag)
1023 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
1024 return str_replace(array('-', '_', '.'), '', $tag);
1027 function common_valid_profile_tag($str)
1029 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
1032 function common_group_link($sender_id, $nickname)
1034 $sender = Profile::staticGet($sender_id);
1035 $group = User_group::getForNickname($nickname, $sender);
1036 if ($sender && $group && $sender->isMember($group)) {
1037 $attrs = array('href' => $group->permalink(),
1039 if (!empty($group->fullname)) {
1040 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
1042 $xs = new XMLStringer();
1043 $xs->elementStart('span', 'vcard');
1044 $xs->elementStart('a', $attrs);
1045 $xs->element('span', 'fn nickname', $nickname);
1046 $xs->elementEnd('a');
1047 $xs->elementEnd('span');
1048 return $xs->getString();
1054 function common_relative_profile($sender, $nickname, $dt=null)
1056 // Try to find profiles this profile is subscribed to that have this nickname
1057 $recipient = new Profile();
1058 // XXX: use a join instead of a subquery
1059 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
1060 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1061 if ($recipient->find(true)) {
1062 // XXX: should probably differentiate between profiles with
1063 // the same name by date of most recent update
1066 // Try to find profiles that listen to this profile and that have this nickname
1067 $recipient = new Profile();
1068 // XXX: use a join instead of a subquery
1069 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
1070 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
1071 if ($recipient->find(true)) {
1072 // XXX: should probably differentiate between profiles with
1073 // the same name by date of most recent update
1076 // If this is a local user, try to find a local user with that nickname.
1077 $sender = User::staticGet($sender->id);
1079 $recipient_user = User::staticGet('nickname', $nickname);
1080 if ($recipient_user) {
1081 return $recipient_user->getProfile();
1084 // Otherwise, no links. @messages from local users to remote users,
1085 // or from remote users to other remote users, are just
1086 // outside our ability to make intelligent guesses about
1090 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
1093 $path = $r->build($action, $args, $params, $fragment);
1095 $ssl = common_is_sensitive($action);
1097 if (common_config('site','fancy')) {
1098 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1100 if (mb_strpos($path, '/index.php') === 0) {
1101 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
1103 $url = common_path('index.php'.$path, $ssl, $addSession);
1109 function common_is_sensitive($action)
1111 static $sensitive = array(
1116 'ApiOauthRequestToken',
1117 'ApiOauthAccessToken',
1118 'ApiOauthAuthorize',
1124 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1125 $ssl = in_array($action, $sensitive);
1131 function common_path($relative, $ssl=false, $addSession=true)
1133 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1135 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1136 || common_config('site', 'ssl') === 'always') {
1138 if (is_string(common_config('site', 'sslserver')) &&
1139 mb_strlen(common_config('site', 'sslserver')) > 0) {
1140 $serverpart = common_config('site', 'sslserver');
1141 } else if (common_config('site', 'server')) {
1142 $serverpart = common_config('site', 'server');
1144 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1148 if (common_config('site', 'server')) {
1149 $serverpart = common_config('site', 'server');
1151 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1156 $relative = common_inject_session($relative, $serverpart);
1159 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1162 function common_inject_session($url, $serverpart = null)
1164 if (common_have_session()) {
1166 if (empty($serverpart)) {
1167 $serverpart = parse_url($url, PHP_URL_HOST);
1170 $currentServer = $_SERVER['HTTP_HOST'];
1172 // Are we pointing to another server (like an SSL server?)
1174 if (!empty($currentServer) &&
1175 0 != strcasecmp($currentServer, $serverpart)) {
1176 // Pass the session ID as a GET parameter
1177 $sesspart = session_name() . '=' . session_id();
1178 $i = strpos($url, '?');
1179 if ($i === false) { // no GET params, just append
1180 $url .= '?' . $sesspart;
1182 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1190 function common_date_string($dt)
1192 // XXX: do some sexy date formatting
1193 // return date(DATE_RFC822, $dt);
1194 $t = strtotime($dt);
1198 if ($now < $t) { // that shouldn't happen!
1199 return common_exact_date($dt);
1200 } else if ($diff < 60) {
1201 // TRANS: Used in notices to indicate when the notice was made compared to now.
1202 return _('a few seconds ago');
1203 } else if ($diff < 92) {
1204 // TRANS: Used in notices to indicate when the notice was made compared to now.
1205 return _('about a minute ago');
1206 } else if ($diff < 3300) {
1207 $minutes = round($diff/60);
1208 // TRANS: Used in notices to indicate when the notice was made compared to now.
1209 return sprintf( ngettext('about one minute ago', 'about %d minutes ago', $minutes), $minutes);
1210 } else if ($diff < 5400) {
1211 // TRANS: Used in notices to indicate when the notice was made compared to now.
1212 return _('about an hour ago');
1213 } else if ($diff < 22 * 3600) {
1214 $hours = round($diff/3600);
1215 // TRANS: Used in notices to indicate when the notice was made compared to now.
1216 return sprintf( ngettext('about one hour ago', 'about %d hours ago', $hours), $hours);
1217 } else if ($diff < 37 * 3600) {
1218 // TRANS: Used in notices to indicate when the notice was made compared to now.
1219 return _('about a day ago');
1220 } else if ($diff < 24 * 24 * 3600) {
1221 $days = round($diff/(24*3600));
1222 // TRANS: Used in notices to indicate when the notice was made compared to now.
1223 return sprintf( ngettext('about one day ago', 'about %d days ago', $days), $days);
1224 } else if ($diff < 46 * 24 * 3600) {
1225 // TRANS: Used in notices to indicate when the notice was made compared to now.
1226 return _('about a month ago');
1227 } else if ($diff < 330 * 24 * 3600) {
1228 $months = round($diff/(30*24*3600));
1229 // TRANS: Used in notices to indicate when the notice was made compared to now.
1230 return sprintf( ngettext('about one month ago', 'about %d months ago',$months), $months);
1231 } else if ($diff < 480 * 24 * 3600) {
1232 // TRANS: Used in notices to indicate when the notice was made compared to now.
1233 return _('about a year ago');
1235 return common_exact_date($dt);
1239 function common_exact_date($dt)
1245 $_utc = new DateTimeZone('UTC');
1246 $_siteTz = new DateTimeZone(common_timezone());
1249 $dateStr = date('d F Y H:i:s', strtotime($dt));
1250 $d = new DateTime($dateStr, $_utc);
1251 $d->setTimezone($_siteTz);
1252 return $d->format(DATE_RFC850);
1255 function common_date_w3dtf($dt)
1257 $dateStr = date('d F Y H:i:s', strtotime($dt));
1258 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1259 $d->setTimezone(new DateTimeZone(common_timezone()));
1260 return $d->format(DATE_W3C);
1263 function common_date_rfc2822($dt)
1265 $dateStr = date('d F Y H:i:s', strtotime($dt));
1266 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1267 $d->setTimezone(new DateTimeZone(common_timezone()));
1268 return $d->format('r');
1271 function common_date_iso8601($dt)
1273 $dateStr = date('d F Y H:i:s', strtotime($dt));
1274 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1275 $d->setTimezone(new DateTimeZone(common_timezone()));
1276 return $d->format('c');
1279 function common_sql_now()
1281 return common_sql_date(time());
1284 function common_sql_date($datetime)
1286 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1290 * Return an SQL fragment to calculate an age-based weight from a given
1291 * timestamp or datetime column.
1293 * @param string $column name of field we're comparing against current time
1294 * @param integer $dropoff divisor for age in seconds before exponentiation
1295 * @return string SQL fragment
1297 function common_sql_weight($column, $dropoff)
1299 if (common_config('db', 'type') == 'pgsql') {
1300 // PostgreSQL doesn't support timestampdiff function.
1301 // @fixme will this use the right time zone?
1302 // @fixme does this handle cross-year subtraction correctly?
1303 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1305 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1309 function common_redirect($url, $code=307)
1311 static $status = array(301 => "Moved Permanently",
1314 307 => "Temporary Redirect");
1316 header('HTTP/1.1 '.$code.' '.$status[$code]);
1317 header("Location: $url");
1319 $xo = new XMLOutputter();
1321 '-//W3C//DTD XHTML 1.0 Strict//EN',
1322 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1323 $xo->element('a', array('href' => $url), $url);
1328 // Stick the notice on the queue
1330 function common_enqueue_notice($notice)
1332 static $localTransports = array('omb',
1335 $transports = array();
1336 if (common_config('sms', 'enabled')) {
1337 $transports[] = 'sms';
1339 if (Event::hasHandler('HandleQueuedNotice')) {
1340 $transports[] = 'plugin';
1343 // We can skip these for gatewayed notices.
1344 if ($notice->isLocal()) {
1345 $transports = array_merge($transports, $localTransports);
1348 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1350 $qm = QueueManager::get();
1352 foreach ($transports as $transport)
1354 $qm->enqueue($notice, $transport);
1357 Event::handle('EndEnqueueNotice', array($notice, $transports));
1364 * Broadcast profile updates to OMB and other remote subscribers.
1366 * Since this may be slow with a lot of subscribers or bad remote sites,
1367 * this is run through the background queues if possible.
1369 function common_broadcast_profile(Profile $profile)
1371 $qm = QueueManager::get();
1372 $qm->enqueue($profile, "profile");
1376 function common_profile_url($nickname)
1378 return common_local_url('showstream', array('nickname' => $nickname),
1383 * Should make up a reasonable root URL
1385 function common_root_url($ssl=false)
1387 $url = common_path('', $ssl, false);
1388 $i = strpos($url, '?');
1390 $url = substr($url, 0, $i);
1396 * returns $bytes bytes of random data as a hexadecimal string
1397 * "good" here is a goal and not a guarantee
1399 function common_good_rand($bytes)
1401 // XXX: use random.org...?
1402 if (@file_exists('/dev/urandom')) {
1403 return common_urandom($bytes);
1404 } else { // FIXME: this is probably not good enough
1405 return common_mtrand($bytes);
1409 function common_urandom($bytes)
1411 $h = fopen('/dev/urandom', 'rb');
1413 $src = fread($h, $bytes);
1416 for ($i = 0; $i < $bytes; $i++) {
1417 $enc .= sprintf("%02x", (ord($src[$i])));
1422 function common_mtrand($bytes)
1425 for ($i = 0; $i < $bytes; $i++) {
1426 $enc .= sprintf("%02x", mt_rand(0, 255));
1432 * Record the given URL as the return destination for a future
1433 * form submission, to be read by common_get_returnto().
1435 * @param string $url
1437 * @fixme as a session-global setting, this can allow multiple forms
1438 * to conflict and overwrite each others' returnto destinations if
1439 * the user has multiple tabs or windows open.
1441 * Should refactor to index with a token or otherwise only pass the
1442 * data along its intended path.
1444 function common_set_returnto($url)
1446 common_ensure_session();
1447 $_SESSION['returnto'] = $url;
1451 * Fetch a return-destination URL previously recorded by
1452 * common_set_returnto().
1454 * @return mixed URL string or null
1456 * @fixme as a session-global setting, this can allow multiple forms
1457 * to conflict and overwrite each others' returnto destinations if
1458 * the user has multiple tabs or windows open.
1460 * Should refactor to index with a token or otherwise only pass the
1461 * data along its intended path.
1463 function common_get_returnto()
1465 common_ensure_session();
1466 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1469 function common_timestamp()
1471 return date('YmdHis');
1474 function common_ensure_syslog()
1476 static $initialized = false;
1477 if (!$initialized) {
1478 openlog(common_config('syslog', 'appname'), 0,
1479 common_config('syslog', 'facility'));
1480 $initialized = true;
1484 function common_log_line($priority, $msg)
1486 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1487 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1488 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . PHP_EOL;
1491 function common_request_id()
1494 $server = common_config('site', 'server');
1495 if (php_sapi_name() == 'cli') {
1496 $script = basename($_SERVER['PHP_SELF']);
1497 return "$server:$script:$pid";
1499 static $req_id = null;
1500 if (!isset($req_id)) {
1501 $req_id = substr(md5(mt_rand()), 0, 8);
1503 if (isset($_SERVER['REQUEST_URI'])) {
1504 $url = $_SERVER['REQUEST_URI'];
1506 $method = $_SERVER['REQUEST_METHOD'];
1507 return "$server:$pid.$req_id $method $url";
1511 function common_log($priority, $msg, $filename=null)
1513 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1514 $msg = '[' . common_request_id() . '] ' . $msg;
1515 $logfile = common_config('site', 'logfile');
1517 $log = fopen($logfile, "a");
1519 $output = common_log_line($priority, $msg);
1520 fwrite($log, $output);
1524 common_ensure_syslog();
1525 syslog($priority, $msg);
1527 Event::handle('EndLog', array($priority, $msg, $filename));
1531 function common_debug($msg, $filename=null)
1534 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1536 common_log(LOG_DEBUG, $msg);
1540 function common_log_db_error(&$object, $verb, $filename=null)
1542 $objstr = common_log_objstring($object);
1543 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1544 if (is_object($last_error)) {
1545 $msg = $last_error->message;
1547 $msg = 'Unknown error (' . var_export($last_error, true) . ')';
1549 common_log(LOG_ERR, $msg . '(' . $verb . ' on ' . $objstr . ')', $filename);
1552 function common_log_objstring(&$object)
1554 if (is_null($object)) {
1557 if (!($object instanceof DB_DataObject)) {
1560 $arr = $object->toArray();
1562 foreach ($arr as $k => $v) {
1563 if (is_object($v)) {
1564 $fields[] = "$k='".get_class($v)."'";
1566 $fields[] = "$k='$v'";
1569 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1573 function common_valid_http_url($url)
1575 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1578 function common_valid_tag($tag)
1580 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1581 return (Validate::email($matches[1]) ||
1582 preg_match('/^([\w-\.]+)$/', $matches[1]));
1588 * Determine if given domain or address literal is valid
1589 * eg for use in JIDs and URLs. Does not check if the domain
1592 * @param string $domain
1593 * @return boolean valid or not
1595 function common_valid_domain($domain)
1597 $octet = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])";
1598 $ipv4 = "(?:$octet(?:\.$octet){3})";
1599 if (preg_match("/^$ipv4$/u", $domain)) return true;
1601 $group = "(?:[0-9a-f]{1,4})";
1602 $ipv6 = "(?:\[($group(?::$group){0,7})?(::)?($group(?::$group){0,7})?\])"; // http://tools.ietf.org/html/rfc3513#section-2.2
1604 if (preg_match("/^$ipv6$/ui", $domain, $matches)) {
1605 $before = explode(":", $matches[1]);
1606 $zeroes = $matches[2];
1607 $after = explode(":", $matches[3]);
1615 $explicit = count($before) + count($after);
1616 if ($explicit < $min || $explicit > $max) {
1623 require_once "Net/IDNA.php";
1624 $idn = Net_IDNA::getInstance();
1625 $domain = $idn->encode($domain);
1626 } catch (Exception $e) {
1630 $subdomain = "(?:[a-z0-9][a-z0-9-]*)"; // @fixme
1631 $fqdn = "(?:$subdomain(?:\.$subdomain)*\.?)";
1633 return preg_match("/^$fqdn$/ui", $domain);
1636 /* Following functions are copied from MediaWiki GlobalFunctions.php
1637 * and written by Evan Prodromou. */
1639 function common_accept_to_prefs($accept, $def = '*/*')
1641 // No arg means accept anything (per HTTP spec)
1643 return array($def => 1);
1648 $parts = explode(',', $accept);
1650 foreach($parts as $part) {
1651 // FIXME: doesn't deal with params like 'text/html; level=1'
1652 @list($value, $qpart) = explode(';', trim($part));
1654 if(!isset($qpart)) {
1656 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1657 $prefs[$value] = $match[1];
1664 function common_mime_type_match($type, $avail)
1666 if(array_key_exists($type, $avail)) {
1669 $parts = explode('/', $type);
1670 if(array_key_exists($parts[0] . '/*', $avail)) {
1671 return $parts[0] . '/*';
1672 } elseif(array_key_exists('*/*', $avail)) {
1680 function common_negotiate_type($cprefs, $sprefs)
1684 foreach(array_keys($sprefs) as $type) {
1685 $parts = explode('/', $type);
1686 if($parts[1] != '*') {
1687 $ckey = common_mime_type_match($type, $cprefs);
1689 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1694 foreach(array_keys($cprefs) as $type) {
1695 $parts = explode('/', $type);
1696 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1697 $skey = common_mime_type_match($type, $sprefs);
1699 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1705 $besttype = 'text/html';
1707 foreach(array_keys($combine) as $type) {
1708 if($combine[$type] > $bestq) {
1710 $bestq = $combine[$type];
1714 if ('text/html' === $besttype) {
1715 return "text/html; charset=utf-8";
1720 function common_config($main, $sub)
1723 return (array_key_exists($main, $config) &&
1724 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1728 * Pull arguments from a GET/POST/REQUEST array with first-level input checks:
1729 * strips "magic quotes" slashes if necessary, and kills invalid UTF-8 strings.
1731 * @param array $from
1734 function common_copy_args($from)
1737 $strip = get_magic_quotes_gpc();
1738 foreach ($from as $k => $v) {
1740 $to[$k] = common_copy_args($v);
1743 $v = stripslashes($v);
1745 $to[$k] = strval(common_validate_utf8($v));
1752 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1753 * This is used before handing a request off to OAuthRequest::from_request.
1754 * @fixme Doesn't consider vars other than _POST and _GET?
1755 * @fixme Can't be undone and could corrupt data if run twice.
1757 function common_remove_magic_from_request()
1759 if(get_magic_quotes_gpc()) {
1760 $_POST=array_map('stripslashes',$_POST);
1761 $_GET=array_map('stripslashes',$_GET);
1765 function common_user_uri(&$user)
1767 return common_local_url('userbyid', array('id' => $user->id),
1771 function common_notice_uri(&$notice)
1773 return common_local_url('shownotice',
1774 array('notice' => $notice->id),
1778 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1780 function common_confirmation_code($bits)
1782 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1783 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1784 $chars = ceil($bits/5);
1786 for ($i = 0; $i < $chars; $i++) {
1787 // XXX: convert to string and back
1788 $num = hexdec(common_good_rand(1));
1789 // XXX: randomness is too precious to throw away almost
1790 // 40% of the bits we get!
1791 $code .= $codechars[$num%32];
1796 // convert markup to HTML
1798 function common_markup_to_html($c)
1800 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1801 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1802 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1803 return Markdown($c);
1806 function common_profile_uri($profile)
1811 $user = User::staticGet($profile->id);
1816 $remote = Remote_profile::staticGet($profile->id);
1818 return $remote->uri;
1820 // XXX: this is a very bad profile!
1824 function common_canonical_sms($sms)
1827 preg_replace('/\D/', '', $sms);
1831 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1836 case E_COMPILE_ERROR:
1840 case E_RECOVERABLE_ERROR:
1841 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1846 case E_COMPILE_WARNING:
1847 case E_CORE_WARNING:
1848 case E_USER_WARNING:
1849 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1854 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1859 case E_USER_DEPRECATED:
1860 // XXX: config variable to log this stuff, too
1864 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1869 // FIXME: show error page if we're on the Web
1870 /* Don't execute PHP internal error handler */
1874 function common_session_token()
1876 common_ensure_session();
1877 if (!array_key_exists('token', $_SESSION)) {
1878 $_SESSION['token'] = common_good_rand(64);
1880 return $_SESSION['token'];
1883 function common_license_terms($uri)
1885 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1886 return explode('-',$matches[1]);
1891 function common_compatible_license($from, $to)
1893 $from_terms = common_license_terms($from);
1894 // public domain and cc-by are compatible with everything
1895 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1898 $to_terms = common_license_terms($to);
1899 // sa is compatible across versions. IANAL
1900 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1901 return count(array_diff($from_terms, $to_terms)) == 0;
1903 // XXX: better compatibility check needed here!
1904 // Should at least normalise URIs
1905 return ($from == $to);
1909 * returns a quoted table name, if required according to config
1911 function common_database_tablename($tablename)
1913 if(common_config('db','quote_identifiers')) {
1914 $tablename = '"'. $tablename .'"';
1916 //table prefixes could be added here later
1921 * Shorten a URL with the current user's configured shortening service,
1922 * or ur1.ca if configured, or not at all if no shortening is set up.
1924 * @param string $long_url original URL
1925 * @param boolean $force Force shortening (used when notice is too long)
1927 * @return string may return the original URL if shortening failed
1929 * @fixme provide a way to specify a particular shortener
1930 * @fixme provide a way to specify to use a given user's shortening preferences
1933 function common_shorten_url($long_url, $force = false)
1935 common_debug("Shortening URL '$long_url' (force = $force)");
1937 $long_url = trim($long_url);
1939 $user = common_current_user();
1941 $maxUrlLength = User_urlshortener_prefs::maxUrlLength($user);
1942 common_debug("maxUrlLength = $maxUrlLength");
1944 // $force forces shortening even if it's not strictly needed
1946 if (mb_strlen($long_url) < $maxUrlLength && !$force) {
1947 common_debug("Skipped shortening URL.");
1951 $shortenerName = User_urlshortener_prefs::urlShorteningService($user);
1953 common_debug("Shortener name = '$shortenerName'");
1955 if (Event::handle('StartShortenUrl', array($long_url, $shortenerName, &$shortenedUrl))) {
1956 //URL wasn't shortened, so return the long url
1959 //URL was shortened, so return the result
1960 return trim($shortenedUrl);
1965 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1966 * null if not a web request
1968 * @fixme X-Forwarded-For can be chained by multiple proxies;
1969 we should parse the list and provide a cleaner array
1970 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1971 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1972 * use function to get exact request headers from Apache if possible.
1974 function common_client_ip()
1976 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1980 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1981 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1982 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1984 $proxy = $_SERVER['REMOTE_ADDR'];
1986 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1989 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1990 $ip = $_SERVER['HTTP_CLIENT_IP'];
1992 $ip = $_SERVER['REMOTE_ADDR'];
1996 return array($proxy, $ip);
1999 function common_url_to_nickname($url)
2001 static $bad = array('query', 'user', 'password', 'port', 'fragment');
2003 $parts = parse_url($url);
2005 # If any of these parts exist, this won't work
2007 foreach ($bad as $badpart) {
2008 if (array_key_exists($badpart, $parts)) {
2013 # We just have host and/or path
2015 # If it's just a host...
2016 if (array_key_exists('host', $parts) &&
2017 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
2019 $hostparts = explode('.', $parts['host']);
2021 # Try to catch common idiom of nickname.service.tld
2023 if ((count($hostparts) > 2) &&
2024 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
2025 (strcmp($hostparts[0], 'www') != 0))
2027 return common_nicknamize($hostparts[0]);
2029 # Do the whole hostname
2030 return common_nicknamize($parts['host']);
2033 if (array_key_exists('path', $parts)) {
2034 # Strip starting, ending slashes
2035 $path = preg_replace('@/$@', '', $parts['path']);
2036 $path = preg_replace('@^/@', '', $path);
2037 $path = basename($path);
2039 // Hack for MediaWiki user pages, in the form:
2040 // http://example.com/wiki/User:Myname
2041 // ('User' may be localized.)
2042 if (strpos($path, ':')) {
2043 $parts = array_filter(explode(':', $path));
2044 $path = $parts[count($parts) - 1];
2048 return common_nicknamize($path);
2056 function common_nicknamize($str)
2058 $str = preg_replace('/\W/', '', $str);
2059 return strtolower($str);