WebsiteBaker Community Forum

WebsiteBaker Support (2.8.x) => Droplets & Snippets => Topic started by: crnogorac081 on January 29, 2010, 07:32:58 PM

Title: Searchbox with suggestions
Post by: crnogorac081 on January 29, 2010, 07:32:58 PM
Hi,

here is tutorial how to make a seaarch box with suggestions

Requires: JQuery

First, take a look at the demo (http://www.ulucg.me/) , try the search..

I used page_title for sugestions, but you can use any field you want.. For example if you populate keywords, or description fields for each(or some) pages, you can generate sugestions based on those fields..

How to make it:
1. Make a new php file in your root and name it suggestion.php and insert this code:

Quote
<?php
// First we prevent direct access
if(!isset($_POST['queryString'])) {
// nowwe redirect to index, if you are in subfolder use ../index.php
header( 'Location: index.php' ) ;
} else {
    // Now we set the path to config file
    require('config.php');
       
    global $database;
    global $wb;

    if(isset($_POST['queryString'])) {

//        $queryString = $_POST['queryString'];
$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

        // I used page_title field from pages. you can set or remove limit -- max number of sugestions
        $query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `page_title` LIKE '%$queryString%' LIMIT 20");
        if($query->numRows()  < 1) {
            // replace this text with: there is no suggestion, or whaatever
            echo '&nbsp;&nbsp;&nbsp;No suggestions';   
        } else {
            // now we can add some text like Here are suggestions
            echo '<span style="display:block; font-weight: bold; font-size: 80%; padding: 5px 5px; text-decoration: underline;">Suggestions:</span>';
            // now we loop thrue suggestions. style list via droplet
            echo '<ul>';
                    while ($result = $query->fetchRow()) {
                    $filename = str_replace(' ', '', strtolower($result['description']));
                        echo '<li onClick="fill(\''.addslashes($result['description']).'\');"><a href="'.WB_URL.PAGES_DIREC TORY.$result['link'].PAGE_EXTENSION.'">'.$result['page_title'].'</a></li>';
                        }
            echo '</ul>';
        }
    }
} // this ends else statement from the top of the page
?>
NOTE: 7th line from below is to long.. So when you copy-paste code you will get PAGES_DIRE C TORY, so you need to remove space in DIRECTORY word..
2. Make a droplet [[search]] (or name it whatever if you already have this droplet):

Quote
global $TEXT;
$return_value = " ";
if(SHOW_SEARCH) {
$scripta = "\n".'<script type="text/javascript">'."\n";
$scripta .= '    function lookup(inputString) {    '."\n";
$scripta .= '    if(inputString.length < 1) {    '."\n";  // after how menu letters script will react
$scripta .= '    $(\'#suggestions\').hide();    '."\n";
$scripta .= '    } else {    '."\n";
$scripta .= '    $.post("'.WB_URL.'/suggestion.php", {queryString: ""+inputString+""}, function(data){    '."\n";
$scripta .= '    if(data.length > 0) {    '."\n";
$scripta .= '    $(\'#suggestions\').show();    '."\n";
$scripta .= '    $(\'#autoSuggestionsList\').html(data);    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '    });    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '    function fill(thisValue) {    '."\n";
$scripta .= '    $(\'#inputString\').val(thisValue);    '."\n";
$scripta .= '    setTimeout("$(\'#suggestions\').hide();", 200);    '."\n";
$scripta .= '    }    '."\n";
$scripta .= '</script>    '."\n";
$scripta .= '<style type="text/css">'."\n";
$scripta .= '.suggestionsBox {    '."\n";
$scripta .= '    position: relative; '."\n";
$scripta .= '    left: 80px;    '."\n";
$scripta .= '    margin: 0px 0px 0px 0px;    '."\n";
$scripta .= '    width: 170px;    '."\n";
$scripta .= '    background-color: #fff;    '."\n";
$scripta .= '    -moz-border-radius: 7px;    '."\n";
$scripta .= '    -webkit-border-radius: 7px;    '."\n";
$scripta .= '    border: 2px solid #424242;    '."\n";
$scripta .= '    color: #333;    '."\n";
$scripta .= '}    '."\n";
$scripta .= '.suggestionList ul {    '."\n";
$scripta .= '    margin: 0px;    '."\n";
$scripta .= '    padding: 0px;    '."\n";
$scripta .= '    list-style-type: none;    '."\n";
$scripta .= '}    '."\n";
$scripta .= '.suggestionList li {    '."\n";
$scripta .= '    margin: 0px 0px 3px 0px;    '."\n";
$scripta .= '    padding: 3px;    '."\n";
$scripta .= '    cursor: pointer;     '."\n";
$scripta .= '}    '."\n";
$scripta .= '.suggestionList li:hover {    '."\n";
$scripta .= '     background-color: #f3f3f3;    '."\n";
$scripta .= '}    '."\n";
$scripta .= '</style>    '."\n";

