home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / xulrunner-1.9.0.14 / components / nsExtensionManager.js < prev    next >
Encoding:
Text File  |  2009-09-02  |  321.9 KB  |  8,715 lines

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