Bug 1167238 - Part 3 - Clean up usage of sanitize.js to properly use Sanitizer.jsm. r=mak draft
authorJohann Hofmann <jhofmann@mozilla.com>
Thu, 18 Jan 2018 16:02:04 +0100
changeset 751170 e6696a5246db3f6ef9dd25aeab5d239d7fc7f8e3
parent 751169 63b0f274f8e84e4003edb61f2dace78981884048
child 751171 10577846b8a407d12f7459b270a5c5573cd425ad
push id97884
push userjhofmann@mozilla.com
push dateMon, 05 Feb 2018 17:07:12 +0000
reviewersmak
bugs1167238
milestone60.0a1
Bug 1167238 - Part 3 - Clean up usage of sanitize.js to properly use Sanitizer.jsm. r=mak This replaces all non-test usage of sanitize.js or legacy Sanitizer.jsm to use the new Sanitizer.jsm module which does not hold internal state and instead receives all configuration through function arguments (or by reading prefs). MozReview-Commit-ID: KitMVptuIG3
browser/base/content/sanitizeDialog.js
browser/base/moz.build
browser/components/customizableui/CustomizableWidgets.jsm
browser/components/extensions/ext-browsingData.js
browser/components/nsBrowserGlue.js
toolkit/components/places/Shutdown.h
--- a/browser/base/content/sanitizeDialog.js
+++ b/browser/base/content/sanitizeDialog.js
@@ -39,19 +39,16 @@ var gSanitizePromptDialog = {
   get warningBox() {
     return document.getElementById("sanitizeEverythingWarningBox");
   },
 
   init() {
     // This is used by selectByTimespan() to determine if the window has loaded.
     this._inited = true;
 
-    var s = new Sanitizer();
-    s.prefDomain = "privacy.cpd.";
-
     document.documentElement.getButton("accept").label =
       this.bundleBrowser.getString("sanitizeButtonOK");
 
     if (this.selectedTimespan === Sanitizer.TIMESPAN_EVERYTHING) {
       this.prepareWarning();
       this.warningBox.hidden = false;
       document.title =
         this.bundleBrowser.getString("sanitizeDialog2.everything.title");
@@ -86,37 +83,39 @@ var gSanitizePromptDialog = {
     }
     window.document.title =
       window.document.documentElement.getAttribute("noneverythingtitle");
   },
 
   sanitize() {
     // Update pref values before handing off to the sanitizer (bug 453440)
     this.updatePrefs();
-    var s = new Sanitizer();
-    s.prefDomain = "privacy.cpd.";
-
-    s.range = Sanitizer.getClearRange(this.selectedTimespan);
-    s.ignoreTimespan = !s.range;
 
     // As the sanitize is async, we disable the buttons, update the label on
     // the 'accept' button to indicate things are happening and return false -
     // once the async operation completes (either with or without errors)
     // we close the window.
     let docElt = document.documentElement;
     let acceptButton = docElt.getButton("accept");
     acceptButton.disabled = true;
     acceptButton.setAttribute("label",
                               this.bundleBrowser.getString("sanitizeButtonClearing"));
     docElt.getButton("cancel").disabled = true;
 
     try {
-      s.sanitize().catch(Components.utils.reportError)
-                  .then(() => window.close())
-                  .catch(Components.utils.reportError);
+      let range = Sanitizer.getClearRange(this.selectedTimespan);
+      let options = {
+        prefDomain: "privacy.cpd.",
+        ignoreTimespan: !range,
+        range,
+      };
+      Sanitizer.sanitize(null, options)
+        .catch(Components.utils.reportError)
+        .then(() => window.close())
+        .catch(Components.utils.reportError);
       return false;
     } catch (er) {
       Components.utils.reportError("Exception during sanitize: " + er);
       return true; // We *do* want to close immediately on error.
     }
   },
 
   /**
@@ -176,17 +175,17 @@ var gSanitizePromptDialog = {
   /**
    * Sanitizer.prototype.sanitize() requires the prefs to be up-to-date.
    * Because the type of this prefwindow is "child" -- and that's needed because
    * without it the dialog has no OK and Cancel buttons -- the prefs are not
    * updated on dialogaccept.  We must therefore manually set the prefs
    * from their corresponding preference elements.
    */
   updatePrefs() {
-    Sanitizer.prefs.setIntPref("timeSpan", this.selectedTimespan);
+    Services.prefs.setIntPref(Sanitizer.PREF_TIMESPAN, this.selectedTimespan);
 
     // Keep the pref for the download history in sync with the history pref.
     Preferences.get("privacy.cpd.downloads").value =
       Preferences.get("privacy.cpd.history").value;
 
     // Now manually set the prefs from their corresponding preference
     // elements.
     var prefs = this._getItemPrefs();
--- a/browser/base/moz.build
+++ b/browser/base/moz.build
@@ -34,16 +34,17 @@ BROWSER_CHROME_MANIFESTS += [
     'content/test/performance/browser.ini',
     'content/test/performance/hidpi/browser.ini',
     'content/test/performance/lowdpi/browser.ini',
     'content/test/permissions/browser.ini',
     'content/test/plugins/browser.ini',
     'content/test/popupNotifications/browser.ini',
     'content/test/popups/browser.ini',
     'content/test/referrer/browser.ini',
+    'content/test/sanitize/browser.ini',
     'content/test/sidebar/browser.ini',
     'content/test/siteIdentity/browser.ini',
     'content/test/static/browser.ini',
     'content/test/sync/browser.ini',
     'content/test/tabcrashed/browser.ini',
     'content/test/tabPrompts/browser.ini',
     'content/test/tabs/browser.ini',
     'content/test/touch/browser.ini',
--- a/browser/components/customizableui/CustomizableWidgets.jsm
+++ b/browser/components/customizableui/CustomizableWidgets.jsm
@@ -16,16 +16,17 @@ XPCOMUtils.defineLazyModuleGetters(this,
   BrowserUITelemetry: "resource:///modules/BrowserUITelemetry.jsm",
   PanelView: "resource:///modules/PanelMultiView.jsm",
   PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
   PlacesUIUtils: "resource:///modules/PlacesUIUtils.jsm",
   RecentlyClosedTabsAndWindowsMenuUtils: "resource:///modules/sessionstore/RecentlyClosedTabsAndWindowsMenuUtils.jsm",
   ShortcutUtils: "resource://gre/modules/ShortcutUtils.jsm",
   CharsetMenu: "resource://gre/modules/CharsetMenu.jsm",
   PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
+  Sanitizer: "resource:///modules/Sanitizer.jsm",
   SyncedTabs: "resource://services-sync/SyncedTabs.jsm",
 });
 
 XPCOMUtils.defineLazyGetter(this, "CharsetBundle", function() {
   const kCharsetBundle = "chrome://global/locale/charsetMenu.properties";
   return Services.strings.createBundle(kCharsetBundle);
 });
 XPCOMUtils.defineLazyGetter(this, "BrandBundle", function() {
@@ -892,45 +893,32 @@ if (AppConstants.platform == "win") {
 }
 CustomizableWidgets.push(preferencesButton);
 
 if (Services.prefs.getBoolPref("privacy.panicButton.enabled")) {
   CustomizableWidgets.push({
     id: "panic-button",
     type: "view",
     viewId: "PanelUI-panicView",
-    _sanitizer: null,
-    _ensureSanitizer() {
-      if (!this.sanitizer) {
-        let scope = {};
-        Services.scriptloader.loadSubScript("chrome://browser/content/sanitize.js",
-                                            scope);
-        this._Sanitizer = scope.Sanitizer;
-        this._sanitizer = new scope.Sanitizer();
-        this._sanitizer.ignoreTimespan = false;
-      }
-    },
-    _getSanitizeRange(aDocument) {
-      let group = aDocument.getElementById("PanelUI-panic-timeSpan");
-      return this._Sanitizer.getClearRange(+group.value);
-    },
+
     forgetButtonCalled(aEvent) {
       let doc = aEvent.target.ownerDocument;
-      this._ensureSanitizer();
-      this._sanitizer.range = this._getSanitizeRange(doc);
       let group = doc.getElementById("PanelUI-panic-timeSpan");
       BrowserUITelemetry.countPanicEvent(group.selectedItem.id);
       group.selectedItem = doc.getElementById("PanelUI-panic-5min");
       let itemsToClear = [
         "cookies", "history", "openWindows", "formdata", "sessions", "cache", "downloads"
       ];
       let newWindowPrivateState = PrivateBrowsingUtils.isWindowPrivate(doc.defaultView) ?
                                   "private" : "non-private";
-      this._sanitizer.items.openWindows.privateStateForNewWindow = newWindowPrivateState;
-      let promise = this._sanitizer.sanitize(itemsToClear);
+      let promise = Sanitizer.sanitize(itemsToClear, {
+        ignoreTimespan: false,
+        range: Sanitizer.getClearRange(+group.value),
+        privateStateForNewWindow: newWindowPrivateState,
+      });
       promise.then(function() {
         let otherWindow = Services.wm.getMostRecentWindow("navigator:browser");
         if (otherWindow.closed) {
           Cu.reportError("Got a closed window!");
         }
         if (otherWindow.PanicButtonNotifier) {
           otherWindow.PanicButtonNotifier.notify();
         } else {
--- a/browser/components/extensions/ext-browsingData.js
+++ b/browser/components/extensions/ext-browsingData.js
@@ -22,38 +22,30 @@ XPCOMUtils.defineLazyServiceGetter(this,
                                    "nsIQuotaManagerService");
 
 /**
 * A number of iterations after which to yield time back
 * to the system.
 */
 const YIELD_PERIOD = 10;
 
-const PREF_DOMAIN = "privacy.cpd.";
-
-XPCOMUtils.defineLazyGetter(this, "sanitizer", () => {
-  let sanitizer = new Sanitizer();
-  sanitizer.prefDomain = PREF_DOMAIN;
-  return sanitizer;
-});
-
 const makeRange = options => {
   return (options.since == null) ?
     null :
     [PlacesUtils.toPRTime(options.since), PlacesUtils.toPRTime(Date.now())];
 };
 
 const clearCache = () => {
   // Clearing the cache does not support timestamps.
-  return sanitizer.items.cache.clear();
+  return Sanitizer.items.cache.clear();
 };
 
 const clearCookies = async function(options) {
   let cookieMgr = Services.cookies;
-  // This code has been borrowed from sanitize.js.
+  // This code has been borrowed from Sanitizer.jsm.
   let yieldCounter = 0;
 
   if (options.since || options.hostnames) {
     // Iterate through the cookies and delete any created after our cutoff.
     for (const cookie of XPCOMUtils.IterSimpleEnumerator(cookieMgr.enumerator, Ci.nsICookie2)) {
       if ((!options.since || cookie.creationTime >= PlacesUtils.toPRTime(options.since)) &&
           (!options.hostnames || options.hostnames.includes(cookie.host.replace(/^\./, "")))) {
         // This cookie was created after our cutoff, clear it.
@@ -67,25 +59,25 @@ const clearCookies = async function(opti
     }
   } else {
     // Remove everything.
     cookieMgr.removeAll();
   }
 };
 
 const clearDownloads = options => {
-  return sanitizer.items.downloads.clear(makeRange(options));
+  return Sanitizer.items.downloads.clear(makeRange(options));
 };
 
 const clearFormData = options => {
-  return sanitizer.items.formdata.clear(makeRange(options));
+  return Sanitizer.items.formdata.clear(makeRange(options));
 };
 
 const clearHistory = options => {
-  return sanitizer.items.history.clear(makeRange(options));
+  return Sanitizer.items.history.clear(makeRange(options));
 };
 
 const clearIndexedDB = async function(options) {
   let promises = [];
 
   await new Promise(resolve => {
     quotaManagerService.getUsage(request => {
       if (request.resultCode != Components.results.NS_OK) {
@@ -145,17 +137,17 @@ const clearPasswords = async function(op
     }
   } else {
     // Remove everything.
     loginManager.removeAllLogins();
   }
 };
 
 const clearPluginData = options => {
-  return sanitizer.items.pluginData.clear(makeRange(options));
+  return Sanitizer.items.pluginData.clear(makeRange(options));
 };
 
 const clearServiceWorkers = async function() {
   // Clearing service workers does not support timestamps.
   let yieldCounter = 0;
 
   // Iterate through the service workers and remove them.
   let serviceWorkers = serviceWorkerManager.getAllRegistrations();
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -61,16 +61,17 @@ XPCOMUtils.defineLazyModuleGetters(this,
   PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
   PluralForm: "resource://gre/modules/PluralForm.jsm",
   PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
   ProcessHangMonitor: "resource:///modules/ProcessHangMonitor.jsm",
   ReaderParent: "resource:///modules/ReaderParent.jsm",
   RecentWindow: "resource:///modules/RecentWindow.jsm",
   RemotePrompt: "resource:///modules/RemotePrompt.jsm",
   SafeBrowsing: "resource://gre/modules/SafeBrowsing.jsm",
+  Sanitizer: "resource:///modules/Sanitizer.jsm",
   SessionStore: "resource:///modules/sessionstore/SessionStore.jsm",
   ShellService: "resource:///modules/ShellService.jsm",
   SimpleServiceDiscovery: "resource://gre/modules/SimpleServiceDiscovery.jsm",
   TabCrashHandler: "resource:///modules/ContentCrashHandlers.jsm",
   UIState: "resource://services-sync/UIState.jsm",
   UITour: "resource:///modules/UITour.jsm",
   WebChannel: "resource://gre/modules/WebChannel.jsm",
   WindowsRegistry: "resource://gre/modules/WindowsRegistry.jsm",
@@ -242,23 +243,16 @@ function BrowserGlue() {
                                      "@mozilla.org/widget/idleservice;1",
                                      "nsIIdleService");
 
   XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
                                 ChromeUtils.import("resource:///modules/distribution.js");
                                 return new DistributionCustomizer();
                               });
 
-  XPCOMUtils.defineLazyGetter(this, "_sanitizer",
-    function() {
-      let sanitizerScope = {};
-      Services.scriptloader.loadSubScript("chrome://browser/content/sanitize.js", sanitizerScope);
-      return sanitizerScope.Sanitizer;
-    });
-
   ChromeUtils.defineModuleGetter(this, "fxAccounts", "resource://gre/modules/FxAccounts.jsm");
   XPCOMUtils.defineLazyServiceGetter(this, "AlertsService", "@mozilla.org/alerts-service;1", "nsIAlertsService");
 
   this._init();
 }
 
 /*
  * OS X has the concept of zero-window sessions and therefore ignores the
@@ -507,17 +501,17 @@ BrowserGlue.prototype = {
             if (addon.type != "experiment") {
               this._notifyUnsignedAddonsDisabled();
               break;
             }
           }
         });
         break;
       case "test-initialize-sanitizer":
-        this._sanitizer.onStartup();
+        Sanitizer.onStartup();
         break;
       case "sync-ui-state:update":
         this._updateFxaBadges();
         break;
       case "handlersvc-store-initialized":
         // Initialize PdfJs when running in-process and remote. This only
         // happens once since PdfJs registers global hooks. If the PdfJs
         // extension is installed the init method below will be overridden
@@ -1059,17 +1053,17 @@ BrowserGlue.prototype = {
         }
       });
     }
 
     if (AppConstants.MOZ_CRASHREPORTER) {
       UnsubmittedCrashHandler.init();
     }
 
-    this._sanitizer.onStartup();
+    Sanitizer.onStartup();
     this._scheduleStartupIdleTasks();
     this._lateTasksIdleObserver = (idleService, topic, data) => {
       if (topic == "idle") {
         idleService.removeIdleObserver(this._lateTasksIdleObserver,
                                        LATE_TASKS_IDLE_TIME_SEC);
         delete this._lateTasksIdleObserver;
         this._scheduleArbitrarilyLateIdleTasks();
       }
@@ -2393,17 +2387,17 @@ BrowserGlue.prototype = {
     // leave it at its current value.
   },
 
   // ------------------------------
   // public nsIBrowserGlue members
   // ------------------------------
 
   sanitize: function BG_sanitize(aParentWindow) {
-    this._sanitizer.sanitize(aParentWindow);
+    Sanitizer.showUI(aParentWindow);
   },
 
   async ensurePlacesDefaultQueriesInitialized() {
     // This is the current smart bookmarks version, it must be increased every
     // time they change.
     // When adding a new smart bookmark below, its newInVersion property must
     // be set to the version it has been added in.  We will compare its value
     // to users' smartBookmarksVersion and add new smart bookmarks without
--- a/toolkit/components/places/Shutdown.h
+++ b/toolkit/components/places/Shutdown.h
@@ -23,17 +23,17 @@ class Database;
  * that forwards the notification to the Database instance).
  * Database::Observe first of all checks if initialization was completed
  * properly, to avoid race conditions, then it notifies "places-shutdown" to
  * legacy clients. Legacy clients are supposed to start and complete any
  * shutdown critical work in the same tick, since we won't wait for them.
 
  * PHASE 2 (Modern clients shutdown)
  * Modern clients should instead register as a blocker by passing a promise to
- * nsPIPlacesDatabase::shutdownClient (for example see sanitize.js), so they
+ * nsPIPlacesDatabase::shutdownClient (for example see Sanitizer.jsm), so they
  * block Places shutdown until the promise is resolved.
  * When profile-change-teardown is observed by async shutdown, it calls
  * ClientsShutdownBlocker::BlockShutdown. This class is registered as a teardown
  * phase blocker in Database::Init (see Database::mClientsShutdown).
  * ClientsShutdownBlocker::BlockShudown waits for all the clients registered
  * through nsPIPlacesDatabase::shutdownClient. When all the clients are done,
  * its `Done` method is invoked, and it stops blocking the shutdown phase, so
  * that it can continue.