aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
authorVirtualTam <virtualtam@flibidi.org>2015-03-12 00:43:02 +0100
committerVirtualTam <virtualtam@flibidi.net>2015-06-11 00:45:45 +0200
commitca74886f30da323f42aa4bd70461003f46ef299b (patch)
tree3714895c25d80bdb472211a564f83d3744d90f34 /index.php
parentcbecab773526b0c39f3cffa1d4595b5caa781bda (diff)
downloadShaarli-ca74886f30da323f42aa4bd70461003f46ef299b.tar.gz
Shaarli-ca74886f30da323f42aa4bd70461003f46ef299b.tar.zst
Shaarli-ca74886f30da323f42aa4bd70461003f46ef299b.zip
LinkDB: move to a proper file, add test coverage
Relates to #71 LinkDB - move to application/LinkDB.php - code cleanup - indentation - whitespaces - formatting - comment cleanup - add missing documentation - unify formatting Test coverage for LinkDB - constructor - public / private access - link-related methods Shaarli utilities (LinkDB dependencies) - move startsWith() and endsWith() functions to application/Utils.php - add test coverage Dev utilities - Composer: add PHPUnit to dev dependencies - Makefile: - update lint targets - add test targets - generate coverage reports Signed-off-by: VirtualTam <virtualtam@flibidi.net>
Diffstat (limited to 'index.php')
-rw-r--r--index.php259
1 files changed, 10 insertions, 249 deletions
diff --git a/index.php b/index.php
index 9561f63b..ed18c7f9 100644
--- a/index.php
+++ b/index.php
@@ -68,6 +68,10 @@ checkphpversion();
68error_reporting(E_ALL^E_WARNING); // See all error except warnings. 68error_reporting(E_ALL^E_WARNING); // See all error except warnings.
69//error_reporting(-1); // See all errors (for debugging only) 69//error_reporting(-1); // See all errors (for debugging only)
70 70
71// Shaarli library
72require_once 'application/LinkDB.php';
73require_once 'application/Utils.php';
74
71include "inc/rain.tpl.class.php"; //include Rain TPL 75include "inc/rain.tpl.class.php"; //include Rain TPL
72raintpl::$tpl_dir = $GLOBALS['config']['RAINTPL_TPL']; // template directory 76raintpl::$tpl_dir = $GLOBALS['config']['RAINTPL_TPL']; // template directory
73raintpl::$cache_dir = $GLOBALS['config']['RAINTPL_TMP']; // cache directory 77raintpl::$cache_dir = $GLOBALS['config']['RAINTPL_TMP']; // cache directory
@@ -268,21 +272,6 @@ function nl2br_escaped($html)
268 return str_replace('>','&gt;',str_replace('<','&lt;',nl2br($html))); 272 return str_replace('>','&gt;',str_replace('<','&lt;',nl2br($html)));
269} 273}
270 274
271/* Returns the small hash of a string, using RFC 4648 base64url format
272 e.g. smallHash('20111006_131924') --> yZH23w
273 Small hashes:
274 - are unique (well, as unique as crc32, at last)
275 - are always 6 characters long.
276 - only use the following characters: a-z A-Z 0-9 - _ @
277 - are NOT cryptographically secure (they CAN be forged)
278 In Shaarli, they are used as a tinyurl-like link to individual entries.
279*/
280function smallHash($text)
281{
282 $t = rtrim(base64_encode(hash('crc32',$text,true)),'=');
283 return strtr($t, '+/', '-_');
284}
285
286// In a string, converts URLs to clickable links. 275// In a string, converts URLs to clickable links.
287// Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722 276// Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
288function text2clickable($url) 277function text2clickable($url)
@@ -536,20 +525,6 @@ function getMaxFileSize()
536 return $maxsize; 525 return $maxsize;
537} 526}
538 527
539// Tells if a string start with a substring or not.
540function startsWith($haystack,$needle,$case=true)
541{
542 if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
543 return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
544}
545
546// Tells if a string ends with a substring or not.
547function endsWith($haystack,$needle,$case=true)
548{
549 if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
550 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
551}
552
553/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch) 528/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
554 (used to build the ADD_DATE attribute in Netscape-bookmarks file) 529 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
555 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */ 530 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
@@ -711,220 +686,6 @@ class pageBuilder
711} 686}
712 687
713// ------------------------------------------------------------------------------------------ 688// ------------------------------------------------------------------------------------------
714/* Data storage for links.
715 This object behaves like an associative array.
716 Example:
717 $mylinks = new linkdb();
718 echo $mylinks['20110826_161819']['title'];
719 foreach($mylinks as $link)
720 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
721
722 Available keys:
723 title : Title of the link
724 url : URL of the link. Can be absolute or relative. Relative URLs are permalinks (e.g.'?m-ukcw')
725 description : description of the entry
726 private : Is this link private? 0=no, other value=yes
727 linkdate : date of the creation of this entry, in the form YYYYMMDD_HHMMSS (e.g.'20110914_192317')
728 tags : tags attached to this entry (separated by spaces)
729
730 We implement 3 interfaces:
731 - ArrayAccess so that this object behaves like an associative array.
732 - Iterator so that this object can be used in foreach() loops.
733 - Countable interface so that we can do a count() on this object.
734*/
735class linkdb implements Iterator, Countable, ArrayAccess
736{
737 private $links; // List of links (associative array. Key=linkdate (e.g. "20110823_124546"), value= associative array (keys:title,description...)
738 private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
739 private $keys; // List of linkdate keys (for the Iterator interface implementation)
740 private $position; // Position in the $this->keys array. (for the Iterator interface implementation.)
741 private $loggedin; // Is the user logged in? (used to filter private links)
742
743 // Constructor:
744 function __construct($isLoggedIn)
745 // Input : $isLoggedIn : is the user logged in?
746 {
747 $this->loggedin = $isLoggedIn;
748 $this->checkdb(); // Make sure data file exists.
749 $this->readdb(); // Then read it.
750 }
751
752 // ---- Countable interface implementation
753 public function count() { return count($this->links); }
754
755 // ---- ArrayAccess interface implementation
756 public function offsetSet($offset, $value)
757 {
758 if (!$this->loggedin) die('You are not authorized to add a link.');
759 if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and URL.');
760 if (empty($offset)) die('You must specify a key.');
761 $this->links[$offset] = $value;
762 $this->urls[$value['url']]=$offset;
763 }
764 public function offsetExists($offset) { return array_key_exists($offset,$this->links); }
765 public function offsetUnset($offset)
766 {
767 if (!$this->loggedin) die('You are not authorized to delete a link.');
768 $url = $this->links[$offset]['url']; unset($this->urls[$url]);
769 unset($this->links[$offset]);
770 }
771 public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; }
772
773 // ---- Iterator interface implementation
774 function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first).
775 function key() { return $this->keys[$this->position]; } // current key
776 function current() { return $this->links[$this->keys[$this->position]]; } // current value
777 function next() { ++$this->position; } // go to next item
778 function valid() { return isset($this->keys[$this->position]); } // Check if current position is valid.
779
780 // ---- Misc methods
781 private function checkdb() // Check if db directory and file exists.
782 {
783 if (!file_exists($GLOBALS['config']['DATASTORE'])) // Create a dummy database for example.
784 {
785 $this->links = array();
786 $link = array('title'=>'Shaarli - sebsauvage.net','url'=>'http://sebsauvage.net/wiki/doku.php?id=php:shaarli','description'=>'Welcome to Shaarli ! This is a bookmark. To edit or delete me, you must first login.','private'=>0,'linkdate'=>'20110914_190000','tags'=>'opensource software');
787 $this->links[$link['linkdate']] = $link;
788 $link = array('title'=>'My secret stuff... - Pastebin.com','url'=>'http://sebsauvage.net/paste/?8434b27936c09649#bR7XsXhoTiLcqCpQbmOpBi3rq2zzQUC5hBI7ZT1O3x8=','description'=>'SShhhh!! I\'m a private link only YOU can see. You can delete me too.','private'=>1,'linkdate'=>'20110914_074522','tags'=>'secretstuff');
789 $this->links[$link['linkdate']] = $link;
790 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
791 }
792 }
793
794 // Read database from disk to memory
795 private function readdb()
796 {
797 // Read data
798 $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
799 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
800
801 // If user is not logged in, filter private links.
802 if (!$this->loggedin)
803 {
804 $toremove=array();
805 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
806 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
807 }
808
809 // Keep the list of the mapping URLs-->linkdate up-to-date.
810 $this->urls=array();
811 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
812 }
813
814 // Save database from memory to disk.
815 public function savedb()
816 {
817 if (!$this->loggedin) die('You are not authorized to change the database.');
818 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
819 invalidateCaches();
820 }
821
822 // Returns the link for a given URL (if it exists). False if it does not exist.
823 public function getLinkFromUrl($url)
824 {
825 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
826 return false;
827 }
828
829 // Case insensitive search among links (in the URLs, title and description). Returns filtered list of links.
830 // e.g. print_r($mydb->filterFulltext('hollandais'));
831 public function filterFulltext($searchterms)
832 {
833 // FIXME: explode(' ',$searchterms) and perform a AND search.
834 // FIXME: accept double-quotes to search for a string "as is"?
835 // Using mb_convert_case($val, MB_CASE_LOWER, 'UTF-8') allows us to perform searches on
836 // Unicode text. See https://github.com/shaarli/Shaarli/issues/75 for examples.
837 $filtered=array();
838 $s = mb_convert_case($searchterms, MB_CASE_LOWER, 'UTF-8');
839 foreach($this->links as $l)
840 {
841 $found= (strpos(mb_convert_case($l['title'], MB_CASE_LOWER, 'UTF-8'),$s) !== false)
842 || (strpos(mb_convert_case($l['description'], MB_CASE_LOWER, 'UTF-8'),$s) !== false)
843 || (strpos(mb_convert_case($l['url'], MB_CASE_LOWER, 'UTF-8'),$s) !== false)
844 || (strpos(mb_convert_case($l['tags'], MB_CASE_LOWER, 'UTF-8'),$s) !== false);
845 if ($found) $filtered[$l['linkdate']] = $l;
846 }
847 krsort($filtered);
848 return $filtered;
849 }
850
851 // Filter by tag.
852 // You can specify one or more tags (tags can be separated by space or comma).
853 // e.g. print_r($mydb->filterTags('linux programming'));
854 public function filterTags($tags,$casesensitive=false)
855 {
856 // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
857 // TODO: is $casesensitive ever true ?
858 $t = str_replace(',',' ',($casesensitive?$tags:mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8')));
859 $searchtags=explode(' ',$t);
860 $filtered=array();
861 foreach($this->links as $l)
862 {
863 $linktags = explode(' ',($casesensitive?$l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER, 'UTF-8')));
864 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
865 $filtered[$l['linkdate']] = $l;
866 }
867 krsort($filtered);
868 return $filtered;
869 }
870
871 // Filter by day. Day must be in the form 'YYYYMMDD' (e.g. '20120125')
872 // Sort order is: older articles first.
873 // e.g. print_r($mydb->filterDay('20120125'));
874 public function filterDay($day)
875 {
876 $filtered=array();
877 foreach($this->links as $l)
878 {
879 if (startsWith($l['linkdate'],$day)) $filtered[$l['linkdate']] = $l;
880 }
881 ksort($filtered);
882 return $filtered;
883 }
884 // Filter by smallHash.
885 // Only 1 article is returned.
886 public function filterSmallHash($smallHash)
887 {
888 $filtered=array();
889 foreach($this->links as $l)
890 {
891 if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow
892 {
893 $filtered[$l['linkdate']] = $l;
894 return $filtered;
895 }
896 }
897 return $filtered;
898 }
899
900 // Returns the list of all tags
901 // Output: associative array key=tags, value=0
902 public function allTags()
903 {
904 $tags=array();
905 foreach($this->links as $link)
906 foreach(explode(' ',$link['tags']) as $tag)
907 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
908 arsort($tags); // Sort tags by usage (most used tag first)
909 return $tags;
910 }
911
912 // Returns the list of days containing articles (oldest first)
913 // Output: An array containing days (in format YYYYMMDD).
914 public function days()
915 {
916 $linkdays=array();
917 foreach(array_keys($this->links) as $day)
918 {
919 $linkdays[substr($day,0,8)]=0;
920 }
921 $linkdays=array_keys($linkdays);
922 sort($linkdays);
923 return $linkdays;
924 }
925}
926
927// ------------------------------------------------------------------------------------------
928// Output the last N links in RSS 2.0 format. 689// Output the last N links in RSS 2.0 format.
929function showRSS() 690function showRSS()
930{ 691{
@@ -941,7 +702,7 @@ function showRSS()
941 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; } 702 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
942 703
943 // If cached was not found (or not usable), then read the database and build the response: 704 // If cached was not found (or not usable), then read the database and build the response:
944 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if user it not logged in). 705 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']);
945 706
946 // Optionally filter the results: 707 // Optionally filter the results:
947 $linksToDisplay=array(); 708 $linksToDisplay=array();
@@ -1019,7 +780,7 @@ function showATOM()
1019 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; } 780 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
1020 // If cached was not found (or not usable), then read the database and build the response: 781 // If cached was not found (or not usable), then read the database and build the response:
1021 782
1022 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 783 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']);
1023 784
1024 785
1025 // Optionally filter the results: 786 // Optionally filter the results:
@@ -1104,7 +865,7 @@ function showDailyRSS()
1104 $cache = new pageCache(pageUrl(),startsWith($query,'do=dailyrss') && !isLoggedIn()); 865 $cache = new pageCache(pageUrl(),startsWith($query,'do=dailyrss') && !isLoggedIn());
1105 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; } 866 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
1106 // If cached was not found (or not usable), then read the database and build the response: 867 // If cached was not found (or not usable), then read the database and build the response:
1107 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 868 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']);
1108 869
1109 /* Some Shaarlies may have very few links, so we need to look 870 /* Some Shaarlies may have very few links, so we need to look
1110 back in time (rsort()) until we have enough days ($nb_of_days). 871 back in time (rsort()) until we have enough days ($nb_of_days).
@@ -1172,7 +933,7 @@ function showDailyRSS()
1172// "Daily" page. 933// "Daily" page.
1173function showDaily() 934function showDaily()
1174{ 935{
1175 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 936 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']);
1176 937
1177 938
1178 $day=Date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD. 939 $day=Date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
@@ -1240,7 +1001,7 @@ function showDaily()
1240// Render HTML page (according to URL parameters and user rights) 1001// Render HTML page (according to URL parameters and user rights)
1241function renderPage() 1002function renderPage()
1242{ 1003{
1243 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 1004 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']);
1244 1005
1245 // -------- Display login form. 1006 // -------- Display login form.
1246 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=login')) 1007 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=login'))
@@ -1822,7 +1583,7 @@ HTML;
1822function importFile() 1583function importFile()
1823{ 1584{
1824 if (!(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI'])) { die('Not allowed.'); } 1585 if (!(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI'])) { die('Not allowed.'); }
1825 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 1586 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']);
1826 $filename=$_FILES['filetoupload']['name']; 1587 $filename=$_FILES['filetoupload']['name'];
1827 $filesize=$_FILES['filetoupload']['size']; 1588 $filesize=$_FILES['filetoupload']['size'];
1828 $data=file_get_contents($_FILES['filetoupload']['tmp_name']); 1589 $data=file_get_contents($_FILES['filetoupload']['tmp_name']);