Bug 248970 - Private Browsing mode (global toggle for saving/caching everything) [places part]; r=dietrich
authorEhsan Akhgari <ehsan.akhgari@gmail.com>
Mon, 20 Oct 2008 00:44:59 +0330
changeset 20637 e9b859357547
parent 20636 53b78b1b3910
child 20638 81e6937843a7
push id3021
push userehsan.akhgari@gmail.com
push date2008-10-19 21:18 +0000
Treeherderresults
reviewersdietrich
bugs248970
milestone1.9.1b2pre
Bug 248970 - Private Browsing mode (global toggle for saving/caching everything) [places part]; r=dietrich
toolkit/components/places/src/nsAnnotationService.cpp
toolkit/components/places/src/nsAnnotationService.h
toolkit/components/places/src/nsFaviconService.cpp
toolkit/components/places/src/nsNavHistory.cpp
toolkit/components/places/src/nsNavHistory.h
toolkit/components/places/src/nsNavHistoryAutoComplete.cpp
toolkit/components/places/tests/unit/test_248970.js
--- a/toolkit/components/places/src/nsAnnotationService.cpp
+++ b/toolkit/components/places/src/nsAnnotationService.cpp
@@ -17,16 +17,17 @@
  * 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):
  *   Brett Wilson <brettw@gmail.com> (original author)
  *   Asaf Romano <mano@mozilla.com>
+ *   Ehsan Akhgari <ehsan.akhgari@gmail.com>
  *
  * 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