$wb_page_data = str_replace('</head>',$scripta."\n".'</head>', $wb_page_data );

    $return_value  = '<form id="searchform" action="'.WB_URL.'/search/index'.PAGE_EXTENSION.'" method="post" >';
    $return_value  .= '<input class="button" name="dugme" type="submit" value=" " />';
    $return_value  .= '<input class="text" type="text" name="string" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" /> ';
    $return_value  .= '</form>';
    $return_value  .= '<div class="suggestionsBox" id="suggestions" style="display: none;">';
    $return_value  .= '    <div class="suggestionList" id="autoSuggestionsList">';
    $return_value  .= '    </div>';
    $return_value  .= '</div>';
}
return $return_value;

You can restyle list with css inside droplet.

There are a lot of comments if you want to use this module for some other projects..

If you put suggestion.php file inside some folder, you must change path to config.php file in suggestion.php file, and the path to suggestion.php file inside droplet..


Comments are welcome
have fun :)
Title: Re: Search box with suggestions
Post by: pcwacht on January 29, 2010, 08:25:14 PM
Demo looks neat

Will sure have a look at it.
Thanks.

John
Title: Re: Search box with suggestions
Post by: seagull on January 29, 2010, 09:34:40 PM
Used the code and the droplet, works ok! :lol:

First i overlooked the one "g" in the filename sugestion.php, i saved it first as suggestion.php
But for the rest, nice job.

Jan
Title: Re: Search box with suggestions
Post by: crnogorac081 on January 29, 2010, 09:52:20 PM
lol I misspelled it :D but Im glad it works and that you liked it :) I also added some opacity on demo site :)

= I corrected one g :)
Title: Re: Searchbox with suggestions
Post by: DarkViper on February 02, 2010, 01:10:37 AM
The module works as planned.

Yet here I am forced to issue a Security Warning!

The script 'suggestion.php' is insecure and an optimal target for SQL-Injections.
Each only halfway decent hacker, is thus in a position to change the database or delete them completely.


@ crnogorac081:: Please revise the parameter passing, so that no more undesirable values can reach the script.
already done..

Werner
( QA-Team )
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 02, 2010, 01:23:28 AM
I am not a coder, could you please help how to improve this from hacking ?

Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 02, 2010, 01:44:32 AM
Ok,

if I replace

$queryString = $_POST['queryString'];

with

$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

did I solved the problem ?
Title: Re: Searchbox with suggestions
Post by: DarkViper on February 02, 2010, 01:56:00 AM
i can give you a 'quick&dirty' solution:

Code: [Select]
$queryString = $_POST['queryString'];
if( preg_match('/;|UPDATE|DROP|DELETE|ALTER|\<SCRIPT.*\>|eval\(/si', $queryString)
{
    echo '&nbsp;&nbsp;&nbsp;Forbidden Request!!';
}
else
{
....

HTML-Entities are not the problem...except "<script...>...</script>. At max they can destroy the design for one view, nothing more. But you must proof that no modified or extended SQL-Statement can be executed. Much important: NEVER a semicolon should appear in the LIKE-clause. It would cancel the current SQL query and possibly execute others, which was added after the semicolon.
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 02, 2010, 02:05:17 AM
cool tnx,

but will this also prevent attack ?

$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

I belive with this code you cant modify SQL request as it will dissable special character, right ?
Title: Re: Searchbox with suggestions
Post by: DarkViper on February 02, 2010, 02:25:37 AM
Example for a SQL-Injection:

original query (after replace variables)
$queryString = 'dingdong';
SELECT * FROM `wb1_pages` WHERE `page_title` LIKE '%dingdong%' LIMIT 20")

a injected query:

$queryString = '\';DELETE FROM `wb1_pages`;';
SELECT * FROM `wb1_pages` WHERE `page_title` LIKE '%';DELETE FROM `wb1_pages`;%' LIMIT 20")

try this.. and your pages-table will be empty..  :evil:
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 02, 2010, 10:12:05 AM
Well I just tested your quoery on my live site and inserted this :

'\';DELETE FROM `ul_pages`;';

into searchbox, and table is still there :) so there is no SQL hack..

But, yestrday I added htmlspecialchars func. to

$queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);

