-/**
- * Checking session state (i.e. is the user still logged in)
- *
- * @param ConfigManager $conf The configuration manager.
- *
- * @return bool: true if the user is logged in, false otherwise.
- */
-function setup_login_state($conf)
-{
- if ($conf->get('security.open_shaarli')) {
- return true;
- }
- $userIsLoggedIn = false; // By default, we do not consider the user as logged in;
- $loginFailure = false; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
- if (! $conf->exists('credentials.login')) {
- $userIsLoggedIn = false; // Shaarli is not configured yet.
- $loginFailure = true;
- }
- if (isset($_COOKIE['shaarli_staySignedIn']) &&
- $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN &&
- !$loginFailure)
- {
- fillSessionInfo($conf);
- $userIsLoggedIn = true;
- }
- // If session does not exist on server side, or IP address has changed, or session has expired, logout.
- if (empty($_SESSION['uid'])
- || ($conf->get('security.session_protection_disabled') === false && $_SESSION['ip'] != allIPs())
- || time() >= $_SESSION['expires_on'])
- {
- logout();
- $userIsLoggedIn = false;
- $loginFailure = true;
- }
- if (!empty($_SESSION['longlastingsession'])) {
- $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
- }
- else {
- $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
- }
- if (!$loginFailure) {
- $userIsLoggedIn = true;
- }
-
- return $userIsLoggedIn;
-}
-$userIsLoggedIn = setup_login_state($conf);
-
-// ------------------------------------------------------------------------------------------
-// Session management
-
-// Returns the IP address of the client (Used to prevent session cookie hijacking.)
-function allIPs()
-{
- $ip = $_SERVER['REMOTE_ADDR'];
- // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
- if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
- if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
- return $ip;
-}
-
-/**
- * Load user session.
- *
- * @param ConfigManager $conf Configuration Manager instance.
- */
-function fillSessionInfo($conf)
-{
- $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
- $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
- $_SESSION['username']= $conf->get('credentials.login');
- $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
-}
-
-/**
- * Check that user/password is correct.
- *
- * @param string $login Username
- * @param string $password User password
- * @param ConfigManager $conf Configuration Manager instance.
- *
- * @return bool: authentication successful or not.
- */
-function check_auth($login, $password, $conf)
-{
- $hash = sha1($password . $login . $conf->get('credentials.salt'));
- if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash'))
- { // Login/password is correct.
- fillSessionInfo($conf);
- logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
- return true;
- }
- logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
- return false;
-}
-
-// Returns true if the user is logged in.
-function isLoggedIn()
-{
- global $userIsLoggedIn;
- return $userIsLoggedIn;
-}
-
-// Force logout.
-function logout() {
- if (isset($_SESSION)) {
- unset($_SESSION['uid']);
- unset($_SESSION['ip']);
- unset($_SESSION['username']);
- unset($_SESSION['privateonly']);
- unset($_SESSION['untaggedonly']);
- }
- setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH);
-}
-
-
-// ------------------------------------------------------------------------------------------
-// Brute force protection system
-// Several consecutive failed logins will ban the IP address for 30 minutes.
-if (!is_file($conf->get('resource.ban_file', 'data/ipbans.php'))) {
- // FIXME! globals
- file_put_contents(
- $conf->get('resource.ban_file', 'data/ipbans.php'),
- "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";\n?>"
- );
-}
-include $conf->get('resource.ban_file', 'data/ipbans.php');
-/**
- * Signal a failed login. Will ban the IP if too many failures:
- *
- * @param ConfigManager $conf Configuration Manager instance.
- */
-function ban_loginFailed($conf)
-{
- $ip = $_SERVER['REMOTE_ADDR'];
- $trusted = $conf->get('security.trusted_proxies', array());
- if (in_array($ip, $trusted)) {
- $ip = getIpAddressFromProxy($_SERVER, $trusted);
- if (!$ip) {
- return;
- }
- }
- $gb = $GLOBALS['IPBANS'];
- if (! isset($gb['FAILURES'][$ip])) {
- $gb['FAILURES'][$ip]=0;
- }
- $gb['FAILURES'][$ip]++;
- if ($gb['FAILURES'][$ip] > ($conf->get('security.ban_after') - 1))
- {
- $gb['BANS'][$ip] = time() + $conf->get('security.ban_after', 1800);
- logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'IP address banned from login');
- }
- $GLOBALS['IPBANS'] = $gb;
- file_put_contents(
- $conf->get('resource.ban_file', 'data/ipbans.php'),
- "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"
- );
-}
-
-/**
- * Signals a successful login. Resets failed login counter.
- *
- * @param ConfigManager $conf Configuration Manager instance.
- */
-function ban_loginOk($conf)
-{
- $ip = $_SERVER['REMOTE_ADDR'];
- $gb = $GLOBALS['IPBANS'];
- unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
- $GLOBALS['IPBANS'] = $gb;
- file_put_contents(
- $conf->get('resource.ban_file', 'data/ipbans.php'),
- "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"
- );
-}
-
-/**
- * Checks if the user CAN login. If 'true', the user can try to login.
- *
- * @param ConfigManager $conf Configuration Manager instance.
- *
- * @return bool: true if the user is allowed to login.
- */
-function ban_canLogin($conf)
-{
- $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
- if (isset($gb['BANS'][$ip]))
- {
- // User is banned. Check if the ban has expired:
- if ($gb['BANS'][$ip]<=time())
- { // Ban expired, user can try to login again.
- logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Ban lifted.');
- unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
- file_put_contents(
- $conf->get('resource.ban_file', 'data/ipbans.php'),
- "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"
- );
- return true; // Ban has expired, user can login.
- }
- return false; // User is banned.
- }
- return true; // User is not banned.
-}
-
-// ------------------------------------------------------------------------------------------
-// Process login form: Check if login/password is correct.
-if (isset($_POST['login']))
-{
- if (!ban_canLogin($conf)) die('I said: NO. You are banned for the moment. Go away.');
- if (isset($_POST['password'])
- && tokenOk($_POST['token'])
- && (check_auth($_POST['login'], $_POST['password'], $conf))
- ) { // Login/password is OK.
- ban_loginOk($conf);
- // If user wants to keep the session cookie even after the browser closes:
- if (!empty($_POST['longlastingsession']))
- {
- $_SESSION['longlastingsession'] = 31536000; // (31536000 seconds = 1 year)
- $expiration = time() + $_SESSION['longlastingsession']; // calculate relative cookie expiration (1 year from now)
- setcookie('shaarli_staySignedIn', STAY_SIGNED_IN_TOKEN, $expiration, WEB_PATH);
- $_SESSION['expires_on'] = $expiration; // Set session expiration on server-side.
-
- $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
- session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
- // Note: Never forget the trailing slash on the cookie path!
- session_regenerate_id(true); // Send cookie with new expiration date to browser.
- }
- else // Standard session expiration (=when browser closes)
- {
- $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
- session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes"
- session_regenerate_id(true);
- }
-
- // Optional redirect after login:
- if (isset($_GET['post'])) {
- $uri = '?post='. urlencode($_GET['post']);
- foreach (array('description', 'source', 'title', 'tags') as $param) {
- if (!empty($_GET[$param])) {
- $uri .= '&'.$param.'='.urlencode($_GET[$param]);
- }
- }
- header('Location: '. $uri);
- exit;
- }
-
- if (isset($_GET['edit_link'])) {
- header('Location: ?edit_link='. escape($_GET['edit_link']));
- exit;
- }
-
- if (isset($_POST['returnurl'])) {
- // Prevent loops over login screen.
- if (strpos($_POST['returnurl'], 'do=login') === false) {
- header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
- exit;
- }
- }
- header('Location: ?'); exit;
- }
- else
- {
- ban_loginFailed($conf);
- $redir = '&username='. $_POST['login'];
- if (isset($_GET['post'])) {
- $redir .= '&post=' . urlencode($_GET['post']);
- foreach (array('description', 'source', 'title', 'tags') as $param) {
- if (!empty($_GET[$param])) {
- $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
- }
- }
- }
- echo '<script>alert("Wrong login/password.");document.location=\'?do=login'.$redir.'\';</script>'; // Redirect to login screen.
- exit;
- }
-}
-
-// ------------------------------------------------------------------------------------------
-// Token management for XSRF protection
-// Token should be used in any form which acts on data (create,update,delete,import...).
-if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
-
-/**
- * Returns a token.
- *
- * @param ConfigManager $conf Configuration Manager instance.
- *
- * @return string token.
- */
-function getToken($conf)
-{
- $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string.
- $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
- return $rnd;
-}
-
-// Tells if a token is OK. Using this function will destroy the token.
-// true=token is OK.
-function tokenOk($token)
-{
- if (isset($_SESSION['tokens'][$token]))
- {
- unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
- return true; // Token is OK.
- }
- return false; // Wrong token, or already used.
-}
-
-/**
- * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
- * Gives the last 7 days (which have links).
- * This RSS feed cannot be filtered.
- *
- * @param ConfigManager $conf Configuration Manager instance.
- */
-function showDailyRSS($conf) {
- // Cache system
- $query = $_SERVER['QUERY_STRING'];
- $cache = new CachedPage(
- $conf->get('config.PAGE_CACHE'),
- page_url($_SERVER),
- startsWith($query,'do=dailyrss') && !isLoggedIn()
- );
- $cached = $cache->cachedVersion();
- if (!empty($cached)) {
- echo $cached;
- exit;
- }
-
- // If cached was not found (or not usable), then read the database and build the response:
- // Read links from database (and filter private links if used it not logged in).
- $LINKSDB = new LinkDB(
- $conf->get('resource.datastore'),
- isLoggedIn(),
- $conf->get('privacy.hide_public_links'),
- $conf->get('redirector.url'),
- $conf->get('redirector.encode_url')
- );
-
- /* Some Shaarlies may have very few links, so we need to look
- back in time until we have enough days ($nb_of_days).
- */
- $nb_of_days = 7; // We take 7 days.
- $today = date('Ymd');
- $days = array();
-
- foreach ($LINKSDB as $link) {
- $day = $link['created']->format('Ymd'); // Extract day (without time)
- if (strcmp($day, $today) < 0) {
- if (empty($days[$day])) {
- $days[$day] = array();
- }
- $days[$day][] = $link;
- }
-
- if (count($days) > $nb_of_days) {
- break; // Have we collected enough days?
- }
- }
-
- // Build the RSS feed.
- header('Content-Type: application/rss+xml; charset=utf-8');
- $pageaddr = escape(index_url($_SERVER));
- echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
- echo '<channel>';
- echo '<title>Daily - '. $conf->get('general.title') . '</title>';
- echo '<link>'. $pageaddr .'</link>';
- echo '<description>Daily shared links</description>';
- echo '<language>en-en</language>';
- echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
-
- // For each day.
- foreach ($days as $day => $links) {
- $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
- $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
-
- // We pre-format some fields for proper output.
- foreach ($links as &$link) {
- $link['formatedDescription'] = format_description($link['description'], $conf->get('redirector.url'));
- $link['thumbnail'] = thumbnail($conf, $link['url']);
- $link['timestamp'] = $link['created']->getTimestamp();
- if (startsWith($link['url'], '?')) {
- $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
- }
- }
-
- // Then build the HTML for this day:
- $tpl = new RainTPL;
- $tpl->assign('title', $conf->get('general.title'));
- $tpl->assign('daydate', $dayDate->getTimestamp());
- $tpl->assign('absurl', $absurl);
- $tpl->assign('links', $links);
- $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
- $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
- $html = $tpl->draw('dailyrss', true);
-
- echo $html . PHP_EOL;
- }
- echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
-
- $cache->cache(ob_get_contents());
- ob_end_flush();
- exit;
-}
-
-/**
- * Show the 'Daily' page.
- *
- * @param PageBuilder $pageBuilder Template engine wrapper.
- * @param LinkDB $LINKSDB LinkDB instance.
- * @param ConfigManager $conf Configuration Manager instance.
- * @param PluginManager $pluginManager Plugin Manager instane.
- */
-function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager)
-{
- $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
- if (isset($_GET['day'])) {
- $day = $_GET['day'];
- }
-
- $days = $LINKSDB->days();
- $i = array_search($day, $days);
- if ($i === false && count($days)) {
- // no links for day, but at least one day with links
- $i = count($days) - 1;
- $day = $days[$i];
- }
- $previousday = '';
- $nextday = '';
-
- if ($i !== false) {
- if ($i >= 1) {
- $previousday=$days[$i - 1];
- }
- if ($i < count($days) - 1) {
- $nextday = $days[$i + 1];
- }
- }
- try {
- $linksToDisplay = $LINKSDB->filterDay($day);
- } catch (Exception $exc) {
- error_log($exc);
- $linksToDisplay = array();
- }
-
- // We pre-format some fields for proper output.
- foreach($linksToDisplay as $key => $link) {
- $taglist = explode(' ',$link['tags']);
- uasort($taglist, 'strcasecmp');
- $linksToDisplay[$key]['taglist']=$taglist;
- $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('redirector.url'));
- $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
- $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
- }
-
- /* We need to spread the articles on 3 columns.
- I did not want to use a JavaScript lib like http://masonry.desandro.com/
- so I manually spread entries with a simple method: I roughly evaluate the
- height of a div according to title and description length.
- */
- $columns = array(array(), array(), array()); // Entries to display, for each column.
- $fill = array(0, 0, 0); // Rough estimate of columns fill.
- foreach($linksToDisplay as $key => $link) {
- // Roughly estimate length of entry (by counting characters)
- // Title: 30 chars = 1 line. 1 line is 30 pixels height.
- // Description: 836 characters gives roughly 342 pixel height.
- // This is not perfect, but it's usually OK.
- $length = strlen($link['title']) + (342 * strlen($link['description'])) / 836;
- if ($link['thumbnail']) {
- $length += 100; // 1 thumbnails roughly takes 100 pixels height.
- }
- // Then put in column which is the less filled:
- $smallest = min($fill); // find smallest value in array.
- $index = array_search($smallest, $fill); // find index of this smallest value.
- array_push($columns[$index], $link); // Put entry in this column.
- $fill[$index] += $length;
- }
-
- $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
- $data = array(
- 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
- 'linksToDisplay' => $linksToDisplay,
- 'cols' => $columns,
- 'day' => $dayDate->getTimestamp(),
- 'dayDate' => $dayDate,
- 'previousday' => $previousday,
- 'nextday' => $nextday,
- );
-
- $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn()));
-
- foreach ($data as $key => $value) {
- $pageBuilder->assign($key, $value);
- }
-
- $pageBuilder->renderPage('daily');
- exit;
-}
-
-/**
- * Renders the linklist
- *
- * @param pageBuilder $PAGE pageBuilder instance.
- * @param LinkDB $LINKSDB LinkDB instance.
- * @param ConfigManager $conf Configuration Manager instance.
- * @param PluginManager $pluginManager Plugin Manager instance.
- */
-function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) {
- buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager); // Compute list of links to display
- $PAGE->renderPage('linklist');
-}
-
-/**
- * Render HTML page (according to URL parameters and user rights)
- *
- * @param ConfigManager $conf Configuration Manager instance.
- * @param PluginManager $pluginManager Plugin Manager instance,
- * @param LinkDB $LINKSDB
- * @param History $history instance
- */
-function renderPage($conf, $pluginManager, $LINKSDB, $history)
-{
- $updater = new Updater(
- read_updates_file($conf->get('resource.updates')),
- $LINKSDB,
- $conf,
- isLoggedIn()
- );
- try {
- $newUpdates = $updater->update();
- if (! empty($newUpdates)) {
- write_updates_file(
- $conf->get('resource.updates'),
- $updater->getDoneUpdates()
- );
- }
- }
- catch(Exception $e) {
- die($e->getMessage());
- }
-
- $PAGE = new PageBuilder($conf, $LINKSDB);
- $PAGE->assign('linkcount', count($LINKSDB));
- $PAGE->assign('privateLinkcount', count_private($LINKSDB));
- $PAGE->assign('plugin_errors', $pluginManager->getErrors());
-
- // Determine which page will be rendered.
- $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
- $targetPage = Router::findPage($query, $_GET, isLoggedIn());
-
- if (
- // if the user isn't logged in
- !isLoggedIn() &&
- // and Shaarli doesn't have public content...
- $conf->get('privacy.hide_public_links') &&
- // and is configured to enforce the login
- $conf->get('privacy.force_login') &&
- // and the current page isn't already the login page
- $targetPage !== Router::$PAGE_LOGIN &&
- // and the user is not requesting a feed (which would lead to a different content-type as expected)
- $targetPage !== Router::$PAGE_FEED_ATOM &&
- $targetPage !== Router::$PAGE_FEED_RSS
- ) {
- // force current page to be the login page
- $targetPage = Router::$PAGE_LOGIN;
- }
-
- // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
- // Then assign generated data to RainTPL.
- $common_hooks = array(
- 'includes',
- 'header',
- 'footer',
- );
-
- foreach($common_hooks as $name) {
- $plugin_data = array();
- $pluginManager->executeHooks('render_' . $name, $plugin_data,
- array(
- 'target' => $targetPage,
- 'loggedin' => isLoggedIn()
- )
- );
- $PAGE->assign('plugins_' . $name, $plugin_data);
- }
-
- // -------- Display login form.
- if ($targetPage == Router::$PAGE_LOGIN)
- {
- if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
- if (isset($_GET['username'])) {
- $PAGE->assign('username', escape($_GET['username']));
- }
- $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
- // add default state of the 'remember me' checkbox
- $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
- $PAGE->renderPage('loginform');
- exit;
- }
- // -------- User wants to logout.
- if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
- {
- invalidateCaches($conf->get('resource.page_cache'));
- logout();
- header('Location: ?');
- exit;
- }
-
- // -------- Picture wall
- if ($targetPage == Router::$PAGE_PICWALL)
- {
- // Optionally filter the results:
- $links = $LINKSDB->filterSearch($_GET);
- $linksToDisplay = array();
-
- // Get only links which have a thumbnail.
- foreach($links as $link)
- {
- $permalink='?'.$link['shorturl'];
- $thumb=lazyThumbnail($conf, $link['url'],$permalink);
- if ($thumb!='') // Only output links which have a thumbnail.
- {
- $link['thumbnail']=$thumb; // Thumbnail HTML code.
- $linksToDisplay[]=$link; // Add to array.
- }
- }
-
- $data = array(
- 'linksToDisplay' => $linksToDisplay,
- );
- $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn()));
-
- foreach ($data as $key => $value) {
- $PAGE->assign($key, $value);
- }
-
- $PAGE->renderPage('picwall');
- exit;
- }
-
- // -------- Tag cloud
- if ($targetPage == Router::$PAGE_TAGCLOUD)
- {
- $visibility = ! empty($_SESSION['privateonly']) ? 'private' : 'all';
- $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
- $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
-
- // We sort tags alphabetically, then choose a font size according to count.
- // First, find max value.
- $maxcount = 0;
- foreach ($tags as $value) {
- $maxcount = max($maxcount, $value);
- }
-
- alphabetical_sort($tags, false, true);
-
- $tagList = array();
- foreach($tags as $key => $value) {
- if (in_array($key, $filteringTags)) {
- continue;
- }
- // Tag font size scaling:
- // default 15 and 30 logarithm bases affect scaling,
- // 22 and 6 are arbitrary font sizes for max and min sizes.
- $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8;
- $tagList[$key] = array(
- 'count' => $value,
- 'size' => number_format($size, 2, '.', ''),
- );
- }
-
- $data = array(
- 'search_tags' => implode(' ', escape($filteringTags)),
- 'tags' => $tagList,
- );
- $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn()));
-
- foreach ($data as $key => $value) {
- $PAGE->assign($key, $value);
- }
-
- $PAGE->renderPage('tag.cloud');
- exit;
- }
-
- // -------- Tag list
- if ($targetPage == Router::$PAGE_TAGLIST)
- {
- $visibility = ! empty($_SESSION['privateonly']) ? 'private' : 'all';
- $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
- $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
- foreach ($filteringTags as $tag) {
- if (array_key_exists($tag, $tags)) {
- unset($tags[$tag]);
- }
- }
-
- if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
- alphabetical_sort($tags, false, true);
- }
-
- $data = [
- 'search_tags' => implode(' ', escape($filteringTags)),
- 'tags' => $tags,
- ];
- $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => isLoggedIn()]);
-
- foreach ($data as $key => $value) {
- $PAGE->assign($key, $value);
- }
-
- $PAGE->renderPage('tag.list');
- exit;
- }
-
- // Daily page.
- if ($targetPage == Router::$PAGE_DAILY) {
- showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
- }
-
- // ATOM and RSS feed.
- if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
- $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
- header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
-
- // Cache system
- $query = $_SERVER['QUERY_STRING'];
- $cache = new CachedPage(
- $conf->get('resource.page_cache'),
- page_url($_SERVER),
- startsWith($query,'do='. $targetPage) && !isLoggedIn()
- );
- $cached = $cache->cachedVersion();
- if (!empty($cached)) {
- echo $cached;
- exit;
- }
-
- // Generate data.
- $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn());
- $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
- $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !isLoggedIn());
- $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
- $data = $feedGenerator->buildData();
-
- // Process plugin hook.
- $pluginManager->executeHooks('render_feed', $data, array(
- 'loggedin' => isLoggedIn(),
- 'target' => $targetPage,
- ));
-
- // Render the template.
- $PAGE->assignAll($data);
- $PAGE->renderPage('feed.'. $feedType);
- $cache->cache(ob_get_contents());
- ob_end_flush();
- exit;
- }