#!D:/Python21/python.exe

# searchme.py - by Greg Holmes, gregholmes@aol.com
#
# make sure you use the script_name in the configuration file

import os
import sys
import string
import win32pipe
import cgi
import urllib

def main():
	#if main returns 0 the user will get an error message
	theQuery=os.environ['QUERY_STRING']
	form = cgi.FieldStorage() 
	if form.has_key("words"):
		pass
	else: 
		wordless()
		return 1

	#Build a retrieve string 
	retrieveString="http://10.1.21.71:8000/cgi-bin/htsearch.exe?"
	retrieveString=retrieveString + theQuery
	
	#Do the search; put the result page into a temporary file
	resultsFile=urllib.urlopen(retrieveString)
	if (resultsFile):
		resultsOut=resultsFile.read()
		resultsOut="Content-type: text/html\n\n"+resultsOut
		resultsTestLine=string.split(resultsOut, "\n")
		resultsFile.close()

		#We want to offer 'hints' based on certain search terms
		replaceString="<!-- This is a tip marker -->"
		if form.has_key("keywords"):
			theKeywords=form["keywords"].value
		else:
			theKeywords=""
		testphrase=form["words"].value+theKeywords
		tipdictionary={}
		tipdictionary["sr"]="If you are looking for information about specific IT Service Requests, you can find it using the Project Tracking System, available in your NAL."
		tipdictionary["facilities"]="Facilities is now Corporate Support Services."
		tipdictionary["ppma"]="You may want to try searching for &quot;PPM&quot; instead of &quot;PPMA&quot;."
		for tipkey in tipdictionary.keys():
			replaceString=tip1(testphrase, tipkey, tipdictionary[tipkey], replaceString)	

		resultsOut=string.replace(resultsOut, "<!-- This is a tip marker -->", replaceString)
		#End 'hints' section

		#restricted search
		if form.has_key("restrict"):
			if form["restrict"]!="":
				if string.find(resultsOut, "<!-- This is a general search link marker -->"):
					newQuery=""
					theWords=""
					for field in form.keys():
						if type(form[field]) is type([]):
							theField=form[field]
							for subfield in theField:
								if (len(newQuery)>0):
									if (field!="restrict" and field!="words"):
										newQuery=newQuery+"&"+field+"="+subfield.value
									if field=="words":
										newQuery=newQuery+"&"+"words"+"="+theWords

								else:
									if field!="restrict":
										newQuery=field +"="+subfield.value
						else:
							if form[field].name=="words":
								if (len(theWords)>0):
									pass
								else:
									theWords=form[field].value
									theWords=string.replace(theWords, " ", "+")

							if (newQuery):
								if field!="restrict":
									newQuery=newQuery+"&"+form[field].name+"="+form[field].value
							else:
								if (field!="restrict" and field!="words"):
									newQuery=form[field].name+"="+form[field].value
								if field=="words":
									newQuery=newQuery+"&"+"words"+"="+theWords
					newQuery=urllib.quote_plus(newQuery, "=&")
					replaceString="<div class='searchWholeIntranet'><h2>You only searched part of the Intranet</h2><a href='/cgi-bin/searchme.py?" + newQuery + "'>" + "Search the whole Intranet for <strong>&quot;" + form["words"].value + ""
					if form.has_key("keywords"):
						replaceString=replaceString+" " +form["keywords"].value
					replaceString=replaceString+ "&quot;</strong></a></div>&nbsp;<br>"
					resultsOut=string.replace(resultsOut, "<!-- This is a general search link marker -->", replaceString)


		#no match
		if (string.find(resultsTestLine[2], "<title>No match for")!=-1):
			mispell1=string.replace(resultsTestLine[2], "<html><head><title>No match for '", "")
			mispell2=string.replace(mispell1, "'</title>", "")
			#ispellString="echo " + mispell2 + " | c:\dos\ispell -a -d //c/dos/english | c:\dos\sed '/^&./!d'"
			ispellString="echo " + mispell2 + " | c:\\aspell\\aspell -a --ignore-case --sug-mode=fast| c:\dos\sed '/^&./!d'"

			spellFile=win32pipe.popen(ispellString, 'r')
			if (spellFile):
				spellOut=spellFile.readlines()
				spellFile.close()
				replaceString="Check the spelling of the search word(s) you used.</p><table border=1 bgcolor='yellow'><tr><td>Search Word<br>&nbsp;</td><td>Suggested Spelling(s)<br><b>Click on a suggestion to search for that word</b></td></tr>"
				if (len(spellOut)):
					for Line in spellOut:
						replaceString=replaceString + "<tr><td>"
						fragment=string.split(Line, ":")
						origWordList=string.split(fragment[0])
						origWord=string.lower(origWordList[1])
						replaceString=replaceString + origWord + "</td><td>"
						suggestList=string.split(fragment[1], ", ")
						newQuery=string.lower(string.replace(theQuery, "-", ""))

						for suggestWord in suggestList:
							suggestWord1=string.lower(string.strip(suggestWord))
							newQuery1=string.replace(newQuery, origWord, suggestWord1)
							newQuery1=urllib.unquote_plus(newQuery1)
							newQuery1=urllib.quote_plus(newQuery1, "=&")
							replaceString=replaceString + "<a href='/cgi-bin/searchme.py?" + newQuery1 + "'>" + suggestWord1 + "</a>&nbsp;"

						replaceString=replaceString +"</td></tr>"
					replaceString=replaceString+ "</table><br>"
					resultsOut2=string.replace(resultsOut, "Check the spelling of the search word(s) you used.", replaceString)
				else:
					resultsOut2=resultsOut
								
				print resultsOut2
				return 1






		resultsOut2=string.replace(resultsOut, "<i><b>Description</b></i><br><br><b><i>Excerpt</i>", "<b><i>Excerpt</i>")
		resultsOut3=string.replace(resultsOut2, "<b><i>Excerpt</i>", "<br><b><i>Excerpt</i>")
		resultsOut4=string.replace(resultsOut3, "<b><i>Excerpt</i></b><br> <br>", "")

		print resultsOut4
	else:
		return 0		
	return 1

def tip1(testPhrase, keyTerm, tipText, theReplaceString):	
		if (string.find(testPhrase.lower(), keyTerm) !=-1):
			#return tip(theReplaceString,tipText)
			return theReplaceString+"<div class='aTip'><p><span class='tip'>Tip!</span> " + tipText + "</p></div><br>"
		else:
			return theReplaceString	

def wordless():
	print "Content-type: text/html\n\n"
	print '<html>\n<head>\n<body bgcolor="#eef7ff">\n'

	print "\n\n<h1>No search words</h1>\n"
	print "\n\n<p>You didn't enter any search words!</p>\n"
	print "\n\n<p>Please click the Back button and try again.</p>\n"

	print "\n</body>\n</html>"
	


if (main()):
	pass
else:
	print "Content-type: text/html\n\n"
	print "<html>\n<head>\n<body>\n"

	print "\n\n<br><p>There was some sort of error.</p>\n"
	print "\n</body>\n</html>"

