Bug 520165 - Part9: remove old expiration code, r=mano
authorMarco Bonardo <mbonardo@mozilla.com>
Fri, 15 Jan 2010 17:40:19 +0100
changeset 37227 15937d3e58341a1e4aff8b04729f3cf9d94467d6
parent 37226 1a6355f9da5a6f7e43b906f49e487523f59c322e
child 37228 adc9abe1362f5ad5a721e5f2e6170773a6dff3bb
push idunknown
push userunknown
push dateunknown
reviewersmano
bugs520165
milestone1.9.3a1pre
Bug 520165 - Part9: remove old expiration code, r=mano
browser/app/profile/firefox.js
browser/components/places/tests/browser/browser_library_middleclick.js
toolkit/components/places/src/Makefile.in
toolkit/components/places/src/nsNavHistory.cpp
toolkit/components/places/src/nsNavHistory.h
toolkit/components/places/src/nsNavHistoryExpire.cpp
toolkit/components/places/src/nsNavHistoryExpire.h
toolkit/components/places/src/nsPlacesAutoComplete.js
toolkit/components/places/src/nsPlacesDBFlush.js
toolkit/components/places/tests/sync/test_expire_on_timed_flush.js
toolkit/components/places/tests/sync/test_expire_on_timed_flush_not_whole_entry.js
toolkit/components/places/tests/sync/test_expire_on_timed_flush_obeys_date.js
toolkit/components/places/tests/unit/test_expiration.js
toolkit/components/places/tests/unit/test_history_sidebar.js
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -306,24 +306,16 @@ pref("browser.search.update.interval", 2
 // Whether or not microsummary and generator updates are enabled
 pref("browser.microsummary.enabled", true);
 pref("browser.microsummary.updateGenerators", true);
 
 // enable search suggestions by default
 pref("browser.search.suggest.enabled", true);
 
 pref("browser.sessionhistory.max_entries", 50);
-#ifndef WINCE
-pref("browser.history_expire_days", 180);
-pref("browser.history_expire_days_min", 90);
-#else
-pref("browser.history_expire_days", 90);
-pref("browser.history_expire_days_min", 45);
-#endif
-pref("browser.history_expire_sites", 40000);
 
 // handle links targeting new windows
 // 0=default window, 1=current window/tab, 2=new window, 3=new tab in most recent window
 pref("browser.link.open_newwindow", 3);
 
 // 0: no restrictions - divert everything
 // 1: don't divert window.open at all
 // 2: don't divert window.open with features
--- a/browser/components/places/tests/browser/browser_library_middleclick.js
+++ b/browser/components/places/tests/browser/browser_library_middleclick.js
@@ -37,17 +37,17 @@
 
  /**
  * Tests middle-clicking items in the Library.
  */
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 
-const DISABLE_HISTORY_PREF = "browser.history_expire_days";
+const ENABLE_HISTORY_PREF = "places.history.enabled";
 
 var gLibrary = null;
 var gTests = [];
 var gCurrentTest = null;
 
 // Listener for TabOpen and tabs progress.
 var gTabsListener = {
   _loadedURIs: [],
@@ -257,17 +257,17 @@ function test() {
   ok(PlacesUtils, "PlacesUtils in context");
   ok(PlacesUIUtils, "PlacesUIUtils in context");
 
   // Add tabs listeners.
   gBrowser.tabContainer.addEventListener("TabOpen", gTabsListener, false);
   gBrowser.addTabsProgressListener(gTabsListener);
 
   // Temporary disable history, so we won't record pages navigation.
-  gPrefService.setIntPref(DISABLE_HISTORY_PREF, 0);
+  gPrefService.setBoolPref(ENABLE_HISTORY_PREF, false);
 
   // Window watcher for Library window.
   var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
            getService(Ci.nsIWindowWatcher);
   var windowObserver = {
     observe: function(aSubject, aTopic, aData) {
       if (aTopic === "domwindowopened") {
         ww.unregisterNotification(this);
@@ -313,18 +313,19 @@ function runNextTest() {
     // Close Library window.
     gLibrary.close();
 
     // Remove tabs listeners.
     gBrowser.tabContainer.removeEventListener("TabOpen", gTabsListener, false);
     gBrowser.removeTabsProgressListener(gTabsListener);
 
     // Restore history.
-    if (gPrefService.prefHasUserValue(DISABLE_HISTORY_PREF))
-      gPrefService.clearUserPref(DISABLE_HISTORY_PREF);
+    try {
+      gPrefService.clearUserPref(ENABLE_HISTORY_PREF);
+    } catch(ex) {}
 
     finish();
   }
 }
 
 function mouseEventOnCell(aTree, aRowIndex, aColumnIndex, aEventDetails) {
   var selection = aTree.view.selection;
   selection.select(aRowIndex);
--- a/toolkit/components/places/src/Makefile.in
+++ b/toolkit/components/places/src/Makefile.in
@@ -51,17 +51,16 @@ MODULE_NAME = nsPlacesModule
 IS_COMPONENT = 1
 
 
 CPPSRCS = \
           nsAnnoProtocolHandler.cpp \
           nsAnnotationService.cpp \
           nsFaviconService.cpp \
           nsNavHistory.cpp \
-          nsNavHistoryExpire.cpp \
           nsNavHistoryQuery.cpp \
           nsNavHistoryResult.cpp \
           nsNavBookmarks.cpp \
           nsMaybeWeakPtr.cpp \
           nsMorkHistoryImporter.cpp \
           nsPlacesModule.cpp \
           SQLFunctions.cpp \
           Helpers.cpp \
--- a/toolkit/components/places/src/nsNavHistory.cpp
+++ b/toolkit/components/places/src/nsNavHistory.cpp
@@ -97,48 +97,44 @@ using namespace mozilla::places;
 // The maximum number of things that we will store in the recent events list
 // before calling ExpireNonrecentEvents. This number should be big enough so it
 // is very difficult to get that many unconsumed events (for example, typed but
 // never visited) in the RECENT_EVENT_THRESHOLD. Otherwise, we'll start
 // checking each one for every page visit, which will be somewhat slower.
 #define RECENT_EVENT_QUEUE_MAX_LENGTH 128
 
 // preference ID strings
-#define PREF_BRANCH_BASE                        "browser."
-
-#define PREF_HISTORY_ENABLED                    "places.history.enabled"
-
-#define PREF_BROWSER_HISTORY_EXPIRE_DAYS_MIN    "history_expire_days_min"
-#define PREF_BROWSER_HISTORY_EXPIRE_DAYS_MAX    "history_expire_days"
-#define PREF_BROWSER_HISTORY_EXPIRE_SITES       "history_expire_sites"
-
-#define PREF_FRECENCY_NUM_VISITS                "places.frecency.numVisits"
-#define PREF_FRECENCY_FIRST_BUCKET_CUTOFF       "places.frecency.firstBucketCutoff"
-#define PREF_FRECENCY_SECOND_BUCKET_CUTOFF      "places.frecency.secondBucketCutoff"
-#define PREF_FRECENCY_THIRD_BUCKET_CUTOFF       "places.frecency.thirdBucketCutoff"
-#define PREF_FRECENCY_FOURTH_BUCKET_CUTOFF      "places.frecency.fourthBucketCutoff"
-#define PREF_FRECENCY_FIRST_BUCKET_WEIGHT       "places.frecency.firstBucketWeight"
-#define PREF_FRECENCY_SECOND_BUCKET_WEIGHT      "places.frecency.secondBucketWeight"
-#define PREF_FRECENCY_THIRD_BUCKET_WEIGHT       "places.frecency.thirdBucketWeight"
-#define PREF_FRECENCY_FOURTH_BUCKET_WEIGHT      "places.frecency.fourthBucketWeight"
-#define PREF_FRECENCY_DEFAULT_BUCKET_WEIGHT     "places.frecency.defaultBucketWeight"
-#define PREF_FRECENCY_EMBED_VISIT_BONUS         "places.frecency.embedVisitBonus"
-#define PREF_FRECENCY_LINK_VISIT_BONUS          "places.frecency.linkVisitBonus"
-#define PREF_FRECENCY_TYPED_VISIT_BONUS         "places.frecency.typedVisitBonus"
-#define PREF_FRECENCY_BOOKMARK_VISIT_BONUS      "places.frecency.bookmarkVisitBonus"
-#define PREF_FRECENCY_DOWNLOAD_VISIT_BONUS      "places.frecency.downloadVisitBonus"
-#define PREF_FRECENCY_PERM_REDIRECT_VISIT_BONUS "places.frecency.permRedirectVisitBonus"
-#define PREF_FRECENCY_TEMP_REDIRECT_VISIT_BONUS "places.frecency.tempRedirectVisitBonus"
-#define PREF_FRECENCY_DEFAULT_VISIT_BONUS       "places.frecency.defaultVisitBonus"
-#define PREF_FRECENCY_UNVISITED_BOOKMARK_BONUS  "places.frecency.unvisitedBookmarkBonus"
-#define PREF_FRECENCY_UNVISITED_TYPED_BONUS     "places.frecency.unvisitedTypedBonus"
-
-#define PREF_LAST_VACUUM                        "places.last_vacuum"
-
-#define PREF_CACHE_TO_MEMORY_PERCENTAGE         "places.database.cache_to_memory_percentage"
+#define PREF_PLACES_BRANCH_BASE                 "places."
+
+#define PREF_HISTORY_ENABLED                    "history.enabled"
+
+#define PREF_FRECENCY_NUM_VISITS                "frecency.numVisits"
+#define PREF_FRECENCY_FIRST_BUCKET_CUTOFF       "frecency.firstBucketCutoff"
+#define PREF_FRECENCY_SECOND_BUCKET_CUTOFF      "frecency.secondBucketCutoff"
+#define PREF_FRECENCY_THIRD_BUCKET_CUTOFF       "frecency.thirdBucketCutoff"
+#define PREF_FRECENCY_FOURTH_BUCKET_CUTOFF      "frecency.fourthBucketCutoff"
+#define PREF_FRECENCY_FIRST_BUCKET_WEIGHT       "frecency.firstBucketWeight"
+#define PREF_FRECENCY_SECOND_BUCKET_WEIGHT      "frecency.secondBucketWeight"
+#define PREF_FRECENCY_THIRD_BUCKET_WEIGHT       "frecency.thirdBucketWeight"
+#define PREF_FRECENCY_FOURTH_BUCKET_WEIGHT      "frecency.fourthBucketWeight"
+#define PREF_FRECENCY_DEFAULT_BUCKET_WEIGHT     "frecency.defaultBucketWeight"
+#define PREF_FRECENCY_EMBED_VISIT_BONUS         "frecency.embedVisitBonus"
+#define PREF_FRECENCY_LINK_VISIT_BONUS          "frecency.linkVisitBonus"
+#define PREF_FRECENCY_TYPED_VISIT_BONUS         "frecency.typedVisitBonus"
+#define PREF_FRECENCY_BOOKMARK_VISIT_BONUS      "frecency.bookmarkVisitBonus"
+#define PREF_FRECENCY_DOWNLOAD_VISIT_BONUS      "frecency.downloadVisitBonus"
+#define PREF_FRECENCY_PERM_REDIRECT_VISIT_BONUS "frecency.permRedirectVisitBonus"
+#define PREF_FRECENCY_TEMP_REDIRECT_VISIT_BONUS "frecency.tempRedirectVisitBonus"
+#define PREF_FRECENCY_DEFAULT_VISIT_BONUS       "frecency.defaultVisitBonus"
+#define PREF_FRECENCY_UNVISITED_BOOKMARK_BONUS  "frecency.unvisitedBookmarkBonus"
+#define PREF_FRECENCY_UNVISITED_TYPED_BONUS     "frecency.unvisitedTypedBonus"
+
+#define PREF_LAST_VACUUM                        "last_vacuum"
+
+#define PREF_CACHE_TO_MEMORY_PERCENTAGE         "database.cache_to_memory_percentage"
 
 // Default integer value for PREF_CACHE_TO_MEMORY_PERCENTAGE.
 // This is 6% of machine memory, giving 15MB for a user with 256MB of memory.
 // Out of this cache, SQLite will use at most the size of the database file.
 #define DATABASE_DEFAULT_CACHE_TO_MEMORY_PERCENTAGE 6
 
 // This is the schema version, update it at any schema change and add a
 // corresponding migrateVxx method below.
@@ -184,19 +180,16 @@ static const PRInt64 USECS_PER_DAY = LL_
 #define LAZY_MESSAGE_TIMEOUT (3 * PR_MSEC_PER_SEC)
 
 // the maximum number of times we'll postpone a lazy timer before committing
 // See StartLazyTimer()
 #define MAX_LAZY_TIMER_DEFERMENTS 2
 
 #endif // LAZY_ADD
 
-// Limit the number of items in the history for performance reasons
-#define EXPIRATION_CAP_SITES 40000
-
 // character-set annotation
 #define CHARSET_ANNO NS_LITERAL_CSTRING("URIProperties/characterSet")
 
 // These macros are used when splitting history by date.
 // These are the day containers and catch-all final container.
 #define HISTORY_ADDITIONAL_DATE_CONT_NUM 3
 // We use a guess of the number of months considering all of them 30 days
 // long, but we split only the last 6 months.
@@ -393,19 +386,16 @@ PLACES_FACTORY_SINGLETON_IMPLEMENTATION(
 
 
 nsNavHistory::nsNavHistory()
 : mBatchLevel(0)
 , mBatchHasTransaction(PR_FALSE)
 , mCachedNow(0)
 , mExpireNowTimer(nsnull)
 , mLastSessionID(0)
-, mExpireDaysMin(0)
-, mExpireDaysMax(0)
-, mExpireSites(0)
 , mHistoryEnabled(PR_TRUE)
 , mNumVisitsForFrecency(10)
 , mTagsFolder(-1)
 , mInPrivateBrowsing(PRIVATEBROWSING_NOTINITED)
 , mDatabaseStatus(DATABASE_STATUS_OK)
 , mCanNotify(true)
 , mCacheObservers("history-observers")
 {
@@ -428,27 +418,25 @@ nsNavHistory::~nsNavHistory()
   if (gHistoryService == this)
     gHistoryService = nsnull;
 }
 
 
 nsresult
 nsNavHistory::Init()
 {
-  nsresult rv;
-
-  // prefs (must be before DB init, which uses the pref service)
   nsCOMPtr<nsIPrefService> prefService =
-    do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = prefService->GetBranch(PREF_BRANCH_BASE, getter_AddRefs(mPrefBranch));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // prefs
-  LoadPrefs(PR_TRUE);
+    do_GetService(NS_PREFSERVICE_CONTRACTID);
+  nsCOMPtr<nsIPrefBranch> placesBranch;
+  NS_ENSURE_TRUE(prefService, NS_ERROR_OUT_OF_MEMORY);
+  nsresult rv = prefService->GetBranch(PREF_PLACES_BRANCH_BASE,
+                                       getter_AddRefs(placesBranch));
+  NS_ENSURE_SUCCESS(rv, rv);
+  mPrefBranch = do_QueryInterface(placesBranch);
+  LoadPrefs();
 
   // Init the database file.  If we won't be able to connect to the database it
   // is most likely corrupt, so we will backup it and create a new one.
   rv = InitDBFile(PR_FALSE);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Init the database schema.  If this will fail there's an high possibility
   // the schema is corrupt or incorrect, so we will force a new database
@@ -465,20 +453,16 @@ nsNavHistory::Init()
 
   // Initialize all the items that are not part of the on-disk database, like
   // views, temp tables, functions.  Do not initialize these in InitDBFile, or
   // in case of failure we would mark the database as corrupt and try to
   // replace it, even if it's sane.
   rv = InitAdditionalDBItems();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // Initialize expiration.  There's no need to do this before, since just now
-  // we have a valid database and a working connection.
-  mExpire = new nsNavHistoryExpire();
-
   // Notify we have finished database initialization.
   // Enqueue the notification, so if we init another service that requires
   // nsNavHistoryService we don't recursive try to get it.
   nsRefPtr<PlacesEvent> completeEvent =
     new PlacesEvent(TOPIC_PLACES_INIT_COMPLETE);
   rv = NS_DispatchToMainThread(completeEvent);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -490,27 +474,19 @@ nsNavHistory::Init()
   /*****************************************************************************
    *** IMPORTANT NOTICE!
    ***
    *** Nothing after these add observer calls should return anything but NS_OK.
    *** If a failure code is returned, this nsNavHistory object will be held onto
    *** by the observer service and the preference service. 
    ****************************************************************************/
 
-  nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefBranch);
-  if (pbi) {
-    pbi->AddObserver(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MAX, this, PR_FALSE);
-    pbi->AddObserver(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MIN, this, PR_FALSE);
-    pbi->AddObserver(PREF_BROWSER_HISTORY_EXPIRE_SITES, this, PR_FALSE);
-  }
-
-  nsCOMPtr<nsIPrefBranch2> prefs =
-    do_GetService("@mozilla.org/preferences-service;1");
-  if (prefs)
-    prefs->AddObserver(PREF_HISTORY_ENABLED, this, PR_FALSE);
+  // Observe preferences branch for changes.
+  if (mPrefBranch)
+    mPrefBranch->AddObserver("", this, PR_FALSE);
 
   nsCOMPtr<nsIObserverService> obsSvc =
     do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
   if (obsSvc) {
     (void)obsSvc->AddObserver(this, TOPIC_XPCOM_SHUTDOWN, PR_FALSE);
     (void)obsSvc->AddObserver(this, TOPIC_IDLE_DAILY, PR_FALSE);
     (void)obsSvc->AddObserver(this, NS_PRIVATE_BROWSING_SWITCH_TOPIC, PR_FALSE);
 #ifdef MOZ_XUL
@@ -701,22 +677,19 @@ nsNavHistory::InitDB()
   // The suggested setting for SQLite is FULL, but Storage defaults to NORMAL.
   rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "PRAGMA synchronous = FULL"));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Compute the size of the database cache using the device's memory size.
   // We don't use PRAGMA default_cache_size, since the database could be moved
   // among different devices and the value would adapt accordingly.
-  nsCOMPtr<nsIPrefBranch> prefs =
-    do_GetService("@mozilla.org/preferences-service;1");
-  NS_WARN_IF_FALSE(prefs, "Unable to get the preferences service");
   PRInt32 cachePercentage;
-  if (!prefs || NS_FAILED(prefs->GetIntPref(PREF_CACHE_TO_MEMORY_PERCENTAGE,
-                                            &cachePercentage)))
+  if (NS_FAILED(mPrefBranch->GetIntPref(PREF_CACHE_TO_MEMORY_PERCENTAGE,
+                                        &cachePercentage)))
     cachePercentage = DATABASE_DEFAULT_CACHE_TO_MEMORY_PERCENTAGE;
   // Sanity checks, we allow values between 0 (disable cache) and 50%.
   if (cachePercentage > 50)
     cachePercentage = 50;
   if (cachePercentage < 0)
     cachePercentage = 0;
   PRInt64 cacheSize = PR_GetPhysicalMemorySize() * cachePercentage / 100;
 
@@ -2033,79 +2006,81 @@ PRBool nsNavHistory::IsURIStringVisited(
 
   PRBool hasMore = PR_FALSE;
   rv = mDBIsPageVisited->ExecuteStep(&hasMore);
   NS_ENSURE_SUCCESS(rv, PR_FALSE);
   return hasMore;
 }
 
 
-nsresult
-nsNavHistory::LoadPrefs(PRBool aInitializing)
-{
-  if (! mPrefBranch)
-    return NS_OK;
-
-  mPrefBranch->GetIntPref(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MAX, &mExpireDaysMax);
-  mPrefBranch->GetIntPref(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MIN, &mExpireDaysMin);
-  // Cap max days to min days to prevent expiring pages younger than min
-  // NOTE: if history is disabled in preferences, then mExpireDaysMax == 0
-  if (mExpireDaysMax && mExpireDaysMax < mExpireDaysMin)
-    mExpireDaysMax = mExpireDaysMin;
-  if (NS_FAILED(mPrefBranch->GetIntPref(PREF_BROWSER_HISTORY_EXPIRE_SITES,
-                                        &mExpireSites)))
-    mExpireSites = EXPIRATION_CAP_SITES;
-
-  // get the frecency prefs
-  nsCOMPtr<nsIPrefBranch> prefs(do_GetService("@mozilla.org/preferences-service;1"));
-  if (prefs) {
-    prefs->GetBoolPref(PREF_HISTORY_ENABLED, &mHistoryEnabled);
-
-    prefs->GetIntPref(PREF_FRECENCY_NUM_VISITS, 
-      &mNumVisitsForFrecency);
-    prefs->GetIntPref(PREF_FRECENCY_FIRST_BUCKET_CUTOFF, 
-      &mFirstBucketCutoffInDays);
-    prefs->GetIntPref(PREF_FRECENCY_SECOND_BUCKET_CUTOFF,
-      &mSecondBucketCutoffInDays);
-    prefs->GetIntPref(PREF_FRECENCY_THIRD_BUCKET_CUTOFF, 
-      &mThirdBucketCutoffInDays);
-    prefs->GetIntPref(PREF_FRECENCY_FOURTH_BUCKET_CUTOFF, 
-      &mFourthBucketCutoffInDays);
-    prefs->GetIntPref(PREF_FRECENCY_EMBED_VISIT_BONUS, 
-      &mEmbedVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_LINK_VISIT_BONUS, 
-      &mLinkVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_TYPED_VISIT_BONUS, 
-      &mTypedVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_BOOKMARK_VISIT_BONUS, 
-      &mBookmarkVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_DOWNLOAD_VISIT_BONUS, 
-      &mDownloadVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_PERM_REDIRECT_VISIT_BONUS, 
-      &mPermRedirectVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_TEMP_REDIRECT_VISIT_BONUS, 
-      &mTempRedirectVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_DEFAULT_VISIT_BONUS, 
-      &mDefaultVisitBonus);
-    prefs->GetIntPref(PREF_FRECENCY_UNVISITED_BOOKMARK_BONUS, 
-      &mUnvisitedBookmarkBonus);
-    prefs->GetIntPref(PREF_FRECENCY_UNVISITED_TYPED_BONUS,
-      &mUnvisitedTypedBonus);
-    prefs->GetIntPref(PREF_FRECENCY_FIRST_BUCKET_WEIGHT, 
-      &mFirstBucketWeight);
-    prefs->GetIntPref(PREF_FRECENCY_SECOND_BUCKET_WEIGHT, 
-      &mSecondBucketWeight);
-    prefs->GetIntPref(PREF_FRECENCY_THIRD_BUCKET_WEIGHT, 
-      &mThirdBucketWeight);
-    prefs->GetIntPref(PREF_FRECENCY_FOURTH_BUCKET_WEIGHT, 
-      &mFourthBucketWeight);
-    prefs->GetIntPref(PREF_FRECENCY_DEFAULT_BUCKET_WEIGHT, 
-      &mDefaultWeight);
-  }
-  return NS_OK;
+void
+nsNavHistory::LoadPrefs()
+{
+  if (!mPrefBranch)
+    return;
+
+  // History preferences.
+  // Check the old preference and migrate disabled state.
+  nsCOMPtr<nsIPrefBranch> prefSvc = do_GetService(NS_PREFSERVICE_CONTRACTID);
+  PRInt32 oldDaysPref = 0;
+  if (prefSvc &&
+      NS_SUCCEEDED(prefSvc->GetIntPref("browser.history_expire_days",
+                                       &oldDaysPref))) {
+    if (!oldDaysPref) {
+      // Preserve history disabled state, for privacy reasons.
+      mPrefBranch->SetBoolPref(PREF_HISTORY_ENABLED, PR_FALSE);
+      mHistoryEnabled = PR_FALSE;
+    }
+    // Clear the old pref, otherwise we will keep using it.
+    prefSvc->ClearUserPref("browser.history_expire_days");
+  }
+  else
+    mPrefBranch->GetBoolPref(PREF_HISTORY_ENABLED, &mHistoryEnabled);
+
+  // Frecency preferences.
+  mPrefBranch->GetIntPref(PREF_FRECENCY_NUM_VISITS,
+    &mNumVisitsForFrecency);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_FIRST_BUCKET_CUTOFF,
+    &mFirstBucketCutoffInDays);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_SECOND_BUCKET_CUTOFF,
+    &mSecondBucketCutoffInDays);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_THIRD_BUCKET_CUTOFF,
+    &mThirdBucketCutoffInDays);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_FOURTH_BUCKET_CUTOFF,
+    &mFourthBucketCutoffInDays);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_EMBED_VISIT_BONUS,
+    &mEmbedVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_LINK_VISIT_BONUS,
+    &mLinkVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_TYPED_VISIT_BONUS,
+    &mTypedVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_BOOKMARK_VISIT_BONUS,
+    &mBookmarkVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_DOWNLOAD_VISIT_BONUS,
+    &mDownloadVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_PERM_REDIRECT_VISIT_BONUS,
+    &mPermRedirectVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_TEMP_REDIRECT_VISIT_BONUS,
+    &mTempRedirectVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_DEFAULT_VISIT_BONUS,
+    &mDefaultVisitBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_UNVISITED_BOOKMARK_BONUS,
+    &mUnvisitedBookmarkBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_UNVISITED_TYPED_BONUS,
+    &mUnvisitedTypedBonus);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_FIRST_BUCKET_WEIGHT,
+    &mFirstBucketWeight);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_SECOND_BUCKET_WEIGHT,
+    &mSecondBucketWeight);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_THIRD_BUCKET_WEIGHT,
+    &mThirdBucketWeight);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_FOURTH_BUCKET_WEIGHT,
+    &mFourthBucketWeight);
+  mPrefBranch->GetIntPref(PREF_FRECENCY_DEFAULT_BUCKET_WEIGHT,
+    &mDefaultWeight);
 }
 
 
 PRInt64
 nsNavHistory::GetNewSessionID()
 {
   // Use cached value if already initialized.
   if (mLastSessionID)
@@ -4480,20 +4455,16 @@ nsNavHistory::PreparePlacesForVisitsDele
  */
 nsresult
 nsNavHistory::CleanupPlacesOnVisitsDelete(const nsCString& aPlaceIdsQueryString)
 {
   // Return early if there is nothing to delete.
   if (aPlaceIdsQueryString.IsEmpty())
     return NS_OK;
 
-  // now that visits have been removed, run annotation expiration.
-  // this will remove all expire-able annotations for these URIs.
-  (void)mExpire->OnDeleteVisits();
-
   // if the entry is not bookmarked and is not a place: uri
   // then we can remove it from moz_places.
   // Note that we do NOT delete favicons. Any unreferenced favicons will be
   // deleted next time the browser is shut down.
   nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
       "DELETE FROM moz_places_view WHERE id IN ("
         "SELECT h.id FROM moz_places_temp h "
         "WHERE h.id IN ( ") + aPlaceIdsQueryString + NS_LITERAL_CSTRING(") "
@@ -4864,28 +4835,62 @@ nsNavHistory::RemoveVisitsByTimeframe(PR
 //
 //    This function is used to clear history.
 
 NS_IMETHODIMP
 nsNavHistory::RemoveAllPages()
 {
   NS_ASSERTION(NS_IsMainThread(), "This can only be called on the main thread");
 
+  mozStorageTransaction transaction(mDBConn, PR_FALSE);
+
 #ifdef LAZY_ADD
   // We must ensure to remove pages from the lazy messages queue too.
   CommitLazyMessages();
 #endif
 
-  // expire everything
-  mExpire->ClearHistory();
+  // reset frecency for all items that will _not_ be deleted
+  // Note, we set frecency to -visit_count since we use that value in our
+  // idle query to figure out which places to recalcuate frecency first.
+  // We must do this before deleting visits.
+  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
+    "UPDATE moz_places_view SET frecency = -MAX(visit_count, 1) "
+    "WHERE id IN("
+      "SELECT h.id FROM moz_places_temp h "
+      "WHERE EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) "
+      "UNION ALL "
+      "SELECT h.id FROM moz_places h "
+      "WHERE EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) "
+    ")"));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Expire visits, then let the paranoid functions do the cleanup for us.
+  rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
+      "DELETE FROM moz_historyvisits_view"));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Some of the remaining places could be place: urls or
+  // unvisited livemark items, so setting the frecency to -1
+  // will cause them to show up in the url bar autocomplete
+  // call FixInvalidFrecenciesForExcludedPlaces to handle that scenario.
+  rv = FixInvalidFrecenciesForExcludedPlaces();
+  if (NS_FAILED(rv))
+    NS_WARNING("failed to fix invalid frecencies");
+
+  rv = transaction.Commit();
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  // Expiration will take care of orphans.
+  ENUMERATE_OBSERVERS(mCanNotify, mCacheObservers, mObservers,
+                      nsINavHistoryObserver, OnClearHistory());
 
   // privacy cleanup, if there's an old history.dat around, just delete it
   nsCOMPtr<nsIFile> oldHistoryFile;
