home *** CD-ROM | disk | FTP | other *** search
/ Chip 2008 June / CHIP-2008-06.iso / bonus / +10SecurityTips / files / xB-Browser_2.0.0.12b.exe / App / Browser / firefox / components / nsSearchService.js < prev    next >
Encoding:
Text File  |  2008-02-02  |  104.5 KB  |  3,094 lines

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