OSC Search Enhancements v1.3
______________________



Tested and should work on installs up to osCommerce 2.2 Milestone 2 Update 051113
Please post questions/comments for this update in the OSC-forum: http://forums.oscommerce.com/index.php?showtopic=59309
______________________

CHANGE LOG
______________________

v1.3 Change found at form http://osdir.com/ml/web.oscommerce.tips/2003-05/msg00111.html
A quick change to the code to make it more compliant with osC standards, namely
to use the tep_href_link() function and so avoid losing any sessions...

v1.2 Adam B. (contact myr.jedi@gmail.com)
- Added full support for Opera web browser on admin page.
- Fixed "NAVBAR_TITLE1" typo in readme.txt.
- Fixed bug on admin page opening the clicked keyword search in the current page.  It now opens in new page only.
- Clicking on keywords on admin page will no longer be counted as searches.

v1.1c Carine B.
- fixed admin keywords bug for search terms with quotation marks (added addslashes in the update section), 
  also only delete the search term, and not all search terms in the while loop

v1.1 Keith W.
- Update to fix bug where if you had one term in admin keywords and it's exact opposite listed it would give you the same search term back. For example if I had dog = cat and then cat = dog in my backend and I search for dog I would get dog again. Now this has been fixed.
- Update to modify the text displayed after a search and to add back the 's' for the customer to see if it was taken off for the search. (cosmetic only, it still searches for terms without the 's')

Up to v1.0 2003-09-22 
Original Contribution by Paul Whiter & v1.0 by Jakob Biegel
______________________

Amongst other things, this contribution provides the ability to fine-tune your site search results over time to allow you to dish up very accurate search results to your customers whatever keywords they search on.

Contribution provides:

1) Automatic logging of all search terms used on your site.

2) Processing of logged search terms into total counts, with sorting by totals or by name.

3) Admin page provides a Google type facility whereby you can add words or phrases and their suggested replacements to a database table, once you've added data to this table if for example a customer searches for 'wheal' a line is added to the top of the search results page saying: 'you could also try: wheel'. This line is a clickable link that automatically re-searches on the replacement words. For this feature to work you must have made an entry via the admin page for the particular word/phrase used as well as the suggested replacement, obviously this data will take a little time to build up, this is the reason for the keyword logging, so as you can periodically check to see what needs adding to the replacements table.

4) Words/phrases and their suggested replacements can be added/edited/deleted at any time via the admin section.

5) Improved layout of Search results page if no results are found, providing the user with some tips on better searching.

6) Complete admin section to view and process logged search results.

7) When searching, any keywords entered as a plural will automatically have the final 's' stripped from the keyword, this should help if you have your products named/described in the singular form. A benefit of this is that even if there *should* be an 's' on the end of the keyword the correct results will be brought up due to the in-built partial matching of the osC search facility.


TIP: Don't forget that you can alter the default search operator within the admin section of osC between 'AND' & 'OR'
This is under: 'Configuration/My Store/Default Search Operator'. It would be a good idea to use this to find which operator works best for you.
-----------------------------------------------------------------
TO DO LIST
-----------------------------------------------------------------
- It would be great if someone could post a modification so more than one search suggestion is displayed if there are more available.
- Another neat feature would be if it would display categories that matched the search terms.
-----------------------------------------------------------------

For an extra-enhanced search facility I would also recommend that you install 2 other search related contributions, links below:

----
Search results with Highlights - By: Robert Hellemans

http://www.oscommerce.com/community/contributions,1086

----
Custom Quick Search - By: Mattice

http://www.oscommerce.com/community/contributions,1036

-----------------------------------------------------------------
UPGRADERS from v1.* 

Just overwrite the old code in advanced_search_result.php and english/advanced_search.php
___________________________________

NEW INSTALLS -> Search enhancements INSTALL INSTRUCTIONS

-----------------------------------------------------------------

BACKUP ALL FILES BEFORE STARTING - I AM NOT RESPONSIBLE FOR ANY PROBLEMS CAUSED.

********-BACKUP FIRST-*********


1)  Using phpMyAdmin or similar run the following sql queries, or use the included sql file.
 
CREATE TABLE `search_queries` (
  `search_id` int(11) NOT NULL auto_increment,
  `search_text` tinytext,
  PRIMARY KEY  (`search_id`)
) TYPE=MyISAM AUTO_INCREMENT=24 ;

