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 return setlocale(LC_ALL, $language . ".utf8",
51 function common_init_language()
53 mb_internal_encoding('UTF-8');
55 // Note that this setlocale() call may "fail" but this is harmless;
56 // gettext will still select the right language.
57 $language = common_language();
58 $locale_set = common_init_locale($language);
61 // The requested locale doesn't exist on the system.
63 // gettext seems very picky... We first need to setlocale()
64 // to a locale which _does_ exist on the system, and _then_
65 // we can set in another locale that may not be set up
66 // (say, ga_ES for Galego/Galician) it seems to take it.
68 // For some reason C and POSIX which are guaranteed to work
69 // don't do the job. en_US.UTF-8 should be there most of the
70 // time, but not guaranteed.
71 $ok = common_init_locale("en_US");
73 // Try to find a complete, working locale...
74 // @fixme shelling out feels awfully inefficient
75 // but I don't think there's a more standard way.
77 foreach (explode("\n", $all) as $locale) {
78 if (preg_match('/\.utf[-_]?8$/i', $locale)) {
79 $ok = setlocale(LC_ALL, $locale);
86 common_log(LOG_ERR, "Unable to find a UTF-8 locale on this system; UI translations may not work.");
89 $locale_set = common_init_locale($language);
92 setlocale(LC_CTYPE, 'C');
93 // So we do not have to make people install the gettext locales
94 $path = common_config('site','locale_path');
95 bindtextdomain("statusnet", $path);
96 bind_textdomain_codeset("statusnet", "UTF-8");
97 textdomain("statusnet");
100 function common_timezone()
102 if (common_logged_in()) {
103 $user = common_current_user();
104 if ($user->timezone) {
105 return $user->timezone;
109 return common_config('site', 'timezone');
112 function common_language()
115 // If there is a user logged in and they've set a language preference
116 // then return that one...
117 if (_have_config() && common_logged_in()) {
118 $user = common_current_user();
119 $user_language = $user->language;
121 if ($user->language) {
122 // Validate -- we don't want to end up with a bogus code
123 // left over from some old junk.
124 foreach (common_config('site', 'languages') as $code => $info) {
125 if ($info['lang'] == $user_language) {
126 return $user_language;
132 // Otherwise, find the best match for the languages requested by the
134 if (common_config('site', 'langdetect')) {
135 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null;
136 if (!empty($httplang)) {
137 $language = client_prefered_language($httplang);
143 // Finally, if none of the above worked, use the site's default...
144 return common_config('site', 'language');
146 // salted, hashed passwords are stored in the DB
148 function common_munge_password($password, $id)
150 if (is_object($id) || is_object($password)) {
151 $e = new Exception();
152 common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' .
153 str_replace("\n", " ", $e->getTraceAsString()));
155 return md5($password . $id);
158 // check if a username exists and has matching password
160 function common_check_user($nickname, $password)
162 $authenticatedUser = false;
164 if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) {
165 $user = User::staticGet('nickname', common_canonical_nickname($nickname));
167 if (!empty($password)) { // never allow login with blank password
168 if (0 == strcmp(common_munge_password($password, $user->id),
170 //internal checking passed
171 $authenticatedUser = $user;
175 Event::handle('EndCheckPassword', array($nickname, $password, $authenticatedUser));
178 return $authenticatedUser;
181 // is the current user logged in?
182 function common_logged_in()
184 return (!is_null(common_current_user()));
187 function common_have_session()
189 return (0 != strcmp(session_id(), ''));
192 function common_ensure_session()
195 if (array_key_exists(session_name(), $_COOKIE)) {
196 $c = $_COOKIE[session_name()];
198 if (!common_have_session()) {
199 if (common_config('sessions', 'handle')) {
200 Session::setSaveHandler();
202 if (array_key_exists(session_name(), $_GET)) {
203 $id = $_GET[session_name()];
204 } else if (array_key_exists(session_name(), $_COOKIE)) {
205 $id = $_COOKIE[session_name()];
211 if (!isset($_SESSION['started'])) {
212 $_SESSION['started'] = time();
214 common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' .
215 ' is set but started value is null');
221 // Three kinds of arguments:
226 // Initialize to false; set to null if none found
230 function common_set_user($user)
235 if (is_null($user) && common_have_session()) {
237 unset($_SESSION['userid']);
239 } else if (is_string($user)) {
241 $user = User::staticGet('nickname', $nickname);
242 } else if (!($user instanceof User)) {
247 if (Event::handle('StartSetUser', array(&$user))) {
249 common_ensure_session();
250 $_SESSION['userid'] = $user->id;
252 Event::handle('EndSetUser', array($user));
260 function common_set_cookie($key, $value, $expiration=0)
262 $path = common_config('site', 'path');
263 $server = common_config('site', 'server');
265 if ($path && ($path != '/')) {
266 $cookiepath = '/' . $path . '/';
270 return setcookie($key,
277 define('REMEMBERME', 'rememberme');
278 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60); // 30 days
280 function common_rememberme($user=null)
283 $user = common_current_user();
289 $rm = new Remember_me();
291 $rm->code = common_good_rand(16);
292 $rm->user_id = $user->id;
294 // Wrap the insert in some good ol' fashioned transaction code
298 $result = $rm->insert();
301 common_log_db_error($rm, 'INSERT', __FILE__);
305 $rm->query('COMMIT');
307 $cookieval = $rm->user_id . ':' . $rm->code;
309 common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname);
311 common_set_cookie(REMEMBERME, $cookieval, time() + REMEMBERME_EXPIRY);
316 function common_remembered_user()
321 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : null;
327 list($id, $code) = explode(':', $packed);
329 if (!$id || !$code) {
330 common_log(LOG_WARNING, 'Malformed rememberme cookie: ' . $packed);
335 $rm = Remember_me::staticGet($code);
338 common_log(LOG_WARNING, 'No such remember code: ' . $code);
343 if ($rm->user_id != $id) {
344 common_log(LOG_WARNING, 'Rememberme code for wrong user: ' . $rm->user_id . ' != ' . $id);
349 $user = User::staticGet($rm->user_id);
352 common_log(LOG_WARNING, 'No such user for rememberme: ' . $rm->user_id);
358 $result = $rm->delete();
361 common_log_db_error($rm, 'DELETE', __FILE__);
362 common_log(LOG_WARNING, 'Could not delete rememberme: ' . $code);
367 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
369 common_set_user($user);
370 common_real_login(false);
372 // We issue a new cookie, so they can log in
373 // automatically again after this session
375 common_rememberme($user);
380 // must be called with a valid user!
382 function common_forgetme()
384 common_set_cookie(REMEMBERME, '', 0);
387 // who is the current user?
388 function common_current_user()
392 if (!_have_config()) {
396 if ($_cur === false) {
398 if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()])
399 || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
400 common_ensure_session();
401 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
403 $user = User::staticGet($id);
411 // that didn't work; try to remember; will init $_cur to null on failure
412 $_cur = common_remembered_user();
415 // XXX: Is this necessary?
416 $_SESSION['userid'] = $_cur->id;
423 // Logins that are 'remembered' aren't 'real' -- they're subject to
424 // cookie-stealing. So, we don't let them do certain things. New reg,
425 // OpenID, and password logins _are_ real.
427 function common_real_login($real=true)
429 common_ensure_session();
430 $_SESSION['real_login'] = $real;
433 function common_is_real_login()
435 return common_logged_in() && $_SESSION['real_login'];
438 // get canonical version of nickname for comparison
439 function common_canonical_nickname($nickname)
441 // XXX: UTF-8 canonicalization (like combining chars)
442 return strtolower($nickname);
445 // get canonical version of email for comparison
446 function common_canonical_email($email)
448 // XXX: canonicalize UTF-8
449 // XXX: lcase the domain part
453 function common_render_content($text, $notice)
455 $r = common_render_text($text);
456 $id = $notice->profile_id;
457 $r = common_linkify_mentions($r, $notice);
458 $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r);
462 function common_linkify_mentions($text, $notice)
464 $mentions = common_find_mentions($text, $notice);
466 // We need to go through in reverse order by position,
467 // so our positions stay valid despite our fudging with the
472 foreach ($mentions as $mention)
474 $points[$mention['position']] = $mention;
479 foreach ($points as $position => $mention) {
481 $linkText = common_linkify_mention($mention);
483 $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text']));
489 function common_linkify_mention($mention)
493 if (Event::handle('StartLinkifyMention', array($mention, &$output))) {
495 $xs = new XMLStringer(false);
497 $attrs = array('href' => $mention['url'],
500 if (!empty($mention['title'])) {
501 $attrs['title'] = $mention['title'];
504 $xs->elementStart('span', 'vcard');
505 $xs->elementStart('a', $attrs);
506 $xs->element('span', 'fn nickname', $mention['text']);
507 $xs->elementEnd('a');
508 $xs->elementEnd('span');
510 $output = $xs->getString();
512 Event::handle('EndLinkifyMention', array($mention, &$output));
518 function common_find_mentions($text, $notice)
522 $sender = Profile::staticGet('id', $notice->profile_id);
524 if (empty($sender)) {
528 if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) {
530 // Get the context of the original notice, if any
532 $originalAuthor = null;
533 $originalNotice = null;
534 $originalMentions = array();
538 if (!empty($notice) && !empty($notice->reply_to)) {
539 $originalNotice = Notice::staticGet('id', $notice->reply_to);
540 if (!empty($originalNotice)) {
541 $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id);
543 $ids = $originalNotice->getReplies();
545 foreach ($ids as $id) {
546 $repliedTo = Profile::staticGet('id', $id);
547 if (!empty($repliedTo)) {
548 $originalMentions[$repliedTo->nickname] = $repliedTo;
554 preg_match_all('/^T ([A-Z0-9]{1,64}) /',
557 PREG_OFFSET_CAPTURE);
559 preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/',
562 PREG_OFFSET_CAPTURE);
564 $matches = array_merge($tmatches[1], $atmatches[1]);
566 foreach ($matches as $match) {
568 $nickname = common_canonical_nickname($match[0]);
570 // Try to get a profile for this nickname.
571 // Start with conversation context, then go to
574 if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) {
576 $mentioned = $originalAuthor;
578 } else if (!empty($originalMentions) &&
579 array_key_exists($nickname, $originalMentions)) {
581 $mentioned = $originalMentions[$nickname];
583 $mentioned = common_relative_profile($sender, $nickname);
586 if (!empty($mentioned)) {
588 $user = User::staticGet('id', $mentioned->id);
591 $url = common_local_url('userbyid', array('id' => $user->id));
593 $url = $mentioned->profileurl;
596 $mention = array('mentioned' => array($mentioned),
598 'position' => $match[1],
601 if (!empty($mentioned->fullname)) {
602 $mention['title'] = $mentioned->fullname;
605 $mentions[] = $mention;
609 // @#tag => mention of all subscriptions tagged 'tag'
611 preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/',
614 PREG_OFFSET_CAPTURE);
616 foreach ($hmatches[1] as $hmatch) {
618 $tag = common_canonical_tag($hmatch[0]);
620 $tagged = Profile_tag::getTagged($sender->id, $tag);
622 $url = common_local_url('subscriptions',
623 array('nickname' => $sender->nickname,
626 $mentions[] = array('mentioned' => $tagged,
627 'text' => $hmatch[0],
628 'position' => $hmatch[1],
632 Event::handle('EndFindMentions', array($sender, $text, &$mentions));
638 function common_render_text($text)
640 $r = htmlspecialchars($text);
642 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
643 $r = common_replace_urls_callback($r, 'common_linkify');
644 $r = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
649 function common_replace_urls_callback($text, $callback, $notice_id = null) {
650 // Start off with a regex
652 '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'.
655 '(?:'. //Known protocols
657 '(?:(?:https?|ftps?|mms|rtsp|gopher|news|nntp|telnet|wais|file|prospero|webcal|irc)://)'.
659 '(?:(?:mailto|aim|tel|xmpp):)'.
661 '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
664 '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]'. //[dns]
666 '[\pN\pL\-\_\:\.]+(?<![\.\:])'. //dns
670 '|(?:(?: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
672 '\[?(?:(?:(?:[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})))\]?(?<!:)'.
674 '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?'. //user:pass@
675 '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'.
676 //tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
677 '(?: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)'.
681 '(?:\:\d+)?'. //:port
682 '(?:/[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@]*)?'. // /path
683 '(?:\?[\pN\pL\$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'@\/]*)?'. // ?query string
684 '(?:\#[\pN\pL$\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\+\'\@/\?\#]*)?'. // #fragment
685 ')(?<![\?\.\,\#\,])'.
688 //preg_match_all($regex,$text,$matches);
690 return preg_replace_callback($regex, curry('callback_helper',$callback,$notice_id) ,$text);
693 function callback_helper($matches, $callback, $notice_id) {
695 $left = strpos($matches[0],$url);
696 $right = $left+strlen($url);
698 $groupSymbolSets=array(
716 $cannotEndWith=array('.','?',',','#');
720 foreach($groupSymbolSets as $groupSymbolSet){
721 if(substr($url,-1)==$groupSymbolSet['right']){
722 $group_left_count = substr_count($url,$groupSymbolSet['left']);
723 $group_right_count = substr_count($url,$groupSymbolSet['right']);
724 if($group_left_count<$group_right_count){
726 $url=substr($url,0,-1);
730 if(in_array(substr($url,-1),$cannotEndWith)){
732 $url=substr($url,0,-1);
734 }while($original_url!=$url);
736 if(empty($notice_id)){
737 $result = call_user_func_array($callback, array($url));
739 $result = call_user_func_array($callback, array(array($url,$notice_id)) );
741 return substr($matches[0],0,$left) . $result . substr($matches[0],$right);
744 if (version_compare(PHP_VERSION, '5.3.0', 'ge')) {
745 // lambda implementation in a separate file; PHP 5.2 won't parse it.
746 require_once INSTALLDIR . "/lib/curry.php";
748 function curry($fn) {
749 $args = func_get_args();
751 $id = uniqid('_partial');
752 $GLOBALS[$id] = array($fn, $args);
753 return create_function('',
754 '$args = func_get_args(); '.
755 'return call_user_func_array('.
756 '$GLOBALS["'.$id.'"][0],'.
759 '$GLOBALS["'.$id.'"][1]));');
763 function common_linkify($url) {
764 // It comes in special'd, so we unspecial it before passing to the stringifying
766 $url = htmlspecialchars_decode($url);
768 if(strpos($url, '@') !== false && strpos($url, ':') === false) {
769 //url is an email address without the mailto: protocol
770 $canon = "mailto:$url";
771 $longurl = "mailto:$url";
774 $canon = File_redirection::_canonUrl($url);
776 $longurl_data = File_redirection::where($canon);
777 if (is_array($longurl_data)) {
778 $longurl = $longurl_data['url'];
779 } elseif (is_string($longurl_data)) {
780 $longurl = $longurl_data;
782 throw new ServerException("Can't linkify url '$url'");
785 $attrs = array('href' => $canon, 'title' => $longurl, 'rel' => 'external');
787 $is_attachment = false;
788 $attachment_id = null;
791 // Check to see whether this is a known "attachment" URL.
793 $f = File::staticGet('url', $longurl);
796 // XXX: this writes to the database. :<
797 $f = File::processNew($longurl);
801 if ($f->getEnclosure()) {
802 $is_attachment = true;
803 $attachment_id = $f->id;
805 $thumb = File_thumbnail::staticGet('file_id', $f->id);
806 if (!empty($thumb)) {
813 if ($is_attachment) {
814 $attrs['class'] = 'attachment';
816 $attrs['class'] = 'attachment thumbnail';
818 $attrs['id'] = "attachment-{$attachment_id}";
821 return XMLStringer::estring('a', $attrs, $url);
824 function common_shorten_links($text)
826 $maxLength = Notice::maxContent();
827 if ($maxLength == 0 || mb_strlen($text) <= $maxLength) return $text;
828 return common_replace_urls_callback($text, array('File_redirection', 'makeShort'));
831 function common_xml_safe_str($str)
833 // Replace common eol and extra whitespace input chars
838 "\0", // null byte eos
839 "\x0B" // vertical tab
842 $replacement = array(
850 $str = str_replace($unWelcome, $replacement, $str);
852 // Neutralize any additional control codes and UTF-16 surrogates
853 // (Twitter uses '*')
854 return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str);
857 function common_tag_link($tag)
859 $canonical = common_canonical_tag($tag);
860 $url = common_local_url('tag', array('tag' => $canonical));
861 $xs = new XMLStringer();
862 $xs->elementStart('span', 'tag');
863 $xs->element('a', array('href' => $url,
866 $xs->elementEnd('span');
867 return $xs->getString();
870 function common_canonical_tag($tag)
872 $tag = mb_convert_case($tag, MB_CASE_LOWER, "UTF-8");
873 return str_replace(array('-', '_', '.'), '', $tag);
876 function common_valid_profile_tag($str)
878 return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str);
881 function common_group_link($sender_id, $nickname)
883 $sender = Profile::staticGet($sender_id);
884 $group = User_group::getForNickname($nickname, $sender);
885 if ($sender && $group && $sender->isMember($group)) {
886 $attrs = array('href' => $group->permalink(),
888 if (!empty($group->fullname)) {
889 $attrs['title'] = $group->fullname . ' (' . $group->nickname . ')';
891 $xs = new XMLStringer();
892 $xs->elementStart('span', 'vcard');
893 $xs->elementStart('a', $attrs);
894 $xs->element('span', 'fn nickname', $nickname);
895 $xs->elementEnd('a');
896 $xs->elementEnd('span');
897 return $xs->getString();
903 function common_relative_profile($sender, $nickname, $dt=null)
905 // Try to find profiles this profile is subscribed to that have this nickname
906 $recipient = new Profile();
907 // XXX: use a join instead of a subquery
908 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
909 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
910 if ($recipient->find(true)) {
911 // XXX: should probably differentiate between profiles with
912 // the same name by date of most recent update
915 // Try to find profiles that listen to this profile and that have this nickname
916 $recipient = new Profile();
917 // XXX: use a join instead of a subquery
918 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
919 $recipient->whereAdd("nickname = '" . trim($nickname) . "'", 'AND');
920 if ($recipient->find(true)) {
921 // XXX: should probably differentiate between profiles with
922 // the same name by date of most recent update
925 // If this is a local user, try to find a local user with that nickname.
926 $sender = User::staticGet($sender->id);
928 $recipient_user = User::staticGet('nickname', $nickname);
929 if ($recipient_user) {
930 return $recipient_user->getProfile();
933 // Otherwise, no links. @messages from local users to remote users,
934 // or from remote users to other remote users, are just
935 // outside our ability to make intelligent guesses about
939 function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true)
942 $path = $r->build($action, $args, $params, $fragment);
944 $ssl = common_is_sensitive($action);
946 if (common_config('site','fancy')) {
947 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
949 if (mb_strpos($path, '/index.php') === 0) {
950 $url = common_path(mb_substr($path, 1), $ssl, $addSession);
952 $url = common_path('index.php'.$path, $ssl, $addSession);
958 function common_is_sensitive($action)
960 static $sensitive = array('login', 'register', 'passwordsettings',
961 'twittersettings', 'api');
964 if (Event::handle('SensitiveAction', array($action, &$ssl))) {
965 $ssl = in_array($action, $sensitive);
971 function common_path($relative, $ssl=false, $addSession=true)
973 $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : '';
975 if (($ssl && (common_config('site', 'ssl') === 'sometimes'))
976 || common_config('site', 'ssl') === 'always') {
978 if (is_string(common_config('site', 'sslserver')) &&
979 mb_strlen(common_config('site', 'sslserver')) > 0) {
980 $serverpart = common_config('site', 'sslserver');
981 } else if (common_config('site', 'server')) {
982 $serverpart = common_config('site', 'server');
984 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
988 if (common_config('site', 'server')) {
989 $serverpart = common_config('site', 'server');
991 common_log(LOG_ERR, 'Site server not configured, unable to determine site name.');
996 $relative = common_inject_session($relative, $serverpart);
999 return $proto.'://'.$serverpart.'/'.$pathpart.$relative;
1002 function common_inject_session($url, $serverpart = null)
1004 if (common_have_session()) {
1006 if (empty($serverpart)) {
1007 $serverpart = parse_url($url, PHP_URL_HOST);
1010 $currentServer = $_SERVER['HTTP_HOST'];
1012 // Are we pointing to another server (like an SSL server?)
1014 if (!empty($currentServer) &&
1015 0 != strcasecmp($currentServer, $serverpart)) {
1016 // Pass the session ID as a GET parameter
1017 $sesspart = session_name() . '=' . session_id();
1018 $i = strpos($url, '?');
1019 if ($i === false) { // no GET params, just append
1020 $url .= '?' . $sesspart;
1022 $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1);
1030 function common_date_string($dt)
1032 // XXX: do some sexy date formatting
1033 // return date(DATE_RFC822, $dt);
1034 $t = strtotime($dt);
1038 if ($now < $t) { // that shouldn't happen!
1039 return common_exact_date($dt);
1040 } else if ($diff < 60) {
1041 return _('a few seconds ago');
1042 } else if ($diff < 92) {
1043 return _('about a minute ago');
1044 } else if ($diff < 3300) {
1045 return sprintf(_('about %d minutes ago'), round($diff/60));
1046 } else if ($diff < 5400) {
1047 return _('about an hour ago');
1048 } else if ($diff < 22 * 3600) {
1049 return sprintf(_('about %d hours ago'), round($diff/3600));
1050 } else if ($diff < 37 * 3600) {
1051 return _('about a day ago');
1052 } else if ($diff < 24 * 24 * 3600) {
1053 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1054 } else if ($diff < 46 * 24 * 3600) {
1055 return _('about a month ago');
1056 } else if ($diff < 330 * 24 * 3600) {
1057 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1058 } else if ($diff < 480 * 24 * 3600) {
1059 return _('about a year ago');
1061 return common_exact_date($dt);
1065 function common_exact_date($dt)
1071 $_utc = new DateTimeZone('UTC');
1072 $_siteTz = new DateTimeZone(common_timezone());
1075 $dateStr = date('d F Y H:i:s', strtotime($dt));
1076 $d = new DateTime($dateStr, $_utc);
1077 $d->setTimezone($_siteTz);
1078 return $d->format(DATE_RFC850);
1081 function common_date_w3dtf($dt)
1083 $dateStr = date('d F Y H:i:s', strtotime($dt));
1084 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1085 $d->setTimezone(new DateTimeZone(common_timezone()));
1086 return $d->format(DATE_W3C);
1089 function common_date_rfc2822($dt)
1091 $dateStr = date('d F Y H:i:s', strtotime($dt));
1092 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1093 $d->setTimezone(new DateTimeZone(common_timezone()));
1094 return $d->format('r');
1097 function common_date_iso8601($dt)
1099 $dateStr = date('d F Y H:i:s', strtotime($dt));
1100 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1101 $d->setTimezone(new DateTimeZone(common_timezone()));
1102 return $d->format('c');
1105 function common_sql_now()
1107 return common_sql_date(time());
1110 function common_sql_date($datetime)
1112 return strftime('%Y-%m-%d %H:%M:%S', $datetime);
1116 * Return an SQL fragment to calculate an age-based weight from a given
1117 * timestamp or datetime column.
1119 * @param string $column name of field we're comparing against current time
1120 * @param integer $dropoff divisor for age in seconds before exponentiation
1121 * @return string SQL fragment
1123 function common_sql_weight($column, $dropoff)
1125 if (common_config('db', 'type') == 'pgsql') {
1126 // PostgreSQL doesn't support timestampdiff function.
1127 // @fixme will this use the right time zone?
1128 // @fixme does this handle cross-year subtraction correctly?
1129 return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))";
1131 return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))";
1135 function common_redirect($url, $code=307)
1137 static $status = array(301 => "Moved Permanently",
1140 307 => "Temporary Redirect");
1142 header('HTTP/1.1 '.$code.' '.$status[$code]);
1143 header("Location: $url");
1145 $xo = new XMLOutputter();
1147 '-//W3C//DTD XHTML 1.0 Strict//EN',
1148 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1149 $xo->element('a', array('href' => $url), $url);
1154 function common_broadcast_notice($notice, $remote=false)
1159 // Stick the notice on the queue
1161 function common_enqueue_notice($notice)
1163 static $localTransports = array('omb',
1166 $transports = array();
1167 if (common_config('sms', 'enabled')) {
1168 $transports[] = 'sms';
1170 if (Event::hasHandler('HandleQueuedNotice')) {
1171 $transports[] = 'plugin';
1174 $xmpp = common_config('xmpp', 'enabled');
1177 $transports[] = 'jabber';
1180 // @fixme move these checks into QueueManager and/or individual handlers
1181 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
1182 $notice->is_local == Notice::LOCAL_NONPUBLIC) {
1183 $transports = array_merge($transports, $localTransports);
1185 $transports[] = 'public';
1189 if (Event::handle('StartEnqueueNotice', array($notice, &$transports))) {
1191 $qm = QueueManager::get();
1193 foreach ($transports as $transport)
1195 $qm->enqueue($notice, $transport);
1198 Event::handle('EndEnqueueNotice', array($notice, $transports));
1205 * Broadcast profile updates to OMB and other remote subscribers.
1207 * Since this may be slow with a lot of subscribers or bad remote sites,
1208 * this is run through the background queues if possible.
1210 function common_broadcast_profile(Profile $profile)
1212 $qm = QueueManager::get();
1213 $qm->enqueue($profile, "profile");
1217 function common_profile_url($nickname)
1219 return common_local_url('showstream', array('nickname' => $nickname),
1223 // Should make up a reasonable root URL
1225 function common_root_url($ssl=false)
1227 $url = common_path('', $ssl, false);
1228 $i = strpos($url, '?');
1230 $url = substr($url, 0, $i);
1235 // returns $bytes bytes of random data as a hexadecimal string
1236 // "good" here is a goal and not a guarantee
1238 function common_good_rand($bytes)
1240 // XXX: use random.org...?
1241 if (@file_exists('/dev/urandom')) {
1242 return common_urandom($bytes);
1243 } else { // FIXME: this is probably not good enough
1244 return common_mtrand($bytes);
1248 function common_urandom($bytes)
1250 $h = fopen('/dev/urandom', 'rb');
1252 $src = fread($h, $bytes);
1255 for ($i = 0; $i < $bytes; $i++) {
1256 $enc .= sprintf("%02x", (ord($src[$i])));
1261 function common_mtrand($bytes)
1264 for ($i = 0; $i < $bytes; $i++) {
1265 $enc .= sprintf("%02x", mt_rand(0, 255));
1270 function common_set_returnto($url)
1272 common_ensure_session();
1273 $_SESSION['returnto'] = $url;
1276 function common_get_returnto()
1278 common_ensure_session();
1279 return (array_key_exists('returnto', $_SESSION)) ? $_SESSION['returnto'] : null;
1282 function common_timestamp()
1284 return date('YmdHis');
1287 function common_ensure_syslog()
1289 static $initialized = false;
1290 if (!$initialized) {
1291 openlog(common_config('syslog', 'appname'), 0,
1292 common_config('syslog', 'facility'));
1293 $initialized = true;
1297 function common_log_line($priority, $msg)
1299 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1300 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1301 return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1304 function common_request_id()
1307 $server = common_config('site', 'server');
1308 if (php_sapi_name() == 'cli') {
1309 $script = basename($_SERVER['PHP_SELF']);
1310 return "$server:$script:$pid";
1312 static $req_id = null;
1313 if (!isset($req_id)) {
1314 $req_id = substr(md5(mt_rand()), 0, 8);
1316 if (isset($_SERVER['REQUEST_URI'])) {
1317 $url = $_SERVER['REQUEST_URI'];
1319 $method = $_SERVER['REQUEST_METHOD'];
1320 return "$server:$pid.$req_id $method $url";
1324 function common_log($priority, $msg, $filename=null)
1326 if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){
1327 $msg = '[' . common_request_id() . '] ' . $msg;
1328 $logfile = common_config('site', 'logfile');
1330 $log = fopen($logfile, "a");
1332 $output = common_log_line($priority, $msg);
1333 fwrite($log, $output);
1337 common_ensure_syslog();
1338 syslog($priority, $msg);
1340 Event::handle('EndLog', array($priority, $msg, $filename));
1344 function common_debug($msg, $filename=null)
1347 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1349 common_log(LOG_DEBUG, $msg);
1353 function common_log_db_error(&$object, $verb, $filename=null)
1355 $objstr = common_log_objstring($object);
1356 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1357 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1360 function common_log_objstring(&$object)
1362 if (is_null($object)) {
1365 if (!($object instanceof DB_DataObject)) {
1368 $arr = $object->toArray();
1370 foreach ($arr as $k => $v) {
1371 if (is_object($v)) {
1372 $fields[] = "$k='".get_class($v)."'";
1374 $fields[] = "$k='$v'";
1377 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1381 function common_valid_http_url($url)
1383 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1386 function common_valid_tag($tag)
1388 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1389 return (Validate::email($matches[1]) ||
1390 preg_match('/^([\w-\.]+)$/', $matches[1]));
1395 /* Following functions are copied from MediaWiki GlobalFunctions.php
1396 * and written by Evan Prodromou. */
1398 function common_accept_to_prefs($accept, $def = '*/*')
1400 // No arg means accept anything (per HTTP spec)
1402 return array($def => 1);
1407 $parts = explode(',', $accept);
1409 foreach($parts as $part) {
1410 // FIXME: doesn't deal with params like 'text/html; level=1'
1411 @list($value, $qpart) = explode(';', trim($part));
1413 if(!isset($qpart)) {
1415 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1416 $prefs[$value] = $match[1];
1423 function common_mime_type_match($type, $avail)
1425 if(array_key_exists($type, $avail)) {
1428 $parts = explode('/', $type);
1429 if(array_key_exists($parts[0] . '/*', $avail)) {
1430 return $parts[0] . '/*';
1431 } elseif(array_key_exists('*/*', $avail)) {
1439 function common_negotiate_type($cprefs, $sprefs)
1443 foreach(array_keys($sprefs) as $type) {
1444 $parts = explode('/', $type);
1445 if($parts[1] != '*') {
1446 $ckey = common_mime_type_match($type, $cprefs);
1448 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1453 foreach(array_keys($cprefs) as $type) {
1454 $parts = explode('/', $type);
1455 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1456 $skey = common_mime_type_match($type, $sprefs);
1458 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1464 $besttype = 'text/html';
1466 foreach(array_keys($combine) as $type) {
1467 if($combine[$type] > $bestq) {
1469 $bestq = $combine[$type];
1473 if ('text/html' === $besttype) {
1474 return "text/html; charset=utf-8";
1479 function common_config($main, $sub)
1482 return (array_key_exists($main, $config) &&
1483 array_key_exists($sub, $config[$main])) ? $config[$main][$sub] : false;
1486 function common_copy_args($from)
1489 $strip = get_magic_quotes_gpc();
1490 foreach ($from as $k => $v) {
1491 $to[$k] = ($strip) ? stripslashes($v) : $v;
1497 * Neutralise the evil effects of magic_quotes_gpc in the current request.
1498 * This is used before handing a request off to OAuthRequest::from_request.
1499 * @fixme Doesn't consider vars other than _POST and _GET?
1500 * @fixme Can't be undone and could corrupt data if run twice.
1502 function common_remove_magic_from_request()
1504 if(get_magic_quotes_gpc()) {
1505 $_POST=array_map('stripslashes',$_POST);
1506 $_GET=array_map('stripslashes',$_GET);
1510 function common_user_uri(&$user)
1512 return common_local_url('userbyid', array('id' => $user->id),
1516 function common_notice_uri(&$notice)
1518 return common_local_url('shownotice',
1519 array('notice' => $notice->id));
1522 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1524 function common_confirmation_code($bits)
1526 // 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1527 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1528 $chars = ceil($bits/5);
1530 for ($i = 0; $i < $chars; $i++) {
1531 // XXX: convert to string and back
1532 $num = hexdec(common_good_rand(1));
1533 // XXX: randomness is too precious to throw away almost
1534 // 40% of the bits we get!
1535 $code .= $codechars[$num%32];
1540 // convert markup to HTML
1542 function common_markup_to_html($c)
1544 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1545 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1546 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1547 return Markdown($c);
1550 function common_profile_uri($profile)
1555 $user = User::staticGet($profile->id);
1560 $remote = Remote_profile::staticGet($profile->id);
1562 return $remote->uri;
1564 // XXX: this is a very bad profile!
1568 function common_canonical_sms($sms)
1571 preg_replace('/\D/', '', $sms);
1575 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
1580 case E_COMPILE_ERROR:
1584 case E_RECOVERABLE_ERROR:
1585 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [ABORT]");
1590 case E_COMPILE_WARNING:
1591 case E_CORE_WARNING:
1592 case E_USER_WARNING:
1593 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1598 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1603 case E_USER_DEPRECATED:
1604 // XXX: config variable to log this stuff, too
1608 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline) [UNKNOWN LEVEL, die()'ing]");
1613 // FIXME: show error page if we're on the Web
1614 /* Don't execute PHP internal error handler */
1618 function common_session_token()
1620 common_ensure_session();
1621 if (!array_key_exists('token', $_SESSION)) {
1622 $_SESSION['token'] = common_good_rand(64);
1624 return $_SESSION['token'];
1627 function common_cache_key($extra)
1629 return Cache::key($extra);
1632 function common_keyize($str)
1634 return Cache::keyize($str);
1637 function common_memcache()
1639 return Cache::instance();
1642 function common_license_terms($uri)
1644 if(preg_match('/creativecommons.org\/licenses\/([^\/]+)/', $uri, $matches)) {
1645 return explode('-',$matches[1]);
1650 function common_compatible_license($from, $to)
1652 $from_terms = common_license_terms($from);
1653 // public domain and cc-by are compatible with everything
1654 if(count($from_terms) == 1 && ($from_terms[0] == 'publicdomain' || $from_terms[0] == 'by')) {
1657 $to_terms = common_license_terms($to);
1658 // sa is compatible across versions. IANAL
1659 if(in_array('sa',$from_terms) || in_array('sa',$to_terms)) {
1660 return count(array_diff($from_terms, $to_terms)) == 0;
1662 // XXX: better compatibility check needed here!
1663 // Should at least normalise URIs
1664 return ($from == $to);
1668 * returns a quoted table name, if required according to config
1670 function common_database_tablename($tablename)
1673 if(common_config('db','quote_identifiers')) {
1674 $tablename = '"'. $tablename .'"';
1676 //table prefixes could be added here later
1681 * Shorten a URL with the current user's configured shortening service,
1682 * or ur1.ca if configured, or not at all if no shortening is set up.
1683 * Length is not considered.
1685 * @param string $long_url
1686 * @return string may return the original URL if shortening failed
1688 * @fixme provide a way to specify a particular shortener
1689 * @fixme provide a way to specify to use a given user's shortening preferences
1691 function common_shorten_url($long_url)
1693 $long_url = trim($long_url);
1694 $user = common_current_user();
1696 // common current user does not find a user when called from the XMPP daemon
1697 // therefore we'll set one here fix, so that XMPP given URLs may be shortened
1698 $shortenerName = 'ur1.ca';
1700 $shortenerName = $user->urlshorteningservice;
1703 if(Event::handle('StartShortenUrl', array($long_url,$shortenerName,&$shortenedUrl))){
1704 //URL wasn't shortened, so return the long url
1707 //URL was shortened, so return the result
1708 return trim($shortenedUrl);
1713 * @return mixed array($proxy, $ip) for web requests; proxy may be null
1714 * null if not a web request
1716 * @fixme X-Forwarded-For can be chained by multiple proxies;
1717 we should parse the list and provide a cleaner array
1718 * @fixme X-Forwarded-For can be forged by clients; only use them if trusted
1719 * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER;
1720 * use function to get exact request headers from Apache if possible.
1722 function common_client_ip()
1724 if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) {
1728 if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1729 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1730 $proxy = $_SERVER['HTTP_CLIENT_IP'];
1732 $proxy = $_SERVER['REMOTE_ADDR'];
1734 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
1737 if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
1738 $ip = $_SERVER['HTTP_CLIENT_IP'];
1740 $ip = $_SERVER['REMOTE_ADDR'];
1744 return array($proxy, $ip);
1747 function common_url_to_nickname($url)
1749 static $bad = array('query', 'user', 'password', 'port', 'fragment');
1751 $parts = parse_url($url);
1753 # If any of these parts exist, this won't work
1755 foreach ($bad as $badpart) {
1756 if (array_key_exists($badpart, $parts)) {
1761 # We just have host and/or path
1763 # If it's just a host...
1764 if (array_key_exists('host', $parts) &&
1765 (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0))
1767 $hostparts = explode('.', $parts['host']);
1769 # Try to catch common idiom of nickname.service.tld
1771 if ((count($hostparts) > 2) &&
1772 (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au
1773 (strcmp($hostparts[0], 'www') != 0))
1775 return common_nicknamize($hostparts[0]);
1777 # Do the whole hostname
1778 return common_nicknamize($parts['host']);
1781 if (array_key_exists('path', $parts)) {
1782 # Strip starting, ending slashes
1783 $path = preg_replace('@/$@', '', $parts['path']);
1784 $path = preg_replace('@^/@', '', $path);
1785 $path = basename($path);
1787 return common_nicknamize($path);
1795 function common_nicknamize($str)
1797 $str = preg_replace('/\W/', '', $str);
1798 return strtolower($str);