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