CREATE TABLE `search_queries_sorted` (
  `search_id` smallint(6) NOT NULL auto_increment,
  `search_text` tinytext NOT NULL,
  `search_count` int(11) NOT NULL default '0',
  PRIMARY KEY  (`search_id`)
) TYPE=MyISAM AUTO_INCREMENT=134 ;

CREATE TABLE `searchword_swap` (
  `sws_id` mediumint(11) NOT NULL auto_increment,
  `sws_word` varchar(100) NOT NULL default '',
  `sws_replacement` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`sws_id`)
) TYPE=MyISAM AUTO_INCREMENT=28 ;


__________________________________________________________________

2) catalog/advanced_search_result.php

FIND: 


*/

  require('includes/application_top.php');

  require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_ADVANCED_SEARCH);



Below ADD:

// Search enhancement mod start
// Start of change from previous version v1.2 of MOD
if (!empty($_GET['keywords']))  {
	if(isset($_GET['keywords']) && $_GET['keywords'] != ''){
		$pwstr_check = strtolower(substr($_GET['keywords'], strlen($_GET['keywords'])-1, strlen($_GET['keywords'])));
	if($pwstr_check == 's'){
		$pwstr_replace = substr($_GET['keywords'], 0, strlen($_GET['keywords'])-1);
		header('location: ' . tep_href_link(FILENAME_ADVANCED_SEARCH_RESULT , 'keywords=' . urlencode($pwstr_replace) . '&search_in_description=1' ));
		exit;
	}
        }
// End of change from previous version v1.2 of MOD

       $pw_keywords = explode(' ',stripslashes(strtolower($_GET['keywords'])));
       $pw_replacement_words = $pw_keywords;
       $pw_boldwords = $pw_keywords;
       $sql_words = tep_db_query("SELECT * FROM searchword_swap");
       $pw_replacement = '';
       while ($sql_words_result = tep_db_fetch_array($sql_words)) {
       	   if(stripslashes(strtolower($_GET['keywords'])) == stripslashes(strtolower($sql_words_result['sws_word']))){
       	       $pw_replacement = stripslashes($sql_words_result['sws_replacement']);
       	       $pw_link_text = '<b><i>' . stripslashes($sql_words_result['sws_replacement']) . '</i></b>';
       	       $pw_phrase = 1;
       	       $pw_mispell = 1;
       	       break;
       	   }
           for($i=0; $i<sizeof($pw_keywords); $i++){
               if($pw_keywords[$i]  == stripslashes(strtolower($sql_words_result['sws_word']))){
               	   $pw_replacement_words[$i] = stripslashes($sql_words_result['sws_replacement']);
                   $pw_boldwords[$i] = '<b><i>' . stripslashes($sql_words_result['sws_replacement']) . '</i></b>';
                   $pw_mispell = 1;
                   break;
               }
           }
       }
       if(!isset($pw_phrase)){
           for($i=0; $i<sizeof($pw_keywords); $i++){
               $pw_replacement .= $pw_replacement_words[$i] . ' ';
       	       $pw_link_text   .= $pw_boldwords[$i]. ' ';
           }
       }
       
       $pw_replacement = trim($pw_replacement);
       $pw_link_text   = trim($pw_link_text);
       $pw_string      = '<br><span class="main"><font color="red">' . TEXT_REPLACEMENT_SUGGESTION . '</font><a href="' . tep_href_link( FILENAME_ADVANCED_SEARCH_RESULT , 'keywords=' . urlencode($pw_replacement) . '&search_in_description=1' ) . '">' . $pw_link_text . '</a></span><br><br>';
        
}
// Search enhancement mod end


FIND:
          <tr>
            <td class="pageHeading"><?php echo HEADING_TITLE_2; ?></td>
            <td class="pageHeading" align="right"><?php echo tep_image(DIR_WS_IMAGES . 'table_background_browse.gif', HEADING_TITLE_2, HEADING_IMAGE_WIDTH, HEADING_IMAGE_HEIGHT); ?></td>
          </tr>
          
BELOW ADD:
	
	<tr>
            <td class="main"><p>
            <?php if (isset($HTTP_GET_VARS['plural']) && ($HTTP_GET_VARS['plural'] == '1')) {
            	  	echo TEXT_REPLACEMENT_SEARCH_RESULTS . ' <b><i>' . stripslashes($_GET['keywords']) . 's</i></b>';
             	  } else {
            		echo TEXT_REPLACEMENT_SEARCH_RESULTS . ' <b><i>' . stripslashes($_GET['keywords']) . '</i></b>';
             	  }
            ?></p></td>
          </tr>
          

