home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / firefox / components / nsExtensionManager.js < prev    next >
Encoding:
Text File  |  2007-04-03  |  311.5 KB  |  8,338 lines

  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Mozilla Public License Version
  6.  * 1.1 (the "License"); you may not use this file except in compliance with
  7.  * the License. You may obtain a copy of the License at
  8.  * http://www.mozilla.org/MPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS IS" basis,
  11.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12.  * for the specific language governing rights and limitations under the
  13.  * License.
  14.  *
  15.  * The Original Code is the Extension Manager.
  16.  *
  17.  * The Initial Developer of the Original Code is Ben Goodger.
  18.  * Portions created by the Initial Developer are Copyright (C) 2004
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *  Ben Goodger <ben@mozilla.org> (Google Inc.)
  23.  *  Benjamin Smedberg <benjamin@smedbergs.us>
  24.  *  Jens Bannmann <jens.b@web.de>
  25.  *  Robert Strong <robert.bugzilla@gmail.com>
  26.  *  Dave Townsend <dave.townsend@blueprintit.co.uk>
  27.  *  Daniel Veditz <dveditz@mozilla.com>
  28.  *
  29.  * Alternatively, the contents of this file may be used under the terms of
  30.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  31.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  32.  * in which case the provisions of the GPL or the LGPL are applicable instead
  33.  * of those above. If you wish to allow use of your version of this file only
  34.  * under the terms of either the GPL or the LGPL, and not to allow others to
  35.  * use your version of this file under the terms of the MPL, indicate your
  36.  * decision by deleting the provisions above and replace them with the notice
  37.  * and other provisions required by the GPL or the LGPL. If you do not delete
  38.  * the provisions above, a recipient may use your version of this file under
  39.  * the terms of any one of the MPL, the GPL or the LGPL.
  40.  *
  41.  * ***** END LICENSE BLOCK ***** */
  42.  
  43. //
  44. // TODO:
  45. // - better logging
  46. //
  47.  
  48. const nsIExtensionManager             = Components.interfaces.nsIExtensionManager;
  49. const nsIAddonUpdateCheckListener     = Components.interfaces.nsIAddonUpdateCheckListener;
  50. const nsIUpdateItem                   = Components.interfaces.nsIUpdateItem;
  51. const nsILocalFile                    = Components.interfaces.nsILocalFile;
  52. const nsILineInputStream              = Components.interfaces.nsILineInputStream;
  53. const nsIInstallLocation              = Components.interfaces.nsIInstallLocation;
  54. const nsIURL                          = Components.interfaces.nsIURL
  55. // XXXrstrong calling hasMoreElements on a nsIDirectoryEnumerator after
  56. // it has been removed will cause a crash on Mac OS X - bug 292823
  57. const nsIDirectoryEnumerator          = Components.interfaces.nsIDirectoryEnumerator;
  58.  
  59. const PREF_EM_CHECK_COMPATIBILITY     = "extensions.checkCompatibility";
  60. const PREF_EM_LAST_APP_VERSION        = "extensions.lastAppVersion";
  61. const PREF_UPDATE_COUNT               = "extensions.update.count";
  62. const PREF_UPDATE_DEFAULT_URL         = "extensions.update.url";
  63. const PREF_EM_IGNOREMTIMECHANGES      = "extensions.ignoreMTimeChanges";
  64. const PREF_EM_DISABLEDOBSOLETE        = "extensions.disabledObsolete";
  65. const PREF_EM_LAST_SELECTED_SKIN      = "extensions.lastSelectedSkin";
  66. const PREF_EM_EXTENSION_FORMAT        = "extensions.%UUID%.";
  67. const PREF_EM_ITEM_UPDATE_ENABLED     = "extensions.%UUID%.update.enabled";
  68. const PREF_EM_UPDATE_ENABLED          = "extensions.update.enabled";
  69. const PREF_EM_ITEM_UPDATE_URL         = "extensions.%UUID%.update.url";
  70. const PREF_EM_DSS_ENABLED             = "extensions.dss.enabled";
  71. const PREF_DSS_SWITCHPENDING          = "extensions.dss.switchPending";
  72. const PREF_DSS_SKIN_TO_SELECT         = "extensions.lastSelectedSkin";
  73. const PREF_GENERAL_SKINS_SELECTEDSKIN = "general.skins.selectedSkin";
  74. const PREF_EM_LOGGING_ENABLED         = "extensions.logging.enabled";
  75. const PREF_EM_UPDATE_INTERVAL         = "extensions.update.interval";
  76. const PREF_BLOCKLIST_URL              = "extensions.blocklist.url";
  77. const PREF_BLOCKLIST_DETAILS_URL      = "extensions.blocklist.detailsURL";
  78. const PREF_BLOCKLIST_ENABLED          = "extensions.blocklist.enabled";
  79. const PREF_BLOCKLIST_INTERVAL         = "extensions.blocklist.interval";
  80. const PREF_UPDATE_NOTIFYUSER          = "extensions.update.notifyUser";
  81.  
  82. const DIR_EXTENSIONS                  = "extensions";
  83. const DIR_CHROME                      = "chrome";
  84. const DIR_STAGE                       = "staged-xpis";
  85. const FILE_EXTENSIONS                 = "extensions.rdf";
  86. const FILE_EXTENSION_MANIFEST         = "extensions.ini";
  87. const FILE_EXTENSIONS_STARTUP_CACHE   = "extensions.cache";
  88. const FILE_AUTOREG                    = ".autoreg";
  89. const FILE_INSTALL_MANIFEST           = "install.rdf";
  90. const FILE_CONTENTS_MANIFEST          = "contents.rdf";
  91. const FILE_CHROME_MANIFEST            = "chrome.manifest";
  92. const FILE_BLOCKLIST                  = "blocklist.xml";
  93.  
  94. const UNKNOWN_XPCOM_ABI               = "unknownABI";
  95.  
  96. const FILE_LOGFILE                    = "extensionmanager.log";
  97.  
  98. const FILE_DEFAULT_THEME_JAR          = "classic.jar";
  99. const TOOLKIT_ID                      = "toolkit@mozilla.org"
  100.  
  101. const KEY_PROFILEDIR                  = "ProfD";
  102. const KEY_PROFILEDS                   = "ProfDS";
  103. const KEY_APPDIR                      = "XCurProcD";
  104. const KEY_TEMPDIR                     = "TmpD";
  105.  
  106. const EM_ACTION_REQUESTED_TOPIC       = "em-action-requested";
  107. const EM_ITEM_INSTALLED               = "item-installed";
  108. const EM_ITEM_UPGRADED                = "item-upgraded";
  109. const EM_ITEM_UNINSTALLED             = "item-uninstalled";
  110. const EM_ITEM_ENABLED                 = "item-enabled";
  111. const EM_ITEM_DISABLED                = "item-disabled";
  112. const EM_ITEM_CANCEL                  = "item-cancel-action";
  113.  
  114. const OP_NONE                         = "";
  115. const OP_NEEDS_INSTALL                = "needs-install";
  116. const OP_NEEDS_UPGRADE                = "needs-upgrade";
  117. const OP_NEEDS_UNINSTALL              = "needs-uninstall";
  118. const OP_NEEDS_ENABLE                 = "needs-enable";
  119. const OP_NEEDS_DISABLE                = "needs-disable";
  120.  
  121. const KEY_APP_PROFILE                 = "app-profile";
  122. const KEY_APP_GLOBAL                  = "app-global";
  123.  
  124. const CATEGORY_INSTALL_LOCATIONS      = "extension-install-locations";
  125.  
  126. const PREFIX_NS_EM                    = "http://www.mozilla.org/2004/em-rdf#";
  127. const PREFIX_NS_CHROME                = "http://www.mozilla.org/rdf/chrome#";
  128. const PREFIX_ITEM_URI                 = "urn:mozilla:item:";
  129. const PREFIX_EXTENSION                = "urn:mozilla:extension:";
  130. const PREFIX_THEME                    = "urn:mozilla:theme:";
  131. const RDFURI_INSTALL_MANIFEST_ROOT    = "urn:mozilla:install-manifest";
  132. const RDFURI_ITEM_ROOT                = "urn:mozilla:item:root"
  133. const RDFURI_DEFAULT_THEME            = "urn:mozilla:item:{972ce4c6-7e08-4474-a285-3208198ce6fd}";
  134. const XMLURI_PARSE_ERROR              = "http://www.mozilla.org/newlayout/xml/parsererror.xml"
  135. const XMLURI_BLOCKLIST                = "http://www.mozilla.org/2006/addons-blocklist";
  136.  
  137. const URI_GENERIC_ICON_XPINSTALL      = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png";
  138. const URI_GENERIC_ICON_THEME          = "chrome://mozapps/skin/extensions/themeGeneric.png";
  139. const URI_XPINSTALL_CONFIRM_DIALOG    = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
  140. const URI_FINALIZE_DIALOG             = "chrome://mozapps/content/extensions/finalize.xul";
  141. const URI_EXTENSIONS_PROPERTIES       = "chrome://mozapps/locale/extensions/extensions.properties";
  142. const URI_BRAND_PROPERTIES            = "chrome://branding/locale/brand.properties";
  143. const URI_DOWNLOADS_PROPERTIES        = "chrome://mozapps/locale/downloads/downloads.properties";
  144. const URI_EXTENSION_UPDATE_DIALOG     = "chrome://mozapps/content/extensions/update.xul";
  145. const URI_EXTENSION_LIST_DIALOG       = "chrome://mozapps/content/extensions/list.xul";
  146.  
  147. const INSTALLERROR_SUCCESS               = 0;
  148. const INSTALLERROR_INVALID_VERSION       = -1;
  149. const INSTALLERROR_INVALID_GUID          = -2;
  150. const INSTALLERROR_INCOMPATIBLE_VERSION  = -3;
  151. const INSTALLERROR_PHONED_HOME           = -4;
  152. const INSTALLERROR_INCOMPATIBLE_PLATFORM = -5;
  153. const INSTALLERROR_BLOCKLISTED           = -6;
  154.  
  155. const MODE_RDONLY   = 0x01;
  156. const MODE_WRONLY   = 0x02;
  157. const MODE_CREATE   = 0x08;
  158. const MODE_APPEND   = 0x10;
  159. const MODE_TRUNCATE = 0x20;
  160.  
  161. const PERMS_FILE      = 0644;
  162. const PERMS_DIRECTORY = 0755;
  163.  
  164. var gApp  = null;
  165. var gPref = null;
  166. var gRDF  = null;
  167. var gOS   = null;
  168. var gXPCOMABI             = null;
  169. var gOSTarget             = null;
  170. var gConsole              = null;
  171. var gInstallManifestRoot  = null;
  172. var gVersionChecker       = null;
  173. var gLoggingEnabled       = null;
  174. var gCheckCompatibility   = true;
  175.  
  176. /** 
  177.  * Valid GUIDs fit this pattern.
  178.  */
  179. var gIDTest = /^(\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}|[a-z0-9-\._]*\@[a-z0-9-\._]+)$/i;
  180.  
  181. // shared code for suppressing bad cert dialogs
  182. //@line 40 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/extensions/src/../../shared/src/badCertHandler.js"
  183.  
  184. /**
  185.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  186.  */
  187. function checkCert(channel) {
  188.   if (!channel.originalURI.schemeIs("https"))  // bypass
  189.     return;
  190.  
  191.   const Ci = Components.interfaces;  
  192.   var cert =
  193.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  194.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  195.  
  196.   var issuer = cert.issuer;
  197.   while (issuer && !cert.equals(issuer)) {
  198.     cert = issuer;
  199.     issuer = cert.issuer;
  200.   }
  201.  
  202.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  203.     throw "cert issuer is not built-in";
  204. }
  205.  
  206. /**
  207.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  208.  * security dialogs from being shown to the user.  It is better to simply fail
  209.  * if the certificate is bad. See bug 304286.
  210.  */
  211. function BadCertHandler() {
  212. }
  213. BadCertHandler.prototype = {
  214.  
  215.   // nsIBadCertListener
  216.   confirmUnknownIssuer: function(socketInfo, cert, certAddType) {
  217.     LOG("EM BadCertHandler: Unknown issuer");
  218.     return false;
  219.   },
  220.  
  221.   confirmMismatchDomain: function(socketInfo, targetURL, cert) {
  222.     LOG("EM BadCertHandler: Mismatched domain");
  223.     return false;
  224.   },
  225.  
  226.   confirmCertExpired: function(socketInfo, cert) {
  227.     LOG("EM BadCertHandler: Expired certificate");
  228.     return false;
  229.   },
  230.  
  231.   notifyCrlNextupdate: function(socketInfo, targetURL, cert) {
  232.   },
  233.  
  234.   // nsIChannelEventSink
  235.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  236.     // make sure the certificate of the old channel checks out before we follow
  237.     // a redirect from it.  See bug 340198.
  238.     checkCert(oldChannel);
  239.   },
  240.  
  241.   // nsIInterfaceRequestor
  242.   getInterface: function(iid) {
  243.     if (iid.equals(Components.interfaces.nsIBadCertListener) ||
  244.         iid.equals(Components.interfaces.nsIChannelEventSink))
  245.       return this;
  246.  
  247.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  248.     return null;
  249.   },
  250.  
  251.   // nsISupports
  252.   QueryInterface: function(iid) {
  253.     if (!iid.equals(Components.interfaces.nsIBadCertListener) &&
  254.         !iid.equals(Components.interfaces.nsIChannelEventSink) &&
  255.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  256.         !iid.equals(Components.interfaces.nsISupports))
  257.       throw Components.results.NS_ERROR_NO_INTERFACE;
  258.     return this;
  259.   }
  260. };
  261. //@line 183 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  262.  
  263. /**
  264.  * Creates a Version Checker object.
  265.  * @returns A handle to the global Version Checker service.
  266.  */
  267. function getVersionChecker() {
  268.   if (!gVersionChecker) {
  269.     gVersionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  270.                                 .getService(Components.interfaces.nsIVersionComparator);
  271.   }
  272.   return gVersionChecker;
  273. }
  274.  
  275. var BundleManager = { 
  276.   /**
  277.   * Creates and returns a String Bundle at the specified URI
  278.   * @param   bundleURI
  279.   *          The URI of the bundle to load
  280.   * @returns A nsIStringBundle which was retrieved.
  281.   */
  282.   getBundle: function(bundleURI) {
  283.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  284.                         .getService(Components.interfaces.nsIStringBundleService);
  285.     return sbs.createBundle(bundleURI);
  286.   },
  287.   
  288.   _appName: "",
  289.   
  290.   /**
  291.    * The Application's display name.
  292.    */
  293.   get appName() {
  294.     if (!this._appName) {
  295.       var brandBundle = this.getBundle(URI_BRAND_PROPERTIES)
  296.       this._appName = brandBundle.GetStringFromName("brandShortName");
  297.     }
  298.     return this._appName;
  299.   }
  300. };
  301.  
  302. ///////////////////////////////////////////////////////////////////////////////
  303. //
  304. // Utility Functions
  305. //
  306. function EM_NS(property) {
  307.   return PREFIX_NS_EM + property;
  308. }
  309.  
  310. function CHROME_NS(property) {
  311.   return PREFIX_NS_CHROME + property;
  312. }
  313.  
  314. function EM_R(property) {
  315.   return gRDF.GetResource(EM_NS(property));
  316. }
  317.  
  318. function EM_L(literal) {
  319.   return gRDF.GetLiteral(literal);
  320. }
  321.  
  322. function EM_I(integer) {
  323.   return gRDF.GetIntLiteral(integer);
  324. }
  325.  
  326. function EM_D(integer) {
  327.   return gRDF.GetDateLiteral(integer);
  328. }
  329.  
  330. /**
  331.  * Gets a preference value, handling the case where there is no default.
  332.  * @param   func
  333.  *          The name of the preference function to call, on nsIPrefBranch
  334.  * @param   preference
  335.  *          The name of the preference
  336.  * @param   defaultValue
  337.  *          The default value to return in the event the preference has 
  338.  *          no setting
  339.  * @returns The value of the preference, or undefined if there was no
  340.  *          user or default value.
  341.  */
  342. function getPref(func, preference, defaultValue) {
  343.   try {
  344.     return gPref[func](preference);
  345.   }
  346.   catch (e) {
  347.   }
  348.   return defaultValue;
  349. }
  350.  
  351. /**
  352.  * Initializes a RDF Container at a URI in a datasource.
  353.  * @param   datasource
  354.  *          The datasource the container is in
  355.  * @param   root
  356.  *          The RDF Resource which is the root of the container.
  357.  * @returns The nsIRDFContainer, initialized at the root.
  358.  */
  359. function getContainer(datasource, root) {
  360.   var ctr = Components.classes["@mozilla.org/rdf/container;1"]
  361.                       .createInstance(Components.interfaces.nsIRDFContainer);
  362.   ctr.Init(datasource, root);
  363.   return ctr;
  364. }
  365.  
  366. /**
  367.  * Gets a RDF Resource for item with the given ID
  368.  * @param   id
  369.  *          The GUID of the item to construct a RDF resource to the 
  370.  *          active item for
  371.  * @returns The RDF Resource to the Active item. 
  372.  */
  373. function getResourceForID(id) {
  374.   return gRDF.GetResource(PREFIX_ITEM_URI + id);
  375. }
  376.  
  377. /**
  378.  * Construct a nsIUpdateItem with the supplied metadata
  379.  * ...
  380.  */
  381. function makeItem(id, version, locationKey, minVersion, maxVersion, name, 
  382.                   updateURL, updateHash, iconURL, updateRDF, type) {
  383.   var item = Components.classes["@mozilla.org/updates/item;1"]
  384.                        .createInstance(Components.interfaces.nsIUpdateItem);
  385.   item.init(id, version, locationKey, minVersion, maxVersion, name,
  386.             updateURL, updateHash, iconURL, updateRDF, type);
  387.   return item;
  388. }
  389.  
  390. /**
  391.  * Gets the specified directory at the speciifed hierarchy under a 
  392.  * Directory Service key. 
  393.  * @param   key
  394.  *          The Directory Service Key to start from
  395.  * @param   pathArray
  396.  *          An array of path components to locate beneath the directory 
  397.  *          specified by |key|
  398.  * @return  nsIFile object for the location specified. If the directory
  399.  *          requested does not exist, it is created, along with any
  400.  *          parent directories that need to be created.
  401.  */
  402. function getDir(key, pathArray) {
  403.   return getDirInternal(key, pathArray, true);
  404. }
  405.  
  406. /**
  407.  * Gets the specified directory at the speciifed hierarchy under a 
  408.  * Directory Service key. 
  409.  * @param   key
  410.  *          The Directory Service Key to start from
  411.  * @param   pathArray
  412.  *          An array of path components to locate beneath the directory 
  413.  *          specified by |key|
  414.  * @return  nsIFile object for the location specified. If the directory
  415.  *          requested does not exist, it is NOT created.
  416.  */
  417. function getDirNoCreate(key, pathArray) {
  418.   return getDirInternal(key, pathArray, false);
  419. }
  420.  
  421. /**
  422.  * Gets the specified directory at the speciifed hierarchy under a 
  423.  * Directory Service key. 
  424.  * @param   key
  425.  *          The Directory Service Key to start from
  426.  * @param   pathArray
  427.  *          An array of path components to locate beneath the directory 
  428.  *          specified by |key|
  429.  * @param   shouldCreate
  430.  *          true if the directory hierarchy specified in |pathArray|
  431.  *          should be created if it does not exist,
  432.  *          false otherwise.
  433.  * @return  nsIFile object for the location specified. 
  434.  */
  435. function getDirInternal(key, pathArray, shouldCreate) {
  436.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  437.                               .getService(Components.interfaces.nsIProperties);
  438.   var dir = fileLocator.get(key, nsILocalFile);
  439.   for (var i = 0; i < pathArray.length; ++i) {
  440.     dir.append(pathArray[i]);
  441.     if (shouldCreate && !dir.exists())
  442.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  443.   }
  444.   dir.followLinks = false;
  445.   return dir;
  446. }
  447.  
  448. /**
  449.  * Gets the file at the speciifed hierarchy under a Directory Service key.
  450.  * @param   key
  451.  *          The Directory Service Key to start from
  452.  * @param   pathArray
  453.  *          An array of path components to locate beneath the directory 
  454.  *          specified by |key|. The last item in this array must be the
  455.  *          leaf name of a file.
  456.  * @return  nsIFile object for the file specified. The file is NOT created
  457.  *          if it does not exist, however all required directories along 
  458.  *          the way are.
  459.  */
  460. function getFile(key, pathArray) {
  461.   var file = getDir(key, pathArray.slice(0, -1));
  462.   file.append(pathArray[pathArray.length - 1]);
  463.   return file;
  464. }
  465.  
  466. /**
  467.  * Gets the descriptor of a directory as a relative path to common base
  468.  * directories (profile, user home, app install dir, etc).
  469.  *
  470.  * @param   itemLocation
  471.  *          The nsILocalFile representing the item's directory.
  472.  * @param   installLocation the nsIInstallLocation for this item
  473.  */
  474. function getDescriptorFromFile(itemLocation, installLocation) {
  475.   var baseDir = installLocation.location;
  476.  
  477.   if (baseDir && baseDir.contains(itemLocation, true)) {
  478.     return "rel%" + itemLocation.getRelativeDescriptor(baseDir);
  479.   }
  480.  
  481.   return "abs%" + itemLocation.persistentDescriptor;
  482. }
  483.  
  484. function getAbsoluteDescriptor(itemLocation) {
  485.   return itemLocation.persistentDescriptor;
  486. }
  487.  
  488. /**
  489.  * Initializes a Local File object based on a descriptor
  490.  * provided by "getDescriptorFromFile".
  491.  *
  492.  * @param   descriptor
  493.  *          The descriptor that locates the directory
  494.  * @param   installLocation
  495.  *          The nsIInstallLocation object for this item.
  496.  * @returns The nsILocalFile object representing the location of the item
  497.  */
  498. function getFileFromDescriptor(descriptor, installLocation) {
  499.   var location = Components.classes["@mozilla.org/file/local;1"]
  500.                            .createInstance(nsILocalFile);
  501.  
  502.   var m = descriptor.match(/^(abs|rel)\%(.*)$/);
  503.   if (!m)
  504.     throw Components.results.NS_ERROR_INVALID_ARG;
  505.  
  506.   if (m[1] == "rel") {
  507.     location.setRelativeDescriptor(installLocation.location, m[2]);
  508.   }
  509.   else {
  510.     location.persistentDescriptor = m[2];
  511.   }
  512.  
  513.   return location;
  514. }
  515.  
  516. /**
  517.  * Determines if a file is an item package - either a XPI or a JAR file.
  518.  * @param   file
  519.  *          The file to check
  520.  * @returns true if the file is an item package, false otherwise.
  521.  */
  522. function fileIsItemPackage(file) {
  523.   var fileURL = getURIFromFile(file);
  524.   if (fileURL instanceof nsIURL)
  525.     var extension = fileURL.fileExtension.toLowerCase();
  526.   return extension == "xpi" || extension == "jar";
  527. }
  528.  
  529. /** 
  530.  * Return the leaf name used by the extension system for staging an item.
  531.  * @param   id
  532.  *          The GUID of the item
  533.  * @param   type
  534.  *          The nsIUpdateItem type of the item
  535.  * @returns The leaf name of the staged file.
  536.  */
  537. function getStagedLeafName(id, type) {
  538.   if (type == nsIUpdateItem.TYPE_THEME) 
  539.     return id + ".jar";
  540.   return id + ".xpi";
  541. }
  542.  
  543. /**
  544.  * Opens a safe file output stream for writing. 
  545.  * @param   file
  546.  *          The file to write to.
  547.  * @param   modeFlags
  548.  *          (optional) File open flags. Can be undefined. 
  549.  * @returns nsIFileOutputStream to write to.
  550.  */
  551. function openSafeFileOutputStream(file, modeFlags) {
  552.   var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  553.                       .createInstance(Components.interfaces.nsIFileOutputStream);
  554.   if (modeFlags === undefined)
  555.     modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  556.   if (!file.exists()) 
  557.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  558.   fos.init(file, modeFlags, PERMS_FILE, 0);
  559.   return fos;
  560. }
  561.  
  562. /**
  563.  * Closes a safe file output stream.
  564.  * @param   stream
  565.  *          The stream to close.
  566.  */
  567. function closeSafeFileOutputStream(stream) {
  568.   if (stream instanceof Components.interfaces.nsISafeOutputStream)
  569.     stream.finish();
  570.   else
  571.     stream.close();
  572. }
  573.  
  574. /**
  575.  * Deletes a directory and its children. First it tries nsIFile::Remove(true).
  576.  * If that fails it will fall back to recursing, setting the appropriate
  577.  * permissions, and deleting the current entry. This is needed for when we have
  578.  * rights to delete a directory but there are entries that have a read-only
  579.  * attribute (e.g. a copy restore from a read-only CD, etc.)
  580.  * @param   dir
  581.  *          A nsIFile for the directory to be deleted
  582.  */
  583. function removeDirRecursive(dir) {
  584.   try {
  585.     dir.remove(true);
  586.     return;
  587.   }
  588.   catch (e) {
  589.   }
  590.  
  591.   var dirEntries = dir.directoryEntries;
  592.   while (dirEntries.hasMoreElements()) {
  593.     var entry = dirEntries.getNext().QueryInterface(Components.interfaces.nsIFile);
  594.  
  595.     if (entry.isDirectory()) {
  596.       removeDirRecursive(entry);
  597.     }
  598.     else {
  599.       entry.permissions = PERMS_FILE;
  600.       entry.remove(false);
  601.     }
  602.   }
  603.   dir.permissions = PERMS_DIRECTORY;
  604.   dir.remove(true);
  605. }
  606.  
  607. /**
  608.  * Logs a string to the error console. 
  609.  * @param   string
  610.  *          The string to write to the error console..
  611.  */  
  612. function LOG(string) {
  613.   if (gLoggingEnabled) {
  614.     dump("*** " + string + "\n");
  615.     gConsole.logStringMessage(string);
  616.   }
  617. }
  618.  
  619. /** 
  620.  * Randomize the specified file name. Used to force RDF to bypass the cache
  621.  * when loading certain types of files.
  622.  * @param   fileName 
  623.  *          A file name to randomize, e.g. install.rdf
  624.  * @returns A randomized file name, e.g. install-xyz.rdf
  625.  */
  626. function getRandomFileName(fileName) {
  627.   var extensionDelimiter = fileName.lastIndexOf(".");
  628.   var prefix = fileName.substr(0, extensionDelimiter);
  629.   var suffix = fileName.substr(extensionDelimiter);
  630.   
  631.   var characters = "abcdefghijklmnopqrstuvwxyz0123456789";
  632.   var nameString = prefix + "-";
  633.   for (var i = 0; i < 3; ++i) {
  634.     var index = Math.round((Math.random()) * characters.length);
  635.     nameString += characters.charAt(index);
  636.   }
  637.   return nameString + "." + suffix;
  638. }
  639.  
  640. /**
  641.  * Get the RDF URI prefix of a nsIUpdateItem type. This function should be used
  642.  * ONLY to support Firefox 1.0 Update RDF files! Item URIs in the datasource 
  643.  * are NOT prefixed.
  644.  * @param   type
  645.  *          The nsIUpdateItem type to find a RDF URI prefix for
  646.  * @returns The RDF URI prefix.
  647.  */
  648. function getItemPrefix(type) {
  649.   if (type & nsIUpdateItem.TYPE_EXTENSION) 
  650.     return PREFIX_EXTENSION;
  651.   else if (type & nsIUpdateItem.TYPE_THEME)
  652.     return PREFIX_THEME;
  653.   return PREFIX_ITEM_URI;
  654. }
  655.  
  656. /**
  657.  * Trims a prefix from a string.
  658.  * @param   string
  659.  *          The source string
  660.  * @param   prefix
  661.  *          The prefix to remove.
  662.  * @returns The suffix (string - prefix)
  663.  */
  664. function stripPrefix(string, prefix) {
  665.   return string.substr(prefix.length);
  666. }
  667.  
  668. /**
  669.  * Gets a File URL spec for a nsIFile
  670.  * @param   file
  671.  *          The file to get a file URL spec to
  672.  * @returns The file URL spec to the file
  673.  */
  674. function getURLSpecFromFile(file) {
  675.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  676.                          .getService(Components.interfaces.nsIIOService);
  677.   var fph = ioServ.getProtocolHandler("file")
  678.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  679.   return fph.getURLSpecFromFile(file);
  680. }
  681.  
  682. /**
  683.  * Constructs a URI to a spec.
  684.  * @param   spec
  685.  *          The spec to construct a URI to
  686.  * @returns The nsIURI constructed.
  687.  */
  688. function newURI(spec) {
  689.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  690.                          .getService(Components.interfaces.nsIIOService);
  691.   return ioServ.newURI(spec, null, null);
  692. }
  693.  
  694. /** 
  695.  * Constructs a File URI to a nsIFile
  696.  * @param   file
  697.  *          The file to construct a File URI to
  698.  * @returns The file URI to the file
  699.  */
  700. function getURIFromFile(file) {
  701.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  702.                          .getService(Components.interfaces.nsIIOService);
  703.   return ioServ.newFileURI(file);
  704. }
  705.  
  706. /**
  707.  * @returns Whether or not we are currently running in safe mode.
  708.  */
  709. function inSafeMode() {
  710.   return gApp.inSafeMode;
  711. }
  712.  
  713. /**
  714.  * Extract the string value from a RDF Literal or Resource
  715.  * @param   literalOrResource
  716.  *          RDF String Literal or Resource
  717.  * @returns String value of the literal or resource, or undefined if the object
  718.  *          supplied is not a RDF string literal or resource.
  719.  */
  720. function stringData(literalOrResource) {
  721.   if (literalOrResource instanceof Components.interfaces.nsIRDFLiteral)
  722.     return literalOrResource.Value;
  723.   if (literalOrResource instanceof Components.interfaces.nsIRDFResource)
  724.     return literalOrResource.Value;
  725.   return undefined;
  726. }
  727.  
  728. /**
  729.  * Extract the integer value of a RDF Literal
  730.  * @param   literal
  731.  *          nsIRDFInt literal
  732.  * @return  integer value of the literal
  733.  */
  734. function intData(literal) {
  735.   if (literal instanceof Components.interfaces.nsIRDFInt)
  736.     return literal.Value;
  737.   return undefined;
  738. }
  739.  
  740. /**
  741.  * Gets a property from an install manifest.
  742.  * @param   installManifest
  743.  *          An Install Manifest datasource to read from
  744.  * @param   property
  745.  *          The name of a proprety to read (sans EM_NS)
  746.  * @returns The literal value of the property, or undefined if the property has
  747.  *          no value.
  748.  */
  749. function getManifestProperty(installManifest, property) {
  750.   var target = installManifest.GetTarget(gInstallManifestRoot, 
  751.                                          gRDF.GetResource(EM_NS(property)), true);
  752.   var val = stringData(target);
  753.   return val === undefined ? intData(target) : val;
  754. }
  755.  
  756. /**
  757.  * Given an Install Manifest Datasource, retrieves the type of item the manifest
  758.  * describes.
  759.  * @param   installManifest 
  760.  *          The Install Manifest Datasource.
  761.  * @return  The nsIUpdateItem type of the item described by the manifest
  762.  *          returns TYPE_EXTENSION if attempts to determine the type fail.
  763.  */
  764. function getAddonTypeFromInstallManifest(installManifest) {
  765.   var target = installManifest.GetTarget(gInstallManifestRoot, 
  766.                                          gRDF.GetResource(EM_NS("type")), true);
  767.   if (target) {
  768.     var type = stringData(target);
  769.     return type === undefined ? intData(target) : parseInt(type);
  770.   }
  771.  
  772.   // Firefox 1.0 and earlier did not support addon-type annotation on the 
  773.   // Install Manifest, so we fall back to a theme-only property to 
  774.   // differentiate.
  775.   if (getManifestProperty(installManifest, "internalName") !== undefined)
  776.     return nsIUpdateItem.TYPE_THEME;
  777.  
  778.   // If no type is provided, default to "Extension"
  779.   return nsIUpdateItem.TYPE_EXTENSION;    
  780. }
  781.  
  782. /**
  783.  * Shows a message about an incompatible Extension/Theme. 
  784.  * @param   installData
  785.  *          An Install Data object from |getInstallData|
  786.  */
  787. function showIncompatibleError(installData) {
  788.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  789.   var params = [extensionStrings.GetStringFromName("type-" + installData.type)];
  790.   var title = extensionStrings.formatStringFromName("incompatibleTitle", 
  791.                                                     params, params.length);
  792.   var message;
  793.   var targetAppData = installData.currentApp;
  794.   if (!targetAppData) {
  795.     params = [installData.name, installData.version, BundleManager.appName];
  796.     message = extensionStrings.formatStringFromName("incompatibleMessageNoApp", 
  797.                                                     params, params.length);
  798.   }
  799.   else if (targetAppData.minVersion == targetAppData.maxVersion) {
  800.     // If the min target app version and the max target app version are the same, don't show
  801.     // a message like, "Foo is only compatible with Firefox versions 0.7 to 0.7", rather just
  802.     // show, "Foo is only compatible with Firefox 0.7"
  803.     params = [installData.name, installData.version, BundleManager.appName, gApp.version, 
  804.               installData.name, installData.version, BundleManager.appName, 
  805.               targetAppData.minVersion];
  806.     message = extensionStrings.formatStringFromName("incompatibleMsgSingleAppVersion", 
  807.                                                     params, params.length);
  808.   }
  809.   else {
  810.     params = [installData.name, installData.version, BundleManager.appName, gApp.version, 
  811.               installData.name, installData.version, BundleManager.appName, 
  812.               targetAppData.minVersion, targetAppData.maxVersion];
  813.     message = extensionStrings.formatStringFromName("incompatibleMsg", params, params.length);
  814.   }
  815.   var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  816.                      .getService(Components.interfaces.nsIPromptService);
  817.   ps.alert(null, title, message);
  818. }
  819.  
  820. /**
  821.  * Shows a message.
  822.  * @param   titleKey
  823.  *          String key of the title string in the Extensions localization file.
  824.  * @param   messageKey
  825.  *          String key of the message string in the Extensions localization file.
  826.  * @param   messageParams
  827.  *          Array of strings to be substituted into |messageKey|. Can be null.
  828.  */
  829. function showMessage(titleKey, titleParams, messageKey, messageParams) {
  830.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  831.   if (titleParams && titleParams.length > 0) {
  832.     var title = extensionStrings.formatStringFromName(titleKey, titleParams,
  833.                                                       titleParams.length);
  834.   }
  835.   else
  836.     title = extensionStrings.GetStringFromName(titleKey);
  837.  
  838.   if (messageParams && messageParams.length > 0) {
  839.     var message = extensionStrings.formatStringFromName(messageKey, messageParams,
  840.                                                         messageParams.length);
  841.   }
  842.   else
  843.     message = extensionStrings.GetStringFromName(messageKey);
  844.   var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  845.                      .getService(Components.interfaces.nsIPromptService);
  846.   ps.alert(null, title, message);
  847. }
  848.  
  849. /**
  850.  * Shows a dialog for blocklisted items.
  851.  * @param   items
  852.  *          An array of nsIUpdateItems.
  853.  * @param   fromInstall
  854.  *          Whether this is called from an install or from the blocklist
  855.  *          background check.
  856.  */
  857. function showBlocklistMessage(items, fromInstall) {
  858.   var win = null;
  859.   var params = Components.classes["@mozilla.org/embedcomp/dialogparam;1"]
  860.                          .createInstance(Components.interfaces.nsIDialogParamBlock);
  861.   params.SetInt(0, (fromInstall ? 1 : 0));
  862.   params.SetInt(1, items.length);
  863.   params.SetNumberStrings(items.length * 2);
  864.   for (var i = 0; i < items.length; ++i) 
  865.     params.SetString(i, items[i].name + " " + items[i].version);
  866.  
  867.   // if this was initiated from an install try to find the appropriate manager
  868.   if (fromInstall) {
  869.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  870.                        .getService(Components.interfaces.nsIWindowMediator);
  871.     win = wm.getMostRecentWindow(nsIUpdateItem.TYPE_THEME ? "Extension:Manager-themes" :
  872.                                                             "Extension:Manager-extensions");
  873.   }
  874.   var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  875.                      .getService(Components.interfaces.nsIWindowWatcher);
  876.   ww.openWindow(win, URI_EXTENSION_LIST_DIALOG, "",
  877.                 "chrome,centerscreen,modal,dialog,titlebar", params);
  878. }
  879.  
  880. /** 
  881.  * Gets a zip reader for the file specified.
  882.  * @param   zipFile
  883.  *          A ZIP archive to open with a nsIZipReader.
  884.  * @return  A nsIZipReader for the file specified.
  885.  */
  886. function getZipReaderForFile(zipFile) {
  887.   try {
  888.     var zipReader = Components.classes["@mozilla.org/libjar/zip-reader;1"]
  889.                               .createInstance(Components.interfaces.nsIZipReader);
  890.     zipReader.init(zipFile);
  891.     zipReader.open();
  892.   }
  893.   catch (e) {
  894.     zipReader.close();
  895.     throw e;
  896.   }
  897.   return zipReader;
  898. }
  899.  
  900. /** 
  901.  * Extract a RDF file from a ZIP archive to a random location in the system
  902.  * temp directory.
  903.  * @param   zipFile
  904.  *          A ZIP archive to read from
  905.  * @param   fileName 
  906.  *          The name of the file to read from the zip. 
  907.  * @param   suppressErrors
  908.  *          Whether or not to report errors. 
  909.  * @return  The file created in the temp directory.
  910.  */
  911. function extractRDFFileToTempDir(zipFile, fileName, suppressErrors) {
  912.   var file = getFile(KEY_TEMPDIR, [getRandomFileName(fileName)]);
  913.   try {
  914.     var zipReader = getZipReaderForFile(zipFile);
  915.     zipReader.getEntry(fileName);
  916.     zipReader.extract(fileName, file);
  917.     zipReader.close();
  918.   }
  919.   catch (e) {
  920.     if (!suppressErrors) {
  921.       showMessage("missingFileTitle", [], "missingFileMessage", 
  922.                   [BundleManager.appName, fileName]);
  923.       throw e;
  924.     }
  925.   }
  926.   return file;
  927. }
  928.  
  929. /**
  930.  * Show a message to the user informing them they are installing an old non-EM
  931.  * style Theme, and that these are not supported.
  932.  * @param   installManifest 
  933.  *          The Old-Style Contents Manifest datasource representing the theme. 
  934.  */
  935. function showOldThemeError(contentsManifest) {
  936.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  937.   var params = [extensionStrings.GetStringFromName("theme")];
  938.   var title = extensionStrings.formatStringFromName("incompatibleTitle", 
  939.                                                     params, params.length);
  940.   var appVersion = extensionStrings.GetStringFromName("incompatibleOlder");
  941.   
  942.   try {  
  943.     var ctr = getContainer(contentsManifest, 
  944.                            gRDF.GetResource("urn:mozilla:skin:root"));
  945.     var elts = ctr.GetElements();
  946.     var nameArc = gRDF.GetResource(CHROME_NS("displayName"));
  947.     while (elts.hasMoreElements()) {
  948.       var elt = elts.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  949.       themeName = stringData(contentsManifest.GetTarget(elt, nameArc, true));
  950.       if (themeName) 
  951.         break;
  952.     }
  953.   }
  954.   catch (e) {
  955.     themeName = extensionStrings.GetStringFromName("incompatibleThemeName");
  956.   }
  957.   
  958.   params = [themeName, "", BundleManager.appName, gApp.version, themeName, "", 
  959.             BundleManager.appName, appVersion];
  960.   var message = extensionStrings.formatStringFromName("incompatibleMsgSingleAppVersion",
  961.                                                       params, params.length);
  962.   var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  963.                      .getService(Components.interfaces.nsIPromptService);
  964.   ps.alert(null, title, message);
  965. }
  966.  
  967. /**
  968.  * Gets an Install Manifest datasource from a file.
  969.  * @param   file
  970.  *          The nsIFile that contains the Install Manifest RDF
  971.  * @returns The Install Manifest datasource
  972.  */
  973. function getInstallManifest(file) {
  974.   var fileURL = getURLSpecFromFile(file);
  975.   var ds = gRDF.GetDataSourceBlocking(fileURL);
  976.   var arcs = ds.ArcLabelsOut(gInstallManifestRoot);
  977.   if (!arcs.hasMoreElements()) {
  978.     ds = null;
  979.     var uri = Components.classes["@mozilla.org/network/io-service;1"]
  980.                         .getService(Components.interfaces.nsIIOService)
  981.                         .newFileURI(file);
  982.     var url = uri.QueryInterface(nsIURL);
  983.     showMessage("malformedTitle", [], "malformedMessage", 
  984.                 [BundleManager.appName, url.fileName]);
  985.   }
  986.   return ds;
  987. }
  988.  
  989. /**
  990.  * An enumeration of items in a JS array.
  991.  * @constructor
  992.  */
  993. function ArrayEnumerator(aItems) {
  994.   this._index = 0;
  995.   if (aItems) {
  996.     for (var i = 0; i < aItems.length; ++i) {
  997.       if (!aItems[i])
  998.         aItems.splice(i, 1);      
  999.     }
  1000.   }
  1001.   this._contents = aItems;
  1002. }
  1003.  
  1004. ArrayEnumerator.prototype = {
  1005.   _index: 0,
  1006.   _contents: [],
  1007.   
  1008.   hasMoreElements: function() {
  1009.     return this._index < this._contents.length;
  1010.   },
  1011.   
  1012.   getNext: function() {
  1013.     return this._contents[this._index++];      
  1014.   }
  1015. };
  1016.  
  1017. /**
  1018.  * An enumeration of files in a JS array.
  1019.  * @param   files
  1020.  *          The files to enumerate
  1021.  * @constructor
  1022.  */
  1023. function FileEnumerator(files) {
  1024.   this._index = 0;
  1025.   if (files) {
  1026.     for (var i = 0; i < files.length; ++i) {
  1027.       if (!files[i])
  1028.         files.splice(i, 1);      
  1029.     }
  1030.   }
  1031.   this._contents = files;
  1032. }
  1033.  
  1034. FileEnumerator.prototype = {
  1035.   _index: 0,
  1036.   _contents: [],
  1037.  
  1038.   /**
  1039.    * Gets the next file in the sequence.
  1040.    */  
  1041.   get nextFile() {
  1042.     if (this._index < this._contents.length)
  1043.       return this._contents[this._index++];
  1044.     return null;
  1045.   },
  1046.   
  1047.   /**
  1048.    * Stop enumerating. Nothing to do here.
  1049.    */
  1050.   close: function() {
  1051.   },
  1052. };
  1053.  
  1054. /**
  1055.  * An object which identifies an Install Location for items, where the location
  1056.  * relationship is each item living in a directory named with its GUID under 
  1057.  * the directory used when constructing this object.
  1058.  *
  1059.  * e.g. <location>\{GUID1}
  1060.  *      <location>\{GUID2}
  1061.  *      <location>\{GUID3}
  1062.  *      ...
  1063.  *
  1064.  * @param   name
  1065.  *          The string identifier of this Install Location.
  1066.  * @param   location
  1067.  *          The directory that contains the items. 
  1068.  * @constructor
  1069.  */
  1070. function DirectoryInstallLocation(name, location, restricted, priority) {
  1071.   this._name = name;
  1072.   if (location.exists()) {
  1073.     if (!location.isDirectory())
  1074.       throw new Error("location must be a directoy!");
  1075.   }
  1076.   else {
  1077.     try {
  1078.       location.create(nsILocalFile.DIRECTORY_TYPE, 0775);
  1079.     }
  1080.     catch (e) {
  1081.       LOG("DirectoryInstallLocation: failed to create location " + 
  1082.           " directory = " + location.path + ", exception = " + e + "\n");
  1083.     }
  1084.   }
  1085.  
  1086.   this._location = location;
  1087.   this._locationToIDMap = {};
  1088.   this._restricted = restricted;
  1089.   this._priority = priority;
  1090. }
  1091. DirectoryInstallLocation.prototype = {
  1092.   _name           : "",
  1093.   _location       : null,
  1094.   _locationToIDMap: null,
  1095.   _restricted     : false,
  1096.   _priority       : 0,
  1097.   _canAccess      : null,
  1098.   
  1099.   /**
  1100.    * See nsIExtensionManager.idl
  1101.    */
  1102.   get name() {
  1103.     return this._name;
  1104.   },
  1105.   
  1106.   /**
  1107.    * Reads a directory linked to in a file.
  1108.    * @param   file
  1109.    *          The file containing the directory path
  1110.    * @returns A nsILocalFile object representing the linked directory.
  1111.    */
  1112.   _readDirectoryFromFile: function(file) {
  1113.     var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1114.                         .createInstance(Components.interfaces.nsIFileInputStream);
  1115.     fis.init(file, -1, -1, false);
  1116.     var line = { value: "" };
  1117.     if (fis instanceof nsILineInputStream)
  1118.       fis.readLine(line);
  1119.     fis.close();
  1120.     if (line.value) {
  1121.       var linkedDirectory = Components.classes["@mozilla.org/file/local;1"]
  1122.                                       .createInstance(nsILocalFile);
  1123.       try {
  1124.         linkedDirectory.initWithPath(line.value);
  1125.       }
  1126.       catch (e) {
  1127.         linkedDirectory.setRelativeDescriptor(file.parent, line.value);
  1128.       }
  1129.       
  1130.       return linkedDirectory;
  1131.     }
  1132.     return null;
  1133.   },
  1134.   
  1135.   /**
  1136.    * See nsIExtensionManager.idl
  1137.    */
  1138.   get itemLocations() {
  1139.     var locations = [];
  1140.     if (!this._location.exists())
  1141.       return new FileEnumerator(locations);
  1142.     
  1143.     try {
  1144.       var entries = this._location.directoryEntries.QueryInterface(nsIDirectoryEnumerator);
  1145.       while (true) {
  1146.         var entry = entries.nextFile;
  1147.         if (!entry)
  1148.           break;
  1149.         entry instanceof nsILocalFile;
  1150.         if (!entry.isDirectory() && gIDTest.test(entry.leafName)) {
  1151.           var linkedDirectory = this._readDirectoryFromFile(entry);
  1152.           if (linkedDirectory && linkedDirectory.exists() && 
  1153.               linkedDirectory.isDirectory()) {
  1154.             locations.push(linkedDirectory);
  1155.             this._locationToIDMap[linkedDirectory.persistentDescriptor] = entry.leafName;
  1156.           }
  1157.         }
  1158.         else
  1159.           locations.push(entry);
  1160.       }
  1161.       entries.close();
  1162.     }
  1163.     catch (e) { 
  1164.     }
  1165.     return new FileEnumerator(locations);
  1166.   },
  1167.   
  1168.   /**
  1169.    * Retrieves the GUID for an item at the specified location.
  1170.    * @param   file
  1171.    *          The location where an item might live.
  1172.    * @returns The ID for an item that might live at the location specified.
  1173.    * 
  1174.    * N.B. This function makes no promises about whether or not this path is 
  1175.    *      actually maintained by this Install Location.
  1176.    */
  1177.   getIDForLocation: function(file) {
  1178.     var section = file.leafName;
  1179.     var filePD = file.persistentDescriptor;
  1180.     if (filePD in this._locationToIDMap) 
  1181.       section = this._locationToIDMap[filePD];
  1182.     
  1183.     if (gIDTest.test(section))
  1184.       return RegExp.$1;
  1185.     return undefined;
  1186.   },
  1187.   
  1188.   /**
  1189.    * See nsIExtensionManager.idl
  1190.    */
  1191.   get location() {
  1192.     return this._location.clone();
  1193.   },
  1194.   
  1195.   /**
  1196.    * See nsIExtensionManager.idl
  1197.    */
  1198.   get restricted() {
  1199.     return this._restricted;
  1200.   },
  1201.   
  1202.   /**
  1203.    * See nsIExtensionManager.idl
  1204.    */
  1205.   get canAccess() {
  1206.     if (this._canAccess != null)
  1207.       return this._canAccess;
  1208.  
  1209.     var testFile = this.location;
  1210.     testFile.append("Access Privileges Test");
  1211.     try {
  1212.       testFile.createUnique(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1213.       testFile.remove(false);
  1214.       this._canAccess = true;
  1215.     }
  1216.     catch (e) {
  1217.       this._canAccess = false;
  1218.     }
  1219.     return this._canAccess;
  1220.   },
  1221.   
  1222.   /**
  1223.    * See nsIExtensionManager.idl
  1224.    */
  1225.   get priority() {
  1226.     return this._priority;
  1227.   },
  1228.   
  1229.   /**
  1230.    * See nsIExtensionManager.idl
  1231.    */
  1232.   getItemLocation: function(id) {
  1233.     var itemLocation = this.location;
  1234.     itemLocation.append(id);
  1235.     if (itemLocation.exists() && !itemLocation.isDirectory())
  1236.       return this._readDirectoryFromFile(itemLocation);
  1237.     if (!itemLocation.exists() && this.canAccess)
  1238.       itemLocation.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1239.     return itemLocation;
  1240.   },
  1241.   
  1242.   /**
  1243.    * See nsIExtensionManager.idl
  1244.    */
  1245.   itemIsManagedIndependently: function(id) {
  1246.     var itemLocation = this.location;
  1247.     itemLocation.append(id);
  1248.     return itemLocation.exists() && !itemLocation.isDirectory();      
  1249.   },
  1250.   
  1251.   /**
  1252.    * See nsIExtensionManager.idl
  1253.    */
  1254.   getItemFile: function(id, filePath) {
  1255.     var itemLocation = this.getItemLocation(id).clone();
  1256.     var parts = filePath.split("/");
  1257.     for (var i = 0; i < parts.length; ++i)
  1258.       itemLocation.append(parts[i]);
  1259.     return itemLocation;
  1260.   },
  1261.  
  1262.   /**
  1263.    * Stages the specified file for later.
  1264.    * @param   file
  1265.    *          The file to stage
  1266.    * @param   id
  1267.    *          The GUID of the item the file represents
  1268.    */
  1269.   stageFile: function(file, id) {
  1270.     var stagedFile = this.location;
  1271.     stagedFile.append(DIR_STAGE);
  1272.     stagedFile.append(id);
  1273.     stagedFile.append(file.leafName);
  1274.  
  1275.     // When an incompatible update is successful the file is already staged
  1276.     if (stagedFile.equals(file))
  1277.       return stagedFile;
  1278.  
  1279.     if (stagedFile.exists()) 
  1280.       stagedFile.remove(false);
  1281.       
  1282.     file.copyTo(stagedFile.parent, stagedFile.leafName);
  1283.     
  1284.     // If the file has incorrect permissions set, correct them now.
  1285.     if (!stagedFile.isWritable())
  1286.       stagedFile.permissions = PERMS_FILE;
  1287.     
  1288.     return stagedFile;
  1289.   },
  1290.   
  1291.   /**
  1292.    * Returns the most recently staged package (e.g. the last XPI or JAR in a
  1293.    * directory) for an item and removes items that do not qualify.
  1294.    * @param   id
  1295.    *          The ID of the staged package
  1296.    * @returns an nsIFile if the package exists otherwise null.
  1297.    */
  1298.   getStageFile: function(id) {
  1299.     var stageFile = null;
  1300.     var stageDir = this.location;
  1301.     stageDir.append(DIR_STAGE);
  1302.     stageDir.append(id);
  1303.     if (!stageDir.exists() || !stageDir.isDirectory())
  1304.       return null;
  1305.     try {
  1306.       var entries = stageDir.directoryEntries.QueryInterface(nsIDirectoryEnumerator);
  1307.       while (entries.hasMoreElements()) {
  1308.         var file = entries.nextFile;
  1309.         if (!(file instanceof nsILocalFile))
  1310.           continue;
  1311.         if (file.isDirectory())
  1312.           removeDirRecursive(file);
  1313.         else if (fileIsItemPackage(file)) {
  1314.           if (stageFile)
  1315.             stageFile.remove(false);
  1316.           stageFile = file;
  1317.         }
  1318.         else
  1319.           file.remove(false);
  1320.       }
  1321.     }
  1322.     catch (e) {
  1323.     }
  1324.     if (entries instanceof nsIDirectoryEnumerator)
  1325.       entries.close();
  1326.     return stageFile;
  1327.   },
  1328.   
  1329.   /**
  1330.    * Removes a file from the stage. This cleans up the stage if there is nothing
  1331.    * else left after the remove operation.
  1332.    * @param   file
  1333.    *          The file to remove.
  1334.    */
  1335.   removeFile: function(file) {
  1336.     if (file.exists())
  1337.       file.remove(false);
  1338.     var parent = file.parent;
  1339.     var entries = parent.directoryEntries;    
  1340.     try {
  1341.       // XXXrstrong calling hasMoreElements on a nsIDirectoryEnumerator after
  1342.       // it has been removed will cause a crash on Mac OS X - bug 292823
  1343.       while (parent && !parent.equals(this.location) &&
  1344.             !entries.hasMoreElements()) {
  1345.         parent.remove(false);
  1346.         parent = parent.parent;
  1347.         entries = parent.directoryEntries;
  1348.       }
  1349.       if (entries instanceof nsIDirectoryEnumerator)
  1350.         entries.close();
  1351.     }
  1352.     catch (e) {
  1353.       LOG("DirectoryInstallLocation::removeFile: failed to remove staged " + 
  1354.           " directory = " + parent.path + ", exception = " + e + "\n");
  1355.     }
  1356.   },
  1357.   
  1358.   /**
  1359.    * See nsISupports.idl
  1360.    */
  1361.   QueryInterface: function (iid) {
  1362.     if (!iid.equals(Components.interfaces.nsIInstallLocation) &&
  1363.         !iid.equals(Components.interfaces.nsISupports))
  1364.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1365.     return this;
  1366.   }
  1367. };
  1368.  
  1369. //@line 1441 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  1370.  
  1371. /**
  1372.  * An object which handles the installation of an Extension.
  1373.  * @constructor
  1374.  */
  1375. function Installer(ds, id, installLocation, type) {
  1376.   this._ds = ds;
  1377.   this._id = id;
  1378.   this._type = type;
  1379.   this._installLocation = installLocation;
  1380. }
  1381. Installer.prototype = {
  1382.   // Item metadata
  1383.   _id: null,
  1384.   _ds: null,
  1385.   _installLocation: null,
  1386.   _metadataDS: null,
  1387.   
  1388.   /**
  1389.    * Gets the Install Manifest datasource we are installing from.
  1390.    */
  1391.   get metadataDS() {
  1392.     if (!this._metadataDS) {
  1393.       var metadataFile = this._installLocation
  1394.                              .getItemFile(this._id, FILE_INSTALL_MANIFEST);
  1395.       if (!metadataFile.exists()) 
  1396.         return null;
  1397.       this._metadataDS = getInstallManifest(metadataFile);
  1398.       if (!this._metadataDS) {
  1399.         LOG("Installer::install: metadata datasource for extension " + 
  1400.             this._id + " at " + metadataFile.path + " could not be loaded. " + 
  1401.             " Installation will not proceed.");
  1402.       }
  1403.     }
  1404.     return this._metadataDS;
  1405.   },
  1406.   
  1407.   /**
  1408.    * Installs the Extension
  1409.    * @param   file
  1410.    *          A XPI/JAR file to install from. If this is null or does not exist,
  1411.    *          the item is assumed to be an expanded directory, located at the GUID
  1412.    *          key in the supplied Install Location.
  1413.    */
  1414.   installFromFile: function(file) {
  1415.     // Move files from the staging dir into the extension's final home.
  1416.     if (file && file.exists()) {
  1417.       this._installExtensionFiles(file);
  1418.     }
  1419.  
  1420.     if (!this.metadataDS)
  1421.       return;
  1422.  
  1423.     // Upgrade old-style contents.rdf Chrome Manifests if necessary.
  1424.     if (this._type == nsIUpdateItem.TYPE_THEME)
  1425.       this.upgradeThemeChrome();
  1426.     else
  1427.       this.upgradeExtensionChrome();
  1428.  
  1429.     // Add metadata for the extension to the global extension metadata set
  1430.     this._ds.addItemMetadata(this._id, this.metadataDS, this._installLocation);
  1431.   },
  1432.   
  1433.   /**
  1434.    * Safely extract the Extension's files into the target folder.
  1435.    * @param   file
  1436.    *          The XPI/JAR file to install from.
  1437.    */
  1438.   _installExtensionFiles: function(file) {
  1439.     var installer = this;
  1440.     /**
  1441.       * Callback for |safeInstallOperation| that performs file level installation
  1442.       * steps for an Extension.
  1443.       * @param   extensionID
  1444.       *          The GUID of the Extension being installed.
  1445.       * @param   installLocation 
  1446.       *          The Install Location where the Extension is being installed.
  1447.       * @param   xpiFile
  1448.       *          The source XPI file that contains the Extension.
  1449.       */
  1450.     function extractExtensionFiles(extensionID, installLocation, xpiFile) {
  1451.       // Create a logger to log install operations for uninstall. This must be 
  1452.       // created in the |safeInstallOperation| callback, since it creates a file
  1453.       // in the target directory. If we do this outside of the callback, we may
  1454.       // be clobbering a file we should not be.
  1455.       var zipReader = getZipReaderForFile(xpiFile);
  1456.       
  1457.       // create directories first
  1458.       var entries = zipReader.findEntries("*/");
  1459.       while (entries.hasMoreElements()) {
  1460.         var entry = entries.getNext().QueryInterface(Components.interfaces.nsIZipEntry);
  1461.         var target = installLocation.getItemFile(extensionID, entry.name);
  1462.         if (!target.exists()) {
  1463.           try {
  1464.             target.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1465.           }
  1466.           catch (e) {
  1467.             LOG("extractExtensionsFiles: failed to create target directory for extraction " + 
  1468.                 " file = " + target.path + ", exception = " + e + "\n");
  1469.           }
  1470.         }
  1471.       }
  1472.  
  1473.       entries = zipReader.findEntries("*");
  1474.       while (entries.hasMoreElements()) {
  1475.         entry = entries.getNext().QueryInterface(Components.interfaces.nsIZipEntry);
  1476.         target = installLocation.getItemFile(extensionID, entry.name);
  1477.         if (target.exists())
  1478.           continue;
  1479.  
  1480.         try {
  1481.           target.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1482.         }
  1483.         catch (e) {
  1484.           LOG("extractExtensionsFiles: failed to create target file for extraction " + 
  1485.               " file = " + target.path + ", exception = " + e + "\n");
  1486.         }
  1487.         zipReader.extract(entry.name, target);
  1488.       }
  1489.       zipReader.close();
  1490.     }
  1491.  
  1492.     var installer = this;
  1493.     /**
  1494.       * Callback for |safeInstallOperation| that performs file level installation
  1495.       * steps for a Theme.
  1496.       * @param   id
  1497.       *          The GUID of the Theme being installed.
  1498.       * @param   installLocation 
  1499.       *          The Install Location where the Theme is being installed.
  1500.       * @param   jarFile
  1501.       *          The source JAR file that contains the Theme.
  1502.       */
  1503.     function extractThemeFiles(id, installLocation, jarFile) {
  1504.       var themeDirectory = installLocation.getItemLocation(id);
  1505.       var zipReader = getZipReaderForFile(jarFile);
  1506.  
  1507.       // The only critical file is the install.rdf and we would not have
  1508.       // gotten this far without one.
  1509.       var rootFiles = [FILE_INSTALL_MANIFEST, FILE_CHROME_MANIFEST,
  1510.                        "preview.png", "icon.png"];
  1511.       for (var i = 0; i < rootFiles.length; ++i) {
  1512.         try {
  1513.           var entry = zipReader.getEntry(rootFiles[i]);
  1514.           var target = installLocation.getItemFile(id, rootFiles[i]);
  1515.           zipReader.extract(rootFiles[i], target);
  1516.         }
  1517.         catch (e) {
  1518.         }
  1519.       }
  1520.  
  1521.       var manifestFile = installLocation.getItemFile(id, FILE_CHROME_MANIFEST);
  1522.       // new theme structure requires a chrome.manifest file
  1523.       if (manifestFile.exists()) {
  1524.         var entries = zipReader.findEntries(DIR_CHROME + "/*");
  1525.         while (entries.hasMoreElements()) {
  1526.           entry = entries.getNext().QueryInterface(Components.interfaces.nsIZipEntry);
  1527.           if (entry.name.substr(entry.name.length - 1, 1) == "/")
  1528.             continue;
  1529.           target = installLocation.getItemFile(id, entry.name);
  1530.           try {
  1531.             target.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1532.           }
  1533.           catch (e) {
  1534.             LOG("extractThemeFiles: failed to create target file for extraction " + 
  1535.                 " file = " + target.path + ", exception = " + e + "\n");
  1536.           }
  1537.           zipReader.extract(entry.name, target);
  1538.         }
  1539.         zipReader.close();
  1540.       }
  1541.       else { // old theme structure requires only an install.rdf
  1542.         try {
  1543.           var entry = zipReader.getEntry(FILE_CONTENTS_MANIFEST);
  1544.           var contentsManifestFile = installLocation.getItemFile(id, FILE_CONTENTS_MANIFEST);
  1545.           contentsManifestFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1546.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  1547.         }
  1548.         catch (e) {
  1549.           zipReader.close();
  1550.           LOG("extractThemeFiles: failed to extract contents.rdf: " + target.path);
  1551.           throw e; // let the safe-op clean up
  1552.         }
  1553.         zipReader.close();
  1554.         var chromeDir = installLocation.getItemFile(id, DIR_CHROME);
  1555.         try {
  1556.           jarFile.copyTo(chromeDir, jarFile.leafName);
  1557.         }
  1558.         catch (e) {
  1559.           LOG("extractThemeFiles: failed to copy theme JAR file to: " + chromeDir.path);
  1560.           throw e; // let the safe-op clean up
  1561.         }
  1562.  
  1563.         if (!installer.metadataDS && installer._type == nsIUpdateItem.TYPE_THEME) {
  1564.           if (contentsManifestFile && contentsManifestFile.exists()) {
  1565.             var contentsManifest = gRDF.GetDataSourceBlocking(getURLSpecFromFile(contentsManifestFile));
  1566.             showOldThemeError(contentsManifest);
  1567.           }
  1568.           LOG("Theme JAR file: " + jarFile.leafName + " contains an Old-Style " + 
  1569.               "Theme that is not compatible with this version of the software.");
  1570.           throw new Error("Old Theme"); // let the safe-op clean up
  1571.         }
  1572.       }
  1573.     }
  1574.  
  1575.     var callback = extractExtensionFiles;
  1576.     if (this._type == nsIUpdateItem.TYPE_THEME)
  1577.       callback = extractThemeFiles;
  1578.     safeInstallOperation(this._id, this._installLocation,
  1579.                           { callback: callback, data: file });
  1580.   },
  1581.   
  1582.   /** 
  1583.    * Upgrade contents.rdf Chrome Manifests used by this Theme to the new 
  1584.    * chrome.manifest format if necessary.
  1585.    */
  1586.   upgradeThemeChrome: function() {
  1587.     // Use the Chrome Registry API to install the theme there
  1588.     var cr = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
  1589.                        .getService(Components.interfaces.nsIToolkitChromeRegistry);
  1590.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1591.     if (manifestFile.exists() ||
  1592.         this._id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  1593.       return;
  1594.  
  1595.     try {
  1596.       // creates a chrome manifest for themes
  1597.       var manifestURI = getURIFromFile(manifestFile);
  1598.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1599.       // We're relying on the fact that there is only one JAR file
  1600.       // in the "chrome" directory. This is a hack, but it works.
  1601.       var entries = chromeDir.directoryEntries.QueryInterface(nsIDirectoryEnumerator);
  1602.       var jarFile = entries.nextFile;
  1603.       if (jarFile) {
  1604.         var jarFileURI = getURIFromFile(jarFile);
  1605.         var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  1606.         var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1607.         var contentsFileURI = getURIFromFile(contentsFile.parent);
  1608.  
  1609.         cr.processContentsManifest(contentsFileURI, manifestURI, contentsURI, false, true);
  1610.       }
  1611.       entries.close();
  1612.       contentsFile.remove(false);
  1613.     }
  1614.     catch (e) {
  1615.       // Failed to register chrome, for any number of reasons - non-existent 
  1616.       // contents.rdf file at the location specified, malformed contents.rdf, 
  1617.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the 
  1618.       // extension is uninstalled properly during the subsequent uninstall 
  1619.       // pass in |ExtensionManager::_finalizeOperations|
  1620.       LOG("upgradeThemeChrome: failed for theme " + this._id + " - why " + 
  1621.           "not convert to the new chrome.manifest format while you're at it? " + 
  1622.           "Failure exception: " + e);
  1623.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1624.                   [BundleManager.appName]);
  1625.  
  1626.       var stageFile = this._installLocation.getStageFile(this._id);
  1627.       if (stageFile)
  1628.         this._installLocation.removeFile(stageFile);
  1629.  
  1630.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1631.       StartupCache.write();
  1632.     }
  1633.   },
  1634.  
  1635.   /** 
  1636.    * Upgrade contents.rdf Chrome Manifests used by this Extension to the new 
  1637.    * chrome.manifest format if necessary.
  1638.    */
  1639.   upgradeExtensionChrome: function() {
  1640.     // If the extension is aware of the new flat chrome manifests and has 
  1641.     // included one, just use it instead of generating one from the
  1642.     // install.rdf/contents.rdf data.
  1643.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1644.     if (manifestFile.exists())
  1645.       return;
  1646.  
  1647.     try {
  1648.       // Enumerate the metadata datasource files collection and register chrome
  1649.       // for each file, calling _registerChrome for each.
  1650.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1651.       
  1652.       if (!manifestFile.parent.exists())
  1653.         return;
  1654.  
  1655.       // Even if an extension doesn't have any chrome, we generate an empty
  1656.       // manifest file so that we don't try to upgrade from the "old-style"
  1657.       // chrome manifests at every startup.
  1658.       manifestFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1659.  
  1660.       var manifestURI = getURIFromFile(manifestFile);
  1661.       var files = this.metadataDS.GetTargets(gInstallManifestRoot, EM_R("file"), true);
  1662.       while (files.hasMoreElements()) {
  1663.         var file = files.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  1664.         var chromeFile = chromeDir.clone();
  1665.         var fileName = file.Value.substr("urn:mozilla:extension:file:".length, file.Value.length);
  1666.         chromeFile.append(fileName);
  1667.  
  1668.         var fileURLSpec = getURLSpecFromFile(chromeFile);
  1669.         if (!chromeFile.isDirectory()) {
  1670.           var zipReader = getZipReaderForFile(chromeFile);
  1671.           fileURLSpec = "jar:" + fileURLSpec + "!/";
  1672.           var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1673.           contentsFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1674.         }
  1675.  
  1676.         var providers = [EM_R("package"), EM_R("skin"), EM_R("locale")];
  1677.         for (var i = 0; i < providers.length; ++i) {
  1678.           var items = this.metadataDS.GetTargets(file, providers[i], true);
  1679.           while (items.hasMoreElements()) {
  1680.             var item = items.getNext().QueryInterface(Components.interfaces.nsIRDFLiteral);
  1681.             var fileURI = newURI(fileURLSpec + item.Value);
  1682.             // Extract the contents.rdf files instead of opening them inside of
  1683.             // the jar. This prevents the jar from being cached by the zip
  1684.             // reader which will keep the jar in use and prevent deletion.
  1685.             if (zipReader) {
  1686.               zipReader.extract(item.Value + FILE_CONTENTS_MANIFEST, contentsFile);
  1687.               var contentsFileURI = getURIFromFile(contentsFile.parent);
  1688.             }
  1689.             else
  1690.               contentsFileURI = fileURI;
  1691.  
  1692.             var cr = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
  1693.                                .getService(Components.interfaces.nsIToolkitChromeRegistry);
  1694.             cr.processContentsManifest(contentsFileURI, manifestURI, fileURI, true, false);
  1695.           }
  1696.         }
  1697.         if (zipReader) {
  1698.           zipReader.close();
  1699.           zipReader = null;
  1700.           contentsFile.remove(false);
  1701.         }
  1702.       }
  1703.     }
  1704.     catch (e) {
  1705.       // Failed to register chrome, for any number of reasons - non-existent 
  1706.       // contents.rdf file at the location specified, malformed contents.rdf, 
  1707.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the 
  1708.       // extension is uninstalled properly during the subsequent uninstall 
  1709.       // pass in |ExtensionManager::_finalizeOperations|
  1710.       LOG("upgradeExtensionChrome: failed for extension " + this._id + " - why " + 
  1711.           "not convert to the new chrome.manifest format while you're at it? " + 
  1712.           "Failure exception: " + e);
  1713.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1714.                   [BundleManager.appName]);
  1715.  
  1716.       var stageFile = this._installLocation.getStageFile(this._id);
  1717.       if (stageFile)
  1718.         this._installLocation.removeFile(stageFile);
  1719.  
  1720.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1721.       StartupCache.write();
  1722.     }
  1723.   }  
  1724. };
  1725.  
  1726. /**
  1727.  * Safely attempt to perform a caller-defined install operation for a given
  1728.  * item ID. Using aggressive success-safety checks, this function will attempt
  1729.  * to move an existing location for an item aside and then allow installation
  1730.  * into the appropriate folder. If any operation fails the installation will 
  1731.  * abort and roll back from the moved-aside old version.
  1732.  * @param   itemID
  1733.  *          The GUID of the item to perform the operation on.
  1734.  * @param   installLocation
  1735.  *          The Install Location where the item is installed.
  1736.  * @param   installCallback
  1737.  *          A caller supplied JS object with the following properties:
  1738.  *          "data"      A data parameter to be passed to the callback.
  1739.  *          "callback"  A function to perform the install operation. This
  1740.  *                      function is passed three parameters:
  1741.  *                      1. The GUID of the item being operated on.
  1742.  *                      2. The Install Location where the item is installed.
  1743.  *                      3. The "data" parameter on the installCallback object.
  1744.  */
  1745. function safeInstallOperation(itemID, installLocation, installCallback) {
  1746.   var movedFiles = [];
  1747.   
  1748.   /**
  1749.    * Reverts a deep move by moving backed up files back to their original
  1750.    * location.
  1751.    */
  1752.   function rollbackMove()
  1753.   {
  1754.     for (var i = 0; i < movedFiles.length; ++i) {
  1755.       var oldFile = movedFiles[i].oldFile;
  1756.       var newFile = movedFiles[i].newFile;
  1757.       try {
  1758.         newFile.moveTo(oldFile.parent, newFile.leafName);
  1759.       }
  1760.       catch (e) {
  1761.         LOG("safeInstallOperation: failed to roll back files after an install " + 
  1762.             "operation failed. Failed to roll back: " + newFile.path + " to: " + 
  1763.             oldFile.path + " ... aborting installation.");
  1764.         throw e;
  1765.       }
  1766.     }
  1767.   }
  1768.   
  1769.   /**
  1770.    * Moves a file to a new folder.
  1771.    * @param   file
  1772.    *          The file to move
  1773.    * @param   destination
  1774.    *          The target folder
  1775.    */
  1776.   function moveFile(file, destination) {
  1777.     try {
  1778.       var oldFile = file.clone();
  1779.       file.moveTo(destination, file.leafName);
  1780.       movedFiles.push({ oldFile: oldFile, newFile: file });
  1781.     }
  1782.     catch (e) {
  1783.       LOG("safeInstallOperation: failed to back up file: " + file.path + " to: " + 
  1784.           destination.path + " ... rolling back file moves and aborting " + 
  1785.           "installation.");
  1786.       rollbackMove();
  1787.       throw e;
  1788.     }
  1789.   }
  1790.   
  1791.   /**
  1792.    * Moves a directory to a new location. If any part of the move fails,
  1793.    * files already moved will be rolled back.
  1794.    * @param   sourceDir
  1795.    *          The directory to move
  1796.    * @param   targetDir
  1797.    *          The destination directory
  1798.    * @param   currentDir
  1799.    *          The current directory (a subdirectory of |sourceDir| or 
  1800.    *          |sourceDir| itself) we are moving files from.
  1801.    */
  1802.   function moveDirectory(sourceDir, targetDir, currentDir) {
  1803.     var entries = currentDir.directoryEntries.QueryInterface(nsIDirectoryEnumerator);
  1804.     while (true) {
  1805.       var entry = entries.nextFile;
  1806.       if (!entry)
  1807.         break;
  1808.       if (entry.isDirectory())
  1809.         moveDirectory(sourceDir, targetDir, entry);
  1810.       else if (entry instanceof nsILocalFile) {
  1811.         var rd = entry.getRelativeDescriptor(sourceDir);
  1812.         var destination = targetDir.clone().QueryInterface(nsILocalFile);
  1813.         destination.setRelativeDescriptor(targetDir, rd);
  1814.         moveFile(entry, destination.parent);
  1815.       }
  1816.     }
  1817.     entries.close();
  1818.   }
  1819.   
  1820.   /**
  1821.    * Removes the temporary backup directory where we stored files. 
  1822.    * @param   directory
  1823.    *          The backup directory to remove
  1824.    */
  1825.   function cleanUpTrash(directory) {
  1826.     try {
  1827.       // Us-generated. Safe.
  1828.       if (directory && directory.exists())
  1829.         removeDirRecursive(directory);
  1830.     }
  1831.     catch (e) {
  1832.       LOG("safeInstallOperation: failed to clean up the temporary backup of the " + 
  1833.           "older version: " + itemLocationTrash.path);
  1834.       // This is a non-fatal error. Annoying, but non-fatal. 
  1835.     }
  1836.   }
  1837.   
  1838.   if (!installLocation.itemIsManagedIndependently(itemID)) {
  1839.     var itemLocation = installLocation.getItemLocation(itemID);
  1840.     if (itemLocation.exists()) {
  1841.       var trashDirName = itemID + "-trash";
  1842.       var itemLocationTrash = itemLocation.parent.clone();
  1843.       itemLocationTrash.append(trashDirName);
  1844.       if (itemLocationTrash.exists()) {
  1845.         // We can remove recursively here since this is a folder we created, not
  1846.         // one the user specified. If this fails, it'll throw, and the caller 
  1847.         // should stop installation.
  1848.         try {
  1849.           removeDirRecursive(itemLocationTrash);
  1850.         }
  1851.         catch (e) {
  1852.           LOG("safeFileOperation: failed to remove existing trash directory " + 
  1853.               itemLocationTrash.path + " ... aborting installation.");
  1854.           throw e;
  1855.         }
  1856.       }
  1857.       
  1858.       // Move the directory that contains the existing version of the item aside, 
  1859.       // into {GUID}-trash. This will throw if there's a failure and the install
  1860.       // will abort.
  1861.       moveDirectory(itemLocation, itemLocationTrash, itemLocation);
  1862.       
  1863.       // Clean up the original location, if necessary. Again, this is a path we 
  1864.       // generated, so it is safe to recursively delete.
  1865.       try {
  1866.         removeDirRecursive(itemLocation);
  1867.       }
  1868.       catch (e) {
  1869.         LOG("safeInstallOperation: failed to clean up item location after its contents " + 
  1870.             "were properly backed up. Failed to clean up: " + itemLocation.path + 
  1871.             " ... rolling back file moves and aborting installation.");
  1872.         rollbackMove();
  1873.         cleanUpTrash(itemLocationTrash);
  1874.         throw e;
  1875.       }
  1876.     }
  1877.   }
  1878.   else if (installLocation.name == KEY_APP_PROFILE ||
  1879.            installLocation.name == KEY_APP_GLOBAL) {
  1880.     // Check for a pointer file and move it aside if it exists
  1881.     var pointerFile = installLocation.location.clone();
  1882.     pointerFile.append(itemID);
  1883.     if (pointerFile.exists() && !pointerFile.isDirectory()) {
  1884.       var trashFileName = itemID + "-trash";
  1885.       var itemLocationTrash = installLocation.location.clone();
  1886.       itemLocationTrash.append(trashFileName);
  1887.       if (itemLocationTrash.exists()) {
  1888.         // We can remove recursively here since this is a folder we created, not
  1889.         // one the user specified. If this fails, it'll throw, and the caller 
  1890.         // should stop installation.
  1891.         try {
  1892.           removeDirRecursive(itemLocationTrash);
  1893.         }
  1894.         catch (e) {
  1895.           LOG("safeFileOperation: failed to remove existing trash directory " + 
  1896.               itemLocationTrash.path + " ... aborting installation.");
  1897.           throw e;
  1898.         }
  1899.       }
  1900.       itemLocationTrash.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1901.       // Move the pointer file to the trash.
  1902.       moveFile(pointerFile, itemLocationTrash);
  1903.     }
  1904.   }
  1905.       
  1906.   // Now tell the client to do their stuff.
  1907.   try {
  1908.     installCallback.callback(itemID, installLocation, installCallback.data);
  1909.   }
  1910.   catch (e) {
  1911.     // This means the install operation failed. Remove everything and roll back.
  1912.     LOG("safeInstallOperation: install operation (caller-supplied callback) failed, " + 
  1913.         "rolling back file moves and aborting installation.");
  1914.     try {
  1915.       // Us-generated. Safe.
  1916.       removeDirRecursive(itemLocation);
  1917.     }
  1918.     catch (e) {
  1919.       LOG("safeInstallOperation: failed to remove the folder we failed to install " + 
  1920.           "an item into: " + itemLocation.path + " -- There is not much to suggest " + 
  1921.           "here... maybe restart and try again?");
  1922.       cleanUpTrash(itemLocationTrash);
  1923.       throw e;
  1924.     }
  1925.     rollbackMove();
  1926.     cleanUpTrash(itemLocationTrash);
  1927.     throw e;        
  1928.   }
  1929.   
  1930.   // Now, and only now - after everything else has succeeded (against all odds!) 
  1931.   // remove the {GUID}-trash directory where we stashed the old version of the 
  1932.   // item.
  1933.   cleanUpTrash(itemLocationTrash);
  1934. }
  1935.  
  1936. /**
  1937.  * Manages the list of pending operations.
  1938.  */
  1939. var PendingOperations = {
  1940.   _ops: { },
  1941.  
  1942.   /**
  1943.    * Adds an entry to the Pending Operations List
  1944.    * @param   opType
  1945.    *          The type of Operation to be performed
  1946.    * @param   entry
  1947.    *          A JS Object representing the item to be operated on:
  1948.    *          "locationKey"   The name of the Install Location where the item
  1949.    *                          is installed.
  1950.    *          "id"            The GUID of the item.
  1951.    */
  1952.   addItem: function(opType, entry) {
  1953.     if (opType == OP_NONE)
  1954.       this.clearOpsForItem(entry.id);
  1955.     else {
  1956.       if (!(opType in this._ops))
  1957.         this._ops[opType] = { };
  1958.       this._ops[opType][entry.id] = entry.locationKey;
  1959.     }
  1960.   },
  1961.   
  1962.   /**
  1963.    * Removes a Pending Operation from the list
  1964.    * @param   opType
  1965.    *          The type of Operation being removed
  1966.    * @param   id
  1967.    *          The GUID of the item to remove the entry for
  1968.    */
  1969.   clearItem: function(opType, id) {
  1970.     if (opType in this._ops && id in this._ops[opType])
  1971.       delete this._ops[opType][id];
  1972.   },
  1973.   
  1974.   /**
  1975.    * Removes all Pending Operation for an item
  1976.    * @param   id
  1977.    *          The ID of the item to remove the entries for
  1978.    */
  1979.   clearOpsForItem: function(id) {
  1980.     for (var opType in this._ops) {
  1981.       if (id in this._ops[opType])
  1982.         delete this._ops[opType][id];
  1983.     }
  1984.   },
  1985.  
  1986.   /**
  1987.    * Remove all Pending Operations of a certain type
  1988.    * @param   opType
  1989.    *          The type of Operation to remove all entries for
  1990.    */
  1991.   clearItems: function(opType) {
  1992.     if (opType in this._ops)
  1993.       delete this._ops[opType];
  1994.   },
  1995.   
  1996.   /**
  1997.    * Get an array of operations of a certain type
  1998.    * @param   opType
  1999.    *          The type of Operation to return a list of
  2000.    */
  2001.   getOperations: function(opType) {
  2002.     if (!(opType in this._ops))
  2003.       return [];
  2004.     var ops = [];
  2005.     for (var id in this._ops[opType])
  2006.       ops.push( {id: id, locationKey: this._ops[opType][id] } );
  2007.     return ops;
  2008.   },
  2009.   
  2010.   /**
  2011.    * The total number of Pending Operations, for all types.
  2012.    */
  2013.   get size() {
  2014.     var size = 0;
  2015.     for (var opType in this._ops) {
  2016.       for (var id in this._ops[opType])
  2017.         ++size;
  2018.     }
  2019.     return size;
  2020.   }
  2021. };
  2022.  
  2023. /**
  2024.  * Manages registered Install Locations
  2025.  */
  2026. var InstallLocations = { 
  2027.   _locations: { },
  2028.  
  2029.   /**
  2030.    * A nsISimpleEnumerator of all available Install Locations.
  2031.    */
  2032.   get enumeration() {
  2033.     var installLocations = [];
  2034.     for (var key in this._locations) 
  2035.       installLocations.push(InstallLocations.get(key));
  2036.     return new ArrayEnumerator(installLocations);
  2037.   },
  2038.   
  2039.   /**
  2040.    * Gets a named Install Location
  2041.    * @param   name
  2042.    *          The name of the Install Location to get
  2043.    */
  2044.   get: function(name) {
  2045.     return name in this._locations ? this._locations[name] : null;
  2046.   },
  2047.   
  2048.   /**
  2049.    * Registers an Install Location
  2050.    * @param   installLocation
  2051.    *          The Install Location to register
  2052.    */
  2053.   put: function(installLocation) {
  2054.     this._locations[installLocation.name] = installLocation;
  2055.   }
  2056. };
  2057.  
  2058. /**
  2059.  * Manages the Startup Cache. The Startup Cache is a representation
  2060.  * of the contents of extensions.cache, a list of all
  2061.  * items the Extension System knows about, whether or not they
  2062.  * are active or visible.
  2063.  */
  2064. var StartupCache = {
  2065.   /**
  2066.    * Location Name -> GUID hash of entries from the Startup Cache file
  2067.    * Each entry has the following properties:
  2068.    *  "descriptor"    The location on disk of the item
  2069.    *  "mtime"         The time the location was last modified
  2070.    *  "op"            Any pending operations on this item.
  2071.    *  "location"      The Install Location name where the item is installed.
  2072.    */
  2073.   entries: { },
  2074.  
  2075.   /**
  2076.    * Puts an entry into the Startup Cache
  2077.    * @param   installLocation
  2078.    *          The Install Location where the item is installed
  2079.    * @param   id
  2080.    *          The GUID of the item
  2081.    * @param   op
  2082.    *          The name of the operation to be performed
  2083.    * @param   shouldCreate
  2084.    *          Whether or not we should create a new entry for this item
  2085.    *          in the cache if one does not already exist. 
  2086.    */
  2087.   put: function(installLocation, id, op, shouldCreate) {
  2088.     var itemLocation = installLocation.getItemLocation(id);
  2089.  
  2090.     var descriptor = null;
  2091.     var mtime = null;
  2092.     if (itemLocation) {
  2093.       itemLocation.QueryInterface(nsILocalFile);
  2094.       descriptor = getDescriptorFromFile(itemLocation, installLocation);
  2095.       if (itemLocation.exists() && itemLocation.isDirectory())
  2096.         mtime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2097.     }
  2098.  
  2099.     this._putRaw(installLocation.name, id, descriptor, mtime, op, shouldCreate);
  2100.   },
  2101.  
  2102.   /**
  2103.    * Private helper function for putting an entry into the Startup Cache
  2104.    * without relying on the presence of its associated nsIInstallLocation
  2105.    * instance.
  2106.    *
  2107.    * @param key
  2108.    *        The install location name.
  2109.    * @param id
  2110.    *        The ID of the item.
  2111.    * @param descriptor
  2112.    *        Value returned from absoluteDescriptor.  May be null, in which
  2113.    *        case the descriptor field is not updated.
  2114.    * @param mtime
  2115.    *        The last modified time of the item.  May be null, in which case the
  2116.    *        descriptor field is not updated.
  2117.    * @param op
  2118.    *        The OP code to store with the entry.
  2119.    * @param shouldCreate
  2120.    *        Boolean value indicating whether to create or delete the entry.
  2121.    */
  2122.   _putRaw: function(key, id, descriptor, mtime, op, shouldCreate) {
  2123.     if (!(key in this.entries))
  2124.       this.entries[key] = { };
  2125.     if (!(id in this.entries[key]))
  2126.       this.entries[key][id] = { };
  2127.     if (shouldCreate) {
  2128.       if (!this.entries[key][id]) 
  2129.         this.entries[key][id] = { };
  2130.  
  2131.       var entry = this.entries[key][id];
  2132.  
  2133.       if (descriptor)
  2134.         entry.descriptor = descriptor;
  2135.       if (mtime) 
  2136.         entry.mtime = mtime;
  2137.       entry.op = op;
  2138.       entry.location = key;
  2139.     }
  2140.     else
  2141.       this.entries[key][id] = null;
  2142.   },
  2143.   
  2144.   /**
  2145.    * Clears an entry from the Startup Cache
  2146.    * @param   installLocation
  2147.    *          The Install Location where item is installed
  2148.    * @param   id
  2149.    *          The GUID of the item.
  2150.    */
  2151.   clearEntry: function(installLocation, id) {
  2152.     var key = installLocation.name;
  2153.     if (key in this.entries && id in this.entries[key])
  2154.       this.entries[key][id] = null;
  2155.   },
  2156.   
  2157.   /**
  2158.    * Get all the startup cache entries for a particular ID.
  2159.    * @param   id
  2160.    *          The GUID of the item to locate.
  2161.    * @returns An array of Startup Cache entries for the specified ID.
  2162.    */
  2163.   findEntries: function(id) {
  2164.     var entries = [];
  2165.     for (var key in this.entries) {
  2166.       if (id in this.entries[key]) 
  2167.         entries.push(this.entries[key][id]);
  2168.     }
  2169.     return entries;
  2170.   },
  2171.  
  2172.   /**
  2173.    * Call a function on each entry.  The callback function takes a single
  2174.    * parameter, which is an entry object.
  2175.    */
  2176.   forEachEntry: function(callback) {
  2177.     for (var key in this.entries) {
  2178.       for (id in this.entries[key])
  2179.         callback(this.entries[key][id]);
  2180.     }
  2181.   },
  2182.   
  2183.   /** 
  2184.    * Read the Item-Change manifest file into a hash of properties.
  2185.    * The Item-Change manifest currently holds a list of paths, with the last
  2186.    * mtime for each path, and the GUID of the item at that path.
  2187.    */
  2188.   read: function() {
  2189.     var itemChangeManifest = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2190.     if (!itemChangeManifest.exists()) {
  2191.       // There is no change manifest for some reason, either we're in an initial
  2192.       // state or something went wrong with one of the other files and the
  2193.       // change manifest was removed. Return an empty dataset and rebuild.
  2194.       return;
  2195.     }
  2196.     var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
  2197.                         .createInstance(Components.interfaces.nsIFileInputStream);
  2198.     fis.init(itemChangeManifest, -1, -1, false);
  2199.     if (fis instanceof nsILineInputStream) {
  2200.       var line = { value: "" };
  2201.       var more = false;
  2202.       do {
  2203.         more = fis.readLine(line);
  2204.         if (line.value) {
  2205.           // The Item-Change manifest is formatted like so:
  2206.           //  (pd = descriptor)
  2207.           // location-key\tguid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2208.           // location-key\tguid-of-item\tpd-to-extension2\tmtime-of-pd\tpending-op
  2209.           // ...
  2210.           // We hash on location-key first, because we don't want to have to 
  2211.           // spin up the main extensions datasource on every start to determine
  2212.           // the Install Location for an item.
  2213.           // We hash on guid second, because we want a way to quickly determine
  2214.           // item GUID during a check loop that runs on every startup.
  2215.           var parts = line.value.split("\t");
  2216.           var op = parts[4];
  2217.           this._putRaw(parts[0], parts[1], parts[2], parts[3], op, true);
  2218.           if (op)
  2219.             PendingOperations.addItem(op, { locationKey: parts[0], id: parts[1] });
  2220.         }
  2221.       }
  2222.       while (more);
  2223.     }
  2224.     fis.close();
  2225.   },
  2226.  
  2227.   /**
  2228.    * Writes the Startup Cache to disk
  2229.    */
  2230.   write: function() {
  2231.     var extensionsCacheFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2232.     var fos = openSafeFileOutputStream(extensionsCacheFile);
  2233.     for (var locationKey in this.entries) {
  2234.       for (var id in this.entries[locationKey]) {
  2235.         var entry = this.entries[locationKey][id];
  2236.         if (entry) {
  2237.           try {
  2238.             var itemLocation = getFileFromDescriptor(entry.descriptor, InstallLocations.get(locationKey));
  2239.  
  2240.             // Update our knowledge of this item's last-modified-time.
  2241.             // XXXdarin: this may cause us to miss changes in some cases.
  2242.             var itemMTime = 0;
  2243.             if (itemLocation.exists() && itemLocation.isDirectory())
  2244.               itemMTime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2245.  
  2246.             // Each line in the startup cache manifest is in this form:
  2247.             // location-key\tid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2248.             var line = locationKey + "\t" + id + "\t" + entry.descriptor + "\t" +
  2249.                        itemMTime + "\t" + entry.op + "\r\n";
  2250.             fos.write(line, line.length);
  2251.           }
  2252.           catch (e) {}
  2253.         }
  2254.       }
  2255.     }
  2256.     closeSafeFileOutputStream(fos);
  2257.   }
  2258. };
  2259.  
  2260. /**
  2261.  * Manages the Blocklist. The Blocklist is a representation of the contents of
  2262.  * blocklist.xml and allows us to remotely disable / re-enable blocklisted
  2263.  * items managed by the Extension Manager with an item's appDisabled property.
  2264.  */
  2265. var Blocklist = {
  2266.   /**
  2267.    * Extension ID -> array of Version Ranges
  2268.    * Each value in the version range array is a JS Object that has the
  2269.    * following properties:
  2270.    *   "minVersion"  The minimum version in a version range (default = 0)
  2271.    *   "maxVersion"  The maximum version in a version range (default = *)
  2272.    *   "targetApps"  Application ID -> array of Version Ranges
  2273.    *                 (default = current application ID)
  2274.    *                 Each value in the version range array is a JS Object that
  2275.    *                 has the following properties:
  2276.    *                   "minVersion"  The minimum version in a version range
  2277.    *                                 (default = 0)
  2278.    *                   "maxVersion"  The maximum version in a version range
  2279.    *                                 (default = *)
  2280.    */
  2281.   entries: null,
  2282.  
  2283.   notify: function() {
  2284.     if (getPref("getBoolPref", PREF_BLOCKLIST_ENABLED, true) == false)
  2285.       return;
  2286.  
  2287.     try {
  2288.       var dsURI = gPref.getCharPref(PREF_BLOCKLIST_URL);
  2289.     }
  2290.     catch (e) {
  2291.       LOG("Blocklist::notify: The " + PREF_BLOCKLIST_URL + " preference" + 
  2292.           " is missing!");
  2293.       return;
  2294.     }
  2295.  
  2296.     dsURI = dsURI.replace(/%APP_ID%/g, gApp.ID);
  2297.     dsURI = dsURI.replace(/%APP_VERSION%/g, gApp.version);
  2298.     // Verify that the URI is valid
  2299.     try {
  2300.       var uri = newURI(dsURI);
  2301.     }
  2302.     catch (e) {
  2303.       LOG("Blocklist::notify: There was an error creating the blocklist URI\r\n" + 
  2304.           "for: " + dsURI + ", error: " + e);
  2305.       return;
  2306.     }
  2307.  
  2308.     var request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  2309.                             .createInstance(Components.interfaces.nsIXMLHttpRequest);
  2310.     request.open("GET", uri.spec, true);
  2311.     request.channel.notificationCallbacks = new BadCertHandler();
  2312.     request.overrideMimeType("text/xml");
  2313.     request.setRequestHeader("Cache-Control", "no-cache");
  2314.  
  2315.     var self = this;
  2316.     request.onerror = function(event) { self.onXMLError(event); };
  2317.     request.onload  = function(event) { self.onXMLLoad(event);  };
  2318.     request.send(null);
  2319.   },
  2320.  
  2321.   onXMLLoad: function(aEvent) {
  2322.     var request = aEvent.target;
  2323.     try {
  2324.       checkCert(request.channel);
  2325.     }
  2326.     catch (e) {
  2327.       LOG("Blocklist::onXMLLoad: " + e);
  2328.       return;
  2329.     }
  2330.     var responseXML = request.responseXML;
  2331.     if (!responseXML || responseXML.documentElement.namespaceURI == XMLURI_PARSE_ERROR ||
  2332.         (request.status != 200 && request.status != 0)) {
  2333.       LOG("Blocklist::onXMLLoad: there was an error during load");
  2334.       return;
  2335.     }
  2336.     var blocklistFile = getFile(KEY_PROFILEDIR, [FILE_BLOCKLIST]);
  2337.     if (blocklistFile.exists())
  2338.       blocklistFile.remove(false);
  2339.     var fos = openSafeFileOutputStream(blocklistFile);
  2340.     fos.write(request.responseText, request.responseText.length);
  2341.     closeSafeFileOutputStream(fos);
  2342.     this.entries = this._loadBlocklistFromFile(getFile(KEY_PROFILEDIR,
  2343.                                                        [FILE_BLOCKLIST]));
  2344.     var em = Components.classes["@mozilla.org/extensions/manager;1"]
  2345.                        .getService(Components.interfaces.nsIExtensionManager)
  2346.                        .QueryInterface(Components.interfaces.nsIExtensionManager_MOZILLA_1_8_BRANCH);
  2347.     em.checkForBlocklistChanges();
  2348.   },
  2349.  
  2350.   onXMLError: function(aEvent) {
  2351.     try {
  2352.       var request = aEvent.target;
  2353.       // the following may throw (e.g. a local file or timeout)
  2354.       var status = request.status;
  2355.     }
  2356.     catch (e) {
  2357.       request = aEvent.target.channel.QueryInterface(Components.interfaces.nsIRequest);
  2358.       status = request.status;
  2359.     }
  2360.     var statusText = request.statusText;
  2361.     // When status is 0 we don't have a valid channel.
  2362.     if (status == 0)
  2363.       statusText = "nsIXMLHttpRequest channel unavailable";
  2364.     LOG("Blocklist:onError: There was an error loading the blocklist file\r\n" + 
  2365.         statusText);
  2366.   },
  2367.  
  2368.   /**
  2369.    * The blocklist XML file looks something like this:
  2370.    *
  2371.    * <blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist">
  2372.    *   <emItems>
  2373.    *     <emItem id="item_1@domain">
  2374.    *       <versionRange minVersion="1.0" maxVersion="2.0.*">
  2375.    *         <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
  2376.    *           <versionRange minVersion="1.5" maxVersion="1.5.*"/>
  2377.    *           <versionRange minVersion="1.7" maxVersion="1.7.*"/>
  2378.    *         </targetApplication>
  2379.    *         <targetApplication id="toolkit@mozilla.org">
  2380.    *           <versionRange minVersion="1.8" maxVersion="1.8.*"/>
  2381.    *         </targetApplication>
  2382.    *       </versionRange>
  2383.    *       <versionRange minVersion="3.0" maxVersion="3.0.*">
  2384.    *         <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
  2385.    *           <versionRange minVersion="1.5" maxVersion="1.5.*"/>
  2386.    *         </targetApplication>
  2387.    *         <targetApplication id="toolkit@mozilla.org">
  2388.    *           <versionRange minVersion="1.8" maxVersion="1.8.*"/>
  2389.    *         </targetApplication>
  2390.    *       </versionRange>
  2391.    *     </emItem>
  2392.    *     <emItem id="item_2@domain">
  2393.    *       <versionRange minVersion="3.1" maxVersion="4.*"/>
  2394.    *     </emItem>
  2395.    *     <emItem id="item_3@domain">
  2396.    *       <versionRange>
  2397.    *         <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
  2398.    *           <versionRange minVersion="1.5" maxVersion="1.5.*"/>
  2399.    *         </targetApplication>
  2400.    *       </versionRange>
  2401.    *     </emItem>
  2402.    *     <emItem id="item_4@domain">
  2403.    *       <versionRange>
  2404.    *         <targetApplication>
  2405.    *           <versionRange minVersion="1.5" maxVersion="1.5.*"/>
  2406.    *         </targetApplication>
  2407.    *       </versionRange>
  2408.    *     <emItem id="item_5@domain"/>
  2409.    *   </emItems>
  2410.    * </blocklist> 
  2411.    */
  2412.   _loadBlocklistFromFile: function(file) {
  2413.     if (getPref("getBoolPref", PREF_BLOCKLIST_ENABLED, true) == false) {
  2414.       LOG("Blocklist::_loadBlocklistFromFile: blocklist is disabled");
  2415.       return { };
  2416.     }
  2417.  
  2418.     if (!file.exists()) {
  2419.       LOG("Blocklist::_loadBlocklistFromFile: XML File does not exist");
  2420.       return { };
  2421.     }
  2422.  
  2423.     var result = { };
  2424.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  2425.                                .createInstance(Components.interfaces.nsIFileInputStream);
  2426.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  2427.     try {
  2428.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  2429.                              .createInstance(Components.interfaces.nsIDOMParser);
  2430.       var doc = parser.parseFromStream(fileStream, "UTF-8", file.fileSize, "text/xml");
  2431.       if (doc.documentElement.namespaceURI != XMLURI_BLOCKLIST) {
  2432.         LOG("Blocklist::_loadBlocklistFromFile: aborting due to incorrect " +
  2433.             "XML Namespace.\r\nExpected: " + XMLURI_BLOCKLIST + "\r\n" +
  2434.             "Received: " + doc.documentElement.namespaceURI);
  2435.         return { };
  2436.       }
  2437.  
  2438.       const kELEMENT_NODE = Components.interfaces.nsIDOMNode.ELEMENT_NODE;
  2439.       var itemNodes = this._getItemNodes(doc.documentElement.childNodes);
  2440.       for (var i = 0; i < itemNodes.length; ++i) {
  2441.         var blocklistElement = itemNodes[i];
  2442.         if (blocklistElement.nodeType != kELEMENT_NODE ||
  2443.             blocklistElement.localName != "emItem")
  2444.           continue;
  2445.  
  2446.         blocklistElement.QueryInterface(Components.interfaces.nsIDOMElement);
  2447.         var versionNodes = blocklistElement.childNodes;
  2448.         var id = blocklistElement.getAttribute("id");
  2449.         result[id] = [];
  2450.         for (var x = 0; x < versionNodes.length; ++x) {
  2451.           var versionRangeElement = versionNodes[x];
  2452.           if (versionRangeElement.nodeType != kELEMENT_NODE ||
  2453.               versionRangeElement.localName != "versionRange")
  2454.             continue;
  2455.  
  2456.           result[id].push(new BlocklistItemData(versionRangeElement));
  2457.         }
  2458.         // if only the extension ID is specified block all versions of the
  2459.         // extension for the current application.
  2460.         if (result[id].length == 0)
  2461.           result[id].push(new BlocklistItemData(null));
  2462.       }
  2463.     }
  2464.     catch (e) {
  2465.       LOG("Blocklist::_loadBlocklistFromFile: Error constructing blocklist " + e);
  2466.       return { };
  2467.     }
  2468.     fileStream.close();
  2469.     return result;
  2470.   },
  2471.  
  2472.   _getItemNodes: function(deChildNodes) {
  2473.     const kELEMENT_NODE = Components.interfaces.nsIDOMNode.ELEMENT_NODE;
  2474.     for (var i = 0; i < deChildNodes.length; ++i) {
  2475.       var emItemsElement = deChildNodes[i];
  2476.       if (emItemsElement.nodeType == kELEMENT_NODE &&
  2477.           emItemsElement.localName == "emItems")
  2478.         return emItemsElement.childNodes;
  2479.     }
  2480.     return [ ];
  2481.   },
  2482.  
  2483.   _ensureBlocklist: function() {
  2484.     if (!this.entries)
  2485.       this.entries = this._loadBlocklistFromFile(getFile(KEY_PROFILEDIR, 
  2486.                                                          [FILE_BLOCKLIST]));
  2487.   }
  2488. };
  2489.  
  2490. /**
  2491.  * Helper for constructing a blocklist.
  2492.  */
  2493. function BlocklistItemData(versionRangeElement) {
  2494.   var versionRange = this.getBlocklistVersionRange(versionRangeElement);
  2495.   this.minVersion = versionRange.minVersion;
  2496.   this.maxVersion = versionRange.maxVersion;
  2497.   this.targetApps = { };
  2498.   var found = false;
  2499.  
  2500.   if (versionRangeElement) {
  2501.     for (var i = 0; i < versionRangeElement.childNodes.length; ++i) {
  2502.       var targetAppElement = versionRangeElement.childNodes[i];
  2503.       if (targetAppElement.nodeType != Components.interfaces.nsIDOMNode.ELEMENT_NODE ||
  2504.           targetAppElement.localName != "targetApplication")
  2505.         continue;
  2506.       found = true;
  2507.       // default to the current application if id is not provided.
  2508.       var appID = targetAppElement.hasAttribute("id") ? targetAppElement.getAttribute("id") : gApp.ID;
  2509.       this.targetApps[appID] = this.getBlocklistAppVersions(targetAppElement);
  2510.     }
  2511.   }
  2512.   // Default to all versions of the extension and the current application when
  2513.   // versionRange is not defined.
  2514.   if (!found)
  2515.     this.targetApps[gApp.ID] = this.getBlocklistAppVersions(null);
  2516. }
  2517.  
  2518. BlocklistItemData.prototype = {
  2519. /**
  2520.  * Retrieves a version range (e.g. minVersion and maxVersion) for a
  2521.  * blocklist item's targetApplication element.
  2522.  * @param   targetAppElement
  2523.  *          A targetApplication blocklist element.
  2524.  * @returns An array of JS objects with the following properties:
  2525.  *          "minVersion"  The minimum version in a version range (default = 0).
  2526.  *          "maxVersion"  The maximum version in a version range (default = *).
  2527.  */
  2528.   getBlocklistAppVersions: function(targetAppElement) {
  2529.     var appVersions = [ ];
  2530.     var found = false;
  2531.  
  2532.     if (targetAppElement) {
  2533.       for (var i = 0; i < targetAppElement.childNodes.length; ++i) {
  2534.         var versionRangeElement = targetAppElement.childNodes[i];
  2535.         if (versionRangeElement.nodeType != Components.interfaces.nsIDOMNode.ELEMENT_NODE ||
  2536.             versionRangeElement.localName != "versionRange")
  2537.           continue;
  2538.         found = true;
  2539.         appVersions.push(this.getBlocklistVersionRange(versionRangeElement));
  2540.       }
  2541.     }
  2542.     // return minVersion = 0 and maxVersion = * if not available
  2543.     if (!found)
  2544.       return [ this.getBlocklistVersionRange(null) ];
  2545.     return appVersions;
  2546.   },
  2547.  
  2548. /**
  2549.  * Retrieves a version range (e.g. minVersion and maxVersion) for a blocklist
  2550.  * versionRange element.
  2551.  * @param   versionRangeElement
  2552.  *          The versionRange blocklist element.
  2553.  * @returns A JS object with the following properties:
  2554.  *          "minVersion"  The minimum version in a version range (default = 0).
  2555.  *          "maxVersion"  The maximum version in a version range (default = *).
  2556.  */
  2557.   getBlocklistVersionRange: function(versionRangeElement) {
  2558.     var minVersion = "0";
  2559.     var maxVersion = "*";
  2560.     if (!versionRangeElement)
  2561.       return { minVersion: minVersion, maxVersion: maxVersion };
  2562.  
  2563.     if (versionRangeElement.hasAttribute("minVersion"))
  2564.       minVersion = versionRangeElement.getAttribute("minVersion");
  2565.     if (versionRangeElement.hasAttribute("maxVersion"))
  2566.       maxVersion = versionRangeElement.getAttribute("maxVersion");
  2567.  
  2568.     return { minVersion: minVersion, maxVersion: maxVersion };
  2569.   }
  2570. };
  2571.  
  2572. /**
  2573.  * Installs, manages and tracks compatibility for Extensions and Themes
  2574.  * @constructor
  2575.  */
  2576. function ExtensionManager() {
  2577.   gApp = Components.classes["@mozilla.org/xre/app-info;1"]
  2578.                    .getService(Components.interfaces.nsIXULAppInfo)
  2579.                    .QueryInterface(Components.interfaces.nsIXULRuntime);
  2580.   gOSTarget = gApp.OS;
  2581.   try {
  2582.     gXPCOMABI = gApp.XPCOMABI;
  2583.   } catch (ex) {
  2584.     // Provide a default for gXPCOMABI. It won't be compared to an
  2585.     // item's metadata (i.e. install.rdf can't specify e.g. WINNT_unknownABI
  2586.     // as targetPlatform), but it will be displayed in error messages and
  2587.     // transmitted to update URLs.
  2588.     gXPCOMABI = UNKNOWN_XPCOM_ABI;
  2589.   }
  2590.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  2591.                     .getService(Components.interfaces.nsIPrefBranch2);
  2592.  
  2593.   gOS = Components.classes["@mozilla.org/observer-service;1"]
  2594.                   .getService(Components.interfaces.nsIObserverService);
  2595.   gOS.addObserver(this, "xpcom-shutdown", false);
  2596.  
  2597.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  2598.                        .getService(Components.interfaces.nsIConsoleService);  
  2599.   
  2600.   gRDF = Components.classes["@mozilla.org/rdf/rdf-service;1"]
  2601.                    .getService(Components.interfaces.nsIRDFService);
  2602.   gInstallManifestRoot = gRDF.GetResource(RDFURI_INSTALL_MANIFEST_ROOT);
  2603.   
  2604.   // Register Global Install Location
  2605.   var appGlobalExtensions = getDirNoCreate(KEY_APPDIR, [DIR_EXTENSIONS]);
  2606.   var priority = nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL;
  2607.   var globalLocation = new DirectoryInstallLocation(KEY_APP_GLOBAL, 
  2608.                                                     appGlobalExtensions, true,
  2609.                                                     priority);
  2610.   InstallLocations.put(globalLocation);
  2611.  
  2612.   // Register App-Profile Install Location
  2613.   var appProfileExtensions = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS]);
  2614.   var priority = nsIInstallLocation.PRIORITY_APP_PROFILE;
  2615.   var profileLocation = new DirectoryInstallLocation(KEY_APP_PROFILE, 
  2616.                                                      appProfileExtensions, false,
  2617.                                                      priority);
  2618.   InstallLocations.put(profileLocation);
  2619.  
  2620. //@line 2706 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  2621.  
  2622.   // Register Additional Install Locations
  2623.   var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  2624.                                   .getService(Components.interfaces.nsICategoryManager);
  2625.   var locations = categoryManager.enumerateCategory(CATEGORY_INSTALL_LOCATIONS);
  2626.   while (locations.hasMoreElements()) {
  2627.     var entry = locations.getNext().QueryInterface(Components.interfaces.nsISupportsCString).data;
  2628.     var contractID = categoryManager.getCategoryEntry(CATEGORY_INSTALL_LOCATIONS, entry);
  2629.     var location = Components.classes[contractID].getService(nsIInstallLocation);
  2630.     InstallLocations.put(location);
  2631.   }
  2632. }
  2633.  
  2634. ExtensionManager.prototype = {
  2635.   /**
  2636.    * See nsIObserver.idl
  2637.    */
  2638.   observe: function(subject, topic, data) {
  2639.     switch (topic) {
  2640.     case "app-startup":
  2641.       gOS.addObserver(this, "profile-after-change", false);
  2642.       break;
  2643.     case "profile-after-change":
  2644.       this._profileSelected();
  2645.       break;
  2646.     case "quit-application-requested":
  2647.       this._confirmCancelDownloadsOnQuit(subject);
  2648.       break;
  2649.     case "offline-requested":
  2650.       this._confirmCancelDownloadsOnOffline(subject);
  2651.       break;
  2652.     case "xpcom-shutdown":
  2653.       this._shutdown();
  2654.       break;
  2655.     case "nsPref:changed":
  2656.       if (data == PREF_EM_LOGGING_ENABLED)
  2657.         this._loggingToggled();
  2658.       else if (data == PREF_EM_CHECK_COMPATIBILITY)
  2659.         this._checkCompatToggled();
  2660.       break;
  2661.     }
  2662.   },
  2663.   
  2664.   /**
  2665.    * Refresh the logging enabled global from preferences when the user changes
  2666.    * the preference settting.
  2667.    */
  2668.   _loggingToggled: function() {
  2669.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2670.   },
  2671.  
  2672.   /**
  2673.    * Enables or disables extensions that are incompatible depending upon the pref
  2674.    * setting for compatibility checking.
  2675.    */
  2676.   _checkCompatToggled: function() {
  2677.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2678.     var ds = this.datasource;
  2679.  
  2680.     // Enumerate all items
  2681.     var ctr = getContainer(ds, ds._itemRoot);
  2682.     var elements = ctr.GetElements();
  2683.     while (elements.hasMoreElements()) {
  2684.       var itemResource = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  2685.  
  2686.       // App disable or enable items as necessary
  2687.       // _appEnableItem and _appDisableItem will do nothing if the item is already
  2688.       // in the right state.
  2689.       id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  2690.       if (this._isUsableItem(id))
  2691.         this._appEnableItem(id);
  2692.       else
  2693.         this._appDisableItem(id);
  2694.     }
  2695.   },
  2696.  
  2697.   /**
  2698.    * Initialize the system after a profile has been selected.
  2699.    */  
  2700.   _profileSelected: function() {
  2701.     // Tell the Chrome Registry which Skin to select
  2702.     try {
  2703.       if (gPref.getBoolPref(PREF_DSS_SWITCHPENDING)) {
  2704.         var toSelect = gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  2705.         gPref.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, toSelect);
  2706.         gPref.clearUserPref(PREF_DSS_SWITCHPENDING);
  2707.         gPref.clearUserPref(PREF_DSS_SKIN_TO_SELECT);
  2708.       }
  2709.     }
  2710.     catch (e) {
  2711.     }
  2712.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2713.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2714.     gPref.addObserver("extensions.", this, false);
  2715.   },
  2716.  
  2717.   /**
  2718.    * Notify user that there are new addons updates
  2719.    */
  2720.   _showUpdatesWindow: function() {
  2721.     if (!getPref("getBoolPref", PREF_UPDATE_NOTIFYUSER, false))
  2722.       return;
  2723.  
  2724.     const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  2725.     const EMFEATURES = "chrome,centerscreen,extra-chrome,dialog,resizable,modal";
  2726.  
  2727.     var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2728.                        .getService(Components.interfaces.nsIWindowWatcher);
  2729.     var param = Components.classes["@mozilla.org/supports-array;1"]
  2730.                           .createInstance(Components.interfaces.nsISupportsArray);
  2731.     var arg = Components.classes["@mozilla.org/supports-string;1"]
  2732.                         .createInstance(Components.interfaces.nsISupportsString);
  2733.     arg.data = "updates-only";
  2734.     param.AppendElement(arg);
  2735.     ww.openWindow(null, EMURL, null, EMFEATURES, param);
  2736.   },
  2737.  
  2738.   /**
  2739.    * Clean up on application shutdown to avoid leaks.
  2740.    */
  2741.   _shutdown: function() {
  2742.     gOS.removeObserver(this, "xpcom-shutdown");
  2743.  
  2744.     // Release strongly held services.
  2745.     gOS = null;
  2746.     if (this._ds && gRDF) 
  2747.       gRDF.UnregisterDataSource(this._ds)
  2748.     gRDF = null;
  2749.     if (gPref)
  2750.       gPref.removeObserver("extensions.", this);
  2751.     gPref = null;
  2752.     gConsole = null;
  2753.     gVersionChecker = null;
  2754.     gInstallManifestRoot = null;
  2755.     gApp = null;
  2756.   },
  2757.   
  2758.   /**
  2759.    * Check for presence of critical Extension system files. If any is missing, 
  2760.    * delete the others and signal that the system needs to rebuild them all
  2761.    * from scratch.
  2762.    * @returns true if any critical file is missing and the system needs to
  2763.    *          be rebuilt, false otherwise.
  2764.    */
  2765.   _ensureDatasetIntegrity: function () {
  2766.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  2767.     var extensionsINI = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2768.     var extensionsCache = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2769.     
  2770.     var dsExists = extensionsDS.exists();
  2771.     var iniExists = extensionsINI.exists();
  2772.     var cacheExists = extensionsCache.exists();
  2773.  
  2774.     if (dsExists && iniExists && cacheExists)
  2775.       return false;
  2776.  
  2777.     // If any of the files are missing, remove the .ini file
  2778.     if (iniExists)
  2779.       extensionsINI.remove(false);
  2780.  
  2781.     // If the extensions datasource is missing remove the .cache file if it exists
  2782.     if (!dsExists && cacheExists)
  2783.       extensionsCache.remove(false);
  2784.  
  2785.     return true;
  2786.   },
  2787.   
  2788.   /**
  2789.    * See nsIExtensionManager.idl
  2790.    */
  2791.   start: function(commandLine) {
  2792.     var isDirty = false;
  2793.     var forceAutoReg = false;
  2794.     
  2795.     this._showUpdatesWindow();
  2796.     
  2797.     // Somehow the component list went away, and for that reason the new one
  2798.     // generated by this function is going to result in a different compreg.
  2799.     // We must force a restart.
  2800.     var componentList = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2801.     if (!componentList.exists())
  2802.       forceAutoReg = true;
  2803.     
  2804.     // Check for missing manifests - e.g. missing extensions.ini, missing
  2805.     // extensions.cache, extensions.rdf etc. If any of these files 
  2806.     // is missing then we are in some kind of weird or initial state and need
  2807.     // to force a regeneration.
  2808.     if (this._ensureDatasetIntegrity())
  2809.       isDirty = true;
  2810.  
  2811.     // Configure any items that are being installed, uninstalled or upgraded 
  2812.     // by being added, removed or modified by another process. We must do this
  2813.     // on every startup since there is no way we can tell if this has happened
  2814.     // or not!
  2815.     if (this._checkForFileChanges())
  2816.       isDirty = true;
  2817.  
  2818.     if (PendingOperations.size != 0)
  2819.       isDirty = true;
  2820.  
  2821.     // Extension Changes
  2822.     if (isDirty) {
  2823.       var needsRestart = this._finishOperations();
  2824.  
  2825.       if (forceAutoReg) {
  2826.         this._extensionListChanged = true;
  2827.         needsRestart = true;
  2828.       }
  2829.       return needsRestart;
  2830.     }
  2831.       
  2832.     this._startTimers();
  2833.  
  2834.     return false;
  2835.   },
  2836.   
  2837.   /**
  2838.    * Begins all background update check timers
  2839.    */
  2840.   _startTimers: function() {
  2841.     // Register a background update check timer
  2842.     var tm = 
  2843.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  2844.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  2845.     var interval = getPref("getIntPref", PREF_EM_UPDATE_INTERVAL, 86400); 
  2846.     tm.registerTimer("addon-background-update-timer", this, interval);
  2847.  
  2848.     interval = getPref("getIntPref", PREF_BLOCKLIST_INTERVAL, 86400); 
  2849.     tm.registerTimer("blocklist-background-update-timer", Blocklist, interval);
  2850.   },
  2851.   
  2852.   /**
  2853.    * Notified when a timer fires
  2854.    * @param   timer
  2855.    *          The timer that fired
  2856.    */
  2857.   notify: function(timer) {
  2858.     if (!getPref("getBoolPref", PREF_EM_UPDATE_ENABLED, true))
  2859.       return;
  2860.  
  2861.     var items = this.getItemList(nsIUpdateItem.TYPE_ADDON, { });
  2862.  
  2863.     var updater = new ExtensionItemUpdater(gApp.ID, gApp.version, this);
  2864.     updater._background = true;
  2865.     updater.checkForUpdates(items, items.length, false, null);
  2866.   },
  2867.   
  2868.   /**
  2869.    * See nsIExtensionManager.idl
  2870.    */
  2871.   handleCommandLineArgs: function(commandLine) {
  2872.     try {
  2873.       var globalExtension = commandLine.handleFlagWithParam("install-global-extension", false);
  2874.       if (globalExtension) {
  2875.         var file = commandLine.resolveFile(globalExtension);
  2876.         this._installGlobalItem(file);
  2877.       }
  2878.       var globalTheme = commandLine.handleFlagWithParam("install-global-theme", false);
  2879.       if (globalTheme) {
  2880.         file = commandLine.resolveFile(globalTheme);
  2881.         this._installGlobalItem(file);
  2882.       }
  2883.     }
  2884.     catch (e) { 
  2885.       LOG("ExtensionManager:handleCommandLineArgs - failure, catching exception - lineno: " +
  2886.           e.lineNumber + " - file: " + e.fileName + " - " + e);
  2887.     }
  2888.     commandLine.preventDefault = true;
  2889.   },
  2890.  
  2891.   /**
  2892.    * Installs an XPI/JAR file into the KEY_APP_GLOBAL install location.
  2893.    * @param   file
  2894.    *          The XPI/JAR file to extract
  2895.    */
  2896.   _installGlobalItem: function(file) {
  2897.     if (!file || !file.exists())
  2898.       throw new Error("Unable to find the file specified on the command line!");
  2899.     var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2900.     if (!installManifestFile.exists())
  2901.       throw new Error("The package is missing an install manifest!");
  2902.     var installManifest = getInstallManifest(installManifestFile);
  2903.     installManifestFile.remove(false);
  2904.     var installData = this._getInstallData(installManifest);
  2905.     var installer = new Installer(installManifest, installData.id,
  2906.                                   InstallLocations.get(KEY_APP_GLOBAL),
  2907.                                   installData.type);
  2908.     installer._installExtensionFiles(file);
  2909.     if (installData.type == nsIUpdateItem.TYPE_THEME)
  2910.       installer.upgradeThemeChrome();
  2911.     else
  2912.       installer.upgradeExtensionChrome();
  2913.   },
  2914.  
  2915.   /**
  2916.    * Check to see if a file is a XPI/JAR file that the user dropped into this
  2917.    * Install Location. (i.e. a XPI that is not a staged XPI from an install 
  2918.    * transaction that is currently in operation). 
  2919.    * @param   file
  2920.    *          The XPI/JAR file to configure
  2921.    * @param   location
  2922.    *          The Install Location where this file was found.
  2923.    * @returns A nsIUpdateItem representing the dropped XPI if this file was a 
  2924.    *          XPI/JAR that needs installation, null otherwise.
  2925.    */
  2926.   _getItemForDroppedFile: function(file, location) {
  2927.     if (fileIsItemPackage(file)) {
  2928.       // We know nothing about this item, it is not something we've
  2929.       // staged in preparation for finalization, so assume it's something
  2930.       // the user dropped in.
  2931.       LOG("A Item Package appeared at: " + file.path + " that we know " + 
  2932.           "nothing about, assuming it was dropped in by the user and " + 
  2933.           "configuring for installation now. Location Key: " + location.name);
  2934.  
  2935.       var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2936.       if (!installManifestFile.exists())
  2937.         return null;
  2938.       var installManifest = getInstallManifest(installManifestFile);
  2939.       installManifestFile.remove(false);
  2940.       var ds = this.datasource;
  2941.       var installData = this._getInstallData(installManifest);
  2942.       var targetAppInfo = ds.getTargetApplicationInfo(installData.id, installManifest);
  2943.       return makeItem(installData.id,
  2944.                       installData.version,
  2945.                       location.name,
  2946.                       targetAppInfo ? targetAppInfo.minVersion : "",
  2947.                       targetAppInfo ? targetAppInfo.maxVersion : "",
  2948.                       getManifestProperty(installManifest, "name"),
  2949.                       "", /* XPI Update URL */
  2950.                       "", /* XPI Update Hash */
  2951.                       getManifestProperty(installManifest, "iconURL"),
  2952.                       getManifestProperty(installManifest, "updateURL"),
  2953.                       installData.type);
  2954.     }
  2955.     return null;
  2956.   },
  2957.   
  2958.   /**
  2959.    * Check for changes to items that were made independently of the Extension 
  2960.    * Manager, e.g. items were added or removed from a Install Location or items
  2961.    * in an Install Location changed. 
  2962.    */
  2963.   _checkForFileChanges: function() {
  2964.     var em = this;
  2965.     /** 
  2966.      * Configure an item that was installed or upgraded by another process
  2967.      * so that |_finishOperations| can properly complete processing and 
  2968.      * registration. 
  2969.      * As this is the only point at which we can reliably know the Install
  2970.      * Location of this item, we use this as an opportunity to:
  2971.      * 1. Check that this item is compatible with this Firefox version.
  2972.      * 2. If it is, configure the item by using the supplied callback.
  2973.      *    We do not do any special handling in the case that the item is
  2974.      *    not compatible with this version other than to simply not register
  2975.      *    it and log that fact - there is no "phone home" check for updates. 
  2976.      *    It may or may not make sense to do this, but for now we'll just
  2977.      *    not register.
  2978.      * @param   id
  2979.      *          The GUID of the item to validate and configure.
  2980.      * @param   location
  2981.      *          The Install Location where this item is installed.
  2982.      * @param   callback
  2983.      *          The callback that configures the item for installation upon
  2984.      *          successful validation.
  2985.      */      
  2986.     function installItem(id, location, callback) {
  2987.       // As this is the only pint at which we reliably know the installation
  2988.       var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  2989.       if (installRDF.exists()) {
  2990.         LOG("Item Installed/Upgraded at Install Location: " + location.name + 
  2991.             " Item ID: " + id + ", attempting to register...");
  2992.         var installManifest = getInstallManifest(installRDF);
  2993.         var installData = em._getInstallData(installManifest);
  2994.         if (installData.error == INSTALLERROR_SUCCESS) {
  2995.           LOG("... success, item is compatible");
  2996.           callback(installManifest, installData.id, location, installData.type);
  2997.         }
  2998.         else if (installData.error == INSTALLERROR_INCOMPATIBLE_VERSION) {
  2999.           LOG("... success, item installed but is not compatible");
  3000.           callback(installManifest, installData.id, location, installData.type);
  3001.           em._appDisableItem(id);
  3002.         }
  3003.         else if (installData.error == INSTALLERROR_BLOCKLISTED) {
  3004.           LOG("... success, item installed but is blocklisted");
  3005.           callback(installManifest, installData.id, location, installData.type);
  3006.           em._appDisableItem(id);
  3007.         }
  3008.         else {
  3009.           /**
  3010.            * Turns an error code into a message for logging
  3011.            * @param   error
  3012.            *          an Install Error code
  3013.            * @returns A string message to be logged.
  3014.            */
  3015.           function translateErrorMessage(error) {
  3016.             switch (error) {
  3017.             case INSTALLERROR_INVALID_GUID:
  3018.               return "Invalid GUID";
  3019.             case INSTALLERROR_INVALID_VERSION:
  3020.               return "Invalid Version";
  3021.             case INSTALLERROR_INCOMPATIBLE_VERSION:
  3022.               return "Incompatible Version";
  3023.             case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  3024.               return "Incompatible Platform";
  3025.             }
  3026.           }
  3027.           LOG("... failure, item is not compatible, error: " + 
  3028.               translateErrorMessage(installData.error));
  3029.  
  3030.           // Add the item to the Startup Cache anyway, so we don't re-detect it
  3031.           // every time the app starts.
  3032.           StartupCache.put(location, id, OP_NONE, true);
  3033.         }
  3034.       }      
  3035.     }
  3036.   
  3037.     /**
  3038.      * Determines if an item can be used based on whether or not the install
  3039.      * location of the "item" has an equal or higher priority than the install
  3040.      * location where another version may live.
  3041.      * @param   id
  3042.      *          The GUID of the item being installed.
  3043.      * @param   location
  3044.      *          The location where an item is to be installed.
  3045.      * @returns true if the item can be installed at that location, false 
  3046.      *          otherwise.
  3047.      */
  3048.     function canUse(id, location) {
  3049.       for (var locationKey in StartupCache.entries) {
  3050.         if (locationKey != location.name && 
  3051.             id in StartupCache.entries[locationKey]) {
  3052.           if (StartupCache.entries[locationKey][id]) {
  3053.             var oldInstallLocation = InstallLocations.get(locationKey);
  3054.             if (oldInstallLocation.priority <= location.priority)
  3055.               return false;
  3056.           }
  3057.         }
  3058.       }
  3059.       return true;
  3060.     }
  3061.     
  3062.     /** 
  3063.       * Gets a Dialog Param Block loaded with a set of strings to initialize the
  3064.       * XPInstall Confirmation Dialog.
  3065.       * @param   strings
  3066.       *          An array of strings
  3067.       * @returns A nsIDialogParamBlock loaded with the strings and dialog state.
  3068.       */
  3069.     function getParamBlock(strings) {
  3070.       var dpb = Components.classes["@mozilla.org/embedcomp/dialogparam;1"]
  3071.                           .createInstance(Components.interfaces.nsIDialogParamBlock);
  3072.       // OK and Cancel Buttons
  3073.       dpb.SetInt(0, 2);
  3074.       // Number of Strings
  3075.       dpb.SetInt(1, strings.length);
  3076.       dpb.SetNumberStrings(strings.length);
  3077.       // Add Strings
  3078.       for (var i = 0; i < strings.length; ++i)
  3079.         dpb.SetString(i, strings[i]);
  3080.       
  3081.       var supportsString = Components.classes["@mozilla.org/supports-string;1"]
  3082.                                      .createInstance(Components.interfaces.nsISupportsString);
  3083.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  3084.       supportsString.data = bundle.GetStringFromName("droppedInWarning");
  3085.       var objs = Components.classes["@mozilla.org/array;1"]
  3086.                            .createInstance(Components.interfaces.nsIMutableArray);
  3087.       objs.appendElement(supportsString, false);
  3088.       dpb.objects = objs;
  3089.       return dpb;        
  3090.     }
  3091.  
  3092.     /**
  3093.      * Installs a set of files which were dropped into an install location by 
  3094.      * the user, only after user confirmation.
  3095.      * @param   droppedInFiles
  3096.      *          An array of JS objects with the following properties:
  3097.      *          "file"      The nsILocalFile where the XPI lives
  3098.      *          "location"  The Install Location where the XPI was found. 
  3099.      * @param   xpinstallStrings
  3100.      *          An array of strings used to initialize the XPInstall Confirm 
  3101.      *          dialog.
  3102.      */ 
  3103.     function installDroppedInFiles(droppedInFiles, xpinstallStrings) {
  3104.       if (droppedInFiles.length == 0) 
  3105.         return;
  3106.         
  3107.       var dpb = getParamBlock(xpinstallStrings);
  3108.       var ifptr = Components.classes["@mozilla.org/supports-interface-pointer;1"]
  3109.                             .createInstance(Components.interfaces.nsISupportsInterfacePointer);
  3110.       ifptr.data = dpb;
  3111.       ifptr.dataIID = Components.interfaces.nsIDialogParamBlock;
  3112.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  3113.                           .getService(Components.interfaces.nsIWindowWatcher);
  3114.       ww.openWindow(null, URI_XPINSTALL_CONFIRM_DIALOG, 
  3115.                     "", "chrome,centerscreen,modal,dialog,titlebar", ifptr);
  3116.       if (!dpb.GetInt(0)) {
  3117.         // User said OK - install items
  3118.         for (var i = 0; i < droppedInFiles.length; ++i) {
  3119.           em.installItemFromFile(droppedInFiles[i].file, 
  3120.                                  droppedInFiles[i].location.name);
  3121.           // We are responsible for cleaning up this file
  3122.           droppedInFiles[i].file.remove(false);
  3123.         }
  3124.       }
  3125.       else {
  3126.         for (i = 0; i < droppedInFiles.length; ++i) {
  3127.           // We are responsible for cleaning up this file
  3128.           droppedInFiles[i].file.remove(false);
  3129.         }
  3130.       }
  3131.     }
  3132.     
  3133.     var isDirty = false;
  3134.     var ignoreMTimeChanges = getPref("getBoolPref", PREF_EM_IGNOREMTIMECHANGES,
  3135.                                      false);
  3136.     StartupCache.read();
  3137.     
  3138.     // Array of objects with 'location' and 'id' properties to maybe install.
  3139.     var newItems = [];
  3140.  
  3141.     var droppedInFiles = [];
  3142.     var xpinstallStrings = [];
  3143.     
  3144.     // Enumerate over the install locations from low to high priority.  The
  3145.     // enumeration returned is pre-sorted.
  3146.     var installLocations = this.installLocations;
  3147.     while (installLocations.hasMoreElements()) {
  3148.       var location = installLocations.getNext().QueryInterface(nsIInstallLocation);
  3149.  
  3150.       // Hash the set of items actually held by the Install Location.  
  3151.       var actualItems = { };
  3152.       var entries = location.itemLocations;
  3153.       while (true) {
  3154.         var entry = entries.nextFile;
  3155.         if (!entry)
  3156.           break;
  3157.  
  3158.         // Is this location a valid item? It must be a directory, and contain
  3159.         // an install.rdf manifest:
  3160.         if (entry.isDirectory()) {
  3161.           var installRDF = entry.clone();
  3162.           installRDF.append(FILE_INSTALL_MANIFEST);
  3163.  
  3164.           var id = location.getIDForLocation(entry);
  3165.           if (!id || (!installRDF.exists() && 
  3166.                       !location.itemIsManagedIndependently(id)))
  3167.             continue;
  3168.  
  3169.           actualItems[id] = entry;
  3170.         }
  3171.         else {
  3172.           // Check to see if this file is a XPI/JAR dropped into this dir
  3173.           // by the user, installing it if necessary. We do this here rather
  3174.           // than separately in |_finishOperations| because I don't want to
  3175.           // walk these lists multiple times on every startup.
  3176.           var item = this._getItemForDroppedFile(entry, location);
  3177.           if (item) {
  3178.             droppedInFiles.push({ file: entry, location: location });
  3179.  
  3180.             var zipReader = Components.classes["@mozilla.org/libjar/zip-reader;1"]
  3181.                                       .createInstance(Components.interfaces.nsIZipReader);
  3182.             zipReader.init(entry);
  3183.             var prettyName = "";
  3184.             try {
  3185.               var jar = zipReader.QueryInterface(Components.interfaces.nsIJAR);
  3186.               var principal = { };
  3187.               var certPrincipal = zipReader.getCertificatePrincipal(null, principal);
  3188.               // XXXbz This string could be empty.  This needs better
  3189.               // UI to present principal.value.certificate's subject.
  3190.               prettyName = principal.value.prettyName;
  3191.             }
  3192.             catch (e) { }
  3193.             xpinstallStrings = xpinstallStrings.concat([item.name, 
  3194.                                                         getURLSpecFromFile(entry),
  3195.                                                         item.iconURL, 
  3196.                                                         prettyName]);
  3197.             isDirty = true;
  3198.           }
  3199.         }
  3200.       }
  3201.       
  3202.       if (location.name in StartupCache.entries) {
  3203.         // Look for items that have been uninstalled by removing their directory.
  3204.         for (var id in StartupCache.entries[location.name]) {
  3205.           if (!StartupCache.entries[location.name] ||
  3206.               !StartupCache.entries[location.name][id]) 
  3207.             continue;
  3208.  
  3209.           // Force _finishOperations to run if we have enabled or disabled items.
  3210.           // XXXdarin this should be unnecessary now that we check
  3211.           // PendingOperations.size in start()
  3212.           if (StartupCache.entries[location.name][id].op == OP_NEEDS_ENABLE ||
  3213.               StartupCache.entries[location.name][id].op == OP_NEEDS_DISABLE)
  3214.             isDirty = true;
  3215.           
  3216.           if (!(id in actualItems) && 
  3217.               StartupCache.entries[location.name][id].op != OP_NEEDS_UNINSTALL &&
  3218.               StartupCache.entries[location.name][id].op != OP_NEEDS_INSTALL &&
  3219.               StartupCache.entries[location.name][id].op != OP_NEEDS_UPGRADE) {
  3220.             // We have an entry for this id in the Extensions database, for this 
  3221.             // install location, but it no longer exists in the Install Location. 
  3222.             // We can infer from this that the item has been removed, so uninstall
  3223.             // it properly. 
  3224.             if (canUse(id, location)) {
  3225.               LOG("Item Uninstalled via file removal from: " + StartupCache.entries[location.name][id].descriptor + 
  3226.                   " Item ID: " + id + " Location Key: " + location.name + ", uninstalling item.");
  3227.               
  3228.               // Load the Extensions Datasource and force this item into the visible
  3229.               // items list if it is not already. This allows us to handle the case 
  3230.               // where there is an entry for an item in the Startup Cache but not
  3231.               // in the extensions.rdf file - in that case the item will not be in
  3232.               // the visible list and calls to |getInstallLocation| will mysteriously
  3233.               // fail.
  3234.               this.datasource.updateVisibleList(id, location.name, false);
  3235.               this.uninstallItem(id);
  3236.               isDirty = true;
  3237.             }
  3238.           }
  3239.           else if (!ignoreMTimeChanges) {
  3240.             // Look for items whose mtime has changed, and as such we can assume 
  3241.             // they have been "upgraded".
  3242.             var lf = { path: StartupCache.entries[location.name][id].descriptor };
  3243.             try {
  3244.                lf = getFileFromDescriptor(StartupCache.entries[location.name][id].descriptor, location);
  3245.             }
  3246.             catch (e) { }
  3247.  
  3248.             if (lf.exists && lf.exists()) {
  3249.               var actualMTime = Math.floor(lf.lastModifiedTime / 1000);
  3250.               if (actualMTime != StartupCache.entries[location.name][id].mtime) {
  3251.                 LOG("Item Location path changed: " + lf.path + " Item ID: " + 
  3252.                     id + " Location Key: " + location.name + ", attempting to upgrade item...");
  3253.                 if (canUse(id, location)) {
  3254.                   installItem(id, location, 
  3255.                               function(installManifest, id, location, type) {
  3256.                                 em._upgradeItem(installManifest, id, location, 
  3257.                                                 type);
  3258.                               });
  3259.                   isDirty = true;
  3260.                 }
  3261.               }
  3262.             }
  3263.             else {
  3264.               isDirty = true;
  3265.               LOG("Install Location returned a missing or malformed item path! " + 
  3266.                   "Item Path: " + lf.path + ", Location Key: " + location.name + 
  3267.                   " Item ID: " + id);
  3268.               if (canUse(id, location)) {
  3269.                 // Load the Extensions Datasource and force this item into the visible
  3270.                 // items list if it is not already. This allows us to handle the case 
  3271.                 // where there is an entry for an item in the Startup Cache but not
  3272.                 // in the extensions.rdf file - in that case the item will not be in
  3273.                 // the visible list and calls to |getInstallLocation| will mysteriously
  3274.                 // fail.
  3275.                 this.datasource.updateVisibleList(id, location.name, false);
  3276.                 this.uninstallItem(id);
  3277.               }
  3278.             }
  3279.           }
  3280.         }
  3281.       }
  3282.  
  3283.       // Look for items that have been installed by appearing in the location.
  3284.       for (var id in actualItems) {
  3285.         if (!(location.name in StartupCache.entries) || 
  3286.             !(id in StartupCache.entries[location.name]) ||
  3287.             !StartupCache.entries[location.name][id]) {
  3288.           // Remember that we've seen this item
  3289.           StartupCache.put(location, id, OP_NONE, true);
  3290.           // Push it on the stack of items to maybe install later
  3291.           newItems.push({location: location, id: id});
  3292.         }
  3293.       }
  3294.     }
  3295.  
  3296.     // Process any newly discovered items.  We do this here instead of in the
  3297.     // previous loop so that we can be sure that we have a fully populated
  3298.     // StartupCache.
  3299.     for (var i = 0; i < newItems.length; ++i) {
  3300.       var id = newItems[i].id;
  3301.       var location = newItems[i].location;
  3302.       if (canUse(id, location)) {
  3303.         LOG("Item Installed via directory addition to Install Location: " + 
  3304.             location.name + " Item ID: " + id + ", attempting to register...");
  3305.         installItem(id, location, 
  3306.                     function(installManifest, id, location, type) { 
  3307.                       em._configureForthcomingItem(installManifest, id, location, 
  3308.                                                    type);
  3309.                     });
  3310.         // Disable add-ons on install when the InstallDisabled file exists.
  3311.         // This is so Talkback will be disabled on a subset of installs.
  3312.         var installDisabled = location.getItemFile(id, "InstallDisabled");
  3313.         if (installDisabled.exists())
  3314.           em.disableItem(id);
  3315.         isDirty = true;
  3316.       }
  3317.     }
  3318.  
  3319.     // Ask the user if they want to install the dropped items, for security
  3320.     // purposes.
  3321.     installDroppedInFiles(droppedInFiles, xpinstallStrings);
  3322.     
  3323.     return isDirty;
  3324.   },
  3325.   
  3326.   /**
  3327.    * Upgrades contents.rdf files to chrome.manifest files for any existing
  3328.    * Extensions and Themes.
  3329.    * @returns true if actions were performed that require a restart, false 
  3330.    *          otherwise.
  3331.    */
  3332.   _upgradeChrome: function() {
  3333.     if (inSafeMode())
  3334.       return false;
  3335.  
  3336.     var checkForNewChrome = false;
  3337.     var ds = this.datasource;
  3338.     // If we have extensions that were installed before the new flat chrome
  3339.     // manifests, and are still valid, we need to manually create the flat
  3340.     // manifest files.
  3341.     var extensions = this._getActiveItems(nsIUpdateItem.TYPE_EXTENSION +
  3342.                                           nsIUpdateItem.TYPE_LOCALE +
  3343.                                           nsIUpdateItem.TYPE_PLUGIN);
  3344.     for (var i = 0; i < extensions.length; ++i) {
  3345.       var e = extensions[i];
  3346.       var itemLocation = e.location.getItemLocation(e.id);
  3347.       var manifest = itemLocation.clone();
  3348.       manifest.append(FILE_CHROME_MANIFEST);
  3349.       if (!manifest.exists()) {
  3350.         var installRDF = itemLocation.clone();
  3351.         installRDF.append(FILE_INSTALL_MANIFEST);
  3352.         var installLocation = this.getInstallLocation(e.id);
  3353.         if (installLocation && installRDF.exists()) {
  3354.           var itemLocation = installLocation.getItemLocation(e.id);
  3355.           if (itemLocation.exists() && itemLocation.isDirectory()) {
  3356.             var installer = new Installer(ds, e.id, installLocation, 
  3357.                                           nsIUpdateItem.TYPE_EXTENSION);
  3358.             installer.upgradeExtensionChrome();
  3359.           }
  3360.         }
  3361.         else {
  3362.           ds.removeItemMetadata(e.id);
  3363.           ds.removeItemFromContainer(e.id);
  3364.         }
  3365.  
  3366.         checkForNewChrome = true;
  3367.       }
  3368.     }
  3369.  
  3370.     var themes = this._getActiveItems(nsIUpdateItem.TYPE_THEME);
  3371.     // If we have themes that were installed before the new flat chrome
  3372.     // manifests, and are still valid, we need to manually create the flat
  3373.     // manifest files.
  3374.     for (i = 0; i < themes.length; ++i) {
  3375.       var item = themes[i];
  3376.       var itemLocation = item.location.getItemLocation(item.id);
  3377.       var manifest = itemLocation.clone();
  3378.       manifest.append(FILE_CHROME_MANIFEST);
  3379.       if (manifest.exists() ||
  3380.           item.id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  3381.         continue;
  3382.  
  3383.       var entries;
  3384.       try {
  3385.         var manifestURI = getURIFromFile(manifest);
  3386.         var chromeDir = itemLocation.clone();
  3387.         chromeDir.append(DIR_CHROME);
  3388.         
  3389.         if (!chromeDir.exists() || !chromeDir.isDirectory()) {
  3390.           ds.removeItemMetadata(item.id);
  3391.           ds.removeItemFromContainer(item.id);
  3392.           continue;
  3393.         }
  3394.  
  3395.         // We're relying on the fact that there is only one JAR file
  3396.         // in the "chrome" directory. This is a hack, but it works.
  3397.         entries = chromeDir.directoryEntries.QueryInterface(nsIDirectoryEnumerator);
  3398.         var jarFile = entries.nextFile;
  3399.         if (jarFile) {
  3400.           var jarFileURI = getURIFromFile(jarFile);
  3401.           var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  3402.  
  3403.           // Use the Chrome Registry API to install the theme there
  3404.           var cr = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
  3405.                             .getService(Components.interfaces.nsIToolkitChromeRegistry);
  3406.           cr.processContentsManifest(contentsURI, manifestURI, contentsURI, false, true);
  3407.         }
  3408.         entries.close();
  3409.       }
  3410.       catch (e) {
  3411.         LOG("_upgradeChrome: failed to upgrade contents manifest for " + 
  3412.             "theme: " + item.id + ", exception: " + e + "... The theme will be " + 
  3413.             "disabled.");
  3414.         this._appDisableItem(item.id);
  3415.       }
  3416.       finally {
  3417.         try {
  3418.           entries.close();
  3419.         }
  3420.         catch (e) {
  3421.         }
  3422.       }
  3423.       checkForNewChrome = true;
  3424.     }
  3425.     return checkForNewChrome;  
  3426.   },
  3427.   
  3428.   _checkForUncoveredItem: function(id) {
  3429.     var ds = this.datasource;
  3430.     var oldLocation = this.getInstallLocation(id);
  3431.     var newLocations = [];
  3432.     for (var locationKey in StartupCache.entries) {
  3433.       var location = InstallLocations.get(locationKey);
  3434.       if (id in StartupCache.entries[locationKey] && 
  3435.           location.priority > oldLocation.priority)
  3436.         newLocations.push(location);
  3437.     }
  3438.     newLocations.sort(function(a, b) { return b.priority - a.priority; });
  3439.     if (newLocations.length > 0) {
  3440.       for (var i = 0; i < newLocations.length; ++i) {
  3441.         // Check to see that the item at the location exists
  3442.         var installRDF = newLocations[i].getItemFile(id, FILE_INSTALL_MANIFEST);
  3443.         if (installRDF.exists()) {
  3444.           // Update the visible item cache so that |_finalizeUpgrade| is properly 
  3445.           // called from |_finishOperations|
  3446.           var name = newLocations[i].name;
  3447.           ds.updateVisibleList(id, name, true);
  3448.           PendingOperations.addItem(OP_NEEDS_UPGRADE, 
  3449.                                     { locationKey: name, id: id });
  3450.           PendingOperations.addItem(OP_NEEDS_INSTALL, 
  3451.                                     { locationKey: name, id: id });
  3452.           break;
  3453.         }
  3454.         else {
  3455.           // If no item exists at the location specified, remove this item
  3456.           // from the visible items list and check again. 
  3457.           StartupCache.clearEntry(newLocations[i], id);
  3458.           ds.updateVisibleList(id, null, true);
  3459.         }
  3460.       }
  3461.     }
  3462.     else
  3463.       ds.updateVisibleList(id, null, true);
  3464.   },
  3465.   
  3466.   /**
  3467.    * Finish up pending operations - perform upgrades, installs, enables/disables, 
  3468.    * uninstalls etc.
  3469.    * @returns true if actions were performed that require a restart, false 
  3470.    *          otherwise.
  3471.    */
  3472.   _finishOperations: function() {
  3473.     try {
  3474.       // Stuff has changed, load the Extensions datasource in all its RDFey
  3475.       // glory. 
  3476.       var ds = this.datasource;
  3477.       var updatedTargetAppInfos = [];
  3478.  
  3479.       var needsRestart = false;      
  3480.       do {
  3481.         // Enable and disable during startup so items that are changed in the
  3482.         // ui can be reset to a no-op.
  3483.         // Look for extensions that need to be enabled.
  3484.         var items = PendingOperations.getOperations(OP_NEEDS_ENABLE);
  3485.         for (var i = items.length - 1; i >= 0; --i) {
  3486.           var id = items[i].id;
  3487.           var installLocation = this.getInstallLocation(id);
  3488.           StartupCache.put(installLocation, id, OP_NONE, true);
  3489.           PendingOperations.clearItem(OP_NEEDS_ENABLE, id);
  3490.           needsRestart = true;
  3491.         }
  3492.         PendingOperations.clearItems(OP_NEEDS_ENABLE);
  3493.  
  3494.         // Look for extensions that need to be disabled.
  3495.         items = PendingOperations.getOperations(OP_NEEDS_DISABLE);
  3496.         for (i = items.length - 1; i >= 0; --i) {
  3497.           id = items[i].id;
  3498.           installLocation = this.getInstallLocation(id);
  3499.           StartupCache.put(installLocation, id, OP_NONE, true);
  3500.           PendingOperations.clearItem(OP_NEEDS_DISABLE, id);
  3501.           needsRestart = true;
  3502.         }
  3503.         PendingOperations.clearItems(OP_NEEDS_DISABLE);
  3504.  
  3505.         // Look for extensions that need to be upgraded. The process here is to
  3506.         // uninstall the old version of the extension first, then install the
  3507.         // new version in its place. 
  3508.         items = PendingOperations.getOperations(OP_NEEDS_UPGRADE);
  3509.         for (i = items.length - 1; i >= 0; --i) {
  3510.           id = items[i].id;
  3511.           var oldLocation = this.getInstallLocation(id);
  3512.           var newLocation = InstallLocations.get(items[i].locationKey);
  3513.           if (newLocation.priority <= oldLocation.priority) {
  3514.             // check if there is updated app compatibility info
  3515.             var newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3516.             if (newTargetAppInfo)
  3517.               updatedTargetAppInfos.push(newTargetAppInfo);
  3518.             this._finalizeUpgrade(id);
  3519.           }
  3520.         }
  3521.         PendingOperations.clearItems(OP_NEEDS_UPGRADE);
  3522.  
  3523.         // Install items
  3524.         items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3525.         for (i = items.length - 1; i >= 0; --i) {
  3526.           needsRestart = true;
  3527.           id = items[i].id;
  3528.           // check if there is updated app compatibility info
  3529.           newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3530.           if (newTargetAppInfo)
  3531.             updatedTargetAppInfos.push(newTargetAppInfo);
  3532.           this._finalizeInstall(id, null);
  3533.         }
  3534.         PendingOperations.clearItems(OP_NEEDS_INSTALL);
  3535.  
  3536.         // Look for extensions that need to be removed. This MUST be done after
  3537.         // the install operations since extensions to be installed may have to be
  3538.         // uninstalled if there are errors during the installation process!
  3539.         items = PendingOperations.getOperations(OP_NEEDS_UNINSTALL);
  3540.         for (i = items.length - 1; i >= 0; --i) {
  3541.           id = items[i].id;
  3542.           this._finalizeUninstall(id);
  3543.           this._checkForUncoveredItem(id);
  3544.           needsRestart = true;
  3545.         }
  3546.         PendingOperations.clearItems(OP_NEEDS_UNINSTALL);
  3547.  
  3548.         // When there have been operations and all operations have completed.
  3549.         if (PendingOperations.size == 0) {
  3550.           // If there is updated app compatibility info update the data sources.
  3551.           for (i = 0; i < updatedTargetAppInfos.length; ++i)
  3552.             ds.updateTargetAppInfo(updatedTargetAppInfos[i].id,
  3553.                                    updatedTargetAppInfos[i].minVersion,
  3554.                                    updatedTargetAppInfos[i].maxVersion);
  3555.  
  3556.           // Enumerate all items
  3557.           var ctr = getContainer(ds, ds._itemRoot);
  3558.           var elements = ctr.GetElements();
  3559.           while (elements.hasMoreElements()) {
  3560.             var itemResource = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  3561.  
  3562.             // Ensure appDisabled is in the correct state.
  3563.             id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3564.             if (this._isUsableItem(id))
  3565.               ds.setItemProperty(id, EM_R("appDisabled"), null);
  3566.             else
  3567.               ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  3568.  
  3569.             // userDisabled is set based on its value being OP_NEEDS_ENABLE or
  3570.             // OP_NEEDS_DISABLE. This allows us to have an item to be enabled
  3571.             // by the app and disabled by the user during a single restart.
  3572.             var value = stringData(ds.GetTarget(itemResource, EM_R("userDisabled"), true));
  3573.             if (value == OP_NEEDS_ENABLE)
  3574.               ds.setItemProperty(id, EM_R("userDisabled"), null);
  3575.             else if (value == OP_NEEDS_DISABLE)
  3576.               ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  3577.           }
  3578.         }
  3579.       }
  3580.       while (PendingOperations.size > 0);
  3581.       
  3582.       // Upgrade contents.rdf files to the new chrome.manifest format for
  3583.       // existing Extensions and Themes
  3584.       if (this._upgradeChrome()) {
  3585.         var cr = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
  3586.                            .getService(Components.interfaces.nsIChromeRegistry);
  3587.         cr.checkForNewChrome();
  3588.       }
  3589.  
  3590.       // If no additional restart is required, it implies that there are
  3591.       // no new components that need registering so we can inform the app
  3592.       // not to do any extra startup checking next time round. 
  3593.       this._updateManifests(needsRestart);
  3594.  
  3595.     }
  3596.     catch (e) {
  3597.       LOG("ExtensionManager:_finishOperations - failure, catching exception - lineno: " +
  3598.           e.lineNumber + " - file: " + e.fileName + " - " + e);
  3599.     }
  3600.     return needsRestart;
  3601.   },
  3602.   
  3603.   /**
  3604.    * Checks to see if there are items that are incompatible with this version
  3605.    * of the application, disables them to prevent incompatibility problems and 
  3606.    * invokes the Update Wizard to look for newer versions.
  3607.    * @returns true if there were incompatible items installed and disabled, and
  3608.    *          the application must now be restarted to reinitialize XPCOM,
  3609.    *          false otherwise.
  3610.    */
  3611.   checkForMismatches: function() {
  3612.     // Check to see if the version of the application that is being started
  3613.     // now is the same one that was started last time. 
  3614.     var currAppVersion = gApp.version;
  3615.     var lastAppVersion = getPref("getCharPref", PREF_EM_LAST_APP_VERSION, "");
  3616.     if (currAppVersion == lastAppVersion)
  3617.       return false;
  3618.     // With a new profile lastAppVersion doesn't exist yet.
  3619.     if (!lastAppVersion) {
  3620.       gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3621.       return false;
  3622.     }
  3623.  
  3624.     // Version mismatch, we have to load the extensions datasource and do
  3625.     // version checking. Time hit here doesn't matter since this doesn't happen
  3626.     // all that often.
  3627.     this._upgradeFromV10();
  3628.     
  3629.     // Make the extensions datasource consistent if it isn't already.
  3630.     var isDirty = false;
  3631.     if (this._ensureDatasetIntegrity())
  3632.       isDirty = true;
  3633.  
  3634.     if (this._checkForFileChanges())
  3635.       isDirty = true;
  3636.  
  3637.     if (PendingOperations.size != 0)
  3638.       isDirty = true;
  3639.  
  3640.     if (isDirty)
  3641.       this._finishOperations();
  3642.  
  3643.     var ds = this.datasource;
  3644.     // During app upgrade cleanup invalid entries in the extensions datasource.
  3645.     ds.beginUpdateBatch();
  3646.     var allResources = ds.GetAllResources();
  3647.     while (allResources.hasMoreElements()) {
  3648.       var res = allResources.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  3649.       if (ds.GetTarget(res, EM_R("downloadURL"), true) ||
  3650.           (!ds.GetTarget(res, EM_R("installLocation"), true) &&
  3651.           stringData(ds.GetTarget(res, EM_R("appDisabled"), true)) == "true"))
  3652.         ds.removeDownload(res.Value);
  3653.     }
  3654.     ds.endUpdateBatch();
  3655.  
  3656.     var allAppManaged = true;
  3657.     var ctr = getContainer(ds, ds._itemRoot);
  3658.     var elements = ctr.GetElements();
  3659.     while (elements.hasMoreElements()) {
  3660.       var itemResource = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  3661.       var id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3662.       if (ds.getItemProperty(id, "appManaged") == "true") {
  3663.         // Force an update of the metadata for appManaged extensions since the
  3664.         // last modified time is not updated for directories on FAT / FAT32
  3665.         // filesystems when software update applies a new version of the app.
  3666.         var location = this.getInstallLocation(id);
  3667.         if (location.name == KEY_APP_GLOBAL) {
  3668.           var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  3669.           if (installRDF.exists()) {
  3670.             var metadataDS = getInstallManifest(installRDF);
  3671.             ds.addItemMetadata(id, metadataDS, location);
  3672.             ds.updateProperty(id, "compatible");
  3673.           }
  3674.         }
  3675.       }
  3676.       else if (allAppManaged)
  3677.         allAppManaged = false;
  3678.       // appDisabled is determined by an item being compatible,
  3679.       // satisfying its dependencies, and not being blocklisted
  3680.       if (this._isUsableItem(id)) {
  3681.         if (ds.getItemProperty(id, "appDisabled"))
  3682.           ds.setItemProperty(id, EM_R("appDisabled"), null);
  3683.       }
  3684.       else if (!ds.getItemProperty(id, "appDisabled"))
  3685.         ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  3686.  
  3687.       ds.setItemProperty(id, EM_R("availableUpdateURL"), null);
  3688.       ds.setItemProperty(id, EM_R("availableUpdateVersion"), null);
  3689.     }
  3690.     // Update the manifests to reflect the items that were disabled / enabled.
  3691.     this._updateManifests(true);
  3692.  
  3693.     // Always check for compatibility updates when upgrading if we have add-ons
  3694.     // that aren't managed by the application.
  3695.     if (!allAppManaged)
  3696.       this._showMismatchWindow();
  3697.     
  3698.     // Finish any pending upgrades from the compatibility update to avoid an
  3699.     // additional restart.
  3700.     if (PendingOperations.size != 0)
  3701.       this._finishOperations();
  3702.  
  3703.     // Update the last app version so we don't do this again with this version.
  3704.     gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3705.  
  3706.     // Prevent extension update dialog from showing
  3707.     gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, false);
  3708.     return true;
  3709.   },
  3710.  
  3711.   /**
  3712.    * Shows the "Compatibility Updates" UI
  3713.    */
  3714.   _showMismatchWindow: function(items) {
  3715.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  3716.                        .getService(Components.interfaces.nsIWindowMediator);
  3717.     var wizard = wm.getMostRecentWindow("Update:Wizard");
  3718.     if (wizard)
  3719.       wizard.focus();
  3720.     else {
  3721.       var features = "chrome,centerscreen,dialog,titlebar,modal";
  3722.       // This *must* be modal so as not to break startup! This code is invoked before
  3723.       // the main event loop is initiated (via checkForMismatches).
  3724.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  3725.                          .getService(Components.interfaces.nsIWindowWatcher);
  3726.       ww.openWindow(null, URI_EXTENSION_UPDATE_DIALOG, "", features, null);
  3727.     }
  3728.   },
  3729.   
  3730.   /*
  3731.    * Catch all for facilitating a version 1.0 profile upgrade.
  3732.    * 1) removes the abandoned default theme directory from the profile.
  3733.    * 2) prepares themes installed with version 1.0 for installation.
  3734.    * 3) initiates an install to populate the new extensions datasource.
  3735.    * 4) migrates the disabled attribute from the old datasource.
  3736.    * 5) migrates the app compatibility info from the old datasource.
  3737.    */
  3738.   _upgradeFromV10: function() {
  3739.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  3740.     var dsExists = extensionsDS.exists();
  3741.     // Toolkiit 1.7 profiles (Firefox 1.0, Thunderbird 1.0, etc.) have a default
  3742.     // theme directory in the profile's extensions directory that will be
  3743.     // disabled due to having a maxVersion that is incompatible with the
  3744.     // toolkit 1.8 release of the app.
  3745.     var profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3746.                                              stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)]);
  3747.     if (profileDefaultTheme && profileDefaultTheme.exists()) {
  3748.       removeDirRecursive(profileDefaultTheme);
  3749.       // Sunbird 0.3a1 didn't move the default theme into the app's extensions
  3750.       // directory and we can't install it while uninstalling the one in the
  3751.       // profile directory. If we have a toolkit 1.8 extensions datasource and
  3752.       // a profile default theme deleting the toolkit 1.8 extensions datasource
  3753.       // will fix this problem when the datasource is re-created.
  3754.       if (dsExists)
  3755.         extensionsDS.remove(false);
  3756.     }
  3757.  
  3758.     // return early if the toolkit 1.7 extensions datasource file doesn't exist.
  3759.     var oldExtensionsFile = getFile(KEY_PROFILEDIR, [DIR_EXTENSIONS, "Extensions.rdf"]);
  3760.     if (!oldExtensionsFile.exists())
  3761.       return;
  3762.  
  3763.     // Sunbird 0.2 used a different GUID for the default theme
  3764.     profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3765.                                          "{8af2d0a7-e394-4de2-ae55-2dae532a7a9b}"]);
  3766.     if (profileDefaultTheme && profileDefaultTheme.exists())
  3767.       removeDirRecursive(profileDefaultTheme);
  3768.  
  3769.     // Firefox 0.9 profiles may have DOMi 1.0 with just an install.rdf
  3770.     var profileDOMi = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3771.                                      "{641d8d09-7dda-4850-8228-ac0ab65e2ac9}"]);
  3772.     if (profileDOMi && profileDOMi.exists())
  3773.       removeDirRecursive(profileDOMi);
  3774.  
  3775.     // return early to avoid migrating data twice if we already have a
  3776.     // toolkit 1.8 extension datasource.
  3777.     if (dsExists)
  3778.       return;
  3779.  
  3780.     // Prepare themes for installation
  3781.     // Only enumerate directories in the app-profile and app-global locations.
  3782.     var locations = [KEY_APP_PROFILE, KEY_APP_GLOBAL];
  3783.     for (var i = 0; i < locations.length; ++i) {
  3784.       var location = InstallLocations.get(locations[i]);
  3785.       if (!location.canAccess)
  3786.         continue;
  3787.  
  3788.       var entries = location.itemLocations;
  3789.       var entry;
  3790.       while ((entry = entries.nextFile)) {
  3791.         var installRDF = entry.clone();
  3792.         installRDF.append(FILE_INSTALL_MANIFEST);
  3793.  
  3794.         var chromeDir = entry.clone();
  3795.         chromeDir.append(DIR_CHROME);
  3796.  
  3797.         // It must be a directory without an install.rdf and it must contain
  3798.         // a chrome directory
  3799.         if (!entry.isDirectory() || installRDF.exists() || !chromeDir.exists())
  3800.           continue;
  3801.  
  3802.         var chromeEntries = chromeDir.directoryEntries.QueryInterface(nsIDirectoryEnumerator);
  3803.         if (!chromeEntries.hasMoreElements())
  3804.           continue;
  3805.  
  3806.         // We're relying on the fact that there is only one JAR file
  3807.         // in the "chrome" directory. This is a hack, but it works.
  3808.         var jarFile = chromeEntries.nextFile;
  3809.         if (jarFile.isDirectory())
  3810.           continue;
  3811.         var id = location.getIDForLocation(entry);
  3812.  
  3813.         try {
  3814.           var zipReader = getZipReaderForFile(jarFile);
  3815.           zipReader.extract(FILE_INSTALL_MANIFEST, installRDF);
  3816.  
  3817.           var contentsManifestFile = location.getItemFile(id, FILE_CONTENTS_MANIFEST);
  3818.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  3819.  
  3820.           var rootFiles = ["preview.png", "icon.png"];
  3821.           for (var i = 0; i < rootFiles.length; ++i) {
  3822.             try {
  3823.               var target = location.getItemFile(id, rootFiles[i]);
  3824.               zipReader.extract(rootFiles[i], target);
  3825.             }
  3826.             catch (e) {
  3827.             }
  3828.           }
  3829.           zipReader.close();
  3830.         }
  3831.         catch (e) {
  3832.           LOG("ExtensionManager:_upgradeFromV10 - failed to extract theme files\r\n" +
  3833.               "Exception: " + e);
  3834.         }
  3835.       }
  3836.     }
  3837.  
  3838.     // When upgrading from a version 1.0 profile we need to populate the
  3839.     // extensions datasource with all items before checking for incompatible
  3840.     // items since the datasource hasn't been created yet.
  3841.     var itemsToCheck = [];
  3842.     if (this._checkForFileChanges()) {
  3843.       // Create a list of all items that are to be installed so we can migrate
  3844.       // these items's settings to the new datasource.
  3845.       var items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3846.       for (i = items.length - 1; i >= 0; --i) {
  3847.         if (items[i].locationKey == KEY_APP_PROFILE ||
  3848.             items[i].locationKey == KEY_APP_GLOBAL)
  3849.           itemsToCheck.push(items[i].id);
  3850.       }
  3851.       this._finishOperations();
  3852.     }
  3853.  
  3854.     // If there are no items to migrate settings for return early.
  3855.     if (itemsToCheck.length == 0)
  3856.       return;
  3857.  
  3858.     var fileURL = getURLSpecFromFile(oldExtensionsFile);
  3859.     var oldExtensionsDS = gRDF.GetDataSourceBlocking(fileURL);
  3860.     var versionChecker = getVersionChecker();
  3861.     var ds = this.datasource;
  3862.     var currAppVersion = gApp.version;
  3863.     var currAppID = gApp.ID;
  3864.     for (var i = 0; i < itemsToCheck.length; ++i) {
  3865.       var item = ds.getItemForID(itemsToCheck[i]);
  3866.       var oldPrefix = (item.type == nsIUpdateItem.TYPE_EXTENSION) ? PREFIX_EXTENSION : PREFIX_THEME;
  3867.       var oldRes = gRDF.GetResource(oldPrefix + item.id);
  3868.       // Disable the item if it was disabled in the version 1.0 extensions
  3869.       // datasource.
  3870.       if (oldExtensionsDS.GetTarget(oldRes, EM_R("disabled"), true))
  3871.         ds.setItemProperty(item.id, EM_R("userDisabled"), EM_L("true"));
  3872.  
  3873.       // app enable all items. If it is incompatible it will be app disabled
  3874.       // later on.
  3875.       ds.setItemProperty(item.id, EM_R("appDisabled"), null);
  3876.  
  3877.       // if the item is already compatible don't attempt to migrate the
  3878.       // item's compatibility info
  3879.       var newRes = getResourceForID(itemsToCheck[i]);
  3880.       if (ds.isCompatible(ds, newRes))
  3881.         continue;
  3882.  
  3883.       var updatedMinVersion = null;
  3884.       var updatedMaxVersion = null;
  3885.       var targetApps = oldExtensionsDS.GetTargets(oldRes, EM_R("targetApplication"), true);
  3886.       while (targetApps.hasMoreElements()) {
  3887.         var targetApp = targetApps.getNext();
  3888.         if (targetApp instanceof Components.interfaces.nsIRDFResource) {
  3889.           try {
  3890.             var foundAppID = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("id"), true));
  3891.             if (foundAppID != currAppID) // Different target application
  3892.               continue;
  3893.  
  3894.             updatedMinVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("minVersion"), true));
  3895.             updatedMaxVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("maxVersion"), true));
  3896.  
  3897.             // Only set the target app info if the extension's target app info
  3898.             // in the version 1.0 extensions datasource makes it compatible
  3899.             if (versionChecker.compare(currAppVersion, updatedMinVersion) >= 0 &&
  3900.                 versionChecker.compare(currAppVersion, updatedMaxVersion) <= 0)
  3901.               ds.updateTargetAppInfo(item.id, updatedMinVersion, updatedMaxVersion);
  3902.  
  3903.             break;
  3904.           }
  3905.           catch (e) { 
  3906.           }
  3907.         }
  3908.       }
  3909.     }
  3910.   },
  3911.  
  3912.   /**
  3913.    * Write the Extensions List and the Startup Cache
  3914.    * @param   needsRestart
  3915.    *          true if the application needs to restart again, false otherwise.
  3916.    */  
  3917.   _updateManifests: function(needsRestart) {
  3918.     // Write the Startup Cache (All Items, visible or not)
  3919.     StartupCache.write();
  3920.     // Write the Extensions Locations Manifest (Visible, enabled items)
  3921.     this._updateExtensionsManifest(needsRestart);
  3922.   },
  3923.  
  3924.   /**
  3925.    * Get a list of items that are currently "active" (turned on) of a specific
  3926.    * type
  3927.    * @param   type
  3928.    *          The nsIUpdateItem type to return a list of items of
  3929.    * @returns An array of active items of the specified type.
  3930.    */
  3931.   _getActiveItems: function(type) {
  3932.     var allItems = this.getItemList(type, { });
  3933.     var activeItems = [];
  3934.     var ds = this.datasource;
  3935.     for (var i = 0; i < allItems.length; ++i) {
  3936.       var item = allItems[i];
  3937.  
  3938.       // An item entry is valid only if it is not disabled, not about to 
  3939.       // be disabled, and not about to be uninstalled.
  3940.       var installLocation = this.getInstallLocation(item.id);
  3941.       if (installLocation.name in StartupCache.entries &&
  3942.           item.id in StartupCache.entries[installLocation.name] &&
  3943.           StartupCache.entries[installLocation.name][item.id]) {
  3944.         var op = StartupCache.entries[installLocation.name][item.id].op;
  3945.         if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE || 
  3946.             op == OP_NEEDS_UNINSTALL || op == OP_NEEDS_DISABLE)
  3947.           continue;
  3948.       }
  3949.       // Suppress items that have been disabled by the user or the app.
  3950.       if (ds.getItemProperty(item.id, "isDisabled") != "true")
  3951.         activeItems.push({ id: item.id, location: installLocation });
  3952.     }
  3953.  
  3954.     return activeItems;
  3955.   },
  3956.   
  3957.   /**
  3958.    * Write the Extensions List
  3959.    * @param   needsRestart
  3960.    *          true if the application needs to restart again, false otherwise.
  3961.    */
  3962.   _updateExtensionsManifest: function(needsRestart) {
  3963.     // When an operation is performed that requires a component re-registration
  3964.     // (extension enabled/disabled, installed, uninstalled), we must write the
  3965.     // set of paths where extensions live so that the startup system can determine
  3966.     // where additional components, preferences, chrome manifests etc live.
  3967.     //
  3968.     // To do this we obtain a list of active extensions and themes and write 
  3969.     // these to the extensions.ini file in the profile directory.
  3970.     var validExtensions = this._getActiveItems(nsIUpdateItem.TYPE_EXTENSION +
  3971.                                                nsIUpdateItem.TYPE_LOCALE +
  3972.                                                nsIUpdateItem.TYPE_PLUGIN);
  3973.     var validThemes     = this._getActiveItems(nsIUpdateItem.TYPE_THEME);
  3974.  
  3975.     var extensionsLocationsFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  3976.     var fos = openSafeFileOutputStream(extensionsLocationsFile);
  3977.         
  3978.     var extensionSectionHeader = "[ExtensionDirs]\r\n";
  3979.     fos.write(extensionSectionHeader, extensionSectionHeader.length);
  3980.     for (var i = 0; i < validExtensions.length; ++i) {
  3981.       var e = validExtensions[i];
  3982.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(nsILocalFile);
  3983.       var descriptor = getAbsoluteDescriptor(itemLocation);
  3984.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  3985.       fos.write(line, line.length);
  3986.     }
  3987.  
  3988.     var themeSectionHeader = "[ThemeDirs]\r\n";
  3989.     fos.write(themeSectionHeader, themeSectionHeader.length);
  3990.     for (i = 0; i < validThemes.length; ++i) {
  3991.       var e = validThemes[i];
  3992.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(nsILocalFile);
  3993.       var descriptor = getAbsoluteDescriptor(itemLocation);
  3994.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  3995.       fos.write(line, line.length);
  3996.     }
  3997.  
  3998.     closeSafeFileOutputStream(fos);
  3999.  
  4000.     // Now refresh the compatibility manifest.
  4001.     this._extensionListChanged = needsRestart;
  4002.   },
  4003.   
  4004.   /**
  4005.    * Say whether or not the Extension List has changed (and thus whether or not
  4006.    * the system will have to restart the next time it is started).
  4007.    * @param   val
  4008.    *          true if the Extension List has changed, false otherwise.
  4009.    * @returns |val|
  4010.    */
  4011.   set _extensionListChanged(val) {
  4012.     // When an extension has an operation perform on it (e.g. install, upgrade,
  4013.     // disable, etc.) we are responsible for creating the .autoreg file and
  4014.     // nsAppRunner is responsible for removing it on restart. At some point it
  4015.     // may make sense to be able to cancel a registration but for now we only
  4016.     // create the file.
  4017.     try {
  4018.       var autoregFile = getFile(KEY_PROFILEDIR, [FILE_AUTOREG]);
  4019.       if (val && !autoregFile.exists())
  4020.         autoregFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  4021.     }
  4022.     catch (e) {
  4023.     }
  4024.     return val;
  4025.   },
  4026.   
  4027.   /**
  4028.    * Gathers data about an item specified by the supplied Install Manifest
  4029.    * and determines whether or not it can be installed as-is. It makes this 
  4030.    * determination by validating the item's GUID, Version, and determining 
  4031.    * if it is compatible with this application.
  4032.    * @param   installManifest 
  4033.    *          A nsIRDFDataSource representing the Install Manifest of the 
  4034.    *          item to be installed.
  4035.    * @return  A JS Object with the following properties:
  4036.    *          "id"       The GUID of the Item being installed.
  4037.    *          "version"  The Version string of the Item being installed.
  4038.    *          "name"     The Name of the Item being installed.
  4039.    *          "type"     The nsIUpdateItem type of the Item being installed.
  4040.    *          "targetApps" An array of TargetApplication Info Objects
  4041.    *                     with "id", "minVersion" and "maxVersion" properties,
  4042.    *                     representing applications targeted by this item.
  4043.    *          "error"    The result code:
  4044.    *                     INSTALLERROR_SUCCESS      
  4045.    *                       no error, item can be installed
  4046.    *                     INSTALLERROR_INVALID_GUID 
  4047.    *                       error, GUID is not well-formed
  4048.    *                     INSTALLERROR_INVALID_VERSION
  4049.    *                       error, Version is not well-formed
  4050.    *                     INSTALLERROR_INCOMPATIBLE_VERSION
  4051.    *                       error, item is not compatible with this version
  4052.    *                       of the application.
  4053.    *                     INSTALLERROR_INCOMPATIBLE_PLATFORM
  4054.    *                       error, item is not compatible with the operating
  4055.    *                       system or ABI the application was built for.
  4056.    *                     INSTALLERROR_BLOCKLISTED
  4057.    *                       error, item is blocklisted
  4058.    */
  4059.   _getInstallData: function(installManifest) {
  4060.     var installData = { id          : "", 
  4061.                         version     : "", 
  4062.                         name        : "", 
  4063.                         type        : 0, 
  4064.                         error       : INSTALLERROR_SUCCESS, 
  4065.                         targetApps  : [],
  4066.                         currentApp  : null };
  4067.  
  4068.     // Fetch properties from the Install Manifest
  4069.     installData.id       = getManifestProperty(installManifest, "id");
  4070.     installData.version  = getManifestProperty(installManifest, "version");
  4071.     installData.name     = getManifestProperty(installManifest, "name");
  4072.     installData.type     = getAddonTypeFromInstallManifest(installManifest);
  4073.     installData.updateURL= getManifestProperty(installManifest, "updateURL");
  4074.  
  4075.     /**
  4076.      * Reads a property off a Target Application resource
  4077.      * @param   resource
  4078.      *          The RDF Resource for a Target Application
  4079.      * @param   property
  4080.      *          The property (less EM_NS) to read
  4081.      * @returns The string literal value of the property.
  4082.      */
  4083.     function readTAProperty(resource, property) {
  4084.       return stringData(installManifest.GetTarget(resource, EM_R(property), true));
  4085.     }
  4086.     
  4087.     var targetApps = installManifest.GetTargets(gInstallManifestRoot, 
  4088.                                                 EM_R("targetApplication"), 
  4089.                                                 true);
  4090.     while (targetApps.hasMoreElements()) {
  4091.       var targetApp = targetApps.getNext();
  4092.       if (targetApp instanceof Components.interfaces.nsIRDFResource) {
  4093.         try {
  4094.           var data = { id        : readTAProperty(targetApp, "id"),
  4095.                        minVersion: readTAProperty(targetApp, "minVersion"),
  4096.                        maxVersion: readTAProperty(targetApp, "maxVersion") };
  4097.           installData.targetApps.push(data);
  4098.           if (data.id == gApp.ID) 
  4099.             installData.currentApp = data;
  4100.         }
  4101.         catch (e) {
  4102.           continue;
  4103.         }
  4104.       }
  4105.     }
  4106.  
  4107.     // If the item specifies one or more target platforms, make sure our OS/ABI
  4108.     // combination is in the list - otherwise, refuse to install the item.
  4109.     var targetPlatforms = null;
  4110.     try {
  4111.       targetPlatforms = installManifest.GetTargets(gInstallManifestRoot, 
  4112.                                                    EM_R("targetPlatform"), 
  4113.                                                    true);
  4114.     } catch(e) {
  4115.       // No targetPlatform nodes, continue.
  4116.     }
  4117.     if (targetPlatforms != null && targetPlatforms.hasMoreElements()) {
  4118.       var foundMatchingOS = false;
  4119.       var foundMatchingOSAndABI = false;
  4120.       var requireABICompatibility = false;
  4121.       while (targetPlatforms.hasMoreElements()) {
  4122.         var targetPlatform = stringData(targetPlatforms.getNext());
  4123.         var os = targetPlatform.split("_")[0];
  4124.         var index = targetPlatform.indexOf("_");
  4125.         var abi = index != -1 ? targetPlatform.substr(index + 1) : null;
  4126.         if (os == gOSTarget) {
  4127.           foundMatchingOS = true;
  4128.           // The presence of any ABI part after our OS means ABI is important.
  4129.           if (abi != null) {
  4130.             requireABICompatibility = true;
  4131.             // If we don't know our ABI, we can't be compatible
  4132.             if (abi == gXPCOMABI && abi != UNKNOWN_XPCOM_ABI) {
  4133.               foundMatchingOSAndABI = true;
  4134.               break;
  4135.             }
  4136.           }
  4137.         }
  4138.       }
  4139.       if (!foundMatchingOS || (requireABICompatibility && !foundMatchingOSAndABI)) {
  4140.         installData.error = INSTALLERROR_INCOMPATIBLE_PLATFORM;
  4141.         return installData;
  4142.       }
  4143.     }
  4144.  
  4145.     // Validate the Item ID
  4146.     if (!gIDTest.test(installData.id)) {
  4147.       installData.error = INSTALLERROR_INVALID_GUID;
  4148.       return installData;
  4149.     }
  4150.      
  4151.     // Check the target application range specified by the extension metadata.
  4152.     if (gCheckCompatibility &&
  4153.         !this.datasource.isCompatible(installManifest, gInstallManifestRoot, undefined))
  4154.       installData.error = INSTALLERROR_INCOMPATIBLE_VERSION;
  4155.     
  4156.     // Check if the item is blocklisted.
  4157.     if (this.datasource.isBlocklisted(installData.id, installData.version,
  4158.                                       undefined, undefined))
  4159.       installData.error = INSTALLERROR_BLOCKLISTED;
  4160.  
  4161.     return installData;
  4162.   },  
  4163.   
  4164.   /**
  4165.    * Installs an item from a XPI/JAR file. 
  4166.    * This is the main entry point into the Install system from outside code
  4167.    * (e.g. XPInstall).
  4168.    * @param   aXPIFile
  4169.    *          The file to install from.
  4170.    * @param   aInstallLocationKey
  4171.    *          The name of the Install Location where this item should be 
  4172.    *          installed.
  4173.    */  
  4174.   installItemFromFile: function(xpiFile, installLocationKey) {
  4175.     this.installItemFromFileInternal(xpiFile, installLocationKey, null);
  4176.   },
  4177.   
  4178.   /**
  4179.    * Installs an item from a XPI/JAR file.
  4180.    * @param   aXPIFile
  4181.    *          The file to install from.
  4182.    * @param   aInstallLocationKey
  4183.    *          The name of the Install Location where this item should be 
  4184.    *          installed.
  4185.    * @param   aInstallManifest
  4186.    *          An updated Install Manifest from the Version Update check.
  4187.    *          Can be null when invoked from callers other than the Version
  4188.    *          Update check.
  4189.    */
  4190.   installItemFromFileInternal: function(aXPIFile, aInstallLocationKey, aInstallManifest) {
  4191.     var em = this;
  4192.     /**
  4193.      * Gets the Install Location for an Item.
  4194.      * @param   itemID 
  4195.      *          The GUID of the item to find an Install Location for.
  4196.      * @return  An object implementing nsIInstallLocation which represents the 
  4197.      *          location where the specified item should be installed. 
  4198.      *          This can be:
  4199.      *          1. an object that corresponds to the location key supplied to
  4200.      *             |installItemFromFileInternal|,
  4201.      *          2. the default install location (the App Profile Extensions Folder)
  4202.      *             if no location key was supplied, or the location key supplied
  4203.      *             was not in the set of registered locations
  4204.      *          3. null, if the location selected by 1 or 2 above does not support
  4205.      *             installs from XPI/JAR files, or that location is not writable 
  4206.      *             with the current access privileges.
  4207.      */
  4208.     function getInstallLocation(itemID) {
  4209.       // Here I use "upgrade" to mean "install a different version of an item".
  4210.       var installLocation = em.getInstallLocation(itemID);
  4211.       if (!installLocation) {
  4212.         // This is not an "upgrade", since we don't have any location data for the
  4213.         // extension ID specified - that is, it's not in our database.
  4214.  
  4215.         // Caller supplied a key to a registered location, use that location
  4216.         // for the installation
  4217.         installLocation = InstallLocations.get(aInstallLocationKey);
  4218.         if (installLocation) {
  4219.           // If the specified location does not have a common metadata location
  4220.           // (e.g. extensions have no common root, or other location specified
  4221.           // by the location implementation) - e.g. for a Registry Key enumeration
  4222.           // location - we cannot install or upgrade using a XPI file, probably
  4223.           // because these application types will be handling upgrading themselves.
  4224.           // Just bail.
  4225.           if (!installLocation.location) {
  4226.             LOG("Install Location \"" + installLocation.name + "\" does not support " + 
  4227.                 "installation of items from XPI/JAR files. You must manage " + 
  4228.                 "installation and update of these items yourself.");
  4229.             installLocation = null;
  4230.           }
  4231.         }
  4232.         else {
  4233.           // In the absence of a preferred install location, just default to
  4234.           // the App-Profile 
  4235.           installLocation = InstallLocations.get(KEY_APP_PROFILE);
  4236.         }
  4237.       } 
  4238.       else {
  4239.         // This is an "upgrade", but not through the Update System, because the
  4240.         // Update code will not let an extension with an incompatible target
  4241.         // app version range through to this point. This is an "upgrade" in the
  4242.         // sense that the user found a different version of an installed extension
  4243.         // and installed it through the web interface, so we have metadata.
  4244.         
  4245.         // If the location is different, return the preferred location rather than
  4246.         // the location of the currently installed version, because we may be in
  4247.         // the situation where an item is being installed into the global app 
  4248.         // dir when there's a version in the profile dir.
  4249.         if (installLocation.name != aInstallLocationKey) 
  4250.           installLocation = InstallLocations.get(aInstallLocationKey);
  4251.       }
  4252.       if (!installLocation.canAccess) {
  4253.         LOG("Install Location\"" + installLocation.name + "\" cannot be written " +
  4254.             "to with your access privileges. Installation will not proceed.");
  4255.         installLocation = null;
  4256.       }
  4257.       return installLocation;
  4258.     }
  4259.     
  4260.     /**
  4261.      * Stages a XPI file in the default item location specified by other 
  4262.      * applications when they registered with XulRunner if the item's
  4263.      * install manifest specified compatibility with them.
  4264.      */
  4265.     function stageXPIForOtherApps(xpiFile, installData) {
  4266.       for (var i = 0; i < installData.targetApps.length; ++i) {
  4267.         var targetApp = installData.targetApps[i];
  4268.         if (targetApp.id != gApp.ID) {
  4269.         /* XXXben uncomment when this works!
  4270.           var settingsThingy = Components.classes[]
  4271.                                         .getService(Components.interfaces.nsIXULRunnerSettingsThingy);
  4272.           try {
  4273.             var appPrefix = "SOFTWARE\\Mozilla\\XULRunner\\Applications\\";
  4274.             var branch = settingsThingy.getBranch(appPrefix + targetApp.id);
  4275.             var path = branch.getProperty("ExtensionsLocation");
  4276.             var destination = Components.classes["@mozilla.org/file/local;1"]
  4277.                                         .createInstance(nsILocalFile);
  4278.             destination.initWithPath(path);
  4279.             xpiFile.copyTo(file, xpiFile.leafName);
  4280.           }
  4281.           catch (e) {
  4282.           }
  4283.          */
  4284.         } 
  4285.       }        
  4286.     }
  4287.     
  4288.     /**
  4289.      * Extracts and then starts the install for extensions / themes contained
  4290.      * within a xpi.
  4291.      */
  4292.     function installMultiXPI(xpiFile, installData) {
  4293.       var fileURL = getURIFromFile(xpiFile).QueryInterface(nsIURL);
  4294.       if (fileURL.fileExtension.toLowerCase() != "xpi") {
  4295.         LOG("Invalid File Extension: Item: \"" + fileURL.fileName + "\" has an " + 
  4296.             "invalid file extension. Only xpi file extensions are allowed for " +
  4297.             "multiple item packages.");
  4298.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4299.         showMessage("invalidFileExtTitle", [], 
  4300.                     "invalidFileExtMessage", [installData.name,
  4301.                     fileURL.fileExtension,
  4302.                     bundle.GetStringFromName("type-" + installData.type)]);
  4303.         return;
  4304.       }
  4305.  
  4306.       try {
  4307.         var zipReader = getZipReaderForFile(xpiFile);
  4308.       }
  4309.       catch (e) {
  4310.         LOG("installMultiXPI: failed to open xpi file: " + xpiFile.path);
  4311.         throw e;
  4312.       }
  4313.  
  4314.       var searchForEntries = ["*.xpi", "*.jar"];
  4315.       var files = [];
  4316.       for (var i = 0; i < searchForEntries.length; ++i) {
  4317.         var entries = zipReader.findEntries(searchForEntries[i]);
  4318.         while (entries.hasMoreElements()) {
  4319.           var entry = entries.getNext().QueryInterface(Components.interfaces.nsIZipEntry);
  4320.           var target = getFile(KEY_TEMPDIR, [entry.name]);
  4321.           try {
  4322.             target.createUnique(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  4323.           }
  4324.           catch (e) {
  4325.             LOG("installMultiXPI: failed to create target file for extraction " +
  4326.                 " file = " + target.path + ", exception = " + e + "\n");
  4327.           }
  4328.           zipReader.extract(entry.name, target);
  4329.           files.push(target);
  4330.         }
  4331.       }
  4332.       zipReader.close();
  4333.  
  4334.       if (files.length == 0) {
  4335.         LOG("Multiple Item Package: Item: \"" + fileURL.fileName + "\" does " +
  4336.             "not contain a valid package to install.");
  4337.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4338.         showMessage("missingPackageFilesTitle",
  4339.                     [bundle.GetStringFromName("type-" + installData.type)],
  4340.                     "missingPackageFilesMessage", [installData.name,
  4341.                     bundle.GetStringFromName("type-" + installData.type)]);
  4342.         return;
  4343.       }
  4344.  
  4345.       for (i = 0; i < files.length; ++i) {
  4346.         em.installItemFromFileInternal(files[i], aInstallLocationKey, null);
  4347.         files[i].remove(false);
  4348.       }
  4349.     }
  4350.  
  4351.     /**
  4352.      * An observer for the Extension Update System.
  4353.      * @constructor
  4354.      */
  4355.     function IncompatibleObserver() {}
  4356.     IncompatibleObserver.prototype = {
  4357.       _id: null,
  4358.       _type: nsIUpdateItem.TYPE_ANY,
  4359.       _xpi: null,
  4360.       _installManifest: null,
  4361.       _installRDF: null,
  4362.       
  4363.       /** 
  4364.        * Ask the Extension Update System if there are any version updates for
  4365.        * this item that will allow it to be compatible with this version of 
  4366.        * the Application.
  4367.        * @param   installManifest 
  4368.        *          The Install Manifest datasource for the item.
  4369.        * @param   installData
  4370.        *          The Install Data object for the item.
  4371.        * @param   xpiFile         
  4372.        *          The staged source XPI file that contains the item. Cleaned 
  4373.        *          up by this process.
  4374.        */
  4375.       checkForUpdates: function(installManifest, installData, xpiFile, installRDF) {
  4376.         this._id              = installData.id;
  4377.         this._type            = installData.type;
  4378.         this._xpi             = xpiFile;
  4379.         this._installManifest = installManifest;
  4380.         this._installRDF      = installRDF;
  4381.         
  4382.         var item = makeItem(installData.id, installData.version, 
  4383.                             aInstallLocationKey, 
  4384.                             installData.currentApp.minVersion, 
  4385.                             installData.currentApp.maxVersion,
  4386.                             installData.name,
  4387.                             "", /* XPI Update URL */
  4388.                             "", /* XPI Update Hash */
  4389.                             "", /* Icon URL */
  4390.                             installData.updateURL || "", 
  4391.                             installData.type);
  4392.         em.update([item], 1, true, this);
  4393.       },
  4394.       
  4395.       /**
  4396.        * See nsIExtensionManager.idl
  4397.        */
  4398.       onUpdateStarted: function() {
  4399.         LOG("Phone Home Listener: Update Started");
  4400.         em.datasource.onUpdateStarted();
  4401.       },
  4402.       
  4403.       /**
  4404.        * See nsIExtensionManager.idl
  4405.        */
  4406.       onUpdateEnded: function() {
  4407.         LOG("Phone Home Listener: Update Ended");
  4408.         // We are responsible for cleaning up this file!
  4409.         this._installRDF.remove(false);
  4410.         em.datasource.onUpdateEnded();
  4411.       },
  4412.       
  4413.       /**
  4414.        * See nsIExtensionManager.idl
  4415.        */
  4416.       onAddonUpdateStarted: function(addon) {
  4417.         LOG("Phone Home Listener: Update For " + addon.id + " started");
  4418.         em.datasource.addIncompatibleUpdateItem(addon.name, this._xpi.path,
  4419.                                                 addon.type, addon.version);
  4420.         em.datasource.onAddonUpdateStarted(addon);
  4421.       },
  4422.       
  4423.       /**
  4424.        * See nsIExtensionManager.idl
  4425.        */
  4426.       onAddonUpdateEnded: function(addon, status) {
  4427.         LOG("Phone Home Listener: Update For " + addon.id + " ended, status = " + status); 
  4428.         em.datasource.removeDownload(this._xpi.path);
  4429.         LOG("Version Check Phone Home Completed");
  4430.         // Only compatibility updates (e.g. STATUS_VERSIONINFO) are currently
  4431.         // supported
  4432.         if (status == nsIAddonUpdateCheckListener.STATUS_VERSIONINFO) {
  4433.           em.datasource.setTargetApplicationInfo(addon.id, 
  4434.                                                  addon.minAppVersion,
  4435.                                                  addon.maxAppVersion, 
  4436.                                                  this._installManifest);
  4437.  
  4438.           // Try and install again, but use the updated compatibility DB
  4439.           em.installItemFromFileInternal(this._xpi, aInstallLocationKey, 
  4440.                                          this._installManifest);
  4441.  
  4442.           // Add the updated compatibility info to the datasource if done
  4443.           if (StartupCache.entries[aInstallLocationKey][addon.id].op == OP_NONE) {
  4444.             em.datasource.updateTargetAppInfo(addon.id, addon.minAppVersion,
  4445.                                               addon.maxAppVersion);
  4446.           }
  4447.           else { // needs a restart
  4448.             // Add updatedMinVersion and updatedMaxVersion so it can be used
  4449.             // to update the data sources during the installation or upgrade.
  4450.             em.datasource.setUpdatedTargetAppInfo(addon.id, addon.minAppVersion,
  4451.                                                   addon.maxAppVersion);
  4452.           }
  4453.           // Prevent the datasource file from being lazily recreated after
  4454.           // it is deleted by calling Flush.
  4455.           this._installManifest.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
  4456.           this._installManifest.Flush();
  4457.         }
  4458.         else {
  4459.           em.datasource.removeDownload(this._xpi.path);
  4460.           showIncompatibleError(installData);
  4461.           // We are responsible for cleaning up this file!
  4462.           InstallLocations.get(aInstallLocationKey).removeFile(this._xpi);
  4463.         }
  4464.         em.datasource.onAddonUpdateEnded(addon, status);
  4465.       },
  4466.  
  4467.       /**
  4468.        * See nsISupports.idl
  4469.        */
  4470.       QueryInterface: function(iid) {
  4471.         if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  4472.             !iid.equals(Components.interfaces.nsISupports))
  4473.           throw Components.results.NS_ERROR_NO_INTERFACE;
  4474.         return this;
  4475.       }
  4476.     }
  4477.  
  4478.     var installManifestFile = extractRDFFileToTempDir(aXPIFile, FILE_INSTALL_MANIFEST, true);
  4479.     var shouldPhoneHomeIfNecessary = false;
  4480.     if (!aInstallManifest) {
  4481.       // If we were not called with an Install Manifest, we were called from 
  4482.       // some other path than the Phone Home system, so we do want to phone
  4483.       // home if the version is incompatible.
  4484.       shouldPhoneHomeIfNecessary = true;
  4485.       var installManifest = getInstallManifest(installManifestFile);
  4486.       if (!installManifest) {
  4487.         LOG("The Install Manifest supplied by this item is not well-formed. " + 
  4488.             "Installation will not proceed.");
  4489.         installManifestFile.remove(false);
  4490.         return;
  4491.       }
  4492.     }
  4493.     else
  4494.       installManifest = aInstallManifest;
  4495.     
  4496.     var installData = this._getInstallData(installManifest);
  4497.     switch (installData.error) {
  4498.     case INSTALLERROR_INCOMPATIBLE_VERSION:
  4499.       // Since the caller cleans up |aXPIFile|, and we're not yet sure whether or
  4500.       // not we need it (we may need it if a remote version bump that makes it 
  4501.       // compatible is discovered by the call home) - so we must stage it for 
  4502.       // later ourselves.
  4503.       if (shouldPhoneHomeIfNecessary && installData.currentApp) {
  4504.         var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4505.         if (!installLocation) {
  4506.           installManifestFile.remove(false);
  4507.           return;
  4508.         }
  4509.         var stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4510.         (new IncompatibleObserver(this)).checkForUpdates(installManifest, 
  4511.                                                          installData, stagedFile,
  4512.                                                          installManifestFile);
  4513.         // Return early to prevent deletion of the install manifest file.
  4514.         return;
  4515.       }
  4516.       else {
  4517.         // XXXben Look up XULRunnerSettingsThingy to see if there is a registered
  4518.         //        app that can handle this item, if so just stage and don't show
  4519.         //        this error!
  4520.         showIncompatibleError(installData);
  4521.       }
  4522.       break;
  4523.     case INSTALLERROR_SUCCESS:
  4524.       // Installation of multiple extensions / themes contained within a single xpi.
  4525.       if (installData.type == nsIUpdateItem.TYPE_MULTI_XPI) {
  4526.         installMultiXPI(aXPIFile, installData);
  4527.         break;
  4528.       }
  4529.  
  4530.       // Stage the extension's XPI so it can be extracted at the next restart.
  4531.       var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4532.       if (!installLocation) {
  4533.         // No cleanup of any of the staged XPI files should be required here, 
  4534.         // because this should only ever fail on the first recurse through
  4535.         // this function, BEFORE staging takes place... technically speaking
  4536.         // a location could become readonly during the phone home process, 
  4537.         // but that's an edge case I don't care about.
  4538.         installManifestFile.remove(false);
  4539.         return;
  4540.       }
  4541.  
  4542.       // Stage a copy of the XPI/JAR file for our own evil purposes...
  4543.       stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4544.       
  4545.       var restartRequired = this.installRequiresRestart(installData.id, 
  4546.                                                         installData.type);
  4547.       // Determine which configuration function to use based on whether or not
  4548.       // there is data about this item in our datasource already - if there is 
  4549.       // we want to upgrade, otherwise we install fresh.
  4550.       var ds = this.datasource;
  4551.       if (installData.id in ds.visibleItems && ds.visibleItems[installData.id]) {
  4552.         // We enter this function if any data corresponding to an existing GUID
  4553.         // is found, regardless of its Install Location. We need to check before
  4554.         // "upgrading" an item that Install Location of the new item is of equal
  4555.         // or higher priority than the old item, to make sure the datasource only
  4556.         // ever tracks metadata for active items.
  4557.         var oldInstallLocation = this.getInstallLocation(installData.id);
  4558.         if (oldInstallLocation.priority >= installLocation.priority) {
  4559.           this._upgradeItem(installManifest, installData.id, installLocation, 
  4560.                             installData.type);
  4561.           if (!restartRequired) {
  4562.             this._finalizeUpgrade(installData.id);
  4563.             this._finalizeInstall(installData.id, stagedFile);
  4564.           }
  4565.         }
  4566.       }
  4567.       else {
  4568.         this._configureForthcomingItem(installManifest, installData.id, 
  4569.                                         installLocation, installData.type);
  4570.         if (!restartRequired)
  4571.           this._finalizeInstall(installData.id, stagedFile);
  4572.       }
  4573.       this._updateManifests(restartRequired);
  4574.       break;
  4575.     case INSTALLERROR_INVALID_GUID:
  4576.       LOG("Invalid GUID: Item has GUID: \"" + installData.id + "\"" + 
  4577.           " which is not well-formed.");
  4578.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4579.       showMessage("incompatibleTitle", 
  4580.                   [bundle.GetStringFromName("type-" + installData.type)], 
  4581.                   "invalidGUIDMessage", [installData.name, installData.id]);
  4582.       break;
  4583.     case INSTALLERROR_INVALID_VERSION:
  4584.       LOG("Invalid Version: Item: \"" + installData.id + "\" has version " + 
  4585.           installData.version + " which is not well-formed.");
  4586.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4587.       showMessage("incompatibleTitle", 
  4588.                   [bundle.GetStringFromName("type-" + installData.type)], 
  4589.                   "invalidVersionMessage", [installData.name, installData.version]);
  4590.       break;
  4591.     case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  4592.       const osABI = gOSTarget + "_" + gXPCOMABI;
  4593.       LOG("Incompatible Platform: Item: \"" + installData.id + "\" is not " + 
  4594.           "compatible with '" + osABI + "'.");
  4595.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4596.       showMessage("incompatibleTitle", 
  4597.                   [bundle.GetStringFromName("type-" + installData.type)], 
  4598.                   "incompatiblePlatformMessage",
  4599.                   [installData.name, BundleManager.appName, osABI]);
  4600.       break;
  4601.     case INSTALLERROR_BLOCKLISTED:
  4602.       LOG("Blocklisted Item: Item: \"" + installData.id + "\" version " + 
  4603.           installData.version + " was not installed.");
  4604.       showBlocklistMessage([installData], true);
  4605.       break;
  4606.     default:
  4607.       break;
  4608.     }
  4609.     
  4610.     // Check to see if this item supports other applications and in that case
  4611.     // stage the the XPI file in the location specified by those applications.
  4612.     stageXPIForOtherApps(aXPIFile, installData);
  4613.  
  4614.     installManifestFile.remove(false);
  4615.   },
  4616.   
  4617.   /**
  4618.    * Whether or not this type's installation/uninstallation requires 
  4619.    * the application to be restarted.
  4620.    * @param   id
  4621.    *          The GUID of the item
  4622.    * @param   type
  4623.    *          The nsIUpdateItem type of the item
  4624.    * @returns true if installation of an item of this type requires a 
  4625.    *          restart.
  4626.    */
  4627.   installRequiresRestart: function(id, type) {
  4628.     switch (type) {
  4629.     case nsIUpdateItem.TYPE_THEME:
  4630.       var internalName = this.datasource.getItemProperty(id, "internalName");
  4631.       var needsRestart = false;
  4632.       if (gPref.prefHasUserValue(PREF_DSS_SKIN_TO_SELECT))
  4633.         needsRestart = internalName == gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  4634.       if (!needsRestart &&
  4635.           gPref.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN))
  4636.         needsRestart = internalName == gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN);
  4637.       return needsRestart;
  4638.     }
  4639.     return true;
  4640.   },
  4641.   
  4642.   /**
  4643.    * Perform initial configuration on an item that has just or will be 
  4644.    * installed. This inserts the item into the appropriate container in the
  4645.    * datasource, so that the application UI shows the item even if it will
  4646.    * not actually be installed until the next restart.
  4647.    * @param   installManifest 
  4648.    *          The Install Manifest datasource that describes this item.
  4649.    * @param   id          
  4650.    *          The GUID of this item.
  4651.    * @param   installLocation
  4652.    *          The Install Location where this item is installed.
  4653.    * @param   type
  4654.    *          The nsIUpdateItem type of this item. 
  4655.    */  
  4656.   _configureForthcomingItem: function(installManifest, id, installLocation, type) {
  4657.     var ds = this.datasource;
  4658.     ds.updateVisibleList(id, installLocation.name, false);
  4659.     var props = { name            : EM_L(getManifestProperty(installManifest, "name")),
  4660.                   version         : EM_L(getManifestProperty(installManifest, "version")),
  4661.                   installLocation : EM_L(installLocation.name),
  4662.                   type            : EM_I(type),
  4663.                   availableUpdateURL    : null,
  4664.                   availableUpdateHash   : null,
  4665.                   availableUpdateVersion: null };
  4666.     for (var p in props)
  4667.       ds.setItemProperty(id, EM_R(p), props[p]);
  4668.     ds.updateProperty(id, "availableUpdateURL");
  4669.     
  4670.     this._setOp(id, OP_NEEDS_INSTALL);
  4671.     
  4672.     // Insert it into the child list NOW rather than later because:
  4673.     // - extensions installed using the command line need to be a member
  4674.     //   of a container during the install phase for the code to be able
  4675.     //   to identify profile vs. global
  4676.     // - extensions installed through the UI should show some kind of
  4677.     //   feedback to indicate their presence is forthcoming (i.e. they
  4678.     //   will be available after a restart).
  4679.     ds.insertItemIntoContainer(id);
  4680.     
  4681.     this._notifyAction(id, EM_ITEM_INSTALLED);
  4682.   },
  4683.   
  4684.   /**
  4685.    * Perform configuration on an item that has just or will be upgraded.
  4686.    * @param   installManifest
  4687.    *          The Install Manifest datasource that describes this item.
  4688.    * @param   itemID
  4689.    *          The GUID of this item.
  4690.    * @param   installLocation
  4691.    *          The Install Location where this item is installed.
  4692.    * @param   type
  4693.    *          The nsIUpdateItem type of this item. 
  4694.    */
  4695.   _upgradeItem: function (installManifest, id, installLocation, type) {
  4696.     // Don't change any props that would need to be reset if the install fails.
  4697.     // They will be reset as appropriate by the upgrade/install process.
  4698.     var ds = this.datasource;
  4699.     ds.updateVisibleList(id, installLocation.name, false);
  4700.     var props = { installLocation : EM_L(installLocation.name),
  4701.                   type            : EM_I(type),
  4702.                   availableUpdateURL      : null,
  4703.                   availableUpdateHash     : null,
  4704.                   availableUpdateVersion  : null };
  4705.     for (var p in props)
  4706.       ds.setItemProperty(id, EM_R(p), props[p]);
  4707.     ds.updateProperty(id, "availableUpdateURL");
  4708.  
  4709.     this._setOp(id, OP_NEEDS_UPGRADE);
  4710.     this._notifyAction(id, EM_ITEM_UPGRADED);
  4711.   },
  4712.  
  4713.   /** 
  4714.    * Completes an Extension's installation.
  4715.    * @param   id
  4716.    *          The GUID of the Extension to install.
  4717.    * @param   file
  4718.    *          The XPI/JAR file to install from. If this is null, we try to
  4719.    *          determine the stage file location from the ID.
  4720.    */
  4721.   _finalizeInstall: function(id, file) {
  4722.     var ds = this.datasource;
  4723.     var type = ds.getItemProperty(id, "type");
  4724.     if (id == 0 || id == -1) {
  4725.       ds.removeCorruptItem(id, type);
  4726.       return;
  4727.     }
  4728.     var installLocation = this.getInstallLocation(id);
  4729.     if (!installLocation) {
  4730.       // If the install location is null, that means we've reached the finalize
  4731.       // state without the item ever having metadata added for it, which implies
  4732.       // bogus data in the Startup Cache. Clear the entries and don't do anything
  4733.       // else.
  4734.       var entries = StartupCache.findEntries(id);
  4735.       for (var i = 0; i < entries.length; ++i) {
  4736.         var location = InstallLocations.get(entries[i].location);
  4737.         StartupCache.clearEntry(location, id);
  4738.         PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4739.       }
  4740.       return;
  4741.     }
  4742.     var itemLocation = installLocation.getItemLocation(id);
  4743.  
  4744.     if (!file && "stageFile" in installLocation)
  4745.       file = installLocation.getStageFile(id);
  4746.     
  4747.     // If |file| is null or does not exist, the installer assumes the item is
  4748.     // a dropped-in directory.
  4749.     var installer = new Installer(this.datasource, id, installLocation, type);
  4750.     installer.installFromFile(file);
  4751.  
  4752.     // If the file was staged, we must clean it up ourselves, otherwise the 
  4753.     // EM caller is responsible for doing so (e.g. XPInstall)
  4754.     if (file)
  4755.       installLocation.removeFile(file);
  4756.     
  4757.     // Clear the op flag from the Startup Cache and Pending Operations sets
  4758.     StartupCache.put(installLocation, id, OP_NONE, true);
  4759.     PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4760.   },
  4761.  
  4762.   /**
  4763.    * Removes an item's metadata in preparation for an upgrade-install.
  4764.    * @param   id
  4765.    *          The GUID of the item to uninstall.
  4766.    */
  4767.   _finalizeUpgrade: function(id) {
  4768.     // Retrieve the item properties *BEFORE* we clean the resource!
  4769.     var ds = this.datasource;
  4770.     var installLocation = this.getInstallLocation(id);
  4771.  
  4772.     var stagedFile = null;
  4773.     if ("getStageFile" in installLocation)
  4774.       stagedFile = installLocation.getStageFile(id);
  4775.  
  4776.     if (stagedFile)
  4777.       var installRDF = extractRDFFileToTempDir(stagedFile, FILE_INSTALL_MANIFEST, true);
  4778.     else
  4779.       installRDF = installLocation.getItemFile(id, FILE_INSTALL_MANIFEST);
  4780.     if (installRDF.exists()) {
  4781.       var installManifest = getInstallManifest(installRDF);
  4782.       if (installManifest) {
  4783.         var type = getAddonTypeFromInstallManifest(installManifest);
  4784.         var userDisabled = ds.getItemProperty(id, "userDisabled") == "true";
  4785.  
  4786.         // Clean the item resource
  4787.         ds.removeItemMetadata(id);
  4788.         // Now set up the properties on the item to mimic an item in its
  4789.         // "initial state" for installation.
  4790.         this._configureForthcomingItem(installManifest, id, installLocation, 
  4791.                                        type);
  4792.         if (userDisabled)
  4793.           ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  4794.       }
  4795.       if (stagedFile)
  4796.         installRDF.remove(false);
  4797.     }
  4798.     // Clear the op flag from the Pending Operations set. Do NOT clear op flag in 
  4799.     // the startup cache since this may have been reset to OP_NEEDS_INSTALL by
  4800.     // |_configureForthcomingItem|.
  4801.     PendingOperations.clearItem(OP_NEEDS_UPGRADE, id);
  4802.   },
  4803.   
  4804.   /**
  4805.    * Completes an item's uninstallation.
  4806.    * @param   id
  4807.    *          The GUID of the item to uninstall.
  4808.    */
  4809.   _finalizeUninstall: function(id) {
  4810.     var ds = this.datasource;
  4811.     
  4812.     var installLocation = this.getInstallLocation(id);
  4813.     if (!installLocation.itemIsManagedIndependently(id)) {
  4814.       try {
  4815.         // Having a callback that does nothing just causes the directory to be
  4816.         // removed.
  4817.         safeInstallOperation(id, installLocation, 
  4818.                              { data: null, callback: function() { } });
  4819.       }
  4820.       catch (e) {
  4821.         LOG("_finalizeUninstall: failed to remove directory for item: " + id + 
  4822.             " at Install Location: " + installLocation.name + ", rolling back uninstall");
  4823.         // Removal of the files failed, reset the uninstalled flag and rewrite
  4824.         // the install manifests so this item's components are registered.
  4825.         // Clear the op flag from the Startup Cache
  4826.         StartupCache.put(installLocation, id, OP_NONE, true);
  4827.         var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  4828.         this._updateManifests(restartRequired);
  4829.         return;
  4830.       }
  4831.     }
  4832.     else if (installLocation.name == KEY_APP_PROFILE ||
  4833.              installLocation.name == KEY_APP_GLOBAL) {
  4834.       // Check for a pointer file and remove it if it exists
  4835.       var pointerFile = installLocation.location.clone();
  4836.       pointerFile.append(id);
  4837.       if (pointerFile.exists() && !pointerFile.isDirectory())
  4838.         pointerFile.remove(false);
  4839.     }
  4840.     
  4841.     // Clean the item resource
  4842.     ds.removeItemMetadata(id);
  4843.     
  4844.     // Do this LAST since inferences are made about an item based on
  4845.     // what container it's in.
  4846.     ds.removeItemFromContainer(id);
  4847.     
  4848.     // Clear the op flag from the Startup Cache and the Pending Operations set.
  4849.     StartupCache.clearEntry(installLocation, id);
  4850.     PendingOperations.clearItem(OP_NEEDS_UNINSTALL, id);
  4851.   },
  4852.   
  4853.   /**
  4854.    * Uninstalls an item. If the uninstallation cannot be performed immediately
  4855.    * it is scheduled for the next restart.
  4856.    * @param   id
  4857.    *          The GUID of the item to uninstall.
  4858.    */
  4859.   uninstallItem: function(id) {
  4860.     var ds = this.datasource;
  4861.     ds.updateDownloadState(PREFIX_ITEM_URI + id, null);
  4862.     if (!ds.isDownloadItem(id)) {
  4863.       var opType = ds.getItemProperty(id, "opType");
  4864.       var installLocation = this.getInstallLocation(id);
  4865.       // Removes any staged xpis for this item.
  4866.       if (opType == OP_NEEDS_UPGRADE || opType == OP_NEEDS_INSTALL) {
  4867.         var stageFile = installLocation.getStageFile(id);
  4868.         if (stageFile)
  4869.           installLocation.removeFile(stageFile);
  4870.       }
  4871.       // Addons with an opType of OP_NEEDS_INSTALL only have a staged xpi file
  4872.       // and are removed immediately since the uninstall can't be canceled.
  4873.       if (opType == OP_NEEDS_INSTALL) {
  4874.         ds.removeItemMetadata(id);
  4875.         ds.removeItemFromContainer(id);
  4876.         ds.updateVisibleList(id, null, true);
  4877.         StartupCache.clearEntry(installLocation, id);
  4878.         this._updateManifests(false);
  4879.       }
  4880.       else {
  4881.         this._setOp(id, OP_NEEDS_UNINSTALL);
  4882.         var type = ds.getItemProperty(id, "type");
  4883.         var restartRequired = this.installRequiresRestart(id, type);
  4884.         if (!restartRequired) {
  4885.           this._finalizeUninstall(id);
  4886.           this._updateManifests(restartRequired);
  4887.         }
  4888.       }
  4889.     }
  4890.     else {
  4891.       // Bad download entry - uri is url, e.g. "http://www.foo.com/test.xpi"
  4892.       // ... just remove it from the list. 
  4893.       ds.removeCorruptDLItem(id);
  4894.     }
  4895.     
  4896.     this._notifyAction(id, EM_ITEM_UNINSTALLED);
  4897.   },
  4898.  
  4899.   /**
  4900.    * Cancels a pending uninstall of an item
  4901.    * @param   id
  4902.    *          The ID of the item.
  4903.    */
  4904.   cancelUninstallItem: function(id) {
  4905.     var ds = this.datasource;
  4906.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  4907.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  4908.     if (appDisabled == "true" || appDisabled == OP_NONE && userDisabled == OP_NONE) {
  4909.       this._setOp(id, OP_NONE);
  4910.       this._notifyAction(id, EM_ITEM_CANCEL);
  4911.     }
  4912.     else if (appDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NEEDS_DISABLE) {
  4913.       this._setOp(id, OP_NEEDS_DISABLE);
  4914.       this._notifyAction(id, EM_ITEM_DISABLED);
  4915.     }
  4916.     else if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE) {
  4917.       this._setOp(id, OP_NEEDS_ENABLE);
  4918.       this._notifyAction(id, EM_ITEM_ENABLED);
  4919.     }
  4920.     else {
  4921.       this._setOp(id, OP_NONE);
  4922.       this._notifyAction(id, EM_ITEM_CANCEL);
  4923.     }
  4924.   },
  4925.  
  4926.   /**
  4927.    * Sets the pending operation for a visible item. 
  4928.    * @param   id
  4929.    *          The GUID of the item
  4930.    * @param   op
  4931.    *          The name of the operation to be performed
  4932.    */  
  4933.   _setOp: function(id, op) {
  4934.     var location = this.getInstallLocation(id);
  4935.     StartupCache.put(location, id, op, true);
  4936.     PendingOperations.addItem(op, { locationKey: location.name, id: id });
  4937.     var ds = this.datasource;
  4938.     if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE)
  4939.       ds.updateDownloadState(PREFIX_ITEM_URI + id, "success");
  4940.  
  4941.     ds.updateProperty(id, "opType");
  4942.     ds.updateProperty(id, "updateable");
  4943.     ds.updateProperty(id, "satisfiesDependencies");
  4944.     var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  4945.     this._updateDependentItemsForID(id);
  4946.     this._updateManifests(restartRequired);
  4947.   },
  4948.   
  4949.   /**
  4950.    * Note on appDisabled and userDisabled property arcs.
  4951.    * The appDisabled and userDisabled RDF property arcs are used to store
  4952.    * the pending operation for app disabling and user disabling for an item as
  4953.    * well as the user and app disabled status after the pending operation has
  4954.    * been completed upon restart. When the appDisabled value changes the value
  4955.    * of userDisabled is reset to prevent the state of widgets and status
  4956.    * messages from being in an incorrect state.
  4957.    */
  4958.  
  4959.   /**
  4960.    * Enables an item for the application (e.g. the item satisfies all
  4961.    * requirements like app compatibility for it to be enabled). The appDisabled
  4962.    * property arc will be removed if the item will be app disabled on next
  4963.    * restart to cancel the app disabled operation for the item otherwise the
  4964.    * property value will be set to OP_NEEDS_ENABLE. The item's pending
  4965.    * operations are then evaluated in order to set the operation to perform
  4966.    * and notify the observers if the operation has been changed.
  4967.    * See "Note on appDisabled and userDisabled property arcs" above.
  4968.    * @param   id
  4969.    *          The ID of the item to be enabled by the application.
  4970.    */
  4971.   _appEnableItem: function(id) {
  4972.     var ds = this.datasource;
  4973.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  4974.     if (appDisabled == OP_NONE || appDisabled == OP_NEEDS_ENABLE)
  4975.       return;
  4976.  
  4977.     var opType = ds.getItemProperty(id, "opType");
  4978.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  4979.     // reset user disabled if it has a pending operation to prevent the ui
  4980.     // state from getting confused as to an item's current state.
  4981.     if (userDisabled == OP_NEEDS_DISABLE)
  4982.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  4983.     else if (userDisabled == OP_NEEDS_ENABLE)
  4984.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  4985.  
  4986.     if (appDisabled == OP_NEEDS_DISABLE)
  4987.       ds.setItemProperty(id, EM_R("appDisabled"), null);
  4988.     else if (appDisabled == "true")
  4989.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_ENABLE));
  4990.  
  4991.     // Don't set a new operation when there is a pending uninstall operation.
  4992.     if (opType == OP_NEEDS_UNINSTALL) {
  4993.       this._updateDependentItemsForID(id);
  4994.       return;
  4995.     }
  4996.  
  4997.     var operation, action;
  4998.     // if this item is already enabled or user disabled don't set a pending
  4999.     // operation - instead immediately enable it and reset the operation type
  5000.     // if needed.
  5001.     if (appDisabled == OP_NEEDS_DISABLE || appDisabled == OP_NONE ||
  5002.         userDisabled == "true") {
  5003.       if (opType != OP_NONE) {
  5004.         operation = OP_NONE;
  5005.         action = EM_ITEM_CANCEL;
  5006.       }
  5007.     }
  5008.     else {
  5009.       if (opType != OP_NEEDS_ENABLE) {
  5010.         operation = OP_NEEDS_ENABLE;
  5011.         action = EM_ITEM_ENABLED;
  5012.       }
  5013.     }
  5014.  
  5015.     if (action) {
  5016.       this._setOp(id, operation);
  5017.       this._notifyAction(id, action);
  5018.     }
  5019.     else {
  5020.       ds.updateProperty(id, "satisfiesDependencies");
  5021.       this._updateDependentItemsForID(id);
  5022.     }
  5023.   },
  5024.  
  5025.   /**
  5026.    * Disables an item for the application (e.g. the item doesn't satisfy all
  5027.    * requirements like app compatibility for it to be enabled). The appDisabled
  5028.    * property arc will be set to true if the item will be app enabled on next
  5029.    * restart to cancel the app enabled operation for the item otherwise the
  5030.    * property value will be set to OP_NEEDS_DISABLE. The item's pending
  5031.    * operations are then evaluated in order to set the operation to perform
  5032.    * and notify the observers if the operation has been changed.
  5033.    * See "Note on appDisabled and userDisabled property arcs" above.
  5034.    * @param   id
  5035.    *          The ID of the item to be disabled by the application.
  5036.    */
  5037.   _appDisableItem: function(id) {
  5038.     var ds = this.datasource;
  5039.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5040.     if (appDisabled == "true" || appDisabled == OP_NEEDS_DISABLE)
  5041.       return;
  5042.  
  5043.     var opType = ds.getItemProperty(id, "opType");
  5044.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5045.  
  5046.     // reset user disabled if it has a pending operation to prevent the ui
  5047.     // state from getting confused as to an item's current state.
  5048.     if (userDisabled == OP_NEEDS_DISABLE)
  5049.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  5050.     else if (userDisabled == OP_NEEDS_ENABLE)
  5051.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5052.  
  5053.     if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE ||
  5054.         ds.getItemProperty(id, "userDisabled") == "true")
  5055.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  5056.     else if (appDisabled == OP_NONE)
  5057.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_DISABLE));
  5058.  
  5059.     // Don't set a new operation when there is a pending uninstall operation.
  5060.     if (opType == OP_NEEDS_UNINSTALL) {
  5061.       this._updateDependentItemsForID(id);
  5062.       return;
  5063.     }
  5064.  
  5065.     var operation, action;
  5066.     // if this item is already disabled don't set a pending operation - instead
  5067.     // immediately disable it and reset the operation type if needed.
  5068.     if (appDisabled == OP_NEEDS_ENABLE || appDisabled == "true" ||
  5069.         userDisabled == OP_NEEDS_ENABLE || userDisabled == "true") {
  5070.       if (opType != OP_NONE) {
  5071.         operation = OP_NONE;
  5072.         action = EM_ITEM_CANCEL;
  5073.       }
  5074.     }
  5075.     else {
  5076.       if (opType != OP_NEEDS_DISABLE) {
  5077.         operation = OP_NEEDS_DISABLE;
  5078.         action = EM_ITEM_DISABLED;
  5079.       }
  5080.     }
  5081.  
  5082.     if (action) {
  5083.       this._setOp(id, operation);
  5084.       this._notifyAction(id, action);
  5085.     }
  5086.     else {
  5087.       ds.updateProperty(id, "satisfiesDependencies");
  5088.       this._updateDependentItemsForID(id);
  5089.     }
  5090.   },
  5091.     
  5092.   /**
  5093.    * Sets an item to be enabled by the user. If the item is already enabled this
  5094.    * clears the needs-enable operation for the next restart.
  5095.    * See "Note on appDisabled and userDisabled property arcs" above.
  5096.    * @param   id
  5097.    *          The ID of the item to be enabled by the user.
  5098.    */
  5099.   enableItem: function(id) {
  5100.     var ds = this.datasource;
  5101.     var opType = ds.getItemProperty(id, "opType");
  5102.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5103.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5104.  
  5105.     var operation, action;
  5106.     // if this item is already enabled don't set a pending operation - instead
  5107.     // immediately enable it and reset the operation type if needed.
  5108.     if (appDisabled == OP_NONE &&
  5109.         userDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NONE) {
  5110.       if (userDisabled == OP_NEEDS_DISABLE)
  5111.         ds.setItemProperty(id, EM_R("userDisabled"), null);
  5112.       if (opType != OP_NONE) {
  5113.         operation = OP_NONE;
  5114.         action = EM_ITEM_CANCEL;
  5115.       }
  5116.     }
  5117.     else {
  5118.       if (userDisabled == "true")
  5119.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_ENABLE));
  5120.       if (opType != OP_NEEDS_ENABLE) {
  5121.         operation = OP_NEEDS_ENABLE;
  5122.         action = EM_ITEM_ENABLED;
  5123.       }
  5124.     }
  5125.  
  5126.     if (action) {
  5127.       this._setOp(id, operation);
  5128.       this._notifyAction(id, action);
  5129.     }
  5130.     else {
  5131.       ds.updateProperty(id, "satisfiesDependencies");
  5132.       this._updateDependentItemsForID(id);
  5133.     }
  5134.   },
  5135.   
  5136.   /**
  5137.    * Sets an item to be disabled by the user. If the item is already disabled
  5138.    * this clears the needs-disable operation for the next restart.
  5139.    * See "Note on appDisabled and userDisabled property arcs" above.
  5140.    * @param   id
  5141.    *          The ID of the item to be disabled by the user.
  5142.    */
  5143.   disableItem: function(id) {
  5144.     var ds = this.datasource;
  5145.     var opType = ds.getItemProperty(id, "opType");
  5146.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5147.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5148.  
  5149.     var operation, action;
  5150.     // if this item is already disabled don't set a pending operation - instead
  5151.     // immediately disable it and reset the operation type if needed.
  5152.     if (userDisabled == OP_NEEDS_ENABLE || userDisabled == "true" ||
  5153.         appDisabled == OP_NEEDS_ENABLE) {
  5154.       if (userDisabled != "true")
  5155.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5156.       if (opType != OP_NONE) {
  5157.         operation = OP_NONE;
  5158.         action = EM_ITEM_CANCEL;
  5159.       }
  5160.     }
  5161.     else {
  5162.       if (userDisabled == OP_NONE)
  5163.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_DISABLE));
  5164.       if (opType != OP_NEEDS_DISABLE) {
  5165.         operation = OP_NEEDS_DISABLE;
  5166.         action = EM_ITEM_DISABLED;
  5167.       }
  5168.     }
  5169.  
  5170.     if (action) {
  5171.       this._setOp(id, operation);
  5172.       this._notifyAction(id, action);
  5173.     }
  5174.     else {
  5175.       ds.updateProperty(id, "satisfiesDependencies");
  5176.       this._updateDependentItemsForID(id);
  5177.     }
  5178.   },
  5179.   
  5180.   /**
  5181.    * Determines whether an item should be disabled by the application.
  5182.    * @param   id
  5183.    *          The ID of the item to check
  5184.    */
  5185.   _isUsableItem: function(id) {
  5186.     var ds = this.datasource;
  5187.     return ((!gCheckCompatibility || ds.getItemProperty(id, "compatible") == "true") &&
  5188.             ds.getItemProperty(id, "blocklisted") == "false" &&
  5189.             ds.getItemProperty(id, "satisfiesDependencies") == "true");
  5190.   },
  5191.  
  5192.   /**
  5193.    * Sets an item's dependent items disabled state for the app based on whether
  5194.    * its dependencies are met and the item is compatible.
  5195.    * @param   id
  5196.    *          The ID of the item whose dependent items will be checked
  5197.    */
  5198.   _updateDependentItemsForID: function(id) {
  5199.     var ds = this.datasource;
  5200.     var dependentItems = this.getDependentItemListForID(id, true, { });
  5201.     for (var i = 0; i < dependentItems.length; ++i) {
  5202.       var dependentID = dependentItems[i].id;
  5203.       ds.updateProperty(dependentID, "satisfiesDependencies");
  5204.       if (this._isUsableItem(dependentID))
  5205.         this._appEnableItem(dependentID);
  5206.       else
  5207.         this._appDisableItem(dependentID);
  5208.     }
  5209.   },
  5210.  
  5211.   /**
  5212.    * Notify observers of a change to an item that has been requested by the
  5213.    * user. 
  5214.    */
  5215.   _notifyAction: function(id, reason) {
  5216.     gOS.notifyObservers(this.datasource.getItemForID(id), 
  5217.                         EM_ACTION_REQUESTED_TOPIC, reason);
  5218.   },
  5219.   
  5220.   /**
  5221.    * See nsIExtensionManager.idl
  5222.    */
  5223.   update: function(items, itemCount, versionUpdateOnly, listener) {
  5224.     var appID = gApp.ID;
  5225.     var appVersion = gApp.version;
  5226.  
  5227.     if (items.length == 0)
  5228.       items = this.getItemList(nsIUpdateItem.TYPE_ADDON, { });
  5229.  
  5230.     var updater = new ExtensionItemUpdater(appID, appVersion, this);
  5231.     updater.checkForUpdates(items, items.length, versionUpdateOnly, listener);
  5232.   },
  5233.  
  5234.  
  5235.   /**
  5236.    * Checks for changes to the blocklist using the local blocklist file,
  5237.    * application disables / enables items that have been added / removed from
  5238.    * the blocklist, and if there are additions to the blocklist this will
  5239.    * inform the user by displaying a list of the items added.
  5240.    *
  5241.    * XXXrstrong - this method is not terribly useful and was added so we can
  5242.    * trigger this check from the additional timer used by blocklisting.
  5243.    */
  5244.   checkForBlocklistChanges: function() {
  5245.     var ds = this.datasource;
  5246.     var items = this.getItemList(nsIUpdateItem.TYPE_ADDON, { });
  5247.     for (var i = 0; i < items.length; ++i) {
  5248.       var id = items[i].id;
  5249.       ds.updateProperty(id, "blocklisted");
  5250.       if (this._isUsableItem(id))
  5251.         this._appEnableItem(id);
  5252.     }
  5253.  
  5254.     items = ds.getBlocklistedItemList(null, null, nsIUpdateItem.TYPE_ADDON,
  5255.                                       false);
  5256.     for (i = 0; i < items.length; ++i)
  5257.       this._appDisableItem(items[i].id);
  5258.  
  5259.     // show the blocklist notification window if there are new blocklist items.
  5260.     if (items.length > 0)
  5261.       showBlocklistMessage(items, false);
  5262.   },
  5263.  
  5264.   /**
  5265.    * @returns An enumeration of all registered Install Locations.
  5266.    */
  5267.   get installLocations () {
  5268.     return InstallLocations.enumeration;
  5269.   },
  5270.   
  5271.   /**
  5272.    * Gets the Install Location where a visible Item is stored.
  5273.    * @param   id
  5274.    *          The GUID of the item to locate an Install Location for.
  5275.    * @returns The Install Location object where the item is stored.
  5276.    */
  5277.   getInstallLocation: function(id) {
  5278.     var key = this.datasource.visibleItems[id];
  5279.     return key ? InstallLocations.get(this.datasource.visibleItems[id]) : null;
  5280.   },
  5281.   
  5282.   /**
  5283.    * Gets a nsIUpdateItem for the item with the specified id.
  5284.    * @param   id
  5285.    *          The GUID of the item to construct a nsIUpdateItem for.
  5286.    * @returns The nsIUpdateItem representing the item.
  5287.    */
  5288.   getItemForID: function(id) {
  5289.     return this.datasource.getItemForID(id);
  5290.   },
  5291.   
  5292.   /**
  5293.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  5294.    * on another item.
  5295.    * @param   id
  5296.    *          The ID of the item that other items depend on.
  5297.    * @param   includeDisabled
  5298.    *          Whether to include disabled items in the set returned.
  5299.    * @param   countRef
  5300.    *          The XPCJS reference to the number of items returned.
  5301.    * @returns An array of installed nsIUpdateItems that depend on the item
  5302.    *          specified by the id parameter.
  5303.    */
  5304.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  5305.     return this.datasource.getDependentItemListForID(id, includeDisabled, countRef);
  5306.   },
  5307.  
  5308.   /**
  5309.    * Retrieves a list of nsIUpdateItems of items matching the specified type.
  5310.    * @param   type
  5311.    *          The type of item to return.
  5312.    * @param   countRef
  5313.    *          The XPCJS reference to the number of items returned.
  5314.    * @returns An array of nsIUpdateItems matching the id/type filter.
  5315.    */
  5316.   getItemList: function(type, countRef) {
  5317.     return this.datasource.getItemList(type, countRef);
  5318.   },
  5319.  
  5320.   /**  
  5321.    * See nsIExtensionManager.idl
  5322.    */
  5323.   getIncompatibleItemList: function(id, version, type, includeDisabled, 
  5324.                                     countRef) {
  5325.     var items = this.datasource.getIncompatibleItemList(id, version ? version : undefined,
  5326.                                                         type, includeDisabled);
  5327.     countRef.value = items.length;
  5328.     return items;
  5329.   },
  5330.   
  5331.   /**
  5332.    * Move an Item to the index of another item in its container.
  5333.    * @param   movingID
  5334.    *          The ID of the item to be moved.
  5335.    * @param   destinationID
  5336.    *          The ID of an item to move another item to.
  5337.    */
  5338.   moveToIndexOf: function(movingID, destinationID) {
  5339.     this.datasource.moveToIndexOf(movingID, destinationID);
  5340.   },
  5341.  
  5342.   /**
  5343.    * Sorts addons of the specified type by the specified property starting from
  5344.    * the top of their container. If the addons are already sorted then no action
  5345.    * is performed.
  5346.    * @param   type
  5347.    *          The nsIUpdateItem type of the items to sort.
  5348.    * @param   propertyName
  5349.    *          The RDF property name used for sorting.
  5350.    * @param   isAscending
  5351.    *          true to sort ascending and false to sort descending
  5352.    */
  5353.   sortTypeByProperty: function(type, propertyName, isAscending) {
  5354.     this.datasource.sortTypeByProperty(type, propertyName, isAscending);
  5355.   },
  5356.  
  5357.   /////////////////////////////////////////////////////////////////////////////    
  5358.   // Downloads
  5359.   _transactions: [],
  5360.   _downloadCount: 0,
  5361.   
  5362.   /**
  5363.    * Ask the user if they really want to quit the application, since this will 
  5364.    * cancel one or more Extension/Theme downloads.
  5365.    * @param   subject
  5366.    *          A nsISupportsPRBool which this function sets to false if the user
  5367.    *          wishes to cancel all active downloads and quit the application,
  5368.    *          false otherwise.
  5369.    */
  5370.   _confirmCancelDownloadsOnQuit: function(subject) {
  5371.     if (this._downloadCount > 0) {
  5372.       // The observers will be notified again after this so set the download
  5373.       // count to 0 to prevent this dialog from being displayed again.
  5374.       this._downloadCount = 0;
  5375.       var result;
  5376. //@line 5462 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  5377.       result = this._confirmCancelDownloads(this._downloadCount, 
  5378.                                             "quitCancelDownloadsAlertTitle",
  5379.                                             "quitCancelDownloadsAlertMsgMultiple",
  5380.                                             "quitCancelDownloadsAlertMsg",
  5381.                                             "dontQuitButtonWin");
  5382. //@line 5474 "/build/buildd/firefox-2.0.0.3+1/toolkit/mozapps/extensions/src/nsExtensionManager.js.in"
  5383.       if (!result)
  5384.         this._cancelDownloads();
  5385.       if (subject instanceof Components.interfaces.nsISupportsPRBool)
  5386.         subject.data = result;
  5387.     }
  5388.   },
  5389.   
  5390.   /**
  5391.    * Ask the user if they really want to go offline, since this will cancel 
  5392.    * one or more Extension/Theme downloads.
  5393.    * @param   subject
  5394.    *          A nsISupportsPRBool which this function sets to false if the user
  5395.    *          wishes to cancel all active downloads and go offline, false
  5396.    *          otherwise.
  5397.    */
  5398.   _confirmCancelDownloadsOnOffline: function(subject) {
  5399.     if (this._downloadCount > 0) {
  5400.       result = this._confirmCancelDownloads(this._downloadCount,
  5401.                                             "offlineCancelDownloadsAlertTitle",
  5402.                                             "offlineCancelDownloadsAlertMsgMultiple",
  5403.                                             "offlineCancelDownloadsAlertMsg",
  5404.                                             "dontGoOfflineButton");
  5405.       if (!result)
  5406.         this._cancelDownloads();
  5407.       if (subject instanceof Components.interfaces.nsISupportsPRBool)
  5408.         subject.data = result;
  5409.     }
  5410.   },
  5411.   
  5412.   /**
  5413.    * Cancels all active downloads and removes them from the applicable UI.
  5414.    */
  5415.   _cancelDownloads: function() {
  5416.     for (var i = 0; i < this._transactions.length; ++i)
  5417.       gOS.notifyObservers(this._transactions[i], "xpinstall-progress", "cancel");
  5418.  
  5419.     this._removeAllDownloads();
  5420.   },
  5421.  
  5422.   /**
  5423.    * Ask the user whether or not they wish to cancel the Extension/Theme
  5424.    * downloads which are currently under way.
  5425.    * @param   count
  5426.    *          The number of active downloads.
  5427.    * @param   title
  5428.    *          The key of the title for the message box to be displayed
  5429.    * @param   cancelMessageMultiple
  5430.    *          The key of the message to be displayed in the message box
  5431.    *          when there are > 1 active downloads.
  5432.    * @param   cancelMessageSingle
  5433.    *          The key of the message to be displayed in the message box
  5434.    *          when there is just one active download.
  5435.    * @param   dontCancelButton
  5436.    *          The key of the label to be displayed on the "Don't Cancel 
  5437.    *          Downloads" button.
  5438.    */
  5439.   _confirmCancelDownloads: function(count, title, cancelMessageMultiple, 
  5440.                                     cancelMessageSingle, dontCancelButton) {
  5441.     var bundle = BundleManager.getBundle(URI_DOWNLOADS_PROPERTIES);
  5442.     var title = bundle.GetStringFromName(title);
  5443.     var message, quitButton;
  5444.     if (count > 1) {
  5445.       message = bundle.formatStringFromName(cancelMessageMultiple, [count], 1);
  5446.       quitButton = bundle.formatStringFromName("cancelDownloadsOKTextMultiple", [count], 1);
  5447.     }
  5448.     else {
  5449.       message = bundle.GetStringFromName(cancelMessageSingle);
  5450.       quitButton = bundle.GetStringFromName("cancelDownloadsOKText");
  5451.     }
  5452.     var dontQuitButton = bundle.GetStringFromName(dontCancelButton);
  5453.     
  5454.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  5455.                        .getService(Components.interfaces.nsIWindowMediator);
  5456.     var win = wm.getMostRecentWindow("Extension:Manager");
  5457.     const nsIPromptService = Components.interfaces.nsIPromptService;
  5458.     var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  5459.                        .getService(nsIPromptService);
  5460.     var flags = (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_0) +
  5461.                 (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_1);
  5462.     var rv = ps.confirmEx(win, title, message, flags, quitButton, dontQuitButton, null, null, { });
  5463.     return rv == 1;
  5464.   },
  5465.   
  5466.   /** 
  5467.    * Adds a set of Item Downloads to the Manager and starts the download
  5468.    * operation.
  5469.    * @param   items
  5470.    *          An array of nsIUpdateItems to begin downlading.
  5471.    * @param   itemCount
  5472.    *          The length of |items|
  5473.    * @param   fromChrome
  5474.    *          true when called from chrome
  5475.    *          false when not called from chrome (e.g. web page)
  5476.    */
  5477.   addDownloads: function(items, itemCount, fromChrome) { 
  5478.     var ds = this.datasource;
  5479.     // Add observers only if they aren't already added for an active download
  5480.     if (this._downloadCount == 0) {
  5481.       gOS.addObserver(this, "offline-requested", false);
  5482.       gOS.addObserver(this, "quit-application-requested", false);
  5483.     }
  5484.     this._downloadCount += itemCount;
  5485.     
  5486.     var urls = [];
  5487.     var hashes = [];
  5488.     var txn = new ItemDownloadTransaction(this);
  5489.     for (var i = 0; i < itemCount; ++i) {
  5490.       var currItem = items[i];
  5491.       var txnID = Math.round(Math.random() * 100);
  5492.       txn.addDownload(currItem, txnID);
  5493.       this._transactions.push(txn);
  5494.       urls.push(currItem.xpiURL);
  5495.       hashes.push(currItem.xpiHash ? currItem.xpiHash : null);
  5496.       // if this is an update remove the update metadata to prevent it from
  5497.       // being updated during an install.
  5498.       if (fromChrome) {
  5499.         var id = currItem.id
  5500.         ds.setItemProperty(id, EM_R("availableUpdateURL"), null);
  5501.         ds.setItemProperty(id, EM_R("availableUpdateHash"), null);
  5502.         ds.setItemProperty(id, EM_R("availableUpdateVersion"), null);
  5503.         ds.updateProperty(id, "availableUpdateURL");
  5504.         ds.updateProperty(id, "updateable"); 
  5505.       }
  5506.       var id = fromChrome ? PREFIX_ITEM_URI + currItem.id : currItem.xpiURL;
  5507.       ds.updateDownloadState(id, "waiting");
  5508.     }
  5509.     
  5510.     if (fromChrome) {
  5511.       // Initiate an install from chrome
  5512.       var xpimgr = 
  5513.           Components.classes["@mozilla.org/xpinstall/install-manager;1"].
  5514.           createInstance(Components.interfaces.nsIXPInstallManager);
  5515.       xpimgr.initManagerWithHashes(urls, hashes, urls.length, txn);
  5516.     }
  5517.     else
  5518.       gOS.notifyObservers(txn, "xpinstall-progress", "open");
  5519.   },
  5520.   
  5521.   /**
  5522.    * Removes a download of a URL.
  5523.    * @param   url
  5524.    *          The URL of the item being downloaded to remove.
  5525.    */
  5526.   removeDownload: function(url) {
  5527.     for (var i = 0; i < this._transactions.length; ++i) {
  5528.       if (this._transactions[i].containsURL(url)) {
  5529.         this._transactions[i].removeDownload(url);
  5530.         return;
  5531.       }
  5532.     } 
  5533.   },
  5534.   
  5535.   /**
  5536.    * Remove all downloads from all transactions.
  5537.    */
  5538.   _removeAllDownloads: function() {
  5539.     for (var i = 0; i < this._transactions.length; ++i)
  5540.       this._transactions[i].removeAllDownloads();
  5541.   },
  5542.  
  5543.   /**
  5544.    * Download Operation State has changed from one to another. 
  5545.    * 
  5546.    * The nsIXPIProgressDialog implementation in the download transaction object
  5547.    * forwards notifications through these methods which we then pass on to any
  5548.    * front end objects implementing nsIExtensionDownloadListener that 
  5549.    * are listening. We maintain the master state of download operations HERE, 
  5550.    * not in the front end, because if the user closes the extension or theme 
  5551.    * managers during the downloads we need to maintain state and not terminate
  5552.    * the download/install process. 
  5553.    *
  5554.    * @param   transaction
  5555.    *          The ItemDownloadTransaction object receiving the download 
  5556.    *          notifications from XPInstall.
  5557.    * @param   addon
  5558.    *          An object representing nsIUpdateItem for the addon being updated
  5559.    * @param   state
  5560.    *          The state we are entering
  5561.    * @param   value
  5562.    *          ???
  5563.    */
  5564.   onStateChange: function(transaction, addon, state, value) {
  5565.     for (var i = 0; i < this._updateListeners.length; ++i)
  5566.       this._updateListeners[i].onStateChange(addon, state, value);
  5567.     var ds = this.datasource;
  5568.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5569.     const nsIXPIProgressDialog = Components.interfaces.nsIXPIProgressDialog;
  5570.     switch (state) {
  5571.     case nsIXPIProgressDialog.DOWNLOAD_START:
  5572.       ds.updateDownloadState(id, "downloading");
  5573.       break;
  5574.     case nsIXPIProgressDialog.INSTALL_START:
  5575.       ds.updateDownloadState(id, "finishing");
  5576.       ds.updateDownloadProgress(id, null);
  5577.       break;
  5578.     case nsIXPIProgressDialog.INSTALL_DONE:
  5579.       --this._downloadCount;
  5580.       // From nsInstall.h
  5581.       // SUCCESS        = 0
  5582.       // REBOOT_NEEDED  = 999
  5583.       // USER_CANCELLED = -210
  5584.       if (value != 0 && value != 999 && value != -210 && id != addon.xpiURL) {
  5585.         ds.updateDownloadState(id, "failure");
  5586.         ds.updateDownloadProgress(id, null);
  5587.       }
  5588.       this.removeDownload(addon.xpiURL);
  5589.       break;
  5590.     case nsIXPIProgressDialog.DIALOG_CLOSE:
  5591.       for (var i = 0; i < this._transactions.length; ++i) {
  5592.         if (this._transactions[i].id == transaction.id) {
  5593.           this._transactions.splice(i, 1);
  5594.           delete transaction;
  5595.           // Remove the observers when all transactions have completed.
  5596.           if (this._transactions.length == 0) {
  5597.             gOS.removeObserver(this, "offline-requested");
  5598.             gOS.removeObserver(this, "quit-application-requested");
  5599.           }
  5600.           break;
  5601.         }
  5602.       }
  5603.       break;
  5604.     }
  5605.   },
  5606.   
  5607.   onProgress: function(addon, value, maxValue) {
  5608.     for (var i = 0; i < this._updateListeners.length; ++i)
  5609.       this._updateListeners[i].onProgress(addon, value, maxValue);
  5610.     
  5611.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5612.     var progress = Math.round((value / maxValue) * 100);
  5613.     this.datasource.updateDownloadProgress(id, progress);
  5614.   },
  5615.  
  5616.   _updateListeners: [],
  5617.   addUpdateListener: function(listener) {
  5618.     for (var i = 0; i < this._updateListeners.length; ++i) {
  5619.       if (this._updateListeners[i] == listener)
  5620.         return i;
  5621.     }
  5622.     this._updateListeners.push(listener);
  5623.     return this._updateListeners.length - 1;
  5624.   },
  5625.   
  5626.   removeUpdateListenerAt: function(index) {
  5627.     this._updateListeners.splice(index, 1);
  5628.   },
  5629.  
  5630.   /**
  5631.    * The Extensions RDF Datasource
  5632.    */
  5633.   _ds: null,
  5634.  
  5635.   /** 
  5636.    * Loads the Extensions Datasource. This should not be called unless: 
  5637.    * - a piece of Extensions UI is being shown, or
  5638.    * - on startup and there has been a change to an Install Location
  5639.    * ... it should NOT be called on every startup!
  5640.    */
  5641.   _ensureDS: function() {
  5642.     if (!this._ds) {
  5643.       this._ds = new ExtensionsDataSource(this);
  5644.       if (this._ds)
  5645.         this._ds.loadExtensions();
  5646.     }
  5647.   },
  5648.  
  5649.   /**
  5650.    * See nsIExtensionManager.idl
  5651.    */
  5652.   get datasource() {
  5653.     this._ensureDS();
  5654.     return this._ds.QueryInterface(Components.interfaces.nsIRDFDataSource);
  5655.   },
  5656.   
  5657.   /**
  5658.    * See nsIClassInfo.idl
  5659.    */
  5660.   getInterfaces: function(count) {
  5661.     var interfaces = [Components.interfaces.nsIExtensionManager,
  5662.                       Components.interfaces.nsIXPIProgressDialog,
  5663.                       Components.interfaces.nsIObserver];
  5664.     count.value = interfaces.length;
  5665.     return interfaces;
  5666.   },
  5667.   getHelperForLanguage: function(language) { 
  5668.     return null;
  5669.   },
  5670.   get contractID() {
  5671.     return "@mozilla.org/extensions/manager;1";
  5672.   },
  5673.   get classDescription() {
  5674.     return "Extension Manager";
  5675.   },
  5676.   get classID() {
  5677.     return Components.ID("{8A115FAA-7DCB-4e8f-979B-5F53472F51CF}");
  5678.   },
  5679.   get implementationLanguage() {
  5680.     return Components.interfaces.nsIProgrammingLanguage.JAVASCRIPT;
  5681.   },
  5682.   get flags() {
  5683.     return Components.interfaces.nsIClassInfo.SINGLETON;
  5684.   },
  5685.  
  5686.   /**
  5687.    * See nsISupports.idl
  5688.    */
  5689.   QueryInterface: function(iid) {
  5690.     if (!iid.equals(Components.interfaces.nsIExtensionManager) &&
  5691.         !iid.equals(Components.interfaces.nsIExtensionManager_MOZILLA_1_8_BRANCH) &&
  5692.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  5693.         !iid.equals(Components.interfaces.nsIObserver) &&
  5694.         !iid.equals(Components.interfaces.nsISupports))
  5695.       throw Components.results.NS_ERROR_NO_INTERFACE;
  5696.     return this;
  5697.   }
  5698. };
  5699.  
  5700. /**
  5701.  * This object implements nsIXPIProgressDialog and represents a collection of
  5702.  * XPI/JAR download and install operations. There is one 
  5703.  * ItemDownloadTransaction per back-end XPInstallManager object. We maintain
  5704.  * a collection of separate transaction objects because it's possible to have
  5705.  * multiple separate XPInstall download/install operations going on 
  5706.  * simultaneously, each with its own XPInstallManager instance. For instance
  5707.  * you could start downloading two extensions and then download a theme. Each
  5708.  * of these operations would open the appropriate FE and have to be able to
  5709.  * track each operation independently.
  5710.  * 
  5711.  * @constructor
  5712.  */
  5713. function ItemDownloadTransaction(manager) {
  5714.   this._manager = manager;
  5715.   this._downloads = [];
  5716. }
  5717. ItemDownloadTransaction.prototype = {
  5718.   _manager    : null,
  5719.   _downloads  : [],
  5720.   id          : -1,
  5721.   
  5722.   /**
  5723.    * Add a download to this transaction
  5724.    * @param   addon
  5725.    *          An object implementing nsIUpdateItem for the item to be downloaded
  5726.    * @param   id
  5727.    *          The integer identifier of this transaction
  5728.    */
  5729.   addDownload: function(addon, id) {
  5730.     this._downloads.push({ addon: addon, waiting: true });
  5731.     this._manager.datasource.addDownload(addon);
  5732.     this.id = id;
  5733.   },
  5734.   
  5735.   /**
  5736.    * Removes a download from this transaction
  5737.    * @param   url
  5738.    *          The URL to remove
  5739.    */
  5740.   removeDownload: function(url) {
  5741.     this._manager.datasource.removeDownload(url);
  5742.   },
  5743.   
  5744.   /**
  5745.    * Remove all downloads from this transaction
  5746.    */
  5747.   removeAllDownloads: function() {
  5748.     for (var i = 0; i < this._downloads.length; ++i) {
  5749.       var addon = this._downloads[i].addon;
  5750.       this.removeDownload(addon.xpiURL);
  5751.     }
  5752.   },
  5753.   
  5754.   /**
  5755.    * Determine if this transaction is handling the download of a url.
  5756.    * @param   url
  5757.    *          The URL to look for
  5758.    * @returns true if this transaction is downloading the supplied url.
  5759.    */
  5760.   containsURL: function(url) {
  5761.     for (var i = 0; i < this._downloads.length; ++i) {
  5762.       if (this._downloads[i].addon.xpiURL == url)
  5763.         return true;
  5764.     }
  5765.     return false;
  5766.   },
  5767.  
  5768.   /**
  5769.    * See nsIXPIProgressDialog.idl
  5770.    */
  5771.   onStateChange: function(index, state, value) {
  5772.     this._manager.onStateChange(this, this._downloads[index].addon, 
  5773.                                 state, value);
  5774.   },
  5775.   
  5776.   /**
  5777.    * See nsIXPIProgressDialog.idl
  5778.    */
  5779.   onProgress: function(index, value, maxValue) { 
  5780.     this._manager.onProgress(this._downloads[index].addon, value, maxValue);
  5781.   },
  5782.   
  5783.   /////////////////////////////////////////////////////////////////////////////
  5784.   // nsISupports
  5785.   QueryInterface: function(iid) {
  5786.     if (!iid.equals(Components.interfaces.nsIXPIProgressDialog) &&
  5787.         !iid.equals(Components.interfaces.nsISupports))
  5788.       throw Components.results.NS_ERROR_NO_INTERFACE;
  5789.     return this;
  5790.   }
  5791. };
  5792.  
  5793. /**
  5794.  * A listener object to the update check process that routes notifications to
  5795.  * the right places and keeps the datasource up to date.
  5796.  */
  5797. function AddonUpdateCheckListener(listener, datasource) {
  5798.   this._listener = listener;
  5799.   this._ds = datasource;
  5800. }
  5801. AddonUpdateCheckListener.prototype = {
  5802.   _listener: null,
  5803.   _ds: null,
  5804.   
  5805.   onUpdateStarted: function() {
  5806.     if (this._listener)
  5807.       this._listener.onUpdateStarted();
  5808.     this._ds.onUpdateStarted();
  5809.   },
  5810.   
  5811.   onUpdateEnded: function() {
  5812.     if (this._listener)
  5813.       this._listener.onUpdateEnded();
  5814.     this._ds.onUpdateEnded();
  5815.   },
  5816.   
  5817.   onAddonUpdateStarted: function(addon) {
  5818.     if (this._listener)
  5819.       this._listener.onAddonUpdateStarted(addon);
  5820.     this._ds.onAddonUpdateStarted(addon);
  5821.   },
  5822.   
  5823.   onAddonUpdateEnded: function(addon, status) {
  5824.     if (this._listener)
  5825.       this._listener.onAddonUpdateEnded(addon, status);
  5826.     this._ds.onAddonUpdateEnded(addon, status);
  5827.   }
  5828. };
  5829.  
  5830. ///////////////////////////////////////////////////////////////////////////////
  5831. //
  5832. // ExtensionItemUpdater
  5833. //
  5834. function ExtensionItemUpdater(aTargetAppID, aTargetAppVersion, aEM) 
  5835. {
  5836.   this._appID = aTargetAppID;
  5837.   this._appVersion = aTargetAppVersion;
  5838.   this._emDS = aEM._ds;
  5839.   this._em = aEM;
  5840.  
  5841.   getVersionChecker();
  5842. }
  5843.  
  5844. ExtensionItemUpdater.prototype = {
  5845.   _appID              : "",
  5846.   _appVersion         : "",
  5847.   _emDS               : null,
  5848.   _em                 : null,
  5849.   _versionUpdateOnly  : 0,
  5850.   _items              : [],
  5851.   _listener           : null,
  5852.   _background         : false,
  5853.   
  5854.   /////////////////////////////////////////////////////////////////////////////
  5855.   // ExtensionItemUpdater
  5856.   //
  5857.   // When we check for updates to an item, there are two pieces of information
  5858.   // that are returned - 1) info about the newest available version, if any,
  5859.   // and 2) info about the currently installed version. The latter is provided
  5860.   // primarily to inform the client of changes to the application compatibility 
  5861.   // metadata for the current item. Depending on the situation, either 2 or 
  5862.   // 1&2 may be what is required.
  5863.   //
  5864.   // Callers:
  5865.   //  1 - nsUpdateService.js, user event
  5866.   //      User clicked on the update icon to invoke an update check, 
  5867.   //      user clicked on an Extension/Theme and clicked "Update". In this
  5868.   //      case we want to update compatibility metadata about the installed
  5869.   //      version, and look for newer versions to offer. 
  5870.   //  2 - nsUpdateService.js, background event
  5871.   //      Timer fired, background update is being performed. In this case
  5872.   //      we also want to update compatibility metadata and look for newer
  5873.   //      versions.
  5874.   //  3 - Mismatch
  5875.   //      User upgraded to a newer version of the app, update compatibility
  5876.   //      metadata and look for newer versions.
  5877.   //  4 - Install Phone Home
  5878.   //      User installed an item that was deemed incompatible based only
  5879.   //      on the information provided in the item's install.rdf manifest, 
  5880.   //      we look ONLY for compatibility updates in this case to determine
  5881.   //      whether or not the item can be installed.
  5882.   //  
  5883.   checkForUpdates: function(aItems, aItemCount, aVersionUpdateOnly, 
  5884.                             aListener) {
  5885.     this._listener = new AddonUpdateCheckListener(aListener, this._emDS);
  5886.     if (this._listener)
  5887.       this._listener.onUpdateStarted();
  5888.     this._versionUpdateOnly = aVersionUpdateOnly;
  5889.     this._items = aItems;
  5890.     this._responseCount = aItemCount;
  5891.     
  5892.     // This is the number of extensions/themes/etc that we found updates for.
  5893.     this._updateCount = 0;
  5894.  
  5895.     for (var i = 0; i < aItemCount; ++i) {
  5896.       var e = this._items[i];
  5897.       if (this._listener)
  5898.         this._listener.onAddonUpdateStarted(e);
  5899.       (new RDFItemUpdater(this)).checkForUpdates(e, aVersionUpdateOnly);
  5900.     }
  5901.   },
  5902.   
  5903.   /////////////////////////////////////////////////////////////////////////////
  5904.   // ExtensionItemUpdater
  5905.   _applyVersionUpdates: function(aLocalItem, aRemoteItem) {
  5906.     var targetAppInfo = this._emDS.getTargetApplicationInfo(aLocalItem.id, this._emDS);
  5907.     // If targetAppInfo is null this is for a new install. If the local item's
  5908.     // maxVersion does not equal the targetAppInfo maxVersion then this is for
  5909.     // an upgrade. In both of these cases return true if the remotely specified
  5910.     // maxVersion is greater than the local item's maxVersion.
  5911.     if (!targetAppInfo ||
  5912.         gVersionChecker.compare(aLocalItem.maxAppVersion, targetAppInfo.maxVersion) != 0) {
  5913.       if (gVersionChecker.compare(aLocalItem.maxAppVersion, aRemoteItem.maxAppVersion) < 0)
  5914.         return true;
  5915.       else
  5916.         return false;
  5917.     }
  5918.  
  5919.     if (gVersionChecker.compare(targetAppInfo.maxVersion, aRemoteItem.maxAppVersion) < 0) {
  5920.       // Remotely specified maxVersion is newer than the maxVersion 
  5921.       // for the installed Extension. Apply that change to the datasources.
  5922.       this._emDS.updateTargetAppInfo(aLocalItem.id, aRemoteItem.minAppVersion,
  5923.                                      aRemoteItem.maxAppVersion);
  5924.  
  5925.       // If we got here through |checkForMismatches|, this extension has
  5926.       // already been disabled, re-enable it.
  5927.       var op = StartupCache.entries[aLocalItem.installLocationKey][aLocalItem.id].op;
  5928.       if (op == OP_NEEDS_DISABLE ||
  5929.           this._emDS.getItemProperty(aLocalItem.id, "appDisabled") == "true")
  5930.         this._em._appEnableItem(aLocalItem.id);
  5931.       return true;
  5932.     }
  5933.     else if (this._versionUpdateOnly == 2)
  5934.       this._emDS.updateTargetAppInfo(aLocalItem.id, aRemoteItem.minAppVersion,
  5935.                                      aRemoteItem.maxAppVersion);
  5936.     return false;
  5937.   },
  5938.   
  5939.   _isValidUpdate: function(aLocalItem, aRemoteItem) {
  5940.     var appExtensionsVersion = gApp.version;
  5941.  
  5942.     // Check if the update will only run on a newer version of Firefox. 
  5943.     if (aRemoteItem.minAppVersion && 
  5944.         gVersionChecker.compare(appExtensionsVersion, aRemoteItem.minAppVersion) < 0) 
  5945.       return false;
  5946.  
  5947.     // Check if the update will only run on an older version of Firefox. 
  5948.     if (aRemoteItem.maxAppVersion && 
  5949.         gVersionChecker.compare(appExtensionsVersion, aRemoteItem.maxAppVersion) > 0) 
  5950.       return false;
  5951.  
  5952.     if (this._emDS.isBlocklisted(aRemoteItem.id, aRemoteItem.version,
  5953.                                  undefined, undefined))
  5954.       return false;
  5955.     
  5956.     return true;
  5957.   },
  5958.   
  5959.   checkForDone: function(item, status) {
  5960.     if (this._background &&
  5961.         status == nsIAddonUpdateCheckListener.STATUS_UPDATE) {
  5962.       var lastupdate = this._emDS.getItemProperty(item.id, "availableUpdateVersion");
  5963.       if (lastupdate != item.version)
  5964.         gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, true);
  5965.     }
  5966.     if (this._listener) {
  5967.       try {
  5968.         this._listener.onAddonUpdateEnded(item, status);
  5969.       }
  5970.       catch (e) {
  5971.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onAddonUpdateEnded: " + e);
  5972.       }
  5973.     }
  5974.     if (--this._responseCount == 0 && this._listener) {
  5975.       try {
  5976.         this._listener.onUpdateEnded();
  5977.       }
  5978.       catch (e) {
  5979.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onUpdateEnded: " + e);
  5980.       }
  5981.     }
  5982.   },
  5983. };
  5984.  
  5985. function RDFItemUpdater(aUpdater) {
  5986.   this._updater = aUpdater;
  5987. }
  5988.  
  5989. RDFItemUpdater.prototype = {
  5990.   _updater            : null,
  5991.   _versionUpdateOnly  : 0,
  5992.   _item               : null,
  5993.   
  5994.   checkForUpdates: function(aItem, aVersionUpdateOnly) {
  5995.     // A preference setting can disable updating for this item
  5996.     try {
  5997.       if (!gPref.getBoolPref(PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, aItem.id))) {
  5998.         var status = nsIAddonUpdateCheckListener.STATUS_DISABLED;
  5999.         this._updater.checkForDone(aItem, status);
  6000.         return;
  6001.       }
  6002.     }
  6003.     catch (e) { }
  6004.  
  6005.     // Items managed by the app are not checked for updates.
  6006.     var emDS = this._updater._emDS;
  6007.     if (emDS.getItemProperty(aItem.id, "appManaged") == "true") {
  6008.       var status = nsIAddonUpdateCheckListener.STATUS_APP_MANAGED;
  6009.       this._updater.checkForDone(aItem, status);
  6010.       return;
  6011.     }
  6012.  
  6013.     // Items that have a pending install, uninstall, or upgrade are not checked
  6014.     // for updates.
  6015.     var opType = emDS.getItemProperty(aItem.id, "opType");
  6016.     if (opType == OP_NEEDS_INSTALL || opType == OP_NEEDS_UNINSTALL ||
  6017.         opType == OP_NEEDS_UPGRADE) {
  6018.       var status = nsIAddonUpdateCheckListener.STATUS_PENDING_OP;
  6019.       this._updater.checkForDone(aItem, status);
  6020.       return;
  6021.     }
  6022.  
  6023.     var installLocation = InstallLocations.get(emDS.getInstallLocationKey(aItem.id));
  6024.     // Don't check items for updates that are installed in a location that is
  6025.     // not managed by the app.
  6026.     if (installLocation && (installLocation.name == "winreg-app-global" ||
  6027.         installLocation.name == "winreg-app-user")) {
  6028.       var status = nsIAddonUpdateCheckListener.STATUS_NOT_MANAGED;
  6029.       this._updater.checkForDone(aItem, status);
  6030.       return;
  6031.     }
  6032.  
  6033.     // Don't check items for updates if the location can't be written to except
  6034.     // when performing a version only update.
  6035.     if (!aVersionUpdateOnly && (!installLocation || !installLocation.canAccess)) {
  6036.       var status = nsIAddonUpdateCheckListener.STATUS_READ_ONLY;
  6037.       this._updater.checkForDone(aItem, status);
  6038.       return;
  6039.     }
  6040.  
  6041.     this._versionUpdateOnly = aVersionUpdateOnly;
  6042.     this._item = aItem;
  6043.   
  6044.     var itemStatus;
  6045.     if (emDS.getItemProperty(aItem.id, "userDisabled") == "true" ||
  6046.         emDS.getItemProperty(aItem.id, "userDisabled") == OP_NEEDS_ENABLE)
  6047.       itemStatus = "userDisabled";
  6048.     else
  6049.       itemStatus = "userEnabled";
  6050.     
  6051.     if (emDS.getItemProperty(aItem.id, "compatible") == "false")
  6052.       itemStatus += ",incompatible";
  6053.     if (emDS.getItemProperty(aItem.id, "blocklisted") == "true")
  6054.       itemStatus += ",blocklisted";
  6055.     if (emDS.getItemProperty(aItem.id, "satisfiesDependencies") == "false")
  6056.       itemStatus += ",needsDependencies";
  6057.  
  6058.     // Look for a custom update URI: 1) supplied by a pref, 2) supplied by the
  6059.     // install manifest, 3) the default configuration
  6060.     try {
  6061.       var dsURI = gPref.getComplexValue(PREF_EM_ITEM_UPDATE_URL.replace(/%UUID%/, aItem.id),
  6062.                                         Components.interfaces.nsIPrefLocalizedString).data;
  6063.     }
  6064.     catch (e) { }
  6065.     if (!dsURI)
  6066.       dsURI = aItem.updateRDF;
  6067.     if (!dsURI) {
  6068.       dsURI = gPref.getComplexValue(PREF_UPDATE_DEFAULT_URL,
  6069.                                     Components.interfaces.nsIPrefLocalizedString).data;
  6070.     }
  6071.     dsURI = dsURI.replace(/%ITEM_ID%/g, aItem.id);
  6072.     dsURI = dsURI.replace(/%ITEM_VERSION%/g, aItem.version);
  6073.     dsURI = dsURI.replace(/%ITEM_MAXAPPVERSION%/g, aItem.maxAppVersion);
  6074.     dsURI = dsURI.replace(/%ITEM_STATUS%/g, itemStatus);
  6075.     dsURI = dsURI.replace(/%APP_ID%/g, this._updater._appID);
  6076.     dsURI = dsURI.replace(/%APP_VERSION%/g, this._updater._appVersion);
  6077.     dsURI = dsURI.replace(/%REQ_VERSION%/g, 1);
  6078.     dsURI = dsURI.replace(/%APP_OS%/g, gOSTarget);
  6079.     dsURI = dsURI.replace(/%APP_ABI%/g, gXPCOMABI);
  6080.     
  6081.     // escape() does not properly encode + symbols in any embedded FVF strings.
  6082.     dsURI = dsURI.replace(/\+/g, "%2B");
  6083.  
  6084.     // Verify that the URI provided is valid
  6085.     try {
  6086.       var uri = newURI(dsURI);
  6087.     }
  6088.     catch (e) {
  6089.       LOG("RDFItemUpdater:checkForUpdates: There was an error loading the \r\n" + 
  6090.           " update datasource for: " + dsURI + ", item = " + aItem.id + ", error: " + e);
  6091.       this._updater.checkForDone(aItem, 
  6092.                                  nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6093.       return;
  6094.     }
  6095.  
  6096.     LOG("RDFItemUpdater:checkForUpdates sending a request to server for: " + 
  6097.         uri.spec + ", item = " + aItem.objectSource);        
  6098.  
  6099.     var request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  6100.                             .createInstance(Components.interfaces.nsIXMLHttpRequest);
  6101.     request.open("GET", uri.spec, true);
  6102.     request.channel.notificationCallbacks = new BadCertHandler();
  6103.     request.overrideMimeType("text/xml");
  6104.     request.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
  6105.  
  6106.     var self = this;
  6107.     request.onerror     = function(event) { self.onXMLError(event, aItem);    };
  6108.     request.onload      = function(event) { self.onXMLLoad(event, aItem);     };
  6109.     request.send(null);
  6110.   },
  6111.  
  6112.   onXMLLoad: function(aEvent, aItem) {
  6113.     var request = aEvent.target;
  6114.     try {
  6115.       checkCert(request.channel);
  6116.     }
  6117.     catch (e) {
  6118.       // This may be overly restrictive in two cases: corporate installations
  6119.       // with a corporate update server using an in-house CA cert (installed
  6120.       // but not "built-in") and lone developers hosting their updates on a
  6121.       // site with a self-signed cert (permanently accepted, otherwise the
  6122.       // BadCertHandler would prevent getting this far). Update checks will
  6123.       // fail in both these scenarios.
  6124.       // How else can we protect the vast majority of updates served from AMO
  6125.       // from the spoofing attack described in bug 340198 while allowing those
  6126.       // other cases? A "hackme" pref? Domain-control certs are cheap, getting
  6127.       // one should not be a barrier in either case.
  6128.       LOG("RDFItemUpdater::onXMLLoad: " + e);
  6129.       this._updater.checkForDone(aItem,
  6130.                                  nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6131.       return;
  6132.     }
  6133.     var responseXML = request.responseXML;
  6134.  
  6135.     // If the item does not have an update RDF and returns an error it is not
  6136.     // treated as a failure since all items without an updateURL are checked
  6137.     // for updates on AMO even if they are not hosted there.
  6138.     if (!responseXML || responseXML.documentElement.namespaceURI == XMLURI_PARSE_ERROR ||
  6139.         (request.status != 200 && request.status != 0)) {
  6140.       this._updater.checkForDone(aItem, (aItem.updateRDF ? nsIAddonUpdateCheckListener.STATUS_FAILURE :
  6141.                                                            nsIAddonUpdateCheckListener.STATUS_NONE));
  6142.       return;
  6143.     }
  6144.  
  6145.     var rdfParser = Components.classes["@mozilla.org/rdf/xml-parser;1"]
  6146.                               .createInstance(Components.interfaces.nsIRDFXMLParser)
  6147.     var ds = Components.classes["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"]
  6148.                        .createInstance(Components.interfaces.nsIRDFDataSource);
  6149.     rdfParser.parseString(ds, request.channel.URI, request.responseText);
  6150.  
  6151.     this.onDatasourceLoaded(ds, aItem);
  6152.   },
  6153.  
  6154.   onXMLError: function(aEvent, aItem) {
  6155.     try {
  6156.       var request = aEvent.target;
  6157.       // the following may throw (e.g. a local file or timeout)
  6158.       var status = request.status;
  6159.     }
  6160.     catch (e) {
  6161.       request = aEvent.target.channel.QueryInterface(Components.interfaces.nsIRequest);
  6162.       status = request.status;
  6163.     }
  6164.     // this can fail when a network connection is not present.
  6165.     try {
  6166.       var statusText = request.statusText;
  6167.     }
  6168.     catch (e) {
  6169.       status = 0;
  6170.     }
  6171.     // When status is 0 we don't have a valid channel.
  6172.     if (status == 0)
  6173.       statusText = "nsIXMLHttpRequest channel unavailable";
  6174.  
  6175.     LOG("RDFItemUpdater:onError: There was an error loading the \r\n" + 
  6176.         "the update datasource for item " + aItem.id + ", error: " + statusText);
  6177.     this._updater.checkForDone(aItem, 
  6178.                                nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6179.   },
  6180.  
  6181.   onDatasourceLoaded: function(aDatasource, aLocalItem) {
  6182.     ///////////////////////////////////////////////////////////////////////////    
  6183.     // The extension update RDF file looks something like this:
  6184.     //
  6185.     //  <RDF:Description about="urn:mozilla:extension:{GUID}">
  6186.     //    <em:updates>
  6187.     //      <RDF:Seq>
  6188.     //        <RDF:li resource="urn:mozilla:extension:{GUID}:4.9"/>
  6189.     //        <RDF:li resource="urn:mozilla:extension:{GUID}:5.0"/>
  6190.     //      </RDF:Seq>
  6191.     //    </em:updates>
  6192.     //    <!-- the version of the extension being offered -->
  6193.     //    <em:version>5.0</em:version>
  6194.     //    <em:updateLink>http://www.mysite.com/myext-50.xpi</em:updateLink>
  6195.     //  </RDF:Description>
  6196.     //
  6197.     //  <RDF:Description about="urn:mozilla:extension:{GUID}:4.9">
  6198.     //    <em:version>4.9</em:version>
  6199.     //    <em:targetApplication>
  6200.     //      <RDF:Description>
  6201.     //        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
  6202.     //        <em:minVersion>0.9</em:minVersion>
  6203.     //        <em:maxVersion>1.0</em:maxVersion>
  6204.     //        <em:updateLink>http://www.mysite.com/myext-49.xpi</em:updateLink>
  6205.     //      </RDF:Description>
  6206.     //    </em:targetApplication>
  6207.     //  </RDF:Description>  
  6208.     //
  6209.     // If we get here because the following happened:
  6210.     // 1) User was using Firefox 0.9 with ExtensionX 0.5 (minVersion 0.8, 
  6211.     //    maxVersion 0.9 for Firefox)
  6212.     // 2) User upgraded Firefox to 1.0
  6213.     // 3) |checkForMismatches| deems ExtensionX 0.5 incompatible with this
  6214.     //    new version of Firefox on the basis of its maxVersion
  6215.     // 4) ** We reach this point **
  6216.     //
  6217.     // If the version of ExtensionX (0.5) matches that provided by the 
  6218.     // server, then this is a cue that the author updated the rdf file
  6219.     // or central repository to say "0.5 is ALSO compatible with Firefox 1.0,
  6220.     // no changes are necessary." In this event, the local metadata for
  6221.     // installed ExtensionX (0.5) is freshened with the new maxVersion, 
  6222.     // and we advance to the next item WITHOUT any download/install 
  6223.     // updates.
  6224.     if (!aDatasource.GetAllResources().hasMoreElements()) {
  6225.       LOG("RDFItemUpdater:onDatasourceLoaded: Datasource empty.\r\n" + 
  6226.           "If you are an Extension developer and were expecting there to be\r\n" + 
  6227.           "updates, this could mean any number of things, since the RDF system\r\n" + 
  6228.           "doesn't give up much in the way of information when the load fails.\r\n" + 
  6229.           "\r\nTry checking that: \r\n" + 
  6230.           " 1. Your remote RDF file exists at the location.\r\n" + 
  6231.           " 2. Your RDF file is valid XML (starts with <?xml version=\"1.0?\">\r\n" + 
  6232.           "    and loads in Firefox displaying pretty printed like other XML documents\r\n" + 
  6233.           " 3. Your server is sending the data in the correct MIME\r\n" + 
  6234.           "    type (text/xml)");
  6235.     }      
  6236.     
  6237.   
  6238.     // Parse the response RDF
  6239.     function UpdateData() {}; 
  6240.     UpdateData.prototype = { version: "0.0", updateLink: null, updateHash: null,
  6241.                              minVersion: "0.0", maxVersion: "0.0" };
  6242.     
  6243.     var versionUpdate = new UpdateData();
  6244.     var newestUpdate  = new UpdateData();
  6245.  
  6246.     var newerItem, sameItem;
  6247.     
  6248.     // Firefox 1.0PR+ update.rdf format
  6249.     if (!this._versionUpdateOnly) {
  6250.       // Look for newer versions of this item, we only do this in "normal" 
  6251.       // mode... see comment by ExtensionItemUpdater_checkForUpdates 
  6252.       // about how we do this in all cases but Install Phone Home - which 
  6253.       // only needs to do a version check.
  6254.       this._parseV20UpdateInfo(aDatasource, aLocalItem, newestUpdate, false);
  6255.  
  6256.       newerItem = makeItem(aLocalItem.id, 
  6257.                            newestUpdate.version, 
  6258.                            aLocalItem.installLocationKey,
  6259.                            newestUpdate.minVersion, 
  6260.                            newestUpdate.maxVersion, 
  6261.                            aLocalItem.name, 
  6262.                            newestUpdate.updateLink,
  6263.                            newestUpdate.updateHash,
  6264.                            "", /* Icon URL */
  6265.                            "", /* RDF Update URL */
  6266.                            aLocalItem.type);
  6267.       if (this._updater._isValidUpdate(aLocalItem, newerItem))
  6268.         ++this._updater._updateCount;
  6269.       else
  6270.         newerItem = null;
  6271.     }
  6272.     
  6273.     // Now look for updated version compatibility metadata for the currently
  6274.     // installed version...
  6275.     this._parseV20UpdateInfo(aDatasource, aLocalItem, versionUpdate, true);
  6276.  
  6277.     var result = gVersionChecker.compare(versionUpdate.version, 
  6278.                                           aLocalItem.version);
  6279.     if (result == 0) {
  6280.       // Local version exactly matches the "Version Update" remote version, 
  6281.       // Apply changes into local datasource.
  6282.       sameItem = makeItem(aLocalItem.id, 
  6283.                           versionUpdate.version, 
  6284.                           aLocalItem.installLocationKey,
  6285.                           versionUpdate.minVersion, 
  6286.                           versionUpdate.maxVersion, 
  6287.                           aLocalItem.name,
  6288.                           "", /* XPI Update URL */
  6289.                           "", /* XPI Update Hash */
  6290.                           "", /* Icon URL */
  6291.                           "", /* RDF Update URL */
  6292.                           aLocalItem.type);
  6293.       if (this._updater._isValidUpdate(aLocalItem, sameItem)) {
  6294.         // Install-time updates are not written to the DS because there is no
  6295.         // entry yet, EM just uses the notifications to ascertain (by hand)
  6296.         // whether or not there is a remote maxVersion tweak that makes the 
  6297.         // item being installed compatible.
  6298.         if (!this._updater._applyVersionUpdates(aLocalItem, sameItem))
  6299.           sameItem = null;
  6300.       }
  6301.       else 
  6302.         sameItem = null;
  6303.     }
  6304.     
  6305.     if (newerItem) {
  6306.       LOG("RDFItemUpdater:onDatasourceLoaded: Found a newer version of this item:\r\n" + 
  6307.           newerItem.objectSource);
  6308.     }
  6309.     if (sameItem) {
  6310.       LOG("RDFItemUpdater:onDatasourceLoaded: Found info about the installed\r\n" + 
  6311.           "version of this item: " + sameItem.objectSource);
  6312.     }
  6313.     var item = null, status = nsIAddonUpdateCheckListener.STATUS_NONE;
  6314.     if (!this._versionUpdateOnly && newerItem) {
  6315.       item = newerItem;
  6316.       status = nsIAddonUpdateCheckListener.STATUS_UPDATE;
  6317.     }
  6318.     else if (sameItem) {
  6319.       item = sameItem;
  6320.       status = nsIAddonUpdateCheckListener.STATUS_VERSIONINFO;
  6321.     }
  6322.     else {
  6323.       item = aLocalItem;
  6324.       status = nsIAddonUpdateCheckListener.STATUS_NO_UPDATE;
  6325.     }
  6326.     // Only one call of this._updater.checkForDone is needed for RDF 
  6327.     // responses, since there is only one response per item.
  6328.     this._updater.checkForDone(item, status);
  6329.   },
  6330.  
  6331.   // Get a compulsory property from a resource. Reports an error if the 
  6332.   // property was not present. 
  6333.   _getPropertyFromResource: function(aDataSource, aSourceResource, aProperty, aLocalItem) {
  6334.     var rv;
  6335.     try {
  6336.       var property = gRDF.GetResource(EM_NS(aProperty));
  6337.       rv = stringData(aDataSource.GetTarget(aSourceResource, property, true));
  6338.       if (rv === undefined)
  6339.         throw Components.results.NS_ERROR_FAILURE;
  6340.     }
  6341.     catch (e) {
  6342.       // XXXben show console message "aProperty" not found on aSourceResource. 
  6343.       return null;
  6344.     }
  6345.     return rv;
  6346.   },
  6347.   
  6348.   // Parses Firefox 1.0RC1+ update.rdf format
  6349.   _parseV20UpdateInfo: function(aDataSource, aLocalItem, aUpdateData, aVersionUpdatesOnly) {
  6350.     var extensionRes  = gRDF.GetResource(getItemPrefix(aLocalItem.type) + aLocalItem.id);
  6351.  
  6352.     var updatesArc = gRDF.GetResource(EM_NS("updates"));
  6353.     var updates = aDataSource.GetTarget(extensionRes, updatesArc, true);
  6354.     
  6355.     try {
  6356.       updates = updates.QueryInterface(Components.interfaces.nsIRDFResource);
  6357.     }
  6358.     catch (e) { 
  6359.       LOG("RDFItemUpdater:_parseV20UpdateInfo: No updates were found for:\r\n" + 
  6360.           aLocalItem.id + "\r\n" + 
  6361.           "If you are an Extension developer and were expecting there to be\r\n" + 
  6362.           "updates, this could mean any number of things, since the RDF system\r\n" + 
  6363.           "doesn't give up much in the way of information when the load fails.\r\n" + 
  6364.           "\r\nTry checking that: \r\n" + 
  6365.           " 1. Your RDF File is correct - e.g. check that there is a top level\r\n" + 
  6366.           "    RDF Resource with a URI urn:mozilla:extension:{GUID}, and that\r\n" + 
  6367.           "    the <em:updates> listed all have matching GUIDs.");
  6368.       return; 
  6369.     }
  6370.     
  6371.     var cu = Components.classes["@mozilla.org/rdf/container-utils;1"]
  6372.                        .getService(Components.interfaces.nsIRDFContainerUtils);
  6373.     if (cu.IsContainer(aDataSource, updates)) {
  6374.       var ctr = getContainer(aDataSource, updates);
  6375.  
  6376.       // In "all update types" mode, we look for newer versions, starting with the 
  6377.       // current installed version.
  6378.       if (!aVersionUpdatesOnly) 
  6379.         aUpdateData.version = aLocalItem.version;
  6380.  
  6381.       var versions = ctr.GetElements();
  6382.       while (versions.hasMoreElements()) {
  6383.         // There are two different methodologies for collecting version 
  6384.         // information depending on whether or not we've bene invoked in 
  6385.         // "version updates only" mode or "version+newest" mode. 
  6386.         var version = versions.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6387.         this._parseV20Update(aDataSource, version, aLocalItem, aUpdateData, aVersionUpdatesOnly);
  6388.         if (aVersionUpdatesOnly && aUpdateData.updateLink)
  6389.           break;
  6390.       }
  6391.     }
  6392.   },
  6393.   
  6394.   _parseV20Update: function(aDataSource, aUpdateResource, aLocalItem, aUpdateData, aVersionUpdatesOnly) {
  6395.     var version = this._getPropertyFromResource(aDataSource, aUpdateResource, 
  6396.                                                 "version", aLocalItem);
  6397.     var taArc = gRDF.GetResource(EM_NS("targetApplication"));
  6398.     var targetApps = aDataSource.GetTargets(aUpdateResource, taArc, true);
  6399.     while (targetApps.hasMoreElements()) {
  6400.       var targetApp = targetApps.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6401.       var id = this._getPropertyFromResource(aDataSource, targetApp, "id", aLocalItem);
  6402.       if (id != this._updater._appID)
  6403.         continue;
  6404.       
  6405.       var result = gVersionChecker.compare(version, aLocalItem.version);
  6406.       if (aVersionUpdatesOnly ? result == 0 : result > 0) {
  6407.         aUpdateData.version = version;
  6408.         aUpdateData.updateLink = this._getPropertyFromResource(aDataSource, targetApp, "updateLink", aLocalItem);
  6409.         aUpdateData.updateHash = this._getPropertyFromResource(aDataSource, targetApp, "updateHash", aLocalItem);
  6410.         aUpdateData.minVersion = this._getPropertyFromResource(aDataSource, targetApp, "minVersion", aLocalItem);
  6411.         aUpdateData.maxVersion = this._getPropertyFromResource(aDataSource, targetApp, "maxVersion", aLocalItem);
  6412.       }
  6413.     }
  6414.   }
  6415. };
  6416.  
  6417. /**
  6418.  * A Datasource that holds Extensions. 
  6419.  * - Implements nsIRDFDataSource to drive UI
  6420.  * - Uses a RDF/XML datasource for storage (this is undesirable)
  6421.  * 
  6422.  * @constructor
  6423.  */
  6424. function ExtensionsDataSource(em) {
  6425.   this._em = em;
  6426.   
  6427.   this._itemRoot = gRDF.GetResource(RDFURI_ITEM_ROOT);
  6428.   this._defaultTheme = gRDF.GetResource(RDFURI_DEFAULT_THEME);
  6429.   gRDF.RegisterDataSource(this, true);
  6430. }
  6431. ExtensionsDataSource.prototype = {
  6432.   _inner    : null,
  6433.   _em       : null,
  6434.   _itemRoot     : null,
  6435.   _defaultTheme : null,
  6436.   
  6437.   /**
  6438.    * Determines if an item's dependencies are satisfied. An item's dependencies
  6439.    * are satisifed when all items specified in the item's em:requires arc are
  6440.    * installed, enabled, and the version is compatible based on the em:requires
  6441.    * minVersion and maxVersion.
  6442.    * @param   id
  6443.    *          The ID of the item
  6444.    * @returns true if the item's dependencies are satisfied.
  6445.    *          false if the item's dependencies are not satisfied.
  6446.    */
  6447.   satisfiesDependencies: function(id) {
  6448.     var ds = this._inner;
  6449.     var itemResource = getResourceForID(id);
  6450.     var targets = ds.GetTargets(itemResource, EM_R("requires"), true);
  6451.     if (!targets.hasMoreElements())
  6452.       return true;
  6453.  
  6454.     getVersionChecker();
  6455.     var idRes = EM_R("id");
  6456.     var minVersionRes = EM_R("minVersion");
  6457.     var maxVersionRes = EM_R("maxVersion");
  6458.     while (targets.hasMoreElements()) {
  6459.       var target = targets.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6460.       var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  6461.       var version = null;
  6462.       version = this.getItemProperty(dependencyID, "version");
  6463.       if (version) {
  6464.         var opType = this.getItemProperty(dependencyID, "opType");
  6465.         if (opType ==  OP_NEEDS_DISABLE || opType == OP_NEEDS_UNINSTALL)
  6466.           return false;
  6467.  
  6468.         if (this.getItemProperty(dependencyID, "userDisabled") == "true" ||
  6469.             this.getItemProperty(dependencyID, "appDisabled") == "true" ||
  6470.             this.getItemProperty(dependencyID, "userDisabled") == OP_NEEDS_DISABLE ||
  6471.             this.getItemProperty(dependencyID, "appDisabled") == OP_NEEDS_DISABLE)
  6472.           return false;
  6473.  
  6474.         var minVersion = stringData(ds.GetTarget(target, minVersionRes, true));
  6475.         var maxVersion = stringData(ds.GetTarget(target, maxVersionRes, true));
  6476.         var compatible = (gVersionChecker.compare(version, minVersion) >= 0 &&
  6477.                           gVersionChecker.compare(version, maxVersion) <= 0);
  6478.         if (!compatible)
  6479.           return false;
  6480.       }
  6481.       else {
  6482.         return false;
  6483.       }
  6484.     }
  6485.  
  6486.     return true;
  6487.   },
  6488.  
  6489.   /**
  6490.    * Determine if an item is compatible
  6491.    * @param   datasource
  6492.    *          The datasource to inspect for compatibility - can be the main
  6493.    *          datasource or an Install Manifest.
  6494.    * @param   source
  6495.    *          The RDF Resource of the item to inspect for compatibility.
  6496.    * @param   version
  6497.    *          The version of the application we are checking for compatibility
  6498.    *          against. If this parameter is undefined, the version of the running
  6499.    *          application is used.
  6500.    * @returns true if the item is compatible with this version of the 
  6501.    *          application, false, otherwise.
  6502.    */
  6503.   isCompatible: function (datasource, source, version) {
  6504.     // The Default Theme is always compatible. 
  6505.     if (source.EqualsNode(this._defaultTheme))
  6506.       return true;
  6507.  
  6508.     if (version === undefined) {
  6509.       version = gApp.version;
  6510.     }              
  6511.     var appID = gApp.ID;
  6512.     
  6513.     var targets = datasource.GetTargets(source, EM_R("targetApplication"), true);
  6514.     var idRes = EM_R("id");
  6515.     var minVersionRes = EM_R("minVersion");
  6516.     var maxVersionRes = EM_R("maxVersion");
  6517.     while (targets.hasMoreElements()) {
  6518.       var targetApp = targets.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6519.       var id          = stringData(datasource.GetTarget(targetApp, idRes, true));
  6520.       var minVersion  = stringData(datasource.GetTarget(targetApp, minVersionRes, true));
  6521.       var maxVersion  = stringData(datasource.GetTarget(targetApp, maxVersionRes, true));
  6522.       if (id == appID) {
  6523.         var versionChecker = getVersionChecker();
  6524.         return ((versionChecker.compare(version, minVersion) >= 0) &&
  6525.                 (versionChecker.compare(version, maxVersion) <= 0));
  6526.       }
  6527.     }
  6528.     return false;
  6529.   },
  6530.  
  6531.   /**
  6532.    * Determine if an item is blocklisted
  6533.    * @param   id
  6534.    *          The id of the item to check.
  6535.    * @param   extVersion
  6536.    *          The item's version.
  6537.    * @param   appVersion
  6538.    *          The version of the application we are checking in the blocklist.
  6539.    *          If this parameter is undefined, the version of the running
  6540.    *          application is used.
  6541.    * @param   toolkitVersion
  6542.    *          The version of the toolkit we are checking in the blocklist.
  6543.    *          If this parameter is undefined, the version of the running
  6544.    *          toolkit is used.
  6545.    * @returns true if the item is compatible with this version of the 
  6546.    *          application, false, otherwise.
  6547.    */
  6548.   isBlocklisted: function(id, extVersion, appVersion, toolkitVersion) {
  6549.     if (appVersion === undefined)
  6550.       appVersion = gApp.version;
  6551.     if (toolkitVersion === undefined)
  6552.       toolkitVersion = gApp.platformVersion;
  6553.  
  6554.     var blItem = Blocklist.entries[id];
  6555.     if (!blItem)
  6556.       return false;
  6557.  
  6558.     var versionChecker = getVersionChecker();
  6559.     for (var i = 0; i < blItem.length; ++i) {
  6560.       if (versionChecker.compare(extVersion, blItem[i].minVersion) < 0  ||
  6561.           versionChecker.compare(extVersion, blItem[i].maxVersion) > 0)
  6562.         continue;
  6563.  
  6564.       var blTargetApp = blItem[i].targetApps[gApp.ID];
  6565.       if (blTargetApp) {
  6566.         for (var x = 0; x < blTargetApp.length; ++x) {
  6567.           if (versionChecker.compare(appVersion, blTargetApp[x].minVersion) < 0  ||
  6568.               versionChecker.compare(appVersion, blTargetApp[x].maxVersion) > 0)
  6569.             continue;
  6570.           return true;
  6571.         }
  6572.       }
  6573.  
  6574.       blTargetApp = blItem[i].targetApps[TOOLKIT_ID];
  6575.       if (!blTargetApp)
  6576.         return false;
  6577.       for (x = 0; x < blTargetApp.length; ++x) {
  6578.         if (versionChecker.compare(toolkitVersion, blTargetApp[x].minVersion) < 0  ||
  6579.             versionChecker.compare(toolkitVersion, blTargetApp[x].maxVersion) > 0)
  6580.           continue;
  6581.         return true;
  6582.       }
  6583.     }
  6584.     return false;
  6585.   },
  6586.  
  6587.   /**
  6588.    * Gets a list of items that are incompatible with a specific application version.
  6589.    * @param   appID
  6590.    *          The ID of the application - XXXben unused?
  6591.    * @param   appVersion
  6592.    *          The Version of the application to check for incompatibility against.
  6593.    * @param   desiredType
  6594.    *          The nsIUpdateItem type of items to look for
  6595.    * @param   includeDisabled
  6596.    *          Whether or not disabled items should be included in the set returned
  6597.    * @returns An array of nsIUpdateItems that are incompatible with the application
  6598.    *          ID/Version supplied.
  6599.    */
  6600.   getIncompatibleItemList: function(appID, appVersion, desiredType, includeDisabled) {
  6601.     var items = [];
  6602.     var ctr = getContainer(this._inner, this._itemRoot);
  6603.     var elements = ctr.GetElements();
  6604.     while (elements.hasMoreElements()) {
  6605.       var item = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6606.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  6607.       var type = this.getItemProperty(id, "type");
  6608.       // Skip this item if we're not seeking disabled items
  6609.       if (!includeDisabled && this.getItemProperty(id, "isDisabled") == "true")
  6610.         continue;
  6611.       
  6612.       // If the id of this item matches one of the items potentially installed
  6613.       // with and maintained by this application AND it is installed in the 
  6614.       // global install location (i.e. the place installed by the app installer)
  6615.       // it is and can be managed by the update file - it's not an item that has
  6616.       // been manually installed by the user into their profile dir, and as such
  6617.       // it is always compatible with the next release of the application since
  6618.       // we will continue to support it.
  6619.       var locationKey = this.getItemProperty(id, "installLocation");
  6620.       var appManaged = this.getItemProperty(id, "appManaged") == "true";
  6621.       if (appManaged && locationKey == KEY_APP_GLOBAL)
  6622.         continue;
  6623.  
  6624.       if (type != -1 && (type & desiredType) && 
  6625.           !this.isCompatible(this, item, appVersion))
  6626.         items.push(this.getItemForID(id));
  6627.     }
  6628.     return items;
  6629.   },
  6630.   
  6631.   /**
  6632.    * Retrieves a list of items that will be blocklisted by the application for
  6633.    * a specific application or toolkit version.
  6634.    * @param   appVersion
  6635.    *          The Version of the application to check the blocklist against.
  6636.    * @param   toolkitVersion
  6637.    *          The Version of the toolkit to check the blocklist against.
  6638.    * @param   desiredType
  6639.    *          The nsIUpdateItem type of items to look for
  6640.    * @param   includeAppDisabled
  6641.    *          Whether or not items that are or are already set to be disabled
  6642.    *          by the app on next restart should be included in the set returned
  6643.    * @returns An array of nsIUpdateItems that are blocklisted with the application
  6644.    *          or toolkit version supplied.
  6645.    */
  6646.   getBlocklistedItemList: function(appVersion, toolkitVersion, desiredType,
  6647.                                    includeAppDisabled) {
  6648.     var items = [];
  6649.     var ctr = getContainer(this._inner, this._itemRoot);
  6650.     var elements = ctr.GetElements();
  6651.     while (elements.hasMoreElements()) {
  6652.       var item = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6653.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  6654.       var type = this.getItemProperty(id, "type");
  6655.  
  6656.       if (!includeAppDisabled &&
  6657.           (this.getItemProperty(id, "appDisabled") == "true" ||
  6658.           this.getItemProperty(id, "appDisabled") == OP_NEEDS_DISABLE))
  6659.         continue;
  6660.  
  6661.       var extVersion = this.getItemProperty(id, "version");
  6662.       if (type != -1 && (type & desiredType) && 
  6663.           this.isBlocklisted(id, extVersion, appVersion, toolkitVersion))
  6664.         items.push(this.getItemForID(id));
  6665.     }
  6666.     return items;
  6667.   },
  6668.  
  6669.   /**
  6670.    * Gets a list of items of a specific type
  6671.    * @param   desiredType
  6672.    *          The nsIUpdateItem type of items to return
  6673.    * @param   countRef
  6674.    *          The XPCJS reference to the size of the returned array
  6675.    * @returns An array of nsIUpdateItems, populated only with an item for |id|
  6676.    *          if |id| is non-null, otherwise all items matching the specified
  6677.    *          type.
  6678.    */
  6679.   getItemList: function(desiredType, countRef) {
  6680.     var items = [];
  6681.     var ctr = getContainer(this, this._itemRoot);      
  6682.     var elements = ctr.GetElements();
  6683.     while (elements.hasMoreElements()) {
  6684.       var e = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6685.       var eID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  6686.       var type = this.getItemProperty(eID, "type");
  6687.       if (type != -1 && type & desiredType)
  6688.         items.push(this.getItemForID(eID));
  6689.     }
  6690.     countRef.value = items.length;
  6691.     return items;
  6692.   },
  6693.  
  6694.   /**
  6695.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  6696.    * on another item.
  6697.    * @param   id
  6698.    *          The ID of the item that other items depend on.
  6699.    * @param   includeDisabled
  6700.    *          Whether to include disabled items in the set returned.
  6701.    * @param   countRef
  6702.    *          The XPCJS reference to the number of items returned.
  6703.    * @returns An array of installed nsIUpdateItems that depend on the item
  6704.    *          specified by the id parameter.
  6705.    */
  6706.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  6707.     var items = [];
  6708.     var ds = this._inner;
  6709.     var ctr = getContainer(this, this._itemRoot);
  6710.     var elements = ctr.GetElements();
  6711.     while (elements.hasMoreElements()) {
  6712.       var e = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6713.       var dependentID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  6714.       var targets = ds.GetTargets(e, EM_R("requires"), true);
  6715.       var idRes = EM_R("id");
  6716.       while (targets.hasMoreElements()) {
  6717.         var target = targets.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6718.         var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  6719.         if (dependencyID == id) {
  6720.           if (!includeDisabled && this.getItemProperty(dependentID, "isDisabled") == "true")
  6721.             continue;
  6722.           items.push(this.getItemForID(dependentID));
  6723.           break;
  6724.         }
  6725.       }
  6726.     }
  6727.     countRef.value = items.length;
  6728.     return items;
  6729.   },
  6730.  
  6731.   /**
  6732.    * Get a list of Item IDs that have a flag set
  6733.    * @param   flag
  6734.    *          The name of an RDF property (less EM_NS) to check for
  6735.    * @param   desiredType
  6736.    *          The nsIUpdateItem type of item to look for
  6737.    * @returns An array of Item IDs 
  6738.    *
  6739.    * XXXben - this function is a little weird since it returns an array of 
  6740.    *          strings, not an array of nsIUpdateItems...  
  6741.    */
  6742.   getItemsWithFlagUnset: function(flag, desiredType) {
  6743.     var items = [];
  6744.  
  6745.     var ctr = getContainer(this, this._itemRoot);    
  6746.     var elements = ctr.GetElements();
  6747.     while (elements.hasMoreElements()) {
  6748.       var e = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  6749.       var id = stripPrefix(e.Value, PREFIX_ITEM_URI);
  6750.       var type = this.getItemProperty(id, "type");
  6751.       if (type != -1 && type & desiredType) {
  6752.         var value = this.GetTarget(e, EM_R(flag), true);
  6753.         if (!value)
  6754.           items.push(id);
  6755.       }
  6756.     }
  6757.     return items;
  6758.   },
  6759.   
  6760.   /**
  6761.    * Constructs an nsIUpdateItem for the given item ID
  6762.    * @param   id
  6763.    *          The GUID of the item to construct a nsIUpdateItem for
  6764.    * @returns The nsIUpdateItem for the id.
  6765.    */  
  6766.   getItemForID: function(id) {
  6767.     var r = getResourceForID(id);
  6768.     if (!r)
  6769.       return null;
  6770.     
  6771.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  6772.     var updateHash = this.getItemProperty(id, "availableUpdateHash");
  6773.     return makeItem(id, 
  6774.                     this.getItemProperty(id, "version"), 
  6775.                     this.getItemProperty(id, "installLocation"),
  6776.                     targetAppInfo ? targetAppInfo.minVersion : "",
  6777.                     targetAppInfo ? targetAppInfo.maxVersion : "",
  6778.                     this.getItemProperty(id, "name"),
  6779.                     this.getItemProperty(id, "availableUpdateURL"),
  6780.                     updateHash ? updateHash : "",
  6781.                     this.getItemProperty(id, "iconURL"), 
  6782.                     this.getItemProperty(id, "updateURL"), 
  6783.                     this.getItemProperty(id, "type"));
  6784.   },
  6785.   
  6786.   /**
  6787.    * Gets the name of the Install Location where an item is installed.
  6788.    * @param   id
  6789.    *          The GUID of the item to locate an Install Location for
  6790.    * @returns The string name of the Install Location where the item is 
  6791.    *          installed.
  6792.    */
  6793.   getInstallLocationKey: function(id) {
  6794.     return this.getItemProperty(id, "installLocation");
  6795.   },
  6796.   
  6797.   /**
  6798.    * Sets an RDF property on an item in a datasource. Does not create
  6799.    * multiple assertions
  6800.    * @param   datasource
  6801.    *          The target datasource where the property should be set
  6802.    * @param   source
  6803.    *          The RDF Resource to set the property on
  6804.    * @param   property
  6805.    *          The RDF Resource of the property to set
  6806.    * @param   newValue
  6807.    *          The RDF Node containing the new property value
  6808.    */
  6809.   _setProperty: function(datasource, source, property, newValue) {
  6810.     var oldValue = datasource.GetTarget(source, property, true);
  6811.     if (oldValue) {
  6812.       if (newValue)
  6813.         datasource.Change(source, property, oldValue, newValue);
  6814.       else
  6815.         datasource.Unassert(source, property, oldValue);
  6816.     }
  6817.     else if (newValue)
  6818.       datasource.Assert(source, property, newValue, true);
  6819.   },
  6820.   
  6821.   /**
  6822.    * Sets the target application info for an item in the Extensions
  6823.    * datasource and in the item's install manifest if it is installed in a
  6824.    * profile's extensions directory, it exists, and we have write access.
  6825.    * @param   id
  6826.    *          The ID of the item to update target application info for
  6827.    * @param   minVersion
  6828.    *          The minimum version of the target application that this item can
  6829.    *          run in
  6830.    * @param   maxVersion
  6831.    *          The maximum version of the target application that this item can
  6832.    *          run in
  6833.    */
  6834.   updateTargetAppInfo: function(id, minVersion, maxVersion)
  6835.   {
  6836.     // Update the Extensions datasource
  6837.     this.setTargetApplicationInfo(id, minVersion, maxVersion, null);
  6838.  
  6839.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  6840.     if (installLocation.name != KEY_APP_PROFILE)
  6841.       return;
  6842.  
  6843.     var installManifestFile = installLocation.getItemFile(id, FILE_INSTALL_MANIFEST);
  6844.     // Only update if the item exists and we can write to the location
  6845.     if (installManifestFile.exists() && installLocation.canAccess)
  6846.       this.setTargetApplicationInfo(id, minVersion, maxVersion,
  6847.                                     getInstallManifest(installManifestFile));
  6848.   },
  6849.  
  6850.   /**
  6851.    * Gets the updated target application info if it exists for an item from
  6852.    * the Extensions datasource during an installation or upgrade.
  6853.    * @param   id
  6854.    *          The ID of the item to discover updated target application info for
  6855.    * @returns A JS Object with the following properties:
  6856.    *          "id"            The id of the item
  6857.    *          "minVersion"    The updated minimum version of the target
  6858.    *                          application that this item can run in
  6859.    *          "maxVersion"    The updated maximum version of the target
  6860.    *                          application that this item can run in
  6861.    */
  6862.   getUpdatedTargetAppInfo: function(id) {
  6863.     // The default theme is always compatible so there is never update info.
  6864.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  6865.       return null;
  6866.  
  6867.     var appID = gApp.ID;
  6868.     var r = getResourceForID(id);
  6869.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  6870.     if (!targetApps.hasMoreElements())
  6871.       targetApps = this._inner.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true); 
  6872.     while (targetApps.hasMoreElements()) {
  6873.       var targetApp = targetApps.getNext();
  6874.       if (targetApp instanceof Components.interfaces.nsIRDFResource) {
  6875.         try {
  6876.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  6877.           if (foundAppID != appID) // Different target application
  6878.             continue;
  6879.           var updatedMinVersion = this._inner.GetTarget(targetApp, EM_R("updatedMinVersion"), true);
  6880.           var updatedMaxVersion = this._inner.GetTarget(targetApp, EM_R("updatedMaxVersion"), true);
  6881.           if (updatedMinVersion && updatedMaxVersion)
  6882.             return { id        : id,
  6883.                      minVersion: stringData(updatedMinVersion),
  6884.                      maxVersion: stringData(updatedMaxVersion) };
  6885.           else
  6886.             return null;
  6887.         }
  6888.         catch (e) { 
  6889.           continue;
  6890.         }
  6891.       }
  6892.     }
  6893.     return null;
  6894.   },
  6895.   
  6896.   /**
  6897.    * Sets the updated target application info for an item in the Extensions
  6898.    * datasource during an installation or upgrade.
  6899.    * @param   id
  6900.    *          The ID of the item to set updated target application info for
  6901.    * @param   updatedMinVersion
  6902.    *          The updated minimum version of the target application that this
  6903.    *          item can run in
  6904.    * @param   updatedMaxVersion
  6905.    *          The updated maximum version of the target application that this
  6906.    *          item can run in
  6907.    */
  6908.   setUpdatedTargetAppInfo: function(id, updatedMinVersion, updatedMaxVersion) {
  6909.     // The default theme is always compatible so it is never updated.
  6910.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  6911.       return;
  6912.  
  6913.     // Version/Dependency Info
  6914.     var updatedMinVersionRes = EM_R("updatedMinVersion");
  6915.     var updatedMaxVersionRes = EM_R("updatedMaxVersion");
  6916.  
  6917.     var appID = gApp.ID;
  6918.     var r = getResourceForID(id);
  6919.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  6920.     // add updatedMinVersion and updatedMaxVersion for an install else an upgrade
  6921.     if (!targetApps.hasMoreElements()) {
  6922.       var idRes = EM_R("id");
  6923.       var targetRes = getResourceForID(id);
  6924.       var property = EM_R("targetApplication");
  6925.       var anon = gRDF.GetAnonymousResource();
  6926.       this._inner.Assert(anon, idRes, EM_L(appID), true);
  6927.       this._inner.Assert(anon, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  6928.       this._inner.Assert(anon, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  6929.       this._inner.Assert(targetRes, property, anon, true);
  6930.     }
  6931.     else {
  6932.       while (targetApps.hasMoreElements()) {
  6933.         var targetApp = targetApps.getNext();
  6934.         if (targetApp instanceof Components.interfaces.nsIRDFResource) {
  6935.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  6936.           if (foundAppID != appID) // Different target application
  6937.             continue;
  6938.           this._inner.Assert(targetApp, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  6939.           this._inner.Assert(targetApp, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  6940.           break;
  6941.         }
  6942.       }
  6943.     }
  6944.     this.Flush();
  6945.   },
  6946.  
  6947.   /**
  6948.    * Gets the target application info for an item from a datasource.
  6949.    * @param   id
  6950.    *          The GUID of the item to discover target application info for
  6951.    * @param   datasource
  6952.    *          The datasource to look up target application info in
  6953.    * @returns A JS Object with the following properties:
  6954.    *          "minVersion"    The minimum version of the target application
  6955.    *                          that this item can run in
  6956.    *          "maxVersion"    The maximum version of the target application
  6957.    *                          that this item can run in
  6958.    *          or null, if no target application data exists for the specified
  6959.    *          id in the supplied datasource.
  6960.    */
  6961.   getTargetApplicationInfo: function(id, datasource) {
  6962.     // The default theme is always compatible. 
  6963.     if (getResourceForID(id).EqualsNode(this._defaultTheme)) {
  6964.       var ver = gApp.version;
  6965.       return { minVersion: ver, maxVersion: ver };
  6966.     }
  6967.     var appID = gApp.ID;
  6968.     var r = getResourceForID(id);
  6969.     var targetApps = datasource.GetTargets(r, EM_R("targetApplication"), true);
  6970.     if (!targetApps)
  6971.       return null;
  6972.     if (!targetApps.hasMoreElements())
  6973.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true); 
  6974.     while (targetApps.hasMoreElements()) {
  6975.       var targetApp = targetApps.getNext();
  6976.       if (targetApp instanceof Components.interfaces.nsIRDFResource) {
  6977.         try {
  6978.           var foundAppID = stringData(datasource.GetTarget(targetApp, EM_R("id"), true));
  6979.           if (foundAppID != appID) // Different target application
  6980.             continue;
  6981.           
  6982.           return { minVersion: stringData(datasource.GetTarget(targetApp, EM_R("minVersion"), true)),
  6983.                    maxVersion: stringData(datasource.GetTarget(targetApp, EM_R("maxVersion"), true)) };
  6984.         }
  6985.         catch (e) { 
  6986.           continue;
  6987.         }
  6988.       }
  6989.     }
  6990.     return null;
  6991.   },
  6992.   
  6993.   /**
  6994.    * Sets the target application info for an item in a datasource.
  6995.    * @param   id
  6996.    *          The GUID of the item to discover target application info for
  6997.    * @param   minVersion
  6998.    *          The minimum version of the target application that this item can
  6999.    *          run in
  7000.    * @param   maxVersion
  7001.    *          The maximum version of the target application that this item can
  7002.    *          run in
  7003.    * @param   datasource
  7004.    *          The datasource to loko up target application info in
  7005.    */
  7006.   setTargetApplicationInfo: function(id, minVersion, maxVersion, datasource) {
  7007.     var targetDataSource = datasource;
  7008.     if (!targetDataSource)
  7009.       targetDataSource = this._inner;
  7010.       
  7011.     var appID = gApp.ID;
  7012.     var r = getResourceForID(id);
  7013.     var targetApps = targetDataSource.GetTargets(r, EM_R("targetApplication"), true);
  7014.     if (!targetApps.hasMoreElements())
  7015.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true); 
  7016.     while (targetApps.hasMoreElements()) {
  7017.       var targetApp = targetApps.getNext();
  7018.       if (targetApp instanceof Components.interfaces.nsIRDFResource) {
  7019.         var foundAppID = stringData(targetDataSource.GetTarget(targetApp, EM_R("id"), true));
  7020.         if (foundAppID != appID) // Different target application
  7021.           continue;
  7022.         
  7023.         this._setProperty(targetDataSource, targetApp, EM_R("minVersion"), EM_L(minVersion));
  7024.         this._setProperty(targetDataSource, targetApp, EM_R("maxVersion"), EM_L(maxVersion));
  7025.         
  7026.         // If we were setting these properties on the main datasource, flush
  7027.         // it now. (Don't flush changes set on Install Manifests - they are
  7028.         // fleeting).
  7029.         if (!datasource)
  7030.           this.Flush();
  7031.  
  7032.         break;
  7033.       }
  7034.     }
  7035.   },
  7036.   
  7037.   /** 
  7038.    * Gets a property of an item
  7039.    * @param   id
  7040.    *          The GUID of the item
  7041.    * @param   property
  7042.    *          The name of the property (excluding EM_NS)
  7043.    * @returns The literal value of the property, or undefined if there is no 
  7044.    *          value.
  7045.    */
  7046.   getItemProperty: function(id, property) { 
  7047.     var item = getResourceForID(id);
  7048.     if (!item) {
  7049.       LOG("getItemProperty failing for lack of an item. This means getResourceForItem \
  7050.            failed to locate a resource for aItemID (item ID = " + id + ", property = " + property + ")");
  7051.     }
  7052.     else 
  7053.       return this._getItemProperty(item, property);
  7054.     return undefined;
  7055.   },
  7056.   
  7057.   /**
  7058.    * Gets a property of an item resource
  7059.    * @param   itemResource
  7060.    *          The RDF Resource of the item
  7061.    * @param   property
  7062.    *          The name of the property (excluding EM_NS)
  7063.    * @returns The literal value of the property, or undefined if there is no
  7064.    *          value.
  7065.    */
  7066.   _getItemProperty: function(itemResource, property) {
  7067.     var target = this.GetTarget(itemResource, EM_R(property), true);
  7068.     var value = stringData(target);
  7069.     if (value === undefined)
  7070.       value = intData(target);
  7071.     return value === undefined ? "" : value;
  7072.   },
  7073.   
  7074.   /**
  7075.    * Sets a property on an item.
  7076.    * @param   id
  7077.    *          The GUID of the item
  7078.    * @param   propertyArc
  7079.    *          The RDF Resource of the property arc
  7080.    * @param   propertyValue
  7081.    *          A nsIRDFLiteral value of the property to be set
  7082.    */
  7083.   setItemProperty: function (id, propertyArc, propertyValue) {
  7084.     var item = getResourceForID(id);
  7085.     this._setProperty(this._inner, item, propertyArc, propertyValue);
  7086.     this.Flush();  
  7087.   },
  7088.  
  7089.   /**
  7090.    * Inserts the RDF resource for an item into a container.
  7091.    * @param   id
  7092.    *          The GUID of the item
  7093.    */
  7094.   insertItemIntoContainer: function(id) {
  7095.     // Get the target container and resource
  7096.     var ctr = getContainer(this._inner, this._itemRoot);
  7097.     var itemResource = getResourceForID(id);
  7098.     // Don't bother adding the extension to the list if it's already there. 
  7099.     // (i.e. we're upgrading)
  7100.     var oldIndex = ctr.IndexOf(itemResource);
  7101.     if (oldIndex == -1)
  7102.       ctr.AppendElement(itemResource);
  7103.     this.Flush();
  7104.   }, 
  7105.  
  7106.   /**
  7107.    * Removes the RDF resource for an item from its container.
  7108.    * @param   id
  7109.    *          The GUID of the item
  7110.    */
  7111.   removeItemFromContainer: function(id) {
  7112.     var ctr = getContainer(this._inner, this._itemRoot);
  7113.     var itemResource = getResourceForID(id);
  7114.     ctr.RemoveElement(itemResource, true);
  7115.     this.Flush();
  7116.   },
  7117.  
  7118.   /**
  7119.    * Removes a corrupt item entry from the extension list added due to buggy 
  7120.    * code in previous EM versions!  
  7121.    * @param   id
  7122.    *          The GUID of the item
  7123.    */
  7124.   removeCorruptItem: function(id) {
  7125.     this.removeItemMetadata(id);
  7126.     this.removeItemFromContainer(id);
  7127.   },
  7128.  
  7129.   /**
  7130.    * Removes a corrupt download entry from the list
  7131.    * @param   uri
  7132.    *          The RDF URI of the item.
  7133.    * @returns The RDF Resource of the removed entry 
  7134.    */
  7135.   removeCorruptDLItem: function(uri) {
  7136.     var itemResource = gRDF.GetResource(uri);
  7137.     var ctr = getContainer(this._inner, this._itemRoot);
  7138.     if (ctr.IndexOf(itemResource) != -1) {
  7139.       ctr.RemoveElement(itemResource, true);
  7140.       this._cleanResource(itemResource);
  7141.       this.Flush();
  7142.     }
  7143.     return itemResource;
  7144.   },
  7145.   
  7146.   /**
  7147.    * Copies metadata from an Install Manifest Datasource into the Extensions
  7148.    * DataSource.
  7149.    * @param   id
  7150.    *          The GUID of the item
  7151.    * @param   installManifest
  7152.    *          The Install Manifest datasource we are copying from
  7153.    * @param   installLocation
  7154.    *          The Install Location of the item. 
  7155.    */
  7156.   addItemMetadata: function(id, installManifest, installLocation) {
  7157.     // Copy the assertions over from the source datasource. 
  7158.     var targetRes = getResourceForID(id);
  7159.     // Assert properties with single values
  7160.     var singleProps = ["version", "name", "description", "creator", "homepageURL", 
  7161.                        "updateURL", "updateService", "optionsURL", "aboutURL", 
  7162.                        "iconURL", "internalName"];
  7163.  
  7164.     // Items installed into restricted Install Locations can also be locked 
  7165.     // (can't be removed or disabled), and hidden (not shown in the UI)
  7166.     if (installLocation.restricted)
  7167.       singleProps = singleProps.concat(["locked", "hidden"]);
  7168.     if (installLocation.name == KEY_APP_GLOBAL) 
  7169.       singleProps = singleProps.concat(["appManaged"]);
  7170.     for (var i = 0; i < singleProps.length; ++i) {
  7171.       var property = EM_R(singleProps[i]);
  7172.       var literal = installManifest.GetTarget(gInstallManifestRoot, property, true);
  7173.       // If literal is null, _setProperty will remove any existing.
  7174.       this._setProperty(this._inner, targetRes, property, literal);
  7175.     }    
  7176.     
  7177.     // Assert properties with multiple values    
  7178.     var manyProps = ["developer", "translator", "contributor"];
  7179.     for (var i = 0; i < manyProps.length; ++i) {
  7180.       var property = EM_R(manyProps[i]);
  7181.       var literals = installManifest.GetTargets(gInstallManifestRoot, property, true);
  7182.       
  7183.       var oldValues = this._inner.GetTargets(targetRes, property, true);
  7184.       while (oldValues.hasMoreElements()) {
  7185.         var oldValue = oldValues.getNext().QueryInterface(Components.interfaces.nsIRDFNode);
  7186.         this._inner.Unassert(targetRes, property, oldValue);
  7187.       }
  7188.       while (literals.hasMoreElements()) {
  7189.         var literal = literals.getNext().QueryInterface(Components.interfaces.nsIRDFNode);
  7190.         this._inner.Assert(targetRes, property, literal, true);
  7191.       }
  7192.     }
  7193.  
  7194.     // Version/Dependency Info
  7195.     var versionProps = ["targetApplication", "requires"];
  7196.     var idRes = EM_R("id");
  7197.     var minVersionRes = EM_R("minVersion");
  7198.     var maxVersionRes = EM_R("maxVersion");
  7199.     for (var i = 0; i < versionProps.length; ++i) {
  7200.       var property = EM_R(versionProps[i]);
  7201.       var newVersionInfos = installManifest.GetTargets(gInstallManifestRoot, property, true);
  7202.  
  7203.       var oldVersionInfos = this._inner.GetTargets(targetRes, property, true);
  7204.       while (oldVersionInfos.hasMoreElements()) {
  7205.         var oldVersionInfo = oldVersionInfos.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  7206.         this._cleanResource(oldVersionInfo);
  7207.         this._inner.Unassert(targetRes, property, oldVersionInfo);
  7208.       }
  7209.       while (newVersionInfos.hasMoreElements()) {
  7210.         var newVersionInfo = newVersionInfos.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  7211.         var anon = gRDF.GetAnonymousResource();
  7212.         this._inner.Assert(anon, idRes, installManifest.GetTarget(newVersionInfo, idRes, true), true);
  7213.         this._inner.Assert(anon, minVersionRes, installManifest.GetTarget(newVersionInfo, minVersionRes, true), true);
  7214.         this._inner.Assert(anon, maxVersionRes, installManifest.GetTarget(newVersionInfo, maxVersionRes, true), true);
  7215.         this._inner.Assert(targetRes, property, anon, true);
  7216.       }
  7217.     }
  7218.     this.updateProperty(id, "opType");
  7219.     this.updateProperty(id, "updateable");
  7220.     this.Flush();
  7221.   },
  7222.   
  7223.   /**
  7224.    * Strips an item entry of all assertions.
  7225.    * @param   id
  7226.    *          The GUID of the item
  7227.    */
  7228.   removeItemMetadata: function(id) {
  7229.     var item = getResourceForID(id);
  7230.     var resources = ["targetApplication", "requires"];
  7231.     for (var i = 0; i < resources.length; ++i) {
  7232.       var targetApps = this._inner.GetTargets(item, EM_R(resources[i]), true);
  7233.       while (targetApps.hasMoreElements()) {
  7234.         var targetApp = targetApps.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  7235.         this._cleanResource(targetApp);
  7236.       }
  7237.     }
  7238.  
  7239.     this._cleanResource(item);
  7240.   },
  7241.   
  7242.   /**
  7243.    * Strips a resource of all outbound assertions. We use methods like this 
  7244.    * since the RDFXMLDatasource will write out all assertions, even if they
  7245.    * are not connected through our root. 
  7246.    * @param   resource
  7247.    *          The resource to clean. 
  7248.    */
  7249.   _cleanResource: function(resource) {
  7250.     // Remove outward arcs
  7251.     var arcs = this._inner.ArcLabelsOut(resource);
  7252.     while (arcs.hasMoreElements()) {
  7253.       var arc = arcs.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  7254.       var targets = this._inner.GetTargets(resource, arc, true);
  7255.       while (targets.hasMoreElements()) {
  7256.         var value = targets.getNext().QueryInterface(Components.interfaces.nsIRDFNode);
  7257.         if (value)
  7258.           this._inner.Unassert(resource, arc, value);
  7259.       }
  7260.     }
  7261.   },
  7262.   
  7263.   /**
  7264.    * Notify views that this propery has changed (this is for properties that
  7265.    * are implemented by this datasource rather than by the inner in-memory
  7266.    * datasource and thus do not get free change handling).
  7267.    * @param   id 
  7268.    *          The GUID of the item to update the property for.
  7269.    * @param   property
  7270.    *          The property (less EM_NS) to update.
  7271.    */
  7272.   updateProperty: function(id, property) {
  7273.     var item = getResourceForID(id);
  7274.     this._updateProperty(item, property);
  7275.   },
  7276.   
  7277.   /**
  7278.    * Notify views that this propery has changed (this is for properties that
  7279.    * are implemented by this datasource rather than by the inner in-memory
  7280.    * datasource and thus do not get free change handling). This allows updating
  7281.    * properties for download items which don't have the em item prefix in there
  7282.    ( resource value. In most instances updateProperty should be used.
  7283.    * @param   item
  7284.    *          The item to update the property for.
  7285.    * @param   property
  7286.    *          The property (less EM_NS) to update.
  7287.    */
  7288.   _updateProperty: function(item, property) {
  7289.     var propertyResource = EM_R(property);
  7290.     var value = this.GetTarget(item, propertyResource, true);
  7291.     if (item && value) {
  7292.       for (var i = 0; i < this._observers.length; ++i)
  7293.         this._observers[i].onChange(this, item, propertyResource, 
  7294.                                     EM_L(""), value);
  7295.     }
  7296.   },
  7297.   
  7298.   /**
  7299.    * Move an Item to the index of another item in its container.
  7300.    * @param   movingID
  7301.    *          The ID of the item to be moved.
  7302.    * @param   destinationID
  7303.    *          The ID of an item to move another item to.
  7304.    */
  7305.   moveToIndexOf: function(movingID, destinationID) {
  7306.     var extensions = gRDF.GetResource(RDFURI_ITEM_ROOT);
  7307.     var ctr = getContainer(this._inner, extensions);
  7308.     var item = gRDF.GetResource(movingID);
  7309.     var index = ctr.IndexOf(gRDF.GetResource(destinationID));
  7310.     if (index == -1)
  7311.       index = 1; // move to the beginning if destinationID is not found
  7312.     this._inner.beginUpdateBatch();
  7313.     ctr.RemoveElement(item, true);
  7314.     ctr.InsertElementAt(item, index, true);
  7315.     this._inner.endUpdateBatch();
  7316.     this.Flush();
  7317.   },
  7318.  
  7319.   /**
  7320.    * Sorts addons of the specified type by the specified property starting from
  7321.    * the top of their container. If the addons are already sorted then no action
  7322.    * is performed.
  7323.    * @param   type
  7324.    *          The nsIUpdateItem type of the items to sort.
  7325.    * @param   propertyName
  7326.    *          The RDF property name used for sorting.
  7327.    * @param   isAscending
  7328.    *          true to sort ascending and false to sort descending
  7329.    */
  7330.   sortTypeByProperty: function(type, propertyName, isAscending) {
  7331.     var items = [];
  7332.     var ctr = getContainer(this._inner, this._itemRoot);
  7333.     var elements = ctr.GetElements();
  7334.     // Base 0 ordinal for checking against the existing order after sorting
  7335.     var ordinal = 0;
  7336.     while (elements.hasMoreElements()) {
  7337.       var item = elements.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  7338.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7339.       var itemType = this.getItemProperty(id, "type");
  7340.       if (itemType & type) {
  7341.         items.push({ item   : item,
  7342.                      ordinal: ordinal,
  7343.                      sortkey: this.getItemProperty(id, propertyName).toLowerCase() });
  7344.         ordinal++;
  7345.       }
  7346.     }
  7347.  
  7348.     var direction = isAscending ? 1 : -1; 
  7349.     // Case insensitive sort
  7350.     function compare(a, b) {
  7351.         if (a.sortkey < b.sortkey) return (-1 * direction);
  7352.         if (a.sortkey > b.sortkey) return (1 * direction);
  7353.         return 0;
  7354.     }
  7355.     items.sort(compare);
  7356.  
  7357.     // Check if there are any changes in the order of the items
  7358.     var isDirty = false;
  7359.     for (var i = 0; i < items.length; i++) {
  7360.       if (items[i].ordinal != i) {
  7361.         isDirty = true;
  7362.         break;
  7363.       }
  7364.     }
  7365.  
  7366.     // If there are no changes then early return to avoid the perf impact
  7367.     if (!isDirty)
  7368.       return;
  7369.  
  7370.     // Reorder the items by moving them to the top of the container
  7371.     this.beginUpdateBatch();
  7372.     for (i = 0; i < items.length; i++) {
  7373.       ctr.RemoveElement(items[i].item, true);
  7374.       ctr.InsertElementAt(items[i].item, i + 1, true);
  7375.     }
  7376.     this.endUpdateBatch();
  7377.     this.Flush();
  7378.   },
  7379.  
  7380.   /**
  7381.    * Determines if an Item is an active download
  7382.    * @param   id
  7383.    *          The ID of the item. This will be a uri scheme without the
  7384.    *          em item prefix so getProperty shouldn't be used.
  7385.    * @returns true if the item is an active download, false otherwise.
  7386.    */
  7387.   isDownloadItem: function(id) {
  7388.     var downloadURL = stringData(this.GetTarget(gRDF.GetResource(id), EM_R("downloadURL"), true));
  7389.     return downloadURL && downloadURL != "";
  7390.   },
  7391.  
  7392.   /**
  7393.    * Adds an entry representing an active download to the appropriate container
  7394.    * @param   addon
  7395.    *          An object implementing nsIUpdateItem for the addon being 
  7396.    *          downloaded.
  7397.    */
  7398.   addDownload: function(addon) {
  7399.     // Updates have already been added to the datasource so we just update the
  7400.     // download state.
  7401.     if (addon.id != addon.xpiURL) {
  7402.       this.updateDownloadState(PREFIX_ITEM_URI + addon.id, "waiting");
  7403.       return;
  7404.     }
  7405.     var res = gRDF.GetResource(addon.xpiURL);
  7406.     this._setProperty(this._inner, res, EM_R("name"), EM_L(addon.name));
  7407.     this._setProperty(this._inner, res, EM_R("version"), EM_L(addon.version));
  7408.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(addon.iconURL));
  7409.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(addon.xpiURL));
  7410.     this._setProperty(this._inner, res, EM_R("type"), EM_I(addon.type));
  7411.  
  7412.     var ctr = getContainer(this._inner, this._itemRoot);
  7413.     if (ctr.IndexOf(res) == -1)
  7414.       ctr.AppendElement(res);
  7415.     
  7416.     this.updateDownloadState(addon.xpiURL, "waiting");
  7417.     this.Flush();
  7418.   },
  7419.   
  7420.   /**
  7421.    * Adds an entry representing an item that is incompatible and is being
  7422.    * checked for a compatibility update.
  7423.    * @param   name
  7424.    *          The display name of the item being checked
  7425.    * @param   url
  7426.    *          The URL string of the xpi file that has been staged.
  7427.    * @param   type
  7428.    *          The nsIUpdateItem type of the item
  7429.    * @param   version
  7430.    *          The version of the item
  7431.    */
  7432.   addIncompatibleUpdateItem: function(name, url, type, version) {
  7433.     var iconURL = (type == nsIUpdateItem.TYPE_THEME) ? URI_GENERIC_ICON_THEME :
  7434.                                                        URI_GENERIC_ICON_XPINSTALL;
  7435.     var extensionsStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  7436.     var updateMsg = extensionsStrings.formatStringFromName("incompatibleUpdateMessage",
  7437.                                                            [BundleManager.appName, name], 2)
  7438.  
  7439.     var res = gRDF.GetResource(url);
  7440.     this._setProperty(this._inner, res, EM_R("name"), EM_L(name));
  7441.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(iconURL));
  7442.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(url));
  7443.     this._setProperty(this._inner, res, EM_R("type"), EM_I(type));
  7444.     this._setProperty(this._inner, res, EM_R("version"), EM_L(version));
  7445.     this._setProperty(this._inner, res, EM_R("incompatibleUpdate"), EM_L("true"));
  7446.     this._setProperty(this._inner, res, EM_R("description"), EM_L(updateMsg));
  7447.  
  7448.     var ctr = getContainer(this._inner, this._itemRoot);
  7449.     if (ctr.IndexOf(res) == -1)
  7450.       ctr.AppendElement(res);
  7451.  
  7452.     this.updateDownloadState(url, "incompatibleUpdate");
  7453.     this.Flush();
  7454.   },
  7455.  
  7456.   /**
  7457.    * Removes an active download from the appropriate container
  7458.    * @param   url
  7459.    *          The URL string of the active download to be removed
  7460.    */
  7461.   removeDownload: function(url) {
  7462.     var res = gRDF.GetResource(url);
  7463.     var ctr = getContainer(this._inner, this._itemRoot);
  7464.     if (ctr.IndexOf(res) != -1) 
  7465.       ctr.RemoveElement(res, true);
  7466.     this._cleanResource(res);
  7467.     this.updateDownloadState(url, null);
  7468.     this.Flush();
  7469.   },
  7470.   
  7471.   /**
  7472.    * A hash of RDF resource values (e.g. Add-on IDs or XPI URLs) that represent
  7473.    * installation progress for a single browser session.
  7474.    */
  7475.   _progressData: { },
  7476.  
  7477.   /**
  7478.    * Updates the install progress data for a given ID (e.g. Add-on IDs or
  7479.    * XPI URLs).
  7480.    * @param   id
  7481.    *          The URL string of the active download to be removed
  7482.    * @param   state
  7483.    *          The current state in the installation process. If null the object
  7484.    *          is deleted from _progressData.
  7485.    */
  7486.   updateDownloadState: function(id, state) {
  7487.     if (!state) {
  7488.       if (id in this._progressData)
  7489.         delete this._progressData[id];
  7490.       return;
  7491.     }
  7492.     else {
  7493.       if (!(id in this._progressData)) 
  7494.         this._progressData[id] = { };
  7495.       this._progressData[id].state = state;
  7496.     }
  7497.     var item = gRDF.GetResource(id);
  7498.     this._updateProperty(item, "state");
  7499.   },
  7500.  
  7501.   updateDownloadProgress: function(id, progress) {
  7502.     if (!progress) {
  7503.       if (!(id in this._progressData))
  7504.         return;
  7505.       this._progressData[id].progress = null;
  7506.     }
  7507.     else {
  7508.       if (!(id in this._progressData))
  7509.         this.updateDownloadState(id, "downloading");
  7510.  
  7511.       if (this._progressData[id].progress == progress)
  7512.         return;
  7513.  
  7514.       this._progressData[id].progress = progress;
  7515.     }
  7516.     var item = gRDF.GetResource(id);
  7517.     this._updateProperty(item, "progress");
  7518.   },
  7519.  
  7520.   /**
  7521.    * A GUID->location-key hash of items that are visible to the application.
  7522.    * These are items that show up in the Extension/Themes etc UI. If there is
  7523.    * an instance of the same item installed in Install Locations of differing 
  7524.    * profiles, the item at the highest priority location will appear in this 
  7525.    * list.
  7526.    */
  7527.   visibleItems: { },
  7528.   
  7529.   /**
  7530.    * Walk the list of installed items and determine what the visible list is, 
  7531.    * based on which items are visible at the highest priority locations. 
  7532.    */  
  7533.   _buildVisibleItemList: function() {
  7534.     var ctr = getContainer(this, this._itemRoot);
  7535.     var items = ctr.GetElements();
  7536.     while (items.hasMoreElements()) {
  7537.       var item = items.getNext().QueryInterface(Components.interfaces.nsIRDFResource);
  7538.       // Resource URIs adopt the format: location-key,item-id
  7539.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7540.       this.visibleItems[id] = this.getItemProperty(id, "installLocation");
  7541.     }
  7542.   },
  7543.   
  7544.   /**
  7545.    * Updates an item's location in the visible item list.
  7546.    * @param   id
  7547.    *          The GUID of the item to update
  7548.    * @param   locationKey
  7549.    *          The name of the Install Location where the item is installed.
  7550.    * @param   forceReplace
  7551.    *          true if the new location should be used, regardless of its 
  7552.    *          priority relationship to existing entries, false if the location
  7553.    *          should only be updated if its priority is lower than the existing
  7554.    *          value.
  7555.    */
  7556.   updateVisibleList: function(id, locationKey, forceReplace) {
  7557.     if (id in this.visibleItems && this.visibleItems[id]) {
  7558.       var oldLocation = InstallLocations.get(this.visibleItems[id]);
  7559.       var newLocation = InstallLocations.get(locationKey);
  7560.       if (forceReplace || newLocation.priority < oldLocation.priority) 
  7561.         this.visibleItems[id] = locationKey;
  7562.     }
  7563.     else 
  7564.       this.visibleItems[id] = locationKey;
  7565.   },
  7566.  
  7567.   /**
  7568.    * Load the Extensions Datasource from disk.
  7569.    */
  7570.   loadExtensions: function() {
  7571.     Blocklist._ensureBlocklist();
  7572.     var extensionsFile  = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  7573.     try {
  7574.       this._inner = gRDF.GetDataSourceBlocking(getURLSpecFromFile(extensionsFile));
  7575.     }
  7576.     catch (e) {
  7577.       LOG("Datasource::loadExtensions: removing corrupted extensions datasource " +
  7578.           " file = " + extensionsFile.path + ", exception = " + e + "\n");
  7579.       extensionsFile.remove(false);
  7580.       return;
  7581.     }
  7582.  
  7583.     var cu = Components.classes["@mozilla.org/rdf/container-utils;1"]
  7584.                        .getService(Components.interfaces.nsIRDFContainerUtils);
  7585.     cu.MakeSeq(this._inner, this._itemRoot);
  7586.  
  7587.     this._buildVisibleItemList();
  7588.   },
  7589.   
  7590.   /**
  7591.    * See nsIExtensionManager.idl
  7592.    */
  7593.   onUpdateStarted: function() {
  7594.     LOG("Datasource: Update Started");
  7595.   },
  7596.   
  7597.   /**
  7598.    * See nsIExtensionManager.idl
  7599.    */
  7600.   onUpdateEnded: function() {
  7601.     LOG("Datasource: Update Ended");
  7602.   },
  7603.   
  7604.   /**
  7605.    * See nsIExtensionManager.idl
  7606.    */
  7607.   onAddonUpdateStarted: function(addon) {
  7608.     LOG("Datasource: Addon Update Started: " + addon.id);
  7609.     this.updateProperty(addon.id, "availableUpdateURL");
  7610.   },
  7611.   
  7612.   /**
  7613.    * See nsIExtensionManager.idl
  7614.    */
  7615.   onAddonUpdateEnded: function(addon, status) {
  7616.     LOG("Datasource: Addon Update Ended: " + addon.id + ", status: " + status);
  7617.     var url = null, hash = null, version = null;
  7618.     var updateAvailable = status == nsIAddonUpdateCheckListener.STATUS_UPDATE;
  7619.     if (updateAvailable) {
  7620.       url = EM_L(addon.xpiURL);
  7621.       if (addon.xpiHash)
  7622.         hash = EM_L(addon.xpiHash);
  7623.       version = EM_L(addon.version);
  7624.     }
  7625.     this.setItemProperty(addon.id, EM_R("availableUpdateURL"), url);
  7626.     this.setItemProperty(addon.id, EM_R("availableUpdateHash"), hash);
  7627.     this.setItemProperty(addon.id, EM_R("availableUpdateVersion"), version);
  7628.     this.updateProperty(addon.id, "availableUpdateURL");
  7629.   },
  7630.  
  7631.   /////////////////////////////////////////////////////////////////////////////
  7632.   // nsIRDFDataSource
  7633.   get URI() {
  7634.     return "rdf:extensions";
  7635.   },
  7636.   
  7637.   GetSource: function(property, target, truthValue) {
  7638.     return this._inner.GetSource(property, target, truthValue);
  7639.   },
  7640.   
  7641.   GetSources: function(property, target, truthValue) {
  7642.     return this._inner.GetSources(property, target, truthValue);
  7643.   },
  7644.   
  7645.   /**
  7646.    * Gets an URL to a theme's image file
  7647.    * @param   item
  7648.    *          The RDF Resource representing the item 
  7649.    * @param   fileName
  7650.    *          The file to locate a URL for
  7651.    * @param   fallbackURL
  7652.    *          If the location fails, supply this URL instead
  7653.    * @returns An RDF Resource to the URL discovered, or the fallback
  7654.    *          if the discovery failed. 
  7655.    */
  7656.   _getThemeImageURL: function(item, fileName, fallbackURL) {
  7657.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7658.     var installLocation = this._em.getInstallLocation(id);
  7659.     var file = installLocation.getItemFile(id, fileName)
  7660.     if (file.exists())
  7661.       return gRDF.GetResource(getURLSpecFromFile(file));
  7662.  
  7663.     if (id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)) {
  7664.       var jarFile = getFile(KEY_APPDIR, [DIR_CHROME, FILE_DEFAULT_THEME_JAR]);
  7665.       var url = "jar:" + getURLSpecFromFile(jarFile) + "!/" + fileName;
  7666.       return gRDF.GetResource(url);
  7667.     }
  7668.  
  7669.     return fallbackURL ? gRDF.GetResource(fallbackURL) : null;
  7670.   },
  7671.  
  7672.   /**
  7673.    * Get the em:iconURL property (icon url of the item)
  7674.    */
  7675.   _rdfGet_iconURL: function(item, property) {
  7676.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7677.     var type = this.getItemProperty(id, "type");
  7678.     if (type & nsIUpdateItem.TYPE_THEME)
  7679.       return this._getThemeImageURL(item, "icon.png", URI_GENERIC_ICON_THEME);
  7680.  
  7681.     if (inSafeMode())
  7682.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  7683.  
  7684.     var hasIconURL = this._inner.hasArcOut(item, property);
  7685.     // If the addon doesn't have an IconURL property or it is disabled use the
  7686.     // generic icon URL instead.
  7687.     if (!hasIconURL || this.getItemProperty(id, "isDisabled") == "true")
  7688.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  7689.     var iconURL = stringData(this._inner.GetTarget(item, property, true));
  7690.     try {
  7691.       var uri = newURI(iconURL);
  7692.       var scheme = uri.scheme;
  7693.       // Only allow chrome URIs or when installing http(s) URIs.
  7694.       if (scheme == "chrome" || (scheme == "http" || scheme == "https") &&
  7695.           this._inner.hasArcOut(item, EM_R("downloadURL")))
  7696.         return null;
  7697.     }
  7698.     catch (e) {
  7699.     }
  7700.     // Use a generic icon URL for addons that have an invalid iconURL.
  7701.     return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  7702.   },
  7703.   
  7704.   /**
  7705.    * Get the em:previewImage property (preview image of the item)
  7706.    */
  7707.   _rdfGet_previewImage: function(item, property) {
  7708.     var type = this.getItemProperty(stripPrefix(item.Value, PREFIX_ITEM_URI), "type");
  7709.     if (type != -1 && type & nsIUpdateItem.TYPE_THEME)
  7710.       return this._getThemeImageURL(item, "preview.png", null);
  7711.     return null;
  7712.   },
  7713.   
  7714.   /**
  7715.    * If we're in safe mode, the item is disabled by the user or app, or the
  7716.    * item is to be upgraded force the generic about dialog for the item.
  7717.    */
  7718.   _rdfGet_aboutURL: function(item, property) {
  7719.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7720.     if (inSafeMode() || this.getItemProperty(id, "isDisabled") == "true" ||
  7721.         this.getItemProperty(id, "opType") == OP_NEEDS_UPGRADE)
  7722.       return EM_L("");
  7723.  
  7724.     return null;
  7725.   },
  7726.  
  7727.   _rdfGet_installDate: function(item, property) {
  7728.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7729.     var key = this.getItemProperty(id, "installLocation");
  7730.     if (key && key in StartupCache.entries && id in StartupCache.entries[key] &&
  7731.         StartupCache.entries[key][id] && StartupCache.entries[key][id].mtime)
  7732.       return EM_D(StartupCache.entries[key][id].mtime * 1000000);
  7733.     return null;
  7734.   },
  7735.  
  7736.   /**
  7737.    * Get the em:compatible property (whether or not this item is compatible)
  7738.    */
  7739.   _rdfGet_compatible: function(item, property) {
  7740.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7741.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  7742.     if (!targetAppInfo) {
  7743.       // When installing a new addon targetAppInfo does not exist yet
  7744.       if (this.getItemProperty(id, "opType") == OP_NEEDS_INSTALL)
  7745.         return EM_L("true");
  7746.       return EM_L("false");
  7747.     }
  7748.     
  7749.     getVersionChecker();
  7750.     var appVersion = gApp.version;
  7751.     if (gVersionChecker.compare(targetAppInfo.maxVersion, appVersion) < 0 || 
  7752.         gVersionChecker.compare(appVersion, targetAppInfo.minVersion) < 0) {
  7753.       // OK, this item is incompatible. 
  7754.       return EM_L("false");
  7755.     }
  7756.     return EM_L("true");
  7757.   }, 
  7758.  
  7759.   /**
  7760.    * Get the em:blocklisted property (whether or not this item is blocklisted)
  7761.    */
  7762.   _rdfGet_blocklisted: function(item, property) {
  7763.     Blocklist._ensureBlocklist();
  7764.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7765.     var blItem = Blocklist.entries[id];
  7766.     if (!blItem)
  7767.       return EM_L("false");
  7768.  
  7769.     getVersionChecker();
  7770.     var version = this.getItemProperty(id, "version");
  7771.     var appVersion = gApp.version;
  7772.     for (var i = 0; i < blItem.length; ++i) {
  7773.       if (gVersionChecker.compare(version, blItem[i].minVersion) < 0  ||
  7774.           gVersionChecker.compare(version, blItem[i].maxVersion) > 0)
  7775.         continue;
  7776.  
  7777.       var blTargetApp = blItem[i].targetApps[gApp.ID];
  7778.       if (blTargetApp) {
  7779.         for (var x = 0; x < blTargetApp.length; ++x) {
  7780.           if (gVersionChecker.compare(appVersion, blTargetApp[x].minVersion) < 0  ||
  7781.               gVersionChecker.compare(appVersion, blTargetApp[x].maxVersion) > 0)
  7782.             continue;
  7783.           return EM_L("true");
  7784.         }
  7785.       }
  7786.  
  7787.       blTargetApp = blItem[i].targetApps[TOOLKIT_ID];
  7788.       if (!blTargetApp)
  7789.         return EM_L("false");
  7790.       for (x = 0; x < blTargetApp.length; ++x) {
  7791.         if (gVersionChecker.compare(gApp.platformVersion, blTargetApp[x].minVersion) < 0  ||
  7792.             gVersionChecker.compare(gApp.platformVersion, blTargetApp[x].maxVersion) > 0)
  7793.           continue;
  7794.         return EM_L("true");
  7795.       }
  7796.     }
  7797.     return EM_L("false");
  7798.   }, 
  7799.   
  7800.   /**
  7801.    * Get the em:state property (represents the current phase of an install).
  7802.    */
  7803.   _rdfGet_state: function(item, property) {
  7804.     var id = item.Value;
  7805.     if (id in this._progressData)
  7806.       return EM_L(this._progressData[id].state);
  7807.     return null;
  7808.   },
  7809.  
  7810.   /**
  7811.    * Get the em:progress property from the _progressData js object. By storing
  7812.    * progress which is updated repeastedly during a download we avoid
  7813.    * repeastedly writing it to the rdf file.
  7814.    */
  7815.   _rdfGet_progress: function(item, property) {
  7816.     var id = item.Value;
  7817.     if (id in this._progressData)
  7818.       return EM_I(this._progressData[id].progress);
  7819.     return null;
  7820.   },
  7821.  
  7822.   /**
  7823.    * Get the em:appManaged property. This prevents extensions from hiding
  7824.    * extensions installed into locations other than the app-global location.
  7825.    */
  7826.   _rdfGet_appManaged: function(item, property) {
  7827.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7828.     var locationKey = this.getItemProperty(id, "installLocation");
  7829.     if (locationKey != KEY_APP_GLOBAL)
  7830.       return EM_L("false");
  7831.     return null;
  7832.   },
  7833.  
  7834.   /**
  7835.    * Get the em:hidden property. This prevents extensions from hiding
  7836.    * extensions installed into locations other than restricted locations.
  7837.    */
  7838.   _rdfGet_hidden: function(item, property) {
  7839.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7840.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  7841.     if (!installLocation || !installLocation.restricted)
  7842.       return EM_L("false");
  7843.     return null;
  7844.   },
  7845.  
  7846.   /**
  7847.    * Get the em:locked property. This prevents extensions from locking
  7848.    * extensions installed into locations other than restricted locations.
  7849.    */
  7850.   _rdfGet_locked: function(item, property) {
  7851.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7852.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  7853.     if (!installLocation || !installLocation.restricted)
  7854.       return EM_L("false");
  7855.     return null;
  7856.   },
  7857.  
  7858.   /** 
  7859.    * Gets the em:availableUpdateURL - the URL to an XPI update package, if
  7860.    * present, or a literal string "none" if there is no update XPI URL.
  7861.    * XXXrstrong we return none due to bug 331689 
  7862.    */
  7863.   _rdfGet_availableUpdateURL: function(item, property) {
  7864.     var value = this._inner.GetTarget(item, property, true);
  7865.     if (!value) 
  7866.       return EM_L("none");
  7867.     return value;
  7868.   },
  7869.  
  7870.   /**
  7871.    * Get the em:satisfiesDependencies property - literal string "false" for
  7872.    * dependencies not satisfied (e.g. dependency disabled, incorrect version,
  7873.    * not installed etc.), and literal string "true" for dependencies satisfied.
  7874.    */
  7875.   _rdfGet_satisfiesDependencies: function(item, property) {
  7876.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7877.     if (this.satisfiesDependencies(id))
  7878.       return EM_L("true");
  7879.     return EM_L("false");
  7880.   },
  7881.   
  7882.   /**
  7883.    * Get the em:opType property (controls widget state for the EM UI)
  7884.    * from the Startup Cache (e.g. extensions.cache)
  7885.    * XXXrstrong we return none for OP_NONE due to bug 331689 
  7886.    */
  7887.   _rdfGet_opType: function(item, property) {
  7888.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7889.     var key = this.getItemProperty(id, "installLocation");
  7890.     if (key in StartupCache.entries && id in StartupCache.entries[key] &&
  7891.         StartupCache.entries[key][id] && StartupCache.entries[key][id].op != OP_NONE)
  7892.       return EM_L(StartupCache.entries[key][id].op);
  7893.     return EM_L("none");
  7894.   },
  7895.  
  7896.   /**
  7897.    * Gets a localizable property. Install Manifests are generally only in one 
  7898.    * language, however an item can customize by providing localized prefs in 
  7899.    * the form:
  7900.    *
  7901.    *    extensions.{GUID}.[name|description|creator|homepageURL]
  7902.    *
  7903.    * to specify localized text for each of these properties.
  7904.    */
  7905.   _getLocalizablePropertyValue: function(item, property) {
  7906.     // These are localizable properties that a language pack supplied by the 
  7907.     // Extension may override.          
  7908.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/, 
  7909.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) + 
  7910.                     stripPrefix(property.Value, PREFIX_NS_EM);
  7911.     try {
  7912.       var value = gPref.getComplexValue(prefName, 
  7913.                                         Components.interfaces.nsIPrefLocalizedString);
  7914.       if (value.data) 
  7915.         return EM_L(value.data);
  7916.     }
  7917.     catch (e) {
  7918.     }
  7919.     return null;
  7920.   },
  7921.   
  7922.   /**
  7923.    * Get the em:name property (name of the item)
  7924.    */
  7925.   _rdfGet_name: function(item, property) {
  7926.     return this._getLocalizablePropertyValue(item, property);
  7927.   },
  7928.   
  7929.   /**
  7930.    * Get the em:description property (description of the item)
  7931.    */
  7932.   _rdfGet_description: function(item, property) {
  7933.     return this._getLocalizablePropertyValue(item, property);
  7934.   },
  7935.   
  7936.   /**
  7937.    * Get the em:creator property (creator of the item)
  7938.    */
  7939.   _rdfGet_creator: function(item, property) { 
  7940.     return this._getLocalizablePropertyValue(item, property);
  7941.   },
  7942.   
  7943.   /**
  7944.    * Get the em:homepageURL property (homepage URL of the item)
  7945.    */
  7946.   _rdfGet_homepageURL: function(item, property) {
  7947.     return this._getLocalizablePropertyValue(item, property);
  7948.   },
  7949.  
  7950.   /**
  7951.    * Get the em:isDisabled property. This will be true if the item has a
  7952.    * appDisabled or a userDisabled property that is true or OP_NEEDS_ENABLE.
  7953.    */
  7954.   _rdfGet_isDisabled: function(item, property) {
  7955.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7956.     if (this.getItemProperty(id, "userDisabled") == "true" ||
  7957.         this.getItemProperty(id, "appDisabled") == "true" ||
  7958.         this.getItemProperty(id, "userDisabled") == OP_NEEDS_ENABLE ||
  7959.         this.getItemProperty(id, "appDisabled") == OP_NEEDS_ENABLE)
  7960.       return EM_L("true");
  7961.     return EM_L("false");
  7962.   },
  7963.  
  7964.   _rdfGet_addonID: function(item, property) {
  7965.     var id = this._inner.GetTarget(item, EM_R("downloadURL"), true) ? item.Value :
  7966.                                                                       stripPrefix(item.Value, PREFIX_ITEM_URI);
  7967.     return EM_L(id);
  7968.   },
  7969.  
  7970.   /**
  7971.    * Get the em:updateable property - this specifies whether the item is
  7972.    * allowed to be updated
  7973.    */
  7974.   _rdfGet_updateable: function(item, property) {
  7975.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7976.     var opType = this.getItemProperty(id, "opType");
  7977.     if (opType == OP_NEEDS_INSTALL || opType == OP_NEEDS_UNINSTALL ||
  7978.         opType == OP_NEEDS_UPGRADE ||
  7979.         this.getItemProperty(id, "appManaged") == "true")
  7980.       return EM_L("false");
  7981.  
  7982.     if (getPref("getBoolPref", (PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, id), false)) == true)
  7983.       return EM_L("false");
  7984.  
  7985.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  7986.     if (!installLocation || !installLocation.canAccess)
  7987.       return EM_L("false");
  7988.  
  7989.     return EM_L("true");
  7990.   },
  7991.  
  7992.   /**
  7993.    * See nsIRDFDataSource.idl
  7994.    */
  7995.   GetTarget: function(source, property, truthValue) {
  7996.     if (!source)
  7997.       return null;
  7998.       
  7999.     var target = null;
  8000.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8001.     if (getter in this)
  8002.       target = this[getter](source, property);
  8003.  
  8004.     return target || this._inner.GetTarget(source, property, truthValue);
  8005.   },
  8006.   
  8007.   /**
  8008.    * Gets an enumeration of values of a localizable property. Install Manifests
  8009.    * are generally only in one language, however an item can customize by 
  8010.    * providing localized prefs in the form:
  8011.    *
  8012.    *    extensions.{GUID}.[contributor].1
  8013.    *    extensions.{GUID}.[contributor].2
  8014.    *    extensions.{GUID}.[contributor].3
  8015.    *    ...
  8016.    *
  8017.    * to specify localized text for each of these properties.
  8018.    */
  8019.   _getLocalizablePropertyValues: function(item, property) {
  8020.     // These are localizable properties that a language pack supplied by the 
  8021.     // Extension may override.          
  8022.     var values = [];
  8023.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/, 
  8024.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) + 
  8025.                     stripPrefix(property.Value, PREFIX_NS_EM);
  8026.     var i = 0;
  8027.     while (true) {
  8028.       try {
  8029.         var value = gPref.getComplexValue(prefName + "." + ++i, 
  8030.                                           Components.interfaces.nsIPrefLocalizedString);
  8031.         if (value.data) 
  8032.           values.push(EM_L(value.data));
  8033.       }
  8034.       catch (e) {
  8035.         try {
  8036.           var value = gPref.getComplexValue(prefName, 
  8037.                                             Components.interfaces.nsIPrefLocalizedString);
  8038.           if (value.data) 
  8039.             values.push(EM_L(value.data));
  8040.         }
  8041.         catch (e) {
  8042.         }
  8043.         break;
  8044.       }
  8045.     }
  8046.     return values.length > 0 ? values : null;
  8047.   },
  8048.  
  8049.   /**
  8050.    * Get the em:developer property (developers of the extension)
  8051.    */
  8052.   _rdfGets_developer: function(item, property) {
  8053.     return this._getLocalizablePropertyValues(item, property); 
  8054.   },
  8055.  
  8056.   /**
  8057.    * Get the em:translator property (translators of the extension)
  8058.    */
  8059.   _rdfGets_translator: function(item, property) {
  8060.     return this._getLocalizablePropertyValues(item, property); 
  8061.   },
  8062.   
  8063.   /**
  8064.    * Get the em:contributor property (contributors to the extension)
  8065.    */
  8066.   _rdfGets_contributor: function(item, property) {
  8067.     return this._getLocalizablePropertyValues(item, property); 
  8068.   },
  8069.   
  8070.   /**
  8071.    * See nsIRDFDataSource.idl
  8072.    */
  8073.   GetTargets: function(source, property, truthValue) {
  8074.     if (!source)
  8075.       return null;
  8076.       
  8077.     var ary = null;
  8078.     var propertyName = stripPrefix(property.Value, PREFIX_NS_EM);
  8079.     var getter = "_rdfGets_" + propertyName;
  8080.     if (getter in this)
  8081.       ary = this[getter](source, property);
  8082.     else {
  8083.       // The template builder calls GetTargets when single value properties
  8084.       // are used in a triple.
  8085.       getter = "_rdfGet_" + propertyName;
  8086.       if (getter in this)
  8087.         ary = [ this[getter](source, property) ];
  8088.     }
  8089.     
  8090.     return ary ? new ArrayEnumerator(ary) 
  8091.                : this._inner.GetTargets(source, property, truthValue);
  8092.   },
  8093.   
  8094.   Assert: function(source, property, target, truthValue) {
  8095.     this._inner.Assert(source, property, target, truthValue);
  8096.   },
  8097.   
  8098.   Unassert: function(source, property, target) {
  8099.     this._inner.Unassert(source, property, target);
  8100.   },
  8101.   
  8102.   Change: function(source, property, oldTarget, newTarget) {
  8103.     this._inner.Change(source, property, oldTarget, newTarget);
  8104.   },
  8105.  
  8106.   Move: function(oldSource, newSource, property, target) {
  8107.     this._inner.Move(oldSource, newSource, property, target);
  8108.   },
  8109.   
  8110.   HasAssertion: function(source, property, target, truthValue) {
  8111.     if (!source || !property || !target)
  8112.       return false;
  8113.  
  8114.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8115.     if (getter in this)
  8116.       return this[getter](source, property) == target;
  8117.     return this._inner.HasAssertion(source, property, target, truthValue);
  8118.   },
  8119.   
  8120.   _observers: [],
  8121.   AddObserver: function(observer) {
  8122.     for (var i = 0; i < this._observers.length; ++i) {
  8123.       if (this._observers[i] == observer) 
  8124.         return;
  8125.     }
  8126.     this._observers.push(observer);
  8127.     this._inner.AddObserver(observer);
  8128.   },
  8129.   
  8130.   RemoveObserver: function(observer) {
  8131.     for (var i = 0; i < this._observers.length; ++i) {
  8132.       if (this._observers[i] == observer) 
  8133.         this._observers.splice(i, 1);
  8134.     }
  8135.     this._inner.RemoveObserver(observer);
  8136.   },
  8137.   
  8138.   ArcLabelsIn: function(node) {
  8139.     return this._inner.ArcLabelsIn(node);
  8140.   },
  8141.   
  8142.   ArcLabelsOut: function(source) {
  8143.     return this._inner.ArcLabelsOut(source);
  8144.   },
  8145.   
  8146.   GetAllResources: function() {
  8147.     return this._inner.GetAllResources();
  8148.   },
  8149.   
  8150.   IsCommandEnabled: function(sources, command, arguments) {
  8151.     return this._inner.IsCommandEnabled(sources, command, arguments);
  8152.   },
  8153.   
  8154.   DoCommand: function(sources, command, arguments) {
  8155.     this._inner.DoCommand(sources, command, arguments);
  8156.   },
  8157.   
  8158.   GetAllCmds: function(source) {
  8159.     return this._inner.GetAllCmds(source);
  8160.   },
  8161.   
  8162.   hasArcIn: function(node, arc) {
  8163.     return this._inner.hasArcIn(node, arc);
  8164.   },
  8165.   
  8166.   hasArcOut: function(source, arc) {
  8167.     return this._inner.hasArcOut(source, arc);
  8168.   },
  8169.   
  8170.   beginUpdateBatch: function() {
  8171.     return this._inner.beginUpdateBatch();
  8172.   },
  8173.   
  8174.   endUpdateBatch: function() {
  8175.     return this._inner.endUpdateBatch();
  8176.   },
  8177.   
  8178.   /**
  8179.    * See nsIRDFRemoteDataSource.idl
  8180.    */
  8181.   get loaded() {
  8182.     throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  8183.   },
  8184.   
  8185.   Init: function(uri) {
  8186.   },
  8187.   
  8188.   Refresh: function(blocking) {
  8189.   },
  8190.   
  8191.   Flush: function() {
  8192.     if (this._inner instanceof Components.interfaces.nsIRDFRemoteDataSource)
  8193.       this._inner.Flush();
  8194.   },
  8195.   
  8196.   FlushTo: function(uri) {
  8197.   },
  8198.   
  8199.   /**
  8200.    * See nsISupports.idl
  8201.    */
  8202.   QueryInterface: function(iid) {
  8203.     if (!iid.equals(Components.interfaces.nsIRDFDataSource) &&
  8204.         !iid.equals(Components.interfaces.nsIRDFRemoteDataSource) && 
  8205.         !iid.equals(Components.interfaces.nsISupports))
  8206.       throw Components.results.NS_ERROR_NO_INTERFACE;
  8207.     return this;
  8208.   }
  8209. };
  8210.  
  8211. function UpdateItem () {
  8212. }
  8213. UpdateItem.prototype = {
  8214.   /**
  8215.    * See nsIUpdateService.idl
  8216.    */
  8217.   init: function(id, version, installLocationKey, minAppVersion, maxAppVersion,
  8218.                  name, downloadURL, xpiHash, iconURL, updateURL, type) {
  8219.     this._id                  = id;
  8220.     this._version             = version;
  8221.     this._installLocationKey  = installLocationKey;
  8222.     this._minAppVersion       = minAppVersion;
  8223.     this._maxAppVersion       = maxAppVersion;
  8224.     this._name                = name;
  8225.     this._downloadURL         = downloadURL;
  8226.     this._xpiHash             = xpiHash;
  8227.     this._iconURL             = iconURL;
  8228.     this._updateURL           = updateURL;
  8229.     this._type                = type;
  8230.   },
  8231.   
  8232.   /**
  8233.    * See nsIUpdateService.idl
  8234.    */
  8235.   get id()                { return this._id;                },
  8236.   get version()           { return this._version;           },
  8237.   get installLocationKey(){ return this._installLocationKey;},
  8238.   get minAppVersion()     { return this._minAppVersion;     },
  8239.   get maxAppVersion()     { return this._maxAppVersion;     },
  8240.   get name()              { return this._name;              },
  8241.   get xpiURL()            { return this._downloadURL;       },
  8242.   get xpiHash()           { return this._xpiHash;           },
  8243.   get iconURL()           { return this._iconURL            },
  8244.   get updateRDF()         { return this._updateURL;         },
  8245.   get type()              { return this._type;              },
  8246.  
  8247.   /**
  8248.    * See nsIUpdateService.idl
  8249.    */
  8250.   get objectSource() {
  8251.     return { id                 : this._id, 
  8252.              version            : this._version, 
  8253.              installLocationKey : this._installLocationKey,
  8254.              minAppVersion      : this._minAppVersion,
  8255.              maxAppVersion      : this._maxAppVersion,
  8256.              name               : this._name, 
  8257.              xpiURL             : this._downloadURL, 
  8258.              xpiHash            : this._xpiHash,
  8259.              iconURL            : this._iconURL, 
  8260.              updateRDF          : this._updateURL,
  8261.              type               : this._type 
  8262.            }.toSource();
  8263.   },
  8264.   
  8265.   /**
  8266.    * See nsISupports.idl
  8267.    */
  8268.   QueryInterface: function(iid) {
  8269.     if (!iid.equals(Components.interfaces.nsIUpdateItem) &&
  8270.         !iid.equals(Components.interfaces.nsISupports))
  8271.       throw Components.results.NS_ERROR_NO_INTERFACE;
  8272.     return this;
  8273.   }
  8274. };
  8275.  
  8276. var gModule = {
  8277.   registerSelf: function(componentManager, fileSpec, location, type) {
  8278.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  8279.     
  8280.     for (var key in this._objects) {
  8281.       var obj = this._objects[key];
  8282.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  8283.                                                fileSpec, location, type);
  8284.     }
  8285.  
  8286.     // Make the Extension Manager a startup observer
  8287.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  8288.                                     .getService(Components.interfaces.nsICategoryManager);
  8289.     categoryManager.addCategoryEntry("app-startup", this._objects.manager.className,
  8290.                                      "service," + this._objects.manager.contractID, 
  8291.                                      true, true, null);
  8292.   },
  8293.   
  8294.   getClassObject: function(componentManager, cid, iid) {
  8295.     if (!iid.equals(Components.interfaces.nsIFactory))
  8296.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  8297.  
  8298.     for (var key in this._objects) {
  8299.       if (cid.equals(this._objects[key].CID))
  8300.         return this._objects[key].factory;
  8301.     }
  8302.     
  8303.     throw Components.results.NS_ERROR_NO_INTERFACE;
  8304.   },
  8305.   
  8306.   _makeFactory: #1= function(ctor) {
  8307.     return { 
  8308.              createInstance: function (outer, iid) {
  8309.                if (outer != null)
  8310.                  throw Components.results.NS_ERROR_NO_AGGREGATION;
  8311.                return (new ctor()).QueryInterface(iid);
  8312.              } 
  8313.            };  
  8314.   },
  8315.   
  8316.   _objects: {
  8317.     manager: { CID        : ExtensionManager.prototype.classID,
  8318.                contractID : ExtensionManager.prototype.contractID,
  8319.                className  : ExtensionManager.prototype.classDescription,
  8320.                factory    : #1#(ExtensionManager)
  8321.              },
  8322.     item:    { CID        : Components.ID("{F3294B1C-89F4-46F8-98A0-44E1EAE92518}"),
  8323.                contractID : "@mozilla.org/updates/item;1",
  8324.                className  : "Update Item",
  8325.                factory    : #1#(UpdateItem)
  8326.              }
  8327.    },
  8328.  
  8329.   canUnload: function(componentManager) {
  8330.     return true;
  8331.   }
  8332. };
  8333.  
  8334. function NSGetModule(compMgr, fileSpec) {
  8335.   return gModule;
  8336. }
  8337.  
  8338.