-  nsresult rv = NS_GetSpecialDirectory(NS_APP_HISTORY_50_FILE,
-                                       getter_AddRefs(oldHistoryFile));
+  rv = NS_GetSpecialDirectory(NS_APP_HISTORY_50_FILE,
+                              getter_AddRefs(oldHistoryFile));
   NS_ENSURE_SUCCESS(rv, rv);
 
   PRBool fileExists;
   if (NS_SUCCEEDED(oldHistoryFile->Exists(&fileExists)) && fileExists) {
     rv = oldHistoryFile->Remove(PR_FALSE);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
@@ -5541,33 +5546,24 @@ nsNavHistory::Observe(nsISupports *aSubj
       {
         e->GetNext(getter_AddRefs(observer));
         rv = observer->Observe(observer,
                                TOPIC_PLACES_INIT_COMPLETE,
                                nsnull);
       }
     }
 
-    nsCOMPtr<nsIPrefService> prefService =
-      do_GetService(NS_PREFSERVICE_CONTRACTID);
-    if (prefService) {
+    // Stop observing preferences changes.
+    if (mPrefBranch)
+      mPrefBranch->RemoveObserver("", this);
+
+    // Force a preferences save.
+    nsCOMPtr<nsIPrefService> prefService = do_QueryInterface(mPrefBranch);
+    if (prefService)
       prefService->SavePrefFile(nsnull);
-      nsCOMPtr<nsIPrefBranch2> prefs = do_QueryInterface(prefService);
-      prefs->RemoveObserver(PREF_HISTORY_ENABLED, this);
-    }
-
-    nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefBranch);
-    if (pbi) {
-      pbi->RemoveObserver(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MAX, this);
-      pbi->RemoveObserver(PREF_BROWSER_HISTORY_EXPIRE_DAYS_MIN, this);
-      pbi->RemoveObserver(PREF_BROWSER_HISTORY_EXPIRE_SITES, this);
-    }
-
-    // Start shutdown expiration.
-    mExpire->OnQuit();
 
 #ifdef LAZY_ADD
     // Commit all pending lazy messages.
     CommitLazyMessages(PR_TRUE);
 
     // Kill lazy timer or it could fire later when statements won't be valid
     // anymore.
     if (mLazyTimer) {
@@ -5613,23 +5609,17 @@ nsNavHistory::Observe(nsISupports *aSubj
     if (selectedIndex == -1)
       return NS_OK;
 
     rv = AutoCompleteFeedback(selectedIndex, controller);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 #endif
   else if (strcmp(aTopic, TOPIC_PREF_CHANGED) == 0) {
-    PRInt32 oldDaysMin = mExpireDaysMin;
-    PRInt32 oldDaysMax = mExpireDaysMax;
-    PRInt32 oldVisits = mExpireSites;
-    LoadPrefs(PR_FALSE);
-    if (oldDaysMin != mExpireDaysMin || oldDaysMax != mExpireDaysMax ||
-        oldVisits != mExpireSites)
-      mExpire->OnExpirationChanged();
+    LoadPrefs();
   }
   else if (strcmp(aTopic, TOPIC_IDLE_DAILY) == 0) {
     // Ensure our connection is still alive.  The idle-daily observer is removed
     // on xpcom-shutdown, but we could have closed the connection earlier due
     // to errors or during normal shutdown process.
     NS_ENSURE_TRUE(mDBConn, NS_OK);
 
     (void)DecayFrecency();
@@ -5684,20 +5674,18 @@ nsNavHistory::VacuumDatabase()
   // For this reason we just take a guess using the freelist count.
   // This way we know how much pages are unused, but we don't know anything
   // about fragmentation.
   // This ratio is used in conjunction with a time pref to avoid vacuuming too
   // often or too rarely.
 
   PRInt32 lastVacuumPref;
   PRInt64 lastVacuumTime = 0;
-  nsCOMPtr<nsIPrefBranch> prefSvc =
-    do_GetService("@mozilla.org/preferences-service;1");
-  NS_ENSURE_TRUE(prefSvc, NS_ERROR_OUT_OF_MEMORY);
-  if (NS_SUCCEEDED(prefSvc->GetIntPref(PREF_LAST_VACUUM, &lastVacuumPref))) {
+  if (mPrefBranch &&
+      NS_SUCCEEDED(mPrefBranch->GetIntPref(PREF_LAST_VACUUM, &lastVacuumPref))) {
     // Value are seconds till epoch, convert it to microseconds.
     lastVacuumTime = (PRInt64)lastVacuumPref * PR_USEC_PER_SEC;
   }
 
   nsresult rv;
   float freePagesRatio = 0;
   if (!lastVacuumTime ||
       (lastVacuumTime < (PR_Now() - DATABASE_MIN_TIME_BEFORE_VACUUM) &&
@@ -5770,24 +5758,26 @@ nsNavHistory::VacuumDatabase()
       vacuum,
       journalToDefault
     };
     nsCOMPtr<mozIStoragePendingStatement> ps;
     rv = mDBConn->ExecuteAsync(stmts, NS_ARRAY_LENGTH(stmts), nsnull,
                                getter_AddRefs(ps));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    rv = prefSvc->SetIntPref(PREF_LAST_VACUUM,
-                             (PRInt32)(PR_Now() / PR_USEC_PER_SEC));
-    NS_ENSURE_SUCCESS(rv, rv);
+    if (mPrefBranch) {
+      (void)mPrefBranch->SetIntPref(PREF_LAST_VACUUM,
+                                    (PRInt32)(PR_Now() / PR_USEC_PER_SEC));
+    }
   }
 
   return NS_OK;
 }
 
+
 nsresult
 nsNavHistory::DecayFrecency()
 {
   // Update frecency values.
   nsresult rv = FixInvalidFrecencies();
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Globally decay places frecency rankings to estimate reduced frecency
--- a/toolkit/components/places/src/nsNavHistory.h
+++ b/toolkit/components/places/src/nsNavHistory.h
@@ -46,30 +46,30 @@
 #include "nsPIPlacesDatabase.h"
 #include "nsPIPlacesHistoryListenersNotifier.h"
 #include "nsIBrowserHistory.h"
 #include "nsIGlobalHistory.h"
 #include "nsIGlobalHistory3.h"
 #include "nsIDownloadHistory.h"
 
 #include "nsIPrefService.h"
+#include "nsIPrefBranch2.h"
 #include "nsIObserverService.h"
 #include "nsICollation.h"
 #include "nsIStringBundle.h"
 #include "nsITimer.h"
 #include "nsMaybeWeakPtr.h"
 #include "nsCategoryCache.h"
 #include "nsICharsetResolver.h"
 #include "nsNetCID.h"
 #include "nsToolkitCompsCID.h"
 
 #include "nsINavBookmarksService.h"
 #include "nsIPrivateBrowsingService.h"
 
-#include "nsNavHistoryExpire.h"
 #include "nsNavHistoryResult.h"
 #include "nsNavHistoryQuery.h"
 
 #include "mozilla/storage.h"
 
 // define to enable lazy link adding
 #define LAZY_ADD
 
@@ -210,17 +210,17 @@ public:
   nsICollation* GetCollation();
   void GetStringFromName(const PRUnichar* aName, nsACString& aResult);
   void GetAgeInDaysString(PRInt32 aInt, const PRUnichar *aName,
                           nsACString& aResult);
   void GetMonthName(PRInt32 aIndex, nsACString& aResult);
 
   // Returns whether history is enabled or not.
   PRBool IsHistoryDisabled() {
-    return mExpireDaysMax == 0 || !mHistoryEnabled || InPrivateBrowsingMode();
+    return !mHistoryEnabled || InPrivateBrowsingMode();
   }
 
   // Constants for the columns returned by the above statement.
   static const PRInt32 kGetInfoIndex_PageID;
   static const PRInt32 kGetInfoIndex_URL;
   static const PRInt32 kGetInfoIndex_Title;
   static const PRInt32 kGetInfoIndex_RevHost;
   static const PRInt32 kGetInfoIndex_VisitCount;
@@ -371,20 +371,18 @@ public:
  private:
   ~nsNavHistory();
 
   // used by GetHistoryService
   static nsNavHistory *gHistoryService;
 
 protected:
 
-  //
-  // Constants
-  //
-  nsCOMPtr<nsIPrefBranch> mPrefBranch; // MAY BE NULL when we are shutting down
+  nsCOMPtr<nsIPrefBranch2> mPrefBranch; // MAY BE NULL when we are shutting down
+
   nsDataHashtable<nsStringHashKey, int> gExpandedItems;
 
   //
   // Database stuff
   //
   nsCOMPtr<mozIStorageService> mDBService;
   nsCOMPtr<mozIStorageConnection> mDBConn;
   nsCOMPtr<nsIFile> mDBFile;
@@ -496,42 +494,36 @@ protected:
   nsresult InternalAddVisit(PRInt64 aPageID, PRInt64 aReferringVisit,
                             PRInt64 aSessionID, PRTime aTime,
                             PRInt32 aTransitionType, PRInt64* aVisitID);
   PRBool FindLastVisit(nsIURI* aURI, PRInt64* aVisitID,
                        PRInt64* aSessionID);
   PRBool IsURIStringVisited(const nsACString& url);
 
   /**
-   * This loads all of the preferences that we use into member variables.
-   * NOTE:  If mPrefBranch is NULL, this does nothing.
+   * Loads all of the preferences that we use into member variables.
    *
-   * @param aInitializing
-   *        Indicates if the autocomplete queries should be regenerated or not.
+   * @note If mPrefBranch is NULL, this does nothing.
    */
-  nsresult LoadPrefs(PRBool aInitializing);
+  void LoadPrefs();
 
   /**
    * Calculates and returns value for mCachedNow.
    * This is an hack to avoid calling PR_Now() too often, as is the case when
    * we're asked the ageindays of many history entries in a row.  A timer is
    * set which will clear our valid flag after a short timeout.
    */
   PRTime GetNow();
   PRTime mCachedNow;
   nsCOMPtr<nsITimer> mExpireNowTimer;
   /**
    * Called when the cached now value is expired and needs renewal.
    */
   static void expireNowTimerCallback(nsITimer* aTimer, void* aClosure);
 
-  // expiration
-  friend class nsNavHistoryExpire;
-  nsNavHistoryExpire *mExpire;
-
 #ifdef LAZY_ADD
   // lazy add committing
   struct LazyMessage {
     enum MessageType { Type_Invalid, Type_AddURI, Type_Title, Type_Favicon };
     LazyMessage()
     {
       type = Type_Invalid;
       isRedirect = PR_FALSE;
@@ -653,20 +645,16 @@ protected:
   // AutoComplete stuff
   mozIStorageStatement *GetDBFeedbackIncrease();
   nsCOMPtr<mozIStorageStatement> mDBFeedbackIncrease;
 
   nsresult AutoCompleteFeedback(PRInt32 aIndex,
                                 nsIAutoCompleteController *aController);
 #endif
 
-  PRInt32 mExpireDaysMin;
-  PRInt32 mExpireDaysMax;
-  PRInt32 mExpireSites;
-
   // Whether history is enabled or not.
   // Will mimic value of the places.history.enabled preference.
   PRBool mHistoryEnabled;
 
   // Frecency preferences.
   PRInt32 mNumVisitsForFrecency;
   PRInt32 mFirstBucketCutoffInDays;
   PRInt32 mSecondBucketCutoffInDays;
deleted file mode 100644
--- a/toolkit/components/places/src/nsNavHistoryExpire.cpp
+++ /dev/null
@@ -1,957 +0,0 @@
-//* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is Mozilla History System
- *
- * The Initial Developer of the Original Code is
- * Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Brett Wilson <brettw@gmail.com> (original author)
- *   Dietrich Ayala <dietrich@mozilla.com>
- *   Marco Bonardo <mak77@bonardo.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/**
- * This class handles expiration of history for nsNavHistory. There is a 1-1
- * mapping between nsNavHistory class and a nsNavHistoryExpire class, the
- * code is separated for better understandability.
- */
-
-#include "nsNavHistory.h"
-#include "mozStorageHelper.h"
-#include "nsNetUtil.h"
-#include "nsIAnnotationService.h"
-#include "nsPrintfCString.h"
-#include "nsPlacesMacros.h"
-#include "nsIIdleService.h"
-
-struct nsNavHistoryExpireRecord {
-  nsNavHistoryExpireRecord(mozIStorageStatement* statement);
-
-  PRInt64 visitID;
-  PRInt64 placeID;
-  PRTime visitDate;
-  nsCString uri;
-  PRInt64 faviconID;
-  PRBool hidden;
-  PRBool bookmarked;
-  PRBool erased; // set to true if/when the history entry is erased
-};
-
-// The time in ms to wait before kick-off partial expiration after preferences
-// are changed.
-#define EXPIRATION_PARTIAL_TIMEOUT 500
-
-// The time in ms to wait between each partial expiration step.
-#define EXPIRATION_PARTIAL_SUBSEQUENT_TIMEOUT ((PRUint32)10 * PR_MSEC_PER_SEC)
-
-// Number of pages we'll expire at each partial expiration run.  Partial
-// expiration runs when expiration preferences run.
-#define EXPIRATION_PAGES_PER_RUN 6
-
-// The time in ms the user should be idle before we run expiration.
-// This will be repeated till we find enough entries to expire, otherwise
-// we will wait for a longer timeout before checking again.
-#define EXPIRATION_IDLE_TIMEOUT ((PRUint32)5 * 60 * PR_MSEC_PER_SEC)
-// The time in ms the user should be idle before we run expiration when the
-// previous call ran out of expirable pages.
-#define EXPIRATION_IDLE_LONG_TIMEOUT EXPIRATION_IDLE_TIMEOUT * 10
-
-// During idle we can expire a larger chunk of pages.
-#define EXPIRATION_MAX_PAGES_AT_IDLE 100
-
-// During shutdown we should cleanup any dangling moz_places record, but we
-// cannot expire a too large number of entries since that would slowdown
-// shutdown.
-#define EXPIRATION_MAX_PAGES_AT_SHUTDOWN 100
-
-// Expiration policy amounts in microseconds.
-const PRTime EXPIRATION_POLICY_DAYS = ((PRTime)7 * 86400 * PR_USEC_PER_SEC);
-const PRTime EXPIRATION_POLICY_WEEKS = ((PRTime)30 * 86400 * PR_USEC_PER_SEC);
-const PRTime EXPIRATION_POLICY_MONTHS = ((PRTime)180 * 86400 * PR_USEC_PER_SEC);
-
-// History preferences.
-#define PREF_BRANCH_BASE                        "browser."
-#define PREF_BROWSER_HISTORY_EXPIRE_DAYS        "history_expire_days"
-
-// Sanitization preferences
-#define PREF_SANITIZE_ON_SHUTDOWN   "privacy.sanitize.sanitizeOnShutdown"
-#define PREF_SANITIZE_ITEM_HISTORY  "privacy.item.history"
-
-nsNavHistoryExpire::nsNavHistoryExpire() :
-    mNextExpirationTime(0)
-{
-  mHistory = nsNavHistory::GetHistoryService();
-  NS_ASSERTION(mHistory, "History service should exist at this point.");
-  mDBConn = mHistory->GetStorageConnection();
-  NS_ASSERTION(mDBConn, "History service should have a valid database connection");
-
-  // Initialize idle timer.
-  InitializeIdleTimer(EXPIRATION_IDLE_TIMEOUT);
-}
-
-nsNavHistoryExpire::~nsNavHistoryExpire()
-{
-  // Cancel any pending timers.
-  if (mPartialExpirationTimer) {
-    mPartialExpirationTimer->Cancel();
-    mPartialExpirationTimer = 0;
-  }
-  if (mIdleTimer) {
-    mIdleTimer->Cancel();
-    mIdleTimer = 0;
-  }
-}
-
-void
-nsNavHistoryExpire::InitializeIdleTimer(PRUint32 aTimeInMs)
-{
-  if (mIdleTimer) {
-    mIdleTimer->Cancel();
-    mIdleTimer = 0;
-  }
-
-  mIdleTimer = do_CreateInstance("@mozilla.org/timer;1");
-  if (mIdleTimer) {
-    (void)mIdleTimer->InitWithFuncCallback(IdleTimerCallback, this, aTimeInMs,
-                                           nsITimer::TYPE_ONE_SHOT);
-  }
-}
-
-void // static
-nsNavHistoryExpire::IdleTimerCallback(nsITimer* aTimer, void* aClosure)
-{
-  nsNavHistoryExpire* expire = static_cast<nsNavHistoryExpire*>(aClosure);
-  expire->mIdleTimer = 0;
-  expire->OnIdle();
-}
-
-void
-nsNavHistoryExpire::OnIdle()
-{
-  PRUint32 idleTime = 0;
-  nsCOMPtr<nsIIdleService> idleService =
-    do_GetService("@mozilla.org/widget/idleservice;1");
-  if (idleService)
-    (void)idleService->GetIdleTime(&idleTime);
-
-  // If we've been idle for more than EXPIRATION_IDLE_TIMEOUT
-  // we can expire a chunk of elements.
-  if (idleTime < EXPIRATION_IDLE_TIMEOUT)
-    return;
-
-  mozStorageTransaction transaction(mDBConn, PR_TRUE);
-
-  bool keepGoing = ExpireItems(EXPIRATION_MAX_PAGES_AT_IDLE);
-  ExpireOrphans(EXPIRATION_MAX_PAGES_AT_IDLE);
-
-  if (!keepGoing) {
-    // We have expired enough entries, so there is no more need to be agressive
-    // on idle for some time.
-    InitializeIdleTimer(EXPIRATION_IDLE_LONG_TIMEOUT);
-  }
-  else
-    InitializeIdleTimer(EXPIRATION_IDLE_TIMEOUT);
-}
-
-void
-nsNavHistoryExpire::OnDeleteVisits()
-{
-  (void)ExpireAnnotations();
-}
-
-void
-nsNavHistoryExpire::OnQuit()
-{
-  // Cancel any pending timers so we won't try to expire during shutdown.
-  if (mPartialExpirationTimer) {
-    mPartialExpirationTimer->Cancel();
-    mPartialExpirationTimer = 0;
-  }
-  if (mIdleTimer) {
-    mIdleTimer->Cancel();
-    mIdleTimer = 0;
-  }
-
-  nsCOMPtr<nsIPrefBranch> prefs =
-    do_GetService("@mozilla.org/preferences-service;1");
-  if (prefs) {
-    // Determine whether we can skip partially expiration of dangling entries
-    // because we be doing a full expiration on shutdown in ClearHistory().
-    PRBool sanitizeOnShutdown = PR_FALSE;
-    (void)prefs->GetBoolPref(PREF_SANITIZE_ON_SHUTDOWN, &sanitizeOnShutdown);
-    PRBool sanitizeHistory = PR_FALSE;
-    (void)prefs->GetBoolPref(PREF_SANITIZE_ITEM_HISTORY, &sanitizeHistory);
-
-    if (sanitizeHistory && sanitizeOnShutdown)
-      return;
-  }
-
-  // Get rid of all records orphaned due to expiration.
-  ExpireOrphans(EXPIRATION_MAX_PAGES_AT_SHUTDOWN);
-}
-
-nsresult
-nsNavHistoryExpire::ClearHistory()
-{
-  mozStorageTransaction transaction(mDBConn, PR_FALSE);
-
-  // reset frecency for all items that will _not_ be deleted
-  // Note, we set frecency to -visit_count since we use that value in our
-  // idle query to figure out which places to recalcuate frecency first.
-  // We must do this before deleting visits.
-  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-    "UPDATE moz_places_view SET frecency = -MAX(visit_count, 1) "
-    "WHERE id IN("
-      "SELECT h.id FROM moz_places_temp h "
-      "WHERE "
-        "EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) "
-      "UNION ALL "
-      "SELECT h.id FROM moz_places h "
-      "WHERE "
-        "EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) "
-    ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Expire visits, then let the paranoid functions do the cleanup for us.
-  rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_historyvisits_view"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Expire all orphans.
-  ExpireOrphans(-1);
-
-  // Some of the remaining places could be place: urls or
-  // unvisited livemark items, so setting the frecency to -1
-  // will cause them to show up in the url bar autocomplete
-  // call FixInvalidFrecenciesForExcludedPlaces to handle that scenario.
-  rv = mHistory->FixInvalidFrecenciesForExcludedPlaces();
-  if (NS_FAILED(rv))
-    NS_WARNING("failed to fix invalid frecencies");
-
-  rv = transaction.Commit();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  ENUMERATE_OBSERVERS(mHistory->canNotify(), mHistory->mCacheObservers,
-                      mHistory->mObservers, nsINavHistoryObserver,
-                      OnClearHistory());
-
-  return NS_OK;
-}
-
-void
-nsNavHistoryExpire::OnExpirationChanged()
-{
-  // Kick off partial expiration.
-  // Subsequent steps will be on timer.
-  StartPartialExpirationTimer(EXPIRATION_PARTIAL_TIMEOUT);
-}
-
-nsresult
-nsNavHistoryExpire::DoPartialExpiration()
-{
-  bool keepGoing = ExpireItems(EXPIRATION_PAGES_PER_RUN);
-  if (keepGoing)
-    StartPartialExpirationTimer(EXPIRATION_PARTIAL_SUBSEQUENT_TIMEOUT);
-
-  return NS_OK;
-}
-
-bool
-nsNavHistoryExpire::ExpireItems(PRUint32 aNumToExpire)
-{
-  // Whether to keep going after this expiration step.
-  bool keepGoing = true;
-
-  // This transaction is important for performance. It makes the DB flush
-  // everything to disk in one larger operation rather than many small ones.
-  // Note that this transaction always commits.
-  mozStorageTransaction transaction(mDBConn, PR_FALSE);
-
-  PRInt64 expireTime;
-  if (!aNumToExpire) {
-    // Special case: erase all pages from history.
-    expireTime = 0;
-  }
-  else {
-    expireTime = PR_Now() - GetExpirationTimeAgo(mHistory->mExpireDaysMax);
-  }
-
-  // Find some visits to expire.
-  nsTArray<nsNavHistoryExpireRecord> expiredVisits;
-  nsresult rv = FindVisits(expireTime, aNumToExpire, expiredVisits);
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "FindVisits Failed");
-
-  // if we didn't find as many things to expire as we could have, then
-  // we should note the next time we need to expire.
-  if (expiredVisits.Length() < aNumToExpire) {
-    keepGoing = false;
-    ComputeNextExpirationTime();
-  }
-
-  rv = EraseVisits(expiredVisits);
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "EraseVisits Failed");
-
-  rv = EraseHistory(expiredVisits);
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "EraseHistory Failed");
-
-  // Send observer messages.
-  nsCOMPtr<nsIURI> uri;
-  for (PRUint32 i = 0; i < expiredVisits.Length(); i ++) {
-    rv = NS_NewURI(getter_AddRefs(uri), expiredVisits[i].uri);
-    if (NS_FAILED(rv)) {
-      NS_WARNING("Trying to expire a corrupt uri?!");
-      continue;
-    }
-
-    // FIXME bug 325241 provide a way to observe hidden elements
-    if (expiredVisits[i].hidden) continue;
-
-    ENUMERATE_OBSERVERS(mHistory->canNotify(), mHistory->mCacheObservers,
-                        mHistory->mObservers, nsINavHistoryObserver,
-                        OnDeleteVisits(uri, expiredVisits[i].visitDate));
-  }
-
-  // Don't worry about errors here, it doesn't affect our ability to continue.
-  rv = EraseFavicons(expiredVisits);
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "EraseFavicons Failed");
-  rv = EraseAnnotations(expiredVisits);
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "EraseAnnotations Failed");
-  rv = ExpireAnnotations();
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "ExpireAnnotarions Failed");
-
-  rv = transaction.Commit();
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Committing transaction Failed");
-
-  return keepGoing;
-}
-
-void
-nsNavHistoryExpire::ExpireOrphans(PRUint32 aNumToExpire)
-{
-  mozStorageTransaction transaction(mDBConn, PR_FALSE);
-
-  nsresult rv = ExpireHistoryParanoid(aNumToExpire);
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "ExpireHistoryParanoid Failed");
-
-  rv = ExpireFaviconsParanoid();
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "ExpireFaviconsParanoid Failed");
-
-  rv = ExpireAnnotationsParanoid();
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "ExpireAnnotationsParanoid Failed");
-
-  rv = ExpireInputHistoryParanoid();
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "ExpireInputHistoryParanoid Failed");
-
-  rv = transaction.Commit();
-  NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Commit Transaction Failed");
-}
-
-/**
- * nsNavHistoryExpireRecord::nsNavHistoryExpireRecord
- *
- * Statement should be the one created in FindVisits. The parameters must
- * agree.
- */
-nsNavHistoryExpireRecord::nsNavHistoryExpireRecord(
-  mozIStorageStatement* statement)
-{
-  visitID = statement->AsInt64(0);
-  placeID = statement->AsInt64(1);
-  visitDate = statement->AsInt64(2);
-  statement->GetUTF8String(3, uri);
-  faviconID = statement->AsInt64(4);
-  hidden = (statement->AsInt32(5) > 0);
-  bookmarked = (statement->AsInt32(6) > 0);
-  erased = PR_FALSE;
-}
-
-nsresult
-nsNavHistoryExpire::FindVisits(PRTime aExpireThreshold, PRUint32 aNumToExpire,
-                               nsTArray<nsNavHistoryExpireRecord>& aRecords)
-{
-  // Select a limited number of visits older than a time.
-  nsCOMPtr<mozIStorageStatement> selectStatement;
-  nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "SELECT v.id, v.place_id, v.visit_date, IFNULL(h_t.url, h.url), "
-             "IFNULL(h_t.favicon_id, h.favicon_id), "
-             "IFNULL(h_t.hidden, h.hidden), b.fk "
-      "FROM moz_historyvisits_temp v "
-      "LEFT JOIN moz_places_temp AS h_t ON h_t.id = v.place_id "
-      "LEFT JOIN moz_places AS h ON h.id = v.place_id "
-      "LEFT JOIN moz_bookmarks b ON b.fk = v.place_id "
-      "WHERE visit_date < ?1 "
-      "UNION ALL "
-      "SELECT v.id, v.place_id, v.visit_date, IFNULL(h_t.url, h.url), "
-             "IFNULL(h_t.favicon_id, h.favicon_id), "
-             "IFNULL(h_t.hidden, h.hidden), b.fk "
-      "FROM moz_historyvisits v "
-      "LEFT JOIN moz_places_temp AS h_t ON h_t.id = v.place_id "
-      "LEFT JOIN moz_places AS h ON h.id = v.place_id "
-      "LEFT JOIN moz_bookmarks b ON b.fk = v.place_id "
-      "WHERE visit_date < ?1 "
-      "ORDER BY v.visit_date ASC "
-      "LIMIT ?2 "),
-    getter_AddRefs(selectStatement));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-  // Use browser.history_expire_days or match all visits.
-  PRTime expireMaxTime = aExpireThreshold ? aExpireThreshold : LL_MAXINT;
-  rv = selectStatement->BindInt64Parameter(0, expireMaxTime);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // Use LIMIT -1 to not limit.
-  PRInt32 numToExpire = aNumToExpire ? aNumToExpire : -1;
-  rv = selectStatement->BindInt64Parameter(1, numToExpire);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  PRBool hasMore = PR_FALSE;
-  while (NS_SUCCEEDED(selectStatement->ExecuteStep(&hasMore)) && hasMore) {
-    nsNavHistoryExpireRecord record(selectStatement);
-    aRecords.AppendElement(record);
-  }
-
-  // If we have found less than aNumToExpire over-max-age records, and we are
-  // over the unique urls cap, select records older than the min-age cap .
-  if (aRecords.Length() < aNumToExpire) {
-    // check the number of visited unique urls in the db.
-    nsCOMPtr<mozIStorageStatement> countStatement;
-    rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-        "SELECT "
-          "(SELECT count(*) FROM moz_places_temp WHERE visit_count > 0) + "
-          "(SELECT count(*) FROM moz_places WHERE visit_count > 0 AND "
-            "id NOT IN (SELECT id FROM moz_places_temp))"),
-      getter_AddRefs(countStatement));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    hasMore = PR_FALSE;
-    // initialize to mExpiresites to avoid expiring if something goes wrong.
-    PRInt32 pageCount = mHistory->mExpireSites;
-    if (NS_SUCCEEDED(countStatement->ExecuteStep(&hasMore)) && hasMore) {
-      rv = countStatement->GetInt32(0, &pageCount);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
-
-    // Don't find any more pages to expire if we have not reached the urls cap.
-    if (pageCount <= mHistory->mExpireSites)
-        return NS_OK;
-
-    rv = selectStatement->Reset();
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    // browser.history_expire_days_min
-    PRTime expireMinTime = PR_Now() -
-                           GetExpirationTimeAgo(mHistory->mExpireDaysMin);
-    rv = selectStatement->BindInt64Parameter(0, expireMinTime);
-    NS_ENSURE_SUCCESS(rv, rv);
-    
-    numToExpire = aNumToExpire - aRecords.Length();
-    rv = selectStatement->BindInt64Parameter(1, numToExpire);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    hasMore = PR_FALSE;
-    while (NS_SUCCEEDED(selectStatement->ExecuteStep(&hasMore)) && hasMore) {
-      nsNavHistoryExpireRecord record(selectStatement);
-      aRecords.AppendElement(record);
-    }
-  }
-
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::EraseVisits(
-    const nsTArray<nsNavHistoryExpireRecord>& aRecords)
-{
-  // build a comma separated string of visit ids to delete
-  // also build a comma separated string of place ids to reset frecency
-  nsCString deletedVisitIds;
-  nsCString placeIds;
-  nsTArray<PRInt64> deletedPlaceIdsArray, deletedVisitIdsArray;
-  for (PRUint32 i = 0; i < aRecords.Length(); i ++) {
-    // Do not add comma separator for the first visit id
-    if (deletedVisitIdsArray.IndexOf(aRecords[i].visitID) == -1) {
-      if (!deletedVisitIds.IsEmpty())
-        deletedVisitIds.AppendLiteral(",");  
-      deletedVisitIds.AppendInt(aRecords[i].visitID);
-    }
-
-    // Do not add comma separator for the first place id
-    if (deletedPlaceIdsArray.IndexOf(aRecords[i].placeID) == -1) {
-      if (!placeIds.IsEmpty())
-        placeIds.AppendLiteral(",");
-      placeIds.AppendInt(aRecords[i].placeID);
-    }
-  }
-
-  if (deletedVisitIds.IsEmpty())
-    return NS_OK;
-
-  // Reset the frecencies for the places that won't have any visits after
-  // we delete them and make sure they aren't bookmarked either. This means we
-  // keep the old frecencies when possible as an estimate for the new frecency
-  // unless we know it has to be invalidated.
-  // We must do this before deleting visits
-  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-    "UPDATE moz_places_view "
-    "SET frecency = -MAX(visit_count, 1) "
-    "WHERE id IN ( "
-      "SELECT h.id FROM moz_places_temp h "
-      "WHERE "
-        "NOT EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) AND "
-        "NOT EXISTS ( "
-          "SELECT v.id FROM moz_historyvisits_temp v "
-          "WHERE v.place_id = h.id "
-          "AND v.id NOT IN (") + deletedVisitIds + NS_LITERAL_CSTRING(") "
-        ") AND "
-        "NOT EXISTS ( "
-          "SELECT v.id FROM moz_historyvisits v "
-          "WHERE v.place_id = h.id "
-          "AND v.id NOT IN (") + deletedVisitIds + NS_LITERAL_CSTRING(") "
-        ") AND "
-        "h.id IN (") + placeIds + NS_LITERAL_CSTRING(") "
-      "UNION ALL "
-      "SELECT h.id FROM moz_places h "
-      "WHERE "
-        "NOT EXISTS (SELECT id FROM moz_bookmarks WHERE fk = h.id) AND "
-        "NOT EXISTS ( "
-          "SELECT v.id FROM moz_historyvisits_temp v "
-          "WHERE v.place_id = h.id "
-          "AND v.id NOT IN (") + deletedVisitIds + NS_LITERAL_CSTRING(") "
-        ") AND "
-        "NOT EXISTS ( "
-          "SELECT v.id FROM moz_historyvisits v "
-          "WHERE v.place_id = h.id "
-          "AND v.id NOT IN (") + deletedVisitIds + NS_LITERAL_CSTRING(") "
-        ") AND "
-        "h.id IN (") + placeIds + NS_LITERAL_CSTRING(") "
-    ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = mDBConn->ExecuteSimpleSQL(
-    NS_LITERAL_CSTRING("DELETE FROM moz_historyvisits_view WHERE id IN (") +
-    deletedVisitIds +
-    NS_LITERAL_CSTRING(")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::EraseHistory(
-    nsTArray<nsNavHistoryExpireRecord>& aRecords)
-{
-  // build a comma separated string of place ids to delete
-  nsCString deletedPlaceIds;
-  nsTArray<PRInt64> deletedPlaceIdsArray;
-  for (PRUint32 i = 0; i < aRecords.Length(); i ++) {
-    // IF bookmarked entries OR "place" URIs do not delete
-    if (aRecords[i].bookmarked ||
-        StringBeginsWith(aRecords[i].uri, NS_LITERAL_CSTRING("place:")))
-      continue;
-    // avoid trying to delete the same place id twice
-    if (deletedPlaceIdsArray.IndexOf(aRecords[i].placeID) == -1) {
-      // Do not add comma separator for the first entry
-      if (!deletedPlaceIds.IsEmpty())
-        deletedPlaceIds.AppendLiteral(",");
-      deletedPlaceIdsArray.AppendElement(aRecords[i].placeID);
-      deletedPlaceIds.AppendInt(aRecords[i].placeID);
-    }
-    aRecords[i].erased = PR_TRUE;
-  }
-
-  if (deletedPlaceIds.IsEmpty())
-    return NS_OK;
-
-  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_places_view WHERE id IN( "
-        "SELECT h.id "
-        "FROM moz_places h "
-        "WHERE h.id IN(") + deletedPlaceIds + NS_LITERAL_CSTRING(") "
-          "AND NOT EXISTS "
-            "(SELECT id FROM moz_historyvisits WHERE place_id = h.id LIMIT 1) "
-          "AND NOT EXISTS "
-            "(SELECT id FROM moz_historyvisits_temp WHERE place_id = h.id LIMIT 1) "
-          "AND NOT EXISTS "
-            "(SELECT id FROM moz_bookmarks WHERE fk = h.id LIMIT 1) "
-          "AND SUBSTR(h.url, 1, 6) <> 'place:' "
-        "UNION ALL "
-        "SELECT h.id "
-        "FROM moz_places_temp h "
-        "WHERE h.id IN(") + deletedPlaceIds + NS_LITERAL_CSTRING(") "
-          "AND NOT EXISTS "
-            "(SELECT id FROM moz_historyvisits WHERE place_id = h.id LIMIT 1) "
-          "AND NOT EXISTS "
-            "(SELECT id FROM moz_historyvisits_temp WHERE place_id = h.id LIMIT 1) "
-          "AND NOT EXISTS "
-            "(SELECT id FROM moz_bookmarks WHERE fk = h.id LIMIT 1) "
-          "AND SUBSTR(h.url, 1, 6) <> 'place:' "
-      ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::EraseFavicons(
-    const nsTArray<nsNavHistoryExpireRecord>& aRecords)
-{
-  // build a comma separated string of favicon ids to delete
-  nsCString deletedFaviconIds;
-  nsTArray<PRInt64> deletedFaviconIdsArray;  
-  for (PRUint32 i = 0; i < aRecords.Length(); i ++) {
-    // IF main entry not expired OR no favicon DO NOT DELETE
-    if (!aRecords[i].erased || aRecords[i].faviconID == 0)
-      continue;
-    // avoid trying to delete the same favicon id twice
-    if (deletedFaviconIdsArray.IndexOf(aRecords[i].faviconID) == -1) {
-      // Do not add comma separator for the first entry
-      if (!deletedFaviconIds.IsEmpty())
-        deletedFaviconIds.AppendLiteral(",");
-      deletedFaviconIdsArray.AppendElement(aRecords[i].faviconID);
-      deletedFaviconIds.AppendInt(aRecords[i].faviconID);
-    }
-  }
-
-  if (deletedFaviconIds.IsEmpty())
-    return NS_OK;
-
-  // delete only if favicon id is not referenced
-  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_favicons WHERE id IN ( "
-        "SELECT f.id FROM moz_favicons f "
-        "LEFT JOIN moz_places h ON f.id = h.favicon_id "
-        "LEFT JOIN moz_places_temp h_t ON f.id = h_t.favicon_id "
-        "WHERE f.id IN (") + deletedFaviconIds + NS_LITERAL_CSTRING(") "
-        "AND h.favicon_id IS NULL "
-        "AND h_t.favicon_id IS NULL "
-      ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::EraseAnnotations(
-    const nsTArray<nsNavHistoryExpireRecord>& aRecords)
-{
-  // remove annotations for the set of records passed in
-  nsCString placeIds;
-  nsTArray<PRInt64> deletedPlaceIdsArray;
-  for (PRUint32 i = 0; i < aRecords.Length(); i ++) {
-    // avoid trying to delete the same place id twice
-    if (deletedPlaceIdsArray.IndexOf(aRecords[i].placeID) == -1) {
-      // Do not add comma separator for the first entry
-      if (!placeIds.IsEmpty())
-        placeIds.AppendLiteral(",");
-      deletedPlaceIdsArray.AppendElement(aRecords[i].placeID);
-      placeIds.AppendInt(aRecords[i].placeID);
-    }
-  }
-  
-  if (placeIds.IsEmpty())
-    return NS_OK;
-    
-  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-    "DELETE FROM moz_annos WHERE place_id in (") +
-      placeIds + NS_LITERAL_CSTRING(") AND expiration != ") +
-      nsPrintfCString("%d", nsIAnnotationService::EXPIRE_NEVER));
-  NS_ENSURE_SUCCESS(rv, rv);
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::ExpireAnnotations()
-{
-  mozStorageTransaction transaction(mDBConn, PR_FALSE);
-
-  // Note: The COALESCE is used to cover a short period where NULLs were inserted
-  // into the lastModified column.
-  PRTime now = PR_Now();
-  nsCOMPtr<mozIStorageStatement> expirePagesStatement;
-  nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_annos "
-      "WHERE expiration = ?1 AND "
-        "(?2 > MAX(COALESCE(lastModified, 0), dateAdded))"),
-    getter_AddRefs(expirePagesStatement));
-  NS_ENSURE_SUCCESS(rv, rv);
-  nsCOMPtr<mozIStorageStatement> expireItemsStatement;
-  rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_items_annos "
-      "WHERE expiration = ?1 AND "
-        "(?2 > MAX(COALESCE(lastModified, 0), dateAdded))"),
-    getter_AddRefs(expireItemsStatement));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // remove days annos
-  rv = expirePagesStatement->BindInt32Parameter(0, nsIAnnotationService::EXPIRE_DAYS);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->BindInt64Parameter(1, (now - EXPIRATION_POLICY_DAYS));
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->Execute();
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->Reset();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // remove days item annos
-  rv = expireItemsStatement->BindInt32Parameter(0, nsIAnnotationService::EXPIRE_DAYS);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->BindInt64Parameter(1, (now - EXPIRATION_POLICY_DAYS));
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->Execute();
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->Reset();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // remove weeks annos
-  rv = expirePagesStatement->BindInt32Parameter(0, nsIAnnotationService::EXPIRE_WEEKS);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->BindInt64Parameter(1, (now - EXPIRATION_POLICY_WEEKS));
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->Execute();
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->Reset();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // remove weeks item annos
-  rv = expireItemsStatement->BindInt32Parameter(0, nsIAnnotationService::EXPIRE_WEEKS);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->BindInt64Parameter(1, (now - EXPIRATION_POLICY_WEEKS));
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->Execute();
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->Reset();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // remove months annos
-  rv = expirePagesStatement->BindInt32Parameter(0, nsIAnnotationService::EXPIRE_MONTHS);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->BindInt64Parameter(1, (now - EXPIRATION_POLICY_MONTHS));
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expirePagesStatement->Execute();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // remove months item annos
-  rv = expireItemsStatement->BindInt32Parameter(0, nsIAnnotationService::EXPIRE_MONTHS);
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->BindInt64Parameter(1, (now - EXPIRATION_POLICY_MONTHS));
-  NS_ENSURE_SUCCESS(rv, rv);
-  rv = expireItemsStatement->Execute();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // remove EXPIRE_WITH_HISTORY annos for pages without visits
-  rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_annos WHERE expiration = ") +
-        nsPrintfCString("%d", nsIAnnotationService::EXPIRE_WITH_HISTORY) +
-        NS_LITERAL_CSTRING(" AND NOT EXISTS "
-          "(SELECT id FROM moz_historyvisits_temp "
-          "WHERE place_id = moz_annos.place_id LIMIT 1) "
-        "AND NOT EXISTS "
-          "(SELECT id FROM moz_historyvisits "
-          "WHERE place_id = moz_annos.place_id LIMIT 1)"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  rv = transaction.Commit();
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::ExpireHistoryParanoid(PRInt32 aMaxRecords)
-{
-  nsCAutoString query(
-    "DELETE FROM moz_places_view WHERE id IN ("
-      "SELECT h.id FROM moz_places h "
-      "LEFT JOIN moz_historyvisits v ON h.id = v.place_id "
-      "LEFT JOIN moz_historyvisits_temp v_t ON h.id = v_t.place_id "
-      "LEFT JOIN moz_bookmarks b ON h.id = b.fk "
-      "WHERE v.id IS NULL "
-        "AND v_t.id IS NULL "
-        "AND b.id IS NULL "
-        "AND SUBSTR(h.url, 1, 6) <> 'place:' "
-      "UNION ALL "
-      "SELECT h.id FROM moz_places_temp h "
-      "LEFT JOIN moz_historyvisits v ON h.id = v.place_id "
-      "LEFT JOIN moz_historyvisits_temp v_t ON h.id = v_t.place_id "
-      "LEFT JOIN moz_bookmarks b ON h.id = b.fk "
-      "WHERE v.id IS NULL "
-        "AND v_t.id IS NULL "
-        "AND b.id IS NULL "
-        "AND SUBSTR(h.url, 1, 6) <> 'place:'");
-  if (aMaxRecords != -1) {
-    query.AppendLiteral(" LIMIT ");
-    query.AppendInt(aMaxRecords);
-  }
-  query.AppendLiteral(")");
-  nsresult rv = mDBConn->ExecuteSimpleSQL(query);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::ExpireFaviconsParanoid()
-{
-  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_favicons WHERE id IN ("
-        "SELECT f.id FROM moz_favicons f "
-        "LEFT JOIN moz_places h ON f.id = h.favicon_id "
-        "LEFT JOIN moz_places_temp h_t ON f.id = h_t.favicon_id "
-        "WHERE h.favicon_id IS NULL "
-          "AND h_t.favicon_id IS NULL "
-      ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-  return rv;
-}
-
-nsresult
-nsNavHistoryExpire::ExpireAnnotationsParanoid()
-{
-  // delete session annos
-  nsCAutoString session_query = NS_LITERAL_CSTRING(
-    "DELETE FROM moz_annos WHERE expiration = ") +
-    nsPrintfCString("%d", nsIAnnotationService::EXPIRE_SESSION);
-  nsresult rv = mDBConn->ExecuteSimpleSQL(session_query);
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // delete all uri annos w/o a corresponding place id
-  // or without any visits *and* not EXPIRE_NEVER.
-  rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_annos WHERE id IN ("
-        "SELECT a.id FROM moz_annos a "
-        "LEFT JOIN moz_places h ON a.place_id = h.id "
-        "LEFT JOIN moz_places_temp h_t ON a.place_id = h_t.id "
-        "LEFT JOIN moz_historyvisits v ON a.place_id = v.place_id "
-        "LEFT JOIN moz_historyvisits_temp v_t ON a.place_id = v_t.place_id "
-        "WHERE (h.id IS NULL AND h_t.id IS NULL) "
-          "OR (v.id IS NULL AND v_t.id IS NULL AND a.expiration != ") +
-            nsPrintfCString("%d", nsIAnnotationService::EXPIRE_NEVER) +
-          NS_LITERAL_CSTRING(")"
-      ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // delete item annos w/o a corresponding item id
-  rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-    "DELETE FROM moz_items_annos WHERE id IN "
-      "(SELECT a.id FROM moz_items_annos a "
-      "LEFT OUTER JOIN moz_bookmarks b ON a.item_id = b.id "
-      "WHERE b.id IS NULL)"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  // delete all anno names w/o a corresponding anno
-  rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_anno_attributes WHERE id IN (" 
-        "SELECT n.id FROM moz_anno_attributes n "
-        "LEFT JOIN moz_annos a ON n.id = a.anno_attribute_id "
-        "LEFT JOIN moz_items_annos t ON n.id = t.anno_attribute_id "
-        "WHERE a.anno_attribute_id IS NULL "
-          "AND t.anno_attribute_id IS NULL "
-      ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-  return NS_OK;
-}
-
-nsresult
-nsNavHistoryExpire::ExpireInputHistoryParanoid()
-{
-  // Delete dangling input history that have no associated pages
-  nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
-      "DELETE FROM moz_inputhistory WHERE place_id IN ( "
-        "SELECT place_id FROM moz_inputhistory "
-        "LEFT JOIN moz_places h ON h.id = place_id "
-        "LEFT JOIN moz_places_temp h_t ON h_t.id = place_id "
-        "WHERE h.id IS NULL "
-          "AND h_t.id IS NULL "
-      ")"));
-  NS_ENSURE_SUCCESS(rv, rv);
-
-  return NS_OK;
-}
-
-void
-nsNavHistoryExpire::ComputeNextExpirationTime()
-{
-  mNextExpirationTime = 0;
-
-  nsCOMPtr<mozIStorageStatement> statement;
-  nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
-      "SELECT MIN(visit_date) FROM moz_historyvisits"),
-    getter_AddRefs(statement));
-  NS_ASSERTION(NS_SUCCEEDED(rv), "Could not create statement");
-  if (NS_FAILED(rv)) return;
-
-  PRBool hasMore;
-  rv = statement->ExecuteStep(&hasMore);
-  if (NS_FAILED(rv) || !hasMore)
-    return; // no items, we'll leave mNextExpirationTime = 0 and try to expire
-            // again next time
-
-  PRTime minTime = statement->AsInt64(0);
-  mNextExpirationTime = minTime + GetExpirationTimeAgo(mHistory->mExpireDaysMax);
-}
-
-void
-nsNavHistoryExpire::StartPartialExpirationTimer(PRUint32 aMilleseconds)
-{
-  if (mPartialExpirationTimer) {
-    mPartialExpirationTimer->Cancel();
-    mPartialExpirationTimer = 0;
-  }
-
-  mPartialExpirationTimer = do_CreateInstance("@mozilla.org/timer;1");
-  if(mPartialExpirationTimer) {
-    (void)mPartialExpirationTimer->InitWithFuncCallback(
-      PartialExpirationTimerCallback, this, aMilleseconds,
-      nsITimer::TYPE_ONE_SHOT);
-  }
-}
-
-void // static
-nsNavHistoryExpire::PartialExpirationTimerCallback(nsITimer* aTimer, void* aClosure)
-{
-  nsNavHistoryExpire* expire = static_cast<nsNavHistoryExpire*>(aClosure);
-  expire->mPartialExpirationTimer = 0;
-  expire->DoPartialExpiration();
-}
-
-PRTime
-nsNavHistoryExpire::GetExpirationTimeAgo(PRInt32 aExpireDays)
-{
-  // Prevent Int64 overflow for people that type in huge numbers.
-  // This number is 2^63 / 24 / 60 / 60 / 1000000 (reversing the math below)
-  const PRInt32 maxDays = 106751991;
-  if (aExpireDays > maxDays)
-    aExpireDays = maxDays;
-
-  // compute how long ago to expire from
-  // seconds per day = 86400 = 24*60*60
-  return (PRTime)aExpireDays * 86400 * PR_USEC_PER_SEC;
-}
deleted file mode 100644
--- a/toolkit/components/places/src/nsNavHistoryExpire.h
+++ /dev/null
@@ -1,206 +0,0 @@
-//* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is Mozilla History System
- *
- * The Initial Developer of the Original Code is
- * Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2006
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Brett Wilson <brettw@gmail.com> (original author)
- *   Dietrich Ayala <dietrich@mozilla.com>
- *   Marco Bonardo <mak77@bonardo.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/**
- * This class handles expiration of history for nsNavHistory. There is a 1-1
- * mapping between nsNavHistory class and a nsNavHistoryExpire class, the
- * code is separated for better understandability.
- */
-
-class mozIStorageConnection;
-class nsNavHistory;
-struct nsNavHistoryExpireRecord;
-
-class nsNavHistoryExpire
-{
-public:
-  nsNavHistoryExpire();
-  ~nsNavHistoryExpire();
-
-  /**
-   * Called by history when visits are deleted from history.
-   * This kicks off an expiration of page annotations.
-   */
-  void OnDeleteVisits();
-
-  /**
-   * Manages shutdown work and final expiration of orphans.
-   */
-  void OnQuit();
-
-  /**
-   * Called when the expiration length in days has changed. We clear any
-   * next expiration time, meaning that we'll try to expire stuff next time,
-   * and recompute the value if there's still nothing to expire.
-   */
-  void OnExpirationChanged();
-
-  /**
-   * Performance: ExpireItems sends notifications. We may want to disable this
-   * for clear history cases. However, my initial tests show that the
-   * notifications are not a significant part of clear history time.
-   */
-  nsresult ClearHistory();
-
-  /**
-
-   * Tries to expire aNumToExpire pages and their associated data.
-   *
-   * @param aNumToExpire
-   *        Number of history pages to expire, pass 0 to expire every page
-   *        in history.
-   * @return true if we did not expire enough items and we should keep expiring.
-   *         false otherwise.
-   */
-  bool ExpireItems(PRUint32 aNumToExpire);
-
-  /**
-   * Tries to expire aNumToExpire items that are orphans.
-   *
-   * @param aNumToExpire
-   *        Limits how many orphan moz_places we worry about.
-   *        Everything else (favicons, annotations, and input history) is
-   *        completely expired.
-   */
-  void ExpireOrphans(PRUint32 aNumToExpire);
-
-protected:
-  nsNavHistory *mHistory;
-  mozIStorageConnection *mDBConn;
-
-  nsCOMPtr<nsITimer> mPartialExpirationTimer;
-  void StartPartialExpirationTimer(PRUint32 aMilleseconds);
-  static void PartialExpirationTimerCallback(nsITimer *aTimer, void *aClosure);
-
-  // When we have found nothing to expire, we compute the time the next item
-  // will expire. This is that time so we won't try to expire anything until
-  // then. It is 0 when we don't need to wait to expire stuff.
-  PRTime mNextExpirationTime;
-
-  /**
-   * This computes mNextExpirationTime. See that var in the header file.
-   * It is passed the number of microseconds that things expire in.
-   */
-  void ComputeNextExpirationTime();
-
-  nsresult DoPartialExpiration();
-
-  /**
-   * Creates the idle timer.  We expire visits and orphans on idle.
-   */
-  void InitializeIdleTimer(PRUint32 aTimeInMs);
-  nsCOMPtr<nsITimer> mIdleTimer;
-  static void IdleTimerCallback(nsITimer *aTimer, void *aClosure);
-
-  /**
-   * We usually expire periodically, but that could not be fast enough, so on idle
-   * we want to expire a bigget chunk of items to help partial expiration.
-   * This way we try to hit when the user is not going to suffer from UI hangs.
-   */
-  void OnIdle();
-
-  PRTime GetExpirationTimeAgo(PRInt32 aExpireDays);
-
-  nsresult ExpireAnnotations();
-
-  /**
-   * Find visits to expire, meeting the following criteria:
-   *
-   *   - With a visit date older than browser.history_expire_days ago.
-   *   - With a visit date older than browser.history_expire_days_min ago
-   *     if we have more than browser.history_expire_sites unique urls.
-   *
-   * aExpireThreshold is the time at which we will delete visits before.
-   * If it is zero, we will match everything.
-   *
-   * aNumToExpire is the maximum number of visits to find. If it is 0, then
-   * we will get all matching visits.
-   */
-  nsresult FindVisits(PRTime aExpireThreshold, PRUint32 aNumToExpire,
-                      nsTArray<nsNavHistoryExpireRecord> &aRecords);
-
-  nsresult EraseVisits(const nsTArray<nsNavHistoryExpireRecord> &aRecords);
-
-  /**
-   * This erases records in moz_places when there are no more visits.
-   * We need to be careful not to delete: bookmarks, items that still have
-   * visits and place: URIs.
-   *
-   * This will modify the input by setting the erased flag on each of the
-   * array elements according to whether the history item was erased or not.
-   */
-  nsresult EraseHistory(nsTArray<nsNavHistoryExpireRecord> &aRecords);
-
-  nsresult EraseFavicons(const nsTArray<nsNavHistoryExpireRecord> &aRecords);
-
-  /**
-   * Periodic expiration of annotations that have time-sensitive
-   * expiration policies.
-   *
-   * @note Always specify the exact policy constant, as they're
-   * not guaranteed to be in numerical order.
-   */
-  nsresult EraseAnnotations(const nsTArray<nsNavHistoryExpireRecord> &aRecords);
-
-  /**
-   * Deletes any dangling history entries that aren't associated with any
-   * visits, bookmarks or "place:" URIs.
-   *
-   *    The aMaxRecords parameter is an optional cap on the number of 
-   *    records to delete. If its value is -1, all records will be deleted.
-   */
-  nsresult ExpireHistoryParanoid(PRInt32 aMaxRecords);
-
-  /**
-   * Deletes any dangling favicons that aren't associated with any pages.
-   */
-  nsresult ExpireFaviconsParanoid();
-
-  /**
-   * Deletes session annotations, dangling annotations
-   * and annotation names that are unused.
-   */
-  nsresult ExpireAnnotationsParanoid();
-
-  /**
-   * Deletes dangling input history
-   */
-  nsresult ExpireInputHistoryParanoid();
-};
--- a/toolkit/components/places/src/nsPlacesAutoComplete.js
+++ b/toolkit/components/places/src/nsPlacesAutoComplete.js
@@ -505,17 +505,17 @@ nsPlacesAutoComplete.prototype = {
   //// nsIObserver
 
   observe: function PAC_observe(aSubject, aTopic, aData)
   {
     if (aTopic == kXPComShutdown) {
       this._os.removeObserver(this, kXPComShutdown);
 
       // Remove our preference observer.
-      this._prefs.removeObserver("", this);
+      this._prefs.QueryInterface(Ci.nsIPrefBranch2).removeObserver("", this);
       delete this._prefs;
 
       // Finalize the statements that we have used.
       let stmts = [
         "_defaultQuery",
         "_historyQuery",
         "_bookmarkQuery",
         "_tagsQuery",
--- a/toolkit/components/places/src/nsPlacesDBFlush.js
+++ b/toolkit/components/places/src/nsPlacesDBFlush.js
@@ -50,32 +50,20 @@ const Cu = Components.utils;
 
 const kXPComShutdown = "xpcom-shutdown";
 const kSyncFinished = "places-sync-finished";
 const kDebugStopSync = "places-debug-stop-sync";
 const kDebugStartSync = "places-debug-start-sync";
 
 const kSyncPrefName = "places.syncDBTableIntervalInSecs";
 const kDefaultSyncInterval = 120;
-const kExpireDaysPrefName = "browser.history_expire_days";
-const kDefaultExpireDays = 90;
-
-// The number of milliseconds in a day.
-const kMSPerDay = 86400000;
-
-// The max number of entries we will flush out when we expire.
-const kMaxExpire = 24;
 
 // Query Constants.  These describe the queries we use.
 const kQuerySyncPlacesId = 0;
 const kQuerySyncHistoryVisitsId = 1;
-const kQuerySelectExpireVisitsId = 2;
-const kQueryExpireVisitsId = 3;
-const kQuerySelectExpireHistoryOrphansId = 4;
-const kQueryExpireHistoryOrphansId = 5;
 
 ////////////////////////////////////////////////////////////////////////////////
 //// nsPlacesDBFlush class
 
 function nsPlacesDBFlush()
 {
   this._prefs = Cc["@mozilla.org/preferences-service;1"].
                 getService(Ci.nsIPrefBranch);
@@ -88,40 +76,25 @@ function nsPlacesDBFlush()
     if (this._syncInterval <= 0)
       this._syncInterval = kDefaultSyncInterval;
   }
   catch (e) {
     // The preference did not exist, so use the default.
     this._syncInterval = kDefaultSyncInterval;
   }
 
-  // Get our maximum allowable age of visits in days.
-  try {
-    // We want to silently fail since getIntPref throws if it does not exist,
-    // and use a default to fallback to.
-    this._expireDays = this._prefs.getIntPref(kExpireDaysPrefName);
-    if (this._expireDays <= 0)
-      this._expireDays = kDefaultExpireDays;
-  }
-  catch (e) {
-    // The preference did not exist, so use the default.
-    this._expireDays = kDefaultExpireDays;
-  }
-
   // Register observers
   this._os = Cc["@mozilla.org/observer-service;1"].
              getService(Ci.nsIObserverService);
   this._os.addObserver(this, kXPComShutdown, false);
   this._os.addObserver(this, kDebugStopSync, false);
   this._os.addObserver(this, kDebugStartSync, false);
 
-  let (pb2 = this._prefs.QueryInterface(Ci.nsIPrefBranch2)) {
+  let (pb2 = this._prefs.QueryInterface(Ci.nsIPrefBranch2))
     pb2.addObserver(kSyncPrefName, this, false);
-    pb2.addObserver(kExpireDaysPrefName, this, false);
-  }
 
   // Create our timer to update everything
   this._timer = this._newTimer();
 
   //////////////////////////////////////////////////////////////////////////////
   //// Smart Getters
 
   XPCOMUtils.defineLazyGetter(this, "_db", function() {
@@ -129,40 +102,34 @@ function nsPlacesDBFlush()
            getService(Ci.nsPIPlacesDatabase).
            DBConnection;
   });
 
   XPCOMUtils.defineLazyServiceGetter(this, "_ios",
                                      "@mozilla.org/network/io-service;1",
                                      "nsIIOService");
 
-  XPCOMUtils.defineLazyServiceGetter(this, "_hsn",
-                                     "@mozilla.org/browser/nav-history-service;1",
-                                     "nsPIPlacesHistoryListenersNotifier");
-
   XPCOMUtils.defineLazyServiceGetter(this, "_bs",
                                      "@mozilla.org/browser/nav-bookmarks-service;1",
                                      "nsINavBookmarksService");
 }
 
 nsPlacesDBFlush.prototype = {
   //////////////////////////////////////////////////////////////////////////////
   //// nsIObserver
 
   observe: function DBFlush_observe(aSubject, aTopic, aData)
   {
     if (aTopic == kXPComShutdown) {
       this._os.removeObserver(this, kXPComShutdown);
       this._os.removeObserver(this, kDebugStopSync);
       this._os.removeObserver(this, kDebugStartSync);
 
-      let (pb2 = this._prefs.QueryInterface(Ci.nsIPrefBranch2)) {
+      let (pb2 = this._prefs.QueryInterface(Ci.nsIPrefBranch2))
         pb2.removeObserver(kSyncPrefName, this);
-        pb2.removeObserver(kExpireDaysPrefName, this);
-      }
 
       if (this._timer) {
         this._timer.cancel();
         this._timer = null;
       }
 
       // Other components could still make changes to history at this point,
       // for example to clear private data on shutdown, so here we dispatch
@@ -192,22 +159,16 @@ nsPlacesDBFlush.prototype = {
       // We may have canceled the timer already for batch updates, so we want to
       // exit early.
       if (!this._timer)
         return;
 
       this._timer.cancel();
       this._timer = this._newTimer();
     }
-    else if (aTopic == "nsPref:changed" && aData == kExpireDaysPrefName) {
-      // Get the new pref and store it.
-      this._expireDays = this._prefs.getIntPref(kExpireDaysPrefName);
-      if (this._expireDays <= 0)
-        this._expireDays = kDefaultExpireDays;
-    }
     else if (aTopic == kDebugStopSync) {
       this._syncStopped = true;
     }
     else if (aTopic == kDebugStartSync) {
       if (_syncStopped in this)
         delete this._syncStopped;
     }
   },
@@ -277,69 +238,38 @@ nsPlacesDBFlush.prototype = {
   onDeleteVisits: function() { },
 
   //////////////////////////////////////////////////////////////////////////////
   //// nsITimerCallback
 
   notify: function DBFlush_timerCallback()
   {
     let queries = [
-      kQuerySelectExpireVisitsId,
-      kQueryExpireVisitsId,
-      kQuerySelectExpireHistoryOrphansId,
-      kQueryExpireHistoryOrphansId,
       kQuerySyncPlacesId,
       kQuerySyncHistoryVisitsId,
     ];
     this._flushWithQueries(queries);
   },
 
   //////////////////////////////////////////////////////////////////////////////
   //// mozIStorageStatementCallback
 
   handleResult: function DBFlush_handleResult(aResultSet)
   {
-    // The only results we'll ever get back is for notifying about expiration.
-    if (!this._expiredResults)
-      this._expiredResults = [];
-
-    let row;
-    while (row = aResultSet.getNextRow()) {
-      if (row.getResultByName("hidden"))
-        continue;
-
-      this._expiredResults.push({
-        uri: this._ios.newURI(row.getResultByName("url"), null, null),
-        visitDate: row.getResultByName("visit_date"),
-        wholeEntry: (row.getResultByName("whole_entry") == 1)
-      });
-    }
   },
 
   handleError: function DBFlush_handleError(aError)
   {
     Cu.reportError("Async statement execution returned with '" +
                    aError.result + "', '" + aError.message + "'");
   },
 
   handleCompletion: function DBFlush_handleCompletion(aReason)
   {
     if (aReason == Ci.mozIStorageStatementCallback.REASON_FINISHED) {
-      // Dispatch to history that we've finished expiring if we have results.
-      if (this._expiredResults) {
-        while (this._expiredResults.length) {
-          let visit = this._expiredResults.shift();
-          this._hsn.notifyOnPageExpired(visit.uri, visit.visitDate,
-                                        visit.wholeEntry);
-        }
-
-        // And reset it...
-        delete this._expiredResults;
-      }
-
       // Dispatch a notification that sync has finished.
       this._os.notifyObservers(null, kSyncFinished, null);
     }
   },
 
   //////////////////////////////////////////////////////////////////////////////
   //// nsPlacesDBFlush
   _syncInterval: kDefaultSyncInterval,
@@ -365,19 +295,20 @@ nsPlacesDBFlush.prototype = {
   },
 
   /**
    * Finalizes all of our mozIStorageStatements so we can properly close the
    * database.
    */
   _finalizeInternalStatements: function DBFlush_finalizeInternalStatements()
   {
-    for each (let stmt in this._cachedStatements)
+    this._cachedStatements.forEach(function(stmt) {
       if (stmt instanceof Ci.mozIStorageStatement)
         stmt.finalize();
+    });
   },
 
   /**
    * Generate the statement to synchronizes the moz_{aTableName} and
    * moz_{aTableName}_temp by copying all the data from the temporary table
    * into the permanent one.
    * Most of the work is done through triggers defined in nsPlacesTriggers.h,
    * they sync back to disk, then delete the data in the temporary table.
@@ -394,25 +325,16 @@ nsPlacesDBFlush.prototype = {
 
       // Bind the appropriate parameters.
       let params = stmt.params;
       switch (aQueryType) {
         case kQuerySyncHistoryVisitsId:
         case kQuerySyncPlacesId:
           params.transition_type = Ci.nsINavHistoryService.TRANSITION_EMBED;
           break;
-        case kQuerySelectExpireVisitsId:
-        case kQueryExpireVisitsId:
-          params.visit_date = (Date.now() - (this._expireDays * kMSPerDay)) * 1000;
-          params.max_expire = kMaxExpire;
-          break;
-        case kQuerySelectExpireHistoryOrphansId:
-        case kQueryExpireHistoryOrphansId:
-          params.max_expire = kMaxExpire;
-          break;
       }
 
       return stmt;
     }
 
     switch(aQueryType) {
       case kQuerySyncHistoryVisitsId:
         // For history table we want to leave embed visits in memory, since
@@ -435,78 +357,16 @@ nsPlacesDBFlush.prototype = {
               "SELECT id FROM moz_historyvisits_temp " +
               "WHERE place_id = h.id AND visit_type = :transition_type " +
               "LIMIT 1 " +
             ") " +
           ")"
         );
         break;
 
-      case kQuerySelectExpireVisitsId:
-        // Determine which entries will be flushed out from moz_historyvisits
-        // when kQueryExpireVisitsId runs.
-        this._cachedStatements[aQueryType] = this._db.createStatement(
-          "SELECT h.url, v.visit_date, h.hidden, 0 AS whole_entry " +
-          "FROM moz_places h " +
-          "JOIN moz_historyvisits v ON h.id = v.place_id " +
-          "WHERE v.visit_date < :visit_date " +
-          "ORDER BY v.visit_date ASC " +
-          "LIMIT :max_expire"
-        );
-        break;
-
-      case kQueryExpireVisitsId:
-        // Expire entries from moz_historyvisits.
-        this._cachedStatements[aQueryType] = this._db.createStatement(
-          "DELETE FROM moz_historyvisits " +
-          "WHERE id IN ( " +
-            "SELECT id " +
-            "FROM moz_historyvisits " +
-            "WHERE visit_date < :visit_date " +
-            "ORDER BY visit_date ASC " +
-            "LIMIT :max_expire " +
-          ")"
-        );
-        break;
-
-      case kQuerySelectExpireHistoryOrphansId:
-        // Determine which entries will be flushed out from moz_places
-        // when kQueryExpireHistoryOrphansId runs.
-        this._cachedStatements[aQueryType] = this._db.createStatement(
-          "SELECT h.url, h.last_visit_date AS visit_date, h.hidden, " +
-                 "1 as whole_entry FROM moz_places h " +
-          "LEFT JOIN moz_historyvisits v ON h.id = v.place_id " +
-          "LEFT JOIN moz_historyvisits_temp v_t ON h.id = v_t.place_id " +
-          "LEFT JOIN moz_bookmarks b ON h.id = b.fk " +
-          "WHERE v.id IS NULL " +
-            "AND v_t.id IS NULL " +
-            "AND b.id IS NULL " +
-            "AND SUBSTR(h.url, 1, 6) <> 'place:' " +
-          "LIMIT :max_expire"
-        );
-        break;
-
-      case kQueryExpireHistoryOrphansId:
-        // Flush out entries from moz_historyvisits.
-        this._cachedStatements[aQueryType] = this._db.createStatement(
-          "DELETE FROM moz_places_view " +
-          "WHERE id IN ( " +
-            "SELECT h.id FROM moz_places h " +
-            "LEFT JOIN moz_historyvisits v ON h.id = v.place_id " +
-            "LEFT JOIN moz_historyvisits_temp v_t ON h.id = v_t.place_id " +
-            "LEFT JOIN moz_bookmarks b ON h.id = b.fk " +
-            "WHERE v.id IS NULL " +
-              "AND v_t.id IS NULL " +
-              "AND b.id IS NULL " +
-              "AND SUBSTR(h.url, 1, 6) <> 'place:' " +
-            "LIMIT :max_expire" +
-          ")"
-        );
-        break;
-
       default:
         throw "Unexpected statement!";
     }
 
     // We only bind our own parameters when we have a cached statement, so we
     // call ourself since we now have a cached statement.
     return this._getQuery(aQueryType);
   },
deleted file mode 100644
--- a/toolkit/components/places/tests/sync/test_expire_on_timed_flush.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 sts=2 expandtab
- * ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Mozilla Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2009
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Shawn Wilsher <me@shawnwilsher.com> (Original Author)
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
-         getService(Ci.nsINavHistoryService);
-var bh = Cc["@mozilla.org/browser/global-history;2"].
-         getService(Ci.nsIBrowserHistory);
-var prefs = Cc["@mozilla.org/preferences-service;1"].
-            getService(Ci.nsIPrefBranch);
-var os = Cc["@mozilla.org/observer-service;1"].
-         getService(Ci.nsIObserverService);
-
-const TEST_URI = "http://test.com/";
-
-const kSyncPrefName = "places.syncDBTableIntervalInSecs";
-const SYNC_INTERVAL = 1;
-const kSyncFinished = "places-sync-finished";
-
-const kExpireDaysPrefName = "browser.history_expire_days";
-const EXPIRE_DAYS = 1;
-
-var observer = {
-  visitId: -1,
-  notificationReceived: false,
-  _syncCount: 0,
-  observe: function(aSubject, aTopic, aData) {
-    if (aTopic == kSyncFinished) {
-      // We won't have expired on the first sync (we expire first, then sync),
-      // so we have to wait for the second sync to check.
-      if (this._syncCount++ == 0)
-        return;
-
-      // Sanity check that we actually added the visit.
-      do_check_neq(this.visitId, -1);
-
-      // Ensure that we received a notification about expiration.
-      do_check_true(this.notificationReceived);
-
-      // remove the observer, we don't need to observe sync on quit
-      os.removeObserver(this, kSyncFinished);
-      // Check the visit
-      new_test_visit_uri_event(this.visitId, TEST_URI, false, true);
-    }
-  }
-}
-os.addObserver(observer, kSyncFinished, false);
-
-// Used to ensure that we did in fact get notified about our expiration.
-var historyObserver = {
-  visitTime: -1,
-  _runCount: 0,
-  onDeleteVisits: function(aURI, aVisitTime)
-  {
-    do_check_true(aURI.equals(uri(TEST_URI)));
-
-    // We should have the visit time that was set in the addVisit call.
-    do_check_eq(this.visitTime, aVisitTime);
-
-    observer.notificationReceived = true;
-    hs.removeObserver(this, false);
-  }
-}
-hs.addObserver(historyObserver, false);
-
-function run_test()
-{
-  // First set our preferences to small values.
-  prefs.setIntPref(kExpireDaysPrefName, EXPIRE_DAYS);
-  prefs.setIntPref(kSyncPrefName, SYNC_INTERVAL);
-
-  // Sanity check to ensure that our test uri is not already visited.
-  do_check_false(bh.isVisited(uri(TEST_URI)));
-
-  // Now add the visit two days ago.
-  let date = Date.now() - 2 * 24 * 60 * 60 * 1000; // (milliseconds)
-  observer.visitId = hs.addVisit(uri(TEST_URI), date * 1000, null,
-                                 hs.TRANSITION_TYPED, false, 0);
-  historyObserver.visitTime = date * 1000;
-
-  do_test_pending();
-}
deleted file mode 100644
--- a/toolkit/components/places/tests/sync/test_expire_on_timed_flush_not_whole_entry.js
+++ /dev/null
@@ -1,125 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 sts=2 expandtab
- * ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Mozilla Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2009
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Shawn Wilsher <me@shawnwilsher.com> (Original Author)
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
-         getService(Ci.nsINavHistoryService);
-var bh = Cc["@mozilla.org/browser/global-history;2"].
-         getService(Ci.nsIBrowserHistory);
-var prefs = Cc["@mozilla.org/preferences-service;1"].
-            getService(Ci.nsIPrefBranch);
-var os = Cc["@mozilla.org/observer-service;1"].
-         getService(Ci.nsIObserverService);
-
-const TEST_URI = "http://test.com/";
-
-const kSyncPrefName = "places.syncDBTableIntervalInSecs";
-const SYNC_INTERVAL = 1;
-const kSyncFinished = "places-sync-finished";
-
-const kExpireDaysPrefName = "browser.history_expire_days";
-const EXPIRE_DAYS = 1;
-
-var observer = {
-  visitId1: -1,
-  visitId2: -1,
-  notificationReceived: false,
-  _syncCount: 0,
-  observe: function(aSubject, aTopic, aData) {
-    if (aTopic == kSyncFinished) {
-      // We won't have expired on the first sync (we expire first, then sync),
-      // so we have to wait for the second sync to check.
-      if (this._syncCount++ == 0)
-        return;
-
-      // Sanity check that we actually added the visits.
-      do_check_neq(this.visitId1, -1);
-      do_check_neq(this.visitId2, -1);
-
-      // Ensure that we received a notification about expiration.
-      do_check_true(this.notificationReceived);
-
-      // remove the observer, we don't need to observe sync on quit
-      os.removeObserver(this, kSyncFinished);
-      // Check the visits
-      new_test_visit_uri_event(this.visitId1, TEST_URI, false);
-      new_test_visit_uri_event(this.visitId2, TEST_URI, true, true);
-    }
-  }
-}
-os.addObserver(observer, kSyncFinished, false);
-
-// Used to ensure that we did in fact get notified about our expiration.
-var historyObserver = {
-  visitTime: -1,
-  onDeleteVisits: function(aURI, aVisitTime)
-  {
-    do_check_true(aURI.equals(uri(TEST_URI)));
-
-    // We should have the visit time that was set in the addVisit call.
-    do_check_eq(this.visitTime, aVisitTime);
-
-    // We should only be called once.
-    do_check_false(observer.notificationReceived);
-    observer.notificationReceived = true;
-    hs.removeObserver(this, false);
-  }
-}
-hs.addObserver(historyObserver, false);
-
-function run_test()
-{
-  // First set our preferences to small values.
-  prefs.setIntPref(kExpireDaysPrefName, EXPIRE_DAYS);
-  prefs.setIntPref(kSyncPrefName, SYNC_INTERVAL);
-
-  // Sanity check to ensure that our test uri is not already visited.
-  do_check_false(bh.isVisited(uri(TEST_URI)));
-
-  // Now add the visit two days ago.
-  let date = Date.now() - 2 * 24 * 60 * 60 * 1000; // (milliseconds)
-  observer.visitId1 = hs.addVisit(uri(TEST_URI), date * 1000, null,
-                                  hs.TRANSITION_TYPED, false, 0);
-  historyObserver.visitTime = date * 1000;
-
-  // Add it again for now (should not expire, making aWholeEntry false).
-  observer.visitId2 = hs.addVisit(uri(TEST_URI), Date.now() * 1000, null,
-                                  hs.TRANSITION_TYPED, false, 0);
-
-  do_test_pending();
-}
deleted file mode 100644
--- a/toolkit/components/places/tests/sync/test_expire_on_timed_flush_obeys_date.js
+++ /dev/null
@@ -1,110 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 sts=2 expandtab
- * ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Mozilla Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2009
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Shawn Wilsher <me@shawnwilsher.com> (Original Author)
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-var hs = Cc["@mozilla.org/browser/nav-history-service;1"].
-         getService(Ci.nsINavHistoryService);
-var bh = Cc["@mozilla.org/browser/global-history;2"].
-         getService(Ci.nsIBrowserHistory);
-var prefs = Cc["@mozilla.org/preferences-service;1"].
-            getService(Ci.nsIPrefBranch);
-var os = Cc["@mozilla.org/observer-service;1"].
-         getService(Ci.nsIObserverService);
-
-const TEST_URI = "http://test.com/";
-
-const kSyncPrefName = "places.syncDBTableIntervalInSecs";
-const SYNC_INTERVAL = 1;
-const kSyncFinished = "places-sync-finished";
-
-const kExpireDaysPrefName = "browser.history_expire_days";
-const EXPIRE_DAYS = 1;
-
-var observer = {
-  visitId: -1,
-  notificationReceived: false,
-  _syncCount: 0,
-  observe: function(aSubject, aTopic, aData) {
-    if (aTopic == kSyncFinished) {
-      // We won't have expired on the first sync (we expire first, then sync),
-      // so we have to wait for the second sync to check.
-      if (this._syncCount++ == 0)
-        return;
-
-      // Sanity check to make sure that we actually added a visit.
-      do_check_neq(this.visitId, -1);
-
-      // Ensure that we received a notification about expiration.
-      do_check_false(this.notificationReceived);
-
-      // remove the observer, we don't need to observe sync on quit
-      os.removeObserver(this, kSyncFinished);
-      hs.removeObserver(historyObserver, false);
-
-      // Check the visit
-      new_test_visit_uri_event(this.visitId, TEST_URI, true, true);
-    }
-  }
-}
-os.addObserver(observer, kSyncFinished, false);
-
-// Used to ensure that we do not expire anything.
-var historyObserver = {
-  onDeleteVisits: function(aURI, aVisitTime)
-  {
-    do_throw("How did we get called?!");
-    observer.notificationReceived = true;
-  }
-}
-hs.addObserver(historyObserver, false);
-
-function run_test()
-{
-  // First set our preferences to small values.
-  prefs.setIntPref(kExpireDaysPrefName, EXPIRE_DAYS);
-  prefs.setIntPref(kSyncPrefName, SYNC_INTERVAL);
-
-  // Sanity check to ensure that our test uri is not already visited.
-  do_check_false(bh.isVisited(uri(TEST_URI)));
-
-  // Now add the visit two days ago.
-  observer.visitId = hs.addVisit(uri(TEST_URI), Date.now() * 1000, null,
-                                 hs.TRANSITION_TYPED, false, 0);
-
-  do_test_pending();
-}
deleted file mode 100644
--- a/toolkit/components/places/tests/unit/test_expiration.js
+++ /dev/null
@@ -1,834 +0,0 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et: */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is Google Inc.
- * Portions created by the Initial Developer are Copyright (C) 2005
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *  Darin Fisher <darin@meer.net>
- *  Dietrich Ayala <dietrich@mozilla.com>
- *  Dan Mills <thunder@mozilla.com>
- *  Marco Bonardo <mak77@supereva.it>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-// Get services
-var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
-              getService(Ci.nsINavHistoryService);
-var bhist = histsvc.QueryInterface(Ci.nsIBrowserHistory);
-var ghist = Cc["@mozilla.org/browser/global-history;2"].
-            getService(Ci.nsIGlobalHistory2);
-var annosvc = Cc["@mozilla.org/browser/annotation-service;1"].
-              getService(Ci.nsIAnnotationService);
-var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
-            getService(Ci.nsINavBookmarksService);
-var prefs = Cc["@mozilla.org/preferences-service;1"].
-            getService(Ci.nsIPrefBranch);
-
-// create and add history observer
-var observer = {
-  onBeginUpdateBatch: function() {
-  },
-  onEndUpdateBatch: function() {
-  },
-  onVisit: function(aURI, aVisitID, aTime, aSessionID, aReferringID, aTransitionType) {
-  },
-  onTitleChanged: function(aURI, aPageTitle) {
-  },
-  onBeforeDeleteURI: function(aURI) {
-  },
-  onDeleteURI: function(aURI) {
-  },
-  onClearHistory: function() {
-    this.historyCleared = true;
-  },
-  onPageChanged: function(aURI, aWhat, aValue) {
-  },
-  expiredURI: null,
-  onDeleteVisits: function(aURI, aVisitTime) {
-    this.expiredURI = aURI.spec;
-  },
-  QueryInterface: function(iid) {
-    if (iid.equals(Ci.nsINavBookmarkObserver) ||
-        iid.equals(Ci.nsISupports)) {
-      return this;
-    }
-    throw Cr.NS_ERROR_NO_INTERFACE;
-  }
-};
-histsvc.addObserver(observer, false);
-
-// get direct db connection for date-based anno tests
-var dbConnection = histsvc.QueryInterface(Ci.nsPIPlacesDatabase).DBConnection;
-
-
-var testURI = uri("http://mozilla.com");
-var testAnnoName = "tests/expiration/history";
-var testAnnoVal = "foo";
-var bookmark = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, testURI, bmsvc.DEFAULT_INDEX, "foo");
-var triggerURI = uri("http://foobar.com");
-
-// main
-function run_test() {
-  /*
-  Test that nsIBrowserHistory.removePagesFromHost removes expirable
-  annotations but doesn't remove bookmarks.
-  */
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName + "Hist", testAnnoVal, 0, annosvc.EXPIRE_WITH_HISTORY);
-  annosvc.setPageAnnotation(testURI, testAnnoName + "Never", testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  bhist.removePagesFromHost("mozilla.com", false);
-
-  do_check_eq(bmsvc.getBookmarkURI(bookmark).spec, testURI.spec);
-  // EXPIRE_WITH_HISTORY anno should be removed since we don't have visits
-  try {
-    annosvc.getPageAnnotation(testAnnoName + "Hist");
-    do_throw("removePagesFromHost() didn't remove an EXPIRE_WITH_HISTORY annotation");
-  } catch(ex) {}
-  // EXPIRE_NEVER anno should be retained since the uri is bookmarked
-  do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName + "Never"), testAnnoVal);
-  // check that moz_places record was not removed for this URI (is bookmarked)
-  do_check_eq(histsvc.getPageTitle(testURI), null);
-
-  //cleanup
-  annosvc.removePageAnnotation(testURI, testAnnoName + "Never");
-
-  /*
-  Test that nsIBrowserHistory.removeAllPages removes expirable
-  annotations but doesn't remove bookmarks.
-  */
-  var removeAllTestURI = uri("http://removeallpages.com");
-  var removeAllTestURINever = uri("http://removeallpagesnever.com");
-  histsvc.addVisit(removeAllTestURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  histsvc.addVisit(removeAllTestURINever, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  var bmURI = uri("http://bookmarked");
-  var bookmark2 = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, bmURI, bmsvc.DEFAULT_INDEX, "foo");
-  var placeURI = uri("place:folder=23");
-  bhist.addPageWithDetails(placeURI, "place uri", Date.now() * 1000);
-  annosvc.setPageAnnotation(removeAllTestURI, testAnnoName + "Hist", testAnnoVal, 0, annosvc.EXPIRE_WITH_HISTORY);
-  annosvc.setPageAnnotation(removeAllTestURINever, testAnnoName + "Never", testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  bhist.removeAllPages();
-
-  // both annotations should be removed since those URIs are not bookmarked
-  try {
-    annosvc.getPageAnnotation(removeAllTestURI, testAnnoName + "Hist");
-    do_throw("nsIBrowserHistory.removeAllPages() didn't remove an EXPIRE_WITH_HISTORY annotation");
-  } catch(ex) {}
-  try {
-    annosvc.getPageAnnotation(removeAllTestURINever, testAnnoName + "Never");
-    do_throw("nsIBrowserHistory.removePagesFromHost() didn't remove an EXPIRE_NEVER annotation");
-  } catch(ex) {}
-  // test that the moz_places record was not removed for place URI
-  do_check_neq(histsvc.getPageTitle(placeURI), null);
-  // test that the moz_places record was not removed for bookmarked URI
-  try {
-    histsvc.getPageTitle(bmURI);
-  }
-  catch(ex) {
-    do_throw("Place record for bookmarked uri was wrongly removed");
-  }
-
-  // cleanup
-  bmsvc.removeItem(bookmark2);
-
-  /*
-  Test anno expiration (EXPIRE_NEVER)
-    - A page annotation should be expired only if the page is removed from the
-      database, i.e. when it has no visits and is not bookmarked
-    - An item annotation does not never expire
-  */
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  // add page/item annotations to bookmarked uri
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-  // add page/item annotations to a not bookmarked uri
-  var expireNeverURI = uri("http://expiremenever.com");
-  histsvc.addVisit(expireNeverURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(expireNeverURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  histsvc.removeAllPages();  
-
-  // check that page and item annotations are still there for bookmarked uri
-  do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName), testAnnoVal);
-  do_check_eq(annosvc.getItemAnnotation(bookmark, testAnnoName), testAnnoVal);
-  // check that page annotation has been removed for not bookmarked uri
-    try {
-    annosvc.getPageAnnotation(expireNeverURI, testAnnoName);
-    do_throw("nsIBrowserHistory.removeAllPages() didn't remove an EXPIRE_NEVER annotation");
-  } catch(ex) {}
-
-  // do some cleanup
-  annosvc.removeItemAnnotation(bookmark, testAnnoName);
-  annosvc.removePageAnnotation(testURI, testAnnoName);
-
-  /*
-  Test anno expiration (EXPIRE_WITH_HISTORY)
-    - A page annotation should be expired when the page has no more visits
-      whatever it is bookmarked or not
-    - An item annotation cannot have this kind of expiration
-  */
-
-  // Add page anno on a bookmarked URI
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_WITH_HISTORY);
-  // Check that we can't add an EXPIRE_WITH_HISTORY anno to a bookmark
-  try {
-    annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_WITH_HISTORY);
-    do_throw("I was able to set an EXPIRE_WITH_HISTORY anno on a bookmark");
-  } catch(ex) {}
-
-  histsvc.removeAllPages();
-
-  // check that anno has been expired correctly even if the URI is bookmarked
-  try {
-    annosvc.getPageAnnotation(testURI, testAnnoName);
-    do_throw("page still had expire_with_history page anno");
-  } catch(ex) {}
-
-  /*
-  test anno expiration (days)
-    - add a bookmark, set an anno on the bookmarked uri 
-    - manually tweak moz_annos.dateAdded, making it expired
-    - add another entry (to kick off expiration)
-    - try to get the anno (should fail. maybe race here? is there a way to determine
-      if the page has been added, so we know that expiration is done?)
-  */
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-
-  // these annotations should be removed (after manually tweaking their dateAdded)
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-
-  // set dateAdded to 8 days ago
-  var expirationDate = (Date.now() - (8 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-
-  // these annotations should remain
-  annosvc.setPageAnnotation(testURI, testAnnoName + "NotExpired", testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName + "NotExpired", testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-
-  // test for unexpired annos
-  try {
-    do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName + "NotExpired"), testAnnoVal);
-  } catch(ex) {
-    do_throw("anno < 7 days old was expired!");
-  }
-  annosvc.removePageAnnotation(testURI, testAnnoName + "NotExpired");
-  try {
-    do_check_eq(annosvc.getItemAnnotation(bookmark, testAnnoName + "NotExpired"), testAnnoVal);
-  } catch(ex) {
-    do_throw("item anno < 7 days old was expired!");
-  }
-  annosvc.removeItemAnnotation(bookmark, testAnnoName + "NotExpired");
-
-  // test for expired annos
-  try {
-    annosvc.getPageAnnotation(testURI, testAnnoName);
-    do_throw("page still had days anno");
-  } catch(ex) {}
-  try {
-    annosvc.getItemAnnotation(bookmark, testAnnoName);
-    do_throw("bookmark still had days anno");
-  } catch(ex) {}
-
-  // test anno expiration (days) removes annos annos 6 days old
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-  // these annotations should remain as they are only 6 days old
-  var expirationDate = (Date.now() - (6 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-
-  // test for unexpired annos
-  try {
-    do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName), testAnnoVal);
-  } catch(ex) {
-    do_throw("anno < 7 days old was expired!");
-  }
-  annosvc.removePageAnnotation(testURI, testAnnoName);
-  try {
-    do_check_eq(annosvc.getItemAnnotation(bookmark, testAnnoName), testAnnoVal);
-  } catch(ex) {
-    do_throw("item anno < 7 days old was expired!");
-  }
-  annosvc.removeItemAnnotation(bookmark, testAnnoName);
-
-
-  // test anno expiration (weeks) removes annos 31 days old
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_WEEKS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_WEEKS);
-  // these annotations should not remain as they are 31 days old
-  var expirationDate = (Date.now() - (31 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  // these annotations should remain
-  annosvc.setPageAnnotation(testURI, testAnnoName + "NotExpired", testAnnoVal, 0, annosvc.EXPIRE_WEEKS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName + "NotExpired", testAnnoVal, 0, annosvc.EXPIRE_WEEKS);
-
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-
-  // test for unexpired annos
-  try {
-    do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName + "NotExpired"), testAnnoVal);
-  } catch(ex) {
-    do_throw("anno < 30 days old was expired!");
-  }
-  annosvc.removePageAnnotation(testURI, testAnnoName + "NotExpired");
-  try {
-    do_check_eq(annosvc.getItemAnnotation(bookmark, testAnnoName + "NotExpired"), testAnnoVal);
-  } catch(ex) {
-    do_throw("item anno < 30 days old was expired!");
-  }
-  annosvc.removeItemAnnotation(bookmark, testAnnoName + "NotExpired");
-
-  try {
-    annosvc.getPageAnnotation(testURI, testAnnoName);
-    do_throw("page still had weeks anno");
-  } catch(ex) {}
-  try {
-    annosvc.getItemAnnotation(bookmark, testAnnoName);
-    do_throw("bookmark still had weeks anno");
-  } catch(ex) {}
-
-  // test anno expiration (weeks) does not remove annos 29 days old
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_WEEKS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_WEEKS);
-  // these annotations should remain as they are only 29 days old
-  var expirationDate = (Date.now() - (29 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-
-  // test for unexpired annos
-  try {
-    do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName), testAnnoVal);
-  } catch(ex) {
-    do_throw("anno < 30 days old was expired!");
-  }
-  annosvc.removePageAnnotation(testURI, testAnnoName);
-  try {
-    do_check_eq(annosvc.getItemAnnotation(bookmark, testAnnoName), testAnnoVal);
-  } catch(ex) {
-    do_throw("item anno < 30 days old was expired!");
-  }
-  annosvc.removeItemAnnotation(bookmark, testAnnoName);
-
-  // test anno expiration (months) removes annos 181 days old
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_MONTHS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_MONTHS);
-  var expirationDate = (Date.now() - (181 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  // these annotations should remain
-  annosvc.setPageAnnotation(testURI, testAnnoName + "NotExpired", testAnnoVal, 0, annosvc.EXPIRE_MONTHS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName + "NotExpired", testAnnoVal, 0, annosvc.EXPIRE_MONTHS);
-
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-
-  // test for unexpired annos
-  try {
-    do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName + "NotExpired"), testAnnoVal);
-  } catch(ex) {
-    do_throw("anno < 180 days old was expired!");
-  }
-  annosvc.removePageAnnotation(testURI, testAnnoName + "NotExpired");
-  try {
-    do_check_eq(annosvc.getItemAnnotation(bookmark, testAnnoName + "NotExpired"), testAnnoVal);
-  } catch(ex) {
-    do_throw("item anno < 180 days old was expired!");
-  }
-  annosvc.removeItemAnnotation(bookmark, testAnnoName + "NotExpired");
-
-  try {
-    var annoVal = annosvc.getPageAnnotation(testURI, testAnnoName);
-    do_throw("page still had months anno");
-  } catch(ex) {}
-  try {
-    annosvc.getItemAnnotation(bookmark, testAnnoName);
-    do_throw("bookmark still had months anno");
-  } catch(ex) {}
-
-  // test anno expiration (months) does not remove annos 179 days old
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_MONTHS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_MONTHS);
-  // these annotations should remain as they are only 179 days old
-  var expirationDate = (Date.now() - (179 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-
-  // test for unexpired annos
-  try {
-    do_check_eq(annosvc.getPageAnnotation(testURI, testAnnoName), testAnnoVal);
-  } catch(ex) {
-    do_throw("anno < 180 days old was expired!");
-  }
-  annosvc.removePageAnnotation(testURI, testAnnoName);
-  try {
-    do_check_eq(annosvc.getItemAnnotation(bookmark, testAnnoName), testAnnoVal);
-  } catch(ex) {
-    do_throw("item anno < 180 days old was expired!");
-  }
-  annosvc.removeItemAnnotation(bookmark, testAnnoName);
-
-  // test anno expiration (session)
-  // XXX requires app restart
-
-  // test expiration of anno dateAdded vs lastModified (bug #389902)
-  // add an anno w/ days expiration
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_DAYS);
-  // make it 8 days old
-  var expirationDate = (Date.now() - (8 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET dateAdded = " + expirationDate + ", lastModified = " + expirationDate);
-  // modify its value
-  annosvc.setPageAnnotation(testURI, testAnnoName, "mod", 0, annosvc.EXPIRE_DAYS);
-  annosvc.setItemAnnotation(bookmark, testAnnoName, "mod", 0, annosvc.EXPIRE_DAYS);
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-  // anno should still be there
-  try {
-    var annoVal = annosvc.getPageAnnotation(testURI, testAnnoName);
-  } catch(ex) {
-    do_throw("page lost a days anno that was 8 days old, but was modified today");
-  }
-  try {
-    annosvc.getItemAnnotation(bookmark, testAnnoName);
-  } catch(ex) {
-    do_throw("bookmark lost a days anno that was 8 days old, but was modified today");
-  }
-
-  // now make the anno lastModified 8 days old
-  var expirationDate = (Date.now() - (8 * 86400 * 1000)) * 1000;
-  dbConnection.executeSimpleSQL("UPDATE moz_annos SET lastModified = " + expirationDate);
-  dbConnection.executeSimpleSQL("UPDATE moz_items_annos SET lastModified = " + expirationDate);
-  // add a uri and then remove it, to trigger expiration
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  bhist.removePage(triggerURI);
-  // anno should have been deleted
-  try {
-    var annoVal = annosvc.getPageAnnotation(testURI, testAnnoName);
-    do_throw("page still had a days anno that was modified 8 days ago");
-  } catch(ex) {}
-  try {
-    annosvc.getItemAnnotation(bookmark, testAnnoName);
-    do_throw("bookmark lost a days anno that was modified 8 days ago");
-  } catch(ex) {}
-
-  // cleanup
-  bmsvc.removeItem(bookmark);
-  annosvc.removePageAnnotations(testURI);
-  annosvc.removePageAnnotations(triggerURI);
-
-  startIncrementalExpirationTests();
-}
-
-// incremental expiration tests
-// run async, chained
-
-function startIncrementalExpirationTests() {
-  do_test_pending();
-  startExpireNeither();
-}
-
-/*
-test 1: NO EXPIRATION CRITERIA MET (INSIDE SITES CAP)
-
-1. zero visits > {browser.history_expire_days}
-2. zero visits > {browser.history_expire_days_min}
-   AND total visited site count < {browser.history_expire_sites}
-
-steps:
-  - clear history
-  - reset observer
-  - add a visit, w/ current date
-  - set browser.history_expire_days to 3
-  - set browser.history_expire_days_min to 2
-  - set browser.history_expire_sites to 2
-  - kick off incremental expiration
-
-confirmation:
-  - check onDeleteVisits, confirm nothing was expired
-  - query for the visit, confirm it's there
-
-*/
-function startExpireNeither() {
-  dump("startExpireNeither()\n");
-  // Cleanup.
-  histsvc.removeAllPages();
-  observer.expiredURI = null;
-
-  // Setup data.
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(triggerURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  // set sites cap to 2
-  prefs.setIntPref("browser.history_expire_sites", 2);
-  // set date minimum to 2
-  prefs.setIntPref("browser.history_expire_days_min", 2);
-  // set date maximum to 3
-  prefs.setIntPref("browser.history_expire_days", 3);
-
-  // Changing expiration preferences triggers partial expiration.
-
-  // Check results.
-  do_timeout(600, checkExpireNeither);
-}
-
-function checkExpireNeither() {
-  dump("checkExpireNeither()\n");
-  try {
-    do_check_eq(observer.expiredURI, null);
-    do_check_eq(annosvc.getPageAnnotationNames(testURI).length, 1);
-    do_check_eq(annosvc.getPageAnnotationNames(triggerURI).length, 1);
-  } catch(ex) {
-    do_throw(ex);
-  }
-  dump("done incremental expiration test 1\n");
-  startExpireDaysOnly();
-}
-
-/*
-test 2: MAX-AGE DATE CRITERIA MET
-
-1. some visits > {browser.history_expire_days}
-2. total visited sites count < {browser.history_expire_sites}
-
-steps:
-  - clear history
-  - reset observer
-  - add a visit, 4 days old (expirable)
-  - add a visit, 1 day old (not expirable)
-  - set browser.history_expire_days to 3
-  - set browser.history_expire_days_min to 2
-  - set browser.history_expire_sites to 20
-  - kick off incremental expiration
-
-confirmation:
-  - check onDeleteVisits, confirm that the expirable uri was expired
-  - query for the visit, confirm it's there
-*/
-function startExpireDaysOnly() {
-  dump("startExpireDaysOnly()\n");
-  // Cleanup.
-  histsvc.removeAllPages();
-  observer.expiredURI = null;
-
-  // add expirable visit
-  histsvc.addVisit(testURI, (Date.now() - (86400 * 4 * 1000)) * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  // add un-expirable visit
-  var unexpirableURI = uri("http://unexpirable.com");
-  histsvc.addVisit(unexpirableURI, (Date.now() - (86400 * 1000)) * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(unexpirableURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  // set sites cap to 20 (make sure it's not an expiration criteria)
-  prefs.setIntPref("browser.history_expire_sites", 20);
-  // set date minimum to 2 (also not an expiration criteria)
-  prefs.setIntPref("browser.history_expire_days_min", 2);
-  // set date maximum to 3
-  prefs.setIntPref("browser.history_expire_days", 3);
-
-  // Changing expiration preferences triggers partial expiration.
-
-  // Check results.
-  do_timeout(600, checkExpireDaysOnly);
-}
-
-function checkExpireDaysOnly() {
-  try {
-    // test expired record
-    do_check_eq(observer.expiredURI, testURI.spec);
-    do_check_eq(annosvc.getPageAnnotationNames(testURI).length, 0);
-
-    // test unexpired record
-    do_check_neq(histsvc.getPageTitle(unexpirableURI), null);
-    do_check_eq(annosvc.getPageAnnotationNames(unexpirableURI).length, 1);
-  } catch(ex) {}
-  dump("done expiration test 2\n");
-  startExpireBoth();
-}
-
-/*
-test 3: MIN-AGE+VISIT-CAP CRITERIA MET
-
-1. zero visits > {browser.history_expire_days}
-2. some visits > {browser.history_expire_days_min}
-   AND total visited sites count > {browser.history_expire_sites}
-
-steps:
-  - clear history
-  - reset observer
-  - add a visit to an url, 2 days old
-  - add a visit to another url, today
-  - set browser.history_expire_days to 3
-  - set browser.history_expire_days_min to 1
-  - set browser.history_expire_sites to 1
-  - kick off incremental expiration
-
-confirmation:
-  - check onDeleteVisits, confirm our oldest visit was expired
-  - query for the oldest visit, confirm it's not there
-*/
-function startExpireBoth() {
-  dump("starting expiration test 3: both criteria met\n");
-  // Cleanup.
-  histsvc.removeAllPages();
-  observer.expiredURI = null;
-
-  // Inserting a bookmark will force a sync, this will ensure that later we will
-  // have the same place in both temp and disk table, and that the expire site
-  // cap count is correct.
-  var bmId = bmsvc.insertBookmark(bmsvc.toolbarFolder, testURI, bmsvc.DEFAULT_INDEX, "foo");
-  bmsvc.removeItem(bmId);
-
-  // add visits
-  // 2 days old, in microseconds
-  var age = (Date.now() - (86400 * 2 * 1000)) * 1000;
-  dump("AGE: " + age + "\n");
-  histsvc.addVisit(testURI, age, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(triggerURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  // set sites cap to 1
-  prefs.setIntPref("browser.history_expire_sites", 1);
-  // set date max to 3
-  prefs.setIntPref("browser.history_expire_days", 3);
-  // set date minimum to 1
-  prefs.setIntPref("browser.history_expire_days_min", 1);
-
-  // Changing expiration preferences triggers partial expiration.
-
-  // Check results.
-  do_timeout(600, checkExpireBoth); // incremental expiration timer is 3500
-}
-
-function checkExpireBoth() {
-  try {
-    do_check_eq(observer.expiredURI, testURI.spec);
-    do_check_eq(annosvc.getPageAnnotationNames(testURI).length, 0);
-    do_check_eq(annosvc.getPageAnnotationNames(triggerURI).length, 1);
-  } catch(ex) {}
-  dump("done expiration test 3\n");
-  startExpireNeitherOver()
-}
-
-/*
-test 4: NO EXPIRATION CRITERIA MET (OVER SITES CAP)
-
-1. zero visits > {browser.history_expire_days}
-2. zero visits > {browser.history_expire_days_min}
-   AND total visited site count > {browser.history_expire_sites}
-
-steps:
-  - clear history
-  - reset observer
-  - add a visit to an url, w/ current date
-  - add a visit to another url, w/ current date
-  - set browser.history_expire_days to 3
-  - set browser.history_expire_days_min to 2
-  - set browser.history_expire_sites to 1
-  - kick off incremental expiration
-
-confirmation:
-  - check onDeleteVisits, confirm nothing was expired
-  - query for the visit, confirm it's there
-
-*/
-function startExpireNeitherOver() {
-  dump("startExpireNeitherOver()\n");
-  // Cleanup.
-  histsvc.removeAllPages();
-  observer.expiredURI = null;
-
-  // add data
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  histsvc.addVisit(triggerURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(triggerURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  // set sites cap to 1
-  prefs.setIntPref("browser.history_expire_sites", 1);
-  // set date minimum to 2
-  prefs.setIntPref("browser.history_expire_days_min", 2);
-  // set date maximum to 3
-  prefs.setIntPref("browser.history_expire_days", 3);
-
-  // Changing expiration preferences triggers partial expiration.
-
-  // Check results.
-  do_timeout(600, checkExpireNeitherOver);
-}
-
-function checkExpireNeitherOver() {
-  dump("checkExpireNeitherOver()\n");
-  try {
-    do_check_eq(observer.expiredURI, null);
-    do_check_eq(annosvc.getPageAnnotationNames(testURI).length, 1);
-    do_check_eq(annosvc.getPageAnnotationNames(triggerURI).length, 1);
-  } catch(ex) {
-    do_throw(ex);
-  }
-  dump("done incremental expiration test 4\n");
-  startExpireHistoryDisabled();
-}
-
-/*
-test 5: HISTORY DISABLED (HISTORY_EXPIRE_DAYS = 0), EXPIRE EVERYTHING
-
-1. special case when history is disabled, expire all visits
-
-steps:
-  - clear history
-  - reset observer
-  - add a visit to an url, w/ current date
-  - set browser.history_expire_days to 0
-  - kick off incremental expiration
-
-confirmation:
-  - check onDeleteVisits, confirm visit was expired
-  - query for the visit, confirm it's not there
-
-*/
-function startExpireHistoryDisabled() {
-  dump("startExpireHistoryDisabled()\n");
-  // Cleanup.
-  histsvc.removeAllPages();
-  observer.expiredURI = null;
-
-  // add data
-  histsvc.addVisit(testURI, Date.now() * 1000, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  // set date maximum to 0
-  prefs.setIntPref("browser.history_expire_days", 0);
-
-  // Changing expiration preferences triggers partial expiration.
-
-  // Check results.
-  do_timeout(600, checkExpireHistoryDisabled);
-}
-
-function checkExpireHistoryDisabled() {
-  dump("checkExpireHistoryDisabled()\n");
-  try {
-    do_check_eq(observer.expiredURI, testURI.spec);
-    do_check_eq(annosvc.getPageAnnotationNames(testURI).length, 0);
-  } catch(ex) {
-    do_throw(ex);
-  }
-  dump("done incremental expiration test 5\n");
-  startExpireBadPrefs();
-}
-
-/*
-test 6: BAD EXPIRATION PREFS (MAX < MIN)
-
-1. if max < min we force max = min to avoid deleting wrong visits
-
-steps:
-  - clear history
-  - reset observer
-  - add a visit to an url, 10 days ago
-  - set browser.history_expire_days to 1
-  - set browser.history_expire_days_min to 20
-  - kick off incremental expiration
-
-confirmation:
-  - check onDeleteVisits, confirm nothing was expired
-  - query for the visit, confirm it's there
-
-*/
-function startExpireBadPrefs() {
-  dump("startExpireBadPrefs()\n");
-  // Cleanup.
-  histsvc.removeAllPages();
-  observer.expiredURI = null;
-
-  // add data
-  var age = (Date.now() - (86400 * 10 * 1000)) * 1000;
-  histsvc.addVisit(testURI, age, null, histsvc.TRANSITION_TYPED, false, 0);
-  annosvc.setPageAnnotation(testURI, testAnnoName, testAnnoVal, 0, annosvc.EXPIRE_NEVER);
-
-  // set date minimum to 20
-  prefs.setIntPref("browser.history_expire_days_min", 20);
-  // set date maximum to 1
-  prefs.setIntPref("browser.history_expire_days", 1);
-
-  // Changing expiration preferences triggers partial expiration.
-
-  // Check results.
-  do_timeout(600, checkExpireBadPrefs);
-}
-
-function checkExpireBadPrefs() {
-  dump("checkExpireBadPrefs()\n");
-  try {
-    do_check_eq(observer.expiredURI, null);
-    do_check_eq(annosvc.getPageAnnotationNames(testURI).length, 1);
-  } catch(ex) {
-    do_throw(ex);
-  }
-  dump("done incremental expiration test 6\n");
-  do_test_finished();
-}
--- a/toolkit/components/places/tests/unit/test_history_sidebar.js
+++ b/toolkit/components/places/tests/unit/test_history_sidebar.js
@@ -94,25 +94,25 @@ function days_for_x_months_ago(aNowObj, 
   // Stay larger for eventual timezone issues, add 2 days.
   return parseInt((aNowObj - oldTime) / (1000*60*60*24)) + 2;
 }
 
 var nowObj = new Date();
 // This test relies on en-US locale
 // Offset is number of days
 var containers = [
-  { label: "Today"               , offset: 0                     , visible: true },
-  { label: "Yesterday"           , offset: -1                    , visible: true },
-  { label: "Last 7 days"         , offset: -3                    , visible: true },
-  { label: "This month"          , offset: -8                    , visible: nowObj.getDate() > 8 },
-  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 0)   , visible: true },
-  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 1)   , visible: true },
-  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 2)   , visible: true },
-  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 3)   , visible: true },
-  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 4)   , visible: true },
+  { label: "Today"               , offset: 0                                 , visible: true },
+  { label: "Yesterday"           , offset: -1                                , visible: true },
+  { label: "Last 7 days"         , offset: -3                                , visible: true },
+  { label: "This month"          , offset: -8                                , visible: nowObj.getDate() > 8 },
+  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 0) , visible: true },
+  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 1) , visible: true },
+  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 2) , visible: true },
+  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 3) , visible: true },
+  { label: ""                    , offset: -days_for_x_months_ago(nowObj, 4) , visible: true },
   { label: "Older than 6 months" , offset: -days_for_x_months_ago(nowObj, 5) , visible: true },
 ];
 
 var visibleContainers = containers.filter(
   function(aContainer) {return aContainer.visible});
 
 /**
  * Fills history and checks containers' labels.
@@ -452,19 +452,16 @@ function test_date_liveupdate(aResultTyp
   root.containerOpen = false;
 
   // Cleanup.
   bs.removeItem(itemId);
 }
 
 // main
 function run_test() {
-  // Increase history limit to 1 year
-  ps.setIntPref("browser.history_expire_days", 365);
-
   // Cleanup.
   bh.removeAllPages();
   remove_all_bookmarks();
 
   fill_history();
   test_RESULTS_AS_DATE_SITE_QUERY();
   test_RESULTS_AS_DATE_QUERY();
   test_RESULTS_AS_SITE_QUERY();