]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - index.php
LinkDB: update datastore method names
[github/shaarli/Shaarli.git] / index.php
index 091ad704e6e1b0d1404e878a69c9246c4466b8d4..84282b8dc6c6ecc41dd67cae0eae0e9c3fdf883a 100644 (file)
--- a/index.php
+++ b/index.php
@@ -1,6 +1,6 @@
 <?php
 /**
- * Shaarli v0.7.0 - Shaare your links...
+ * Shaarli v0.8.0 - Shaare your links...
  *
  * The personal, minimalist, super-fast, database free, bookmarking service.
  *
@@ -25,7 +25,7 @@ if (date_default_timezone_get() == '') {
 /*
  * PHP configuration
  */
-define('shaarli_version', '0.7.0');
+define('shaarli_version', '0.8.0');
 
 // http://server.com/x/shaarli --> /shaarli/
 define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
@@ -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';
@@ -65,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 {
@@ -319,8 +332,17 @@ include $conf->get('resource.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))
     {
@@ -584,8 +606,6 @@ function showDailyRSS($conf) {
         $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.
@@ -756,6 +776,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'] : '';
@@ -810,7 +831,7 @@ function renderPage($conf, $pluginManager)
         // Get only links which have a thumbnail.
         foreach($links as $link)
         {
-            $permalink='?'.escape(smallhash($link['linkdate']));
+            $permalink='?'.escape(smallHash($link['linkdate']));
             $thumb=lazyThumbnail($conf, $link['url'],$permalink);
             if ($thumb!='') // Only output links which have a thumbnail.
             {
@@ -844,7 +865,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')) {
@@ -1190,7 +1211,7 @@ function renderPage($conf, $pluginManager)
                 $value['tags']=trim(implode(' ',$tags));
                 $LINKSDB[$key]=$value;
             }
-            $LINKSDB->savedb($conf->get('resource.page_cache'));
+            $LINKSDB->save($conf->get('resource.page_cache'));
             echo '<script>alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>';
             exit;
         }
@@ -1207,7 +1228,7 @@ function renderPage($conf, $pluginManager)
                 $value['tags']=trim(implode(' ',$tags));
                 $LINKSDB[$key]=$value;
             }
-            $LINKSDB->savedb($conf->get('resource.page_cache')); // Save to disk.
+            $LINKSDB->save($conf->get('resource.page_cache')); // Save to disk.
             echo '<script>alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
             exit;
         }
@@ -1223,6 +1244,9 @@ function renderPage($conf, $pluginManager)
     // -------- User clicked the "Save" button when editing a link: Save link to database.
     if (isset($_POST['save_edit']))
     {
+        $linkdate = $_POST['lf_linkdate'];
+        $updated = isset($LINKSDB[$linkdate]) ? strval(date('Ymd_His')) : false;
+
         // Go away!
         if (! tokenOk($_POST['token'])) {
             die('Wrong token.');
@@ -1233,7 +1257,7 @@ function renderPage($conf, $pluginManager)
         $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:')
@@ -1248,6 +1272,7 @@ function renderPage($conf, $pluginManager)
             'description' => $_POST['lf_description'],
             'private' => (isset($_POST['lf_private']) ? 1 : 0),
             'linkdate' => $linkdate,
+            'updated' => $updated,
             'tags' => str_replace(',', ' ', $tags)
         );
         // If title is empty, use the URL as title.
@@ -1258,7 +1283,7 @@ function renderPage($conf, $pluginManager)
         $pluginManager->executeHooks('save_link', $link);
 
         $LINKSDB[$linkdate] = $link;
-        $LINKSDB->savedb($conf->get('resource.page_cache'));
+        $LINKSDB->save($conf->get('resource.page_cache'));
         pubsubhub($conf);
 
         // If we are called from the bookmarklet, we must close the popup:
@@ -1300,7 +1325,7 @@ function renderPage($conf, $pluginManager)
         $pluginManager->executeHooks('delete_link', $LINKSDB[$linkdate]);
 
         unset($LINKSDB[$linkdate]);
-        $LINKSDB->savedb('resource.page_cache'); // save to disk
+        $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 '<script>self.close();</script>'; exit; }
@@ -1412,7 +1437,7 @@ function renderPage($conf, $pluginManager)
             '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);
 
@@ -1468,26 +1493,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 '<script>alert("The file you are trying to upload is probably bigger than what this webserver can accept ('.getMaxFileSize().' bytes). Please upload in smaller chunks.");document.location=\''.escape($returnurl).'\';</script>';
+    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('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 '<script>alert("The file you are trying to upload is probably'
+                .' bigger than what this webserver can accept ('
+                .getMaxFileSize().' bytes).'
+                .' Please upload in smaller chunks.");document.location=\'?do='
+                .Router::$PAGE_IMPORT .'\';</script>';
+            exit;
+        }
+        if (! tokenOk($_POST['token'])) {
+            die('Wrong token.');
+        }
+        $status = NetscapeBookmarkUtils::import(
+            $_POST,
+            $_FILES,
+            $LINKSDB,
+            $conf->get('resource.page_cache')
+        );
+        echo '<script>alert("'.$status.'");document.location=\'?do='
+             .Router::$PAGE_IMPORT .'\';</script>';
         exit;
     }
 
@@ -1544,95 +1580,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,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $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('<DT>',$data) as $html) // explode is very fast
-        {
-            $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);
-            $d = explode('<DD>',$html);
-            if (startsWith($d[0], '<A '))
-            {
-                $link['description'] = (isset($d[1]) ? html_entity_decode(trim($d[1]),ENT_QUOTES,'UTF-8') : '');  // Get description (optional)
-                preg_match('!<A .*?>(.*?)</A>!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('resource.page_cache'));
-
-        echo '<script>alert("File '.json_encode($filename).' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
-    }
-    else
-    {
-        echo '<script>alert("File '.json_encode($filename).' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>';
-    }
-}
-
 /**
  * Template for the list of links (<div id="linklist">)
  * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
@@ -1689,6 +1636,12 @@ function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
         $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;
@@ -1715,8 +1668,6 @@ function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
         $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
     }
 
-    $token = isLoggedIn() ? getToken($conf) : '';
-
     // Fill all template fields.
     $data = array(
         'previous_page_url' => $previous_page_url,