MyShaarli/index.php

2205 lines
87 KiB
PHP
Raw Normal View History

2013-02-26 10:09:41 +01:00
<?php
/**
* Shaarli v0.8.0 - Shaare your links...
*
* The personal, minimalist, super-fast, database free, bookmarking service.
*
* Friendly fork by the Shaarli community:
* - https://github.com/shaarli/Shaarli
*
* Original project by sebsauvage.net:
* - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
* - https://github.com/sebsauvage/Shaarli
*
* Licence: http://www.opensource.org/licenses/zlib-license.php
*
* Requires: PHP 5.3.x
*/
// Set 'UTC' as the default timezone if it is not defined in php.ini
// See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
if (date_default_timezone_get() == '') {
date_default_timezone_set('UTC');
}
/*
* PHP configuration
*/
define('shaarli_version', '0.8.0');
// http://server.com/x/shaarli --> /shaarli/
define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
2013-02-26 10:09:41 +01:00
// High execution time in case of problematic imports/exports.
ini_set('max_input_time','60');
// Try to set max upload file size and read
ini_set('memory_limit', '128M');
2013-02-26 10:09:41 +01:00
ini_set('post_max_size', '16M');
ini_set('upload_max_filesize', '16M');
// See all error except warnings
error_reporting(E_ALL^E_WARNING);
// See all errors (for debugging only)
//error_reporting(-1);
// 3rd-party libraries
if (! file_exists(__DIR__ . '/vendor/autoload.php')) {
header('Content-Type: text/plain; charset=utf-8');
echo "Error: missing Composer configuration\n\n"
."If you installed Shaarli through Git or using the development branch,\n"
."please refer to the installation documentation to install PHP"
." dependencies using Composer:\n"
."- https://github.com/shaarli/Shaarli/wiki/Server-requirements\n"
."- https://github.com/shaarli/Shaarli/wiki/Download-and-Installation";
exit;
}
require_once 'inc/rain.tpl.class.php';
require_once __DIR__ . '/vendor/autoload.php';
// Shaarli library
require_once 'application/ApplicationUtils.php';
require_once 'application/Cache.php';
require_once 'application/CachedPage.php';
require_once 'application/config/ConfigManager.php';
require_once 'application/config/ConfigPlugin.php';
require_once 'application/FeedBuilder.php';
require_once 'application/FileUtils.php';
require_once 'application/HttpUtils.php';
require_once 'application/Languages.php';
require_once 'application/LinkDB.php';
require_once 'application/LinkFilter.php';
require_once 'application/LinkUtils.php';
require_once 'application/NetscapeBookmarkUtils.php';
require_once 'application/PageBuilder.php';
require_once 'application/TimeZone.php';
require_once 'application/Url.php';
require_once 'application/Utils.php';
require_once 'application/PluginManager.php';
require_once 'application/Router.php';
require_once 'application/Updater.php';
// Ensure the PHP version is supported
try {
ApplicationUtils::checkPHPVersion('5.3', PHP_VERSION);
} catch(Exception $exc) {
header('Content-Type: text/plain; charset=utf-8');
echo $exc->getMessage();
exit;
}
// Force cookie path (but do not change lifetime)
$cookie = session_get_cookie_params();
$cookiedir = '';
if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
$cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
}
// Set default cookie expiration and path.
session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
// Set session parameters on server side.
// If the user does not access any page within this time, his/her session is considered expired.
define('INACTIVITY_TIMEOUT', 3600); // in seconds.
// Use cookies to store session.
ini_set('session.use_cookies', 1);
// Force cookies for session (phpsessionID forbidden in URL).
ini_set('session.use_only_cookies', 1);
// Prevent PHP form using sessionID in URL if cookies are disabled.
ini_set('session.use_trans_sid', false);
session_name('shaarli');
// Start session if needed (Some server auto-start sessions).
if (session_id() == '') {
session_start();
}
// Regenerate session ID if invalid or not defined in cookie.
if (isset($_COOKIE['shaarli']) && !is_session_id_valid($_COOKIE['shaarli'])) {
session_regenerate_id(true);
$_COOKIE['shaarli'] = session_id();
}
$conf = new ConfigManager();
$conf->setEmpty('general.timezone', date_default_timezone_get());
$conf->setEmpty('general.title', 'Shared links on '. escape(index_url($_SERVER)));
RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl'); // template directory
RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
2013-02-26 10:09:41 +01:00
$pluginManager = new PluginManager($conf);
$pluginManager->load($conf->get('general.enabled_plugins'));
date_default_timezone_set($conf->get('general.timezone', 'UTC'));
2016-05-29 14:26:23 +02:00
2013-02-26 10:09:41 +01:00
ob_start(); // Output buffering for the page cache.
// In case stupid admin has left magic_quotes enabled in php.ini:
if (get_magic_quotes_gpc())
{
function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
// Prevent caching on client side or proxy: (yes, it's ugly)
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
if (! is_file($conf->getConfigFileExt())) {
// Ensure Shaarli has proper access to its resources
$errors = ApplicationUtils::checkResourcePermissions($conf);
if ($errors != array()) {
$message = '<p>Insufficient permissions:</p><ul>';
foreach ($errors as $error) {
$message .= '<li>'.$error.'</li>';
}
$message .= '</ul>';
header('Content-Type: text/html; charset=utf-8');
echo $message;
exit;
}
// Display the installation form if no existing config is found
install($conf);
}
// a token depending of deployment salt, user password, and the current ip
define('STAY_SIGNED_IN_TOKEN', sha1($conf->get('credentials.hash') . $_SERVER['REMOTE_ADDR'] . $conf->get('credentials.salt')));
// Sniff browser language and set date format accordingly.
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
}
2013-02-26 10:09:41 +01:00
header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
/**
* 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);
2013-02-26 10:09:41 +01:00
/**
* PubSubHubbub protocol support (if enabled) [UNTESTED]
* (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
*
* @param ConfigManager $conf Configuration Manager instance.
*/
function pubsubhub($conf)
2013-02-26 10:09:41 +01:00
{
$pshUrl = $conf->get('config.PUBSUBHUB_URL');
if (!empty($pshUrl))
2013-02-26 10:09:41 +01:00
{
include_once './publisher.php';
$p = new Publisher($pshUrl);
$topic_url = array (
index_url($_SERVER).'?do=atom',
index_url($_SERVER).'?do=rss'
);
$p->publish_update($topic_url);
2013-02-26 10:09:41 +01:00
}
}
// ------------------------------------------------------------------------------------------
// Session management
// Returns the IP address of the client (Used to prevent session cookie hijacking.)
function allIPs()
{
$ip = $_SERVER['REMOTE_ADDR'];
2013-02-26 10:09:41 +01:00
// 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)
2013-02-26 10:09:41 +01:00
{
$hash = sha1($password . $login . $conf->get('credentials.salt'));
if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash'))
2013-02-26 10:09:41 +01:00
{ // Login/password is correct.
fillSessionInfo($conf);
logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
return true;
2013-02-26 10:09:41 +01:00
}
logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
return false;
2013-02-26 10:09:41 +01:00
}
// Returns true if the user is logged in.
function isLoggedIn()
{
global $userIsLoggedIn;
return $userIsLoggedIn;
2013-02-26 10:09:41 +01:00
}
// Force logout.
function logout() {
if (isset($_SESSION)) {
unset($_SESSION['uid']);
unset($_SESSION['ip']);
unset($_SESSION['username']);
unset($_SESSION['privateonly']);
}
setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH);
}
2013-02-26 10:09:41 +01:00
// ------------------------------------------------------------------------------------------
// 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)
2013-02-26 10:09:41 +01:00
{
$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;
}
2013-02-26 10:09:41 +01:00
$gb['FAILURES'][$ip]++;
if ($gb['FAILURES'][$ip] > ($conf->get('security.ban_after') - 1))
2013-02-26 10:09:41 +01:00
{
$gb['BANS'][$ip] = time() + $conf->get('security.ban_after', 1800);
logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'IP address banned from login');
2013-02-26 10:09:41 +01:00
}
$GLOBALS['IPBANS'] = $gb;
file_put_contents(
$conf->get('resource.ban_file', 'data/ipbans.php'),
"<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>"
);
2013-02-26 10:09:41 +01:00
}
/**
* Signals a successful login. Resets failed login counter.
*
* @param ConfigManager $conf Configuration Manager instance.
*/
function ban_loginOk($conf)
2013-02-26 10:09:41 +01:00
{
$ip = $_SERVER['REMOTE_ADDR'];
$gb = $GLOBALS['IPBANS'];
2013-02-26 10:09:41 +01:00
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?>"
);
2013-02-26 10:09:41 +01:00
}
/**
* 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)
2013-02-26 10:09:41 +01:00
{
$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.');
2013-02-26 10:09:41 +01:00
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?>"
);
2013-02-26 10:09:41 +01:00
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);
2013-02-26 10:09:41 +01:00
// If user wants to keep the session cookie even after the browser closes:
if (!empty($_POST['longlastingsession']))
{
setcookie('shaarli_staySignedIn', STAY_SIGNED_IN_TOKEN, time()+31536000, WEB_PATH);
2013-02-26 10:09:41 +01:00
$_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year)
$_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // 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!
2013-02-26 10:09:41 +01:00
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"
2013-02-26 10:09:41 +01:00
session_regenerate_id(true);
}
2013-02-26 10:09:41 +01:00
// Optional redirect after login:
if (isset($_GET['post'])) {
$uri = '?post='. urlencode($_GET['post']);
foreach (array('description', 'source', 'title') 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;
}
2013-02-26 10:09:41 +01:00
}
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') 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.
2013-02-26 10:09:41 +01:00
exit;
}
}
// ------------------------------------------------------------------------------------------
// Misc utility functions:
// Convert post_max_size/upload_max_filesize (e.g. '16M') parameters to bytes.
2013-02-26 10:09:41 +01:00
function return_bytes($val)
{
$val = trim($val); $last=strtolower($val[strlen($val)-1]);
switch($last)
{
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
// Try to determine max file size for uploads (POST).
// Returns an integer (in bytes)
function getMaxFileSize()
{
$size1 = return_bytes(ini_get('post_max_size'));
$size2 = return_bytes(ini_get('upload_max_filesize'));
// Return the smaller of two:
$maxsize = min($size1,$size2);
// FIXME: Then convert back to readable notations ? (e.g. 2M instead of 2000000)
2013-02-26 10:09:41 +01:00
return $maxsize;
}
// ------------------------------------------------------------------------------------------
// 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)
2013-02-26 10:09:41 +01:00
{
$rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string.
2013-02-26 10:09:41 +01:00
$_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.
2013-02-26 10:09:41 +01:00
function tokenOk($token)
{
if (isset($_SESSION['tokens'][$token]))
{
unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
return true; // Token is OK.
2013-02-26 10:09:41 +01:00
}
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) {
2013-02-26 10:09:41 +01:00
// Cache system
2016-05-10 23:31:41 +02:00
$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')
);
2013-02-26 10:09:41 +01:00
/* Some Shaarlies may have very few links, so we need to look
back in time (rsort()) until we have enough days ($nb_of_days).
*/
$linkdates = array();
foreach ($LINKSDB as $linkdate => $value) {
$linkdates[] = $linkdate;
}
2013-02-26 10:09:41 +01:00
rsort($linkdates);
$nb_of_days = 7; // We take 7 days.
$today = date('Ymd');
$days = array();
foreach ($linkdates as $linkdate) {
$day = substr($linkdate, 0, 8); // Extract day (without time)
if (strcmp($day,$today) < 0) {
if (empty($days[$day])) {
$days[$day] = array();
}
$days[$day][] = $linkdate;
}
if (count($days) > $nb_of_days) {
break; // Have we collected enough days?
2013-02-26 10:09:41 +01:00
}
}
2013-02-26 10:09:41 +01:00
// Build the RSS feed.
header('Content-Type: application/rss+xml; charset=utf-8');
$pageaddr = escape(index_url($_SERVER));
2013-02-26 10:09:41 +01:00
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 => $linkdates) {
$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.
2013-02-26 10:09:41 +01:00
// Build the HTML body of this RSS entry.
$links = array();
2013-02-26 10:09:41 +01:00
// We pre-format some fields for proper output.
foreach ($linkdates as $linkdate) {
2013-02-26 10:09:41 +01:00
$l = $LINKSDB[$linkdate];
$l['formatedDescription'] = format_description($l['description'], $conf->get('redirector.url'));
$l['thumbnail'] = thumbnail($conf, $l['url']);
$l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']);
$l['timestamp'] = $l_date->getTimestamp();
if (startsWith($l['url'], '?')) {
$l['url'] = index_url($_SERVER) . $l['url']; // make permalink URL absolute
}
$links[$linkdate] = $l;
2013-02-26 10:09:41 +01:00
}
2013-02-26 10:09:41 +01:00
// 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', $return_string=true);
2013-02-26 10:09:41 +01:00
echo $html . PHP_EOL;
}
echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
2013-02-26 10:09:41 +01:00
$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)
2013-02-26 10:09:41 +01:00
{
$day=date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
2013-02-26 10:09:41 +01:00
if (isset($_GET['day'])) $day=$_GET['day'];
2013-02-26 10:09:41 +01:00
$days = $LINKSDB->days();
$i = array_search($day,$days);
if ($i===false) { $i=count($days)-1; $day=$days[$i]; }
$previousday='';
$nextday='';
2013-02-26 10:09:41 +01:00
if ($i!==false)
{
if ($i>=1) $previousday=$days[$i-1];
2013-02-26 10:09:41 +01:00
if ($i<count($days)-1) $nextday=$days[$i+1];
}
try {
$linksToDisplay = $LINKSDB->filterDay($day);
} catch (Exception $exc) {
error_log($exc);
$linksToDisplay = array();
}
2013-02-26 10:09:41 +01:00
// We pre-format some fields for proper output.
foreach($linksToDisplay as $key=>$link)
{
2013-03-01 17:09:52 +01:00
$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']);
$date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
$linksToDisplay[$key]['timestamp'] = $date->getTimestamp();
2013-02-26 10:09:41 +01:00
}
2013-02-26 10:09:41 +01:00
/* 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
2013-02-26 10:09:41 +01:00