aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
authorSeb Sauvage <sebsauvage@sebsauvage.net>2011-09-23 15:10:18 +0200
committerEmilien Klein <emilien@klein.st>2011-09-23 15:10:18 +0200
commitf4aba1ac2f3730ae8b73c98aa0fc612fe9d099c5 (patch)
tree35d5bfcbb134b9c4051f8cc84017d64a63f3e61c /index.php
parente6a0ab545d7eb8ca4a2b0ecf746b2f03d3cc67c1 (diff)
downloadShaarli-f4aba1ac2f3730ae8b73c98aa0fc612fe9d099c5.tar.gz
Shaarli-f4aba1ac2f3730ae8b73c98aa0fc612fe9d099c5.tar.zst
Shaarli-f4aba1ac2f3730ae8b73c98aa0fc612fe9d099c5.zip
Version 0.0.17 beta:
- New: Change password screen added (based on a patch by killruana). - New: Autocomplete in the tag search form. - New: You can rename or delete a tag in all links (very handy if you misspelled a tag or want to merge tags). - New: When you click the RSS feed, the feed will be filtered with the same filters as the page you were viewing. - Changed: CSS adjustments by jerrywham. - Changed: Minor corrections.
Diffstat (limited to 'index.php')
-rw-r--r--index.php189
1 files changed, 153 insertions, 36 deletions
diff --git a/index.php b/index.php
index b5915ec3..af76ed9b 100644
--- a/index.php
+++ b/index.php
@@ -1,5 +1,5 @@
1<?php 1<?php
2// Shaarli 0.0.16 beta - Shaare your links... 2// Shaarli 0.0.17 beta - Shaare your links...
3// The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net 3// The personal, minimalist, super-fast, no-database delicious clone. By sebsauvage.net
4// http://sebsauvage.net/wiki/doku.php?id=php:shaarli 4// http://sebsauvage.net/wiki/doku.php?id=php:shaarli
5// Licence: http://www.opensource.org/licenses/zlib-license.php 5// Licence: http://www.opensource.org/licenses/zlib-license.php
@@ -33,6 +33,7 @@ checkphpversion();
33error_reporting(E_ALL^E_WARNING); // See all error except warnings. 33error_reporting(E_ALL^E_WARNING); // See all error except warnings.
34//error_reporting(-1); // See all errors (for debugging only) 34//error_reporting(-1); // See all errors (for debugging only)
35ob_start(); 35ob_start();
36
36// In case stupid admin has left magic_quotes enabled in php.ini: 37// In case stupid admin has left magic_quotes enabled in php.ini:
37if (get_magic_quotes_gpc()) 38if (get_magic_quotes_gpc())
38{ 39{
@@ -46,7 +47,7 @@ header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
46header("Cache-Control: no-store, no-cache, must-revalidate"); 47header("Cache-Control: no-store, no-cache, must-revalidate");
47header("Cache-Control: post-check=0, pre-check=0", false); 48header("Cache-Control: post-check=0, pre-check=0", false);
48header("Pragma: no-cache"); 49header("Pragma: no-cache");
49define('shaarli_version','0.0.16 beta'); 50define('shaarli_version','0.0.17 beta');
50if (!is_dir(DATADIR)) { mkdir(DATADIR,0705); chmod(DATADIR,0705); } 51if (!is_dir(DATADIR)) { mkdir(DATADIR,0705); chmod(DATADIR,0705); }
51if (!is_file(DATADIR.'/.htaccess')) { file_put_contents(DATADIR.'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files. 52if (!is_file(DATADIR.'/.htaccess')) { file_put_contents(DATADIR.'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
52if (!is_file(CONFIG_FILE)) install(); 53if (!is_file(CONFIG_FILE)) install();
@@ -93,10 +94,8 @@ function checkUpdate()
93// Log to text file 94// Log to text file
94function logm($message) 95function logm($message)
95{ 96{
96 if (!file_exists(DATADIR.'/log.txt')) {$logFile = fopen(DATADIR.'/log.txt','w'); } 97 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
97 else { $logFile = fopen(DATADIR.'/log.txt','a'); } 98 file_put_contents(DATADIR.'/log.txt',$t,FILE_APPEND);
98 fwrite($logFile,strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n");
99 fclose($logFile);
100} 99}
101 100
102// ------------------------------------------------------------------------------------------ 101// ------------------------------------------------------------------------------------------
@@ -310,7 +309,7 @@ function linkdate2rfc822($linkdate)
310 309
311/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format. 310/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
312 (used to display link date on screen) 311 (used to display link date on screen)
313 The date format is automatically chose according to locale/languages sniffed from browser headers (see autoLocale()). */ 312 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
314function linkdate2locale($linkdate) 313function linkdate2locale($linkdate)
315{ 314{
316 return utf8_encode(strftime('%c',linkdate2timestamp($linkdate))); // %c is for automatic date format according to locale. 315 return utf8_encode(strftime('%c',linkdate2timestamp($linkdate))); // %c is for automatic date format according to locale.
@@ -476,6 +475,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
476 { 475 {
477 // Read data 476 // Read data
478 $this->links=(file_exists(DATASTORE) ? unserialize(gzinflate(base64_decode(substr(file_get_contents(DATASTORE),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() ); 477 $this->links=(file_exists(DATASTORE) ? unserialize(gzinflate(base64_decode(substr(file_get_contents(DATASTORE),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
478 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
479 479
480 // If user is not logged in, filter private links. 480 // If user is not logged in, filter private links.
481 if (!$this->loggedin) 481 if (!$this->loggedin)
@@ -505,7 +505,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
505 } 505 }
506 506
507 // Case insentitive search among links (in url, title and description). Returns filtered list of links. 507 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
508 // eg. print_r($mydb->filterTags('hollandais')); 508 // eg. print_r($mydb->filterFulltext('hollandais'));
509 public function filterFulltext($searchterms) 509 public function filterFulltext($searchterms)
510 { 510 {
511 // FIXME: explode(' ',$searchterms) and perform a AND search. 511 // FIXME: explode(' ',$searchterms) and perform a AND search.
@@ -524,14 +524,14 @@ class linkdb implements Iterator, Countable, ArrayAccess
524 // Filter by tag. 524 // Filter by tag.
525 // You can specify one or more tags (tags can be separated by space or comma). 525 // You can specify one or more tags (tags can be separated by space or comma).
526 // eg. print_r($mydb->filterTags('linux programming')); 526 // eg. print_r($mydb->filterTags('linux programming'));
527 public function filterTags($tags) 527 public function filterTags($tags,$casesensitive=false)
528 { 528 {
529 $t = str_replace(',',' ',strtolower($tags)); 529 $t = str_replace(',',' ',($casesensitive?$tags:strtolower($tags)));
530 $searchtags=explode(' ',$t); 530 $searchtags=explode(' ',$t);
531 $filtered=array(); 531 $filtered=array();
532 foreach($this->links as $l) 532 foreach($this->links as $l)
533 { 533 {
534 $linktags = explode(' ',strtolower($l['tags'])); 534 $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags'])));
535 if (count(array_intersect($linktags,$searchtags)) == count($searchtags)) 535 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
536 $filtered[$l['linkdate']] = $l; 536 $filtered[$l['linkdate']] = $l;
537 } 537 }
@@ -549,8 +549,7 @@ class linkdb implements Iterator, Countable, ArrayAccess
549 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1); 549 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
550 arsort($tags); // Sort tags by usage (most used tag first) 550 arsort($tags); // Sort tags by usage (most used tag first)
551 return $tags; 551 return $tags;
552 } 552 }
553
554} 553}
555 554
556// ------------------------------------------------------------------------------------------ 555// ------------------------------------------------------------------------------------------
@@ -562,7 +561,7 @@ function showRSS()
562 // Optionnaly filter the results: 561 // Optionnaly filter the results:
563 $linksToDisplay=array(); 562 $linksToDisplay=array();
564 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); 563 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
565 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags($_GET['searchtags']); 564 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
566 else $linksToDisplay = $LINKSDB; 565 else $linksToDisplay = $LINKSDB;
567 566
568 header('Content-Type: application/xhtml+xml; charset=utf-8'); 567 header('Content-Type: application/xhtml+xml; charset=utf-8');
@@ -627,7 +626,7 @@ function renderPage()
627 if (startswith($_SERVER["QUERY_STRING"],'do=tagcloud')) 626 if (startswith($_SERVER["QUERY_STRING"],'do=tagcloud'))
628 { 627 {
629 $tags= $LINKSDB->allTags(); 628 $tags= $LINKSDB->allTags();
630 // We sort tags alphabetically, when choose a font size according to count. 629 // We sort tags alphabetically, then choose a font size according to count.
631 // First, find max value. 630 // First, find max value.
632 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value); 631 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value);
633 ksort($tags); 632 ksort($tags);
@@ -651,7 +650,7 @@ function renderPage()
651 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query. 650 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
652 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER 651 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
653 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params); 652 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
654 $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags'].' '.urlencode($_GET['addtag']))); 653 $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags']).' '.urlencode(trim($_GET['addtag'])));
655 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different) 654 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
656 header('Location: ?'.http_build_query($params)); 655 header('Location: ?'.http_build_query($params));
657 exit; 656 exit;
@@ -698,10 +697,10 @@ function renderPage()
698 $searchform=<<<HTML 697 $searchform=<<<HTML
699<div id="headerform" style="width:100%; white-space:nowrap;";> 698<div id="headerform" style="width:100%; white-space:nowrap;";>
700 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form> 699 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
701 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form> 700 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
702</div> 701</div>
703HTML; 702HTML;
704 $onload = 'document.searchform.searchterm.focus();'; 703 $onload = 'onload="document.searchform.searchterm.focus();"';
705 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload); 704 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload);
706 templatePage($data); 705 templatePage($data);
707 exit; // Never remove this one ! 706 exit; // Never remove this one !
@@ -714,8 +713,11 @@ HTML;
714 { 713 {
715 $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ? 714 $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ?
716 // The javascript code for the bookmarklet: 715 // The javascript code for the bookmarklet:
716 $changepwd = (OPEN_SHAARLI ? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
717 $toolbar= <<<HTML 717 $toolbar= <<<HTML
718<div id="headerform"><br> 718<div id="headerform"><br>
719 {$changepwd}
720 <a href="?do=changetag"><b>Rename/delete tags</b></a> - Rename or delete a tag in all links.<br><br>
719 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br> 721 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
720 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br> 722 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
721 <a class="smallbutton" style="color:black;" onclick="alert('Drag this link to your bookmarks toolbar, or right-click it and choose Bookmark This Link...');return false;" href="javascript:javascript:(function(){var%20url%20=%20location.href;var%20title%20=%20document.title%20||%20url;window.open('{$pageabsaddr}?post='%20+%20encodeURIComponent(url)+'&amp;title='%20+%20encodeURIComponent(title)+'&amp;source=bookmarklet','_blank','menubar=no,height=400,width=608,toolbar=no,scrollbars=no,status=no');})();">Shaare link</a> - Drag this link to your bookmarks toolbar (or right-click it and choose Bookmark This Link....). Then click "Shaare link" button in any page you want to share.<br><br> 723 <a class="smallbutton" style="color:black;" onclick="alert('Drag this link to your bookmarks toolbar, or right-click it and choose Bookmark This Link...');return false;" href="javascript:javascript:(function(){var%20url%20=%20location.href;var%20title%20=%20document.title%20||%20url;window.open('{$pageabsaddr}?post='%20+%20encodeURIComponent(url)+'&amp;title='%20+%20encodeURIComponent(title)+'&amp;source=bookmarklet','_blank','menubar=no,height=400,width=608,toolbar=no,scrollbars=no,status=no');})();">Shaare link</a> - Drag this link to your bookmarks toolbar (or right-click it and choose Bookmark This Link....). Then click "Shaare link" button in any page you want to share.<br><br>
@@ -725,11 +727,107 @@ HTML;
725 templatePage($data); 727 templatePage($data);
726 exit; 728 exit;
727 } 729 }
730
731 // -------- User wants to change his/her password.
732 if (startswith($_SERVER["QUERY_STRING"],'do=changepasswd'))
733 {
734 if (OPEN_SHAARLI) die('You are not supposed to change a password on an Open Shaarli.');
735 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
736 {
737 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
738
739 // Make sure old password is correct.
740 $oldhash = sha1($_POST['oldpassword'].$GLOBALS['login'].$GLOBALS['salt']);
741 if ($oldhash!=$GLOBALS['hash']) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; }
742
743 // Save new password
744 $salt=sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
745 $hash = sha1($_POST['setpassword'].$GLOBALS['login'].$salt);
746 $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($hash,true).'; $GLOBALS[\'salt\']='.var_export($salt,true).'; date_default_timezone_set('.var_export(date_default_timezone_get(),true).'); ?>';
747 if (!file_put_contents(CONFIG_FILE,$config) || strcmp(file_get_contents(CONFIG_FILE),$config)!=0)
748 {
749 echo '<script language="JavaScript">alert("Shaarli could not create the config file. Please make sure Shaarli has the right to write in the folder is it installed in.");document.location=\'?\';</script>';
750 exit;
751 }
752 echo '<script language="JavaScript">alert("Your password has been changed.");document.location=\'?do=tools\';</script>';
753 exit;
754 }
755 else
756 {
757 $token = getToken();
758 $changepwdform= <<<HTML
759<form method="POST" action="" name="changepasswordform" style="padding:10 10 10 10;">
760Old password: <input type="password" name="oldpassword">&nbsp; &nbsp;
761New password: <input type="password" name="setpassword">
762<input type="hidden" name="token" value="{$token}">
763<input type="submit" name="Save" value="Save password" class="bigbutton"></form>
764HTML;
765 $data = array('pageheader'=>$changepwdform,'body'=>'','onload'=>'onload="document.changepasswordform.oldpassword.focus();"');
766 templatePage($data);
767 exit;
768 }
769 }
770
771 // -------- User wants to rename a tag or delete it
772 if (startswith($_SERVER["QUERY_STRING"],'do=changetag'))
773 {
774 if (empty($_POST['fromtag']))
775 {
776 $token = getToken();
777 $changetagform = <<<HTML
778<form method="POST" action="" name="changetag" style="padding:10 10 10 10;">
779<input type="hidden" name="token" value="{$token}">
780Tag: <input type="text" name="fromtag" id="fromtag">
781<input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">
782&nbsp;&nbsp;or&nbsp; <input type="submit" name="deletetag" value="Delete tag" class="bigbutton" onClick="return confirmDeleteTag();"><br>(Case sensitive)</form>
783<script language="JavaScript">function confirmDeleteTag() { var agree=confirm("Are you sure you want to delete this tag from all links ?"); if (agree) return true ; else return false ; }</script>
784HTML;
785 $data = array('pageheader'=>$changetagform,'body'=>'','onload'=>'onload="document.changetag.fromtag.focus();"');
786 templatePage($data);
787 exit;
788 }
789 if (!tokenOk($_POST['token'])) die('Wrong token.');
790
791 if (!empty($_POST['deletetag']) && !empty($_POST['fromtag']))
792 {
793 $needle=trim($_POST['fromtag']);
794 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
795 foreach($linksToAlter as $key=>$value)
796 {
797 $tags = explode(' ',trim($value['tags']));
798 unset($tags[array_search($needle,$tags)]); // Remove tag.
799 $value['tags']=trim(implode(' ',$tags));
800 $LINKSDB[$key]=$value;
801 }
802 $LINKSDB->savedb(); // save to disk
803 invalidateCaches();
804 echo '<script language="JavaScript">alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>';
805 exit;
806 }
807
808 // Rename a tag:
809 if (!empty($_POST['renametag']) && !empty($_POST['fromtag']) && !empty($_POST['totag']))
810 {
811 $needle=trim($_POST['fromtag']);
812 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
813 foreach($linksToAlter as $key=>$value)
814 {
815 $tags = explode(' ',trim($value['tags']));
816 $tags[array_search($needle,$tags)] = trim($_POST['totag']); // Remplace tags value.
817 $value['tags']=trim(implode(' ',$tags));
818 $LINKSDB[$key]=$value;
819 }
820 $LINKSDB->savedb(); // save to disk
821 invalidateCaches();
822 echo '<script language="JavaScript">alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
823 exit;
824 }
825 }
728 826
729 // -------- User wants to add a link without using the bookmarklet: show form. 827 // -------- User wants to add a link without using the bookmarklet: show form.
730 if (startswith($_SERVER["QUERY_STRING"],'do=addlink')) 828 if (startswith($_SERVER["QUERY_STRING"],'do=addlink'))
731 { 829 {
732 $onload = 'document.addform.post.focus();'; 830 $onload = 'onload="document.addform.post.focus();"';
733 $addform= '<div id="headerform"><form method="GET" action="" name="addform"><input type="text" name="post" style="width:70%;"> <input type="submit" value="Add link" class="bigbutton"></div>'; 831 $addform= '<div id="headerform"><form method="GET" action="" name="addform"><input type="text" name="post" style="width:70%;"> <input type="submit" value="Add link" class="bigbutton"></div>';
734 $data = array('pageheader'=>$addform,'body'=>'','onload'=>$onload); 832 $data = array('pageheader'=>$addform,'body'=>'','onload'=>$onload);
735 templatePage($data); 833 templatePage($data);
@@ -899,12 +997,12 @@ HTML;
899<div id="headerform"> 997<div id="headerform">
900Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes). 998Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
901<form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform"> 999<form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
902 <input type="hidden" name="token" value="{$token}"> 1000 <input type="hidden" name="token" value="{$token}">
903 <input type="file" name="filetoupload" size="80"> 1001 <input type="file" name="filetoupload" size="80">
904 <input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}"> 1002 <input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}">
905 <input type="submit" name="import_file" value="Import" class="bigbutton"><br> 1003 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
906 <input type="checkbox" name="private">&nbsp;Import all links as private<br> 1004 <input type="checkbox" name="private">&nbsp;Import all links as private<br>
907 <input type="checkbox" name="overwrite">&nbsp;Overwrite existing links 1005 <input type="checkbox" name="overwrite">&nbsp;Overwrite existing links
908</form> 1006</form>
909</div> 1007</div>
910HTML; 1008HTML;
@@ -917,10 +1015,10 @@ HTML;
917 $searchform=<<<HTML 1015 $searchform=<<<HTML
918<div id="headerform" style="width:100%; white-space:nowrap;";> 1016<div id="headerform" style="width:100%; white-space:nowrap;";>
919 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form> 1017 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
920 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form> 1018 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" id="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
921</div> 1019</div>
922HTML; 1020HTML;
923 $onload = 'document.searchform.searchterm.focus();'; 1021 $onload = 'onload="document.searchform.searchterm.focus();"';
924 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload); 1022 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload);
925 templatePage($data); 1023 templatePage($data);
926 exit; 1024 exit;
@@ -1044,13 +1142,13 @@ function templateLinkList()
1044 $searched=''; 1142 $searched='';
1045 if (!empty($_GET['searchterm'])) // Fulltext search 1143 if (!empty($_GET['searchterm'])) // Fulltext search
1046 { 1144 {
1047 $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); 1145 $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm']));
1048 $searched='&nbsp;<b>'.count($linksToDisplay).' results for <i>'.htmlspecialchars($_GET['searchterm']).'</i></b>:'; 1146 $searched='&nbsp;<b>'.count($linksToDisplay).' results for <i>'.htmlspecialchars(trim($_GET['searchterm'])).'</i></b>:';
1049 } 1147 }
1050 elseif (!empty($_GET['searchtags'])) // Search by tag 1148 elseif (!empty($_GET['searchtags'])) // Search by tag
1051 { 1149 {
1052 $linksToDisplay = $LINKSDB->filterTags($_GET['searchtags']); 1150 $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
1053 $tagshtml=''; foreach(explode(' ',$_GET['searchtags']) as $tag) $tagshtml.='<span class="linktag" title="Remove tag"><a href="?removetag='.htmlspecialchars($tag).'">'.htmlspecialchars($tag).' <span style="border-left:1px solid #aaa; padding-left:5px; color:#6767A7;">x</span></a></span> '; 1151 $tagshtml=''; foreach(explode(' ',trim($_GET['searchtags'])) as $tag) $tagshtml.='<span class="linktag" title="Remove tag"><a href="?removetag='.htmlspecialchars($tag).'">'.htmlspecialchars($tag).' <span style="border-left:1px solid #aaa; padding-left:5px; color:#6767A7;">x</span></a></span> ';
1054 $searched='&nbsp;<b>'.count($linksToDisplay).' results for tags '.$tagshtml.':</b>'; 1152 $searched='&nbsp;<b>'.count($linksToDisplay).' results for tags '.$tagshtml.':</b>';
1055 } 1153 }
1056 else 1154 else
@@ -1128,7 +1226,8 @@ function templatePage($data)
1128 $open='Open '; 1226 $open='Open ';
1129 } 1227 }
1130 else 1228 else
1131 $menu=(isLoggedIn() ? ' <a href="?do=logout">Logout</a> &nbsp;<a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>' : ' <a href="?do=login">Login</a>'); 1229 $menu=(isLoggedIn() ? ' <a href="?do=logout">Logout</a> &nbsp;<a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>' : ' <a href="?do=login">Login</a>');
1230
1132 foreach(array('pageheader','body','onload') as $k) // make sure all required fields exist (put an empty string if not). 1231 foreach(array('pageheader','body','onload') as $k) // make sure all required fields exist (put an empty string if not).
1133 { 1232 {
1134 if (!array_key_exists($k,$data)) $data[$k]=''; 1233 if (!array_key_exists($k,$data)) $data[$k]='';
@@ -1137,17 +1236,22 @@ function templatePage($data)
1137 if (OPEN_SHAARLI || isLoggedIn()) 1236 if (OPEN_SHAARLI || isLoggedIn())
1138 { 1237 {
1139 $jsincludes='<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>'; 1238 $jsincludes='<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>';
1140 $source = serverUrl().$_SERVER['SCRIPT_NAME'].'?ws=tags'; 1239 $source = serverUrl().$_SERVER['SCRIPT_NAME'];
1141 $jsincludes_bottom = <<<JS 1240 $jsincludes_bottom = <<<JS
1142<script language="JavaScript"> 1241<script language="JavaScript">
1143$(document).ready(function() 1242$(document).ready(function()
1144{ 1243{
1145 $('#lf_tags').autocomplete({source:'{$source}',minLength:0}); 1244 $('#lf_tags').autocomplete({source:'{$source}?ws=tags',minLength:1});
1146}); 1245 $('#searchtags').autocomplete({source:'{$source}?ws=tags',minLength:1});
1147</script> 1246 $('#fromtag').autocomplete({source:'{$source}?ws=singletag',minLength:1});
1247});
1248</script>
1148JS; 1249JS;
1149 } 1250 }
1150 $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss'); 1251 $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss');
1252 if (!empty($_GET['searchtags'])) $feedurl.='&searchtags='.$_GET['searchtags'];
1253 elseif (!empty($_GET['searchterm'])) $feedurl.='&searchterm='.$_GET['searchterm'];
1254
1151 echo <<<HTML 1255 echo <<<HTML
1152<html> 1256<html>
1153<head> 1257<head>
@@ -1223,7 +1327,7 @@ function processWS()
1223 global $LINKSDB; 1327 global $LINKSDB;
1224 header('Content-Type: application/json; charset=utf-8'); 1328 header('Content-Type: application/json; charset=utf-8');
1225 1329
1226 // Search in tags 1330 // Search in tags (case insentitive, cumulative search)
1227 if ($_GET['ws']=='tags') 1331 if ($_GET['ws']=='tags')
1228 { 1332 {
1229 $tags=explode(' ',$term); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d") 1333 $tags=explode(' ',$term); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
@@ -1238,6 +1342,19 @@ function processWS()
1238 echo json_encode(array_keys($suggested)); 1342 echo json_encode(array_keys($suggested));
1239 exit; 1343 exit;
1240 } 1344 }
1345
1346 // Search a single tag (case sentitive, single tag search)
1347 if ($_GET['ws']=='singletag')
1348 {
1349 /* To speed up things, we store list of tags in session */
1350 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1351 foreach($_SESSION['tags'] as $key=>$value)
1352 {
1353 if (startsWith($key,$term,$case=true)) $suggested[$key]=0;
1354 }
1355 echo json_encode(array_keys($suggested));
1356 exit;
1357 }
1241} 1358}
1242 1359
1243// Invalidate caches when the database is changed or the user logs out. 1360// Invalidate caches when the database is changed or the user logs out.