So now it is ok for general use ?
Title: Re: Searchbox with suggestions
Post by: doc on February 02, 2010, 10:14:57 AM
@crnogorac081: Most likely because your server has magic_quotes_gpc enabled. This option automatically escapes critical characters from get, post, cookie array. Servers without this setting however would be vulnerable to the SQL injection posted by DarkViper.

Doc
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 02, 2010, 10:49:49 AM
@doc

Will this code: $queryString = htmlspecialchars($_POST['queryString'], ENT_QUOTES);  work to prevent DB hack on servers where magic quotes are disabled ?

If this code want work, please point me to the right direction..

Title: Re: Searchbox with suggestions
Post by: DarkViper on February 02, 2010, 11:18:38 AM
'\';DELETE FROM `ul_pages`;';
into searchbox, and table is still there :) so there is no SQL hack..
This was an extremely simple try... be sure, there are much more posibillities...

last night i posted a first solution (https://forum.WebsiteBaker.org/index.php/topic,16943.msg111739.html#msg111739) for your prob..
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 02, 2010, 11:25:38 AM
ok, but what if I have page_title named: Update or Updated, Alter Ego, or any word containing UPDATE, DROP, DELETE, ALTER or SCRIPT..

will your code print: Forbiden request ?
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 03, 2010, 12:04:45 PM
Also I tried this code to add slashes to DB call:

Code: [Select]
// Include WB functions file
        require_once(WB_PATH.'/framework/functions.php');

AND THEN:

$queryString = $wb->add_slashes($_POST['queryString']);

but then script want work.. does anyone know why ?
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on February 04, 2010, 10:08:50 PM
[[refresh]]  :-D
Title: Re: Searchbox with suggestions
Post by: finrodfelegund on March 29, 2010, 11:58:06 PM
i get this error , does anyone can help me. also if anyone can post the final look of the script with the security added!
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/coldhost/public_html/dorohoinews.ro/suggestion.php on line 30

thanks!!
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on March 30, 2010, 01:58:59 AM
Hi,

I got no erors, it is working stable, see the demo. Are you sure the code is copied well?

cheers
Title: Re: Searchbox with suggestions
Post by: finrodfelegund on March 30, 2010, 02:18:34 AM
i got error here:
                        echo '<li onClick="fill(\''.addslashes($result['description']).'\');"><a href="'.WB_URL.PAGES_DIREC TORY.$result['link'].PAGE_EXTENSION.'">'.$result['page_title'].'</a></li>';

i think there is something wrong with the url:
href="'.WB_URL.PAGES_DIREC TORY.$result['link'].PAGE_EXTENSION.'"

donno whats that DIREC TROY

hmm

i removed DIREC TROY and i get a weird redirection to pages:
http://dorohoinews.ro/pages/reducere-a-impozitului.php
take a look

i am trying your jq script also :)

in the end i did a ugly hack of the code:
echo '<li onClick="fill(\''.addslashes($result['description']).'\');"><a href="'.WB_URL.'/pages'.$result['link'].PAGE_EXTENSION.'">'.$result['page_title'] .'</a></li>';