FIND:

  $breadcrumb->add(NAVBAR_TITLE_1, tep_href_link(FILENAME_ADVANCED_SEARCH));
  $breadcrumb->add(NAVBAR_TITLE_2, tep_href_link(FILENAME_ADVANCED_SEARCH_RESULT, tep_get_all_get_params(), 'NONSSL', true, false));?>

ABOVE ADD:

// Search enhancement mod start
                $search_enhancements_keywords = $_GET['keywords'];
                $search_enhancements_keywords = strip_tags($search_enhancements_keywords);
                $search_enhancements_keywords = addslashes($search_enhancements_keywords);                
          
                if ($search_enhancements_keywords != $last_search_insert) {
                        tep_db_query("insert into search_queries (search_text)  values ('" .  $search_enhancements_keywords . "')");
                        tep_session_register('last_search_insert');
                        $last_search_insert = $search_enhancements_keywords;
                }
// Search enhancement mod end


__________________________________________________________________

3) catalog/includes/languages/english/advanced_search.php

FIND:

define('TEXT_NO_PRODUCTS', 'There is no product that matches the search criteria.');



REPLACE with:

define('TEXT_NO_PRODUCTS', '<br><span style="font-size:11px;"><i>Your search did not match any products.</i></span><br><br>Some Suggestions:<ol><li>Check that your spelling was accurate.</li><li>Try using different keywords</li><li>Try using fewer keywords</li><li>Try using more general keywords</li></ol>');


At the end of the file FIND:

?>



Above ADD:

define('TEXT_REPLACEMENT_SUGGESTION', 'You could also try: ');
define('TEXT_REPLACEMENT_SEARCH_RESULTS', 'Your search results for: ');

__________________________________________________________________

4) catalog/includes/modules/product_listing.php

At approx line 14 FIND:

  $listing_split = new splitPageResults($listing_sql, MAX_DISPLAY_SEARCH_RESULTS, 'p.products_id');
// fix counted products



REPLACE with:

if (isset($pw_mispell)){ //added for search enhancements mod
?>
<table border="0" width="100%" cellspacing="0" cellpadding="2">
<tr><td><?php echo $pw_string; ?></td></tr>
</table>
<?php
 } //end added search enhancements mod
  $listing_split = new splitPageResults($listing_sql, MAX_DISPLAY_SEARCH_RESULTS, 'p.products_id');
// fix counted products

__________________________________________________________________

5) Upload included files:

admin/stats_keywords.php
admin/includes/languages/english/stats_keywords.php

__________________________________________________________________

6) admin/includes/filenames.php

FIND:

// define the filenames used in the project



Below ADD:

  define('FILENAME_KEYWORDS', 'stats_keywords.php');

__________________________________________________________________

7) admin/includes/languages/english.php

FIND:

// tools text in includes/boxes/tools.php



Below ADD:

  define('BOX_TOOLS_KEYWORDS', 'Keyword Manager');

__________________________________________________________________

8) admin/includes/boxes/tools.php

FIND:

'<a href="' . tep_href_link(FILENAME_FILE_MANAGER) . '" class="menuBoxContentLink">' . BOX_TOOLS_FILE_MANAGER . '</a><br>' .



Below ADD:

'<a href="' . tep_href_link(FILENAME_KEYWORDS) . '" class="menuBoxContentLink">' . BOX_TOOLS_KEYWORDS . '</a><br>' .

__________________________________________________________________

9) Copy catalog/advanced_search_result.php to catalog/advanced_search_result_notally.php

In catalog/advanced_search_result_notally.php 

FIND:
tep_db_query("insert into search_queries (search_text)  values ('" .  $search_enhancements_keywords . "')");


REPLACE with:
// tep_db_query("insert into search_queries (search_text)  values ('" .  $search_enhancements_keywords . "')");

________________________________________________________________________________
________________________________________________________________________________


That should be it!

Before you can test anything you will need to do a few searches on your site to have some data entered into the database. 
Once you have done this you can then go to your admin section and choose the 'Tools' section, follow the link to 'Keyword Manager'.

The first thing to do is click the button 'Update from Raw data'. Once you have done this the features should be self-explanatory...


Problems??

If you have any problem using this mod you may need to run a search and replace on the modified code/New files to replace $_GET with $HTTP_GET_VARS , this is dependant on the PHP version you are using.

Any further problems please post on the osC forums and DO NOT mail me privately, I am very busy and I receive a LOT of mails daily, I do not have time to answer help requests privately.
