X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=lib%2Futil.php;h=da2799d4f92d23766c464b1e15b4c66ab6704217;hb=f39d3e34bb5298f13824699c7090e05b75d7549b;hp=68f3520db5c366086ce2c3e0af4c9a2501d47b63;hpb=959d278c347fdf90e0227adc57c0215f5d82404a;p=quix0rs-gnu-social.git diff --git a/lib/util.php b/lib/util.php index 68f3520db5..da2799d4f9 100644 --- a/lib/util.php +++ b/lib/util.php @@ -58,18 +58,17 @@ function common_init_language() // (say, ga_ES for Galego/Galician) it seems to take it. common_init_locale("en_US"); + // Note that this setlocale() call may "fail" but this is harmless; + // gettext will still select the right language. $language = common_language(); $locale_set = common_init_locale($language); + setlocale(LC_CTYPE, 'C'); // So we do not have to make people install the gettext locales $path = common_config('site','locale_path'); bindtextdomain("statusnet", $path); bind_textdomain_codeset("statusnet", "UTF-8"); textdomain("statusnet"); - - if(!$locale_set) { - common_log(LOG_INFO, 'Language requested:' . $language . ' - locale could not be set. Perhaps that system locale is not installed.', __FILE__); - } } function common_timezone() @@ -92,17 +91,27 @@ function common_language() if (_have_config() && common_logged_in()) { $user = common_current_user(); $user_language = $user->language; - if ($user_language) - return $user_language; + + if ($user->language) { + // Validate -- we don't want to end up with a bogus code + // left over from some old junk. + foreach (common_config('site', 'languages') as $code => $info) { + if ($info['lang'] == $user_language) { + return $user_language; + } + } + } } // Otherwise, find the best match for the languages requested by the // user's browser... - $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null; - if (!empty($httplang)) { - $language = client_prefered_language($httplang); - if ($language) - return $language; + if (common_config('site', 'langdetect')) { + $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : null; + if (!empty($httplang)) { + $language = client_prefered_language($httplang); + if ($language) + return $language; + } } // Finally, if none of the above worked, use the site's default... @@ -112,6 +121,11 @@ function common_language() function common_munge_password($password, $id) { + if (is_object($id) || is_object($password)) { + $e = new Exception(); + common_log(LOG_ERR, __METHOD__ . ' object in param to common_munge_password ' . + str_replace("\n", " ", $e->getTraceAsString())); + } return md5($password . $id); } @@ -122,13 +136,13 @@ function common_check_user($nickname, $password) $authenticatedUser = false; if (Event::handle('StartCheckPassword', array($nickname, $password, &$authenticatedUser))) { - $user = User::staticGet('nickname', $nickname); + $user = User::staticGet('nickname', common_canonical_nickname($nickname)); if (!empty($user)) { if (!empty($password)) { // never allow login with blank password if (0 == strcmp(common_munge_password($password, $user->id), $user->password)) { //internal checking passed - $authenticatedUser =& $user; + $authenticatedUser = $user; } } } @@ -159,10 +173,18 @@ function common_ensure_session() if (common_config('sessions', 'handle')) { Session::setSaveHandler(); } + if (array_key_exists(session_name(), $_GET)) { + $id = $_GET[session_name()]; + } else if (array_key_exists(session_name(), $_COOKIE)) { + $id = $_COOKIE[session_name()]; + } + if (isset($id)) { + session_id($id); + } @session_start(); if (!isset($_SESSION['started'])) { $_SESSION['started'] = time(); - if (!empty($c)) { + if (!empty($id)) { common_log(LOG_WARNING, 'Session cookie "' . $_COOKIE[session_name()] . '" ' . ' is set but started value is null'); } @@ -196,10 +218,15 @@ function common_set_user($user) } if ($user) { - common_ensure_session(); - $_SESSION['userid'] = $user->id; - $_cur = $user; - return $_cur; + if (Event::handle('StartSetUser', array(&$user))) { + if($user){ + common_ensure_session(); + $_SESSION['userid'] = $user->id; + $_cur = $user; + Event::handle('EndSetUser', array($user)); + return $_cur; + } + } } return false; } @@ -229,7 +256,6 @@ function common_rememberme($user=null) if (!$user) { $user = common_current_user(); if (!$user) { - common_debug('No current user to remember', __FILE__); return false; } } @@ -247,14 +273,11 @@ function common_rememberme($user=null) if (!$result) { common_log_db_error($rm, 'INSERT', __FILE__); - common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__); return false; } $rm->query('COMMIT'); - common_debug('Inserted rememberme record (' . $rm->code . ', ' . $rm->user_id . '); result = ' . $result . '.', __FILE__); - $cookieval = $rm->user_id . ':' . $rm->code; common_log(LOG_INFO, 'adding rememberme cookie "' . $cookieval . '" for ' . $user->nickname); @@ -346,7 +369,8 @@ function common_current_user() if ($_cur === false) { - if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) { + if (isset($_COOKIE[session_name()]) || isset($_GET[session_name()]) + || (isset($_SESSION['userid']) && $_SESSION['userid'])) { common_ensure_session(); $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false; if ($id) { @@ -362,8 +386,6 @@ function common_current_user() $_cur = common_remembered_user(); if ($_cur) { - common_debug("Got User " . $_cur->nickname); - common_debug("Faking session on remembered user"); // XXX: Is this necessary? $_SESSION['userid'] = $_cur->id; } @@ -406,13 +428,187 @@ function common_render_content($text, $notice) { $r = common_render_text($text); $id = $notice->profile_id; - $r = preg_replace('/(^|\s+)@(['.NICKNAME_FMT.']{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r); - $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r); - $r = preg_replace('/(^|[\s\.\,\:\;]+)@#([A-Za-z0-9]{1,64})/e', "'\\1@#'.common_at_hash_link($id, '\\2')", $r); + $r = common_linkify_mentions($r, $notice); $r = preg_replace('/(^|[\s\.\,\:\;]+)!([A-Za-z0-9]{1,64})/e', "'\\1!'.common_group_link($id, '\\2')", $r); return $r; } +function common_linkify_mentions($text, $notice) +{ + $mentions = common_find_mentions($text, $notice); + + // We need to go through in reverse order by position, + // so our positions stay valid despite our fudging with the + // string! + + $points = array(); + + foreach ($mentions as $mention) + { + $points[$mention['position']] = $mention; + } + + krsort($points); + + foreach ($points as $position => $mention) { + + $linkText = common_linkify_mention($mention); + + $text = substr_replace($text, $linkText, $position, mb_strlen($mention['text'])); + } + + return $text; +} + +function common_linkify_mention($mention) +{ + $output = null; + + if (Event::handle('StartLinkifyMention', array($mention, &$output))) { + + $xs = new XMLStringer(false); + + $attrs = array('href' => $mention['url'], + 'class' => 'url'); + + if (!empty($mention['title'])) { + $attrs['title'] = $mention['title']; + } + + $xs->elementStart('span', 'vcard'); + $xs->elementStart('a', $attrs); + $xs->element('span', 'fn nickname', $mention['text']); + $xs->elementEnd('a'); + $xs->elementEnd('span'); + + $output = $xs->getString(); + + Event::handle('EndLinkifyMention', array($mention, &$output)); + } + + return $output; +} + +function common_find_mentions($text, $notice) +{ + $mentions = array(); + + $sender = Profile::staticGet('id', $notice->profile_id); + + if (empty($sender)) { + return $mentions; + } + + if (Event::handle('StartFindMentions', array($sender, $text, &$mentions))) { + + // Get the context of the original notice, if any + + $originalAuthor = null; + $originalNotice = null; + $originalMentions = array(); + + // Is it a reply? + + if (!empty($notice) && !empty($notice->reply_to)) { + $originalNotice = Notice::staticGet('id', $notice->reply_to); + if (!empty($originalNotice)) { + $originalAuthor = Profile::staticGet('id', $originalNotice->profile_id); + + $ids = $originalNotice->getReplies(); + + foreach ($ids as $id) { + $repliedTo = Profile::staticGet('id', $id); + if (!empty($repliedTo)) { + $originalMentions[$repliedTo->nickname] = $repliedTo; + } + } + } + } + + preg_match_all('/^T ([A-Z0-9]{1,64}) /', + $text, + $tmatches, + PREG_OFFSET_CAPTURE); + + preg_match_all('/(?:^|\s+)@(['.NICKNAME_FMT.']{1,64})/', + $text, + $atmatches, + PREG_OFFSET_CAPTURE); + + $matches = array_merge($tmatches[1], $atmatches[1]); + + foreach ($matches as $match) { + + $nickname = common_canonical_nickname($match[0]); + + // Try to get a profile for this nickname. + // Start with conversation context, then go to + // sender context. + + if (!empty($originalAuthor) && $originalAuthor->nickname == $nickname) { + + $mentioned = $originalAuthor; + + } else if (!empty($originalMentions) && + array_key_exists($nickname, $originalMentions)) { + + $mentioned = $originalMentions[$nickname]; + } else { + $mentioned = common_relative_profile($sender, $nickname); + } + + if (!empty($mentioned)) { + + $user = User::staticGet('id', $mentioned->id); + + if ($user) { + $url = common_local_url('userbyid', array('id' => $user->id)); + } else { + $url = $mentioned->profileurl; + } + + $mention = array('mentioned' => array($mentioned), + 'text' => $match[0], + 'position' => $match[1], + 'url' => $url); + + if (!empty($mentioned->fullname)) { + $mention['title'] = $mentioned->fullname; + } + + $mentions[] = $mention; + } + } + + // @#tag => mention of all subscriptions tagged 'tag' + + preg_match_all('/(?:^|[\s\.\,\:\;]+)@#([\pL\pN_\-\.]{1,64})/', + $text, + $hmatches, + PREG_OFFSET_CAPTURE); + + foreach ($hmatches[1] as $hmatch) { + + $tag = common_canonical_tag($hmatch[0]); + + $tagged = Profile_tag::getTagged($sender->id, $tag); + + $url = common_local_url('subscriptions', + array('nickname' => $sender->nickname, + 'tag' => $tag)); + + $mentions[] = array('mentioned' => $tagged, + 'text' => $hmatch[0], + 'position' => $hmatch[1], + 'url' => $url); + } + + Event::handle('EndFindMentions', array($sender, $text, &$mentions)); + } + + return $mentions; +} + function common_render_text($text) { $r = htmlspecialchars($text); @@ -519,19 +715,23 @@ function callback_helper($matches, $callback, $notice_id) { return substr($matches[0],0,$left) . $result . substr($matches[0],$right); } -function curry($fn) { - //TODO switch to a PHP 5.3 function closure based approach if PHP 5.3 is used - $args = func_get_args(); - array_shift($args); - $id = uniqid('_partial'); - $GLOBALS[$id] = array($fn, $args); - return create_function('', - '$args = func_get_args(); '. - 'return call_user_func_array('. - '$GLOBALS["'.$id.'"][0],'. - 'array_merge('. - '$args,'. - '$GLOBALS["'.$id.'"][1]));'); +if (version_compare(PHP_VERSION, '5.3.0', 'ge')) { + // lambda implementation in a separate file; PHP 5.2 won't parse it. + require_once INSTALLDIR . "/lib/curry.php"; +} else { + function curry($fn) { + $args = func_get_args(); + array_shift($args); + $id = uniqid('_partial'); + $GLOBALS[$id] = array($fn, $args); + return create_function('', + '$args = func_get_args(); '. + 'return call_user_func_array('. + '$GLOBALS["'.$id.'"][0],'. + 'array_merge('. + '$args,'. + '$GLOBALS["'.$id.'"][1]));'); + } } function common_linkify($url) { @@ -572,20 +772,13 @@ function common_linkify($url) { } if (!empty($f)) { - if ($f->isEnclosure()) { + if ($f->getEnclosure()) { $is_attachment = true; $attachment_id = $f->id; - } else { - $foe = File_oembed::staticGet('file_id', $f->id); - if (!empty($foe)) { - // if it has OEmbed info, it's an attachment, too - $is_attachment = true; - $attachment_id = $f->id; - - $thumb = File_thumbnail::staticGet('file_id', $f->id); - if (!empty($thumb)) { - $has_thumb = true; - } + + $thumb = File_thumbnail::staticGet('file_id', $f->id); + if (!empty($thumb)) { + $has_thumb = true; } } } @@ -611,8 +804,28 @@ function common_shorten_links($text) function common_xml_safe_str($str) { - // Neutralize control codes and surrogates - return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str); + // Replace common eol and extra whitespace input chars + $unWelcome = array( + "\t", // tab + "\n", // newline + "\r", // cr + "\0", // null byte eos + "\x0B" // vertical tab + ); + + $replacement = array( + ' ', // single space + ' ', + '', // nothing + '', + ' ' + ); + + $str = str_replace($unWelcome, $replacement, $str); + + // Neutralize any additional control codes and UTF-16 surrogates + // (Twitter uses '*') + return preg_replace('/[\p{Cc}\p{Cs}]/u', '*', $str); } function common_tag_link($tag) @@ -639,39 +852,11 @@ function common_valid_profile_tag($str) return preg_match('/^[A-Za-z0-9_\-\.]{1,64}$/', $str); } -function common_at_link($sender_id, $nickname) -{ - $sender = Profile::staticGet($sender_id); - $recipient = common_relative_profile($sender, common_canonical_nickname($nickname)); - if ($recipient) { - $user = User::staticGet('id', $recipient->id); - if ($user) { - $url = common_local_url('userbyid', array('id' => $user->id)); - } else { - $url = $recipient->profileurl; - } - $xs = new XMLStringer(false); - $attrs = array('href' => $url, - 'class' => 'url'); - if (!empty($recipient->fullname)) { - $attrs['title'] = $recipient->fullname . ' (' . $recipient->nickname . ')'; - } - $xs->elementStart('span', 'vcard'); - $xs->elementStart('a', $attrs); - $xs->element('span', 'fn nickname', $nickname); - $xs->elementEnd('a'); - $xs->elementEnd('span'); - return $xs->getString(); - } else { - return $nickname; - } -} - function common_group_link($sender_id, $nickname) { $sender = Profile::staticGet($sender_id); - $group = User_group::getForNickname($nickname); - if ($group && $sender->isMember($group)) { + $group = User_group::getForNickname($nickname, $sender); + if ($sender && $group && $sender->isMember($group)) { $attrs = array('href' => $group->permalink(), 'class' => 'url'); if (!empty($group->fullname)) { @@ -689,29 +874,6 @@ function common_group_link($sender_id, $nickname) } } -function common_at_hash_link($sender_id, $tag) -{ - $user = User::staticGet($sender_id); - if (!$user) { - return $tag; - } - $tagged = Profile_tag::getTagged($user->id, common_canonical_tag($tag)); - if ($tagged) { - $url = common_local_url('subscriptions', - array('nickname' => $user->nickname, - 'tag' => $tag)); - $xs = new XMLStringer(); - $xs->elementStart('span', 'tag'); - $xs->element('a', array('href' => $url, - 'rel' => $tag), - $tag); - $xs->elementEnd('span'); - return $xs->getString(); - } else { - return $tag; - } -} - function common_relative_profile($sender, $nickname, $dt=null) { // Try to find profiles this profile is subscribed to that have this nickname @@ -748,7 +910,7 @@ function common_relative_profile($sender, $nickname, $dt=null) return null; } -function common_local_url($action, $args=null, $params=null, $fragment=null) +function common_local_url($action, $args=null, $params=null, $fragment=null, $addSession=true) { $r = Router::get(); $path = $r->build($action, $args, $params, $fragment); @@ -756,12 +918,12 @@ function common_local_url($action, $args=null, $params=null, $fragment=null) $ssl = common_is_sensitive($action); if (common_config('site','fancy')) { - $url = common_path(mb_substr($path, 1), $ssl); + $url = common_path(mb_substr($path, 1), $ssl, $addSession); } else { if (mb_strpos($path, '/index.php') === 0) { - $url = common_path(mb_substr($path, 1), $ssl); + $url = common_path(mb_substr($path, 1), $ssl, $addSession); } else { - $url = common_path('index.php'.$path, $ssl); + $url = common_path('index.php'.$path, $ssl, $addSession); } } return $url; @@ -780,7 +942,7 @@ function common_is_sensitive($action) return $ssl; } -function common_path($relative, $ssl=false) +function common_path($relative, $ssl=false, $addSession=true) { $pathpart = (common_config('site', 'path')) ? common_config('site', 'path')."/" : ''; @@ -793,20 +955,52 @@ function common_path($relative, $ssl=false) } else if (common_config('site', 'server')) { $serverpart = common_config('site', 'server'); } else { - common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.'); + common_log(LOG_ERR, 'Site server not configured, unable to determine site name.'); } } else { $proto = 'http'; if (common_config('site', 'server')) { $serverpart = common_config('site', 'server'); } else { - common_log(LOG_ERR, 'Site Sever not configured, unable to determine site name.'); + common_log(LOG_ERR, 'Site server not configured, unable to determine site name.'); } } + if ($addSession) { + $relative = common_inject_session($relative, $serverpart); + } + return $proto.'://'.$serverpart.'/'.$pathpart.$relative; } +function common_inject_session($url, $serverpart = null) +{ + if (common_have_session()) { + + if (empty($serverpart)) { + $serverpart = parse_url($url, PHP_URL_HOST); + } + + $currentServer = $_SERVER['HTTP_HOST']; + + // Are we pointing to another server (like an SSL server?) + + if (!empty($currentServer) && + 0 != strcasecmp($currentServer, $serverpart)) { + // Pass the session ID as a GET parameter + $sesspart = session_name() . '=' . session_id(); + $i = strpos($url, '?'); + if ($i === false) { // no GET params, just append + $url .= '?' . $sesspart; + } else { + $url = substr($url, 0, $i + 1).$sesspart.'&'.substr($url, $i + 1); + } + } + } + + return $url; +} + function common_date_string($dt) { // XXX: do some sexy date formatting @@ -892,6 +1086,26 @@ function common_sql_date($datetime) return strftime('%Y-%m-%d %H:%M:%S', $datetime); } +/** + * Return an SQL fragment to calculate an age-based weight from a given + * timestamp or datetime column. + * + * @param string $column name of field we're comparing against current time + * @param integer $dropoff divisor for age in seconds before exponentiation + * @return string SQL fragment + */ +function common_sql_weight($column, $dropoff) +{ + if (common_config('db', 'type') == 'pgsql') { + // PostgreSQL doesn't support timestampdiff function. + // @fixme will this use the right time zone? + // @fixme does this handle cross-year subtraction correctly? + return "sum(exp(-extract(epoch from (now() - $column)) / $dropoff))"; + } else { + return "sum(exp(timestampdiff(second, utc_timestamp(), $column) / $dropoff))"; + } +} + function common_redirect($url, $code=307) { static $status = array(301 => "Moved Permanently", @@ -913,7 +1127,7 @@ function common_redirect($url, $code=307) function common_broadcast_notice($notice, $remote=false) { - return common_enqueue_notice($notice); + // DO NOTHING! } // Stick the notice on the queue @@ -923,9 +1137,13 @@ function common_enqueue_notice($notice) static $localTransports = array('omb', 'ping'); - static $allTransports = array('sms', 'plugin'); - - $transports = $allTransports; + $transports = array(); + if (common_config('sms', 'enabled')) { + $transports[] = 'sms'; + } + if (Event::hasHandler('HandleQueuedNotice')) { + $transports[] = 'plugin'; + } $xmpp = common_config('xmpp', 'enabled'); @@ -933,6 +1151,7 @@ function common_enqueue_notice($notice) $transports[] = 'jabber'; } + // @fixme move these checks into QueueManager and/or individual handlers if ($notice->is_local == Notice::LOCAL_PUBLIC || $notice->is_local == Notice::LOCAL_NONPUBLIC) { $transports = array_merge($transports, $localTransports); @@ -956,25 +1175,35 @@ function common_enqueue_notice($notice) return true; } -function common_broadcast_profile($profile) +/** + * Broadcast profile updates to OMB and other remote subscribers. + * + * Since this may be slow with a lot of subscribers or bad remote sites, + * this is run through the background queues if possible. + */ +function common_broadcast_profile(Profile $profile) { - // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ - require_once(INSTALLDIR.'/lib/omb.php'); - omb_broadcast_profile($profile); - // XXX: Other broadcasts...? + $qm = QueueManager::get(); + $qm->enqueue($profile, "profile"); return true; } function common_profile_url($nickname) { - return common_local_url('showstream', array('nickname' => $nickname)); + return common_local_url('showstream', array('nickname' => $nickname), + null, null, false); } // Should make up a reasonable root URL function common_root_url($ssl=false) { - return common_path('', $ssl); + $url = common_path('', $ssl, false); + $i = strpos($url, '?'); + if ($i !== false) { + $url = substr($url, 0, $i); + } + return $url; } // returns $bytes bytes of random data as a hexadecimal string @@ -1046,19 +1275,43 @@ function common_log_line($priority, $msg) return date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n"; } +function common_request_id() +{ + $pid = getmypid(); + $server = common_config('site', 'server'); + if (php_sapi_name() == 'cli') { + $script = basename($_SERVER['PHP_SELF']); + return "$server:$script:$pid"; + } else { + static $req_id = null; + if (!isset($req_id)) { + $req_id = substr(md5(mt_rand()), 0, 8); + } + if (isset($_SERVER['REQUEST_URI'])) { + $url = $_SERVER['REQUEST_URI']; + } + $method = $_SERVER['REQUEST_METHOD']; + return "$server:$pid.$req_id $method $url"; + } +} + function common_log($priority, $msg, $filename=null) { - $logfile = common_config('site', 'logfile'); - if ($logfile) { - $log = fopen($logfile, "a"); - if ($log) { - $output = common_log_line($priority, $msg); - fwrite($log, $output); - fclose($log); + if(Event::handle('StartLog', array(&$priority, &$msg, &$filename))){ + $msg = '[' . common_request_id() . '] ' . $msg; + $logfile = common_config('site', 'logfile'); + if ($logfile) { + $log = fopen($logfile, "a"); + if ($log) { + $output = common_log_line($priority, $msg); + fwrite($log, $output); + fclose($log); + } + } else { + common_ensure_syslog(); + syslog($priority, $msg); } - } else { - common_ensure_syslog(); - syslog($priority, $msg); + Event::handle('EndLog', array($priority, $msg, $filename)); } } @@ -1214,8 +1467,12 @@ function common_copy_args($from) return $to; } -// Neutralise the evil effects of magic_quotes_gpc in the current request. -// This is used before handing a request off to OAuthRequest::from_request. +/** + * Neutralise the evil effects of magic_quotes_gpc in the current request. + * This is used before handing a request off to OAuthRequest::from_request. + * @fixme Doesn't consider vars other than _POST and _GET? + * @fixme Can't be undone and could corrupt data if run twice. + */ function common_remove_magic_from_request() { if(get_magic_quotes_gpc()) { @@ -1226,7 +1483,8 @@ function common_remove_magic_from_request() function common_user_uri(&$user) { - return common_local_url('userbyid', array('id' => $user->id)); + return common_local_url('userbyid', array('id' => $user->id), + null, null, false); } function common_notice_uri(&$notice) @@ -1342,41 +1600,17 @@ function common_session_token() function common_cache_key($extra) { - $base_key = common_config('memcached', 'base'); - - if (empty($base_key)) { - $base_key = common_keyize(common_config('site', 'name')); - } - - return 'statusnet:' . $base_key . ':' . $extra; + return Cache::key($extra); } function common_keyize($str) { - $str = strtolower($str); - $str = preg_replace('/\s/', '_', $str); - return $str; + return Cache::keyize($str); } function common_memcache() { - static $cache = null; - if (!common_config('memcached', 'enabled')) { - return null; - } else { - if (!$cache) { - $cache = new Memcache(); - $servers = common_config('memcached', 'server'); - if (is_array($servers)) { - foreach($servers as $server) { - $cache->addServer($server); - } - } else { - $cache->addServer($servers); - } - } - return $cache; - } + return Cache::instance(); } function common_license_terms($uri) @@ -1417,8 +1651,20 @@ function common_database_tablename($tablename) return $tablename; } +/** + * Shorten a URL with the current user's configured shortening service, + * or ur1.ca if configured, or not at all if no shortening is set up. + * Length is not considered. + * + * @param string $long_url + * @return string may return the original URL if shortening failed + * + * @fixme provide a way to specify a particular shortener + * @fixme provide a way to specify to use a given user's shortening preferences + */ function common_shorten_url($long_url) { + $long_url = trim($long_url); $user = common_current_user(); if (empty($user)) { // common current user does not find a user when called from the XMPP daemon @@ -1433,10 +1679,20 @@ function common_shorten_url($long_url) return $long_url; }else{ //URL was shortened, so return the result - return $shortenedUrl; + return trim($shortenedUrl); } } +/** + * @return mixed array($proxy, $ip) for web requests; proxy may be null + * null if not a web request + * + * @fixme X-Forwarded-For can be chained by multiple proxies; + we should parse the list and provide a cleaner array + * @fixme X-Forwarded-For can be forged by clients; only use them if trusted + * @fixme X_Forwarded_For headers will override X-Forwarded-For read through $_SERVER; + * use function to get exact request headers from Apache if possible. + */ function common_client_ip() { if (!isset($_SERVER) || !array_key_exists('REQUEST_METHOD', $_SERVER)) { @@ -1461,3 +1717,57 @@ function common_client_ip() return array($proxy, $ip); } + +function common_url_to_nickname($url) +{ + static $bad = array('query', 'user', 'password', 'port', 'fragment'); + + $parts = parse_url($url); + + # If any of these parts exist, this won't work + + foreach ($bad as $badpart) { + if (array_key_exists($badpart, $parts)) { + return null; + } + } + + # We just have host and/or path + + # If it's just a host... + if (array_key_exists('host', $parts) && + (!array_key_exists('path', $parts) || strcmp($parts['path'], '/') == 0)) + { + $hostparts = explode('.', $parts['host']); + + # Try to catch common idiom of nickname.service.tld + + if ((count($hostparts) > 2) && + (strlen($hostparts[count($hostparts) - 2]) > 3) && # try to skip .co.uk, .com.au + (strcmp($hostparts[0], 'www') != 0)) + { + return common_nicknamize($hostparts[0]); + } else { + # Do the whole hostname + return common_nicknamize($parts['host']); + } + } else { + if (array_key_exists('path', $parts)) { + # Strip starting, ending slashes + $path = preg_replace('@/$@', '', $parts['path']); + $path = preg_replace('@^/@', '', $path); + $path = basename($path); + if ($path) { + return common_nicknamize($path); + } + } + } + + return null; +} + +function common_nicknamize($str) +{ + $str = preg_replace('/\W/', '', $str); + return strtolower($str); +}