MyShaarli/index.php

1957 lines
75 KiB
PHP
Raw Normal View History

2013-02-26 10:09:41 +01:00
<?php
/**
* Shaarli - 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.5.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
*/
// 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://shaarli.readthedocs.io/en/master/Server-configuration/\n"
."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
exit;
}
require_once 'inc/rain.tpl.class.php';
require_once __DIR__ . '/vendor/autoload.php';
// Shaarli library
require_once 'application/bookmark/LinkUtils.php';
2017-03-08 19:59:00 +01:00
require_once 'application/config/ConfigPlugin.php';
require_once 'application/feed/Cache.php';
require_once 'application/http/HttpUtils.php';
require_once 'application/http/UrlUtils.php';
require_once 'application/updater/UpdaterUtils.php';
require_once 'application/FileUtils.php';
require_once 'application/TimeZone.php';
require_once 'application/Utils.php';
use \Shaarli\ApplicationUtils;
use \Shaarli\Bookmark\Exception\LinkNotFoundException;
use \Shaarli\Bookmark\LinkDB;
use \Shaarli\Config\ConfigManager;
use \Shaarli\Feed\CachedPage;
use \Shaarli\Feed\FeedBuilder;
use \Shaarli\History;
use \Shaarli\Languages;
use \Shaarli\Netscape\NetscapeBookmarkUtils;
use \Shaarli\Plugin\PluginManager;
use \Shaarli\Render\PageBuilder;
use \Shaarli\Render\ThemeUtils;
use \Shaarli\Router;
use \Shaarli\Security\LoginManager;
use \Shaarli\Security\SessionManager;
use \Shaarli\Thumbnailer;
use \Shaarli\Updater\Updater;
// Ensure the PHP version is supported
try {
ApplicationUtils::checkPHPVersion('5.5', PHP_VERSION);
} catch (Exception $exc) {
header('Content-Type: text/plain; charset=utf-8');
echo $exc->getMessage();
exit;
}
define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
// 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.
// 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_status() == PHP_SESSION_NONE) {
session_start();
}
// Regenerate session ID if invalid or not defined in cookie.
if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
session_regenerate_id(true);
$_COOKIE['shaarli'] = session_id();
}
$conf = new ConfigManager();
$sessionManager = new SessionManager($_SESSION, $conf);
$loginManager = new LoginManager($GLOBALS, $conf, $sessionManager);
$loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
$clientIpId = client_ip_id($_SERVER);
// LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
if (! defined('LC_MESSAGES')) {
define('LC_MESSAGES', LC_COLLATE);
}
// Sniff browser language and set date format accordingly.
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
}
new Languages(setlocale(LC_MESSAGES, 0), $conf);
$conf->setEmpty('general.timezone', date_default_timezone_get());
$conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // 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.
// 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>'. t('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, $sessionManager, $loginManager);
}
$loginManager->checkLoginState($_COOKIE, $clientIpId);
2013-02-26 10:09:41 +01:00
/**
* Adapter function to ensure compatibility with third-party templates
*
* @see https://github.com/shaarli/Shaarli/pull/1086
*
* @return bool true when the user is logged in, false otherwise
*/
2013-02-26 10:09:41 +01:00
function isLoggedIn()
{
global $loginManager;
return $loginManager->isLoggedIn();
2013-02-26 10:09:41 +01:00
}
2013-02-26 10:09:41 +01:00
// ------------------------------------------------------------------------------------------
// Process login form: Check if login/password is correct.
if (isset($_POST['login'])) {
if (! $loginManager->canLogin($_SERVER)) {
die(t('I said: NO. You are banned for the moment. Go away.'));
}
if (isset($_POST['password'])
&& $sessionManager->checkToken($_POST['token'])
&& $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
) {
$loginManager->handleSuccessfulLogin($_SERVER);
$cookiedir = '';
if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
// Note: Never forget the trailing slash on the cookie path!
$cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
2013-02-26 10:09:41 +01:00
}
if (!empty($_POST['longlastingsession'])) {
// Keep the session cookie even after the browser closes
$sessionManager->setStaySignedIn(true);
$expirationTime = $sessionManager->extendSession();
setcookie(
$loginManager::$STAY_SIGNED_IN_COOKIE,
$loginManager->getStaySignedInToken(),
$expirationTime,
WEB_PATH
);
} else {
// Standard session expiration (=when browser closes)
$expirationTime = 0;
2013-02-26 10:09:41 +01:00
}
// Send cookie with the new expiration date to the browser
session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
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']);
2017-03-25 19:41:01 +01:00
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;
}
2013-02-26 10:09:41 +01:00
}
header('Location: ?');
exit;
} else {
$loginManager->handleFailedLogin($_SERVER);
$redir = '&username='. urlencode($_POST['login']);
if (isset($_GET['post'])) {
$redir .= '&post=' . urlencode($_GET['post']);
2017-03-25 19:41:01 +01:00
foreach (array('description', 'source', 'title', 'tags') as $param) {
if (!empty($_GET[$param])) {
$redir .= '&' . $param . '=' . urlencode($_GET[$param]);
}
}
}
// Redirect to login screen.
echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
2013-02-26 10:09:41 +01:00
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.
}
2013-02-26 10:09:41 +01:00
/**
* 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
* @param LoginManager $loginManager LoginManager instance
*/
function showDailyRSS($conf, $loginManager)
{
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') && !$loginManager->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'),
$loginManager->isLoggedIn(),
$conf->get('privacy.hide_public_links')
);
2013-02-26 10:09:41 +01:00
/* Some Shaarlies may have very few links, so we need to look
back in time until we have enough days ($nb_of_days).
2013-02-26 10:09:41 +01:00
*/
$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?
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 => $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.
2013-02-26 10:09:41 +01:00
// We pre-format some fields for proper output.
foreach ($links as &$link) {
$link['formatedDescription'] = format_description($link['description']);
$link['timestamp'] = $link['created']->getTimestamp();
if (is_note($link['url'])) {
$link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
}
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));
$tpl->assign('index_url', $pageaddr);
$html = $tpl->draw('dailyrss', 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 instance.
* @param LoginManager $loginManager Login Manager instance
*/
function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
2013-02-26 10:09:41 +01:00
{
$day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
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 && count($days)) {
// no links for day, but at least one day with links
$i = count($days) - 1;
$day = $days[$i];
2013-02-26 10:09:41 +01:00
}
$previousday = '';
$nextday = '';
2013-02-26 10:09:41 +01:00
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();
}
2013-02-26 10:09:41 +01:00
// We pre-format some fields for proper output.
foreach ($linksToDisplay as $key => $link) {
$taglist = explode(' ', $link['tags']);
2013-03-01 17:09:52 +01:00
uasort($taglist, 'strcasecmp');
$linksToDisplay[$key]['taglist']=$taglist;
$linksToDisplay[$key]['formatedDescription'] = format_description($link['description']);
$linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
2013-02-26 10:09:41 +01:00
}
$dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
$data = array(
'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
'linksToDisplay' => $linksToDisplay,
'day' => $dayDate->getTimestamp(),
'dayDate' => $dayDate,
'previousday' => $previousday,
'nextday' => $nextday,
);
/* Hook is called before column construction so that plugins don't have
to deal with columns. */
$pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
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
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 ($data['linksToDisplay'] as $key => $link) {
2013-02-26 10:09:41 +01:00
// 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.
}
2013-02-26 10:09:41 +01:00
// 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;
2013-02-26 10:09:41 +01:00
}
$data['cols'] = $columns;
foreach ($data as $key => $value) {
$pageBuilder->assign($key, $value);
}
$pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
$pageBuilder->renderPage('daily');
2013-02-26 10:09:41 +01:00
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, $loginManager)
{
buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
$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
* @param SessionManager $sessionManager SessionManager instance
* @param LoginManager $loginManager LoginManager instance
*/
function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
2013-02-26 10:09:41 +01:00
{
$updater = new Updater(
read_updates_file($conf->get('resource.updates')),
$LINKSDB,
$conf,
$loginManager->isLoggedIn(),
$_SESSION
);
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, $_SESSION, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
2016-05-11 00:05:22 +02:00
$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, $loginManager->isLoggedIn());
if (// if the user isn't logged in
!$loginManager->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' => $loginManager->isLoggedIn()
)
);
$PAGE->assign('plugins_' . $name, $plugin_data);
}
2013-02-26 10:09:41 +01:00
// -------- 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->assign('user_can_login', $loginManager->canLogin($_SERVER));
$PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
2013-02-26 10:09:41 +01:00
$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'));
$sessionManager->logout();
setcookie(LoginManager::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH);
2013-02-26 10:09:41 +01:00
header('Location: ?');
exit;
}
// -------- Picture wall
if ($targetPage == Router::$PAGE_PICWALL) {
$PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
if (! $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) === Thumbnailer::MODE_NONE) {
$PAGE->assign('linksToDisplay', []);