home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / firefox-3.0.14 / components / nsSearchService.js < prev    next >
Encoding:
Text File  |  2009-09-07  |  108.6 KB  |  3,219 lines

  1. //@line 40 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/components/search/nsSearchService.js"
  2.  
  3. const Ci = Components.interfaces;
  4. const Cc = Components.classes;
  5. const Cr = Components.results;
  6.  
  7. const PERMS_FILE      = 0644;
  8. const PERMS_DIRECTORY = 0755;
  9.  
  10. const MODE_RDONLY   = 0x01;
  11. const MODE_WRONLY   = 0x02;
  12. const MODE_CREATE   = 0x08;
  13. const MODE_APPEND   = 0x10;
  14. const MODE_TRUNCATE = 0x20;
  15.  
  16. // Directory service keys
  17. const NS_APP_SEARCH_DIR_LIST  = "SrchPluginsDL";
  18. const NS_APP_USER_SEARCH_DIR  = "UsrSrchPlugns";
  19. const NS_APP_SEARCH_DIR       = "SrchPlugns";
  20. const NS_APP_USER_PROFILE_50_DIR = "ProfD";
  21.  
  22. // Search engine "locations". If this list is changed, be sure to update
  23. // the engine's _isDefault function accordingly.
  24. const SEARCH_APP_DIR = 1;
  25. const SEARCH_PROFILE_DIR = 2;
  26. const SEARCH_IN_EXTENSION = 3;
  27.  
  28. // See documentation in nsIBrowserSearchService.idl.
  29. const SEARCH_ENGINE_TOPIC        = "browser-search-engine-modified";
  30. const QUIT_APPLICATION_TOPIC     = "quit-application";
  31.  
  32. const SEARCH_ENGINE_REMOVED      = "engine-removed";
  33. const SEARCH_ENGINE_ADDED        = "engine-added";
  34. const SEARCH_ENGINE_CHANGED      = "engine-changed";
  35. const SEARCH_ENGINE_LOADED       = "engine-loaded";
  36. const SEARCH_ENGINE_CURRENT      = "engine-current";
  37.  
  38. const SEARCH_TYPE_MOZSEARCH      = Ci.nsISearchEngine.TYPE_MOZSEARCH;
  39. const SEARCH_TYPE_OPENSEARCH     = Ci.nsISearchEngine.TYPE_OPENSEARCH;
  40. const SEARCH_TYPE_SHERLOCK       = Ci.nsISearchEngine.TYPE_SHERLOCK;
  41.  
  42. const SEARCH_DATA_XML            = Ci.nsISearchEngine.DATA_XML;
  43. const SEARCH_DATA_TEXT           = Ci.nsISearchEngine.DATA_TEXT;
  44.  
  45. // File extensions for search plugin description files
  46. const XML_FILE_EXT      = "xml";
  47. const SHERLOCK_FILE_EXT = "src";
  48.  
  49. // Delay for lazy serialization (ms)
  50. const LAZY_SERIALIZE_DELAY = 100;
  51.  
  52. const ICON_DATAURL_PREFIX = "data:image/x-icon;base64,";
  53.  
  54. // Supported extensions for Sherlock plugin icons
  55. const SHERLOCK_ICON_EXTENSIONS = [".gif", ".png", ".jpg", ".jpeg"];
  56.  
  57. const NEW_LINES = /(\r\n|\r|\n)/;
  58.  
  59. // Set an arbitrary cap on the maximum icon size. Without this, large icons can
  60. // cause big delays when loading them at startup.
  61. const MAX_ICON_SIZE   = 10000;
  62.  
  63. // Default charset to use for sending search parameters. ISO-8859-1 is used to
  64. // match previous nsInternetSearchService behavior.
  65. const DEFAULT_QUERY_CHARSET = "ISO-8859-1";
  66.  
  67. const SEARCH_BUNDLE = "chrome://browser/locale/search.properties";
  68. const BRAND_BUNDLE = "chrome://branding/locale/brand.properties";
  69.  
  70. const OPENSEARCH_NS_10  = "http://a9.com/-/spec/opensearch/1.0/";
  71. const OPENSEARCH_NS_11  = "http://a9.com/-/spec/opensearch/1.1/";
  72.  
  73. // Although the specification at http://opensearch.a9.com/spec/1.1/description/
  74. // gives the namespace names defined above, many existing OpenSearch engines
  75. // are using the following versions.  We therefore allow either.
  76. const OPENSEARCH_NAMESPACES = [
  77.   OPENSEARCH_NS_11, OPENSEARCH_NS_10,
  78.   "http://a9.com/-/spec/opensearchdescription/1.1/",
  79.   "http://a9.com/-/spec/opensearchdescription/1.0/"
  80. ];
  81.  
  82. const OPENSEARCH_LOCALNAME = "OpenSearchDescription";
  83.  
  84. const MOZSEARCH_NS_10     = "http://www.mozilla.org/2006/browser/search/";
  85. const MOZSEARCH_LOCALNAME = "SearchPlugin";
  86.  
  87. const URLTYPE_SUGGEST_JSON = "application/x-suggestions+json";
  88. const URLTYPE_SEARCH_HTML  = "text/html";
  89.  
  90. // Empty base document used to serialize engines to file.
  91. const EMPTY_DOC = "<?xml version=\"1.0\"?>\n" +
  92.                   "<" + MOZSEARCH_LOCALNAME +
  93.                   " xmlns=\"" + MOZSEARCH_NS_10 + "\"" +
  94.                   " xmlns:os=\"" + OPENSEARCH_NS_11 + "\"" +
  95.                   "/>";
  96.  
  97. const BROWSER_SEARCH_PREF = "browser.search.";
  98.  
  99. const USER_DEFINED = "{searchTerms}";
  100.  
  101. // Custom search parameters
  102. //@line 143 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/components/search/nsSearchService.js"
  103. const MOZ_OFFICIAL = "unofficial";
  104. //@line 145 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/components/search/nsSearchService.js"
  105. const MOZ_DISTRIBUTION_ID = "com.ubuntu";
  106.  
  107. const MOZ_PARAM_LOCALE         = /\{moz:locale\}/g;
  108. const MOZ_PARAM_DIST_ID        = /\{moz:distributionID\}/g;
  109. const MOZ_PARAM_OFFICIAL       = /\{moz:official\}/g;
  110.  
  111. // Supported OpenSearch parameters
  112. // See http://opensearch.a9.com/spec/1.1/querysyntax/#core
  113. const OS_PARAM_USER_DEFINED    = /\{searchTerms\??\}/g;
  114. const OS_PARAM_INPUT_ENCODING  = /\{inputEncoding\??\}/g;
  115. const OS_PARAM_LANGUAGE        = /\{language\??\}/g;
  116. const OS_PARAM_OUTPUT_ENCODING = /\{outputEncoding\??\}/g;
  117.  
  118. // Default values
  119. const OS_PARAM_LANGUAGE_DEF         = "*";
  120. const OS_PARAM_OUTPUT_ENCODING_DEF  = "UTF-8";
  121. const OS_PARAM_INPUT_ENCODING_DEF   = "UTF-8";
  122.  
  123. // "Unsupported" OpenSearch parameters. For example, we don't support
  124. // page-based results, so if the engine requires that we send the "page index"
  125. // parameter, we'll always send "1".
  126. const OS_PARAM_COUNT        = /\{count\??\}/g;
  127. const OS_PARAM_START_INDEX  = /\{startIndex\??\}/g;
  128. const OS_PARAM_START_PAGE   = /\{startPage\??\}/g;
  129.  
  130. // Default values
  131. const OS_PARAM_COUNT_DEF        = "20"; // 20 results
  132. const OS_PARAM_START_INDEX_DEF  = "1";  // start at 1st result
  133. const OS_PARAM_START_PAGE_DEF   = "1";  // 1st page
  134.  
  135. // Optional parameter
  136. const OS_PARAM_OPTIONAL     = /\{(?:\w+:)?\w+\?\}/g;
  137.  
  138. // A array of arrays containing parameters that we don't fully support, and
  139. // their default values. We will only send values for these parameters if
  140. // required, since our values are just really arbitrary "guesses" that should
  141. // give us the output we want.
  142. var OS_UNSUPPORTED_PARAMS = [
  143.   [OS_PARAM_COUNT, OS_PARAM_COUNT_DEF],
  144.   [OS_PARAM_START_INDEX, OS_PARAM_START_INDEX_DEF],
  145.   [OS_PARAM_START_PAGE, OS_PARAM_START_PAGE_DEF],
  146. ];
  147.  
  148. // The default engine update interval, in days. This is only used if an engine
  149. // specifies an updateURL, but not an updateInterval.
  150. const SEARCH_DEFAULT_UPDATE_INTERVAL = 7;
  151.  
  152. // Returns false for whitespace-only or commented out lines in a
  153. // Sherlock file, true otherwise.
  154. function isUsefulLine(aLine) {
  155.   return !(/^\s*($|#)/i.test(aLine));
  156. }
  157.  
  158. /**
  159.  * Prefixed to all search debug output.
  160.  */
  161. const SEARCH_LOG_PREFIX = "*** Search: ";
  162.  
  163. /**
  164.  * Outputs aText to the JavaScript console as well as to stdout.
  165.  */
  166. function DO_LOG(aText) {
  167.   dump(SEARCH_LOG_PREFIX + aText + "\n");
  168.   var consoleService = Cc["@mozilla.org/consoleservice;1"].
  169.                        getService(Ci.nsIConsoleService);
  170.   consoleService.logStringMessage(aText);
  171. }
  172.  
  173. //@line 233 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/components/search/nsSearchService.js"
  174.  
  175. /**
  176.  * Otherwise, don't log at all by default. This can be overridden at startup
  177.  * by the pref, see SearchService's _init method.
  178.  */
  179. var LOG = function(){};
  180.  
  181. //@line 241 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/components/search/nsSearchService.js"
  182.  
  183. function ERROR(message, resultCode) {
  184.   NS_ASSERT(false, SEARCH_LOG_PREFIX + message);
  185.   throw resultCode;
  186. }
  187.  
  188. /**
  189.  * Ensures an assertion is met before continuing. Should be used to indicate
  190.  * fatal errors.
  191.  * @param  assertion
  192.  *         An assertion that must be met
  193.  * @param  message
  194.  *         A message to display if the assertion is not met
  195.  * @param  resultCode
  196.  *         The NS_ERROR_* value to throw if the assertion is not met
  197.  * @throws resultCode
  198.  */
  199. function ENSURE_WARN(assertion, message, resultCode) {
  200.   NS_ASSERT(assertion, SEARCH_LOG_PREFIX + message);
  201.   if (!assertion)
  202.     throw resultCode;
  203. }
  204.  
  205. /**
  206.  * Ensures an assertion is met before continuing, but does not warn the user.
  207.  * Used to handle normal failure conditions.
  208.  * @param  assertion
  209.  *         An assertion that must be met
  210.  * @param  message
  211.  *         A message to display if the assertion is not met
  212.  * @param  resultCode
  213.  *         The NS_ERROR_* value to throw if the assertion is not met
  214.  * @throws resultCode
  215.  */
  216. function ENSURE(assertion, message, resultCode) {
  217.   if (!assertion) {
  218.     LOG(message);
  219.     throw resultCode;
  220.   }
  221. }
  222.  
  223. /**
  224.  * Ensures an argument assertion is met before continuing.
  225.  * @param  assertion
  226.  *         An argument assertion that must be met
  227.  * @param  message
  228.  *         A message to display if the assertion is not met
  229.  * @throws NS_ERROR_INVALID_ARG for invalid arguments
  230.  */
  231. function ENSURE_ARG(assertion, message) {
  232.   ENSURE(assertion, message, Cr.NS_ERROR_INVALID_ARG);
  233. }
  234.  
  235. function loadListener(aChannel, aEngine, aCallback) {
  236.   this._channel = aChannel;
  237.   this._bytes = [];
  238.   this._engine = aEngine;
  239.   this._callback = aCallback;
  240. }
  241. loadListener.prototype = {
  242.   _callback: null,
  243.   _channel: null,
  244.   _countRead: 0,
  245.   _engine: null,
  246.   _stream: null,
  247.  
  248.   QueryInterface: function SRCH_loadQI(aIID) {
  249.     if (aIID.equals(Ci.nsISupports)           ||
  250.         aIID.equals(Ci.nsIRequestObserver)    ||
  251.         aIID.equals(Ci.nsIStreamListener)     ||
  252.         aIID.equals(Ci.nsIChannelEventSink)   ||
  253.         aIID.equals(Ci.nsIInterfaceRequestor) ||
  254.         aIID.equals(Ci.nsIBadCertListener2)   ||
  255.         aIID.equals(Ci.nsISSLErrorListener)   ||
  256.         // See FIXME comment below
  257.         aIID.equals(Ci.nsIHttpEventSink)      ||
  258.         aIID.equals(Ci.nsIProgressEventSink)  ||
  259.         false)
  260.       return this;
  261.  
  262.     throw Cr.NS_ERROR_NO_INTERFACE;
  263.   },
  264.  
  265.   // nsIRequestObserver
  266.   onStartRequest: function SRCH_loadStartR(aRequest, aContext) {
  267.     LOG("loadListener: Starting request: " + aRequest.name);
  268.     this._stream = Cc["@mozilla.org/binaryinputstream;1"].
  269.                    createInstance(Ci.nsIBinaryInputStream);
  270.   },
  271.  
  272.   onStopRequest: function SRCH_loadStopR(aRequest, aContext, aStatusCode) {
  273.     LOG("loadListener: Stopping request: " + aRequest.name);
  274.  
  275.     var requestFailed = !Components.isSuccessCode(aStatusCode);
  276.     if (!requestFailed && (aRequest instanceof Ci.nsIHttpChannel))
  277.       requestFailed = !aRequest.requestSucceeded;
  278.  
  279.     if (requestFailed || this._countRead == 0) {
  280.       LOG("loadListener: request failed!");
  281.       // send null so the callback can deal with the failure
  282.       this._callback(null, this._engine);
  283.     } else
  284.       this._callback(this._bytes, this._engine);
  285.     this._channel = null;
  286.     this._engine  = null;
  287.   },
  288.  
  289.   // nsIStreamListener
  290.   onDataAvailable: function SRCH_loadDAvailable(aRequest, aContext,
  291.                                                 aInputStream, aOffset,
  292.                                                 aCount) {
  293.     this._stream.setInputStream(aInputStream);
  294.  
  295.     // Get a byte array of the data
  296.     this._bytes = this._bytes.concat(this._stream.readByteArray(aCount));
  297.     this._countRead += aCount;
  298.   },
  299.  
  300.   // nsIChannelEventSink
  301.   onChannelRedirect: function SRCH_loadCRedirect(aOldChannel, aNewChannel,
  302.                                                  aFlags) {
  303.     this._channel = aNewChannel;
  304.   },
  305.  
  306.   // nsIInterfaceRequestor
  307.   getInterface: function SRCH_load_GI(aIID) {
  308.     return this.QueryInterface(aIID);
  309.   },
  310.  
  311.   // nsIBadCertListener2
  312.   notifyCertProblem: function SRCH_certProblem(socketInfo, status, targetSite) {
  313.     return true;
  314.   },
  315.  
  316.   // nsISSLErrorListener
  317.   notifySSLError: function SRCH_SSLError(socketInfo, error, targetSite) {
  318.     return true;
  319.   },
  320.  
  321.   // FIXME: bug 253127
  322.   // nsIHttpEventSink
  323.   onRedirect: function (aChannel, aNewChannel) {},
  324.   // nsIProgressEventSink
  325.   onProgress: function (aRequest, aContext, aProgress, aProgressMax) {},
  326.   onStatus: function (aRequest, aContext, aStatus, aStatusArg) {}
  327. }
  328.  
  329.  
  330. /**
  331.  * Used to verify a given DOM node's localName and namespaceURI.
  332.  * @param aElement
  333.  *        The element to verify.
  334.  * @param aLocalNameArray
  335.  *        An array of strings to compare against aElement's localName.
  336.  * @param aNameSpaceArray
  337.  *        An array of strings to compare against aElement's namespaceURI.
  338.  *
  339.  * @returns false if aElement is null, or if its localName or namespaceURI
  340.  *          does not match one of the elements in the aLocalNameArray or
  341.  *          aNameSpaceArray arrays, respectively.
  342.  * @throws NS_ERROR_INVALID_ARG if aLocalNameArray or aNameSpaceArray are null.
  343.  */
  344. function checkNameSpace(aElement, aLocalNameArray, aNameSpaceArray) {
  345.   ENSURE_ARG(aLocalNameArray && aNameSpaceArray, "missing aLocalNameArray or \
  346.              aNameSpaceArray for checkNameSpace");
  347.   return (aElement                                                &&
  348.           (aLocalNameArray.indexOf(aElement.localName)    != -1)  &&
  349.           (aNameSpaceArray.indexOf(aElement.namespaceURI) != -1));
  350. }
  351.  
  352. /**
  353.  * Safely close a nsISafeOutputStream.
  354.  * @param aFOS
  355.  *        The file output stream to close.
  356.  */
  357. function closeSafeOutputStream(aFOS) {
  358.   if (aFOS instanceof Ci.nsISafeOutputStream) {
  359.     try {
  360.       aFOS.finish();
  361.       return;
  362.     } catch (e) { }
  363.   }
  364.   aFOS.close();
  365. }
  366.  
  367. /**
  368.  * Wrapper function for nsIIOService::newURI.
  369.  * @param aURLSpec
  370.  *        The URL string from which to create an nsIURI.
  371.  * @returns an nsIURI object, or null if the creation of the URI failed.
  372.  */
  373. function makeURI(aURLSpec, aCharset) {
  374.   var ios = Cc["@mozilla.org/network/io-service;1"].
  375.             getService(Ci.nsIIOService);
  376.   try {
  377.     return ios.newURI(aURLSpec, aCharset, null);
  378.   } catch (ex) { }
  379.  
  380.   return null;
  381. }
  382.  
  383. /**
  384.  * Gets a directory from the directory service.
  385.  * @param aKey
  386.  *        The directory service key indicating the directory to get.
  387.  */
  388. function getDir(aKey) {
  389.   ENSURE_ARG(aKey, "getDir requires a directory key!");
  390.  
  391.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  392.                     getService(Ci.nsIProperties);
  393.   var dir = fileLocator.get(aKey, Ci.nsIFile);
  394.   return dir;
  395. }
  396.  
  397. /**
  398.  * The following two functions are essentially copied from
  399.  * nsInternetSearchService. They are required for backwards compatibility.
  400.  */
  401. function queryCharsetFromCode(aCode) {
  402.   const codes = [];
  403.   codes[0] = "x-mac-roman";
  404.   codes[6] = "x-mac-greek";
  405.   codes[35] = "x-mac-turkish";
  406.   codes[513] = "ISO-8859-1";
  407.   codes[514] = "ISO-8859-2";
  408.   codes[517] = "ISO-8859-5";
  409.   codes[518] = "ISO-8859-6";
  410.   codes[519] = "ISO-8859-7";
  411.   codes[520] = "ISO-8859-8";
  412.   codes[521] = "ISO-8859-9";
  413.   codes[1049] = "IBM864";
  414.   codes[1280] = "windows-1252";
  415.   codes[1281] = "windows-1250";
  416.   codes[1282] = "windows-1251";
  417.   codes[1283] = "windows-1253";
  418.   codes[1284] = "windows-1254";
  419.   codes[1285] = "windows-1255";
  420.   codes[1286] = "windows-1256";
  421.   codes[1536] = "us-ascii";
  422.   codes[1584] = "GB2312";
  423.   codes[1585] = "x-gbk";
  424.   codes[1600] = "EUC-KR";
  425.   codes[2080] = "ISO-2022-JP";
  426.   codes[2096] = "ISO-2022-CN";
  427.   codes[2112] = "ISO-2022-KR";
  428.   codes[2336] = "EUC-JP";
  429.   codes[2352] = "GB2312";
  430.   codes[2353] = "x-euc-tw";
  431.   codes[2368] = "EUC-KR";
  432.   codes[2561] = "Shift_JIS";
  433.   codes[2562] = "KOI8-R";
  434.   codes[2563] = "Big5";
  435.   codes[2565] = "HZ-GB-2312";
  436.  
  437.   if (codes[aCode])
  438.     return codes[aCode];
  439.  
  440.   return getLocalizedPref("intl.charset.default", DEFAULT_QUERY_CHARSET);
  441. }
  442. function fileCharsetFromCode(aCode) {
  443.   const codes = [
  444.     "x-mac-roman",           // 0
  445.     "Shift_JIS",             // 1
  446.     "Big5",                  // 2
  447.     "EUC-KR",                // 3
  448.     "X-MAC-ARABIC",          // 4
  449.     "X-MAC-HEBREW",          // 5
  450.     "X-MAC-GREEK",           // 6
  451.     "X-MAC-CYRILLIC",        // 7
  452.     "X-MAC-DEVANAGARI" ,     // 9
  453.     "X-MAC-GURMUKHI",        // 10
  454.     "X-MAC-GUJARATI",        // 11
  455.     "X-MAC-ORIYA",           // 12
  456.     "X-MAC-BENGALI",         // 13
  457.     "X-MAC-TAMIL",           // 14
  458.     "X-MAC-TELUGU",          // 15
  459.     "X-MAC-KANNADA",         // 16
  460.     "X-MAC-MALAYALAM",       // 17
  461.     "X-MAC-SINHALESE",       // 18
  462.     "X-MAC-BURMESE",         // 19
  463.     "X-MAC-KHMER",           // 20
  464.     "X-MAC-THAI",            // 21
  465.     "X-MAC-LAOTIAN",         // 22
  466.     "X-MAC-GEORGIAN",        // 23
  467.     "X-MAC-ARMENIAN",        // 24
  468.     "GB2312",                // 25
  469.     "X-MAC-TIBETAN",         // 26
  470.     "X-MAC-MONGOLIAN",       // 27
  471.     "X-MAC-ETHIOPIC",        // 28
  472.     "X-MAC-CENTRALEURROMAN", // 29
  473.     "X-MAC-VIETNAMESE",      // 30
  474.     "X-MAC-EXTARABIC"        // 31
  475.   ];
  476.   // Sherlock files have always defaulted to x-mac-roman, so do that here too
  477.   return codes[aCode] || codes[0];
  478. }
  479.  
  480. /**
  481.  * Returns a string interpretation of aBytes using aCharset, or null on
  482.  * failure.
  483.  */
  484. function bytesToString(aBytes, aCharset) {
  485.   var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
  486.                   createInstance(Ci.nsIScriptableUnicodeConverter);
  487.   LOG("bytesToString: converting using charset: " + aCharset);
  488.  
  489.   try {
  490.     converter.charset = aCharset;
  491.     return converter.convertFromByteArray(aBytes, aBytes.length);
  492.   } catch (ex) {}
  493.  
  494.   return null;
  495. }
  496.  
  497. /**
  498.  * Converts an array of bytes representing a Sherlock file into an array of
  499.  * lines representing the useful data from the file.
  500.  *
  501.  * @param aBytes
  502.  *        The array of bytes representing the Sherlock file.
  503.  * @param aCharsetCode
  504.  *        An integer value representing a character set code to be passed to
  505.  *        fileCharsetFromCode, or null for the default Sherlock encoding.
  506.  */
  507. function sherlockBytesToLines(aBytes, aCharsetCode) {
  508.   // fileCharsetFromCode returns the default encoding if aCharsetCode is null
  509.   var charset = fileCharsetFromCode(aCharsetCode);
  510.  
  511.   var dataString = bytesToString(aBytes, charset);
  512.   ENSURE(dataString, "sherlockBytesToLines: Couldn't convert byte array!",
  513.          Cr.NS_ERROR_FAILURE);
  514.  
  515.   // Split the string into lines, and filter out comments and
  516.   // whitespace-only lines
  517.   return dataString.split(NEW_LINES).filter(isUsefulLine);
  518. }
  519.  
  520. /**
  521.  * Gets the current value of the locale.  It's possible for this preference to
  522.  * be localized, so we have to do a little extra work here.  Similar code
  523.  * exists in nsHttpHandler.cpp when building the UA string.
  524.  */
  525. function getLocale() {
  526.   const localePref = "general.useragent.locale";
  527.   var locale = getLocalizedPref(localePref);
  528.   if (locale)
  529.     return locale;
  530.  
  531.   // Not localized
  532.   var prefs = Cc["@mozilla.org/preferences-service;1"].
  533.               getService(Ci.nsIPrefBranch);
  534.   return prefs.getCharPref(localePref);
  535. }
  536.  
  537. /**
  538.  * Wrapper for nsIPrefBranch::getComplexValue.
  539.  * @param aPrefName
  540.  *        The name of the pref to get.
  541.  * @returns aDefault if the requested pref doesn't exist.
  542.  */
  543. function getLocalizedPref(aPrefName, aDefault) {
  544.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  545.               getService(Ci.nsIPrefBranch);
  546.   const nsIPLS = Ci.nsIPrefLocalizedString;
  547.   try {
  548.     return prefB.getComplexValue(aPrefName, nsIPLS).data;
  549.   } catch (ex) {}
  550.  
  551.   return aDefault;
  552. }
  553.  
  554. /**
  555.  * Wrapper for nsIPrefBranch::setComplexValue.
  556.  * @param aPrefName
  557.  *        The name of the pref to set.
  558.  */
  559. function setLocalizedPref(aPrefName, aValue) {
  560.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  561.               getService(Ci.nsIPrefBranch);
  562.   const nsIPLS = Ci.nsIPrefLocalizedString;
  563.   try {
  564.     var pls = Components.classes["@mozilla.org/pref-localizedstring;1"]
  565.                         .createInstance(Ci.nsIPrefLocalizedString);
  566.     pls.data = aValue;
  567.     prefB.setComplexValue(aPrefName, nsIPLS, pls);
  568.   } catch (ex) {}
  569. }
  570.  
  571. /**
  572.  * Wrapper for nsIPrefBranch::getBoolPref.
  573.  * @param aPrefName
  574.  *        The name of the pref to get.
  575.  * @returns aDefault if the requested pref doesn't exist.
  576.  */
  577. function getBoolPref(aName, aDefault) {
  578.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  579.               getService(Ci.nsIPrefBranch);
  580.   try {
  581.     return prefB.getBoolPref(aName);
  582.   } catch (ex) {
  583.     return aDefault;
  584.   }
  585. }
  586.  
  587. /**
  588.  * Get a unique nsIFile object with a sanitized name, based on the engine name.
  589.  * @param aName
  590.  *        A name to "sanitize". Can be an empty string, in which case a random
  591.  *        8 character filename will be produced.
  592.  * @returns A nsIFile object in the user's search engines directory with a
  593.  *          unique sanitized name.
  594.  */
  595. function getSanitizedFile(aName) {
  596.   var fileName = sanitizeName(aName) + "." + XML_FILE_EXT;
  597.   var file = getDir(NS_APP_USER_SEARCH_DIR);
  598.   file.append(fileName);
  599.   file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE);
  600.   return file;
  601. }
  602.  
  603. /**
  604.  * Removes all characters not in the "chars" string from aName.
  605.  *
  606.  * @returns a sanitized name to be used as a filename, or a random name
  607.  *          if a sanitized name cannot be obtained (if aName contains
  608.  *          no valid characters).
  609.  */
  610. function sanitizeName(aName) {
  611.   const chars = "-abcdefghijklmnopqrstuvwxyz0123456789";
  612.   const maxLength = 60;
  613.  
  614.   var name = aName.toLowerCase();
  615.   name = name.replace(/ /g, "-");
  616.   name = name.split("").filter(function (el) {
  617.                                  return chars.indexOf(el) != -1;
  618.                                }).join("");
  619.  
  620.   if (!name) {
  621.     // Our input had no valid characters - use a random name
  622.     var cl = chars.length - 1;
  623.     for (var i = 0; i < 8; ++i)
  624.       name += chars.charAt(Math.round(Math.random() * cl));
  625.   }
  626.  
  627.   if (name.length > maxLength)
  628.     name = name.substring(0, maxLength);
  629.  
  630.   return name;
  631. }
  632.  
  633. /**
  634.  * Notifies watchers of SEARCH_ENGINE_TOPIC about changes to an engine or to
  635.  * the state of the search service.
  636.  *
  637.  * @param aEngine
  638.  *        The nsISearchEngine object to which the change applies.
  639.  * @param aVerb
  640.  *        A verb describing the change.
  641.  *
  642.  * @see nsIBrowserSearchService.idl
  643.  */
  644. function notifyAction(aEngine, aVerb) {
  645.   var os = Cc["@mozilla.org/observer-service;1"].
  646.            getService(Ci.nsIObserverService);
  647.   LOG("NOTIFY: Engine: \"" + aEngine.name + "\"; Verb: \"" + aVerb + "\"");
  648.   os.notifyObservers(aEngine, SEARCH_ENGINE_TOPIC, aVerb);
  649. }
  650.  
  651. /**
  652.  * Simple object representing a name/value pair.
  653.  */
  654. function QueryParameter(aName, aValue) {
  655.   ENSURE_ARG(aName && (aValue != null),
  656.              "missing name or value for QueryParameter!");
  657.  
  658.   this.name = aName;
  659.   this.value = aValue;
  660. }
  661.  
  662. /**
  663.  * Perform OpenSearch parameter substitution on aParamValue.
  664.  *
  665.  * @param aParamValue
  666.  *        A string containing OpenSearch search parameters.
  667.  * @param aSearchTerms
  668.  *        The user-provided search terms. This string will inserted into
  669.  *        aParamValue as the value of the OS_PARAM_USER_DEFINED parameter.
  670.  *        This value must already be escaped appropriately - it is inserted
  671.  *        as-is.
  672.  * @param aQueryEncoding
  673.  *        The value to use for the OS_PARAM_INPUT_ENCODING parameter. See
  674.  *        definition in the OpenSearch spec.
  675.  *
  676.  * @see http://opensearch.a9.com/spec/1.1/querysyntax/#core
  677.  */
  678. function ParamSubstitution(aParamValue, aSearchTerms, aEngine) {
  679.   var value = aParamValue;
  680.  
  681.   var distributionID = MOZ_DISTRIBUTION_ID;
  682.   try {
  683.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  684.                 getService(Ci.nsIPrefBranch);
  685.     distributionID = prefB.getCharPref(BROWSER_SEARCH_PREF + "distributionID");
  686.   }
  687.   catch (ex) { }
  688.  
  689.   // Custom search parameters. These are only available to default search
  690.   // engines.
  691.   if (aEngine._isDefault) {
  692.     value = value.replace(MOZ_PARAM_LOCALE, getLocale());
  693.     value = value.replace(MOZ_PARAM_DIST_ID, distributionID);
  694.     value = value.replace(MOZ_PARAM_OFFICIAL, MOZ_OFFICIAL);
  695.   }
  696.  
  697.   // Insert the OpenSearch parameters we're confident about
  698.   value = value.replace(OS_PARAM_USER_DEFINED, aSearchTerms);
  699.   value = value.replace(OS_PARAM_INPUT_ENCODING, aEngine.queryCharset);
  700.   value = value.replace(OS_PARAM_LANGUAGE,
  701.                         getLocale() || OS_PARAM_LANGUAGE_DEF);
  702.   value = value.replace(OS_PARAM_OUTPUT_ENCODING,
  703.                         OS_PARAM_OUTPUT_ENCODING_DEF);
  704.  
  705.   // Replace any optional parameters
  706.   value = value.replace(OS_PARAM_OPTIONAL, "");
  707.  
  708.   // Insert any remaining required params with our default values
  709.   for (var i = 0; i < OS_UNSUPPORTED_PARAMS.length; ++i) {
  710.     value = value.replace(OS_UNSUPPORTED_PARAMS[i][0],
  711.                           OS_UNSUPPORTED_PARAMS[i][1]);
  712.   }
  713.  
  714.   return value;
  715. }
  716.  
  717. /**
  718.  * Creates a mozStorage statement that can be used to access the database we
  719.  * use to hold metadata.
  720.  *
  721.  * @param dbconn  the database that the statement applies to
  722.  * @param sql     a string specifying the sql statement that should be created
  723.  */
  724. function createStatement (dbconn, sql) {
  725.   var stmt = dbconn.createStatement(sql);
  726.   var wrapper = Cc["@mozilla.org/storage/statement-wrapper;1"].
  727.                 createInstance(Ci.mozIStorageStatementWrapper);
  728.  
  729.   wrapper.initialize(stmt);
  730.   return wrapper;
  731. }
  732.  
  733. /**
  734.  * Creates an engineURL object, which holds the query URL and all parameters.
  735.  *
  736.  * @param aType
  737.  *        A string containing the name of the MIME type of the search results
  738.  *        returned by this URL.
  739.  * @param aMethod
  740.  *        The HTTP request method. Must be a case insensitive value of either
  741.  *        "GET" or "POST".
  742.  * @param aTemplate
  743.  *        The URL to which search queries should be sent. For GET requests,
  744.  *        must contain the string "{searchTerms}", to indicate where the user
  745.  *        entered search terms should be inserted.
  746.  *
  747.  * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag
  748.  *
  749.  * @throws NS_ERROR_NOT_IMPLEMENTED if aType is unsupported.
  750.  */
  751. function EngineURL(aType, aMethod, aTemplate) {
  752.   ENSURE_ARG(aType && aMethod && aTemplate,
  753.              "missing type, method or template for EngineURL!");
  754.  
  755.   var method = aMethod.toUpperCase();
  756.   var type   = aType.toLowerCase();
  757.  
  758.   ENSURE_ARG(method == "GET" || method == "POST",
  759.              "method passed to EngineURL must be \"GET\" or \"POST\"");
  760.  
  761.   this.type     = type;
  762.   this.method   = method;
  763.   this.params   = [];
  764.  
  765.   var templateURI = makeURI(aTemplate);
  766.   ENSURE(templateURI, "new EngineURL: template is not a valid URI!",
  767.          Cr.NS_ERROR_FAILURE);
  768.  
  769.   switch (templateURI.scheme) {
  770.     case "http":
  771.     case "https":
  772.     // Disable these for now, see bug 295018
  773.     // case "file":
  774.     // case "resource":
  775.       this.template = aTemplate;
  776.       break;
  777.     default:
  778.       ENSURE(false, "new EngineURL: template uses invalid scheme!",
  779.              Cr.NS_ERROR_FAILURE);
  780.   }
  781. }
  782. EngineURL.prototype = {
  783.  
  784.   addParam: function SRCH_EURL_addParam(aName, aValue) {
  785.     this.params.push(new QueryParameter(aName, aValue));
  786.   },
  787.  
  788.   getSubmission: function SRCH_EURL_getSubmission(aSearchTerms, aEngine) {
  789.     var url = ParamSubstitution(this.template, aSearchTerms, aEngine);
  790.  
  791.     // Create an application/x-www-form-urlencoded representation of our params
  792.     // (name=value&name=value&name=value)
  793.     var dataString = "";
  794.     for (var i = 0; i < this.params.length; ++i) {
  795.       var param = this.params[i];
  796.       var value = ParamSubstitution(param.value, aSearchTerms, aEngine);
  797.  
  798.       dataString += (i > 0 ? "&" : "") + param.name + "=" + value;
  799.     }
  800.  
  801.     var postData = null;
  802.     if (this.method == "GET") {
  803.       // GET method requests have no post data, and append the encoded
  804.       // query string to the url...
  805.       if (url.indexOf("?") == -1 && dataString)
  806.         url += "?";
  807.       url += dataString;
  808.     } else if (this.method == "POST") {
  809.       // POST method requests must wrap the encoded text in a MIME
  810.       // stream and supply that as POSTDATA.
  811.       var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].
  812.                          createInstance(Ci.nsIStringInputStream);
  813. //@line 876 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/components/search/nsSearchService.js"
  814.       stringStream.data = dataString;
  815. //@line 878 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/browser/components/search/nsSearchService.js"
  816.  
  817.       postData = Cc["@mozilla.org/network/mime-input-stream;1"].
  818.                  createInstance(Ci.nsIMIMEInputStream);
  819.       postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
  820.       postData.addContentLength = true;
  821.       postData.setData(stringStream);
  822.     }
  823.  
  824.     return new Submission(makeURI(url), postData);
  825.   },
  826.  
  827.   /**
  828.    * Serializes the engine object to a OpenSearch Url element.
  829.    * @param aDoc
  830.    *        The document to use to create the Url element.
  831.    * @param aElement
  832.    *        The element to which the created Url element is appended.
  833.    *
  834.    * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag
  835.    */
  836.   _serializeToElement: function SRCH_EURL_serializeToEl(aDoc, aElement) {
  837.     var url = aDoc.createElementNS(OPENSEARCH_NS_11, "Url");
  838.     url.setAttribute("type", this.type);
  839.     url.setAttribute("method", this.method);
  840.     url.setAttribute("template", this.template);
  841.  
  842.     for (var i = 0; i < this.params.length; ++i) {
  843.       var param = aDoc.createElementNS(OPENSEARCH_NS_11, "Param");
  844.       param.setAttribute("name", this.params[i].name);
  845.       param.setAttribute("value", this.params[i].value);
  846.       url.appendChild(aDoc.createTextNode("\n  "));
  847.       url.appendChild(param);
  848.     }
  849.     url.appendChild(aDoc.createTextNode("\n"));
  850.     aElement.appendChild(url);
  851.   }
  852. };
  853.  
  854. /**
  855.  * nsISearchEngine constructor.
  856.  * @param aLocation
  857.  *        A nsILocalFile or nsIURI object representing the location of the
  858.  *        search engine data file.
  859.  * @param aSourceDataType
  860.  *        The data type of the file used to describe the engine. Must be either
  861.  *        DATA_XML or DATA_TEXT.
  862.  * @param aIsReadOnly
  863.  *        Boolean indicating whether the engine should be treated as read-only.
  864.  *        Read only engines cannot be serialized to file.
  865.  */
  866. function Engine(aLocation, aSourceDataType, aIsReadOnly) {
  867.   this._dataType = aSourceDataType;
  868.   this._readOnly = aIsReadOnly;
  869.   this._urls = [];
  870.  
  871.   if (aLocation instanceof Ci.nsILocalFile) {
  872.     // we already have a file (e.g. loading engines from disk)
  873.     this._file = aLocation;
  874.   } else if (aLocation instanceof Ci.nsIURI) {
  875.     this._uri = aLocation;
  876.     switch (aLocation.scheme) {
  877.       case "https":
  878.       case "http":
  879.       case "ftp":
  880.       case "data":
  881.       case "file":
  882.       case "resource":
  883.         this._uri = aLocation;
  884.         break;
  885.       default:
  886.         ERROR("Invalid URI passed to the nsISearchEngine constructor",
  887.               Cr.NS_ERROR_INVALID_ARG);
  888.     }
  889.   } else
  890.     ERROR("Engine location is neither a File nor a URI object",
  891.           Cr.NS_ERROR_INVALID_ARG);
  892. }
  893.  
  894. Engine.prototype = {
  895.   // The engine's alias.
  896.   _alias: null,
  897.   // The data describing the engine. Is either an array of bytes, for Sherlock
  898.   // files, or an XML document element, for XML plugins.
  899.   _data: null,
  900.   // The engine's data type. See data types (DATA_) defined above.
  901.   _dataType: null,
  902.   // Whether or not the engine is readonly.
  903.   _readOnly: true,
  904.   // The engine's description
  905.   _description: "",
  906.   // Used to store the engine to replace, if we're an update to an existing
  907.   // engine.
  908.   _engineToUpdate: null,
  909.   // The file from which the plugin was loaded.
  910.   _file: null,
  911.   // Set to true if the engine has a preferred icon (an icon that should not be
  912.   // overridden by a non-preferred icon).
  913.   _hasPreferredIcon: null,
  914.   // Whether the engine is hidden from the user.
  915.   _hidden: null,
  916.   // The engine's name.
  917.   _name: null,
  918.   // The engine type. See engine types (TYPE_) defined above.
  919.   _type: null,
  920.   // The name of the charset used to submit the search terms.
  921.   _queryCharset: null,
  922.   // A URL string pointing to the engine's search form.
  923.   __searchForm: null,
  924.   get _searchForm() {
  925.     return this.__searchForm;
  926.   },
  927.   set _searchForm(aValue) {
  928.     if (/^https?:/i.test(aValue))
  929.       this.__searchForm = aValue;
  930.     else
  931.       LOG("_searchForm: Invalid URL dropped for " + this._name ||
  932.           "the current engine");
  933.   },
  934.   // The URI object from which the engine was retrieved.
  935.   // This is null for local plugins, and is used for error messages and logging.
  936.   _uri: null,
  937.   // Whether to obtain user confirmation before adding the engine. This is only
  938.   // used when the engine is first added to the list.
  939.   _confirm: false,
  940.   // Whether to set this as the current engine as soon as it is loaded.  This
  941.   // is only used when the engine is first added to the list.
  942.   _useNow: true,
  943.   // Where the engine was loaded from. Can be one of: SEARCH_APP_DIR,
  944.   // SEARCH_PROFILE_DIR, SEARCH_IN_EXTENSION.
  945.   __installLocation: null,
  946.   // The number of days between update checks for new versions
  947.   _updateInterval: null,
  948.   // The url to check at for a new update
  949.   _updateURL: null,
  950.   // The url to check for a new icon
  951.   _iconUpdateURL: null,
  952.   // A reference to the timer used for lazily serializing the engine to file
  953.   _serializeTimer: null,
  954.  
  955.   /**
  956.    * Retrieves the data from the engine's file. If the engine's dataType is
  957.    * XML, the document element is placed in the engine's data field. For text
  958.    * engines, the data is just read directly from file and placed as an array
  959.    * of lines in the engine's data field.
  960.    */
  961.   _initFromFile: function SRCH_ENG_initFromFile() {
  962.     ENSURE(this._file && this._file.exists(),
  963.            "File must exist before calling initFromFile!",
  964.            Cr.NS_ERROR_UNEXPECTED);
  965.  
  966.     var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"].
  967.                        createInstance(Ci.nsIFileInputStream);
  968.  
  969.     fileInStream.init(this._file, MODE_RDONLY, PERMS_FILE, false);
  970.  
  971.     switch (this._dataType) {
  972.       case SEARCH_DATA_XML:
  973.         var domParser = Cc["@mozilla.org/xmlextras/domparser;1"].
  974.                         createInstance(Ci.nsIDOMParser);
  975.         var doc = domParser.parseFromStream(fileInStream, "UTF-8",
  976.                                             this._file.fileSize,
  977.                                             "text/xml");
  978.  
  979.         this._data = doc.documentElement;
  980.         break;
  981.       case SEARCH_DATA_TEXT:
  982.         var binaryInStream = Cc["@mozilla.org/binaryinputstream;1"].
  983.                              createInstance(Ci.nsIBinaryInputStream);
  984.         binaryInStream.setInputStream(fileInStream);
  985.  
  986.         var bytes = binaryInStream.readByteArray(binaryInStream.available());
  987.         this._data = bytes;
  988.  
  989.         break;
  990.       default:
  991.         ERROR("Bogus engine _dataType: \"" + this._dataType + "\"",
  992.               Cr.NS_ERROR_UNEXPECTED);
  993.     }
  994.     fileInStream.close();
  995.  
  996.     // Now that the data is loaded, initialize the engine object
  997.     this._initFromData();
  998.   },
  999.  
  1000.   /**
  1001.    * Retrieves the engine data from a URI.
  1002.    */
  1003.   _initFromURI: function SRCH_ENG_initFromURI() {
  1004.     ENSURE_WARN(this._uri instanceof Ci.nsIURI,
  1005.                 "Must have URI when calling _initFromURI!",
  1006.                 Cr.NS_ERROR_UNEXPECTED);
  1007.  
  1008.     LOG("_initFromURI: Downloading engine from: \"" + this._uri.spec + "\".");
  1009.  
  1010.     var ios = Cc["@mozilla.org/network/io-service;1"].
  1011.               getService(Ci.nsIIOService);
  1012.     var chan = ios.newChannelFromURI(this._uri);
  1013.  
  1014.     if (this._engineToUpdate && (chan instanceof Ci.nsIHttpChannel)) {
  1015.       var lastModified = engineMetadataService.getAttr(this._engineToUpdate,
  1016.                                                        "updatelastmodified");
  1017.       if (lastModified)
  1018.         chan.setRequestHeader("If-Modified-Since", lastModified, false);
  1019.     }
  1020.     var listener = new loadListener(chan, this, this._onLoad);
  1021.     chan.notificationCallbacks = listener;
  1022.     chan.asyncOpen(listener, null);
  1023.   },
  1024.  
  1025.   /**
  1026.    * Attempts to find an EngineURL object in the set of EngineURLs for
  1027.    * this Engine that has the given type string.  (This corresponds to the
  1028.    * "type" attribute in the "Url" node in the OpenSearch spec.)
  1029.    * This method will return the first matching URL object found, or null
  1030.    * if no matching URL is found.
  1031.    *
  1032.    * @param aType string to match the EngineURL's type attribute
  1033.    */
  1034.   _getURLOfType: function SRCH_ENG__getURLOfType(aType) {
  1035.     for (var i = 0; i < this._urls.length; ++i) {
  1036.       if (this._urls[i].type == aType)
  1037.         return this._urls[i];
  1038.     }
  1039.  
  1040.     return null;
  1041.   },
  1042.  
  1043.   _confirmAddEngine: function SRCH_SVC_confirmAddEngine() {
  1044.     var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  1045.               getService(Ci.nsIStringBundleService);
  1046.     var stringBundle = sbs.createBundle(SEARCH_BUNDLE);
  1047.     var titleMessage = stringBundle.GetStringFromName("addEngineConfirmTitle");
  1048.  
  1049.     // Display only the hostname portion of the URL.
  1050.     var dialogMessage =
  1051.         stringBundle.formatStringFromName("addEngineConfirmation",
  1052.                                           [this._name, this._uri.host], 2);
  1053.     var checkboxMessage = stringBundle.GetStringFromName("addEngineUseNowText");
  1054.     var addButtonLabel =
  1055.         stringBundle.GetStringFromName("addEngineAddButtonLabel");
  1056.  
  1057.     var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  1058.              getService(Ci.nsIPromptService);
  1059.     var buttonFlags = (ps.BUTTON_TITLE_IS_STRING * ps.BUTTON_POS_0) +
  1060.                       (ps.BUTTON_TITLE_CANCEL    * ps.BUTTON_POS_1) +
  1061.                        ps.BUTTON_POS_0_DEFAULT;
  1062.  
  1063.     var checked = {value: false};
  1064.     // confirmEx returns the index of the button that was pressed.  Since "Add"
  1065.     // is button 0, we want to return the negation of that value.
  1066.     var confirm = !ps.confirmEx(null,
  1067.                                 titleMessage,
  1068.                                 dialogMessage,
  1069.                                 buttonFlags,
  1070.                                 addButtonLabel,
  1071.                                 null, null, // button 1 & 2 names not used
  1072.                                 checkboxMessage,
  1073.                                 checked);
  1074.  
  1075.     return {confirmed: confirm, useNow: checked.value};
  1076.   },
  1077.  
  1078.   /**
  1079.    * Handle the successful download of an engine. Initializes the engine and
  1080.    * triggers parsing of the data. The engine is then flushed to disk. Notifies
  1081.    * the search service once initialization is complete.
  1082.    */
  1083.   _onLoad: function SRCH_ENG_onLoad(aBytes, aEngine) {
  1084.     /**
  1085.      * Handle an error during the load of an engine by prompting the user to
  1086.      * notify him that the load failed.
  1087.      */
  1088.     function onError(aErrorString, aTitleString) {
  1089.       if (aEngine._engineToUpdate) {
  1090.         // We're in an update, so just fail quietly
  1091.         LOG("updating " + aEngine._engineToUpdate.name + " failed");
  1092.         return;
  1093.       }
  1094.       var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  1095.                 getService(Ci.nsIStringBundleService);
  1096.  
  1097.       var brandBundle = sbs.createBundle(BRAND_BUNDLE);
  1098.       var brandName = brandBundle.GetStringFromName("brandShortName");
  1099.  
  1100.       var searchBundle = sbs.createBundle(SEARCH_BUNDLE);
  1101.       var msgStringName = aErrorString || "error_loading_engine_msg2";
  1102.       var titleStringName = aTitleString || "error_loading_engine_title";
  1103.       var title = searchBundle.GetStringFromName(titleStringName);
  1104.       var text = searchBundle.formatStringFromName(msgStringName,
  1105.                                                    [brandName, aEngine._location],
  1106.                                                    2);
  1107.  
  1108.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  1109.                getService(Ci.nsIWindowWatcher);
  1110.       ww.getNewPrompter(null).alert(title, text);
  1111.     }
  1112.  
  1113.     if (!aBytes) {
  1114.       onError();
  1115.       return;
  1116.     }
  1117.  
  1118.     var engineToUpdate = null;
  1119.     if (aEngine._engineToUpdate) {
  1120.       engineToUpdate = aEngine._engineToUpdate.wrappedJSObject;
  1121.  
  1122.       // Make this new engine use the old engine's file.
  1123.       aEngine._file = engineToUpdate._file;
  1124.     }
  1125.  
  1126.     switch (aEngine._dataType) {
  1127.       case SEARCH_DATA_XML:
  1128.         var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1129.                      createInstance(Ci.nsIDOMParser);
  1130.         var doc = parser.parseFromBuffer(aBytes, aBytes.length, "text/xml");
  1131.         aEngine._data = doc.documentElement;
  1132.         break;
  1133.       case SEARCH_DATA_TEXT:
  1134.         aEngine._data = aBytes;
  1135.         break;
  1136.       default:
  1137.         onError();
  1138.         LOG("_onLoad: Bogus engine _dataType: \"" + this._dataType + "\"");
  1139.         return;
  1140.     }
  1141.  
  1142.     try {
  1143.       // Initialize the engine from the obtained data
  1144.       aEngine._initFromData();
  1145.     } catch (ex) {
  1146.       LOG("_onLoad: Failed to init engine!\n" + ex);
  1147.       // Report an error to the user
  1148.       onError();
  1149.       return;
  1150.     }
  1151.  
  1152.     // Check to see if this is a duplicate engine. If we're confirming the
  1153.     // engine load, then we display a "this is a duplicate engine" prompt,
  1154.     // otherwise we fail silently.
  1155.     if (!engineToUpdate) {
  1156.       var ss = Cc["@mozilla.org/browser/search-service;1"].
  1157.                getService(Ci.nsIBrowserSearchService);
  1158.       if (ss.getEngineByName(aEngine.name)) {
  1159.         if (aEngine._confirm)
  1160.           onError("error_duplicate_engine_msg", "error_invalid_engine_title");
  1161.  
  1162.         LOG("_onLoad: duplicate engine found, bailing");
  1163.         return;
  1164.       }
  1165.     }
  1166.  
  1167.     // If requested, confirm the addition now that we have the title.
  1168.     // This property is only ever true for engines added via
  1169.     // nsIBrowserSearchService::addEngine.
  1170.     if (aEngine._confirm) {
  1171.       var confirmation = aEngine._confirmAddEngine();
  1172.       LOG("_onLoad: confirm is " + confirmation.confirmed +
  1173.           "; useNow is " + confirmation.useNow);
  1174.       if (!confirmation.confirmed)
  1175.         return;
  1176.       aEngine._useNow = confirmation.useNow;
  1177.     }
  1178.  
  1179.     // If we don't yet have a file, get one now. The only case where we would
  1180.     // already have a file is if this is an update and _file was set above.
  1181.     if (!aEngine._file)
  1182.       aEngine._file = getSanitizedFile(aEngine.name);
  1183.  
  1184.     if (engineToUpdate) {
  1185.       // Keep track of the last modified date, so that we can make conditional
  1186.       // requests for future updates.
  1187.       engineMetadataService.setAttr(aEngine, "updatelastmodified",
  1188.                                     (new Date()).toUTCString());
  1189.  
  1190.       // Set the new engine's icon, if it doesn't yet have one.
  1191.       if (!aEngine._iconURI && engineToUpdate._iconURI)
  1192.         aEngine._iconURI = engineToUpdate._iconURI;
  1193.  
  1194.       // Clear the "use now" flag since we don't want to be changing the
  1195.       // current engine for an update.
  1196.       aEngine._useNow = false;
  1197.     }
  1198.  
  1199.     // Write the engine to file
  1200.     aEngine._serializeToFile();
  1201.  
  1202.     // Notify the search service of the sucessful load. It will deal with
  1203.     // updates by checking aEngine._engineToUpdate.
  1204.     notifyAction(aEngine, SEARCH_ENGINE_LOADED);
  1205.   },
  1206.  
  1207.   /**
  1208.    * Sets the .iconURI property of the engine.
  1209.    *
  1210.    *  @param aIconURL
  1211.    *         A URI string pointing to the engine's icon. Must have a http[s],
  1212.    *         ftp, or data scheme. Icons with HTTP[S] or FTP schemes will be
  1213.    *         downloaded and converted to data URIs for storage in the engine
  1214.    *         XML files, if the engine is not readonly.
  1215.    *  @param aIsPreferred
  1216.    *         Whether or not this icon is to be preferred. Preferred icons can
  1217.    *         override non-preferred icons.
  1218.    */
  1219.   _setIcon: function SRCH_ENG_setIcon(aIconURL, aIsPreferred) {
  1220.     // If we already have a preferred icon, and this isn't a preferred icon,
  1221.     // just ignore it.
  1222.     if (this._hasPreferredIcon && !aIsPreferred)
  1223.       return;
  1224.  
  1225.     var uri = makeURI(aIconURL);
  1226.  
  1227.     // Ignore bad URIs
  1228.     if (!uri)
  1229.       return;
  1230.  
  1231.     LOG("_setIcon: Setting icon url \"" + uri.spec + "\" for engine \""
  1232.         + this.name + "\".");
  1233.     // Only accept remote icons from http[s] or ftp
  1234.     switch (uri.scheme) {
  1235.       case "data":
  1236.         this._iconURI = uri;
  1237.         notifyAction(this, SEARCH_ENGINE_CHANGED);
  1238.         this._hasPreferredIcon = aIsPreferred;
  1239.         break;
  1240.       case "http":
  1241.       case "https":
  1242.       case "ftp":
  1243.         // No use downloading the icon if the engine file is read-only
  1244.         if (!this._readOnly) {
  1245.           LOG("_setIcon: Downloading icon: \"" + uri.spec +
  1246.               "\" for engine: \"" + this.name + "\"");
  1247.           var ios = Cc["@mozilla.org/network/io-service;1"].
  1248.                     getService(Ci.nsIIOService);
  1249.           var chan = ios.newChannelFromURI(uri);
  1250.  
  1251.           function iconLoadCallback(aByteArray, aEngine) {
  1252.             // This callback may run after we've already set a preferred icon,
  1253.             // so check again.
  1254.             if (aEngine._hasPreferredIcon && !aIsPreferred)
  1255.               return;
  1256.  
  1257.             if (!aByteArray || aByteArray.length > MAX_ICON_SIZE) {
  1258.               LOG("iconLoadCallback: load failed, or the icon was too large!");
  1259.               return;
  1260.             }
  1261.  
  1262.             var str = btoa(String.fromCharCode.apply(null, aByteArray));
  1263.             aEngine._iconURI = makeURI(ICON_DATAURL_PREFIX + str);
  1264.  
  1265.             // The engine might not have a file yet, if it's being downloaded,
  1266.             // because the request for the engine file itself (_onLoad) may not
  1267.             // yet be complete. In that case, this change will be written to
  1268.             // file when _onLoad is called.
  1269.             if (aEngine._file)
  1270.               aEngine._serializeToFile();
  1271.  
  1272.             notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
  1273.             aEngine._hasPreferredIcon = aIsPreferred;
  1274.           }
  1275.  
  1276.           // If we're currently acting as an "update engine", then the callback
  1277.           // should set the icon on the engine we're updating and not us, since
  1278.           // |this| might be gone by the time the callback runs.
  1279.           var engineToSet = this._engineToUpdate || this;
  1280.  
  1281.           var listener = new loadListener(chan, engineToSet, iconLoadCallback);
  1282.           chan.notificationCallbacks = listener;
  1283.           chan.asyncOpen(listener, null);
  1284.         }
  1285.         break;
  1286.     }
  1287.   },
  1288.  
  1289.   /**
  1290.    * Initialize this Engine object from the collected data.
  1291.    */
  1292.   _initFromData: function SRCH_ENG_initFromData() {
  1293.  
  1294.     ENSURE_WARN(this._data, "Can't init an engine with no data!",
  1295.                 Cr.NS_ERROR_UNEXPECTED);
  1296.  
  1297.     // Find out what type of engine we are
  1298.     switch (this._dataType) {
  1299.       case SEARCH_DATA_XML:
  1300.         if (checkNameSpace(this._data, [MOZSEARCH_LOCALNAME],
  1301.             [MOZSEARCH_NS_10])) {
  1302.  
  1303.           LOG("_init: Initing MozSearch plugin from " + this._location);
  1304.  
  1305.           this._type = SEARCH_TYPE_MOZSEARCH;
  1306.           this._parseAsMozSearch();
  1307.  
  1308.         } else if (checkNameSpace(this._data, [OPENSEARCH_LOCALNAME],
  1309.                                   OPENSEARCH_NAMESPACES)) {
  1310.  
  1311.           LOG("_init: Initing OpenSearch plugin from " + this._location);
  1312.  
  1313.           this._type = SEARCH_TYPE_OPENSEARCH;
  1314.           this._parseAsOpenSearch();
  1315.  
  1316.         } else
  1317.           ENSURE(false, this._location + " is not a valid search plugin.",
  1318.                  Cr.NS_ERROR_FAILURE);
  1319.  
  1320.         break;
  1321.       case SEARCH_DATA_TEXT:
  1322.         LOG("_init: Initing Sherlock plugin from " + this._location);
  1323.  
  1324.         // the only text-based format we support is Sherlock
  1325.         this._type = SEARCH_TYPE_SHERLOCK;
  1326.         this._parseAsSherlock();
  1327.     }
  1328.  
  1329.     // No need to keep a ref to our data (which in some cases can be a document
  1330.     // element) past this point
  1331.     this._data = null;
  1332.   },
  1333.  
  1334.   /**
  1335.    * Initialize this Engine object from a collection of metadata.
  1336.    */
  1337.   _initFromMetadata: function SRCH_ENG_initMetaData(aName, aIconURL, aAlias,
  1338.                                                     aDescription, aMethod,
  1339.                                                     aTemplate) {
  1340.     ENSURE_WARN(!this._readOnly,
  1341.                 "Can't call _initFromMetaData on a readonly engine!",
  1342.                 Cr.NS_ERROR_FAILURE);
  1343.  
  1344.     this._urls.push(new EngineURL("text/html", aMethod, aTemplate));
  1345.  
  1346.     this._name = aName;
  1347.     this.alias = aAlias;
  1348.     this._description = aDescription;
  1349.     this._setIcon(aIconURL, true);
  1350.  
  1351.     this._serializeToFile();
  1352.   },
  1353.  
  1354.   /**
  1355.    * Extracts data from an OpenSearch URL element and creates an EngineURL
  1356.    * object which is then added to the engine's list of URLs.
  1357.    *
  1358.    * @throws NS_ERROR_FAILURE if a URL object could not be created.
  1359.    *
  1360.    * @see http://opensearch.a9.com/spec/1.1/querysyntax/#urltag.
  1361.    * @see EngineURL()
  1362.    */
  1363.   _parseURL: function SRCH_ENG_parseURL(aElement) {
  1364.     var type     = aElement.getAttribute("type");
  1365.     // According to the spec, method is optional, defaulting to "GET" if not
  1366.     // specified
  1367.     var method   = aElement.getAttribute("method") || "GET";
  1368.     var template = aElement.getAttribute("template");
  1369.  
  1370.     try {
  1371.       var url = new EngineURL(type, method, template);
  1372.     } catch (ex) {
  1373.       LOG("_parseURL: failed to add " + template + " as a URL");
  1374.       throw Cr.NS_ERROR_FAILURE;
  1375.     }
  1376.  
  1377.     for (var i = 0; i < aElement.childNodes.length; ++i) {
  1378.       var param = aElement.childNodes[i];
  1379.       if (param.localName == "Param") {
  1380.         try {
  1381.           url.addParam(param.getAttribute("name"), param.getAttribute("value"));
  1382.         } catch (ex) {
  1383.           // Ignore failure
  1384.           LOG("_parseURL: Url element has an invalid param");
  1385.         }
  1386.       } else if (param.localName == "MozParam" &&
  1387.                  // We only support MozParams for default search engines
  1388.                  this._isDefault) {
  1389.         var value;
  1390.         switch (param.getAttribute("condition")) {
  1391.           case "defaultEngine":
  1392.             const defPref = BROWSER_SEARCH_PREF + "defaultenginename";
  1393.             var defaultPrefB = Cc["@mozilla.org/preferences-service;1"].
  1394.                                getService(Ci.nsIPrefService).
  1395.                                getDefaultBranch(null);
  1396.             const nsIPLS = Ci.nsIPrefLocalizedString;
  1397.             var defaultName;
  1398.             try {
  1399.               defaultName = defaultPrefB.getComplexValue(defPref, nsIPLS).data;
  1400.             } catch (ex) {}
  1401.  
  1402.             // If this engine was the default search engine, use the true value
  1403.             if (this.name == defaultName)
  1404.               value = param.getAttribute("trueValue");
  1405.             else
  1406.               value = param.getAttribute("falseValue");
  1407.             url.addParam(param.getAttribute("name"), value);
  1408.             break;
  1409.  
  1410.           case "pref":
  1411.             try {
  1412.               var prefB = Cc["@mozilla.org/preferences-service;1"].
  1413.                           getService(Ci.nsIPrefBranch);
  1414.               value = prefB.getCharPref(BROWSER_SEARCH_PREF + "param." +
  1415.                                         param.getAttribute("pref"));
  1416.               url.addParam(param.getAttribute("name"), value);
  1417.             } catch (e) { }
  1418.             break;
  1419.         }
  1420.       }
  1421.     }
  1422.  
  1423.     this._urls.push(url);
  1424.   },
  1425.  
  1426.   /**
  1427.    * Get the icon from an OpenSearch Image element.
  1428.    * @see http://opensearch.a9.com/spec/1.1/description/#image
  1429.    */
  1430.   _parseImage: function SRCH_ENG_parseImage(aElement) {
  1431.     LOG("_parseImage: Image textContent: \"" + aElement.textContent + "\"");
  1432.     if (aElement.getAttribute("width")  == "16" &&
  1433.         aElement.getAttribute("height") == "16") {
  1434.       this._setIcon(aElement.textContent, true);
  1435.     }
  1436.   },
  1437.  
  1438.   _parseAsMozSearch: function SRCH_ENG_parseAsMoz() {
  1439.     //forward to the OpenSearch parser
  1440.     this._parseAsOpenSearch();
  1441.   },
  1442.  
  1443.   /**
  1444.    * Extract search engine information from the collected data to initialize
  1445.    * the engine object.
  1446.    */
  1447.   _parseAsOpenSearch: function SRCH_ENG_parseAsOS() {
  1448.     var doc = this._data;
  1449.  
  1450.     // The OpenSearch spec sets a default value for the input encoding.
  1451.     this._queryCharset = OS_PARAM_INPUT_ENCODING_DEF;
  1452.  
  1453.     for (var i = 0; i < doc.childNodes.length; ++i) {
  1454.       var child = doc.childNodes[i];
  1455.       switch (child.localName) {
  1456.         case "ShortName":
  1457.           this._name = child.textContent;
  1458.           break;
  1459.         case "Description":
  1460.           this._description = child.textContent;
  1461.           break;
  1462.         case "Url":
  1463.           try {
  1464.             this._parseURL(child);
  1465.           } catch (ex) {
  1466.             // Parsing of the element failed, just skip it.
  1467.           }
  1468.           break;
  1469.         case "Image":
  1470.           this._parseImage(child);
  1471.           break;
  1472.         case "InputEncoding":
  1473.           this._queryCharset = child.textContent.toUpperCase();
  1474.           break;
  1475.  
  1476.         // Non-OpenSearch elements
  1477.         case "SearchForm":
  1478.           this._searchForm = child.textContent;
  1479.           break;
  1480.         case "UpdateUrl":
  1481.           this._updateURL = child.textContent;
  1482.           break;
  1483.         case "UpdateInterval":
  1484.           this._updateInterval = parseInt(child.textContent);
  1485.           break;
  1486.         case "IconUpdateUrl":
  1487.           this._iconUpdateURL = child.textContent;
  1488.           break;
  1489.       }
  1490.     }
  1491.     ENSURE(this.name && (this._urls.length > 0),
  1492.            "_parseAsOpenSearch: No name, or missing URL!",
  1493.            Cr.NS_ERROR_FAILURE);
  1494.     ENSURE(this.supportsResponseType(URLTYPE_SEARCH_HTML),
  1495.            "_parseAsOpenSearch: No text/html result type!",
  1496.            Cr.NS_ERROR_FAILURE);
  1497.   },
  1498.  
  1499.   /**
  1500.    * Extract search engine information from the collected data to initialize
  1501.    * the engine object.
  1502.    */
  1503.   _parseAsSherlock: function SRCH_ENG_parseAsSherlock() {
  1504.     /**
  1505.      * Trims leading and trailing whitespace from aStr.
  1506.      */
  1507.     function sTrim(aStr) {
  1508.       return aStr.replace(/^\s+/g, "").replace(/\s+$/g, "");
  1509.     }
  1510.  
  1511.     /**
  1512.      * Extracts one Sherlock "section" from aSource. A section is essentially
  1513.      * an HTML element with attributes, but each attribute must be on a new
  1514.      * line, by definition.
  1515.      *
  1516.      * @param aLines
  1517.      *        An array of lines from the sherlock file.
  1518.      * @param aSection
  1519.      *        The name of the section (e.g. "search" or "browser"). This value
  1520.      *        is not case sensitive.
  1521.      * @returns an object whose properties correspond to the section's
  1522.      *          attributes.
  1523.      */
  1524.     function getSection(aLines, aSection) {
  1525.       LOG("_parseAsSherlock::getSection: Sherlock lines:\n" +
  1526.           aLines.join("\n"));
  1527.       var lines = aLines;
  1528.       var startMark = new RegExp("^\\s*<" + aSection.toLowerCase() + "\\s*",
  1529.                                  "gi");
  1530.       var endMark   = /\s*>\s*$/gi;
  1531.  
  1532.       var foundStart = false;
  1533.       var startLine, numberOfLines;
  1534.       // Find the beginning and end of the section
  1535.       for (var i = 0; i < lines.length; i++) {
  1536.         if (foundStart) {
  1537.           if (endMark.test(lines[i])) {
  1538.             numberOfLines = i - startLine;
  1539.             // Remove the end marker
  1540.             lines[i] = lines[i].replace(endMark, "");
  1541.             // If the endmarker was not the only thing on the line, include
  1542.             // this line in the results
  1543.             if (lines[i])
  1544.               numberOfLines++;
  1545.             break;
  1546.           }
  1547.         } else {
  1548.           if (startMark.test(lines[i])) {
  1549.             foundStart = true;
  1550.             // Remove the start marker
  1551.             lines[i] = lines[i].replace(startMark, "");
  1552.             startLine = i;
  1553.             // If the line is empty, don't include it in the result
  1554.             if (!lines[i])
  1555.               startLine++;
  1556.           }
  1557.         }
  1558.       }
  1559.       LOG("_parseAsSherlock::getSection: Start index: " + startLine +
  1560.           "\nNumber of lines: " + numberOfLines);
  1561.       lines = lines.splice(startLine, numberOfLines);
  1562.       LOG("_parseAsSherlock::getSection: Section lines:\n" +
  1563.           lines.join("\n"));
  1564.  
  1565.       var section = {};
  1566.       for (var i = 0; i < lines.length; i++) {
  1567.         var line = sTrim(lines[i]);
  1568.  
  1569.         var els = line.split("=");
  1570.         var name = sTrim(els.shift().toLowerCase());
  1571.         var value = sTrim(els.join("="));
  1572.  
  1573.         if (!name || !value)
  1574.           continue;
  1575.  
  1576.         // Strip leading and trailing whitespace, remove quotes from the
  1577.         // value, and remove any trailing slashes or ">" characters
  1578.         value = value.replace(/^["']/, "")
  1579.                      .replace(/["']\s*[\\\/]?>?\s*$/, "") || "";
  1580.         value = sTrim(value);
  1581.  
  1582.         // Don't clobber existing attributes
  1583.         if (!(name in section))
  1584.           section[name] = value;
  1585.       }
  1586.       return section;
  1587.     }
  1588.  
  1589.     /**
  1590.      * Returns an array of name-value pair arrays representing the Sherlock
  1591.      * file's input elements. User defined inputs return USER_DEFINED
  1592.      * as the value. Elements are returned in the order they appear in the
  1593.      * source file.
  1594.      *
  1595.      *   Example:
  1596.      *      <input name="foo" value="bar">
  1597.      *      <input name="foopy" user>
  1598.      *   Returns:
  1599.      *      [["foo", "bar"], ["foopy", "{searchTerms}"]]
  1600.      *
  1601.      * @param aLines
  1602.      *        An array of lines from the source file.
  1603.      */
  1604.     function getInputs(aLines) {
  1605.  
  1606.       /**
  1607.        * Extracts an attribute value from a given a line of text.
  1608.        *    Example: <input value="foo" name="bar">
  1609.        *      Extracts the string |foo| or |bar| given an input aAttr of
  1610.        *      |value| or |name|.
  1611.        * Attributes may be quoted or unquoted. If unquoted, any whitespace
  1612.        * indicates the end of the attribute value.
  1613.        *    Example: < value=22 33 name=44\334 >
  1614.        *      Returns |22| for "value" and |44\334| for "name".
  1615.        *
  1616.        * @param aAttr
  1617.        *        The name of the attribute for which to obtain the value. This
  1618.        *        value is not case sensitive.
  1619.        * @param aLine
  1620.        *        The line containing the attribute.
  1621.        *
  1622.        * @returns the attribute value, or an empty string if the attribute
  1623.        *          doesn't exist.
  1624.        */
  1625.       function getAttr(aAttr, aLine) {
  1626.         // Used to determine whether an "input" line from a Sherlock file is a
  1627.         // "user defined" input.
  1628.         const userInput = /(\s|["'=])user(\s|[>="'\/\\+]|$)/i;
  1629.  
  1630.         LOG("_parseAsSherlock::getAttr: Getting attr: \"" +
  1631.             aAttr + "\" for line: \"" + aLine + "\"");
  1632.         // We're not case sensitive, but we want to return the attribute value
  1633.         // in its original case, so create a copy of the source
  1634.         var lLine = aLine.toLowerCase();
  1635.         var attr = aAttr.toLowerCase();
  1636.  
  1637.         var attrStart = lLine.search(new RegExp("\\s" + attr, "i"));
  1638.         if (attrStart == -1) {
  1639.  
  1640.           // If this is the "user defined input" (i.e. contains the empty
  1641.           // "user" attribute), return our special keyword
  1642.           if (userInput.test(lLine) && attr == "value") {
  1643.             LOG("_parseAsSherlock::getAttr: Found user input!\nLine:\"" + lLine
  1644.                 + "\"");
  1645.             return USER_DEFINED;
  1646.           }
  1647.           // The attribute doesn't exist - ignore
  1648.           LOG("_parseAsSherlock::getAttr: Failed to find attribute:\nLine:\""
  1649.               + lLine + "\"\nAttr:\"" + attr + "\"");
  1650.           return "";
  1651.         }
  1652.  
  1653.         var valueStart = lLine.indexOf("=", attrStart) + "=".length;
  1654.         if (valueStart == -1)
  1655.           return "";
  1656.  
  1657.         var quoteStart = lLine.indexOf("\"", valueStart);
  1658.         if (quoteStart == -1) {
  1659.  
  1660.           // Unquoted attribute, get the rest of the line, trimmed at the first
  1661.           // sign of whitespace. If the rest of the line is only whitespace,
  1662.           // returns a blank string.
  1663.           return lLine.substr(valueStart).replace(/\s.*$/, "");
  1664.  
  1665.         } else {
  1666.           // Make sure that there's only whitespace between the start of the
  1667.           // value and the first quote. If there is, end the attribute value at
  1668.           // the first sign of whitespace. This prevents us from falling into
  1669.           // the next attribute if this is an unquoted attribute followed by a
  1670.           // quoted attribute.
  1671.           var betweenEqualAndQuote = lLine.substring(valueStart, quoteStart);
  1672.           if (/\S/.test(betweenEqualAndQuote))
  1673.             return lLine.substr(valueStart).replace(/\s.*$/, "");
  1674.  
  1675.           // Adjust the start index to account for the opening quote
  1676.           valueStart = quoteStart + "\"".length;
  1677.           // Find the closing quote
  1678.           valueEnd = lLine.indexOf("\"", valueStart);
  1679.           // If there is no closing quote, just go to the end of the line
  1680.           if (valueEnd == -1)
  1681.             valueEnd = aLine.length;
  1682.         }
  1683.         return aLine.substring(valueStart, valueEnd);
  1684.       }
  1685.  
  1686.       var inputs = [];
  1687.  
  1688.       LOG("_parseAsSherlock::getInputs: Lines:\n" + aLines);
  1689.       // Filter out everything but non-inputs
  1690.       lines = aLines.filter(function (line) {
  1691.         return /^\s*<input/i.test(line);
  1692.       });
  1693.       LOG("_parseAsSherlock::getInputs: Filtered lines:\n" + lines);
  1694.  
  1695.       lines.forEach(function (line) {
  1696.         // Strip leading/trailing whitespace and remove the surrounding markup
  1697.         // ("<input" and ">")
  1698.         line = sTrim(line).replace(/^<input/i, "").replace(/>$/, "");
  1699.  
  1700.         // If this is one of the "directional" inputs (<inputnext>/<inputprev>)
  1701.         const directionalInput = /^(prev|next)/i;
  1702.         if (directionalInput.test(line)) {
  1703.  
  1704.           // Make it look like a normal input by removing "prev" or "next"
  1705.           line = line.replace(directionalInput, "");
  1706.  
  1707.           // If it has a name, give it a dummy value to match previous
  1708.           // nsInternetSearchService behavior
  1709.           if (/name\s*=/i.test(line)) {
  1710.             line += " value=\"0\"";
  1711.           } else
  1712.             return; // Line has no name, skip it
  1713.         }
  1714.  
  1715.         var attrName = getAttr("name", line);
  1716.         var attrValue = getAttr("value", line);
  1717.         LOG("_parseAsSherlock::getInputs: Got input:\nName:\"" + attrName +
  1718.             "\"\nValue:\"" + attrValue + "\"");
  1719.         if (attrValue)
  1720.           inputs.push([attrName, attrValue]);
  1721.       });
  1722.       return inputs;
  1723.     }
  1724.  
  1725.     function err(aErr) {
  1726.       LOG("_parseAsSherlock::err: Sherlock param error:\n" + aErr);
  1727.       throw Cr.NS_ERROR_FAILURE;
  1728.     }
  1729.  
  1730.     // First try converting our byte array using the default Sherlock encoding.
  1731.     // If this fails, or if we find a sourceTextEncoding attribute, we need to
  1732.     // reconvert the byte array using the specified encoding.
  1733.     var sherlockLines, searchSection, sourceTextEncoding, browserSection;
  1734.     try {
  1735.       sherlockLines = sherlockBytesToLines(this._data);
  1736.       searchSection = getSection(sherlockLines, "search");
  1737.       browserSection = getSection(sherlockLines, "browser");
  1738.       sourceTextEncoding = parseInt(searchSection["sourcetextencoding"]);
  1739.       if (sourceTextEncoding) {
  1740.         // Re-convert the bytes using the found sourceTextEncoding
  1741.         sherlockLines = sherlockBytesToLines(this._data, sourceTextEncoding);
  1742.         searchSection = getSection(sherlockLines, "search");
  1743.         browserSection = getSection(sherlockLines, "browser");
  1744.       }
  1745.     } catch (ex) {
  1746.       // The conversion using the default charset failed. Remove any non-ascii
  1747.       // bytes and try to find a sourceTextEncoding.
  1748.       var asciiBytes = this._data.filter(function (n) {return !(0x80 & n);});
  1749.       var asciiString = String.fromCharCode.apply(null, asciiBytes);
  1750.       sherlockLines = asciiString.split(NEW_LINES).filter(isUsefulLine);
  1751.       searchSection = getSection(sherlockLines, "search");
  1752.       sourceTextEncoding = parseInt(searchSection["sourcetextencoding"]);
  1753.       if (sourceTextEncoding) {
  1754.         sherlockLines = sherlockBytesToLines(this._data, sourceTextEncoding);
  1755.         searchSection = getSection(sherlockLines, "search");
  1756.         browserSection = getSection(sherlockLines, "browser");
  1757.       } else
  1758.         ERROR("Couldn't find a working charset", Cr.NS_ERROR_FAILURE);
  1759.     }
  1760.  
  1761.     LOG("_parseAsSherlock: Search section:\n" + searchSection.toSource());
  1762.  
  1763.     this._name = searchSection["name"] || err("Missing name!");
  1764.     this._description = searchSection["description"] || "";
  1765.     this._queryCharset = searchSection["querycharset"] ||
  1766.                          queryCharsetFromCode(searchSection["queryencoding"]);
  1767.     this._searchForm = searchSection["searchform"];
  1768.  
  1769.     this._updateInterval = parseInt(browserSection["updatecheckdays"]);
  1770.  
  1771.     this._updateURL = browserSection["update"];
  1772.     this._iconUpdateURL = browserSection["updateicon"];
  1773.  
  1774.     var method = (searchSection["method"] || "GET").toUpperCase();
  1775.     var template = searchSection["action"] || err("Missing action!");
  1776.  
  1777.     var inputs = getInputs(sherlockLines);
  1778.     LOG("_parseAsSherlock: Inputs:\n" + inputs.toSource());
  1779.  
  1780.     var url = null;
  1781.  
  1782.     if (method == "GET") {
  1783.       // Here's how we construct the input string:
  1784.       // <input> is first:  Name Attr:  Prefix      Data           Example:
  1785.       // YES                EMPTY       None        <value>        TEMPLATE<value>
  1786.       // YES                NON-EMPTY   ?           <name>=<value> TEMPLATE?<name>=<value>
  1787.       // NO                 EMPTY       ------------- <ignored> --------------
  1788.       // NO                 NON-EMPTY   &           <name>=<value> TEMPLATE?<n1>=<v1>&<n2>=<v2>
  1789.       for (var i = 0; i < inputs.length; i++) {
  1790.         var name  = inputs[i][0];
  1791.         var value = inputs[i][1];
  1792.         if (i==0) {
  1793.           if (name == "")
  1794.             template += USER_DEFINED;
  1795.           else
  1796.             template += "?" + name + "=" + value;
  1797.         } else if (name != "")
  1798.           template += "&" + name + "=" + value;
  1799.       }
  1800.       url = new EngineURL("text/html", method, template);
  1801.  
  1802.     } else if (method == "POST") {
  1803.       // Create the URL object and just add the parameters directly
  1804.       url = new EngineURL("text/html", method, template);
  1805.       for (var i = 0; i < inputs.length; i++) {
  1806.         var name  = inputs[i][0];
  1807.         var value = inputs[i][1];
  1808.         if (name)
  1809.           url.addParam(name, value);
  1810.       }
  1811.     } else
  1812.       err("Invalid method!");
  1813.  
  1814.     this._urls.push(url);
  1815.   },
  1816.  
  1817.   /**
  1818.    * Returns an XML document object containing the search plugin information,
  1819.    * which can later be used to reload the engine.
  1820.    */
  1821.   _serializeToElement: function SRCH_ENG_serializeToEl() {
  1822.     function appendTextNode(aNameSpace, aLocalName, aValue) {
  1823.       if (!aValue)
  1824.         return null;
  1825.       var node = doc.createElementNS(aNameSpace, aLocalName);
  1826.       node.appendChild(doc.createTextNode(aValue));
  1827.       docElem.appendChild(node);
  1828.       docElem.appendChild(doc.createTextNode("\n"));
  1829.       return node;
  1830.     }
  1831.  
  1832.     var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1833.                  createInstance(Ci.nsIDOMParser);
  1834.  
  1835.     var doc = parser.parseFromString(EMPTY_DOC, "text/xml");
  1836.     var docElem = doc.documentElement;
  1837.  
  1838.     docElem.appendChild(doc.createTextNode("\n"));
  1839.  
  1840.     appendTextNode(OPENSEARCH_NS_11, "ShortName", this.name);
  1841.     appendTextNode(OPENSEARCH_NS_11, "Description", this._description);
  1842.     appendTextNode(OPENSEARCH_NS_11, "InputEncoding", this._queryCharset);
  1843.  
  1844.     if (this._iconURI) {
  1845.       var imageNode = appendTextNode(OPENSEARCH_NS_11, "Image",
  1846.                                      this._iconURI.spec);
  1847.       if (imageNode) {
  1848.         imageNode.setAttribute("width", "16");
  1849.         imageNode.setAttribute("height", "16");
  1850.       }
  1851.     }
  1852.  
  1853.     appendTextNode(MOZSEARCH_NS_10, "UpdateInterval", this._updateInterval);
  1854.     appendTextNode(MOZSEARCH_NS_10, "UpdateUrl", this._updateURL);
  1855.     appendTextNode(MOZSEARCH_NS_10, "IconUpdateUrl", this._iconUpdateURL);
  1856.     appendTextNode(MOZSEARCH_NS_10, "SearchForm", this._searchForm);
  1857.  
  1858.     for (var i = 0; i < this._urls.length; ++i)
  1859.       this._urls[i]._serializeToElement(doc, docElem);
  1860.     docElem.appendChild(doc.createTextNode("\n"));
  1861.  
  1862.     return doc;
  1863.   },
  1864.  
  1865.   _lazySerializeToFile: function SRCH_ENG_serializeToFile() {
  1866.     if (this._serializeTimer) {
  1867.       // Reset the timer
  1868.       this._serializeTimer.delay = LAZY_SERIALIZE_DELAY;
  1869.     } else {
  1870.       this._serializeTimer = Cc["@mozilla.org/timer;1"].
  1871.                              createInstance(Ci.nsITimer);
  1872.       var timerCallback = {
  1873.         self: this,
  1874.         notify: function SRCH_ENG_notify(aTimer) {
  1875.           try {
  1876.             this.self._serializeToFile();
  1877.           } catch (ex) {
  1878.             LOG("Serialization from timer callback failed:\n" + ex);
  1879.           }
  1880.           this.self._serializeTimer = null;
  1881.         }
  1882.       };
  1883.       this._serializeTimer.initWithCallback(timerCallback,
  1884.                                             LAZY_SERIALIZE_DELAY,
  1885.                                             Ci.nsITimer.TYPE_ONE_SHOT);
  1886.     }
  1887.   },
  1888.  
  1889.   /**
  1890.    * Serializes the engine object to file.
  1891.    */
  1892.   _serializeToFile: function SRCH_ENG_serializeToFile() {
  1893.     var file = this._file;
  1894.     ENSURE_WARN(!this._readOnly, "Can't serialize a read only engine!",
  1895.                 Cr.NS_ERROR_FAILURE);
  1896.     ENSURE_WARN(file && file.exists(), "Can't serialize: file doesn't exist!",
  1897.                 Cr.NS_ERROR_UNEXPECTED);
  1898.  
  1899.     var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  1900.               createInstance(Ci.nsIFileOutputStream);
  1901.  
  1902.     // Serialize the engine first - we don't want to overwrite a good file
  1903.     // if this somehow fails.
  1904.     var doc = this._serializeToElement();
  1905.  
  1906.     fos.init(file, (MODE_WRONLY | MODE_TRUNCATE), PERMS_FILE, 0);
  1907.  
  1908.     try {
  1909.       var serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].
  1910.                        createInstance(Ci.nsIDOMSerializer);
  1911.       serializer.serializeToStream(doc.documentElement, fos, null);
  1912.     } catch (e) {
  1913.       LOG("_serializeToFile: Error serializing engine:\n" + e);
  1914.     }
  1915.  
  1916.     closeSafeOutputStream(fos);
  1917.   },
  1918.  
  1919.   /**
  1920.    * Remove the engine's file from disk. The search service calls this once it
  1921.    * removes the engine from its internal store. This function will throw if
  1922.    * the file cannot be removed.
  1923.    */
  1924.   _remove: function SRCH_ENG_remove() {
  1925.     ENSURE(!this._readOnly, "Can't remove read only engine!",
  1926.            Cr.NS_ERROR_FAILURE);
  1927.     ENSURE(this._file && this._file.exists(),
  1928.            "Can't remove engine: file doesn't exist!",
  1929.            Cr.NS_ERROR_FILE_NOT_FOUND);
  1930.  
  1931.     this._file.remove(false);
  1932.   },
  1933.  
  1934.   // nsISearchEngine
  1935.   get alias() {
  1936.     if (this._alias === null)
  1937.       this._alias = engineMetadataService.getAttr(this, "alias");
  1938.  
  1939.     return this._alias;
  1940.   },
  1941.   set alias(val) {
  1942.     this._alias = val;
  1943.     engineMetadataService.setAttr(this, "alias", val);
  1944.     notifyAction(this, SEARCH_ENGINE_CHANGED);
  1945.   },
  1946.  
  1947.   get description() {
  1948.     return this._description;
  1949.   },
  1950.  
  1951.   get hidden() {
  1952.     if (this._hidden === null)
  1953.       this._hidden = engineMetadataService.getAttr(this, "hidden");
  1954.     return this._hidden;
  1955.   },
  1956.   set hidden(val) {
  1957.     var value = !!val;
  1958.     if (value != this._hidden) {
  1959.       this._hidden = value;
  1960.       engineMetadataService.setAttr(this, "hidden", value);
  1961.       notifyAction(this, SEARCH_ENGINE_CHANGED);
  1962.     }
  1963.   },
  1964.  
  1965.   get iconURI() {
  1966.     return this._iconURI;
  1967.   },
  1968.  
  1969.   get _iconURL() {
  1970.     if (!this._iconURI)
  1971.       return "";
  1972.     return this._iconURI.spec;
  1973.   },
  1974.  
  1975.   // Where the engine is being loaded from: will return the URI's spec if the
  1976.   // engine is being downloaded and does not yet have a file. This is only used
  1977.   // for logging.
  1978.   get _location() {
  1979.     if (this._file)
  1980.       return this._file.path;
  1981.  
  1982.     if (this._uri)
  1983.       return this._uri.spec;
  1984.  
  1985.     return "";
  1986.   },
  1987.  
  1988.   // The file that the plugin is loaded from is a unique identifier for it.  We
  1989.   // use this as the identifier to store data in the sqlite database
  1990.   get _id() {
  1991.     ENSURE_WARN(this._file, "No _file for id!", Cr.NS_ERROR_FAILURE);
  1992.  
  1993.     if (this._isInProfile)
  1994.       return "[profile]/" + this._file.leafName;
  1995.  
  1996.     if (this._isInAppDir)
  1997.       return "[app]/" + this._file.leafName;
  1998.  
  1999.     // We're not in the profile or appdir, so this must be an extension-shipped
  2000.     // plugin. Use the full path.
  2001.     return this._file.path;
  2002.   },
  2003.  
  2004.   get _installLocation() {
  2005.     ENSURE_WARN(this._file && this._file.exists(),
  2006.                 "_installLocation: engine has no file!",
  2007.                 Cr.NS_ERROR_FAILURE);
  2008.  
  2009.     if (this.__installLocation === null) {
  2010.       if (this._file.parent.equals(getDir(NS_APP_SEARCH_DIR)))
  2011.         this.__installLocation = SEARCH_APP_DIR;
  2012.       else if (this._file.parent.equals(getDir(NS_APP_USER_SEARCH_DIR)))
  2013.         this.__installLocation = SEARCH_PROFILE_DIR;
  2014.       else
  2015.         this.__installLocation = SEARCH_IN_EXTENSION;
  2016.     }
  2017.  
  2018.     return this.__installLocation;
  2019.   },
  2020.  
  2021.   get _isInAppDir() {
  2022.     return this._installLocation == SEARCH_APP_DIR;
  2023.   },
  2024.   get _isInProfile() {
  2025.     return this._installLocation == SEARCH_PROFILE_DIR;
  2026.   },
  2027.  
  2028.   get _isDefault() {
  2029.     // For now, our concept of a "default engine" is "one that is not in the
  2030.     // user's profile directory", which is currently equivalent to "is app- or
  2031.     // extension-shipped".
  2032.     return !this._isInProfile;
  2033.   },
  2034.  
  2035.   get _hasUpdates() {
  2036.     // Whether or not the engine has an update URL
  2037.     return !!(this._updateURL || this._iconUpdateURL);
  2038.   },
  2039.  
  2040.   get name() {
  2041.     return this._name;
  2042.   },
  2043.  
  2044.   get type() {
  2045.     return this._type;
  2046.   },
  2047.  
  2048.   get searchForm() {
  2049.     if (!this._searchForm) {
  2050.       // No searchForm specified in the engine definition file, use the prePath
  2051.       // (e.g. https://foo.com for https://foo.com/search.php?q=bar).
  2052.       var htmlUrl = this._getURLOfType(URLTYPE_SEARCH_HTML);
  2053.       ENSURE_WARN(htmlUrl, "Engine has no HTML URL!", Cr.NS_ERROR_UNEXPECTED);
  2054.       this._searchForm = makeURI(htmlUrl.template).prePath;
  2055.     }
  2056.  
  2057.     return this._searchForm;
  2058.   },
  2059.  
  2060.   get queryCharset() {
  2061.     if (this._queryCharset)
  2062.       return this._queryCharset;
  2063.     return this._queryCharset = queryCharsetFromCode(/* get the default */);
  2064.   },
  2065.  
  2066.   // from nsISearchEngine
  2067.   addParam: function SRCH_ENG_addParam(aName, aValue, aResponseType) {
  2068.     ENSURE_ARG(aName && (aValue != null),
  2069.                "missing name or value for nsISearchEngine::addParam!");
  2070.     ENSURE_WARN(!this._readOnly,
  2071.                 "called nsISearchEngine::addParam on a read-only engine!",
  2072.                 Cr.NS_ERROR_FAILURE);
  2073.     if (!aResponseType)
  2074.       aResponseType = URLTYPE_SEARCH_HTML;
  2075.  
  2076.     var url = this._getURLOfType(aResponseType);
  2077.  
  2078.     ENSURE(url, "Engine object has no URL for response type " + aResponseType,
  2079.            Cr.NS_ERROR_FAILURE);
  2080.  
  2081.     url.addParam(aName, aValue);
  2082.  
  2083.     // Serialize the changes to file lazily
  2084.     this._lazySerializeToFile();
  2085.   },
  2086.  
  2087.   // from nsISearchEngine
  2088.   getSubmission: function SRCH_ENG_getSubmission(aData, aResponseType) {
  2089.     if (!aResponseType)
  2090.       aResponseType = URLTYPE_SEARCH_HTML;
  2091.  
  2092.     var url = this._getURLOfType(aResponseType);
  2093.  
  2094.     if (!url)
  2095.       return null;
  2096.  
  2097.     if (!aData) {
  2098.       // Return a dummy submission object with our searchForm attribute
  2099.       return new Submission(makeURI(this.searchForm), null);
  2100.     }
  2101.  
  2102.     LOG("getSubmission: In data: \"" + aData + "\"");
  2103.     var textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"].
  2104.                        getService(Ci.nsITextToSubURI);
  2105.     var data = "";
  2106.     try {
  2107.       data = textToSubURI.ConvertAndEscape(this.queryCharset, aData);
  2108.     } catch (ex) {
  2109.       LOG("getSubmission: Falling back to default queryCharset!");
  2110.       data = textToSubURI.ConvertAndEscape(DEFAULT_QUERY_CHARSET, aData);
  2111.     }
  2112.     LOG("getSubmission: Out data: \"" + data + "\"");
  2113.     return url.getSubmission(data, this);
  2114.   },
  2115.  
  2116.   // from nsISearchEngine
  2117.   supportsResponseType: function SRCH_ENG_supportsResponseType(type) {
  2118.     return (this._getURLOfType(type) != null);
  2119.   },
  2120.  
  2121.   // nsISupports
  2122.   QueryInterface: function SRCH_ENG_QI(aIID) {
  2123.     if (aIID.equals(Ci.nsISearchEngine) ||
  2124.         aIID.equals(Ci.nsISupports))
  2125.       return this;
  2126.     throw Cr.NS_ERROR_NO_INTERFACE;
  2127.   },
  2128.  
  2129.   get wrappedJSObject() {
  2130.     return this;
  2131.   }
  2132.  
  2133. };
  2134.  
  2135. // nsISearchSubmission
  2136. function Submission(aURI, aPostData) {
  2137.   this._uri = aURI;
  2138.   this._postData = aPostData;
  2139. }
  2140. Submission.prototype = {
  2141.   get uri() {
  2142.     return this._uri;
  2143.   },
  2144.   get postData() {
  2145.     return this._postData;
  2146.   },
  2147.   QueryInterface: function SRCH_SUBM_QI(aIID) {
  2148.     if (aIID.equals(Ci.nsISearchSubmission) ||
  2149.         aIID.equals(Ci.nsISupports))
  2150.       return this;
  2151.     throw Cr.NS_ERROR_NO_INTERFACE;
  2152.   }
  2153. }
  2154.  
  2155. // nsIBrowserSearchService
  2156. function SearchService() {
  2157.   this._init();
  2158. }
  2159. SearchService.prototype = {
  2160.   _engines: { },
  2161.   _sortedEngines: null,
  2162.   // Whether or not we need to write the order of engines on shutdown. This
  2163.   // needs to happen anytime _sortedEngines is modified after initial startup. 
  2164.   _needToSetOrderPrefs: false,
  2165.  
  2166.   _init: function() {
  2167.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2168.                 getService(Ci.nsIPrefBranch);
  2169.     var shouldLog = false;
  2170.     try {
  2171.       shouldLog = prefB.getBoolPref(BROWSER_SEARCH_PREF + "log");
  2172.     } catch (ex) {}
  2173.  
  2174.     if (shouldLog) {
  2175.       // Replace the empty LOG function with the useful one
  2176.       LOG = DO_LOG;
  2177.     }
  2178.  
  2179.     engineMetadataService.init();
  2180.     engineUpdateService.init();
  2181.  
  2182.     this._addObservers();
  2183.  
  2184.     var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  2185.                       getService(Ci.nsIProperties);
  2186.     var locations = fileLocator.get(NS_APP_SEARCH_DIR_LIST,
  2187.                                     Ci.nsISimpleEnumerator);
  2188.  
  2189.     while (locations.hasMoreElements()) {
  2190.       var location = locations.getNext().QueryInterface(Ci.nsIFile);
  2191.       this._loadEngines(location);
  2192.     }
  2193.  
  2194.     // Now that all engines are loaded, build the sorted engine list
  2195.     this._buildSortedEngineList();
  2196.  
  2197.     selectedEngineName = getLocalizedPref(BROWSER_SEARCH_PREF +
  2198.                                           "selectedEngine");
  2199.     this._currentEngine = this.getEngineByName(selectedEngineName) ||
  2200.                           this.defaultEngine;
  2201.   },
  2202.  
  2203.   _addEngineToStore: function SRCH_SVC_addEngineToStore(aEngine) {
  2204.     LOG("_addEngineToStore: Adding engine: \"" + aEngine.name + "\"");
  2205.  
  2206.     // See if there is an existing engine with the same name. However, if this
  2207.     // engine is updating another engine, it's allowed to have the same name.
  2208.     var hasSameNameAsUpdate = (aEngine._engineToUpdate &&
  2209.                                aEngine.name == aEngine._engineToUpdate.name);
  2210.     if (aEngine.name in this._engines && !hasSameNameAsUpdate) {
  2211.       LOG("_addEngineToStore: Duplicate engine found, aborting!");
  2212.       return;
  2213.     }
  2214.  
  2215.     if (aEngine._engineToUpdate) {
  2216.       // We need to replace engineToUpdate with the engine that just loaded.
  2217.       var oldEngine = aEngine._engineToUpdate;
  2218.  
  2219.       // Remove the old engine from the hash, since it's keyed by name, and our
  2220.       // name might change (the update might have a new name).
  2221.       delete this._engines[oldEngine.name];
  2222.  
  2223.       // Hack: we want to replace the old engine with the new one, but since
  2224.       // people may be holding refs to the nsISearchEngine objects themselves,
  2225.       // we'll just copy over all "private" properties (those without a getter
  2226.       // or setter) from one object to the other.
  2227.       for (var p in aEngine) {
  2228.         if (!(aEngine.__lookupGetter__(p) || aEngine.__lookupSetter__(p)))
  2229.           oldEngine[p] = aEngine[p];
  2230.       }
  2231.       aEngine = oldEngine;
  2232.       aEngine._engineToUpdate = null;
  2233.  
  2234.       // Add the engine back
  2235.       this._engines[aEngine.name] = aEngine;
  2236.       notifyAction(aEngine, SEARCH_ENGINE_CHANGED);
  2237.     } else {
  2238.       // Not an update, just add the new engine.
  2239.       this._engines[aEngine.name] = aEngine;
  2240.       // Only add the engine to the list of sorted engines if the initial list
  2241.       // has already been built (i.e. if this._sortedEngines is non-null). If
  2242.       // it hasn't, we're still loading engines from disk, and will build the
  2243.       // sorted engine list when that initial loading is done.
  2244.       if (this._sortedEngines) {
  2245.         this._sortedEngines.push(aEngine);
  2246.         this._needToSetOrderPrefs = true;
  2247.       }
  2248.       notifyAction(aEngine, SEARCH_ENGINE_ADDED);
  2249.     }
  2250.  
  2251.     if (aEngine._hasUpdates) {
  2252.       // Schedule the engine's next update, if it isn't already.
  2253.       if (!engineMetadataService.getAttr(aEngine, "updateexpir"))
  2254.         engineUpdateService.scheduleNextUpdate(aEngine);
  2255.   
  2256.       // We need to save the engine's _dataType, if this is the first time the
  2257.       // engine is added to the dataStore, since ._dataType isn't persisted
  2258.       // and will change on the next startup (since the engine will then be
  2259.       // XML). We need this so that we know how to load any future updates from
  2260.       // this engine.
  2261.       if (!engineMetadataService.getAttr(aEngine, "updatedatatype"))
  2262.         engineMetadataService.setAttr(aEngine, "updatedatatype",
  2263.                                       aEngine._dataType);
  2264.     }
  2265.   },
  2266.  
  2267.   _loadEngines: function SRCH_SVC_loadEngines(aDir) {
  2268.     LOG("_loadEngines: Searching in " + aDir.path + " for search engines.");
  2269.  
  2270.     // Check whether aDir is the user profile dir
  2271.     var isInProfile = aDir.equals(getDir(NS_APP_USER_SEARCH_DIR));
  2272.  
  2273.     var files = aDir.directoryEntries
  2274.                     .QueryInterface(Ci.nsIDirectoryEnumerator);
  2275.     var ios = Cc["@mozilla.org/network/io-service;1"].
  2276.               getService(Ci.nsIIOService);
  2277.  
  2278.     while (files.hasMoreElements()) {
  2279.       var file = files.nextFile;
  2280.  
  2281.       // Ignore hidden and empty files, and directories
  2282.       if (!file.isFile() || file.fileSize == 0 || file.isHidden())
  2283.         continue;
  2284.  
  2285.       var fileURL = ios.newFileURI(file).QueryInterface(Ci.nsIURL);
  2286.       var fileExtension = fileURL.fileExtension.toLowerCase();
  2287.       var isWritable = isInProfile && file.isWritable();
  2288.  
  2289.       var dataType;
  2290.       switch (fileExtension) {
  2291.         case XML_FILE_EXT:
  2292.           dataType = SEARCH_DATA_XML;
  2293.           break;
  2294.         case SHERLOCK_FILE_EXT:
  2295.           dataType = SEARCH_DATA_TEXT;
  2296.           break;
  2297.         default:
  2298.           // Not an engine
  2299.           continue;
  2300.       }
  2301.  
  2302.       var addedEngine = null;
  2303.       try {
  2304.         addedEngine = new Engine(file, dataType, !isWritable);
  2305.         addedEngine._initFromFile();
  2306.       } catch (ex) {
  2307.         LOG("_loadEngines: Failed to load " + file.path + "!\n" + ex);
  2308.         continue;
  2309.       }
  2310.  
  2311.       if (fileExtension == SHERLOCK_FILE_EXT) {
  2312.         if (isWritable) {
  2313.           try {
  2314.             this._convertSherlockFile(addedEngine, fileURL.fileBaseName);
  2315.           } catch (ex) {
  2316.             LOG("_loadEngines: Failed to convert: " + fileURL.path + "\n" + ex);
  2317.             // The engine couldn't be converted, mark it as read-only
  2318.             addedEngine._readOnly = true;
  2319.           }
  2320.         }
  2321.  
  2322.         // If the engine still doesn't have an icon, see if we can find one
  2323.         if (!addedEngine._iconURI) {
  2324.           var icon = this._findSherlockIcon(file, fileURL.fileBaseName);
  2325.           if (icon)
  2326.             addedEngine._iconURI = ios.newFileURI(icon);
  2327.         }
  2328.       }
  2329.  
  2330.       this._addEngineToStore(addedEngine);
  2331.     }
  2332.   },
  2333.  
  2334.   _saveSortedEngineList: function SRCH_SVC_saveSortedEngineList() {
  2335.     // We only need to write the prefs. if something has changed.
  2336.     if (!this._needToSetOrderPrefs)
  2337.       return;
  2338.  
  2339.     // Set the useDB pref to indicate that from now on we should use the order
  2340.     // information stored in the database.
  2341.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2342.                 getService(Ci.nsIPrefBranch);
  2343.     prefB.setBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", true);
  2344.  
  2345.     var engines = this._getSortedEngines(true);
  2346.     var values = [];
  2347.     var names = [];
  2348.  
  2349.     for (var i = 0; i < engines.length; ++i) {
  2350.       names[i] = "order";
  2351.       values[i] = i + 1;
  2352.     }
  2353.  
  2354.     engineMetadataService.setAttrs(engines, names, values);
  2355.   },
  2356.  
  2357.   _buildSortedEngineList: function SRCH_SVC_buildSortedEngineList() {
  2358.     var addedEngines = { };
  2359.     this._sortedEngines = [];
  2360.     var engine;
  2361.  
  2362.     // If the user has specified a custom engine order, read the order
  2363.     // information from the engineMetadataService instead of the default
  2364.     // prefs.
  2365.     if (getBoolPref(BROWSER_SEARCH_PREF + "useDBForOrder", false)) {
  2366.       for each (engine in this._engines) {
  2367.         var orderNumber = engineMetadataService.getAttr(engine, "order");
  2368.  
  2369.         // Since the DB isn't regularly cleared, and engine files may disappear
  2370.         // without us knowing, we may already have an engine in this slot. If
  2371.         // that happens, we just skip it - it will be added later on as an
  2372.         // unsorted engine. This problem will sort itself out when we call
  2373.         // _saveSortedEngineList at shutdown.
  2374.         if (orderNumber && !this._sortedEngines[orderNumber-1]) {
  2375.           this._sortedEngines[orderNumber-1] = engine;
  2376.           addedEngines[engine.name] = engine;
  2377.         } else {
  2378.           // We need to call _saveSortedEngines so this gets sorted out.
  2379.           this._needToSetOrderPrefs = true;
  2380.         }
  2381.       }
  2382.  
  2383.       // Filter out any nulls for engines that may have been removed
  2384.       var filteredEngines = this._sortedEngines.filter(function(a) { return !!a; });
  2385.       if (this._sortedEngines.length != filteredEngines.length)
  2386.         this._needToSetOrderPrefs = true;
  2387.       this._sortedEngines = filteredEngines;
  2388.  
  2389.     } else {
  2390.       // The DB isn't being used, so just read the engine order from the prefs
  2391.       var i = 0;
  2392.       var engineName;
  2393.       var prefName;
  2394.  
  2395.       try {
  2396.         var prefB = Cc["@mozilla.org/preferences-service;1"].
  2397.                     getService(Ci.nsIPrefBranch);
  2398.         var extras =
  2399.           prefB.getChildList(BROWSER_SEARCH_PREF + "order.extra.", { });
  2400.  
  2401.         for each (prefName in extras) {
  2402.           engineName = prefB.getCharPref(prefName);
  2403.  
  2404.           engine = this._engines[engineName];
  2405.           if (!engine || engine.name in addedEngines)
  2406.             continue;
  2407.  
  2408.           this._sortedEngines.push(engine);
  2409.           addedEngines[engine.name] = engine;
  2410.         }
  2411.       }
  2412.       catch (e) { }
  2413.  
  2414.       while (true) {
  2415.         engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + (++i));
  2416.         if (!engineName)
  2417.           break;
  2418.  
  2419.         engine = this._engines[engineName];
  2420.         if (!engine || engine.name in addedEngines)
  2421.           continue;
  2422.         
  2423.         this._sortedEngines.push(engine);
  2424.         addedEngines[engine.name] = engine;
  2425.       }
  2426.     }
  2427.  
  2428.     // Array for the remaining engines, alphabetically sorted
  2429.     var alphaEngines = [];
  2430.  
  2431.     for each (engine in this._engines) {
  2432.       if (!(engine.name in addedEngines))
  2433.         alphaEngines.push(this._engines[engine.name]);
  2434.     }
  2435.     alphaEngines = alphaEngines.sort(function (a, b) {
  2436.                                        return a.name.localeCompare(b.name);
  2437.                                      });
  2438.     this._sortedEngines = this._sortedEngines.concat(alphaEngines);
  2439.   },
  2440.  
  2441.   /**
  2442.    * Converts a Sherlock file and its icon into the custom XML format used by
  2443.    * the Search Service. Saves the engine's icon (if present) into the XML as a
  2444.    * data: URI and changes the extension of the source file from ".src" to
  2445.    * ".xml". The engine data is then written to the file as XML.
  2446.    * @param aEngine
  2447.    *        The Engine object that needs to be converted.
  2448.    * @param aBaseName
  2449.    *        The basename of the Sherlock file.
  2450.    *          Example: "foo" for file "foo.src".
  2451.    *
  2452.    * @throws NS_ERROR_FAILURE if the file could not be converted.
  2453.    *
  2454.    * @see nsIURL::fileBaseName
  2455.    */
  2456.   _convertSherlockFile: function SRCH_SVC_convertSherlock(aEngine, aBaseName) {
  2457.     var oldSherlockFile = aEngine._file;
  2458.  
  2459.     // Back up the old file
  2460.     try {
  2461.       var backupDir = oldSherlockFile.parent;
  2462.       backupDir.append("searchplugins-backup");
  2463.  
  2464.       if (!backupDir.exists())
  2465.         backupDir.create(Ci.nsIFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  2466.  
  2467.       oldSherlockFile.copyTo(backupDir, null);
  2468.     } catch (ex) {
  2469.       // Just bail. Engines that can't be backed up won't be converted, but
  2470.       // engines that aren't converted are loaded as readonly.
  2471.       LOG("_convertSherlockFile: Couldn't back up " + oldSherlockFile.path +
  2472.           ":\n" + ex);
  2473.       throw Cr.NS_ERROR_FAILURE;
  2474.     }
  2475.  
  2476.     // Rename the file, but don't clobber existing files
  2477.     var newXMLFile = oldSherlockFile.parent.clone();
  2478.     newXMLFile.append(aBaseName + "." + XML_FILE_EXT);
  2479.  
  2480.     if (newXMLFile.exists()) {
  2481.       // There is an existing file with this name, create a unique file
  2482.       newXMLFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE);
  2483.     }
  2484.  
  2485.     // Rename the .src file to .xml
  2486.     oldSherlockFile.moveTo(null, newXMLFile.leafName);
  2487.  
  2488.     aEngine._file = newXMLFile;
  2489.  
  2490.     // Write the converted engine to disk
  2491.     aEngine._serializeToFile();
  2492.  
  2493.     // Update the engine's _type.
  2494.     aEngine._type = SEARCH_TYPE_MOZSEARCH;
  2495.  
  2496.     // See if it has a corresponding icon
  2497.     try {
  2498.       var icon = this._findSherlockIcon(aEngine._file, aBaseName);
  2499.       if (icon && icon.fileSize < MAX_ICON_SIZE) {
  2500.         // Use this as the engine's icon
  2501.         var bStream = Cc["@mozilla.org/binaryinputstream;1"].
  2502.                         createInstance(Ci.nsIBinaryInputStream);
  2503.         var fileInStream = Cc["@mozilla.org/network/file-input-stream;1"].
  2504.                            createInstance(Ci.nsIFileInputStream);
  2505.  
  2506.         fileInStream.init(icon, MODE_RDONLY, PERMS_FILE, 0);
  2507.         bStream.setInputStream(fileInStream);
  2508.  
  2509.         var bytes = [];
  2510.         while (bStream.available() != 0)
  2511.           bytes = bytes.concat(bStream.readByteArray(bStream.available()));
  2512.         bStream.close();
  2513.  
  2514.         // Convert the byte array to a base64-encoded string
  2515.         var str = btoa(String.fromCharCode.apply(null, bytes));
  2516.  
  2517.         aEngine._iconURI = makeURI(ICON_DATAURL_PREFIX + str);
  2518.         LOG("_importSherlockEngine: Set sherlock iconURI to: \"" +
  2519.             aEngine._iconURL + "\"");
  2520.  
  2521.         // Write the engine to disk to save changes
  2522.         aEngine._serializeToFile();
  2523.  
  2524.         // Delete the icon now that we're sure everything's been saved
  2525.         icon.remove(false);
  2526.       }
  2527.     } catch (ex) { LOG("_convertSherlockFile: Error setting icon:\n" + ex); }
  2528.   },
  2529.  
  2530.   /**
  2531.    * Finds an icon associated to a given Sherlock file. Searches the provided
  2532.    * file's parent directory looking for files with the same base name and one
  2533.    * of the file extensions in SHERLOCK_ICON_EXTENSIONS.
  2534.    * @param aEngineFile
  2535.    *        The Sherlock plugin file.
  2536.    * @param aBaseName
  2537.    *        The basename of the Sherlock file.
  2538.    *          Example: "foo" for file "foo.src".
  2539.    * @see nsIURL::fileBaseName
  2540.    */
  2541.   _findSherlockIcon: function SRCH_SVC_findSherlock(aEngineFile, aBaseName) {
  2542.     for (var i = 0; i < SHERLOCK_ICON_EXTENSIONS.length; i++) {
  2543.       var icon = aEngineFile.parent.clone();
  2544.       icon.append(aBaseName + SHERLOCK_ICON_EXTENSIONS[i]);
  2545.       if (icon.exists() && icon.isFile())
  2546.         return icon;
  2547.     }
  2548.     return null;
  2549.   },
  2550.  
  2551.   /**
  2552.    * Get a sorted array of engines.
  2553.    * @param aWithHidden
  2554.    *        True if hidden plugins should be included in the result.
  2555.    */
  2556.   _getSortedEngines: function SRCH_SVC_getSorted(aWithHidden) {
  2557.     if (aWithHidden)
  2558.       return this._sortedEngines;
  2559.  
  2560.     return this._sortedEngines.filter(function (engine) {
  2561.                                         return !engine.hidden;
  2562.                                       });
  2563.   },
  2564.  
  2565.   // nsIBrowserSearchService
  2566.   getEngines: function SRCH_SVC_getEngines(aCount) {
  2567.     LOG("getEngines: getting all engines");
  2568.     var engines = this._getSortedEngines(true);
  2569.     aCount.value = engines.length;
  2570.     return engines;
  2571.   },
  2572.  
  2573.   getVisibleEngines: function SRCH_SVC_getVisible(aCount) {
  2574.     LOG("getVisibleEngines: getting all visible engines");
  2575.     var engines = this._getSortedEngines(false);
  2576.     aCount.value = engines.length;
  2577.     return engines;
  2578.   },
  2579.  
  2580.   getDefaultEngines: function SRCH_SVC_getDefault(aCount) {
  2581.     function isDefault(engine) {
  2582.       return engine._isDefault;
  2583.     };
  2584.     var engines = this._sortedEngines.filter(isDefault);
  2585.     var engineOrder = {};
  2586.     var engineName;
  2587.     var i = 1;
  2588.  
  2589.     // Build a list of engines which we have ordering information for.
  2590.     // We're rebuilding the list here because _sortedEngines contain the
  2591.     // current order, but we want the original order.
  2592.  
  2593.     // First, look at the "browser.search.order.extra" branch.
  2594.     try {
  2595.       var prefB = Cc["@mozilla.org/preferences-service;1"].
  2596.                   getService(Ci.nsIPrefBranch);
  2597.       var extras = prefB.getChildList(BROWSER_SEARCH_PREF + "order.extra.",
  2598.                                       {});
  2599.  
  2600.       for each (var prefName in extras) {
  2601.         engineName = prefB.getCharPref(prefName);
  2602.  
  2603.         if (!(engineName in engineOrder))
  2604.           engineOrder[engineName] = i++;
  2605.       }
  2606.     } catch (e) {
  2607.       LOG("Getting extra order prefs failed: " + e);
  2608.     }
  2609.  
  2610.     // Now look through the "browser.search.order" branch.
  2611.     for (var j = 1; ; j++) {
  2612.       engineName = getLocalizedPref(BROWSER_SEARCH_PREF + "order." + j);
  2613.       if (!engineName)
  2614.         break;
  2615.  
  2616.       if (!(engineName in engineOrder))
  2617.         engineOrder[engineName] = i++;
  2618.     }
  2619.  
  2620.     LOG("getDefaultEngines: engineOrder: " + engineOrder.toSource());
  2621.  
  2622.     function compareEngines (a, b) {
  2623.       var aIdx = engineOrder[a.name];
  2624.       var bIdx = engineOrder[b.name];
  2625.  
  2626.       if (aIdx && bIdx)
  2627.         return aIdx - bIdx;
  2628.       if (aIdx)
  2629.         return -1;
  2630.       if (bIdx)
  2631.         return 1;
  2632.  
  2633.       return a.name.localeCompare(b.name);
  2634.     }
  2635.     engines.sort(compareEngines);
  2636.  
  2637.     aCount.value = engines.length;
  2638.     return engines;
  2639.   },
  2640.  
  2641.   getEngineByName: function SRCH_SVC_getEngineByName(aEngineName) {
  2642.     return this._engines[aEngineName] || null;
  2643.   },
  2644.  
  2645.   getEngineByAlias: function SRCH_SVC_getEngineByAlias(aAlias) {
  2646.     for (var engineName in this._engines) {
  2647.       var engine = this._engines[engineName];
  2648.       if (engine && engine.alias == aAlias)
  2649.         return engine;
  2650.     }
  2651.     return null;
  2652.   },
  2653.  
  2654.   addEngineWithDetails: function SRCH_SVC_addEWD(aName, aIconURL, aAlias,
  2655.                                                  aDescription, aMethod,
  2656.                                                  aTemplate) {
  2657.     ENSURE_ARG(aName, "Invalid name passed to addEngineWithDetails!");
  2658.     ENSURE_ARG(aMethod, "Invalid method passed to addEngineWithDetails!");
  2659.     ENSURE_ARG(aTemplate, "Invalid template passed to addEngineWithDetails!");
  2660.  
  2661.     ENSURE(!this._engines[aName], "An engine with that name already exists!",
  2662.            Cr.NS_ERROR_FILE_ALREADY_EXISTS);
  2663.  
  2664.     var engine = new Engine(getSanitizedFile(aName), SEARCH_DATA_XML, false);
  2665.     engine._initFromMetadata(aName, aIconURL, aAlias, aDescription,
  2666.                              aMethod, aTemplate);
  2667.     this._addEngineToStore(engine);
  2668.   },
  2669.  
  2670.   addEngine: function SRCH_SVC_addEngine(aEngineURL, aDataType, aIconURL,
  2671.                                          aConfirm) {
  2672.     LOG("addEngine: Adding \"" + aEngineURL + "\".");
  2673.     try {
  2674.       var uri = makeURI(aEngineURL);
  2675.       var engine = new Engine(uri, aDataType, false);
  2676.       engine._initFromURI();
  2677.     } catch (ex) {
  2678.       LOG("addEngine: Error adding engine:\n" + ex);
  2679.       throw Cr.NS_ERROR_FAILURE;
  2680.     }
  2681.     engine._setIcon(aIconURL, false);
  2682.     engine._confirm = aConfirm;
  2683.   },
  2684.  
  2685.   removeEngine: function SRCH_SVC_removeEngine(aEngine) {
  2686.     ENSURE_ARG(aEngine, "no engine passed to removeEngine!");
  2687.  
  2688.     var engineToRemove = null;
  2689.     for (var e in this._engines)
  2690.       if (aEngine.wrappedJSObject == this._engines[e])
  2691.         engineToRemove = this._engines[e];
  2692.  
  2693.     ENSURE(engineToRemove, "removeEngine: Can't find engine to remove!",
  2694.            Cr.NS_ERROR_FILE_NOT_FOUND);
  2695.  
  2696.     if (engineToRemove == this.currentEngine)
  2697.       this._currentEngine = null;
  2698.  
  2699.     if (engineToRemove._readOnly) {
  2700.       // Just hide it (the "hidden" setter will notify) and remove its alias to
  2701.       // avoid future conflicts with other engines.
  2702.       engineToRemove.hidden = true;
  2703.       engineToRemove.alias = null;
  2704.     } else {
  2705.       // Cancel the lazy serialization timer if it's running
  2706.       if (engineToRemove._serializeTimer) {
  2707.         engineToRemove._serializeTimer.cancel();
  2708.         engineToRemove._serializeTimer = null;
  2709.       }
  2710.  
  2711.       // Remove the engine file from disk (this might throw)
  2712.       engineToRemove._remove();
  2713.       engineToRemove._file = null;
  2714.  
  2715.       // Remove the engine from _sortedEngines
  2716.       var index = this._sortedEngines.indexOf(engineToRemove);
  2717.       ENSURE(index != -1, "Can't find engine to remove in _sortedEngines!",
  2718.              Cr.NS_ERROR_FAILURE);
  2719.       this._sortedEngines.splice(index, 1);
  2720.  
  2721.       // Remove the engine from the internal store
  2722.       delete this._engines[engineToRemove.name];
  2723.  
  2724.       notifyAction(engineToRemove, SEARCH_ENGINE_REMOVED);
  2725.  
  2726.       // Since we removed an engine, we need to update the preferences.
  2727.       this._needToSetOrderPrefs = true;
  2728.     }
  2729.   },
  2730.  
  2731.   moveEngine: function SRCH_SVC_moveEngine(aEngine, aNewIndex) {
  2732.     ENSURE_ARG((aNewIndex < this._sortedEngines.length) && (aNewIndex >= 0),
  2733.                "SRCH_SVC_moveEngine: Index out of bounds!");
  2734.     ENSURE_ARG(aEngine instanceof Ci.nsISearchEngine,
  2735.                "SRCH_SVC_moveEngine: Invalid engine passed to moveEngine!");
  2736.     ENSURE(!aEngine.hidden, "moveEngine: Can't move a hidden engine!",
  2737.            Cr.NS_ERROR_FAILURE);
  2738.  
  2739.     var engine = aEngine.wrappedJSObject;
  2740.  
  2741.     var currentIndex = this._sortedEngines.indexOf(engine);
  2742.     ENSURE(currentIndex != -1, "moveEngine: Can't find engine to move!",
  2743.            Cr.NS_ERROR_UNEXPECTED);
  2744.  
  2745.     // Our callers only take into account non-hidden engines when calculating
  2746.     // aNewIndex, but we need to move it in the array of all engines, so we
  2747.     // need to adjust aNewIndex accordingly. To do this, we count the number
  2748.     // of hidden engines in the list before the engine that we're taking the
  2749.     // place of. We do this by first finding newIndexEngine (the engine that
  2750.     // we were supposed to replace) and then iterating through the complete 
  2751.     // engine list until we reach it, increasing aNewIndex for each hidden
  2752.     // engine we find on our way there.
  2753.     //
  2754.     // This could be further simplified by having our caller pass in
  2755.     // newIndexEngine directly instead of aNewIndex.
  2756.     var newIndexEngine = this._getSortedEngines(false)[aNewIndex];
  2757.     ENSURE(newIndexEngine, "moveEngine: Can't find engine to replace!",
  2758.            Cr.NS_ERROR_UNEXPECTED);
  2759.  
  2760.     for (var i = 0; i < this._sortedEngines.length; ++i) {
  2761.       if (newIndexEngine == this._sortedEngines[i])
  2762.         break;
  2763.       if (this._sortedEngines[i].hidden)
  2764.         aNewIndex++;
  2765.     }
  2766.  
  2767.     if (currentIndex == aNewIndex)
  2768.       return; // nothing to do!
  2769.  
  2770.     // Move the engine
  2771.     var movedEngine = this._sortedEngines.splice(currentIndex, 1)[0];
  2772.     this._sortedEngines.splice(aNewIndex, 0, movedEngine);
  2773.  
  2774.     notifyAction(engine, SEARCH_ENGINE_CHANGED);
  2775.  
  2776.     // Since we moved an engine, we need to update the preferences.
  2777.     this._needToSetOrderPrefs = true;
  2778.   },
  2779.  
  2780.   restoreDefaultEngines: function SRCH_SVC_resetDefaultEngines() {
  2781.     for each (var e in this._engines) {
  2782.       // Unhide all default engines
  2783.       if (e.hidden && e._isDefault)
  2784.         e.hidden = false;
  2785.     }
  2786.   },
  2787.  
  2788.   get defaultEngine() {
  2789.     const defPref = BROWSER_SEARCH_PREF + "defaultenginename";
  2790.     // Get the default engine - this pref should always exist, but the engine
  2791.     // might be hidden
  2792.     this._defaultEngine = this.getEngineByName(getLocalizedPref(defPref, ""));
  2793.     if (!this._defaultEngine || this._defaultEngine.hidden)
  2794.       this._defaultEngine = this._getSortedEngines(false)[0] || null;
  2795.     return this._defaultEngine;
  2796.   },
  2797.  
  2798.   get currentEngine() {
  2799.     if (!this._currentEngine || this._currentEngine.hidden)
  2800.       this._currentEngine = this.defaultEngine;
  2801.     return this._currentEngine;
  2802.   },
  2803.   set currentEngine(val) {
  2804.     ENSURE_ARG(val instanceof Ci.nsISearchEngine,
  2805.                "Invalid argument passed to currentEngine setter");
  2806.  
  2807.     var newCurrentEngine = this.getEngineByName(val.name);
  2808.     ENSURE(newCurrentEngine, "Can't find engine in store!",
  2809.            Cr.NS_ERROR_UNEXPECTED);
  2810.  
  2811.     this._currentEngine = newCurrentEngine;
  2812.  
  2813.     var currentEnginePref = BROWSER_SEARCH_PREF + "selectedEngine";
  2814.  
  2815.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  2816.       getService(Ci.nsIPrefService).QueryInterface(Ci.nsIPrefBranch);
  2817.  
  2818.     if (this._currentEngine == this.defaultEngine) {
  2819.       if (prefB.prefHasUserValue(currentEnginePref))
  2820.         prefB.clearUserPref(currentEnginePref);
  2821.     }
  2822.     else {
  2823.       setLocalizedPref(currentEnginePref, this._currentEngine.name);
  2824.     }
  2825.  
  2826.     notifyAction(this._currentEngine, SEARCH_ENGINE_CURRENT);
  2827.   },
  2828.  
  2829.   // nsIObserver
  2830.   observe: function SRCH_SVC_observe(aEngine, aTopic, aVerb) {
  2831.     switch (aTopic) {
  2832.       case SEARCH_ENGINE_TOPIC:
  2833.         if (aVerb == SEARCH_ENGINE_LOADED) {
  2834.           var engine = aEngine.QueryInterface(Ci.nsISearchEngine);
  2835.           LOG("nsSearchService::observe: Done installation of " + engine.name
  2836.               + ".");
  2837.           this._addEngineToStore(engine.wrappedJSObject);
  2838.           if (engine.wrappedJSObject._useNow) {
  2839.             LOG("nsSearchService::observe: setting current");
  2840.             this.currentEngine = aEngine;
  2841.           }
  2842.         }
  2843.         break;
  2844.       case QUIT_APPLICATION_TOPIC:
  2845.         this._removeObservers();
  2846.         this._saveSortedEngineList();
  2847.         break;
  2848.     }
  2849.   },
  2850.  
  2851.   _addObservers: function SRCH_SVC_addObservers() {
  2852.     var os = Cc["@mozilla.org/observer-service;1"].
  2853.              getService(Ci.nsIObserverService);
  2854.     os.addObserver(this, SEARCH_ENGINE_TOPIC, false);
  2855.     os.addObserver(this, QUIT_APPLICATION_TOPIC, false);
  2856.   },
  2857.  
  2858.   _removeObservers: function SRCH_SVC_removeObservers() {
  2859.     var os = Cc["@mozilla.org/observer-service;1"].
  2860.              getService(Ci.nsIObserverService);
  2861.     os.removeObserver(this, SEARCH_ENGINE_TOPIC);
  2862.     os.removeObserver(this, QUIT_APPLICATION_TOPIC);
  2863.   },
  2864.  
  2865.   QueryInterface: function SRCH_SVC_QI(aIID) {
  2866.     if (aIID.equals(Ci.nsIBrowserSearchService) ||
  2867.         aIID.equals(Ci.nsIObserver)             ||
  2868.         aIID.equals(Ci.nsISupports))
  2869.       return this;
  2870.     throw Cr.NS_ERROR_NO_INTERFACE;
  2871.   }
  2872. };
  2873.  
  2874. var engineMetadataService = {
  2875.   init: function epsInit() {
  2876.     var engineDataTable = "id INTEGER PRIMARY KEY, engineid STRING, name STRING, value STRING";
  2877.     var file = getDir(NS_APP_USER_PROFILE_50_DIR);
  2878.     file.append("search.sqlite");
  2879.     var dbService = Cc["@mozilla.org/storage/service;1"].
  2880.                     getService(Ci.mozIStorageService);
  2881.     try {
  2882.         this.mDB = dbService.openDatabase(file);
  2883.     } catch (ex) {
  2884.         if (ex.result == 0x8052000b) { /* NS_ERROR_FILE_CORRUPTED */
  2885.             // delete and try again
  2886.             file.remove(false);
  2887.             this.mDB = dbService.openDatabase(file);
  2888.         } else {
  2889.             throw ex;
  2890.         }
  2891.     }
  2892.  
  2893.     try {
  2894.       this.mDB.createTable("engine_data", engineDataTable);
  2895.     } catch (ex) {
  2896.       // Fails if the table already exists, which is fine
  2897.     }
  2898.  
  2899.     this.mGetData = createStatement (
  2900.       this.mDB,
  2901.       "SELECT value FROM engine_data WHERE engineid = :engineid AND name = :name");
  2902.     this.mDeleteData = createStatement (
  2903.       this.mDB,
  2904.       "DELETE FROM engine_data WHERE engineid = :engineid AND name = :name");
  2905.     this.mInsertData = createStatement (
  2906.       this.mDB,
  2907.       "INSERT INTO engine_data (engineid, name, value) " +
  2908.       "VALUES (:engineid, :name, :value)");
  2909.   },
  2910.   getAttr: function epsGetAttr(engine, name) {
  2911.      // attr names must be lower case
  2912.      name = name.toLowerCase();
  2913.  
  2914.     var stmt = this.mGetData;
  2915.     stmt.reset();
  2916.     var pp = stmt.params;
  2917.     pp.engineid = engine._id;
  2918.     pp.name = name;
  2919.  
  2920.     var value = null;
  2921.     if (stmt.step())
  2922.       value = stmt.row.value;
  2923.     stmt.reset();
  2924.     return value;
  2925.   },
  2926.  
  2927.   setAttr: function epsSetAttr(engine, name, value) {
  2928.     // attr names must be lower case
  2929.     name = name.toLowerCase();
  2930.  
  2931.     this.mDB.beginTransaction();
  2932.  
  2933.     var pp = this.mDeleteData.params;
  2934.     pp.engineid = engine._id;
  2935.     pp.name = name;
  2936.     this.mDeleteData.step();
  2937.     this.mDeleteData.reset();
  2938.  
  2939.     pp = this.mInsertData.params;
  2940.     pp.engineid = engine._id;
  2941.     pp.name = name;
  2942.     pp.value = value;
  2943.     this.mInsertData.step();
  2944.     this.mInsertData.reset();
  2945.  
  2946.     this.mDB.commitTransaction();
  2947.   },
  2948.  
  2949.   setAttrs: function epsSetAttrs(engines, names, values) {
  2950.     this.mDB.beginTransaction();
  2951.  
  2952.     for (var i = 0; i < engines.length; i++) {
  2953.       // attr names must be lower case
  2954.       var name = names[i].toLowerCase();
  2955.  
  2956.       var pp = this.mDeleteData.params;
  2957.       pp.engineid = engines[i]._id;
  2958.       pp.name = names[i];
  2959.       this.mDeleteData.step();
  2960.       this.mDeleteData.reset();
  2961.  
  2962.       pp = this.mInsertData.params;
  2963.       pp.engineid = engines[i]._id;
  2964.       pp.name = names[i];
  2965.       pp.value = values[i];
  2966.       this.mInsertData.step();
  2967.       this.mInsertData.reset();
  2968.     }
  2969.  
  2970.     this.mDB.commitTransaction();
  2971.   },
  2972.  
  2973.   deleteEngineData: function epsDelData(engine, name) {
  2974.     // attr names must be lower case
  2975.     name = name.toLowerCase();
  2976.  
  2977.     var pp = this.mDeleteData.params;
  2978.     pp.engineid = engine._id;
  2979.     pp.name = name;
  2980.     this.mDeleteData.step();
  2981.     this.mDeleteData.reset();
  2982.   }
  2983. }
  2984.  
  2985. const SEARCH_UPDATE_LOG_PREFIX = "*** Search update: ";
  2986.  
  2987. /**
  2988.  * Outputs aText to the JavaScript console as well as to stdout, if the search
  2989.  * logging pref (browser.search.update.log) is set to true.
  2990.  */
  2991. function ULOG(aText) {
  2992.   var prefB = Cc["@mozilla.org/preferences-service;1"].
  2993.               getService(Ci.nsIPrefBranch);
  2994.   var shouldLog = false;
  2995.   try {
  2996.     shouldLog = prefB.getBoolPref(BROWSER_SEARCH_PREF + "update.log");
  2997.   } catch (ex) {}
  2998.  
  2999.   if (shouldLog) {
  3000.     dump(SEARCH_UPDATE_LOG_PREFIX + aText + "\n");
  3001.     var consoleService = Cc["@mozilla.org/consoleservice;1"].
  3002.                          getService(Ci.nsIConsoleService);
  3003.     consoleService.logStringMessage(aText);
  3004.   }
  3005. }
  3006.  
  3007. var engineUpdateService = {
  3008.   init: function eus_init() {
  3009.     var tm = Cc["@mozilla.org/updates/timer-manager;1"].
  3010.              getService(Ci.nsIUpdateTimerManager);
  3011.     // figure out how often to check for any expired engines
  3012.     var prefB = Cc["@mozilla.org/preferences-service;1"].
  3013.                 getService(Ci.nsIPrefBranch);
  3014.     var interval = prefB.getIntPref(BROWSER_SEARCH_PREF + "updateinterval");
  3015.  
  3016.     // Interval is stored in hours
  3017.     var seconds = interval * 3600;
  3018.     tm.registerTimer("search-engine-update-timer", engineUpdateService,
  3019.                      seconds);
  3020.   },
  3021.  
  3022.   scheduleNextUpdate: function eus_scheduleNextUpdate(aEngine) {
  3023.     var interval = aEngine._updateInterval || SEARCH_DEFAULT_UPDATE_INTERVAL;
  3024.     var milliseconds = interval * 86400000; // |interval| is in days
  3025.     engineMetadataService.setAttr(aEngine, "updateexpir",
  3026.                                   Date.now() + milliseconds);
  3027.   },
  3028.  
  3029.   notify: function eus_Notify(aTimer) {
  3030.     ULOG("notify called");
  3031.  
  3032.     if (!getBoolPref(BROWSER_SEARCH_PREF + "update", true))
  3033.       return;
  3034.  
  3035.     // Our timer has expired, but unfortunately, we can't get any data from it.
  3036.     // Therefore, we need to walk our engine-list, looking for expired engines
  3037.     var searchService = Cc["@mozilla.org/browser/search-service;1"].
  3038.                         getService(Ci.nsIBrowserSearchService);
  3039.     var currentTime = Date.now();
  3040.     ULOG("currentTime: " + currentTime);
  3041.     for each (engine in searchService.getEngines({})) {
  3042.       engine = engine.wrappedJSObject;
  3043.       if (!engine._hasUpdates || engine._readOnly)
  3044.         continue;
  3045.  
  3046.       ULOG("checking " + engine.name);
  3047.  
  3048.       var expirTime = engineMetadataService.getAttr(engine, "updateexpir");
  3049.       var updateURL = engine._updateURL;
  3050.       var iconUpdateURL = engine._iconUpdateURL;
  3051.       ULOG("expirTime: " + expirTime + "\nupdateURL: " + updateURL +
  3052.            "\niconUpdateURL: " + iconUpdateURL);
  3053.  
  3054.       var engineExpired = expirTime <= currentTime;
  3055.  
  3056.       if (!expirTime || !engineExpired) {
  3057.         ULOG("skipping engine");
  3058.         continue;
  3059.       }
  3060.  
  3061.       ULOG(engine.name + " has expired");
  3062.  
  3063.       var testEngine = null;
  3064.  
  3065.       var updateURI = makeURI(updateURL);
  3066.       if (updateURI) {
  3067.         var dataType = engineMetadataService.getAttr(engine, "updatedatatype")
  3068.         if (!dataType) {
  3069.           ULOG("No loadtype to update engine!");
  3070.           continue;
  3071.         }
  3072.  
  3073.         testEngine = new Engine(updateURI, dataType, false);
  3074.         testEngine._engineToUpdate = engine;
  3075.         testEngine._initFromURI();
  3076.       } else
  3077.         ULOG("invalid updateURI");
  3078.  
  3079.       if (iconUpdateURL) {
  3080.         // If we're updating the engine too, use the new engine object,
  3081.         // otherwise use the existing engine object.
  3082.         (testEngine || engine)._setIcon(iconUpdateURL, true);
  3083.       }
  3084.  
  3085.       // Schedule the next update
  3086.       this.scheduleNextUpdate(engine);
  3087.  
  3088.     } // end engine iteration
  3089.   }
  3090. };
  3091.  
  3092. const kClassID    = Components.ID("{7319788a-fe93-4db3-9f39-818cf08f4256}");
  3093. const kClassName  = "Browser Search Service";
  3094. const kContractID = "@mozilla.org/browser/search-service;1";
  3095.  
  3096. // nsIFactory
  3097. const kFactory = {
  3098.   createInstance: function (outer, iid) {
  3099.     if (outer != null)
  3100.       throw Cr.NS_ERROR_NO_AGGREGATION;
  3101.     return (new SearchService()).QueryInterface(iid);
  3102.   }
  3103. };
  3104.  
  3105. // nsIModule
  3106. const gModule = {
  3107.   registerSelf: function (componentManager, fileSpec, location, type) {
  3108.     componentManager.QueryInterface(Ci.nsIComponentRegistrar);
  3109.     componentManager.registerFactoryLocation(kClassID,
  3110.                                              kClassName,
  3111.                                              kContractID,
  3112.                                              fileSpec, location, type);
  3113.   },
  3114.  
  3115.   unregisterSelf: function(componentManager, fileSpec, location) {
  3116.     componentManager.QueryInterface(Ci.nsIComponentRegistrar);
  3117.     componentManager.unregisterFactoryLocation(kClassID, fileSpec);
  3118.   },
  3119.  
  3120.   getClassObject: function (componentManager, cid, iid) {
  3121.     if (!cid.equals(kClassID))
  3122.       throw Cr.NS_ERROR_NO_INTERFACE;
  3123.     if (!iid.equals(Ci.nsIFactory))
  3124.       throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  3125.     return kFactory;
  3126.   },
  3127.  
  3128.   canUnload: function (componentManager) {
  3129.     return true;
  3130.   }
  3131. };
  3132.  
  3133. function NSGetModule(componentManager, fileSpec) {
  3134.   return gModule;
  3135. }
  3136.  
  3137. //@line 44 "/build/buildd/firefox-3.0-3.0.14+build2+nobinonly/build-tree/mozilla/toolkit/content/debug.js"
  3138.  
  3139. var EXPORTED_SYMBOLS = ["NS_ASSERT"];
  3140.  
  3141. var gTraceOnAssert = true;
  3142.  
  3143. /**
  3144.  * This function provides a simple assertion function for JavaScript.
  3145.  * If the condition is true, this function will do nothing.  If the
  3146.  * condition is false, then the message will be printed to the console
  3147.  * and an alert will appear showing a stack trace, so that the (alpha
  3148.  * or nightly) user can file a bug containing it.  For future enhancements, 
  3149.  * see bugs 330077 and 330078.
  3150.  *
  3151.  * To suppress the dialogs, you can run with the environment variable
  3152.  * XUL_ASSERT_PROMPT set to 0 (if unset, this defaults to 1).
  3153.  *
  3154.  * @param condition represents the condition that we're asserting to be
  3155.  *                  true when we call this function--should be
  3156.  *                  something that can be evaluated as a boolean.
  3157.  * @param message   a string to be displayed upon failure of the assertion
  3158.  */
  3159.  
  3160. function NS_ASSERT(condition, message) {
  3161.   if (condition)
  3162.     return;
  3163.  
  3164.   var releaseBuild = true;
  3165.   var defB = Components.classes["@mozilla.org/preferences-service;1"]
  3166.                        .getService(Components.interfaces.nsIPrefService)
  3167.                        .getDefaultBranch(null);
  3168.   try {
  3169.     switch (defB.getCharPref("app.update.channel")) {
  3170.       case "nightly":
  3171.       case "beta":
  3172.       case "default":
  3173.         releaseBuild = false;
  3174.     }
  3175.   } catch(ex) {}
  3176.  
  3177.   var caller = arguments.callee.caller;
  3178.   var assertionText = "ASSERT: " + message + "\n";
  3179.  
  3180.   if (releaseBuild) {
  3181.     // Just report the error to the console
  3182.     Components.utils.reportError(assertionText);
  3183.     return;
  3184.   }
  3185.  
  3186.   // Otherwise, dump to stdout and launch an assertion failure dialog
  3187.   dump(assertionText);
  3188.  
  3189.   var stackText = "";
  3190.   if (gTraceOnAssert) {
  3191.     stackText = "Stack Trace: \n";
  3192.     var count = 0;
  3193.     while (caller) {
  3194.       stackText += count++ + ":" + caller.name + "(";
  3195.       for (var i = 0; i < caller.arguments.length; ++i) {
  3196.         var arg = caller.arguments[i];
  3197.         stackText += arg;
  3198.         if (i < caller.arguments.length - 1)
  3199.           stackText += ",";
  3200.       }
  3201.       stackText += ")\n";
  3202.       caller = caller.arguments.callee.caller;
  3203.     }
  3204.   }
  3205.  
  3206.   var environment = Components.classes["@mozilla.org/process/environment;1"].
  3207.                     getService(Components.interfaces.nsIEnvironment);
  3208.   if (environment.exists("XUL_ASSERT_PROMPT") &&
  3209.       !parseInt(environment.get("XUL_ASSERT_PROMPT")))
  3210.     return;
  3211.  
  3212.   var source = null;
  3213.   if (this.window)
  3214.     source = this.window;
  3215.   var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].
  3216.            getService(Components.interfaces.nsIPromptService);
  3217.   ps.alert(source, "Assertion Failed", assertionText + stackText);
  3218. }
  3219.