'.$link['description']."\n";
- }
+ // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
+ $selection = $_GET['selection'];
+ if (isset($_GET['prepend_note_url'])) {
+ $prependNoteUrl = $_GET['prepend_note_url'];
+ } else {
+ $prependNoteUrl = false;
}
- 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 '';
+ try {
+ $PAGE->assign(
+ 'links',
+ NetscapeBookmarkUtils::filterAndFormat(
+ $LINKSDB,
+ $selection,
+ $prependNoteUrl,
+ index_url($_SERVER)
+ )
+ );
+ } catch (Exception $exc) {
+ header('Content-Type: text/plain; charset=utf-8');
+ echo $exc->getMessage();
exit;
}
- if (!tokenOk($_POST['token'])) die('Wrong token.');
- importFile();
+ $now = new DateTime();
+ header('Content-Type: text/html; charset=utf-8');
+ header(
+ 'Content-disposition: attachment; filename=bookmarks_'
+ .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
+ );
+ $PAGE->assign('date', $now->format(DateTime::RFC822));
+ $PAGE->assign('eol', PHP_EOL);
+ $PAGE->assign('selection', $selection);
+ $PAGE->renderPage('export.bookmarks');
exit;
}
- // -------- Show upload/import dialog:
- if ($targetPage == Router::$PAGE_IMPORT)
- {
- $PAGE->assign('linkcount',count($LINKSDB));
- $PAGE->assign('token',getToken());
- $PAGE->assign('maxfilesize',getMaxFileSize());
- $PAGE->renderPage('import');
+ 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;
+ }
+
+ // 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;
}
@@ -1671,7 +1535,7 @@ HTML;
// Split plugins into 2 arrays: ordered enabled plugins and disabled.
$enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
// Load parameters.
- $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $GLOBALS['plugins']);
+ $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
uasort(
$enabledPlugins,
function($a, $b) { return $a['order'] - $b['order']; }
@@ -1690,13 +1554,13 @@ HTML;
if (isset($_POST['parameters_form'])) {
unset($_POST['parameters_form']);
foreach ($_POST as $param => $value) {
- $GLOBALS['plugins'][$param] = escape($value);
+ $conf->set('plugins.'. $param, escape($value));
}
}
else {
- $GLOBALS['config']['ENABLED_PLUGINS'] = save_plugin_config($_POST);
+ $conf->set('general.enabled_plugins', save_plugin_config($_POST));
}
- writeConfig($GLOBALS, isLoggedIn());
+ $conf->write(isLoggedIn());
}
catch (Exception $e) {
error_log(
@@ -1713,154 +1577,38 @@ HTML;
}
// -------- Otherwise, simply display search form and links:
- showLinkList($PAGE, $LINKSDB);
+ showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
exit;
}
-// -----------------------------------------------------------------------------------------------
-// Process the import file form.
-function importFile()
-{
- if (!isLoggedIn()) { die('Not allowed.'); }
- $LINKSDB = new LinkDB(
- $GLOBALS['config']['DATASTORE'],
- isLoggedIn(),
- $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
- $GLOBALS['redirector']
- );
- $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($GLOBALS['config']['PAGECACHE']);
-
- echo '';
- }
- else
- {
- echo '';
- }
-}
-
-// -----------------------------------------------------------------------------------------------
-// Template for the list of links (
)
-// This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
-function buildLinkList($PAGE,$LINKSDB)
+/**
+ * Template for the list of links (
)
+ * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
+ *
+ * @param pageBuilder $PAGE pageBuilder instance.
+ * @param LinkDB $LINKSDB LinkDB instance.
+ * @param ConfigManager $conf Configuration Manager instance.
+ * @param PluginManager $pluginManager Plugin Manager instance.
+ */
+function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
{
- // Filter link database according to parameters.
+ // Used in templates
$searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
- $searchterm = !empty($_GET['searchterm']) ? escape(trim($_GET['searchterm'])) : '';
- $privateonly = !empty($_SESSION['privateonly']) ? true : false;
-
- // Search tags + fullsearch.
- if (! empty($searchtags) && ! empty($searchterm)) {
- $linksToDisplay = $LINKSDB->filter(
- LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT,
- array($searchtags, $searchterm),
- false,
- $privateonly
- );
- }
- // Search by tags.
- elseif (! empty($searchtags)) {
- $linksToDisplay = $LINKSDB->filter(
- LinkFilter::$FILTER_TAG,
- $searchtags,
- false,
- $privateonly
- );
- }
- // Fulltext search.
- elseif (! empty($searchterm)) {
- $linksToDisplay = $LINKSDB->filter(
- LinkFilter::$FILTER_TEXT,
- $searchterm,
- false,
- $privateonly
- );
- }
- // Detect smallHashes in URL.
- elseif (! empty($_SERVER['QUERY_STRING'])
- && preg_match('/[a-zA-Z0-9-_@]{6}(&.+?)?/', $_SERVER['QUERY_STRING'])
- ) {
- $linksToDisplay = $LINKSDB->filter(
- LinkFilter::$FILTER_HASH,
- substr(trim($_SERVER["QUERY_STRING"], '/'), 0, 6)
- );
+ $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
- if (count($linksToDisplay) == 0) {
- $PAGE->render404('The link you are trying to reach does not exist or has been deleted.');
+ // Smallhash filter
+ if (! empty($_SERVER['QUERY_STRING'])
+ && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
+ try {
+ $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
+ } catch (LinkNotFoundException $e) {
+ $PAGE->render404($e->getMessage());
exit;
}
- }
- // Otherwise, display without filtering.
- else {
- $linksToDisplay = $LINKSDB->filter('', '', false, $privateonly);
+ } else {
+ // Filter links according search parameters.
+ $privateonly = !empty($_SESSION['privateonly']);
+ $linksToDisplay = $LINKSDB->filterSearch($_GET, false, $privateonly);
}
// ---- Handle paging.
@@ -1869,10 +1617,7 @@ function buildLinkList($PAGE,$LINKSDB)
$keys[] = $key;
}
- // If there is only a single link, we change on-the-fly the title of the page.
- if (count($linksToDisplay) == 1) {
- $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title'];
- }
+
// Select articles according to paging.
$pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
@@ -1887,11 +1632,17 @@ function buildLinkList($PAGE,$LINKSDB)
while ($i<$end && $iget('redirector.url'));
$classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
$link['class'] = $link['private'] == 0 ? $classLi : 'private';
$date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
$link['timestamp'] = $date->getTimestamp();
+ if (! empty($link['updated'])) {
+ $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['updated']);
+ $link['updated_timestamp'] = $date->getTimestamp();
+ } else {
+ $link['updated_timestamp'] = '';
+ }
$taglist = explode(' ', $link['tags']);
uasort($taglist, 'strcasecmp');
$link['taglist'] = $taglist;
@@ -1918,11 +1669,8 @@ function buildLinkList($PAGE,$LINKSDB)
$next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
}
- $token = isLoggedIn() ? getToken() : '';
-
// Fill all template fields.
$data = array(
- 'linkcount' => count($LINKSDB),
'previous_page_url' => $previous_page_url,
'next_page_url' => $next_page_url,
'page_current' => $page,
@@ -1930,17 +1678,16 @@ function buildLinkList($PAGE,$LINKSDB)
'result_count' => count($linksToDisplay),
'search_term' => $searchterm,
'search_tags' => $searchtags,
- 'redirector' => empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'], // Optional redirector URL.
- 'token' => $token,
+ 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
'links' => $linkDisp,
'tags' => $LINKSDB->allTags(),
);
- // FIXME! temporary fix - see #399.
- if (!empty($GLOBALS['pagetitle']) && count($linkDisp) == 1) {
- $data['pagetitle'] = $GLOBALS['pagetitle'];
+
+ // If there is only a single link, we change on-the-fly the title of the page.
+ if (count($linksToDisplay) == 1) {
+ $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
}
- $pluginManager = PluginManager::getInstance();
$pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
foreach ($data as $key => $value) {
@@ -1950,18 +1697,26 @@ function buildLinkList($PAGE,$LINKSDB)
return;
}
-// Compute the thumbnail for a link.
-//
-// With a link to the original URL.
-// Understands various services (youtube.com...)
-// Input: $url = URL for which the thumbnail must be found.
-// $href = if provided, this URL will be followed instead of $url
-// Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
-// Some of them may be missing.
-// Return an empty array if no thumbnail available.
-function computeThumbnail($url,$href=false)
+/**
+ * Compute the thumbnail for a link.
+ *
+ * With a link to the original URL.
+ * Understands various services (youtube.com...)
+ * Input: $url = URL for which the thumbnail must be found.
+ * $href = if provided, this URL will be followed instead of $url
+ * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
+ * Some of them may be missing.
+ * Return an empty array if no thumbnail available.
+ *
+ * @param ConfigManager $conf Configuration Manager instance.
+ * @param string $url
+ * @param string|bool $href
+ *
+ * @return array
+ */
+function computeThumbnail($conf, $url, $href = false)
{
- if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return array();
+ if (!$conf->get('thumbnail.enable_thumbnails')) return array();
if ($href==false) $href=$url;
// For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
@@ -2029,7 +1784,7 @@ function computeThumbnail($url,$href=false)
// So we deport the thumbnail generation in order not to slow down page generation
// (and we also cache the thumbnail)
- if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
+ if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
|| $domain=='vimeo.com'
@@ -2052,7 +1807,7 @@ function computeThumbnail($url,$href=false)
$path = parse_url($url,PHP_URL_PATH);
if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
}
- $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
+ $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
}
@@ -2063,7 +1818,7 @@ function computeThumbnail($url,$href=false)
$ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
{
- $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
+ $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
}
@@ -2080,7 +1835,9 @@ function computeThumbnail($url,$href=false)
// Returns '' if no thumbnail available.
function thumbnail($url,$href=false)
{
- $t = computeThumbnail($url,$href);
+ // FIXME!
+ global $conf;
+ $t = computeThumbnail($conf, $url,$href);
if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
$html='';
@@ -2126,10 +1885,13 @@ function lazyThumbnail($url,$href=false)
}
-// -----------------------------------------------------------------------------------------------
-// Installation
-// This function should NEVER be called if the file data/config.php exists.
-function install()
+/**
+ * Installation
+ * This function should NEVER be called if the file data/config.php exists.
+ *
+ * @param ConfigManager $conf Configuration Manager instance.
+ */
+function install($conf)
{
// On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
@@ -2161,20 +1923,26 @@ function install()
if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
{
$tz = 'UTC';
- if (!empty($_POST['continent']) && !empty($_POST['city'])) {
- if (isTimeZoneValid($_POST['continent'], $_POST['city'])) {
- $tz = $_POST['continent'].'/'.$_POST['city'];
- }
+ if (!empty($_POST['continent']) && !empty($_POST['city'])
+ && isTimeZoneValid($_POST['continent'], $_POST['city'])
+ ) {
+ $tz = $_POST['continent'].'/'.$_POST['city'];
+ }
+ $conf->set('general.timezone', $tz);
+ $login = $_POST['setlogin'];
+ $conf->set('credentials.login', $login);
+ $salt = sha1(uniqid('', true) .'_'. mt_rand());
+ $conf->set('credentials.salt', $salt);
+ $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
+ if (!empty($_POST['title'])) {
+ $conf->set('general.title', escape($_POST['title']));
+ } else {
+ $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
}
- $GLOBALS['timezone'] = $tz;
- // Everything is ok, let's create config file.
- $GLOBALS['login'] = $_POST['setlogin'];
- $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
- $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
- $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.escape(index_url($_SERVER)) : $_POST['title'] );
- $GLOBALS['config']['ENABLE_UPDATECHECK'] = !empty($_POST['updateCheck']);
+ $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
try {
- writeConfig($GLOBALS, isLoggedIn());
+ // Everything is ok, let's create config file.
+ $conf->write(isLoggedIn());
}
catch(Exception $e) {
error_log(
@@ -2197,42 +1965,46 @@ function install()
$timezone_html = '