home *** CD-ROM | disk | FTP | other *** search
- var search = {
-
- // Set this to false to disable debug output
- SEARCH_DEBUG : false,
-
- // Constants
- MAX_HISTORY_SIZE : 10,
- SEARCH_PLUGINS_FOLDER : "searchplugins",
- SEARCH_PROVIDER_RDF_FILE : "search-providers.rdf",
- SEARCH_HISTORY_FILE : "search-history.txt",
-
- // File open flags (from prio.h)
- PR_RDONLY : 1,
- PR_WRONLY : 2,
- PR_TRUNCATE : 4,
-
- // RDF Predicates
- SPUI_NS : "http://home.netscape.com/NC-spui#",
- RES_NAME : null,
- RES_ICON : null,
- RES_SRC : null,
-
- // Globals
- profileDir : null,
- ioService : null,
- prefService : null,
- RDFService : null,
- httpService : null,
- localRDFLoadObserver : null,
- remoteRDFLoadObserver : null,
- remoteRDFFetchURL : null,
-
-
- Init : function() {
- this.debug('Init()');
-
- // Get the user's profile directory
- if (!this.profileDir) {
- this.profileDir = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties)
- .get("ProfD", Components.interfaces.nsILocalFile);
- }
- this.debug(' profileDir: '+this.profileDir.path);
-
- // IO Service
- if (!this.ioService) {
- this.ioService = Components.classes["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService);
- }
-
- // Pref Service
- if (!this.prefService) {
- this.prefService = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefBranch);
- }
-
- // RDF Service
- if (!this.RDFService) {
- this.RDFService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
- .getService(Components.interfaces.nsIRDFService);
- }
-
- // HTTP Service
- if (!this.httpService) {
- this.httpService = Components.classes["@mozilla.org/network/protocol;1?name=http"]
- .getService(Components.interfaces.nsIHttpProtocolHandler);
- }
-
- // RDF Predicates
- this.RES_NAME = this.RDFService.GetResource(this.SPUI_NS+'name');
- this.RES_ICON = this.RDFService.GetResource(this.SPUI_NS+'icon');
- this.RES_SRC = this.RDFService.GetResource(this.SPUI_NS+'src');
-
- // Local RDF Load Observer
- // ... watches loading of the *local* search-providers.rdf file
- if (!this.localRDFLoadObserver) {
- this.debug(' instanciating local RDF load observer');
- this.localRDFLoadObserver = {
- onBeginLoad : function(sink){},
- onInterrupt : function(sink){},
- onResume : function(sink){},
- onError : function(sink,status,msg){},
- onEndLoad : function(sink) {
- this.debug('onEndLoad()');
- // Load datasource
- sink.removeXMLSinkObserver(this);
- sink.QueryInterface(Components.interfaces.nsIRDFDataSource);
- this.debug(' loaded local datasource: '+sink.URI);
- // Parse the datasource
- this.parent.ParseDataSource(sink);
- // Now update from the server
- this.parent.LoadRemoteSearchProviders();
- },
- debug : function(msg) {
- this.parent.debug('localRDFLoadObserver: '+msg);
- }
- };
- this.localRDFLoadObserver.parent = this;
- }
-
- // Remote RDF Load Observer
- // ... watches loading of the *remote* search-providers.rdf file
- if (!this.remoteRDFLoadObserver) {
- this.debug(' instanciating remote RDF load observer');
- this.remoteRDFLoadObserver = {
- onBeginLoad : function(sink){},
- onInterrupt : function(sink){},
- onResume : function(sink){},
- onError : function(sink,status,msg){},
- onEndLoad : function(sink) {
- this.debug('onEndLoad()');
- // Load datasource
- sink.removeXMLSinkObserver(this);
- sink.QueryInterface(Components.interfaces.nsIRDFDataSource);
- this.debug(' loaded remote datasource: '+sink.URI);
- // Copy over top of the local file
- var localFile = this.parent.GetLocalSearchProviderRDFFile();
- this.debug(' saving a local copy of the RDF file');
- var localFileURI = this.parent.ioService.newFileURI(localFile);
- sink.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
- sink.FlushTo(localFileURI.spec);
- // Parse the datasource
- this.parent.ParseDataSource(sink);
- },
- debug : function(msg) {
- this.parent.debug('remoteRDFLoadObserver: '+msg);
- }
- };
- this.remoteRDFLoadObserver.parent = this;
- }
-
- // Construct URL to fetch the remote search provider RDF file
- if (!this.remoteRDFFetchURL) {
- var user_guid = this.prefService.getCharPref("browser.info.guid");
- var partnerId;
- try {
- partnerId = this.prefService.getCharPref("browser.partnerId");
- } catch (ex) {
- partnerId = 'chapera';
- }
- this.remoteRDFFetchURL =
- this.prefService.getCharPref("browser.search.providers.url");
- // + "?guid="+user_guid + "&partnerId="+partnerId;
- this.debug(' remote RDF URL: '+this.remoteRDFFetchURL);
- }
-
- this.LoadLocalSearchProviders();
- },
-
-
- LoadLocalSearchProviders : function() {
- this.debug('RefreshLocalSearchProviders()');
- var file = this.GetLocalSearchProviderRDFFile();
- var fileURI = this.ioService.newFileURI(file);
- try {
- // Start loading local RDF file of search providers
- var ds = this.RDFService.GetDataSource(fileURI.spec);
- // Register a listener to pick things up when the file is done
- // loading. (Control will go to the onEndLoad function...)
- ds.QueryInterface(Components.interfaces.nsIRDFXMLSink);
- ds.addXMLSinkObserver(this.localRDFLoadObserver);
- } catch (ex) {
- // If there was a problem loading the local file, just go
- // directly to the online one
- this.debug(' problem loading local '+this.SEARCH_PROVIDER_RDF_FILE);
- this.LoadRemoteSearchProviders();
- }
- },
-
-
- LoadRemoteSearchProviders : function() {
- this.debug('RefreshRemoteSearchProviders()');
- try {
- ds = this.RDFService.GetDataSource(this.remoteRDFFetchURL);
- ds.QueryInterface(Components.interfaces.nsIRDFXMLSink);
- ds.addXMLSinkObserver(this.remoteRDFLoadObserver);
- } catch (ex) {
- this.debug(' problem loading remote search providers file');
- }
- },
-
-
- ParseDataSource : function(datasource) {
- // Iterate through resources
- var resources = datasource.GetAllResources();
- var res;
- while (resources.hasMoreElements()) {
- res = resources.getNext();
- res.QueryInterface(Components.interfaces.nsIRDFResource);
- this.LoadSingleProviderResource(datasource, res);
- this.RDFService.UnregisterResource(res);
- }
- this.RDFService.UnregisterDataSource(datasource);
- },
-
-
- LoadSingleProviderResource : function(datasource, resource) {
- this.debug('LoadSingleProviderResource('+resource.Value+')');
- // See if this resource specifies an actual search provider
- if (datasource.hasArcOut(resource, this.RES_NAME) &&
- datasource.hasArcOut(resource, this.RES_ICON) &&
- datasource.hasArcOut(resource, this.RES_SRC))
- {
- var name = datasource.GetTarget(resource, this.RES_NAME, true);
- name.QueryInterface(Components.interfaces.nsIRDFLiteral);
- this.debug(' name: '+name.Value);
- var icon = datasource.GetTarget(resource, this.RES_ICON, true);
- icon.QueryInterface(Components.interfaces.nsIRDFLiteral);
- this.debug(' icon: '+icon.Value);
- var src = datasource.GetTarget(resource, this.RES_SRC, true);
- src.QueryInterface(Components.interfaces.nsIRDFLiteral);
- this.debug(' src: '+src.Value);
- // Create the searchplugins folder if it doesn't exist
- var pluginsFolder = this.EnsureSearchPluginsFolderExists();
- // Download the icon and src files and stick them in the
- // searchplugins folder
- this.DownloadToSearchPluginsFolder(icon.Value, ["gif", "jpg", "bmp", "png"]);
- this.DownloadToSearchPluginsFolder(src.Value);
- }
- },
-
-
- DownloadToSearchPluginsFolder : function(urlSpec, clearFiles) {
- this.debug('DownloadToSearchPluginsFolder('+urlSpec+')');
-
- // Create URL object
- var remoteURL = Components.classes["@mozilla.org/network/standard-url;1"]
- .createInstance(Components.interfaces.nsIStandardURL);
- remoteURL.init(Components.interfaces.nsIStandardURL.URLTYPE_STANDARD,
- null, urlSpec, null, null);
- remoteURL.QueryInterface(Components.interfaces.nsIURL);
- this.debug(' filename is: '+remoteURL.fileName);
-
- // Download
- var downloadObserver = {
- QueryInterface : function(iid) {
- if (!iid.equals(nsIDownloadObserver) &&
- !iid.equals(nsISupports))
- throw Components.results.NS_ERROR_NO_INTERFACE;
- return this;
- },
- onDownloadComplete : function(downloader, request, ctxt, status, file) {
- // file.path now references a temporary cached copy of the file,
- // so copy it to the searchplugins folder
- this.debug('file is at: '+file.path);
- var pluginsFolder = this.parent.GetSearchPluginsFolder();
- this.debug('copying to: '+pluginsFolder.path+' '+this.fileName);
-
- // BLT 152031 fix: replace the existing icon files
- if(!clearFiles) {
- clearFiles = [""];
- }
-
- for(var i in clearFiles) {
- var ext = clearFiles[i];
- var destFname = this.fileName;
- if(ext != "") {
- var ind = destFname.lastIndexOf(".");
- if(ind >= 0) {
- destFname = destFname.substring(0, ind);
- }
- destFname += "." + ext;
- }
- // Test if the file already exists
- var destinationFile = pluginsFolder.clone();
- destinationFile.append(destFname);
- if (destinationFile.exists()) {
- this.debug(' (removing pre-existing file: '+destFname+')');
- destinationFile.remove(false);
- file.copyTo(pluginsFolder, destFname);
- }
- else if(this.fileName == destFname) {
- file.copyTo(pluginsFolder, destFname);
- }
- }
- },
- debug : function(msg) {
- this.parent.debug('downloadObserver: '+msg);
- }
- };
- downloadObserver.parent = this;
- downloadObserver.fileName = remoteURL.fileName;
- var channel = this.ioService.newChannel(remoteURL.spec, null, null);
- var downloader = Components.classes["@mozilla.org/network/downloader;1"]
- .createInstance(Components.interfaces.nsIDownloader);
- downloader.init(downloadObserver, null);
- channel.asyncOpen(downloader, null);
- },
-
-
- GetSearchPluginsFolder : function() {
- this.debug('GetSearchPluginsFolder()');
- // Create file descriptor
- var folder = this.profileDir.clone();
- folder.append(this.SEARCH_PLUGINS_FOLDER);
- return folder; // returns nsILocalFile
- },
-
-
- EnsureSearchPluginsFolderExists : function() {
- this.debug('EnsureSearchPluginsFolderExists()');
- var folder = this.GetSearchPluginsFolder();
- if (!folder.exists()) {
- folder.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0);
- }
- return folder; // returns nsILocalFile
- },
-
-
- GetLocalSearchProviderRDFFile : function() {
- this.debug('GetLocalSearchProviderRDFFile(): '+this.SEARCH_PROVIDER_RDF_FILE);
- // Create file descriptor
- var file = this.profileDir.clone();
- file.append(this.SEARCH_PROVIDER_RDF_FILE);
- return file; // returns nsILocalFile
- },
-
-
- GetSearchHistoryFile : function() {
- this.debug('GetSearchHistoryFile(): '+this.SEARCH_HISTORY_FILE);
- // Create file descriptor
- var file = this.profileDir.clone();
- file.append(this.SEARCH_HISTORY_FILE);
- return file; // returns nsILocalFile
- },
-
-
- EnsureSearchHistoryFileExists : function() {
- this.debug('EnsureSearchHistoryFileExists()');
- var file = this.GetSearchHistoryFile();
- if (!file.exists()) {
- this.debug(' creating file: '+this.SEARCH_HISTORY_FILE);
- file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0);
- }
- return file; // returns nsILocalFile
- },
-
-
- ReadSearchHistory : function() {
- this.debug('ReadSearchHistory()');
-
- var file = this.EnsureSearchHistoryFileExists();
-
- // Init the file input stream
- var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Components.interfaces.nsIFileInputStream);
- fis.init(file, this.PR_RDONLY, 0, 0);
-
- // Init a scriptable input stream
- var sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
- .createInstance(Components.interfaces.nsIScriptableInputStream);
- sis.init(fis);
-
- // Read the file
- var fileContents = sis.read(sis.available());
-
- // Close file
- fis.close();
-
- // Return the lines as an array
- return fileContents.split('\n');
- },
-
-
- PopulateHistoryPopup : function(evt) {
- this.debug('PopulateHistoryPopup()');
-
- // Purge the history menu
- var popup = evt.target;
- while (popup.lastChild)
- popup.removeChild(popup.lastChild);
-
- // Load in the fresh history items
- var entries = this.ReadSearchHistory();
- for (var i = 0; i < entries.length; i++) {
- if (!entries[i].length) continue;
- var newItem = document.createElement('menuitem');
- newItem.setAttribute('label', entries[i]);
- newItem.setAttribute('oncommand', 'search.HistoryCommand("'+entries[i]+'");');
- popup.appendChild(newItem);
- }
-
- // Only add the separator if there were history items
- if (popup.lastChild)
- popup.appendChild(document.createElement('menuseparator'));
-
- // Always add the 'clear history' menu item
- var clearHist = document.createElement('menuitem');
- clearHist.setAttribute('label', 'Clear Search History');
- clearHist.setAttribute('oncommand', 'search.ClearSearchHistory();');
-
- // ... but if there were no history items, then make it disabled
- if (!popup.lastChild)
- clearHist.setAttribute('disabled','true');
- popup.appendChild(clearHist);
- },
-
-
- HistoryCommand : function(value) {
- this.debug('HistoryCommand("'+value+'")');
- var searchbar = document.getElementById('searchbar');
- if (searchbar) {
- // Put the value into the text box
- searchbar.mTextbox.value = value;
- // Execute search
- searchbar.mTextbox.onTextEntered();
- }
- },
-
-
- AddToHistory : function(value) {
- this.debug('AddToHistory("'+value+'")');
-
- // If it's whitespace, don't bother
- if (!this.trim(value).length) return;
-
- // Create the new list
- var oldList = this.ReadSearchHistory();
- var newList = new Array();
- newList[0] = value;
- for (var i = 0; i < oldList.length; i++) {
- if (oldList[i] != value)
- newList[newList.length] = oldList[i];
- if (newList.length >= this.MAX_HISTORY_SIZE)
- break;
- }
-
- // Open the history file for writing
- var file = this.GetSearchHistoryFile();
- file.remove(false);
- file = this.EnsureSearchHistoryFileExists();
- var fos = Components.classes["@mozilla.org/network/file-output-stream;1"]
- .createInstance(Components.interfaces.nsIFileOutputStream);
- fos.init(file, this.PR_WRONLY, 0, 0);
- var contents = newList.join('\n');
- this.debug(' - writing contents:\n'+contents+'\n\n');
- fos.write(contents, contents.length);
- fos.close();
- },
-
-
- ClearSearchHistory : function() {
- this.debug('ClearSearchHistory()');
- var file = this.GetSearchHistoryFile();
- if (file.exists()) {
- // Init the file input stream
- var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Components.interfaces.nsIFileInputStream);
- fis.init(file, this.PR_RDONLY, 0,
- Components.interfaces.nsIFileInputStream.DELETE_ON_CLOSE);
- fis.close();
- }
- // MERC (rpaul) clear the searchbar text
- var searchbar = document.getElementById('searchbar');
- if (searchbar)
- searchbar.clear();
- },
-
-
- debug : function(msg) {
- if (!this.prefService ||
- (this.prefService.getPrefType("search.debug")) &&
- (this.prefService.getBoolPref("search.debug")) )
- {
- dump('search.js: '+msg+'\n');
- }
- },
-
-
- trim : function(str) {
- if (!str) return "";
- str = str.replace(/^\s+/, "");
- return str.replace(/\s+$/, "");
- }
-
- };
-