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