this seem to work for me - for the moment :) if someone could tell me whats wrong there i will be happy.
Now only problem is that the list its not going above the page :(
Title: Re: Searchbox with suggestions
Post by: snark on April 28, 2010, 10:51:44 PM
when I put the code from the first post into a droplet I get a red droplet ...

Title: Re: Searchbox with suggestions
Post by: kweitzel on April 29, 2010, 06:46:34 AM
Quote
PAGES_DIREC TORY

looks like it should be:
Code: [Select]
PAGES_DIRECTORY
cheers

Klaus
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on April 29, 2010, 09:30:05 AM
Hi Klaus,

I copy-pasted the code and because of code container width text was braked..

Thanks for letting other know if droplet error appears..

cheers
Title: Re: Searchbox with suggestions
Post by: VSG on May 02, 2010, 05:37:13 PM
As much as I like the concept of it and the demo on your site, I can't get it to work.
although I simply copied your code (and corrected the DIREC TORY mishap) it wouldn't show any suggestions.

The java-error-console gives the following report:
Code: [Select]
Uncaught exception: ReferenceError: Undefined variable: $
Error thrown at line 6, column 4 in lookup(inputString) in http://MYSITE/pages/forum2.php:
    $.post("http://MYSITE/suggestion.php", {queryString: ""+inputString+""}, function(data){   
called from line 1, column 0 in <anonymous function>(event):
    lookup(this.value);

MYSITE stands for my correct website-address.
Any ideas? I'd really like to make this work. By the way, does it work if all the pages are hidden? (Not private, just hidden.)

You can look for yourself here (http://treffpunkt-kritik.de/pages/forum2.php).
Thanks in advance!
Best regards,
VSG
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on May 02, 2010, 09:40:02 PM
Hi mate,

there are no limitations regarding page visibility.

Regarding your issue (I forgot to mention, now I did in first post..), please add this line:

      <script type="text/javascript" src="<?php echo WB_URL; ?>/include/jquery/jquery-min.js"></script>

into your template's header.

all best,
Ivan
Title: Re: Searchbox with suggestions
Post by: VSG on May 03, 2010, 08:24:25 PM
Thanks, that did the trick!

Now I just have to customize it to blend it in with the website as my standard-search ... :)
Great idea!

Thanks again and best regards,
VSG
Title: Re: Searchbox with suggestions
Post by: VSG on May 03, 2010, 08:52:56 PM
One more question: is there a way to define a color for your suggestions? I can't seem to find it. Was able to define most of the colors though ...

Thanks in advance for any tip!
Best regards,
VSG
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on May 03, 2010, 08:58:55 PM
Hi,

the links use your standard link color from your css. If you want other color, you will have to style .suggestionList class

cheers
Title: Re: Searchbox with suggestions
Post by: nuke on July 25, 2011, 11:08:23 PM
Very cool - is there any way to limit the suggestions to a certain sub dir:
e.g. for my multilingual site I use the search_path value as /en/ to limit the search to just my English section, and do the same with my Spanish /es/ etc

(More info here:
https://forum.WebsiteBaker.org/index.php/topic,10058.msg59052.html#msg59052 )

How would I go about limiting the suggestions in a similar fashion? Thanks in advance,

-Michael
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on July 26, 2011, 11:13:05 PM
Hi,

try to replace
Code: [Select]
$query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `page_title` LIKE '%$queryString%' LIMIT 20");
WITH
$query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `language` = '".LANGUAGE."' `page_title` LIKE '%$queryString%' LIMIT 20");

in php file..
cheers
Title: Re: Searchbox with suggestions
Post by: nuke on July 27, 2011, 05:15:24 PM
Thanks for your prompt response crnogorac081. Apologies in advance, I'm probably missing something obvious, but I can't seem to get that code to work.

I tried replacing the line you mentioned with the following:
Code: [Select]
$query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `language` = '".LANGUAGE."' `page_title` LIKE '%$queryString%' LIMIT 20");
And it didn't work, so I thought maybe I have to specify the language, so I tried:
Code: [Select]
$query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `FR` = '".LANGUAGE."' `page_title` LIKE '%$queryString%' LIMIT 20");
then tried:
Code: [Select]
$query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `language` = '"FR"' `page_title` LIKE '%$queryString%' LIMIT 20");
then:
Code: [Select]
$query = $database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `language` = '".FR."' `page_title` LIKE '%$queryString%' LIMIT 20");
As you can tell I'm not a programmer =/, can you provide some assistance?

So I'm assuming there is no way to limit the suggestions based on the sub directory? I'll have to go through my multi-lang site and make sure each page has the correct specified language (in the meantime I've set a few sections to French... I have a fairly large site and was hoping there would be another way)

Thanks,
-Mike
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on July 28, 2011, 05:17:34 PM
Hi, create me a temp admin account and send me to PM, I will take a look
Title: Re: Searchbox with suggestions
Post by: crnogorac081 on September 23, 2011, 12:08:52 AM
Hi,

I have this code in /search/search_convert.php to show special chars in local language in standard search, and it works ok.
Code: [Select]
$t["š"] = array("š", "s");
$t["s"] = array("š", "s");
$t["đ"] = array("đ", "dj");
$t["dj"] = array("đ", "dj");
$t["č"] = array("č", "c");
$t["c"] = array("č", "ć");
$t["ć"] = array("c", "ć");
$t["ž"] = array("ž", "z");
$t["z"] = array("ž", "z");

In search suggestion SQL I have this code which works ok :
Code: [Select]
$database->query("SELECT * FROM `".TABLE_PREFIX."pages` WHERE `page_title` LIKE '%$queryString%' LIMIT 20");

What I need is help to combine these two..could someone give me a hint or help ?

for example it title is: my name is saša , if I type both sasa or saša to work.

cheers,
Ivan