X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=index.php;h=8a0be951b1e6adf518c87cff42ffd8231f24729c;hb=9e425954817621711a528bb3bd2972692a2a528a;hp=d061f9124687864dd8c36d172184aecef42df77e;hpb=278d9ee2836df7d805845077f26f8cecd16f0f4f;p=github%2Fshaarli%2FShaarli.git diff --git a/index.php b/index.php index d061f912..8a0be951 100644 --- a/index.php +++ b/index.php @@ -1,8 +1,8 @@ /shaarli/ define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0))); @@ -44,6 +44,20 @@ error_reporting(E_ALL^E_WARNING); //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'; @@ -53,6 +67,7 @@ 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'; @@ -64,7 +79,6 @@ require_once 'application/Utils.php'; require_once 'application/PluginManager.php'; require_once 'application/Router.php'; require_once 'application/Updater.php'; -require_once 'inc/rain.tpl.class.php'; // Ensure the PHP version is supported try { @@ -108,8 +122,8 @@ if (isset($_COOKIE['shaarli']) && !is_session_id_valid($_COOKIE['shaarli'])) { $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('path.raintpl_tpl'); // template directory -RainTPL::$cache_dir = $conf->get('path.raintpl_tmp'); // cache directory +RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl'); // template directory +RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory $pluginManager = new PluginManager($conf); $pluginManager->load($conf->get('general.enabled_plugins')); @@ -172,7 +186,7 @@ header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper int */ function setup_login_state($conf) { - if ($conf->get('extras.open_shaarli')) { + if ($conf->get('security.open_shaarli')) { return true; } $userIsLoggedIn = false; // By default, we do not consider the user as logged in; @@ -273,10 +287,10 @@ function check_auth($login, $password, $conf) if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash')) { // Login/password is correct. fillSessionInfo($conf); - logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login successful'); + logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful'); return true; } - logm($conf->get('path.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login); + logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login); return false; } @@ -302,14 +316,14 @@ function logout() { // ------------------------------------------------------------------------------------------ // Brute force protection system // Several consecutive failed logins will ban the IP address for 30 minutes. -if (!is_file($conf->get('path.ban_file', 'data/ipbans.php'))) { +if (!is_file($conf->get('resource.ban_file', 'data/ipbans.php'))) { // FIXME! globals file_put_contents( - $conf->get('path.ban_file', 'data/ipbans.php'), + $conf->get('resource.ban_file', 'data/ipbans.php'), "array(),'BANS'=>array()),true).";\n?>" ); } -include $conf->get('path.ban_file', 'data/ipbans.php'); +include $conf->get('resource.ban_file', 'data/ipbans.php'); /** * Signal a failed login. Will ban the IP if too many failures: * @@ -318,17 +332,26 @@ include $conf->get('path.ban_file', 'data/ipbans.php'); 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; + 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('path.log'), $_SERVER['REMOTE_ADDR'], 'IP address banned from login'); + logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'IP address banned from login'); } $GLOBALS['IPBANS'] = $gb; file_put_contents( - $conf->get('path.ban_file', 'data/ipbans.php'), + $conf->get('resource.ban_file', 'data/ipbans.php'), "" ); } @@ -345,7 +368,7 @@ function ban_loginOk($conf) unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); $GLOBALS['IPBANS'] = $gb; file_put_contents( - $conf->get('path.ban_file', 'data/ipbans.php'), + $conf->get('resource.ban_file', 'data/ipbans.php'), "" ); } @@ -365,10 +388,10 @@ function ban_canLogin($conf) // 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('path.log'), $_SERVER['REMOTE_ADDR'], 'Ban lifted.'); + logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Ban lifted.'); unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]); file_put_contents( - $conf->get('path.ban_file', 'data/ipbans.php'), + $conf->get('resource.ban_file', 'data/ipbans.php'), "" ); return true; // Ban has expired, user can login. @@ -436,7 +459,7 @@ if (isset($_POST['login'])) else { ban_loginFailed($conf); - $redir = '&username='. $_POST['login']; + $redir = '&username='. urlencode($_POST['login']); if (isset($_GET['post'])) { $redir .= '&post=' . urlencode($_GET['post']); foreach (array('description', 'source', 'title') as $param) { @@ -533,32 +556,27 @@ function showDailyRSS($conf) { // 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('path.datastore'), + $conf->get('resource.datastore'), isLoggedIn(), - $conf->get('extras.hide_public_links'), - $conf->get('extras.redirector'), - $conf->get('extras.redirector_encode_url') + $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 (rsort()) until we have enough days ($nb_of_days). + back in time until we have enough days ($nb_of_days). */ - $linkdates = array(); - foreach ($LINKSDB as $linkdate => $value) { - $linkdates[] = $linkdate; - } - 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) { + 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][] = $linkdate; + $days[$day][] = $link; } if (count($days) > $nb_of_days) { @@ -578,26 +596,18 @@ function showDailyRSS($conf) { echo ''. $pageaddr .''. PHP_EOL; // For each day. - foreach ($days as $day => $linkdates) { + 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. - // Build the HTML body of this RSS entry. - $html = ''; - $href = ''; - $links = array(); - // We pre-format some fields for proper output. - foreach ($linkdates as $linkdate) { - $l = $LINKSDB[$linkdate]; - $l['formatedDescription'] = format_description($l['description'], $conf->get('extras.redirector')); - $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 + 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 } - $links[$linkdate] = $l; } // Then build the HTML for this day: @@ -607,7 +617,7 @@ function showDailyRSS($conf) { $tpl->assign('absurl', $absurl); $tpl->assign('links', $links); $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS))); - $tpl->assign('hide_timestamps', $conf->get('extras.hide_timestamps', false)); + $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false)); $html = $tpl->draw('dailyrss', $return_string=true); echo $html . PHP_EOL; @@ -657,10 +667,9 @@ function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager) $taglist = explode(' ',$link['tags']); uasort($taglist, 'strcasecmp'); $linksToDisplay[$key]['taglist']=$taglist; - $linksToDisplay[$key]['formatedDescription'] = format_description($link['description'], $conf->get('extras.redirector')); + $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(); + $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp(); } /* We need to spread the articles on 3 columns. @@ -726,15 +735,15 @@ function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) { function renderPage($conf, $pluginManager) { $LINKSDB = new LinkDB( - $conf->get('path.datastore'), + $conf->get('resource.datastore'), isLoggedIn(), - $conf->get('extras.hide_public_links'), - $conf->get('extras.redirector'), - $conf->get('extras.redirector_encode_url') + $conf->get('privacy.hide_public_links'), + $conf->get('redirector.url'), + $conf->get('redirector.encode_url') ); $updater = new Updater( - read_updates_file($conf->get('path.updates')), + read_updates_file($conf->get('resource.updates')), $LINKSDB, $conf, isLoggedIn() @@ -743,7 +752,7 @@ function renderPage($conf, $pluginManager) $newUpdates = $updater->update(); if (! empty($newUpdates)) { write_updates_file( - $conf->get('path.updates'), + $conf->get('resource.updates'), $updater->getDoneUpdates() ); } @@ -755,6 +764,7 @@ function renderPage($conf, $pluginManager) $PAGE = new PageBuilder($conf); $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'] : ''; @@ -782,9 +792,7 @@ function renderPage($conf, $pluginManager) // -------- Display login form. if ($targetPage == Router::$PAGE_LOGIN) { - if ($conf->get('extras.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli - $token=''; if (ban_canLogin($conf)) $token=getToken($conf); // Do not waste token generation if not useful. - $PAGE->assign('token',$token); + 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'])); } @@ -795,7 +803,7 @@ function renderPage($conf, $pluginManager) // -------- User wants to logout. if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) { - invalidateCaches($conf->get('path.page_cache')); + invalidateCaches($conf->get('resource.page_cache')); logout(); header('Location: ?'); exit; @@ -811,7 +819,7 @@ function renderPage($conf, $pluginManager) // Get only links which have a thumbnail. foreach($links as $link) { - $permalink='?'.escape(smallhash($link['linkdate'])); + $permalink='?'.$link['shorturl']; $thumb=lazyThumbnail($conf, $link['url'],$permalink); if ($thumb!='') // Only output links which have a thumbnail. { @@ -845,7 +853,7 @@ function renderPage($conf, $pluginManager) $maxcount = max($maxcount, $value); } - // Sort tags alphabetically: case insensitive, support locale if avalaible. + // Sort tags alphabetically: case insensitive, support locale if available. uksort($tags, function($a, $b) { // Collator is part of PHP intl. if (class_exists('Collator')) { @@ -895,7 +903,7 @@ function renderPage($conf, $pluginManager) // Cache system $query = $_SERVER['QUERY_STRING']; $cache = new CachedPage( - $conf->get('path.page_cache'), + $conf->get('resource.page_cache'), page_url($_SERVER), startsWith($query,'do='. $targetPage) && !isLoggedIn() ); @@ -908,8 +916,8 @@ function renderPage($conf, $pluginManager) // Generate data. $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn()); $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0))); - $feedGenerator->setHideDates($conf->get('extras.hide_timestamps') && !isLoggedIn()); - $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('general.rss_permalinks')); + $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !isLoggedIn()); + $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks')); $pshUrl = $conf->get('config.PUBSUBHUB_URL'); if (!empty($pshUrl)) { $feedGenerator->setPubsubhubUrl($pshUrl); @@ -1058,6 +1066,7 @@ function renderPage($conf, $pluginManager) { $data = array( 'pageabsaddr' => index_url($_SERVER), + 'sslenabled' => !empty($_SERVER['HTTPS']) ); $pluginManager->executeHooks('render_tools', $data); @@ -1072,7 +1081,7 @@ function renderPage($conf, $pluginManager) // -------- User wants to change his/her password. if ($targetPage == Router::$PAGE_CHANGEPASSWORD) { - if ($conf->get('extras.open_shaarli')) { + if ($conf->get('security.open_shaarli')) { die('You are not supposed to change a password on an Open Shaarli.'); } @@ -1105,7 +1114,6 @@ function renderPage($conf, $pluginManager) } else // show the change password form. { - $PAGE->assign('token',getToken($conf)); $PAGE->renderPage('changepassword'); exit; } @@ -1128,12 +1136,12 @@ function renderPage($conf, $pluginManager) $conf->set('general.timezone', $tz); $conf->set('general.title', escape($_POST['title'])); $conf->set('general.header_link', escape($_POST['titleLink'])); - $conf->set('extras.redirector', escape($_POST['redirector'])); + $conf->set('redirector.url', escape($_POST['redirector'])); $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection'])); - $conf->set('general.default_private_links', !empty($_POST['privateLinkByDefault'])); - $conf->set('general.rss_permalinks', !empty($_POST['enableRssPermalinks'])); - $conf->set('general.check_updates', !empty($_POST['updateCheck'])); - $conf->set('extras.hide_public_links', !empty($_POST['hidePublicLinks'])); + $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault'])); + $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks'])); + $conf->set('updates.check_updates', !empty($_POST['updateCheck'])); + $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks'])); try { $conf->write(isLoggedIn()); } @@ -1152,16 +1160,16 @@ function renderPage($conf, $pluginManager) } else // Show the configuration form. { - $PAGE->assign('token',getToken($conf)); $PAGE->assign('title', $conf->get('general.title')); - $PAGE->assign('redirector', $conf->get('extras.redirector')); + $PAGE->assign('redirector', $conf->get('redirector.url')); list($timezone_form, $timezone_js) = generateTimeZoneForm($conf->get('general.timezone')); $PAGE->assign('timezone_form', $timezone_form); $PAGE->assign('timezone_js',$timezone_js); - $PAGE->assign('private_links_default', $conf->get('general.default_private_links', false)); - $PAGE->assign('enable_rss_permalinks', $conf->get('general.rss_permalinks', false)); - $PAGE->assign('enable_update_check', $conf->get('general.check_updates', true)); - $PAGE->assign('hide_public_links', $conf->get('extras.hide_public_links', false)); + $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false)); + $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false)); + $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false)); + $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true)); + $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false)); $PAGE->renderPage('configure'); exit; } @@ -1171,7 +1179,6 @@ function renderPage($conf, $pluginManager) if ($targetPage == Router::$PAGE_CHANGETAG) { if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) { - $PAGE->assign('token', getToken($conf)); $PAGE->assign('tags', $LINKSDB->allTags()); $PAGE->renderPage('changetag'); exit; @@ -1193,7 +1200,7 @@ function renderPage($conf, $pluginManager) $value['tags']=trim(implode(' ',$tags)); $LINKSDB[$key]=$value; } - $LINKSDB->savedb($conf->get('path.page_cache')); + $LINKSDB->save($conf->get('resource.page_cache')); echo ''; exit; } @@ -1210,7 +1217,7 @@ function renderPage($conf, $pluginManager) $value['tags']=trim(implode(' ',$tags)); $LINKSDB[$key]=$value; } - $LINKSDB->savedb($conf->get('path.page_cache')); // Save to disk. + $LINKSDB->save($conf->get('resource.page_cache')); // Save to disk. echo ''; exit; } @@ -1230,13 +1237,33 @@ function renderPage($conf, $pluginManager) if (! tokenOk($_POST['token'])) { die('Wrong token.'); } + + // lf_id should only be present if the link exists. + $id = !empty($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId(); + // Linkdate is kept here to: + // - use the same permalink for notes as they're displayed when creating them + // - let users hack creation date of their posts + // See: https://github.com/shaarli/Shaarli/wiki/Datastore-hacks#changing-the-timestamp-for-a-link + $linkdate = escape($_POST['lf_linkdate']); + if (isset($LINKSDB[$id])) { + // Edit + $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate); + $updated = new DateTime(); + $shortUrl = $LINKSDB[$id]['shorturl']; + } else { + // New link + $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate); + $updated = null; + $shortUrl = link_small_hash($created, $id); + } + // Remove multiple spaces. $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags'])); // Remove first '-' char in tags. $tags = preg_replace('/(^| )\-/', '$1', $tags); // Remove duplicates. $tags = implode(' ', array_unique(explode(' ', $tags))); - $linkdate = $_POST['lf_linkdate']; + $url = trim($_POST['lf_url']); if (! startsWith($url, 'http:') && ! startsWith($url, 'https:') && ! startsWith($url, 'ftp:') && ! startsWith($url, 'magnet:') @@ -1246,13 +1273,17 @@ function renderPage($conf, $pluginManager) } $link = array( + 'id' => $id, 'title' => trim($_POST['lf_title']), 'url' => $url, 'description' => $_POST['lf_description'], 'private' => (isset($_POST['lf_private']) ? 1 : 0), - 'linkdate' => $linkdate, - 'tags' => str_replace(',', ' ', $tags) + 'created' => $created, + 'updated' => $updated, + 'tags' => str_replace(',', ' ', $tags), + 'shorturl' => $shortUrl, ); + // If title is empty, use the URL as title. if ($link['title'] == '') { $link['title'] = $link['url']; @@ -1260,8 +1291,8 @@ function renderPage($conf, $pluginManager) $pluginManager->executeHooks('save_link', $link); - $LINKSDB[$linkdate] = $link; - $LINKSDB->savedb($conf->get('path.page_cache')); + $LINKSDB[$id] = $link; + $LINKSDB->save($conf->get('resource.page_cache')); pubsubhub($conf); // If we are called from the bookmarklet, we must close the popup: @@ -1273,7 +1304,7 @@ function renderPage($conf, $pluginManager) $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?'; $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link')); // Scroll to the link which has been edited. - $location .= '#' . smallHash($_POST['lf_linkdate']); + $location .= '#' . $link['shorturl']; // After saving the link, redirect to the page the user was on. header('Location: '. $location); exit; @@ -1284,8 +1315,10 @@ function renderPage($conf, $pluginManager) { // If we are called from the bookmarklet, we must close the popup: if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo ''; exit; } + $link = $LINKSDB[(int) escape($_POST['lf_id'])]; $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' ); - $returnurl .= '#'.smallHash($_POST['lf_linkdate']); // Scroll to the link which has been edited. + // Scroll to the link which has been edited. + $returnurl .= '#'. $link['shorturl']; $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link')); header('Location: '.$returnurl); // After canceling, redirect to the page the user was on. exit; @@ -1295,15 +1328,18 @@ function renderPage($conf, $pluginManager) if (isset($_POST['delete_link'])) { if (!tokenOk($_POST['token'])) die('Wrong token.'); + // We do not need to ask for confirmation: // - confirmation is handled by JavaScript // - we are protected from XSRF by the token. - $linkdate=$_POST['lf_linkdate']; - $pluginManager->executeHooks('delete_link', $LINKSDB[$linkdate]); + // FIXME! We keep `lf_linkdate` for consistency before a proper API. To be removed. + $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : intval(escape($_POST['lf_linkdate'])); - unset($LINKSDB[$linkdate]); - $LINKSDB->savedb('path.page_cache'); // save to disk + $pluginManager->executeHooks('delete_link', $LINKSDB[$id]); + + unset($LINKSDB[$id]); + $LINKSDB->save('resource.page_cache'); // save to disk // If we are called from the bookmarklet, we must close the popup: if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo ''; exit; } @@ -1341,12 +1377,13 @@ function renderPage($conf, $pluginManager) // -------- User clicked the "EDIT" button on a link: Display link edit form. if (isset($_GET['edit_link'])) { - $link = $LINKSDB[$_GET['edit_link']]; // Read database + $id = (int) escape($_GET['edit_link']); + $link = $LINKSDB[$id]; // Read database if (!$link) { header('Location: ?'); exit; } // Link not found in database. + $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT); $data = array( 'link' => $link, 'link_is_new' => false, - 'token' => getToken($conf), 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), 'tags' => $LINKSDB->allTags(), ); @@ -1367,10 +1404,10 @@ function renderPage($conf, $pluginManager) $link_is_new = false; // Check if URL is not already in database (in this case, we will edit the existing link) $link = $LINKSDB->getLinkFromUrl($url); - if (!$link) + if (! $link) { $link_is_new = true; - $linkdate = strval(date('Ymd_His')); + $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT)); // Get title if it was provided in URL (by the bookmarklet). $title = empty($_GET['title']) ? '' : escape($_GET['title']); // Get description if it was provided in URL (by the bookmarklet). [Bronco added that] @@ -1394,7 +1431,7 @@ function renderPage($conf, $pluginManager) } if ($url == '') { - $url = '?' . smallHash($linkdate); + $url = '?' . smallHash($linkdate . $LINKSDB->getNextId()); $title = 'Note: '; } $url = escape($url); @@ -1408,16 +1445,17 @@ function renderPage($conf, $pluginManager) 'tags' => $tags, 'private' => $private ); + } else { + $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT); } $data = array( 'link' => $link, 'link_is_new' => $link_is_new, - 'token' => getToken($conf), // XSRF protection. 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''), 'source' => (isset($_GET['source']) ? $_GET['source'] : ''), 'tags' => $LINKSDB->allTags(), - 'default_private_links' => $conf->get('default_private_links', false), + 'default_private_links' => $conf->get('privacy.default_private_links', false), ); $pluginManager->executeHooks('render_editlink', $data); @@ -1473,27 +1511,37 @@ function renderPage($conf, $pluginManager) exit; } - // -------- User is uploading a file for import - if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=upload')) - { - // If file is too big, some form field may be missing. - if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0)) - { - $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] ); - echo ''; + if ($targetPage == Router::$PAGE_IMPORT) { + // Upload a Netscape bookmark dump to import its contents + + if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) { + // Show import dialog + $PAGE->assign('maxfilesize', getMaxFileSize()); + $PAGE->renderPage('import'); exit; } - if (!tokenOk($_POST['token'])) die('Wrong token.'); - importFile($LINKSDB); - exit; - } - // -------- Show upload/import dialog: - if ($targetPage == Router::$PAGE_IMPORT) - { - $PAGE->assign('token',getToken($conf)); - $PAGE->assign('maxfilesize',getMaxFileSize()); - $PAGE->renderPage('import'); + // Import bookmarks from an uploaded file + if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) { + // The file is too big or some form field may be missing. + echo ''; + exit; + } + if (! tokenOk($_POST['token'])) { + die('Wrong token.'); + } + $status = NetscapeBookmarkUtils::import( + $_POST, + $_FILES, + $LINKSDB, + $conf->get('resource.page_cache') + ); + echo ''; exit; } @@ -1550,95 +1598,6 @@ function renderPage($conf, $pluginManager) exit; } -/** - * Process the import file form. - * - * @param LinkDB $LINKSDB Loaded LinkDB instance. - * @param ConfigManager $conf Configuration Manager instance. - */ -function importFile($LINKSDB, $conf) -{ - if (!isLoggedIn()) { die('Not allowed.'); } - - $filename=$_FILES['filetoupload']['name']; - $filesize=$_FILES['filetoupload']['size']; - $data=file_get_contents($_FILES['filetoupload']['tmp_name']); - $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private? - $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones? - $import_count=0; - - // Sniff file type: - $type='unknown'; - if (startsWith($data,'')) $type='netscape'; // Netscape bookmark file (aka Firefox). - - // Then import the bookmarks. - if ($type=='netscape') - { - // This is a standard Netscape-style bookmark file. - // This format is supported by all browsers (except IE, of course), also Delicious, Diigo and others. - foreach(explode('
',$data) as $html) // explode is very fast - { - $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0); - $d = explode('
',$html); - if (startsWith($d[0], '(.*?)!i',$d[0],$matches); $link['title'] = (isset($matches[1]) ? trim($matches[1]) : ''); // Get title - $link['title'] = html_entity_decode($link['title'],ENT_QUOTES,'UTF-8'); - preg_match_all('! ([A-Z_]+)=\"(.*?)"!i',$html,$matches,PREG_SET_ORDER); // Get all other attributes - $raw_add_date=0; - foreach($matches as $m) - { - $attr=$m[1]; $value=$m[2]; - if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8'); - elseif ($attr=='ADD_DATE') - { - $raw_add_date=intval($value); - if ($raw_add_date>30000000000) $raw_add_date/=1000; //If larger than year 2920, then was likely stored in milliseconds instead of seconds - } - elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1); - elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8'); - } - if ($link['url']!='') - { - if ($private==1) $link['private']=1; - $dblink = $LINKSDB->getLinkFromUrl($link['url']); // See if the link is already in database. - if ($dblink==false) - { // Link not in database, let's import it... - if (empty($raw_add_date)) $raw_add_date=time(); // In case of shitty bookmark file with no ADD_DATE - - // Make sure date/time is not already used by another link. - // (Some bookmark files have several different links with the same ADD_DATE) - // We increment date by 1 second until we find a date which is not used in DB. - // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.) - while (!empty($LINKSDB[date('Ymd_His',$raw_add_date)])) { $raw_add_date++; }// Yes, I know it's ugly. - $link['linkdate']=date('Ymd_His',$raw_add_date); - $LINKSDB[$link['linkdate']] = $link; - $import_count++; - } - else // Link already present in database. - { - if ($overwrite) - { // If overwrite is required, we import link data, except date/time. - $link['linkdate']=$dblink['linkdate']; - $LINKSDB[$link['linkdate']] = $link; - $import_count++; - } - } - - } - } - } - $LINKSDB->savedb($conf->get('path.page_cache')); - - echo ''; - } - else - { - echo ''; - } -} - /** * Template for the list of links (