@@ -464,16 +465,19 @@ nsAnnotationService::SetItemAnnotation(P
 
 NS_IMETHODIMP
 nsAnnotationService::SetPageAnnotationString(nsIURI* aURI,
                                              const nsACString& aName,
                                              const nsAString& aValue,
                                              PRInt32 aFlags,
                                              PRUint16 aExpiration)
 {
+  if (InPrivateBrowsingMode())
+    return NS_OK;
+
   PRInt64 placeId;
   nsresult rv = GetPlaceIdForURI(aURI, &placeId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetAnnotationStringInternal(placeId, PR_FALSE, aName, aValue, aFlags,
                                    aExpiration);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -541,16 +545,19 @@ nsAnnotationService::SetAnnotationInt32I
 
 NS_IMETHODIMP
 nsAnnotationService::SetPageAnnotationInt32(nsIURI* aURI,
                                             const nsACString& aName,
                                             PRInt32 aValue,
                                             PRInt32 aFlags,
                                             PRUint16 aExpiration)
 {
+  if (InPrivateBrowsingMode())
+    return NS_OK;
+
   PRInt64 placeId;
   nsresult rv = GetPlaceIdForURI(aURI, &placeId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetAnnotationInt32Internal(placeId, PR_FALSE, aName, aValue, aFlags,
                                   aExpiration);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -617,16 +624,19 @@ nsAnnotationService::SetAnnotationInt64I
 
 NS_IMETHODIMP
 nsAnnotationService::SetPageAnnotationInt64(nsIURI* aURI,
                                             const nsACString& aName,
                                             PRInt64 aValue,
                                             PRInt32 aFlags,
                                             PRUint16 aExpiration)
 {
+  if (InPrivateBrowsingMode())
+    return NS_OK;
+
   PRInt64 placeId;
   nsresult rv = GetPlaceIdForURI(aURI, &placeId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetAnnotationInt64Internal(placeId, PR_FALSE, aName, aValue, aFlags,
                                   aExpiration);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -693,16 +703,19 @@ nsAnnotationService::SetAnnotationDouble
 
 NS_IMETHODIMP
 nsAnnotationService::SetPageAnnotationDouble(nsIURI* aURI,
                                              const nsACString& aName,
                                              double aValue,
                                              PRInt32 aFlags,
                                              PRUint16 aExpiration)
 {
+  if (InPrivateBrowsingMode())
+    return NS_OK;
+
   PRInt64 placeId;
   nsresult rv = GetPlaceIdForURI(aURI, &placeId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetAnnotationDoubleInternal(placeId, PR_FALSE, aName, aValue, aFlags,
                                    aExpiration);                      
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -776,16 +789,19 @@ NS_IMETHODIMP
 nsAnnotationService::SetPageAnnotationBinary(nsIURI* aURI,
                                              const nsACString& aName,
                                              const PRUint8 *aData,
                                              PRUint32 aDataLen,
                                              const nsACString& aMimeType,
                                              PRInt32 aFlags,
                                              PRUint16 aExpiration)
 {
+  if (InPrivateBrowsingMode())
+    return NS_OK;
+
   PRInt64 placeId;
   nsresult rv = GetPlaceIdForURI(aURI, &placeId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetAnnotationBinaryInternal(placeId, PR_FALSE, aName, aData, aDataLen,
                                    aMimeType, aFlags, aExpiration);
   CallSetForPageObservers(aURI, aName);
   return NS_OK;
@@ -1570,16 +1586,19 @@ nsAnnotationService::RemoveItemAnnotatio
 //    efficient than operating on name IDs, which we should consider if this
 //    is too slow.
 
 NS_IMETHODIMP
 nsAnnotationService::CopyPageAnnotations(nsIURI* aSourceURI,
                                          nsIURI* aDestURI,
                                          PRBool aOverwriteDest)
 {
+  if (InPrivateBrowsingMode())
+    return NS_OK;
+
   mozStorageTransaction transaction(mDBConn, PR_FALSE);
 
   // source
   PRInt64 sourcePlaceId;
   nsresult rv = GetPlaceIdForURI(aSourceURI, &sourcePlaceId, PR_FALSE);
   NS_ENSURE_SUCCESS(rv, rv);
   if (sourcePlaceId == 0) // Check if URI exists.
     return NS_OK;
@@ -1814,16 +1833,24 @@ nsAnnotationService::StartGetAnnotationF
 
   // on success, DON'T reset the statement, the caller needs to read from it,
   // and it is the caller's job to do the reseting.
   statementResetter.Abandon();
   return NS_OK;
 }
 
 
+PRBool
+nsAnnotationService::InPrivateBrowsingMode() const
+{
+  nsNavHistory* history = nsNavHistory::GetHistoryService();
+  return history && history->InPrivateBrowsingMode();
+}
+
+
 nsresult
 nsAnnotationService::GetPlaceIdForURI(nsIURI* aURI, PRInt64* _retval,
                                       PRBool aAutoCreate)
 {
   nsNavHistory* history = nsNavHistory::GetHistoryService();
   NS_ENSURE_TRUE(history, NS_ERROR_FAILURE);
 
   return history->GetUrlIdFor(aURI, _retval, aAutoCreate);
--- a/toolkit/components/places/src/nsAnnotationService.h
+++ b/toolkit/components/places/src/nsAnnotationService.h
@@ -166,16 +166,18 @@ protected:
                                        PRInt32 aFlags,
                                        PRUint16 aExpiration);
   nsresult RemoveAnnotationInternal(PRInt64 aFkId,
                                     PRBool aIsItemAnnotation,
                                     const nsACString& aName);
   static nsresult GetPlaceIdForURI(nsIURI* aURI, PRInt64* _retval,
                                    PRBool aAutoCreate = PR_TRUE);
 
+  PRBool InPrivateBrowsingMode() const;
+
   void CallSetForPageObservers(nsIURI* aURI, const nsACString& aName);
   void CallSetForItemObservers(PRInt64 aItemId, const nsACString& aName);
 
 public:
   nsresult GetPagesWithAnnotationCOMArray(const nsACString& aName,
                                           nsCOMArray<nsIURI>* aResults);
   nsresult GetItemsWithAnnotationTArray(const nsACString& aName,
                                         nsTArray<PRInt64>* aResult);
--- a/toolkit/components/places/src/nsFaviconService.cpp
+++ b/toolkit/components/places/src/nsFaviconService.cpp
@@ -290,16 +290,22 @@ nsFaviconService::SetFaviconUrlForPageIn
         *aHasData = PR_TRUE;
 
       // expiration
       rv = mDBGetIconInfo->GetInt64(2, aExpiration);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
+  nsNavHistory* historyService = nsNavHistory::GetHistoryService();
+  NS_ENSURE_TRUE(historyService, NS_ERROR_OUT_OF_MEMORY);
+
+  if (historyService->InPrivateBrowsingMode())
+    return NS_OK;
+
   if (iconId == -1) {
     // We did not find any entry, so create a new one
     *aHasData = PR_FALSE;
     *aExpiration = 0;
 
     // not-binded params are automatically nullified by mozStorage
     mozStorageStatementScoper scoper(mDBInsertIcon);
     rv = BindStatementURI(mDBInsertIcon, 0, aFaviconURI);
@@ -318,19 +324,16 @@ nsFaviconService::SetFaviconUrlForPageIn
       rv = mDBGetIconInfo->ExecuteStep(&hasResult);
       NS_ENSURE_SUCCESS(rv, rv);
       NS_ASSERTION(hasResult, "hasResult is false but the call succeeded?");
       iconId = mDBGetIconInfo->AsInt64(0);
     }
   }
 
   // now link our icon entry with the page
-  nsNavHistory* historyService = nsNavHistory::GetHistoryService();
-  NS_ENSURE_TRUE(historyService, NS_ERROR_OUT_OF_MEMORY);
-
   PRInt64 pageId;
   rv = historyService->GetUrlIdFor(aPageURI, &pageId, PR_TRUE);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mozStorageStatementScoper scoper(mDBSetPageFavicon);
   rv = mDBSetPageFavicon->BindInt64Parameter(0, pageId);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = mDBSetPageFavicon->BindInt64Parameter(1, iconId);
--- a/toolkit/components/places/src/nsNavHistory.cpp
+++ b/toolkit/components/places/src/nsNavHistory.cpp
@@ -20,16 +20,18 @@
  *
  * Contributor(s):
  *   Brett Wilson <brettw@gmail.com> (original author)
  *   Dietrich Ayala <dietrich@mozilla.com>
  *   Seth Spitzer <sspitzer@mozilla.com>
  *   Asaf Romano <mano@mozilla.com>
  *   Marco Bonardo <mak77@bonardo.net>
  *   Edward Lee <edward.lee@engineering.uiuc.edu>
+ *   Michael Ventnor <m.ventnor@gmail.com>
+ *   Ehsan Akhgari <ehsan.akhgari@gmail.com>
  *
  * 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
@@ -362,17 +364,18 @@ nsNavHistory::nsNavHistory() : mBatchLev
                                mMatchTitle(PR_FALSE),
                                mMatchUrl(PR_FALSE),
                                mPreviousChunkOffset(-1),
                                mAutoCompleteFinishedSearch(PR_FALSE),
                                mExpireDaysMin(0),
                                mExpireDaysMax(0),
                                mExpireSites(0),
                                mNumVisitsForFrecency(10),
-                               mTagsFolder(-1)
+                               mTagsFolder(-1),
+                               mInPrivateBrowsing(PRIVATEBROWSING_NOTINITED)
 {
 #ifdef LAZY_ADD
   mLazyTimerSet = PR_TRUE;
   mLazyTimerDeferments = 0;
 #endif
   NS_ASSERTION(! gHistoryService, "YOU ARE CREATING 2 COPIES OF THE HISTORY SERVICE. Everything will break.");
   gHistoryService = this;
 }
@@ -510,16 +513,17 @@ nsNavHistory::Init()
     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);
   }
 
   observerService->AddObserver(this, gQuitApplicationMessage, PR_FALSE);
   observerService->AddObserver(this, gXpcomShutdown, PR_FALSE);
   observerService->AddObserver(this, gAutoCompleteFeedback, PR_FALSE);
+  observerService->AddObserver(this, NS_PRIVATE_BROWSING_SWITCH_TOPIC, PR_FALSE);
 
   /*****************************************************************************
    *** IMPORTANT NOTICE!
    ***
    *** NO CODE SHOULD GO BEYOND THIS POINT THAT WOULD PROPAGATE AN ERROR.  IN
    *** OTHER WORDS, THE ONLY THING THAT SHOULD BE RETURNED AFTER THIS POINT IS
    *** NS_OK.
    ****************************************************************************/
@@ -2441,16 +2445,22 @@ nsNavHistory::MarkPageAsFollowedBookmark
 
 NS_IMETHODIMP
 nsNavHistory::CanAddURI(nsIURI* aURI, PRBool* canAdd)
 {
   NS_ASSERTION(NS_IsMainThread(), "This can only be called on the main thread");
 
   NS_ENSURE_ARG_POINTER(aURI);
 
+  // If the user is in private browsing mode, don't add any entry.
+  if (InPrivateBrowsingMode()) {
+    *canAdd = PR_FALSE;
+    return NS_OK;
+  }
+
   nsCAutoString scheme;
   nsresult rv = aURI->GetScheme(scheme);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // first check the most common cases (HTTP, HTTPS) to allow in to avoid most
   // of the work
   if (scheme.EqualsLiteral("http")) {
     *canAdd = PR_TRUE;
@@ -4700,16 +4710,17 @@ nsNavHistory::Observe(nsISupports *aSubj
     nsNavBookmarks* bookmarks = nsNavBookmarks::GetBookmarksService();
     NS_ENSURE_TRUE(bookmarks, NS_ERROR_OUT_OF_MEMORY);
     (void)bookmarks->OnQuit();
   } else if (nsCRT::strcmp(aTopic, gXpcomShutdown) == 0) {
     nsresult rv;
     nsCOMPtr<nsIObserverService> observerService =
       do_GetService("@mozilla.org/observer-service;1", &rv);
     NS_ENSURE_SUCCESS(rv, rv);
+    observerService->RemoveObserver(this, NS_PRIVATE_BROWSING_SWITCH_TOPIC);
     observerService->RemoveObserver(this, gAutoCompleteFeedback);
     observerService->RemoveObserver(this, gXpcomShutdown);
     observerService->RemoveObserver(this, gQuitApplicationMessage);
   } else if (nsCRT::strcmp(aTopic, gAutoCompleteFeedback) == 0) {
 #ifdef MOZ_XUL
     nsCOMPtr<nsIAutoCompleteInput> input = do_QueryInterface(aSubject);
     if (!input)
       return NS_OK;
@@ -4744,16 +4755,22 @@ nsNavHistory::Observe(nsISupports *aSubj
   } else if (nsCRT::strcmp(aTopic, "nsPref:changed") == 0) {
     PRInt32 oldDaysMin = mExpireDaysMin;
     PRInt32 oldDaysMax = mExpireDaysMax;
     PRInt32 oldVisits = mExpireSites;
     LoadPrefs(PR_FALSE);
     if (oldDaysMin != mExpireDaysMin || oldDaysMax != mExpireDaysMax ||
         oldVisits != mExpireSites)
       mExpire.OnExpirationChanged();
+  } else if (nsCRT::strcmp(aTopic, NS_PRIVATE_BROWSING_SWITCH_TOPIC) == 0) {
+    if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_ENTER).Equals(aData)) {
+      mInPrivateBrowsing = PR_TRUE;
+    } else if (NS_LITERAL_STRING(NS_PRIVATE_BROWSING_LEAVE).Equals(aData)) {
+      mInPrivateBrowsing = PR_FALSE;
+    }
   }
 
   return NS_OK;
 }
 
 
 // Lazy stuff ******************************************************************
 
--- a/toolkit/components/places/src/nsNavHistory.h
+++ b/toolkit/components/places/src/nsNavHistory.h
@@ -17,16 +17,17 @@
  * 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):
  *   Brett Wilson <brettw@gmail.com> (original author)
  *   Edward Lee <edward.lee@engineering.uiuc.edu>
+ *   Ehsan Akhgari <ehsan.akhgari@gmail.com>
  *
  * 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
@@ -84,16 +85,19 @@
 #include "nsMaybeWeakPtr.h"
 
 #include "nsNavHistoryExpire.h"
 #include "nsNavHistoryResult.h"
 #include "nsNavHistoryQuery.h"
 
 #include "nsICharsetResolver.h"
 
+#include "nsIPrivateBrowsingService.h"
+#include "nsNetCID.h"
+
 // define to maintain sqlite temporary tables in memory rather than on disk
 #define IN_MEMORY_SQLITE_TEMP_STORE
 
 // define to enable lazy link adding
 #define LAZY_ADD
 
 #define QUERYUPDATE_TIME 0
 #define QUERYUPDATE_SIMPLE 1
@@ -103,16 +107,20 @@
 
 // this is a work-around for a problem with the optimizer of sqlite
 // A sub-select on MAX(visit_date) is slower than this query with our indexes
 // see Bug #392399 for more details
 #define SQL_STR_FRAGMENT_MAX_VISIT_DATE( place_relation ) \
   "(SELECT visit_date FROM moz_historyvisits WHERE place_id = " place_relation \
   " AND visit_type NOT IN (0,4,7) ORDER BY visit_date DESC LIMIT 1)"
 
+// This magic number specified an uninitialized value for the
+// mInPrivateBrowsing member
+#define PRIVATEBROWSING_NOTINITED (PRBool(0xffffffff))
+
 struct AutoCompleteIntermediateResult;
 class AutoCompleteResultComparator;
 class mozIAnnotationService;
 class nsNavHistory;
 class nsNavBookmarks;
 class QueryKeyValuePair;
 class nsIEffectiveTLDService;
 class nsIIDNService;
@@ -240,17 +248,17 @@ public:
     { return mLocale; }
   nsICollation* GetCollation()
     { return mCollation; }
   nsIDateTimeFormat* GetDateFormatter()
     { return mDateFormatter; }
   void GetStringFromName(const PRUnichar* aName, nsACString& aResult);
 
   // returns true if history has been disabled
-  PRBool IsHistoryDisabled() { return mExpireDaysMax == 0; }
+  PRBool IsHistoryDisabled() { return mExpireDaysMax == 0 || InPrivateBrowsingMode(); }
 
   // get the statement for selecting a history row by URL
   mozIStorageStatement* DBGetURLPageInfo() { return mDBGetURLPageInfo; }
 
   // Constants for the columns returned by the above statement.
   static const PRInt32 kGetInfoIndex_PageID;
   static const PRInt32 kGetInfoIndex_URL;
   static const PRInt32 kGetInfoIndex_Title;
@@ -364,16 +372,31 @@ public:
   // Checks the database for any duplicate URLs.  If any are found,
   // all but the first are removed.  This must be called after using
   // AddPageWithVisit, to ensure that the database is in a consistent state.
   nsresult RemoveDuplicateURIs();
 
   // sets the schema version in the database to match SCHEMA_VERSION
   nsresult UpdateSchemaVersion();
 
+  // Returns true if we are currently in private browsing mode
+  PRBool InPrivateBrowsingMode()
+  {
+    if (mInPrivateBrowsing == PRIVATEBROWSING_NOTINITED) {
+      mInPrivateBrowsing = PR_FALSE;
+      nsCOMPtr<nsIPrivateBrowsingService> pbs =
+        do_GetService(NS_PRIVATE_BROWSING_SERVICE_CONTRACTID);
+      if (pbs) {
+        pbs->GetPrivateBrowsingEnabled(&mInPrivateBrowsing);
+      }
+    }
+
+    return mInPrivateBrowsing;
+  }
+
   typedef nsDataHashtable<nsCStringHashKey, nsCString> StringHash;
 
  private:
   ~nsNavHistory();
 
   // used by GetHistoryService
   static nsNavHistory* gHistoryService;
 
@@ -784,16 +807,18 @@ protected:
    */
   nsCOMPtr<nsITimer> mIdleTimer;
   nsresult InitializeIdleTimer();
   static void IdleTimerCallback(nsITimer* aTimer, void* aClosure);
   nsresult OnIdle();
 
   PRInt64 mTagsFolder;
   PRInt64 GetTagsFolder();
+
+  PRBool mInPrivateBrowsing;
 };
 
 /**
  * Shared between the places components, this function binds the given URI as
  * UTF8 to the given parameter for the statement.
  */
 nsresult BindStatementURI(mozIStorageStatement* statement, PRInt32 index,
                           nsIURI* aURI);
--- a/toolkit/components/places/src/nsNavHistoryAutoComplete.cpp
+++ b/toolkit/components/places/src/nsNavHistoryAutoComplete.cpp
@@ -21,16 +21,17 @@
  *
  * Contributor(s):
  *   Brett Wilson <brettw@gmail.com>
  *   Joe Hewitt <hewitt@netscape.com>
  *   Blake Ross <blaker@netscape.com>
  *   Seth Spitzer <sspitzer@mozilla.org>
  *   Dietrich Ayala <dietrich@mozilla.com>
  *   Edward Lee <edward.lee@engineering.uiuc.edu>
+ *   Ehsan Akhgari <ehsan.akhgari@gmail.com>
  *
  * 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
@@ -1004,16 +1005,20 @@ nsNavHistory::OnValueRemoved(nsIAutoComp
 
   return NS_OK;
 }
 
 nsresult
 nsNavHistory::AutoCompleteFeedback(PRInt32 aIndex,
                                    nsIAutoCompleteController *aController)
 {
+  // we don't track user choices in the awesomebar in private browsing mode
+  if (InPrivateBrowsingMode())
+    return NS_OK;
+
   mozStorageStatementScoper scope(mDBFeedbackIncrease);
 
   nsAutoString input;
   nsresult rv = aController->GetSearchString(input);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = mDBFeedbackIncrease->BindStringParameter(0, input);
   NS_ENSURE_SUCCESS(rv, rv);
 
new file mode 100644
--- /dev/null
+++ b/toolkit/components/places/tests/unit/test_248970.js
@@ -0,0 +1,358 @@
+/* ***** 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 Private Browsing Tests.
+ *
+ * The Initial Developer of the Original Code is
+ * Aaron Train.
+ * Portions created by the Initial Developer are Copyright (C) 2008
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Aaron Train <aaron.train@gmail.com> (Original Author)
+ *   Ehsan Akhgari <ehsan.akhgari@gmail.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of 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 unit test performs checks on the history testing area as outlined
+// https://wiki.mozilla.org/Firefox3.1/PrivateBrowsing/TestPlan#History
+// http://developer.mozilla.org/en/Using_the_Places_history_service
+
+// Get global history service
+try {
+  var bhist = Cc["@mozilla.org/browser/global-history;2"].
+                getService(Ci.nsIBrowserHistory);
+} catch(ex) {
+  do_throw("Could not get global history service");
+}
+
+// Get bookmark service
+try {
+  var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
+              getService(Ci.nsINavBookmarksService);
+} catch(ex) {
+  do_throw("Could not get nav-bookmarks-service");
+}
+
+// Get history service
+try {
+  var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
+                getService(Ci.nsINavHistoryService);
+} catch(ex) {
+  do_throw("Could not get history service");
+}
+
+// Get the IO service
+try {
+  var ios = Cc["@mozilla.org/network/io-service;1"].
+            getService(Components.interfaces.nsIIOService);
+} catch(ex) {
+  do_throw("Could not get the io service");
+}
+
+
+/**
+ * Function prohibits an attempt to pop up a confirmation
+ * dialog box when entering Private Browsing mode.
+ *
+ * @returns a reference to the Private Browsing service
+ */
+var _PBSvc = null;
+function get_PBSvc() {
+  if (_PBSvc)
+    return _PBSvc;
+
+  try {
+    _PBSvc = Components.classes["@mozilla.org/privatebrowsing;1"].
+             getService(Components.interfaces.nsIPrivateBrowsingService);
+    if (_PBSvc) {
+      var observer = {
+        QueryInterface: function (iid) {
+          const interfaces = [Components.interfaces.nsIObserver,
+                              Components.interfaces.nsISupports];
+          if (!interfaces.some(function(v) iid.equals(v)))
+            throw Components.results.NS_ERROR_NO_INTERFACE;
+          return this;
+        },
+        observe: function (subject, topic, data) {
+          subject.QueryInterface(Components.interfaces.nsISupportsPRUint32);
+          subject.data = 0;
+        }
+      };
+      var os = Components.classes["@mozilla.org/observer-service;1"].
+               getService(Components.interfaces.nsIObserverService);
+      os.addObserver(observer, "private-browsing-enter", false);
+    }
+    return _PBSvc;
+  } catch (e) {}
+  return null;
+}
+
+/**
+ * Adds a test URI visit to the database
+ *
+ * @param aURI
+ *        The URI to add a visit for.
+ * @param aType
+ *        Transition type for the URI.
+ * @returns the place id for aURI.
+ */
+function add_visit(aURI, aType) {
+  var placeID = histsvc.addVisit(uri(aURI),
+                                 Date.now() * 1000,
+                                 null, // no referrer
+                                 aType,
+                                 false, // not redirect
+                                 0);
+  return placeID;
+}
+
+/**
+ * Checks to see that a URI is in the database.
+ *
+ * @param aURI
+ *        The URI to check.
+ * @returns true if the URI is in the DB, false otherwise.
+ */
+function uri_in_db(aURI) {
+  var options = histsvc.getNewQueryOptions();
+  options.maxResults = 1;
+  options.resultType = options.RESULTS_AS_URI;
+  options.includeHidden = true;
+  var query = histsvc.getNewQuery();
+  query.uri = aURI;
+  var result = histsvc.executeQuery(query, options);
+  var root = result.root;
+  root.containerOpen = true;
+  return (root.childCount == 1);
+}
+
+var visited_URIs = ["http://www.test-link.com/",
+                    "http://www.test-typed.com/",
+                    "http://www.test-bookmark.com/",
+                    "http://www.test-redirect-permanent.com/",
+                    "http://www.test-redirect-temporary.com/",
+                    "http://www.test-embed.com",
+                    "http://www.test-download.com"];
+
+var nonvisited_URIs = ["http://www.google.ca/",
+                       "http://www.google.com/",
+                       "http://www.google.co.il/",
+                       "http://www.google.fr/",
+                       "http://www.google.es",
+                       "http://www.google.com.tr",
+                       "http://www.google.de"];
+/**
+ * Function fills history, one for each transition type.
+ *
+ * @returns nothing
+ */
+function fill_history_visitedURI() {
+  add_visit(visited_URIs[0], histsvc.TRANSITION_LINK);
+  add_visit(visited_URIs[1], histsvc.TRANSITION_TYPED);
+  add_visit(visited_URIs[2], histsvc.TRANSITION_BOOKMARK);
+  add_visit(visited_URIs[3], histsvc.TRANSITION_EMBED);
+  add_visit(visited_URIs[4], histsvc.TRANSITION_REDIRECT_PERMANENT);
+  add_visit(visited_URIs[5], histsvc.TRANSITION_REDIRECT_TEMPORARY);
+  add_visit(visited_URIs[6], histsvc.TRANSITION_DOWNLOAD);
+}
+
+/**
+ * Function fills history, one for each transition type.
+ * second batch of history items
+ *
+ * @returns nothing
+ */
+function fill_history_nonvisitedURI() {
+  add_visit(nonvisited_URIs[0], histsvc.TRANSITION_TYPED);
+  add_visit(nonvisited_URIs[1], histsvc.TRANSITION_BOOKMARK);
+  add_visit(nonvisited_URIs[2], histsvc.TRANSITION_LINK);
+  add_visit(nonvisited_URIs[3], histsvc.TRANSITION_DOWNLOAD);
+  add_visit(nonvisited_URIs[4], histsvc.TRANSITION_EMBED);
+  add_visit(nonvisited_URIs[5], histsvc.TRANSITION_REDIRECT_PERMANENT);
+  add_visit(nonvisited_URIs[6], histsvc.TRANSITION_REDIRECT_TEMPORARY);
+}
+
+// Initial batch of history items (7) + Bookmark_A (1)
+// This number should not change after tests enter private browsing
+// it will be set to 9 with the addition of Bookmark-B during private
+// browsing mode.
+var num_places_entries = 8; 
+
+/**
+ * Function performs a really simple query on our places entries,
+ * and makes sure that the number of entries equal num_places_entries.
+ *
+ * @returns nothing
+ */
+function check_placesItem_Count(){
+  var options = histsvc.getNewQueryOptions();
+  options.includeHidden = true;
+  var query = histsvc.getNewQuery();
+  var result = histsvc.executeQuery(query, options);
+  var root = result.root;
+  root.containerOpen = true;
+  var cc = root.childCount;
+  do_check_eq(cc,num_places_entries);
+  root.containerOpen = false;
+}
+
+/**
+ * Function creates a bookmark
+ * @param aURI
+ *        The URI for the bookmark
+ * @param aTitle
+ *        The title for the bookmark
+ * @param aKeyword
+ *        The keyword for the bookmark
+ * @returns the bookmark
+ */
+
+var myBookmarks=new Array(2); // Bookmark-A
+                              // Bookmark-B
+
+function create_bookmark(aURI, aTitle, aKeyword) {
+  var bookmarkID = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder,aURI,
+                   bmsvc.DEFAULT_INDEX,aTitle);
+  bmsvc.setKeywordForBookmark(bookmarkID,aKeyword);
+  return bookmarkID;
+}
+
+/**
+ * Function attempts to check if Bookmark-A has been visited
+ * during private browsing mode, function should return false
+ *
+ * @returns false if the accessCount has not changed
+ *          true if the accessCount has changed
+ */
+function is_bookmark_A_altered(){
+
+  var options = histsvc.getNewQueryOptions();
+  options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
+  options.maxResults = 1; // should only expect Bookmark-A
+  options.resultType = options.RESULT_TYPE_VISIT;
+
+  var query  = histsvc.getNewQuery();
+  query.setFolders([bmsvc.bookmarksMenuFolder],1);
+
+  var result = histsvc.executeQuery(query,options);
+  var root = result.root;
+
+  root.containerOpen = true;
+
+  do_check_eq(root.childCount,options.maxResults);
+
+  var node = root.getChild(0);
+  root.containerOpen = false;
+
+  return (node.accessCount!=0);
+}
+
+function run_test() {
+
+  // Fetch the private browsing service
+  var pb = get_PBSvc();
+
+  if(pb){ // Private Browsing might not be available
+
+    // History database should be empty
+    do_check_false(histsvc.hasHistoryEntries);
+
+    // Create a handful of history items with various visit types
+    fill_history_visitedURI();
+
+    // History database should have entries
+    do_check_true(histsvc.hasHistoryEntries);
+
+    // Create Bookmark-A
+    var bookmark_A_URI = ios.newURI("http://google.com/", null, null);
+    myBookmarks[0] = create_bookmark(bookmark_A_URI,"title 1", "google");
+
+    // History items should be retrievable by query
+    for each(var visited_uri in visited_URIs) {
+      do_check_true(bhist.isVisited(uri(visited_uri)));
+      do_check_true(uri_in_db(uri(visited_uri)));
+    }
+
+    check_placesItem_Count();
+
+    // Bookmark-A should be bookmarked, data should be retrievable
+    do_check_true(bmsvc.isBookmarked(bookmark_A_URI));
+    do_check_eq("google",bmsvc.getKeywordForURI(bookmark_A_URI));
+
+    // Enter Private Browsing Mode
+    pb.privateBrowsingEnabled = true;
+
+    // History items should not retrievable by isVisited
+    for each(var visited_uri in visited_URIs)
+      do_check_false(bhist.isVisited(uri(visited_uri)));
+
+    // Check if Bookmark-A has been visited, should be false
+    do_check_false(is_bookmark_A_altered());
+
+    // Add a second set of history items during private browsing mode
+    // should not be viewed/stored or in any way retrievable
+    fill_history_nonvisitedURI();
+    for each(var nonvisited_uri in nonvisited_URIs) {
+      do_check_false(uri_in_db(uri(nonvisited_uri)));
+      do_check_false(bhist.isVisited(uri(nonvisited_uri)));
+    }
+
+    // We attempted to add another 7 new entires, but we still have 7 history entries
+    // and 1 history entry, Bookmark-A.
+    // Private browsing blocked the entry of the new history entries
+    check_placesItem_Count();
+
+    // Check if Bookmark-A is still accessible
+    do_check_true(bmsvc.isBookmarked(bookmark_A_URI));
+    do_check_eq("google",bmsvc.getKeywordForURI(bookmark_A_URI));
+
+    // Create Bookmark-B
+    var bookmark_B_URI = ios.newURI("http://bugzilla.mozilla.org/", null, null);
+    myBookmarks[1] = create_bookmark(bookmark_B_URI,"title 2", "bugzilla");
+
+    // A check on the history count should be same as before, 7 history entries with
+    // now 2 bookmark items (A) and bookmark (B), so we set num_places_entries to 9
+    num_places_entries = 9; // Bookmark-B successfully added but not the history entries.
+    check_placesItem_Count();
+
+    // Exit Private Browsing Mode
+    pb.privateBrowsingEnabled = false;
+
+    // Check if Bookmark-B is still accessible
+    do_check_true(bmsvc.isBookmarked(bookmark_B_URI));
+    do_check_eq("bugzilla",bmsvc.getKeywordForURI(bookmark_B_URI));
+
+    // Check if Bookmark-A is still accessible
+    do_check_true(bmsvc.isBookmarked(bookmark_A_URI));
+    do_check_eq("google",bmsvc.getKeywordForURI(bookmark_A_URI));
+
+    // Check that the original set of history items are still accessible via isVisited
+    for each(var visited_uri in visited_URIs) {
+      do_check_true(uri_in_db(uri(visited_uri)));
+      do_check_true(bhist.isVisited(uri(visited_uri)));
+    }
+  }
+}