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) */
22 // Show a server error
24 function common_server_error($msg, $code=500)
26 $err = new ServerErrorAction($msg, $code);
31 function common_user_error($msg, $code=400)
33 $err = new ClientErrorAction($msg, $code);
37 function common_init_locale($language=null)
40 $language = common_language();
42 putenv('LANGUAGE='.$language);
43 putenv('LANG='.$language);
44 $ok = setlocale(LC_ALL, $language . ".utf8",
53 function common_init_language()
55 mb_internal_encoding('UTF-8');
57 // Note that this setlocale() call may "fail" but this is harmless;
58 // gettext will still select the right language.
59 $language = common_language();
60 $locale_set = common_init_locale($language);
63 // The requested locale doesn't exist on the system.
65 // gettext seems very picky... We first need to setlocale()
66 // to a locale which _does_ exist on the system, and _then_
67 // we can set in another locale that may not be set up
68 // (say, ga_ES for Galego/Galician) it seems to take it.
70 // For some reason C and POSIX which are guaranteed to work
71 // don't do the job. en_US.UTF-8 should be there most of the
72 // time, but not guaranteed.
73 $ok = common_init_locale("en_US");
75 // Try to find a complete, working locale...
76 // @fixme shelling out feels awfully inefficient
77 // but I don't think there's a more standard way.
79 foreach (explode("\n", $all) as $locale) {
80 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
81 $ok = setlocale(LC_ALL, $locale);
88 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
91 $locale_set = common_init_locale($language);
94 common_init_gettext();
100 function common_init_gettext()
102 setlocale(LC_CTYPE, 'C');
103 // So we do not have to make people install the gettext locales
104 $path = common_config('site','locale_path');
105 bindtextdomain("statusnet", $path);
106 bind_textdomain_codeset("statusnet", "UTF-8");
107 textdomain("statusnet");
111 * Switch locale during runtime, and poke gettext until it cries uncle.
112 * Otherwise, sometimes it doesn't actually switch away from the old language.
114 * @param string $language code for locale ('en', 'fr', 'pt_BR' etc)
116 function common_switch_locale($language=null)
118 common_init_locale($language);
120 setlocale(LC_CTYPE, 'C');
121 // So we do not have to make people install the gettext locales
122 $path = common_config('site','locale_path');
123 bindtextdomain("statusnet", $path);
124 bind_textdomain_codeset("statusnet", "UTF-8");
125 textdomain("statusnet");
129 function common_timezone()
131 if (common_logged_in()) {
132 $user = common_current_user();
133 if ($user->timezone) {
134 return $user->timezone;
138 return common_config('site', 'timezone');
141 function common_language()
144 // If there is a user logged in and they've set a language preference
145 // then return that one...
146 if (_have_config() && common_logged_in()) {
147 $user = common_current_user();
148 $user_language = $user->language;
150 if ($user->language) {
151 // Validate -- we don't want to end up with a bogus code
152 // left over from some old junk.
153 foreach (common_config('site', 'languages') as $code => $info) {
154 if ($info['lang'] == $user_language) {
155 return $user_language;
161 // Otherwise, find the best match for the languages requested by the
163 if (common_config('site', 'langdetect')) {
164 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
165 if (!empty($httplang)) {
166 $language = client_prefered_language($httplang);
172 // Finally, if none of the above worked, use the site's default...
173 return common_config('site', 'language');
175 // salted, hashed passwords are stored in the DB
177 function common_munge_password($password, $id)
179 if (is_object($id) || is_object($password)) {
180 $e = new Exception();
181 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
182 str_replace("\n", " ", $e->getTraceAsString()));
184 return md5($password . $id);
187 // check if a username exists and has matching password
189 function common_check_user($nickname, $password)
191 // empty nickname always unacceptable
192 if (empty($nickname)) {
196 $authenticatedUser = false;
198 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
199 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
201 if (!empty($password)) { // never allow login with blank password
202 if (0 == strcmp(common_munge_password($password, $user->id),
204 //internal checking passed
205 $authenticatedUser = $user;
209 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
212 return $authenticatedUser;
215 // is the current user logged in?
216 function common_logged_in()
218 return (!is_null(common_current_user()));
221 function common_have_session()
223 return (0 != strcmp(session_id(), ''));
226 function common_ensure_session()
229 if (array_key_exists(session_name(), $_COOKIE)) {
230 $c = $_COOKIE[session_name()];
232 if (!common_have_session()) {
233 if (common_config('sessions', 'handle')) {
234 Session::setSaveHandler();
236 if (array_key_exists(session_name(), $_GET)) {
237 $id = $_GET[session_name()];
238 } else if (array_key_exists(session_name(), $_COOKIE)) {
239 $id = $_COOKIE[session_name()];
245 if (!isset($_SESSION['started'])) {
246 $_SESSION['started'] = time();
248 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
249 ' is set but started value is null');
255 // Three kinds of arguments:
260 // Initialize to false; set to null if none found
264 function common_set_user($user)
269 if (is_null($user) && common_have_session()) {
271 unset($_SESSION['userid']);
273 } else if (is_string($user)) {
275 $user = User::staticGet('nickname', $nickname);
276 } else if (!($user instanceof User)) {
281 if (Event::handle('StartSetUser', array(&$user))) {
283 common_ensure_session();
284 $_SESSION['userid'] = $user->id;
286 Event::handle('EndSetUser', array($user));
294 function common_set_cookie($key, $value, $expiration=0)
296 $path = common_config('site', 'path');
297 $server = common_config('site', 'server');
299 if ($path && ($path != '/')) {
300 $cookiepath = '/' . $path . '/';
304 return setcookie($key,
311 define('REMEMBERME', 'rememberme');
312 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
314 function common_rememberme($user=null)
317 $user = common_current_user();
323 $rm = new Remember_me();
325 $rm->code = common_good_rand(16);
326 $rm->user_id = $user->id;
328 // Wrap the insert in some good ol' fashioned transaction code
332 $result = $rm->insert();
335 common_log_db_error($rm, 'INSERT', __FILE__);
339 $rm->query('COMMIT');
341 $cookieval = $rm->user_id . ':' . $rm->code;
343 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
345 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
350 function common_remembered_user()
355 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
361 list($id, $code) = explode(':', $packed);
363 if (!$id || !$code) {
364 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
369 $rm = Remember_me::staticGet($code);
372 common_log(LOG_WARNING, 'No such remember code: ' . $code);
377 if ($rm->user_id != $id) {
378 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
383 $user = User::staticGet($rm->user_id);
386 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
392 $result = $rm->delete();
395 common_log_db_error($rm, 'DELETE', __FILE__);
396 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
401 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
403 common_set_user($user);
404 common_real_login(false);
406 // We issue a new cookie, so they can log in
407 // automatically again after this session
409 common_rememberme($user);
414 // must be called with a valid user!
416 function common_forgetme()
418 common_set_cookie(REMEMBERME, '', 0);
421 // who is the current user?
422 function common_current_user()
426 if (!_have_config()) {
430 if ($_cur === false) {
432 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
433 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
434 common_ensure_session();
435 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
437 $user = User::staticGet($id);
445 // that didn't work; try to remember; will init $_cur to null on failure
446 $_cur = common_remembered_user();
449 // XXX: Is this necessary?
450 $_SESSION['userid'] = $_cur->id;
457 // Logins that are 'remembered' aren't 'real' -- they're subject to
458 // cookie-stealing. So, we don't let them do certain things. New reg,
459 // OpenID, and password logins _are_ real.
461 function common_real_login($real=true)
463 common_ensure_session();
464 $_SESSION['real_login'] = $real;
467 function common_is_real_login()
469 return common_logged_in() && $_SESSION['real_login'];
472 // get canonical version of nickname for comparison
473 function common_canonical_nickname($nickname)
475 // XXX: UTF-8 canonicalization (like combining chars)
476 return strtolower($nickname);
479 // get canonical version of email for comparison
480 function common_canonical_email($email)
482 // XXX: canonicalize UTF-8
483 // XXX: lcase the domain part
487 function common_render_content($text, $notice)
489 $r = common_render_text($text);
490 $id = $notice->profile_id;
491 $r = common_linkify_mentions($r, $notice);
492 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
496 function common_linkify_mentions($text, $notice)
498 $mentions = common_find_mentions($text, $notice);
500 // We need to go through in reverse order by position,
501 // so our positions stay valid despite our fudging with the
506 foreach ($mentions as $mention)
508 $points[$mention['position']] = $mention;
513 foreach ($points as $position => $mention) {
515 $linkText = common_linkify_mention($mention);
517 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
523 function common_linkify_mention($mention)
527 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
529 $xs = new XMLStringer(false);
531 $attrs = array('href' => $mention['url'],
534 if (!empty($mention['title'])) {
535 $attrs['title'] = $mention['title'];
538 $xs->elementStart('span', 'vcard');
539 $xs->elementStart('a', $attrs);
540 $xs->element('span', 'fn nickname', $mention['text']);
541 $xs->elementEnd('a');
542 $xs->elementEnd('span');
544 $output = $xs->getString();
546 Event::handle('EndLinkifyMention', array($mention, &$output));
552 function common_find_mentions($text, $notice)
556 $sender = Profile::staticGet('id', $notice->profile_id);
558 if (empty($sender)) {
562 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
564 // Get the context of the original notice, if any
566 $originalAuthor = null;
567 $originalNotice = null;
568 $originalMentions = array();
572 if (!empty($notice) && !empty($notice->reply_to)) {
573 $originalNotice = Notice::staticGet('id', $notice->reply_to);
574 if (!empty($originalNotice)) {
575 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
577 $ids = $originalNotice->getReplies();
579 foreach ($ids as $id) {
580 $repliedTo = Profile::staticGet('id', $id);
581 if (!empty($repliedTo)) {
582 $originalMentions[$repliedTo->nickname] = $repliedTo;
588 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
591 PREG_OFFSET_CAPTURE);
593 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
596 PREG_OFFSET_CAPTURE);
598 $matches = array_merge($tmatches[1], $atmatches[1]);
600 foreach ($matches as $match) {
602 $nickname = common_canonical_nickname($match[0]);
604 // Try to get a profile for this nickname.
605 // Start with conversation context, then go to
608 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
610 $mentioned = $originalAuthor;
612 } else if (!empty($originalMentions) &&
613 array_key_exists($nickname, $originalMentions)) {
615 $mentioned = $originalMentions[$nickname];
617 $mentioned = common_relative_profile($sender, $nickname);
620 if (!empty($mentioned)) {
622 $user = User::staticGet('id', $mentioned->id);
625 $url = common_local_url('userbyid', array('id' => $user->id));
627 $url = $mentioned->profileurl;
630 $mention = array('mentioned' => array($mentioned),
632 'position' => $match[1],
635 if (!empty($mentioned->fullname)) {
636 $mention['title'] = $mentioned->fullname;
639 $mentions[] = $mention;
643 // @#tag => mention of all subscriptions tagged 'tag'
645 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
648 PREG_OFFSET_CAPTURE);
650 foreach ($hmatches[1] as $hmatch) {
652 $tag = common_canonical_tag($hmatch[0]);
654 $tagged = Profile_tag::getTagged($sender->id, $tag);
656 $url = common_local_url('subscriptions',
657 array('nickname' => $sender->nickname,
660 $mentions[] = array('mentioned' => $tagged,
661 'text' => $hmatch[0],
662 'position' => $hmatch[1],
666 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
672 function common_render_text($text)
674 $r = htmlspecialchars($text);
676 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
677 $r = common_replace_urls_callback($r, 'common_linkify');
678 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
683 function common_replace_urls_callback($text, $callback, $notice_id = null) {
684 // Start off with a regex
686 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
689 '(?:'. //Known protocols
691 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
693 '(?:(?:mailto|aim|tel|xmpp):)'.
695 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
698 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
700 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
704 '|(?:(?: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
706 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
708 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
709 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
710 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
711 '(?: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)'.
715 '(?:\:\d+)?'. //:port
716 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
717 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
718 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
719 ')(?<![\?\.\,\#\,])'.
722 //preg_match_all($regex,$text,$matches);
724 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
727 function callback_helper($matches, $callback, $notice_id) {
729 $left = strpos($matches[0],$url);
730 $right = $left+strlen($url);
732 $groupSymbolSets=array(
750 $cannotEndWith=array('.','?',',','#');
754 foreach($groupSymbolSets as $groupSymbolSet){
755 if(substr($url,-1)==$groupSymbolSet['right']){
756 $group_left_count = substr_count($url,$groupSymbolSet['left']);
757 $group_right_count = substr_count($url,$groupSymbolSet['right']);
758 if($group_left_count<$group_right_count){
760 $url=substr($url,0,-1);
764 if(in_array(substr($url,-1),$cannotEndWith)){
766 $url=substr($url,0,-1);
768 }while($original_url!=$url);
770 if(empty($notice_id)){
771 $result = call_user_func_array($callback, array($url));
773 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
775 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
778 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
779 // lambda implementation in a separate file; PHP 5.2 won't parse it.
780 require_once INSTALLDIR . "/lib/curry.php";
782 function curry($fn) {
783 $args = func_get_args();
785 $id = uniqid('_partial');
786 $GLOBALS[$id] = array($fn, $args);
787 return create_function('',
788 '$args = func_get_args(); '.
789 'return call_user_func_array('.
790 '$GLOBALS["'.$id.'"][0],'.
793 '$GLOBALS["'.$id.'"][1]));');
797 function common_linkify($url) {
798 // It comes in special'd, so we unspecial it before passing to the stringifying
800 $url = htmlspecialchars_decode($url);
802 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
803 //url is an email address without the mailto: protocol
804 $canon = "mailto:$url";
805 $longurl = "mailto:$url";
808 $canon = File_redirection::_canonUrl($url);
810 $longurl_data = File_redirection::where($canon);
811 if (is_array($longurl_data)) {
812 $longurl = $longurl_data['url'];
813 } elseif (is_string($longurl_data)) {
814 $longurl = $longurl_data;
816 throw new ServerException("Can't linkify url '$url'");
819 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
821 $is_attachment = false;
822 $attachment_id = null;
825 // Check to see whether this is a known "attachment" URL.
827 $f = File::staticGet('url', $longurl);
830 // XXX: this writes to the database. :<
831 $f = File::processNew($longurl);
835 if ($f->getEnclosure()) {
836 $is_attachment = true;
837 $attachment_id = $f->id;
839 $thumb = File_thumbnail::staticGet('file_id', $f->id);
840 if (!empty($thumb)) {
847 if ($is_attachment) {
848 $attrs['class'] = 'attachment';
850 $attrs['class'] = 'attachment thumbnail';
852 $attrs['id'] = "attachment-{$attachment_id}";
855 return XMLStringer::estring('a', $attrs, $url);
858 function common_shorten_links($text)
860 $maxLength = Notice::maxContent();
861 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
862 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
865 function common_xml_safe_str($str)
867 // Replace common eol and extra whitespace input chars
872 "\0", // null byte eos
873 "\x0B" // vertical tab
876 $replacement = array(
884 $str = str_replace($unWelcome, $replacement, $str);
886 // Neutralize any additional control codes and UTF-16 surrogates
887 // (Twitter uses '*')
888 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
891 function common_tag_link($tag)
893 $canonical = common_canonical_tag($tag);
894 if (common_config('singleuser', 'enabled')) {
895 // regular TagAction isn't set up in 1user mode
896 $url = common_local_url('showstream',
897 array('nickname' => common_config('singleuser', 'nickname'),
898 'tag' => $canonical));
900 $url = common_local_url('tag', array('tag' => $canonical));
902 $xs = new XMLStringer();
903 $xs->elementStart('span', 'tag');
904 $xs->element('a', array('href' => $url,
907 $xs->elementEnd('span');
908 return $xs->getString();
911 function common_canonical_tag($tag)
913 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
914 return str_replace(array('-', '_', '.'), '', $tag);
917 function common_valid_profile_tag($str)
919 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
922 function common_group_link($sender_id, $nickname)
924 $sender = Profile::staticGet($sender_id);
925 $group = User_group::getForNickname($nickname, $sender);
926 if ($sender && $group && $sender->isMember($group)) {
927 $attrs = array('href' => $group->permalink(),
929 if (!empty($group->fullname)) {
930 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
932 $xs = new XMLStringer();
933 $xs->elementStart('span', 'vcard');
934 $xs->elementStart('a', $attrs);
935 $xs->element('span', 'fn nickname', $nickname);
936 $xs->elementEnd('a');
937 $xs->elementEnd('span');
938 return $xs->getString();
944 function common_relative_profile($sender, $nickname, $dt=null)
946 // Try to find profiles this profile is subscribed to that have this nickname
947 $recipient = new Profile();
948 // XXX: use a join instead of a subquery
949 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
950 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
951 if ($recipient->find(true)) {
952 // XXX: should probably differentiate between profiles with
953 // the same name by date of most recent update
956 // Try to find profiles that listen to this profile and that have this nickname
957 $recipient = new Profile();
958 // XXX: use a join instead of a subquery
959 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
960 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
961 if ($recipient->find(true)) {
962 // XXX: should probably differentiate between profiles with
963 // the same name by date of most recent update
966 // If this is a local user, try to find a local user with that nickname.
967 $sender = User::staticGet($sender->id);
969 $recipient_user = User::staticGet('nickname', $nickname);
970 if ($recipient_user) {
971 return $recipient_user->getProfile();
974 // Otherwise, no links. @messages from local users to remote users,
975 // or from remote users to other remote users, are just
976 // outside our ability to make intelligent guesses about
980 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
983 $path = $r->build($action, $args, $params, $fragment);
985 $ssl = common_is_sensitive($action);
987 if (common_config('site','fancy')) {
988 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
990 if (mb_strpos($path, '/index.php') === 0) {
991 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
993 $url = common_path('index.php'.$path, $ssl, $addSession);
999 function common_is_sensitive($action)
1001 static $sensitive = array('login', 'register', 'passwordsettings',
1002 'twittersettings', 'api');
1005 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
1006 $ssl = in_array($action, $sensitive);
1012 function common_path($relative, $ssl=false, $addSession=true)
1014 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
1016 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
1017 || common_config('site', 'ssl') === 'always') {
1019 if (is_string(common_config('site', 'sslserver')) &&
1020 mb_strlen(common_config('site', 'sslserver')) > 0) {
1021 $serverpart = common_config('site', 'sslserver');
1022 } else if (common_config('site', 'server')) {
1023 $serverpart = common_config('site', 'server');
1025 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1029 if (common_config('site', 'server')) {
1030 $serverpart = common_config('site', 'server');
1032 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
1037 $relative = common_inject_session($relative, $serverpart);
1040 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1043 function common_inject_session($url, $serverpart = null)
1045 if (common_have_session()) {
1047 if (empty($serverpart)) {
1048 $serverpart = parse_url($url, PHP_URL_HOST);
1051 $currentServer = $_SERVER['HTTP_HOST'];
1053 // Are we pointing to another server (like an SSL server?)
1055 if (!empty($currentServer) &&
1056 0 != strcasecmp($currentServer, $serverpart)) {
1057 // Pass the session ID as a GET parameter
1058 $sesspart = session_name() . '=' . session_id();
1059 $i = strpos($url, '?');
1060 if ($i === false) { // no GET params, just append
1061 $url .= '?' . $sesspart;
1063 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1071 function common_date_string($dt)
1073 // XXX: do some sexy date formatting
1074 // return date(DATE_RFC822, $dt);
1075 $t = strtotime($dt);
1079 if ($now < $t) { // that shouldn't happen!
1080 return common_exact_date($dt);
1081 } else if ($diff < 60) {
1082 return _('a few seconds ago');
1083 } else if ($diff < 92) {
1084 return _('about a minute ago');
1085 } else if ($diff < 3300) {
1086 return sprintf(_('about %d minutes ago'), round($diff/60));
1087 } else if ($diff < 5400) {
1088 return _('about an hour ago');
1089 } else if ($diff < 22 * 3600) {
1090 return sprintf(_('about %d hours ago'), round($diff/3600));
1091 } else if ($diff < 37 * 3600) {
1092 return _('about a day ago');
1093 } else if ($diff < 24 * 24 * 3600) {
1094 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1095 } else if ($diff < 46 * 24 * 3600) {
1096 return _('about a month ago');
1097 } else if ($diff < 330 * 24 * 3600) {
1098 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1099 } else if ($diff < 480 * 24 * 3600) {
1100 return _('about a year ago');
1102 return common_exact_date($dt);
1106 function common_exact_date($dt)
1112 $_utc = new DateTimeZone('UTC');
1113 $_siteTz = new DateTimeZone(common_timezone());
1116 $dateStr = date('d F Y H:i:s', strtotime($dt));
1117 $d = new DateTime($dateStr, $_utc);
1118 $d->setTimezone($_siteTz);
1119 return $d->format(DATE_RFC850);
1122 function common_date_w3dtf($dt)
1124 $dateStr = date('d F Y H:i:s', strtotime($dt));
1125 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1126 $d->setTimezone(new DateTimeZone(common_timezone()));
1127 return $d->format(DATE_W3C);
1130 function common_date_rfc2822($dt)
1132 $dateStr = date('d F Y H:i:s', strtotime($dt));
1133 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1134 $d->setTimezone(new DateTimeZone(common_timezone()));
1135 return $d->format('r');
1138 function common_date_iso8601($dt)
1140 $dateStr = date('d F Y H:i:s', strtotime($dt));
1141 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1142 $d->setTimezone(new DateTimeZone(common_timezone()));
1143 return $d->format('c');
1146 function common_sql_now()
1148 return common_sql_date(time());
1151 function common_sql_date($datetime)
1153 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1157 * Return an SQL fragment to calculate an age-based weight from a given
1158 * timestamp or datetime column.
1160 * @param string $column name of field we're comparing against current time
1161 * @param integer $dropoff divisor for age in seconds before exponentiation
1162 * @return string SQL fragment
1164 function common_sql_weight($column, $dropoff)
1166 if (common_config('db', 'type') == 'pgsql') {
1167 // PostgreSQL doesn't support timestampdiff function.
1168 // @fixme will this use the right time zone?
1169 // @fixme does this handle cross-year subtraction correctly?
1170 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1172 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1176 function common_redirect($url, $code=307)
1178 static $status = array(301 => "Moved Permanently",
1181 307 => "Temporary Redirect");
1183 header('HTTP/1.1 '.$code.' '.$status[$code]);
1184 header("Location: $url");
1186 $xo = new XMLOutputter();
1188 '-//W3C//DTD XHTML 1.0 Strict//EN',
1189 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1190 $xo->element('a', array('href' => $url), $url);
1195 function common_broadcast_notice($notice, $remote=false)
1200 // Stick the notice on the queue
1202 function common_enqueue_notice($notice)
1204 static $localTransports = array('omb',
1207 $transports = array();
1208 if (common_config('sms', 'enabled')) {
1209 $transports[] = 'sms';
1211 if (Event::hasHandler('HandleQueuedNotice')) {
1212 $transports[] = 'plugin';
1215 $xmpp = common_config('xmpp', 'enabled');
1218 $transports[] = 'jabber';
1221 // @fixme move these checks into QueueManager and/or individual handlers
1222 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1223 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1224 $transports = array_merge($transports, $localTransports);
1226 $transports[] = 'public';
1230 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1232 $qm = QueueManager::get();
1234 foreach ($transports as $transport)
1236 $qm->enqueue($notice, $transport);
1239 Event::handle('EndEnqueueNotice', array($notice, $transports));
1246 * Broadcast profile updates to OMB and other remote subscribers.
1248 * Since this may be slow with a lot of subscribers or bad remote sites,
1249 * this is run through the background queues if possible.
1251 function common_broadcast_profile(Profile $profile)
1253 $qm = QueueManager::get();
1254 $qm->enqueue($profile, "profile");
1258 function common_profile_url($nickname)
1260 return common_local_url('showstream', array('nickname' => $nickname),
1264 // Should make up a reasonable root URL
1266 function common_root_url($ssl=false)
1268 $url = common_path('', $ssl, false);
1269 $i = strpos($url, '?');
1271 $url = substr($url, 0, $i);
1276 // returns $bytes bytes of random data as a hexadecimal string
1277 // "good" here is a goal and not a guarantee
1279 function common_good_rand($bytes)
1281 // XXX: use random.org...?
1282 if (@file_exists('/dev/urandom')) {
1283 return common_urandom($bytes);
1284 } else { // FIXME: this is probably not good enough
1285 return common_mtrand($bytes);
1289 function common_urandom($bytes)
1291 $h = fopen('/dev/urandom', 'rb');
1293 $src = fread($h, $bytes);
1296 for ($i = 0; $i < $bytes; $i++) {
1297 $enc .= sprintf("%02x", (ord($src[$i])));
1302 function common_mtrand($bytes)
1305 for ($i = 0; $i < $bytes; $i++) {
1306 $enc .= sprintf("%02x", mt_rand(0, 255));
1311 function common_set_returnto($url)
1313 common_ensure_session();
1314 $_SESSION['returnto'] = $url;
1317 function common_get_returnto()
1319 common_ensure_session();
1320 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1323 function common_timestamp()
1325 return date('YmdHis');
1328 function common_ensure_syslog()
1330 static $initialized = false;
1331 if (!$initialized) {
1332 openlog(common_config('syslog', 'appname'), 0,
1333 common_config('syslog', 'facility'));
1334 $initialized = true;
1338 function common_log_line($priority, $msg)
1340 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1341 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1342 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1345 function common_request_id()
1348 $server = common_config('site', 'server');
1349 if (php_sapi_name() == 'cli') {
1350 $script = basename($_SERVER['PHP_SELF']);
1351 return "$server:$script:$pid";
1353 static $req_id = null;
1354 if (!isset($req_id)) {
1355 $req_id = substr(md5(mt_rand()), 0, 8);
1357 if (isset($_SERVER['REQUEST_URI'])) {
1358 $url = $_SERVER['REQUEST_URI'];
1360 $method = $_SERVER['REQUEST_METHOD'];
1361 return "$server:$pid.$req_id $method $url";
1365 function common_log($priority, $msg, $filename=null)
1367 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1368 $msg = '[' . common_request_id() . '] ' . $msg;
1369 $logfile = common_config('site', 'logfile');
1371 $log = fopen($logfile, "a");
1373 $output = common_log_line($priority, $msg);
1374 fwrite($log, $output);
1378 common_ensure_syslog();
1379 syslog($priority, $msg);
1381 Event::handle('EndLog', array($priority, $msg, $filename));
1385 function common_debug($msg, $filename=null)
1388 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1390 common_log(LOG_DEBUG, $msg);
1394 function common_log_db_error(&$object, $verb, $filename=null)
1396 $objstr = common_log_objstring($object);
1397 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1398 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1401 function common_log_objstring(&$object)
1403 if (is_null($object)) {
1406 if (!($object instanceof DB_DataObject)) {
1409 $arr = $object->toArray();
1411 foreach ($arr as $k => $v) {
1412 if (is_object($v)) {
1413 $fields[] = "$k='".get_class($v)."'";
1415 $fields[] = "$k='$v'";
1418 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1422 function common_valid_http_url($url)
1424 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1427 function common_valid_tag($tag)
1429 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1430 return (Validate::email($matches[1]) ||
1431 preg_match('/^([\w-\.]+)$/', $matches[1]));
1436 /* Following functions are copied from MediaWiki GlobalFunctions.php
1437 * and written by Evan Prodromou. */
1439 function common_accept_to_prefs($accept, $def = '*/*')
1441 // No arg means accept anything (per HTTP spec)
1443 return array($def => 1);
1448 $parts = explode(',', $accept);
1450 foreach($parts as $part) {
1451 // FIXME: doesn't deal with params like 'text/html; level=1'
1452 @list($value, $qpart) = explode(';', trim($part));
1454 if(!isset($qpart)) {
1456 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1457 $prefs[$value] = $match[1];
1464 function common_mime_type_match($type, $avail)
1466 if(array_key_exists($type, $avail)) {
1469 $parts = explode('/', $type);
1470 if(array_key_exists($parts[0] . '/*', $avail)) {
1471 return $parts[0] . '/*';
1472 } elseif(array_key_exists('*/*', $avail)) {
1480 function common_negotiate_type($cprefs, $sprefs)
1484 foreach(array_keys($sprefs) as $type) {
1485 $parts = explode('/', $type);
1486 if($parts[1] != '*') {
1487 $ckey = common_mime_type_match($type, $cprefs);
1489 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1494 foreach(array_keys($cprefs) as $type) {
1495 $parts = explode('/', $type);
1496 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1497 $skey = common_mime_type_match($type, $sprefs);
1499 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1505 $besttype = 'text/html';
1507 foreach(array_keys($combine) as $type) {
1508 if($combine[$type] > $bestq) {
1510 $bestq = $combine[$type];
1514 if ('text/html' === $besttype) {
1515 return "text/html; charset=utf-8";
1520 function common_config($main, $sub)
1523 return (array_key_exists($main, $config) &&
1524 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1527 function common_copy_args($from)
1530 $strip = get_magic_quotes_gpc();
1531 foreach ($from as $k => $v) {
1534 $to[$k] = common_copy_args($v);
1536 $to[$k] = stripslashes($v);
1546 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1547 * This is used before handing a request off to OAuthRequest::from_request.
1548 * @fixme Doesn't consider vars other than _POST and _GET?
1549 * @fixme Can't be undone and could corrupt data if run twice.
1551 function common_remove_magic_from_request()
1553 if(get_magic_quotes_gpc()) {
1554 $_POST=array_map('stripslashes',$_POST);
1555 $_GET=array_map('stripslashes',$_GET);
1559 function common_user_uri(&$user)
1561 return common_local_url('userbyid', array('id' => $user->id),
1565 function common_notice_uri(&$notice)
1567 return common_local_url('shownotice',
1568 array('notice' => $notice->id),
1572 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1574 function common_confirmation_code($bits)
1576 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1577 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1578 $chars = ceil($bits/5);
1580 for ($i = 0; $i < $chars; $i++) {
1581 // XXX: convert to string and back
1582 $num = hexdec(common_good_rand(1));
1583 // XXX: randomness is too precious to throw away almost
1584 // 40% of the bits we get!
1585 $code .= $codechars[$num%32];
1590 // convert markup to HTML
1592 function common_markup_to_html($c)
1594 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1595 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1596 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1597 return Markdown($c);
1600 function common_profile_uri($profile)
1605 $user = User::staticGet($profile->id);
1610 $remote = Remote_profile::staticGet($profile->id);
1612 return $remote->uri;
1614 // XXX: this is a very bad profile!
1618 function common_canonical_sms($sms)
1621 preg_replace('/\D/', '', $sms);
1625 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1630 case E_COMPILE_ERROR:
1634 case E_RECOVERABLE_ERROR:
1635 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1640 case E_COMPILE_WARNING:
1641 case E_CORE_WARNING:
1642 case E_USER_WARNING:
1643 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1648 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1653 case E_USER_DEPRECATED:
1654 // XXX: config variable to log this stuff, too
1658 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1663 // FIXME: show error page if we're on the Web
1664 /* Don't execute PHP internal error handler */
1668 function common_session_token()
1670 common_ensure_session();
1671 if (!array_key_exists('token', $_SESSION)) {
1672 $_SESSION['token'] = common_good_rand(64);
1674 return $_SESSION['token'];
1677 function common_cache_key($extra)
1679 return Cache::key($extra);
1682 function common_keyize($str)
1684 return Cache::keyize($str);
1687 function common_memcache()
1689 return Cache::instance();
1692 function common_license_terms($uri)
1694 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1695 return explode('-',$matches[1]);
1700 function common_compatible_license($from, $to)
1702 $from_terms = common_license_terms($from);
1703 // public domain and cc-by are compatible with everything
1704 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1707 $to_terms = common_license_terms($to);
1708 // sa is compatible across versions. IANAL
1709 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1710 return count(array_diff($from_terms, $to_terms)) == 0;
1712 // XXX: better compatibility check needed here!
1713 // Should at least normalise URIs
1714 return ($from == $to);
1718 * returns a quoted table name, if required according to config
1720 function common_database_tablename($tablename)
1723 if(common_config('db','quote_identifiers')) {
1724 $tablename = '"'. $tablename .'"';
1726 //table prefixes could be added here later
1731 * Shorten a URL with the current user's configured shortening service,
1732 * or ur1.ca if configured, or not at all if no shortening is set up.
1733 * Length is not considered.
1735 * @param string $long_url
1736 * @return string may return the original URL if shortening failed
1738 * @fixme provide a way to specify a particular shortener
1739 * @fixme provide a way to specify to use a given user's shortening preferences
1741 function common_shorten_url($long_url)
1743 $long_url = trim($long_url);
1744 $user = common_current_user();
1746 // common current user does not find a user when called from the XMPP daemon
1747 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1748 $shortenerName = 'ur1.ca';
1750 $shortenerName = $user->urlshorteningservice;
1753 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1754 //URL wasn't shortened, so return the long url
1757 //URL was shortened, so return the result
1758 return trim($shortenedUrl);
1763 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1764 * null if not a web request
1766 * @fixme X-Forwarded-For can be chained by multiple proxies;
1767 we should parse the list and provide a cleaner array
1768 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1769 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1770 * use function to get exact request headers from Apache if possible.
1772 function common_client_ip()
1774 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1778 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1779 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1780 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1782 $proxy = $_SERVER['REMOTE_ADDR'];
1784 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1787 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1788 $ip = $_SERVER['HTTP_CLIENT_IP'];
1790 $ip = $_SERVER['REMOTE_ADDR'];
1794 return array($proxy, $ip);
1797 function common_url_to_nickname($url)
1799 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1801 $parts = parse_url($url);
1803 # If any of these parts exist, this won't work
1805 foreach ($bad as $badpart) {
1806 if (array_key_exists($badpart, $parts)) {
1811 # We just have host and/or path
1813 # If it's just a host...
1814 if (array_key_exists('host', $parts) &&
1815 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1817 $hostparts = explode('.', $parts['host']);
1819 # Try to catch common idiom of nickname.service.tld
1821 if ((count($hostparts) > 2) &&
1822 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1823 (strcmp($hostparts[0], 'www') != 0))
1825 return common_nicknamize($hostparts[0]);
1827 # Do the whole hostname
1828 return common_nicknamize($parts['host']);
1831 if (array_key_exists('path', $parts)) {
1832 # Strip starting, ending slashes
1833 $path = preg_replace('@/$@', '', $parts['path']);
1834 $path = preg_replace('@^/@', '', $path);
1835 $path = basename($path);
1837 return common_nicknamize($path);
1845 function common_nicknamize($str)
1847 $str = preg_replace('/\W/', '', $str);
1848 return strtolower($str);