aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
authorArthurHoaro <arthur@hoa.ro>2016-06-09 20:04:02 +0200
committerArthurHoaro <arthur@hoa.ro>2016-06-11 09:30:56 +0200
commit278d9ee2836df7d805845077f26f8cecd16f0f4f (patch)
tree9155cab8890074e83b54efaa649bfa74885d3ab5 /index.php
parent7f179985b497053c59338667fe49c390aa626ab7 (diff)
downloadShaarli-278d9ee2836df7d805845077f26f8cecd16f0f4f.tar.gz
Shaarli-278d9ee2836df7d805845077f26f8cecd16f0f4f.tar.zst
Shaarli-278d9ee2836df7d805845077f26f8cecd16f0f4f.zip
ConfigManager no longer uses singleton pattern
Diffstat (limited to 'index.php')
-rw-r--r--index.php317
1 files changed, 190 insertions, 127 deletions
diff --git a/index.php b/index.php
index ac4a680d..d061f912 100644
--- a/index.php
+++ b/index.php
@@ -48,6 +48,8 @@ error_reporting(E_ALL^E_WARNING);
48require_once 'application/ApplicationUtils.php'; 48require_once 'application/ApplicationUtils.php';
49require_once 'application/Cache.php'; 49require_once 'application/Cache.php';
50require_once 'application/CachedPage.php'; 50require_once 'application/CachedPage.php';
51require_once 'application/config/ConfigManager.php';
52require_once 'application/config/ConfigPlugin.php';
51require_once 'application/FeedBuilder.php'; 53require_once 'application/FeedBuilder.php';
52require_once 'application/FileUtils.php'; 54require_once 'application/FileUtils.php';
53require_once 'application/HttpUtils.php'; 55require_once 'application/HttpUtils.php';
@@ -59,8 +61,6 @@ require_once 'application/PageBuilder.php';
59require_once 'application/TimeZone.php'; 61require_once 'application/TimeZone.php';
60require_once 'application/Url.php'; 62require_once 'application/Url.php';
61require_once 'application/Utils.php'; 63require_once 'application/Utils.php';
62require_once 'application/config/ConfigManager.php';
63require_once 'application/config/ConfigPlugin.php';
64require_once 'application/PluginManager.php'; 64require_once 'application/PluginManager.php';
65require_once 'application/Router.php'; 65require_once 'application/Router.php';
66require_once 'application/Updater.php'; 66require_once 'application/Updater.php';
@@ -105,13 +105,13 @@ if (isset($_COOKIE['shaarli']) && !is_session_id_valid($_COOKIE['shaarli'])) {
105 $_COOKIE['shaarli'] = session_id(); 105 $_COOKIE['shaarli'] = session_id();
106} 106}
107 107
108$conf = ConfigManager::getInstance(); 108$conf = new ConfigManager();
109$conf->setEmpty('general.timezone', date_default_timezone_get()); 109$conf->setEmpty('general.timezone', date_default_timezone_get());
110$conf->setEmpty('general.title', 'Shared links on '. escape(index_url($_SERVER))); 110$conf->setEmpty('general.title', 'Shared links on '. escape(index_url($_SERVER)));
111RainTPL::$tpl_dir = $conf->get('path.raintpl_tpl'); // template directory 111RainTPL::$tpl_dir = $conf->get('path.raintpl_tpl'); // template directory
112RainTPL::$cache_dir = $conf->get('path.raintpl_tmp'); // cache directory 112RainTPL::$cache_dir = $conf->get('path.raintpl_tmp'); // cache directory
113 113
114$pluginManager = PluginManager::getInstance(); 114$pluginManager = new PluginManager($conf);
115$pluginManager->load($conf->get('general.enabled_plugins')); 115$pluginManager->load($conf->get('general.enabled_plugins'));
116 116
117date_default_timezone_set($conf->get('general.timezone', 'UTC')); 117date_default_timezone_set($conf->get('general.timezone', 'UTC'));
@@ -133,9 +133,9 @@ header("Cache-Control: no-store, no-cache, must-revalidate");
133header("Cache-Control: post-check=0, pre-check=0", false); 133header("Cache-Control: post-check=0, pre-check=0", false);
134header("Pragma: no-cache"); 134header("Pragma: no-cache");
135 135
136if (! is_file($conf->getConfigFile())) { 136if (! is_file($conf->getConfigFileExt())) {
137 // Ensure Shaarli has proper access to its resources 137 // Ensure Shaarli has proper access to its resources
138 $errors = ApplicationUtils::checkResourcePermissions(); 138 $errors = ApplicationUtils::checkResourcePermissions($conf);
139 139
140 if ($errors != array()) { 140 if ($errors != array()) {
141 $message = '<p>Insufficient permissions:</p><ul>'; 141 $message = '<p>Insufficient permissions:</p><ul>';
@@ -151,7 +151,7 @@ if (! is_file($conf->getConfigFile())) {
151 } 151 }
152 152
153 // Display the installation form if no existing config is found 153 // Display the installation form if no existing config is found
154 install(); 154 install($conf);
155} 155}
156 156
157// a token depending of deployment salt, user password, and the current ip 157// a token depending of deployment salt, user password, and the current ip
@@ -163,13 +163,15 @@ if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
163} 163}
164header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling. 164header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
165 165
166//================================================================================================== 166/**
167// Checking session state (i.e. is the user still logged in) 167 * Checking session state (i.e. is the user still logged in)
168//================================================================================================== 168 *
169 169 * @param ConfigManager $conf The configuration manager.
170function setup_login_state() { 170 *
171 $conf = ConfigManager::getInstance(); 171 * @return bool: true if the user is logged in, false otherwise.
172 172 */
173function setup_login_state($conf)
174{
173 if ($conf->get('extras.open_shaarli')) { 175 if ($conf->get('extras.open_shaarli')) {
174 return true; 176 return true;
175 } 177 }
@@ -183,7 +185,7 @@ function setup_login_state() {
183 $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN && 185 $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN &&
184 !$loginFailure) 186 !$loginFailure)
185 { 187 {
186 fillSessionInfo(); 188 fillSessionInfo($conf);
187 $userIsLoggedIn = true; 189 $userIsLoggedIn = true;
188 } 190 }
189 // If session does not exist on server side, or IP address has changed, or session has expired, logout. 191 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
@@ -207,14 +209,16 @@ function setup_login_state() {
207 209
208 return $userIsLoggedIn; 210 return $userIsLoggedIn;
209} 211}
210$userIsLoggedIn = setup_login_state(); 212$userIsLoggedIn = setup_login_state($conf);
211 213
212// ------------------------------------------------------------------------------------------ 214/**
213// PubSubHubbub protocol support (if enabled) [UNTESTED] 215 * PubSubHubbub protocol support (if enabled) [UNTESTED]
214// (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ ) 216 * (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
215function pubsubhub() 217 *
218 * @param ConfigManager $conf Configuration Manager instance.
219 */
220function pubsubhub($conf)
216{ 221{
217 $conf = ConfigManager::getInstance();
218 $pshUrl = $conf->get('config.PUBSUBHUB_URL'); 222 $pshUrl = $conf->get('config.PUBSUBHUB_URL');
219 if (!empty($pshUrl)) 223 if (!empty($pshUrl))
220 { 224 {
@@ -241,27 +245,39 @@ function allIPs()
241 return $ip; 245 return $ip;
242} 246}
243 247
244function fillSessionInfo() { 248/**
245 $conf = ConfigManager::getInstance(); 249 * Load user session.
250 *
251 * @param ConfigManager $conf Configuration Manager instance.
252 */
253function fillSessionInfo($conf)
254{
246 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid) 255 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
247 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked. 256 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
248 $_SESSION['username']= $conf->get('credentials.login'); 257 $_SESSION['username']= $conf->get('credentials.login');
249 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration. 258 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
250} 259}
251 260
252// Check that user/password is correct. 261/**
253function check_auth($login,$password) 262 * Check that user/password is correct.
263 *
264 * @param string $login Username
265 * @param string $password User password
266 * @param ConfigManager $conf Configuration Manager instance.
267 *
268 * @return bool: authentication successful or not.
269 */
270function check_auth($login, $password, $conf)
254{ 271{
255 $conf = ConfigManager::getInstance();
256 $hash = sha1($password . $login . $conf->get('credentials.salt')); 272 $hash = sha1($password . $login . $conf->get('credentials.salt'));
257 if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash')) 273 if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash'))
258 { // Login/password is correct. 274 { // Login/password is correct.
259 fillSessionInfo(); 275 fillSessionInfo($conf);
260 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login successful'); 276 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
261 return True; 277 return true;
262 } 278 }
263 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login); 279 logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
264 return False; 280 return false;
265} 281}
266 282
267// Returns true if the user is logged in. 283// Returns true if the user is logged in.
@@ -294,10 +310,13 @@ if (!is_file($conf->get('path.ban_file', 'data/ipbans.php'))) {
294 ); 310 );
295} 311}
296include $conf->get('path.ban_file', 'data/ipbans.php'); 312include $conf->get('path.ban_file', 'data/ipbans.php');
297// Signal a failed login. Will ban the IP if too many failures: 313/**
298function ban_loginFailed() 314 * Signal a failed login. Will ban the IP if too many failures:
315 *
316 * @param ConfigManager $conf Configuration Manager instance.
317 */
318function ban_loginFailed($conf)
299{ 319{
300 $conf = ConfigManager::getInstance();
301 $ip = $_SERVER['REMOTE_ADDR']; 320 $ip = $_SERVER['REMOTE_ADDR'];
302 $gb = $GLOBALS['IPBANS']; 321 $gb = $GLOBALS['IPBANS'];
303 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0; 322 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
@@ -314,10 +333,13 @@ function ban_loginFailed()
314 ); 333 );
315} 334}
316 335
317// Signals a successful login. Resets failed login counter. 336/**
318function ban_loginOk() 337 * Signals a successful login. Resets failed login counter.
338 *
339 * @param ConfigManager $conf Configuration Manager instance.
340 */
341function ban_loginOk($conf)
319{ 342{
320 $conf = ConfigManager::getInstance();
321 $ip = $_SERVER['REMOTE_ADDR']; 343 $ip = $_SERVER['REMOTE_ADDR'];
322 $gb = $GLOBALS['IPBANS']; 344 $gb = $GLOBALS['IPBANS'];
323 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); 345 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
@@ -328,10 +350,15 @@ function ban_loginOk()
328 ); 350 );
329} 351}
330 352
331// Checks if the user CAN login. If 'true', the user can try to login. 353/**
332function ban_canLogin() 354 * Checks if the user CAN login. If 'true', the user can try to login.
355 *
356 * @param ConfigManager $conf Configuration Manager instance.
357 *
358 * @return bool: true if the user is allowed to login.
359 */
360function ban_canLogin($conf)
333{ 361{
334 $conf = ConfigManager::getInstance();
335 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS']; 362 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
336 if (isset($gb['BANS'][$ip])) 363 if (isset($gb['BANS'][$ip]))
337 { 364 {
@@ -355,10 +382,12 @@ function ban_canLogin()
355// Process login form: Check if login/password is correct. 382// Process login form: Check if login/password is correct.
356if (isset($_POST['login'])) 383if (isset($_POST['login']))
357{ 384{
358 if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.'); 385 if (!ban_canLogin($conf)) die('I said: NO. You are banned for the moment. Go away.');
359 if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password']))) 386 if (isset($_POST['password'])
360 { // Login/password is OK. 387 && tokenOk($_POST['token'])
361 ban_loginOk(); 388 && (check_auth($_POST['login'], $_POST['password'], $conf))
389 ) { // Login/password is OK.
390 ban_loginOk($conf);
362 // If user wants to keep the session cookie even after the browser closes: 391 // If user wants to keep the session cookie even after the browser closes:
363 if (!empty($_POST['longlastingsession'])) 392 if (!empty($_POST['longlastingsession']))
364 { 393 {
@@ -406,7 +435,7 @@ if (isset($_POST['login']))
406 } 435 }
407 else 436 else
408 { 437 {
409 ban_loginFailed(); 438 ban_loginFailed($conf);
410 $redir = '&username='. $_POST['login']; 439 $redir = '&username='. $_POST['login'];
411 if (isset($_GET['post'])) { 440 if (isset($_GET['post'])) {
412 $redir .= '&post=' . urlencode($_GET['post']); 441 $redir .= '&post=' . urlencode($_GET['post']);
@@ -454,10 +483,15 @@ function getMaxFileSize()
454// Token should be used in any form which acts on data (create,update,delete,import...). 483// Token should be used in any form which acts on data (create,update,delete,import...).
455if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session. 484if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
456 485
457// Returns a token. 486/**
458function getToken() 487 * Returns a token.
488 *
489 * @param ConfigManager $conf Configuration Manager instance.
490 *
491 * @return string token.
492 */
493function getToken($conf)
459{ 494{
460 $conf = ConfigManager::getInstance();
461 $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string. 495 $rnd = sha1(uniqid('', true) .'_'. mt_rand() . $conf->get('credentials.salt')); // We generate a random string.
462 $_SESSION['tokens'][$rnd]=1; // Store it on the server side. 496 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
463 return $rnd; 497 return $rnd;
@@ -475,12 +509,14 @@ function tokenOk($token)
475 return false; // Wrong token, or already used. 509 return false; // Wrong token, or already used.
476} 510}
477 511
478// ------------------------------------------------------------------------------------------ 512/**
479// Daily RSS feed: 1 RSS entry per day giving all the links on that day. 513 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
480// Gives the last 7 days (which have links). 514 * Gives the last 7 days (which have links).
481// This RSS feed cannot be filtered. 515 * This RSS feed cannot be filtered.
482function showDailyRSS() { 516 *
483 $conf = ConfigManager::getInstance(); 517 * @param ConfigManager $conf Configuration Manager instance.
518 */
519function showDailyRSS($conf) {
484 // Cache system 520 // Cache system
485 $query = $_SERVER['QUERY_STRING']; 521 $query = $_SERVER['QUERY_STRING'];
486 $cache = new CachedPage( 522 $cache = new CachedPage(
@@ -555,7 +591,7 @@ function showDailyRSS() {
555 foreach ($linkdates as $linkdate) { 591 foreach ($linkdates as $linkdate) {
556 $l = $LINKSDB[$linkdate]; 592 $l = $LINKSDB[$linkdate];
557 $l['formatedDescription'] = format_description($l['description'], $conf->get('extras.redirector')); 593 $l['formatedDescription'] = format_description($l['description'], $conf->get('extras.redirector'));
558 $l['thumbnail'] = thumbnail($l['url']); 594 $l['thumbnail'] = thumbnail($conf, $l['url']);
559 $l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']); 595 $l_date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $l['linkdate']);
560 $l['timestamp'] = $l_date->getTimestamp(); 596 $l['timestamp'] = $l_date->getTimestamp();
561 if (startsWith($l['url'], '?')) { 597 if (startsWith($l['url'], '?')) {
@@ -586,12 +622,13 @@ function showDailyRSS() {
586/** 622/**
587 * Show the 'Daily' page. 623 * Show the 'Daily' page.
588 * 624 *
589 * @param PageBuilder $pageBuilder Template engine wrapper. 625 * @param PageBuilder $pageBuilder Template engine wrapper.
590 * @param LinkDB $LINKSDB LinkDB instance. 626 * @param LinkDB $LINKSDB LinkDB instance.
627 * @param ConfigManager $conf Configuration Manager instance.
628 * @param PluginManager $pluginManager Plugin Manager instane.
591 */ 629 */
592function showDaily($pageBuilder, $LINKSDB) 630function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager)
593{ 631{
594 $conf = ConfigManager::getInstance();
595 $day=date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD. 632 $day=date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
596 if (isset($_GET['day'])) $day=$_GET['day']; 633 if (isset($_GET['day'])) $day=$_GET['day'];
597 634
@@ -621,7 +658,7 @@ function showDaily($pageBuilder, $LINKSDB)
621 uasort($taglist, 'strcasecmp'); 658 uasort($taglist, 'strcasecmp');
622 $linksToDisplay[$key]['taglist']=$taglist; 659 $linksToDisplay[$key]['taglist']=$taglist;
623 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('extras.redirector')); 660 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('extras.redirector'));
624 $linksToDisplay[$key]['thumbnail'] = thumbnail($link['url']); 661 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
625 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']); 662 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
626 $linksToDisplay[$key]['timestamp'] = $date->getTimestamp(); 663 $linksToDisplay[$key]['timestamp'] = $date->getTimestamp();
627 } 664 }
@@ -656,7 +693,7 @@ function showDaily($pageBuilder, $LINKSDB)
656 'previousday' => $previousday, 693 'previousday' => $previousday,
657 'nextday' => $nextday, 694 'nextday' => $nextday,
658 ); 695 );
659 $pluginManager = PluginManager::getInstance(); 696
660 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn())); 697 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn()));
661 698
662 foreach ($data as $key => $value) { 699 foreach ($data as $key => $value) {
@@ -667,18 +704,27 @@ function showDaily($pageBuilder, $LINKSDB)
667 exit; 704 exit;
668} 705}
669 706
670// Renders the linklist 707/**
671function showLinkList($PAGE, $LINKSDB) { 708 * Renders the linklist
672 buildLinkList($PAGE,$LINKSDB); // Compute list of links to display 709 *
710 * @param pageBuilder $PAGE pageBuilder instance.
711 * @param LinkDB $LINKSDB LinkDB instance.
712 * @param ConfigManager $conf Configuration Manager instance.
713 * @param PluginManager $pluginManager Plugin Manager instance.
714 */
715function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) {
716 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager); // Compute list of links to display
673 $PAGE->renderPage('linklist'); 717 $PAGE->renderPage('linklist');
674} 718}
675 719
676 720/**
677// ------------------------------------------------------------------------------------------ 721 * Render HTML page (according to URL parameters and user rights)
678// Render HTML page (according to URL parameters and user rights) 722 *
679function renderPage() 723 * @param ConfigManager $conf Configuration Manager instance.
724 * @param PluginManager $pluginManager Plugin Manager instance,
725 */
726function renderPage($conf, $pluginManager)
680{ 727{
681 $conf = ConfigManager::getInstance();
682 $LINKSDB = new LinkDB( 728 $LINKSDB = new LinkDB(
683 $conf->get('path.datastore'), 729 $conf->get('path.datastore'),
684 isLoggedIn(), 730 isLoggedIn(),
@@ -690,6 +736,7 @@ function renderPage()
690 $updater = new Updater( 736 $updater = new Updater(
691 read_updates_file($conf->get('path.updates')), 737 read_updates_file($conf->get('path.updates')),
692 $LINKSDB, 738 $LINKSDB,
739 $conf,
693 isLoggedIn() 740 isLoggedIn()
694 ); 741 );
695 try { 742 try {
@@ -705,7 +752,7 @@ function renderPage()
705 die($e->getMessage()); 752 die($e->getMessage());
706 } 753 }
707 754
708 $PAGE = new PageBuilder(); 755 $PAGE = new PageBuilder($conf);
709 $PAGE->assign('linkcount', count($LINKSDB)); 756 $PAGE->assign('linkcount', count($LINKSDB));
710 $PAGE->assign('privateLinkcount', count_private($LINKSDB)); 757 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
711 758
@@ -720,7 +767,7 @@ function renderPage()
720 'header', 767 'header',
721 'footer', 768 'footer',
722 ); 769 );
723 $pluginManager = PluginManager::getInstance(); 770
724 foreach($common_hooks as $name) { 771 foreach($common_hooks as $name) {
725 $plugin_data = array(); 772 $plugin_data = array();
726 $pluginManager->executeHooks('render_' . $name, $plugin_data, 773 $pluginManager->executeHooks('render_' . $name, $plugin_data,
@@ -736,7 +783,7 @@ function renderPage()
736 if ($targetPage == Router::$PAGE_LOGIN) 783 if ($targetPage == Router::$PAGE_LOGIN)
737 { 784 {
738 if ($conf->get('extras.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli 785 if ($conf->get('extras.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
739 $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful. 786 $token=''; if (ban_canLogin($conf)) $token=getToken($conf); // Do not waste token generation if not useful.
740 $PAGE->assign('token',$token); 787 $PAGE->assign('token',$token);
741 if (isset($_GET['username'])) { 788 if (isset($_GET['username'])) {
742 $PAGE->assign('username', escape($_GET['username'])); 789 $PAGE->assign('username', escape($_GET['username']));
@@ -765,7 +812,7 @@ function renderPage()
765 foreach($links as $link) 812 foreach($links as $link)
766 { 813 {
767 $permalink='?'.escape(smallhash($link['linkdate'])); 814 $permalink='?'.escape(smallhash($link['linkdate']));
768 $thumb=lazyThumbnail($link['url'],$permalink); 815 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
769 if ($thumb!='') // Only output links which have a thumbnail. 816 if ($thumb!='') // Only output links which have a thumbnail.
770 { 817 {
771 $link['thumbnail']=$thumb; // Thumbnail HTML code. 818 $link['thumbnail']=$thumb; // Thumbnail HTML code.
@@ -837,7 +884,7 @@ function renderPage()
837 884
838 // Daily page. 885 // Daily page.
839 if ($targetPage == Router::$PAGE_DAILY) { 886 if ($targetPage == Router::$PAGE_DAILY) {
840 showDaily($PAGE, $LINKSDB); 887 showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
841 } 888 }
842 889
843 // ATOM and RSS feed. 890 // ATOM and RSS feed.
@@ -870,7 +917,6 @@ function renderPage()
870 $data = $feedGenerator->buildData(); 917 $data = $feedGenerator->buildData();
871 918
872 // Process plugin hook. 919 // Process plugin hook.
873 $pluginManager = PluginManager::getInstance();
874 $pluginManager->executeHooks('render_feed', $data, array( 920 $pluginManager->executeHooks('render_feed', $data, array(
875 'loggedin' => isLoggedIn(), 921 'loggedin' => isLoggedIn(),
876 'target' => $targetPage, 922 'target' => $targetPage,
@@ -996,7 +1042,7 @@ function renderPage()
996 exit; 1042 exit;
997 } 1043 }
998 1044
999 showLinkList($PAGE, $LINKSDB); 1045 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1000 if (isset($_GET['edit_link'])) { 1046 if (isset($_GET['edit_link'])) {
1001 header('Location: ?do=login&edit_link='. escape($_GET['edit_link'])); 1047 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
1002 exit; 1048 exit;
@@ -1059,7 +1105,7 @@ function renderPage()
1059 } 1105 }
1060 else // show the change password form. 1106 else // show the change password form.
1061 { 1107 {
1062 $PAGE->assign('token',getToken()); 1108 $PAGE->assign('token',getToken($conf));
1063 $PAGE->renderPage('changepassword'); 1109 $PAGE->renderPage('changepassword');
1064 exit; 1110 exit;
1065 } 1111 }
@@ -1106,7 +1152,7 @@ function renderPage()
1106 } 1152 }
1107 else // Show the configuration form. 1153 else // Show the configuration form.
1108 { 1154 {
1109 $PAGE->assign('token',getToken()); 1155 $PAGE->assign('token',getToken($conf));
1110 $PAGE->assign('title', $conf->get('general.title')); 1156 $PAGE->assign('title', $conf->get('general.title'));
1111 $PAGE->assign('redirector', $conf->get('extras.redirector')); 1157 $PAGE->assign('redirector', $conf->get('extras.redirector'));
1112 list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('general.timezone')); 1158 list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('general.timezone'));
@@ -1125,7 +1171,7 @@ function renderPage()
1125 if ($targetPage == Router::$PAGE_CHANGETAG) 1171 if ($targetPage == Router::$PAGE_CHANGETAG)
1126 { 1172 {
1127 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) { 1173 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1128 $PAGE->assign('token', getToken()); 1174 $PAGE->assign('token', getToken($conf));
1129 $PAGE->assign('tags', $LINKSDB->allTags()); 1175 $PAGE->assign('tags', $LINKSDB->allTags());
1130 $PAGE->renderPage('changetag'); 1176 $PAGE->renderPage('changetag');
1131 exit; 1177 exit;
@@ -1216,7 +1262,7 @@ function renderPage()
1216 1262
1217 $LINKSDB[$linkdate] = $link; 1263 $LINKSDB[$linkdate] = $link;
1218 $LINKSDB->savedb($conf->get('path.page_cache')); 1264 $LINKSDB->savedb($conf->get('path.page_cache'));
1219 pubsubhub(); 1265 pubsubhub($conf);
1220 1266
1221 // If we are called from the bookmarklet, we must close the popup: 1267 // If we are called from the bookmarklet, we must close the popup:
1222 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { 1268 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
@@ -1300,7 +1346,7 @@ function renderPage()
1300 $data = array( 1346 $data = array(
1301 'link' => $link, 1347 'link' => $link,
1302 'link_is_new' => false, 1348 'link_is_new' => false,
1303 'token' => getToken(), 1349 'token' => getToken($conf),
1304 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), 1350 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1305 'tags' => $LINKSDB->allTags(), 1351 'tags' => $LINKSDB->allTags(),
1306 ); 1352 );
@@ -1367,7 +1413,7 @@ function renderPage()
1367 $data = array( 1413 $data = array(
1368 'link' => $link, 1414 'link' => $link,
1369 'link_is_new' => $link_is_new, 1415 'link_is_new' => $link_is_new,
1370 'token' => getToken(), // XSRF protection. 1416 'token' => getToken($conf), // XSRF protection.
1371 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), 1417 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1372 'source' => (isset($_GET['source']) ? $_GET['source'] : ''), 1418 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1373 'tags' => $LINKSDB->allTags(), 1419 'tags' => $LINKSDB->allTags(),
@@ -1445,7 +1491,7 @@ function renderPage()
1445 // -------- Show upload/import dialog: 1491 // -------- Show upload/import dialog:
1446 if ($targetPage == Router::$PAGE_IMPORT) 1492 if ($targetPage == Router::$PAGE_IMPORT)
1447 { 1493 {
1448 $PAGE->assign('token',getToken()); 1494 $PAGE->assign('token',getToken($conf));
1449 $PAGE->assign('maxfilesize',getMaxFileSize()); 1495 $PAGE->assign('maxfilesize',getMaxFileSize());
1450 $PAGE->renderPage('import'); 1496 $PAGE->renderPage('import');
1451 exit; 1497 exit;
@@ -1500,16 +1546,19 @@ function renderPage()
1500 } 1546 }
1501 1547
1502 // -------- Otherwise, simply display search form and links: 1548 // -------- Otherwise, simply display search form and links:
1503 showLinkList($PAGE, $LINKSDB); 1549 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1504 exit; 1550 exit;
1505} 1551}
1506 1552
1507// ----------------------------------------------------------------------------------------------- 1553/**
1508// Process the import file form. 1554 * Process the import file form.
1509function importFile($LINKSDB) 1555 *
1556 * @param LinkDB $LINKSDB Loaded LinkDB instance.
1557 * @param ConfigManager $conf Configuration Manager instance.
1558 */
1559function importFile($LINKSDB, $conf)
1510{ 1560{
1511 if (!isLoggedIn()) { die('Not allowed.'); } 1561 if (!isLoggedIn()) { die('Not allowed.'); }
1512 $conf = ConfigManager::getInstance();
1513 1562
1514 $filename=$_FILES['filetoupload']['name']; 1563 $filename=$_FILES['filetoupload']['name'];
1515 $filesize=$_FILES['filetoupload']['size']; 1564 $filesize=$_FILES['filetoupload']['size'];
@@ -1594,12 +1643,13 @@ function importFile($LINKSDB)
1594 * Template for the list of links (<div id="linklist">) 1643 * Template for the list of links (<div id="linklist">)
1595 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html' 1644 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1596 * 1645 *
1597 * @param pageBuilder $PAGE pageBuilder instance. 1646 * @param pageBuilder $PAGE pageBuilder instance.
1598 * @param LinkDB $LINKSDB LinkDB instance. 1647 * @param LinkDB $LINKSDB LinkDB instance.
1648 * @param ConfigManager $conf Configuration Manager instance.
1649 * @param PluginManager $pluginManager Plugin Manager instance.
1599 */ 1650 */
1600function buildLinkList($PAGE,$LINKSDB) 1651function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
1601{ 1652{
1602 $conf = ConfigManager::getInstance();
1603 // Used in templates 1653 // Used in templates
1604 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : ''; 1654 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
1605 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : ''; 1655 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
@@ -1674,7 +1724,7 @@ function buildLinkList($PAGE,$LINKSDB)
1674 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl; 1724 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1675 } 1725 }
1676 1726
1677 $token = isLoggedIn() ? getToken() : ''; 1727 $token = isLoggedIn() ? getToken($conf) : '';
1678 1728
1679 // Fill all template fields. 1729 // Fill all template fields.
1680 $data = array( 1730 $data = array(
@@ -1695,7 +1745,6 @@ function buildLinkList($PAGE,$LINKSDB)
1695 $data['pagetitle'] = $conf->get('pagetitle'); 1745 $data['pagetitle'] = $conf->get('pagetitle');
1696 } 1746 }
1697 1747
1698 $pluginManager = PluginManager::getInstance();
1699 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn())); 1748 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
1700 1749
1701 foreach ($data as $key => $value) { 1750 foreach ($data as $key => $value) {
@@ -1705,18 +1754,25 @@ function buildLinkList($PAGE,$LINKSDB)
1705 return; 1754 return;
1706} 1755}
1707 1756
1708// Compute the thumbnail for a link. 1757/**
1709// 1758 * Compute the thumbnail for a link.
1710// With a link to the original URL. 1759 *
1711// Understands various services (youtube.com...) 1760 * With a link to the original URL.
1712// Input: $url = URL for which the thumbnail must be found. 1761 * Understands various services (youtube.com...)
1713// $href = if provided, this URL will be followed instead of $url 1762 * Input: $url = URL for which the thumbnail must be found.
1714// Returns an associative array with thumbnail attributes (src,href,width,height,style,alt) 1763 * $href = if provided, this URL will be followed instead of $url
1715// Some of them may be missing. 1764 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1716// Return an empty array if no thumbnail available. 1765 * Some of them may be missing.
1717function computeThumbnail($url,$href=false) 1766 * Return an empty array if no thumbnail available.
1767 *
1768 * @param ConfigManager $conf Configuration Manager instance.
1769 * @param string $url
1770 * @param string|bool $href
1771 *
1772 * @return array
1773 */
1774function computeThumbnail($conf, $url, $href = false)
1718{ 1775{
1719 $conf = ConfigManager::getInstance();
1720 if (!$conf->get('general.enable_thumbnails')) return array(); 1776 if (!$conf->get('general.enable_thumbnails')) return array();
1721 if ($href==false) $href=$url; 1777 if ($href==false) $href=$url;
1722 1778
@@ -1836,7 +1892,9 @@ function computeThumbnail($url,$href=false)
1836// Returns '' if no thumbnail available. 1892// Returns '' if no thumbnail available.
1837function thumbnail($url,$href=false) 1893function thumbnail($url,$href=false)
1838{ 1894{
1839 $t = computeThumbnail($url,$href); 1895 // FIXME!
1896 global $conf;
1897 $t = computeThumbnail($conf, $url,$href);
1840 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL. 1898 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1841 1899
1842 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"'; 1900 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
@@ -1854,9 +1912,11 @@ function thumbnail($url,$href=false)
1854// Input: $url = URL for which the thumbnail must be found. 1912// Input: $url = URL for which the thumbnail must be found.
1855// $href = if provided, this URL will be followed instead of $url 1913// $href = if provided, this URL will be followed instead of $url
1856// Returns '' if no thumbnail available. 1914// Returns '' if no thumbnail available.
1857function lazyThumbnail($url,$href=false) 1915function lazyThumbnail($conf, $url,$href=false)
1858{ 1916{
1859 $t = computeThumbnail($url,$href); 1917 // FIXME!
1918 global $conf;
1919 $t = computeThumbnail($conf, $url,$href);
1860 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL. 1920 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1861 1921
1862 $html='<a href="'.escape($t['href']).'">'; 1922 $html='<a href="'.escape($t['href']).'">';
@@ -1882,10 +1942,13 @@ function lazyThumbnail($url,$href=false)
1882} 1942}
1883 1943
1884 1944
1885// ----------------------------------------------------------------------------------------------- 1945/**
1886// Installation 1946 * Installation
1887// This function should NEVER be called if the file data/config.php exists. 1947 * This function should NEVER be called if the file data/config.php exists.
1888function install() 1948 *
1949 * @param ConfigManager $conf Configuration Manager instance.
1950 */
1951function install($conf)
1889{ 1952{
1890 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work. 1953 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1891 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705); 1954 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
@@ -1916,7 +1979,6 @@ function install()
1916 1979
1917 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) 1980 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1918 { 1981 {
1919 $conf = ConfigManager::getInstance();
1920 $tz = 'UTC'; 1982 $tz = 'UTC';
1921 if (!empty($_POST['continent']) && !empty($_POST['city']) 1983 if (!empty($_POST['continent']) && !empty($_POST['city'])
1922 && isTimeZoneValid($_POST['continent'], $_POST['city']) 1984 && isTimeZoneValid($_POST['continent'], $_POST['city'])
@@ -1960,25 +2022,27 @@ function install()
1960 $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>'; 2022 $timezone_html = '<tr><td><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
1961 } 2023 }
1962 2024
1963 $PAGE = new PageBuilder(); 2025 $PAGE = new PageBuilder($conf);
1964 $PAGE->assign('timezone_html',$timezone_html); 2026 $PAGE->assign('timezone_html',$timezone_html);
1965 $PAGE->assign('timezone_js',$timezone_js); 2027 $PAGE->assign('timezone_js',$timezone_js);
1966 $PAGE->renderPage('install'); 2028 $PAGE->renderPage('install');
1967 exit; 2029 exit;
1968} 2030}
1969 2031
1970/* Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL, 2032/**
1971 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation. 2033 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1972 The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail. 2034 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1973 This function is called by passing the URL: 2035 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1974 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL] 2036 * This function is called by passing the URL:
1975 [URL] is the URL of the link (e.g. a flickr page) 2037 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1976 [HMAC] is the signature for the [URL] (so that these URL cannot be forged). 2038 * [URL] is the URL of the link (e.g. a flickr page)
1977 The function below will fetch the image from the webservice and store it in the cache. 2039 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1978*/ 2040 * The function below will fetch the image from the webservice and store it in the cache.
1979function genThumbnail() 2041 *
2042 * @param ConfigManager $conf Configuration Manager instance,
2043 */
2044function genThumbnail($conf)
1980{ 2045{
1981 $conf = ConfigManager::getInstance();
1982 // Make sure the parameters in the URL were generated by us. 2046 // Make sure the parameters in the URL were generated by us.
1983 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt')); 2047 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
1984 if ($sign!=$_GET['hmac']) die('Naughty boy!'); 2048 if ($sign!=$_GET['hmac']) die('Naughty boy!');
@@ -2190,10 +2254,9 @@ function resizeImage($filepath)
2190 return true; 2254 return true;
2191} 2255}
2192 2256
2193if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database. 2257if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database.
2194if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS(); exit; } 2258if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
2195if (!isset($_SESSION['LINKS_PER_PAGE'])) { 2259if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2196 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20); 2260 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2197} 2261}
2198renderPage(); 2262renderPage($conf, $pluginManager);
2199?>