aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
Diffstat (limited to 'index.php')
-rw-r--r--index.php266
1 files changed, 10 insertions, 256 deletions
diff --git a/index.php b/index.php
index b44ec463..d0dd5306 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,226 +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 // Public links are hidden and user not logged in => nothing to show
798 if ($GLOBALS['config']['HIDE_PUBLIC_LINKS'] && !isLoggedIn()) {
799 $this->links = array();
800 return;
801 }
802
803 // Read data
804 $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
805 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
806
807 // If user is not logged in, filter private links.
808 if (!$this->loggedin)
809 {
810 $toremove=array();
811 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
812 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
813 }
814
815 // Keep the list of the mapping URLs-->linkdate up-to-date.
816 $this->urls=array();
817 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
818 }
819
820 // Save database from memory to disk.
821 public function savedb()
822 {
823 if (!$this->loggedin) die('You are not authorized to change the database.');
824 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
825 invalidateCaches();
826 }
827
828 // Returns the link for a given URL (if it exists). False if it does not exist.
829 public function getLinkFromUrl($url)
830 {
831 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
832 return false;
833 }
834
835 // Case insensitive search among links (in the URLs, title and description). Returns filtered list of links.
836 // e.g. print_r($mydb->filterFulltext('hollandais'));
837 public function filterFulltext($searchterms)
838 {
839 // FIXME: explode(' ',$searchterms) and perform a AND search.
840 // FIXME: accept double-quotes to search for a string "as is"?
841 // Using mb_convert_case($val, MB_CASE_LOWER, 'UTF-8') allows us to perform searches on
842 // Unicode text. See https://github.com/shaarli/Shaarli/issues/75 for examples.
843 $filtered=array();
844 $s = mb_convert_case($searchterms, MB_CASE_LOWER, 'UTF-8');
845 foreach($this->links as $l)
846 {
847 $found= (strpos(mb_convert_case($l['title'], MB_CASE_LOWER, 'UTF-8'),$s) !== false)
848 || (strpos(mb_convert_case($l['description'], MB_CASE_LOWER, 'UTF-8'),$s) !== false)
849 || (strpos(mb_convert_case($l['url'], MB_CASE_LOWER, 'UTF-8'),$s) !== false)
850 || (strpos(mb_convert_case($l['tags'], MB_CASE_LOWER, 'UTF-8'),$s) !== false);
851 if ($found) $filtered[$l['linkdate']] = $l;
852 }
853 krsort($filtered);
854 return $filtered;
855 }
856
857 // Filter by tag.
858 // You can specify one or more tags (tags can be separated by space or comma).
859 // e.g. print_r($mydb->filterTags('linux programming'));
860 public function filterTags($tags,$casesensitive=false)
861 {
862 // Same as above, we use UTF-8 conversion to handle various graphemes (i.e. cyrillic, or greek)
863 // TODO: is $casesensitive ever true ?
864 $t = str_replace(',',' ',($casesensitive?$tags:mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8')));
865 $searchtags=explode(' ',$t);
866 $filtered=array();
867 foreach($this->links as $l)
868 {
869 $linktags = explode(' ',($casesensitive?$l['tags']:mb_convert_case($l['tags'], MB_CASE_LOWER, 'UTF-8')));
870 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
871 $filtered[$l['linkdate']] = $l;
872 }
873 krsort($filtered);
874 return $filtered;
875 }
876
877 // Filter by day. Day must be in the form 'YYYYMMDD' (e.g. '20120125')
878 // Sort order is: older articles first.
879 // e.g. print_r($mydb->filterDay('20120125'));
880 public function filterDay($day)
881 {
882 $filtered=array();
883 foreach($this->links as $l)
884 {
885 if (startsWith($l['linkdate'],$day)) $filtered[$l['linkdate']] = $l;
886 }
887 ksort($filtered);
888 return $filtered;
889 }
890 // Filter by smallHash.
891 // Only 1 article is returned.
892 public function filterSmallHash($smallHash)
893 {
894 $filtered=array();
895 foreach($this->links as $l)
896 {
897 if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow
898 {
899 $filtered[$l['linkdate']] = $l;
900 return $filtered;
901 }
902 }
903 return $filtered;
904 }
905
906 // Returns the list of all tags
907 // Output: associative array key=tags, value=0
908 public function allTags()
909 {
910 $tags=array();
911 foreach($this->links as $link)
912 foreach(explode(' ',$link['tags']) as $tag)
913 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
914 arsort($tags); // Sort tags by usage (most used tag first)
915 return $tags;
916 }
917
918 // Returns the list of days containing articles (oldest first)
919 // Output: An array containing days (in format YYYYMMDD).
920 public function days()
921 {
922 $linkdays=array();
923 foreach(array_keys($this->links) as $day)
924 {
925 $linkdays[substr($day,0,8)]=0;
926 }
927 $linkdays=array_keys($linkdays);
928 sort($linkdays);
929 return $linkdays;
930 }
931}
932
933// ------------------------------------------------------------------------------------------
934// Output the last N links in RSS 2.0 format. 689// Output the last N links in RSS 2.0 format.
935function showRSS() 690function showRSS()
936{ 691{
@@ -947,7 +702,7 @@ function showRSS()
947 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; } 702 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
948 703
949 // 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:
950 $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']); // Read links from database (and filter private links if user it not logged in).
951 706
952 // Optionally filter the results: 707 // Optionally filter the results:
953 $linksToDisplay=array(); 708 $linksToDisplay=array();
@@ -1022,7 +777,7 @@ function showATOM()
1022 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; } 777 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; }
1023 // If cached was not found (or not usable), then read the database and build the response: 778 // If cached was not found (or not usable), then read the database and build the response:
1024 779
1025 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 780 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
1026 781
1027 782
1028 // Optionally filter the results: 783 // Optionally filter the results:
@@ -1104,7 +859,7 @@ function showDailyRSS()
1104 $cache = new pageCache(pageUrl(),startsWith($query,'do=dailyrss') && !isLoggedIn()); 859 $cache = new pageCache(pageUrl(),startsWith($query,'do=dailyrss') && !isLoggedIn());
1105 $cached = $cache->cachedVersion(); if (!empty($cached)) { echo $cached; exit; } 860 $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: 861 // 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). 862 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
1108 863
1109 /* Some Shaarlies may have very few links, so we need to look 864 /* 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). 865 back in time (rsort()) until we have enough days ($nb_of_days).
@@ -1172,7 +927,7 @@ function showDailyRSS()
1172// "Daily" page. 927// "Daily" page.
1173function showDaily() 928function showDaily()
1174{ 929{
1175 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 930 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
1176 931
1177 932
1178 $day=Date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD. 933 $day=Date('Ymd',strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
@@ -1190,7 +945,6 @@ function showDaily()
1190 } 945 }
1191 946
1192 $linksToDisplay=$LINKSDB->filterDay($day); 947 $linksToDisplay=$LINKSDB->filterDay($day);
1193
1194 // We pre-format some fields for proper output. 948 // We pre-format some fields for proper output.
1195 foreach($linksToDisplay as $key=>$link) 949 foreach($linksToDisplay as $key=>$link)
1196 { 950 {
@@ -1239,7 +993,7 @@ function showDaily()
1239// Render HTML page (according to URL parameters and user rights) 993// Render HTML page (according to URL parameters and user rights)
1240function renderPage() 994function renderPage()
1241{ 995{
1242 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 996 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
1243 997
1244 // -------- Display login form. 998 // -------- Display login form.
1245 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=login')) 999 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=login'))
@@ -1817,7 +1571,7 @@ HTML;
1817function importFile() 1571function importFile()
1818{ 1572{
1819 if (!(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI'])) { die('Not allowed.'); } 1573 if (!(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI'])) { die('Not allowed.'); }
1820 $LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in). 1574 $LINKSDB = new LinkDB(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
1821 $filename=$_FILES['filetoupload']['name']; 1575 $filename=$_FILES['filetoupload']['name'];
1822 $filesize=$_FILES['filetoupload']['size']; 1576 $filesize=$_FILES['filetoupload']['size'];
1823 $data=file_get_contents($_FILES['filetoupload']['tmp_name']); 1577 $data=file_get_contents($_FILES['filetoupload']['tmp_name']);