history_backend.cc revision a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/history/history_backend.h"
6
7#include <algorithm>
8#include <functional>
9#include <list>
10#include <map>
11#include <set>
12#include <vector>
13
14#include "base/basictypes.h"
15#include "base/bind.h"
16#include "base/compiler_specific.h"
17#include "base/files/file_enumerator.h"
18#include "base/memory/scoped_ptr.h"
19#include "base/memory/scoped_vector.h"
20#include "base/message_loop/message_loop.h"
21#include "base/metrics/histogram.h"
22#include "base/rand_util.h"
23#include "base/strings/string_util.h"
24#include "base/strings/utf_string_conversions.h"
25#include "base/time/time.h"
26#include "chrome/browser/autocomplete/history_url_provider.h"
27#include "chrome/browser/bookmarks/bookmark_service.h"
28#include "chrome/browser/chrome_notification_types.h"
29#include "chrome/browser/favicon/favicon_changed_details.h"
30#include "chrome/browser/history/download_row.h"
31#include "chrome/browser/history/history_db_task.h"
32#include "chrome/browser/history/history_notifications.h"
33#include "chrome/browser/history/in_memory_history_backend.h"
34#include "chrome/browser/history/page_usage_data.h"
35#include "chrome/browser/history/select_favicon_frames.h"
36#include "chrome/browser/history/top_sites.h"
37#include "chrome/browser/history/typed_url_syncable_service.h"
38#include "chrome/browser/history/visit_filter.h"
39#include "chrome/common/chrome_constants.h"
40#include "chrome/common/importer/imported_favicon_usage.h"
41#include "chrome/common/url_constants.h"
42#include "grit/chromium_strings.h"
43#include "grit/generated_resources.h"
44#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
45#include "sql/error_delegate_util.h"
46#include "url/gurl.h"
47
48#if defined(OS_ANDROID)
49#include "chrome/browser/history/android/android_provider_backend.h"
50#endif
51
52using base::Time;
53using base::TimeDelta;
54using base::TimeTicks;
55
56/* The HistoryBackend consists of a number of components:
57
58    HistoryDatabase (stores past 3 months of history)
59      URLDatabase (stores a list of URLs)
60      DownloadDatabase (stores a list of downloads)
61      VisitDatabase (stores a list of visits for the URLs)
62      VisitSegmentDatabase (stores groups of URLs for the most visited view).
63
64    ArchivedDatabase (stores history older than 3 months)
65      URLDatabase (stores a list of URLs)
66      DownloadDatabase (stores a list of downloads)
67      VisitDatabase (stores a list of visits for the URLs)
68
69      (this does not store visit segments as they expire after 3 mos.)
70
71    ExpireHistoryBackend (manages moving things from HistoryDatabase to
72                          the ArchivedDatabase and deleting)
73*/
74
75namespace history {
76
77// How long we keep segment data for in days. Currently 3 months.
78// This value needs to be greater or equal to
79// MostVisitedModel::kMostVisitedScope but we don't want to introduce a direct
80// dependency between MostVisitedModel and the history backend.
81const int kSegmentDataRetention = 90;
82
83// How long we'll wait to do a commit, so that things are batched together.
84const int kCommitIntervalSeconds = 10;
85
86// The amount of time before we re-fetch the favicon.
87const int kFaviconRefetchDays = 7;
88
89// The maximum number of items we'll allow in the redirect list before
90// deleting some.
91const int kMaxRedirectCount = 32;
92
93// The number of days old a history entry can be before it is considered "old"
94// and is archived.
95const int kArchiveDaysThreshold = 90;
96
97#if defined(OS_ANDROID)
98// The maximum number of top sites to track when recording top page visit stats.
99const size_t kPageVisitStatsMaxTopSites = 50;
100#endif
101
102// Converts from PageUsageData to MostVisitedURL. |redirects| is a
103// list of redirects for this URL. Empty list means no redirects.
104MostVisitedURL MakeMostVisitedURL(const PageUsageData& page_data,
105                                  const RedirectList& redirects) {
106  MostVisitedURL mv;
107  mv.url = page_data.GetURL();
108  mv.title = page_data.GetTitle();
109  if (redirects.empty()) {
110    // Redirects must contain at least the target url.
111    mv.redirects.push_back(mv.url);
112  } else {
113    mv.redirects = redirects;
114    if (mv.redirects[mv.redirects.size() - 1] != mv.url) {
115      // The last url must be the target url.
116      mv.redirects.push_back(mv.url);
117    }
118  }
119  return mv;
120}
121
122// This task is run on a timer so that commits happen at regular intervals
123// so they are batched together. The important thing about this class is that
124// it supports canceling of the task so the reference to the backend will be
125// freed. The problem is that when history is shutting down, there is likely
126// to be one of these commits still pending and holding a reference.
127//
128// The backend can call Cancel to have this task release the reference. The
129// task will still run (if we ever get to processing the event before
130// shutdown), but it will not do anything.
131//
132// Note that this is a refcounted object and is not a task in itself. It should
133// be assigned to a RunnableMethod.
134//
135// TODO(brettw): bug 1165182: This should be replaced with a
136// base::WeakPtrFactory which will handle everything automatically (like we do
137// in ExpireHistoryBackend).
138class CommitLaterTask : public base::RefCounted<CommitLaterTask> {
139 public:
140  explicit CommitLaterTask(HistoryBackend* history_backend)
141      : history_backend_(history_backend) {
142  }
143
144  // The backend will call this function if it is being destroyed so that we
145  // release our reference.
146  void Cancel() {
147    history_backend_ = NULL;
148  }
149
150  void RunCommit() {
151    if (history_backend_.get())
152      history_backend_->Commit();
153  }
154
155 private:
156  friend class base::RefCounted<CommitLaterTask>;
157
158  ~CommitLaterTask() {}
159
160  scoped_refptr<HistoryBackend> history_backend_;
161};
162
163// HistoryBackend --------------------------------------------------------------
164
165HistoryBackend::HistoryBackend(const base::FilePath& history_dir,
166                               int id,
167                               Delegate* delegate,
168                               BookmarkService* bookmark_service)
169    : delegate_(delegate),
170      id_(id),
171      history_dir_(history_dir),
172      scheduled_kill_db_(false),
173      expirer_(this, bookmark_service),
174      recent_redirects_(kMaxRedirectCount),
175      backend_destroy_message_loop_(NULL),
176      segment_queried_(false),
177      bookmark_service_(bookmark_service) {
178}
179
180HistoryBackend::~HistoryBackend() {
181  DCHECK(!scheduled_commit_.get()) << "Deleting without cleanup";
182  ReleaseDBTasks();
183
184#if defined(OS_ANDROID)
185  // Release AndroidProviderBackend before other objects.
186  android_provider_backend_.reset();
187#endif
188
189  // First close the databases before optionally running the "destroy" task.
190  CloseAllDatabases();
191
192  if (!backend_destroy_task_.is_null()) {
193    // Notify an interested party (typically a unit test) that we're done.
194    DCHECK(backend_destroy_message_loop_);
195    backend_destroy_message_loop_->PostTask(FROM_HERE, backend_destroy_task_);
196  }
197
198#if defined(OS_ANDROID)
199  sql::Connection::Delete(GetAndroidCacheFileName());
200#endif
201}
202
203void HistoryBackend::Init(const std::string& languages, bool force_fail) {
204  if (!force_fail)
205    InitImpl(languages);
206  delegate_->DBLoaded(id_);
207  typed_url_syncable_service_.reset(new TypedUrlSyncableService(this));
208  memory_pressure_listener_.reset(new base::MemoryPressureListener(
209      base::Bind(&HistoryBackend::OnMemoryPressure, base::Unretained(this))));
210#if defined(OS_ANDROID)
211  PopulateMostVisitedURLMap();
212#endif
213}
214
215void HistoryBackend::SetOnBackendDestroyTask(base::MessageLoop* message_loop,
216                                             const base::Closure& task) {
217  if (!backend_destroy_task_.is_null())
218    DLOG(WARNING) << "Setting more than one destroy task, overriding";
219  backend_destroy_message_loop_ = message_loop;
220  backend_destroy_task_ = task;
221}
222
223void HistoryBackend::Closing() {
224  // Any scheduled commit will have a reference to us, we must make it
225  // release that reference before we can be destroyed.
226  CancelScheduledCommit();
227
228  // Release our reference to the delegate, this reference will be keeping the
229  // history service alive.
230  delegate_.reset();
231}
232
233void HistoryBackend::NotifyRenderProcessHostDestruction(const void* host) {
234  tracker_.NotifyRenderProcessHostDestruction(host);
235}
236
237base::FilePath HistoryBackend::GetThumbnailFileName() const {
238  return history_dir_.Append(chrome::kThumbnailsFilename);
239}
240
241base::FilePath HistoryBackend::GetFaviconsFileName() const {
242  return history_dir_.Append(chrome::kFaviconsFilename);
243}
244
245base::FilePath HistoryBackend::GetArchivedFileName() const {
246  return history_dir_.Append(chrome::kArchivedHistoryFilename);
247}
248
249#if defined(OS_ANDROID)
250base::FilePath HistoryBackend::GetAndroidCacheFileName() const {
251  return history_dir_.Append(chrome::kAndroidCacheFilename);
252}
253#endif
254
255SegmentID HistoryBackend::GetLastSegmentID(VisitID from_visit) {
256  // Set is used to detect referrer loops.  Should not happen, but can
257  // if the database is corrupt.
258  std::set<VisitID> visit_set;
259  VisitID visit_id = from_visit;
260  while (visit_id) {
261    VisitRow row;
262    if (!db_->GetRowForVisit(visit_id, &row))
263      return 0;
264    if (row.segment_id)
265      return row.segment_id;  // Found a visit in this change with a segment.
266
267    // Check the referrer of this visit, if any.
268    visit_id = row.referring_visit;
269
270    if (visit_set.find(visit_id) != visit_set.end()) {
271      NOTREACHED() << "Loop in referer chain, giving up";
272      break;
273    }
274    visit_set.insert(visit_id);
275  }
276  return 0;
277}
278
279SegmentID HistoryBackend::UpdateSegments(
280    const GURL& url,
281    VisitID from_visit,
282    VisitID visit_id,
283    content::PageTransition transition_type,
284    const Time ts) {
285  if (!db_)
286    return 0;
287
288  // We only consider main frames.
289  if (!content::PageTransitionIsMainFrame(transition_type))
290    return 0;
291
292  SegmentID segment_id = 0;
293  content::PageTransition t =
294      content::PageTransitionStripQualifier(transition_type);
295
296  // Are we at the beginning of a new segment?
297  // Note that navigating to an existing entry (with back/forward) reuses the
298  // same transition type.  We are not adding it as a new segment in that case
299  // because if this was the target of a redirect, we might end up with
300  // 2 entries for the same final URL. Ex: User types google.net, gets
301  // redirected to google.com. A segment is created for google.net. On
302  // google.com users navigates through a link, then press back. That last
303  // navigation is for the entry google.com transition typed. We end up adding
304  // a segment for that one as well. So we end up with google.net and google.com
305  // in the segment table, showing as 2 entries in the NTP.
306  // Note also that we should still be updating the visit count for that segment
307  // which we are not doing now. It should be addressed when
308  // http://crbug.com/96860 is fixed.
309  if ((t == content::PAGE_TRANSITION_TYPED ||
310       t == content::PAGE_TRANSITION_AUTO_BOOKMARK) &&
311      (transition_type & content::PAGE_TRANSITION_FORWARD_BACK) == 0) {
312    // If so, create or get the segment.
313    std::string segment_name = db_->ComputeSegmentName(url);
314    URLID url_id = db_->GetRowForURL(url, NULL);
315    if (!url_id)
316      return 0;
317
318    if (!(segment_id = db_->GetSegmentNamed(segment_name))) {
319      if (!(segment_id = db_->CreateSegment(url_id, segment_name))) {
320        NOTREACHED();
321        return 0;
322      }
323    } else {
324      // Note: if we update an existing segment, we update the url used to
325      // represent that segment in order to minimize stale most visited
326      // images.
327      db_->UpdateSegmentRepresentationURL(segment_id, url_id);
328    }
329  } else {
330    // Note: it is possible there is no segment ID set for this visit chain.
331    // This can happen if the initial navigation wasn't AUTO_BOOKMARK or
332    // TYPED. (For example GENERATED). In this case this visit doesn't count
333    // toward any segment.
334    if (!(segment_id = GetLastSegmentID(from_visit)))
335      return 0;
336  }
337
338  // Set the segment in the visit.
339  if (!db_->SetSegmentID(visit_id, segment_id)) {
340    NOTREACHED();
341    return 0;
342  }
343
344  // Finally, increase the counter for that segment / day.
345  if (!db_->IncreaseSegmentVisitCount(segment_id, ts, 1)) {
346    NOTREACHED();
347    return 0;
348  }
349  return segment_id;
350}
351
352void HistoryBackend::UpdateWithPageEndTime(const void* host,
353                                           int32 page_id,
354                                           const GURL& url,
355                                           Time end_ts) {
356  // Will be filled with the URL ID and the visit ID of the last addition.
357  VisitID visit_id = tracker_.GetLastVisit(host, page_id, url);
358  UpdateVisitDuration(visit_id, end_ts);
359}
360
361void HistoryBackend::UpdateVisitDuration(VisitID visit_id, const Time end_ts) {
362  if (!db_)
363    return;
364
365  // Get the starting visit_time for visit_id.
366  VisitRow visit_row;
367  if (db_->GetRowForVisit(visit_id, &visit_row)) {
368    // We should never have a negative duration time even when time is skewed.
369    visit_row.visit_duration = end_ts > visit_row.visit_time ?
370        end_ts - visit_row.visit_time : TimeDelta::FromMicroseconds(0);
371    db_->UpdateVisitRow(visit_row);
372  }
373}
374
375void HistoryBackend::AddPage(const HistoryAddPageArgs& request) {
376  if (!db_)
377    return;
378
379  // Will be filled with the URL ID and the visit ID of the last addition.
380  std::pair<URLID, VisitID> last_ids(0, tracker_.GetLastVisit(
381      request.id_scope, request.page_id, request.referrer));
382
383  VisitID from_visit_id = last_ids.second;
384
385  // If a redirect chain is given, we expect the last item in that chain to be
386  // the final URL.
387  DCHECK(request.redirects.empty() ||
388         request.redirects.back() == request.url);
389
390  // If the user is adding older history, we need to make sure our times
391  // are correct.
392  if (request.time < first_recorded_time_)
393    first_recorded_time_ = request.time;
394
395  content::PageTransition request_transition = request.transition;
396  content::PageTransition stripped_transition =
397    content::PageTransitionStripQualifier(request_transition);
398  bool is_keyword_generated =
399      (stripped_transition == content::PAGE_TRANSITION_KEYWORD_GENERATED);
400
401  // If the user is navigating to a not-previously-typed intranet hostname,
402  // change the transition to TYPED so that the omnibox will learn that this is
403  // a known host.
404  bool has_redirects = request.redirects.size() > 1;
405  if (content::PageTransitionIsMainFrame(request_transition) &&
406      (stripped_transition != content::PAGE_TRANSITION_TYPED) &&
407      !is_keyword_generated) {
408    const GURL& origin_url(has_redirects ?
409        request.redirects[0] : request.url);
410    if (origin_url.SchemeIs(content::kHttpScheme) ||
411        origin_url.SchemeIs(content::kHttpsScheme) ||
412        origin_url.SchemeIs(content::kFtpScheme)) {
413      std::string host(origin_url.host());
414      size_t registry_length =
415          net::registry_controlled_domains::GetRegistryLength(
416              host,
417              net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
418              net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
419      if (registry_length == 0 && !db_->IsTypedHost(host)) {
420        stripped_transition = content::PAGE_TRANSITION_TYPED;
421        request_transition =
422            content::PageTransitionFromInt(
423                stripped_transition |
424                content::PageTransitionGetQualifier(request_transition));
425      }
426    }
427  }
428
429  if (!has_redirects) {
430    // The single entry is both a chain start and end.
431    content::PageTransition t = content::PageTransitionFromInt(
432        request_transition |
433        content::PAGE_TRANSITION_CHAIN_START |
434        content::PAGE_TRANSITION_CHAIN_END);
435
436    // No redirect case (one element means just the page itself).
437    last_ids = AddPageVisit(request.url, request.time,
438                            last_ids.second, t, request.visit_source);
439
440    // Update the segment for this visit. KEYWORD_GENERATED visits should not
441    // result in changing most visited, so we don't update segments (most
442    // visited db).
443    if (!is_keyword_generated) {
444      UpdateSegments(request.url, from_visit_id, last_ids.second, t,
445                     request.time);
446
447      // Update the referrer's duration.
448      UpdateVisitDuration(from_visit_id, request.time);
449    }
450  } else {
451    // Redirect case. Add the redirect chain.
452
453    content::PageTransition redirect_info =
454        content::PAGE_TRANSITION_CHAIN_START;
455
456    RedirectList redirects = request.redirects;
457    if (redirects[0].SchemeIs(chrome::kAboutScheme)) {
458      // When the redirect source + referrer is "about" we skip it. This
459      // happens when a page opens a new frame/window to about:blank and then
460      // script sets the URL to somewhere else (used to hide the referrer). It
461      // would be nice to keep all these redirects properly but we don't ever
462      // see the initial about:blank load, so we don't know where the
463      // subsequent client redirect came from.
464      //
465      // In this case, we just don't bother hooking up the source of the
466      // redirects, so we remove it.
467      redirects.erase(redirects.begin());
468    } else if (request_transition & content::PAGE_TRANSITION_CLIENT_REDIRECT) {
469      redirect_info = content::PAGE_TRANSITION_CLIENT_REDIRECT;
470      // The first entry in the redirect chain initiated a client redirect.
471      // We don't add this to the database since the referrer is already
472      // there, so we skip over it but change the transition type of the first
473      // transition to client redirect.
474      //
475      // The referrer is invalid when restoring a session that features an
476      // https tab that redirects to a different host or to http. In this
477      // case we don't need to reconnect the new redirect with the existing
478      // chain.
479      if (request.referrer.is_valid()) {
480        DCHECK(request.referrer == redirects[0]);
481        redirects.erase(redirects.begin());
482
483        // If the navigation entry for this visit has replaced that for the
484        // first visit, remove the CHAIN_END marker from the first visit. This
485        // can be called a lot, for example, the page cycler, and most of the
486        // time we won't have changed anything.
487        VisitRow visit_row;
488        if (request.did_replace_entry &&
489            db_->GetRowForVisit(last_ids.second, &visit_row) &&
490            visit_row.transition & content::PAGE_TRANSITION_CHAIN_END) {
491          visit_row.transition = content::PageTransitionFromInt(
492              visit_row.transition & ~content::PAGE_TRANSITION_CHAIN_END);
493          db_->UpdateVisitRow(visit_row);
494        }
495      }
496    }
497
498    for (size_t redirect_index = 0; redirect_index < redirects.size();
499         redirect_index++) {
500      content::PageTransition t =
501          content::PageTransitionFromInt(stripped_transition | redirect_info);
502
503      // If this is the last transition, add a CHAIN_END marker
504      if (redirect_index == (redirects.size() - 1)) {
505        t = content::PageTransitionFromInt(
506            t | content::PAGE_TRANSITION_CHAIN_END);
507      }
508
509      // Record all redirect visits with the same timestamp. We don't display
510      // them anyway, and if we ever decide to, we can reconstruct their order
511      // from the redirect chain.
512      last_ids = AddPageVisit(redirects[redirect_index],
513                              request.time, last_ids.second,
514                              t, request.visit_source);
515      if (t & content::PAGE_TRANSITION_CHAIN_START) {
516        // Update the segment for this visit.
517        UpdateSegments(redirects[redirect_index],
518                       from_visit_id, last_ids.second, t, request.time);
519
520        // Update the visit_details for this visit.
521        UpdateVisitDuration(from_visit_id, request.time);
522      }
523
524      // Subsequent transitions in the redirect list must all be server
525      // redirects.
526      redirect_info = content::PAGE_TRANSITION_SERVER_REDIRECT;
527    }
528
529    // Last, save this redirect chain for later so we can set titles & favicons
530    // on the redirected pages properly.
531    recent_redirects_.Put(request.url, redirects);
532  }
533
534  // TODO(brettw) bug 1140015: Add an "add page" notification so the history
535  // views can keep in sync.
536
537  // Add the last visit to the tracker so we can get outgoing transitions.
538  // TODO(evanm): Due to http://b/1194536 we lose the referrers of a subframe
539  // navigation anyway, so last_visit_id is always zero for them.  But adding
540  // them here confuses main frame history, so we skip them for now.
541  if (stripped_transition != content::PAGE_TRANSITION_AUTO_SUBFRAME &&
542      stripped_transition != content::PAGE_TRANSITION_MANUAL_SUBFRAME &&
543      !is_keyword_generated) {
544    tracker_.AddVisit(request.id_scope, request.page_id, request.url,
545                      last_ids.second);
546  }
547
548  ScheduleCommit();
549}
550
551void HistoryBackend::InitImpl(const std::string& languages) {
552  DCHECK(!db_) << "Initializing HistoryBackend twice";
553  // In the rare case where the db fails to initialize a dialog may get shown
554  // the blocks the caller, yet allows other messages through. For this reason
555  // we only set db_ to the created database if creation is successful. That
556  // way other methods won't do anything as db_ is still NULL.
557
558  TimeTicks beginning_time = TimeTicks::Now();
559
560  // Compute the file names.
561  base::FilePath history_name = history_dir_.Append(chrome::kHistoryFilename);
562  base::FilePath thumbnail_name = GetFaviconsFileName();
563  base::FilePath archived_name = GetArchivedFileName();
564
565  // Delete the old index database files which are no longer used.
566  DeleteFTSIndexDatabases();
567
568  // History database.
569  db_.reset(new HistoryDatabase());
570
571  // Unretained to avoid a ref loop with db_.
572  db_->set_error_callback(
573      base::Bind(&HistoryBackend::DatabaseErrorCallback,
574                 base::Unretained(this)));
575
576  sql::InitStatus status = db_->Init(history_name);
577  switch (status) {
578    case sql::INIT_OK:
579      break;
580    case sql::INIT_FAILURE: {
581      // A NULL db_ will cause all calls on this object to notice this error
582      // and to not continue. If the error callback scheduled killing the
583      // database, the task it posted has not executed yet. Try killing the
584      // database now before we close it.
585      bool kill_db = scheduled_kill_db_;
586      if (kill_db)
587        KillHistoryDatabase();
588      UMA_HISTOGRAM_BOOLEAN("History.AttemptedToFixProfileError", kill_db);
589      delegate_->NotifyProfileError(id_, status);
590      db_.reset();
591      return;
592    }
593    default:
594      NOTREACHED();
595  }
596
597  // Fill the in-memory database and send it back to the history service on the
598  // main thread.
599  InMemoryHistoryBackend* mem_backend = new InMemoryHistoryBackend;
600  if (mem_backend->Init(history_name, db_.get()))
601    delegate_->SetInMemoryBackend(id_, mem_backend);  // Takes ownership of
602                                                      // pointer.
603  else
604    delete mem_backend;  // Error case, run without the in-memory DB.
605  db_->BeginExclusiveMode();  // Must be after the mem backend read the data.
606
607  // Thumbnail database.
608  // TODO(shess): "thumbnail database" these days only stores
609  // favicons.  Thumbnails are stored in "top sites".  Consider
610  // renaming "thumbnail" references to "favicons" or something of the
611  // sort.
612  thumbnail_db_.reset(new ThumbnailDatabase());
613  if (thumbnail_db_->Init(thumbnail_name) != sql::INIT_OK) {
614    // Unlike the main database, we don't error out when the database is too
615    // new because this error is much less severe. Generally, this shouldn't
616    // happen since the thumbnail and main database versions should be in sync.
617    // We'll just continue without thumbnails & favicons in this case or any
618    // other error.
619    LOG(WARNING) << "Could not initialize the thumbnail database.";
620    thumbnail_db_.reset();
621  }
622
623  // Archived database.
624  if (db_->needs_version_17_migration()) {
625    // See needs_version_17_migration() decl for more. In this case, we want
626    // to delete the archived database and need to do so before we try to
627    // open the file. We can ignore any error (maybe the file doesn't exist).
628    sql::Connection::Delete(archived_name);
629  }
630  archived_db_.reset(new ArchivedDatabase());
631  if (!archived_db_->Init(archived_name)) {
632    LOG(WARNING) << "Could not initialize the archived database.";
633    archived_db_.reset();
634  }
635
636  // Generate the history and thumbnail database metrics only after performing
637  // any migration work.
638  if (base::RandInt(1, 100) == 50) {
639    // Only do this computation sometimes since it can be expensive.
640    db_->ComputeDatabaseMetrics(history_name);
641    if (thumbnail_db_)
642      thumbnail_db_->ComputeDatabaseMetrics();
643  }
644
645  // Tell the expiration module about all the nice databases we made. This must
646  // happen before db_->Init() is called since the callback ForceArchiveHistory
647  // may need to expire stuff.
648  //
649  // *sigh*, this can all be cleaned up when that migration code is removed.
650  // The main DB initialization should intuitively be first (not that it
651  // actually matters) and the expirer should be set last.
652  expirer_.SetDatabases(db_.get(), archived_db_.get(), thumbnail_db_.get());
653
654  // Open the long-running transaction.
655  db_->BeginTransaction();
656  if (thumbnail_db_)
657    thumbnail_db_->BeginTransaction();
658  if (archived_db_)
659    archived_db_->BeginTransaction();
660
661  // Get the first item in our database.
662  db_->GetStartDate(&first_recorded_time_);
663
664  // Start expiring old stuff.
665  expirer_.StartArchivingOldStuff(TimeDelta::FromDays(kArchiveDaysThreshold));
666
667#if defined(OS_ANDROID)
668  if (thumbnail_db_) {
669    android_provider_backend_.reset(new AndroidProviderBackend(
670        GetAndroidCacheFileName(), db_.get(), thumbnail_db_.get(),
671        bookmark_service_, delegate_.get()));
672  }
673#endif
674
675  HISTOGRAM_TIMES("History.InitTime",
676                  TimeTicks::Now() - beginning_time);
677}
678
679void HistoryBackend::OnMemoryPressure(
680    base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
681  bool trim_aggressively = memory_pressure_level ==
682      base::MemoryPressureListener::MEMORY_PRESSURE_CRITICAL;
683  if (db_)
684    db_->TrimMemory(trim_aggressively);
685  if (thumbnail_db_)
686    thumbnail_db_->TrimMemory(trim_aggressively);
687  if (archived_db_)
688    archived_db_->TrimMemory(trim_aggressively);
689}
690
691void HistoryBackend::CloseAllDatabases() {
692  if (db_) {
693    // Commit the long-running transaction.
694    db_->CommitTransaction();
695    db_.reset();
696    // Forget the first recorded time since the database is closed.
697    first_recorded_time_ = base::Time();
698  }
699  if (thumbnail_db_) {
700    thumbnail_db_->CommitTransaction();
701    thumbnail_db_.reset();
702  }
703  if (archived_db_) {
704    archived_db_->CommitTransaction();
705    archived_db_.reset();
706  }
707}
708
709std::pair<URLID, VisitID> HistoryBackend::AddPageVisit(
710    const GURL& url,
711    Time time,
712    VisitID referring_visit,
713    content::PageTransition transition,
714    VisitSource visit_source) {
715  // Top-level frame navigations are visible, everything else is hidden
716  bool new_hidden = !content::PageTransitionIsMainFrame(transition);
717
718  // NOTE: This code must stay in sync with
719  // ExpireHistoryBackend::ExpireURLsForVisits().
720  // TODO(pkasting): http://b/1148304 We shouldn't be marking so many URLs as
721  // typed, which would eliminate the need for this code.
722  int typed_increment = 0;
723  content::PageTransition transition_type =
724      content::PageTransitionStripQualifier(transition);
725  if ((transition_type == content::PAGE_TRANSITION_TYPED &&
726      !content::PageTransitionIsRedirect(transition)) ||
727      transition_type == content::PAGE_TRANSITION_KEYWORD_GENERATED)
728    typed_increment = 1;
729
730#if defined(OS_ANDROID)
731  // Only count the page visit if it came from user browsing and only count it
732  // once when cycling through a redirect chain.
733  if (visit_source == SOURCE_BROWSED &&
734      (transition & content::PAGE_TRANSITION_CHAIN_END) != 0) {
735    RecordTopPageVisitStats(url);
736  }
737#endif
738
739  // See if this URL is already in the DB.
740  URLRow url_info(url);
741  URLID url_id = db_->GetRowForURL(url, &url_info);
742  if (url_id) {
743    // Update of an existing row.
744    if (content::PageTransitionStripQualifier(transition) !=
745        content::PAGE_TRANSITION_RELOAD)
746      url_info.set_visit_count(url_info.visit_count() + 1);
747    if (typed_increment)
748      url_info.set_typed_count(url_info.typed_count() + typed_increment);
749    if (url_info.last_visit() < time)
750      url_info.set_last_visit(time);
751
752    // Only allow un-hiding of pages, never hiding.
753    if (!new_hidden)
754      url_info.set_hidden(false);
755
756    db_->UpdateURLRow(url_id, url_info);
757  } else {
758    // Addition of a new row.
759    url_info.set_visit_count(1);
760    url_info.set_typed_count(typed_increment);
761    url_info.set_last_visit(time);
762    url_info.set_hidden(new_hidden);
763
764    url_id = db_->AddURL(url_info);
765    if (!url_id) {
766      NOTREACHED() << "Adding URL failed.";
767      return std::make_pair(0, 0);
768    }
769    url_info.id_ = url_id;
770  }
771
772  // Add the visit with the time to the database.
773  VisitRow visit_info(url_id, time, referring_visit, transition, 0);
774  VisitID visit_id = db_->AddVisit(&visit_info, visit_source);
775  NotifyVisitObservers(visit_info);
776
777  if (visit_info.visit_time < first_recorded_time_)
778    first_recorded_time_ = visit_info.visit_time;
779
780  // Broadcast a notification of the visit.
781  if (visit_id) {
782    if (typed_url_syncable_service_.get())
783      typed_url_syncable_service_->OnUrlVisited(transition, &url_info);
784
785    URLVisitedDetails* details = new URLVisitedDetails;
786    details->transition = transition;
787    details->row = url_info;
788    // TODO(meelapshah) Disabled due to potential PageCycler regression.
789    // Re-enable this.
790    // GetMostRecentRedirectsTo(url, &details->redirects);
791    BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URL_VISITED, details);
792  } else {
793    VLOG(0) << "Failed to build visit insert statement:  "
794            << "url_id = " << url_id;
795  }
796
797  return std::make_pair(url_id, visit_id);
798}
799
800void HistoryBackend::AddPagesWithDetails(const URLRows& urls,
801                                         VisitSource visit_source) {
802  if (!db_)
803    return;
804
805  scoped_ptr<URLsModifiedDetails> modified(new URLsModifiedDetails);
806  for (URLRows::const_iterator i = urls.begin(); i != urls.end(); ++i) {
807    DCHECK(!i->last_visit().is_null());
808
809    // We will add to either the archived database or the main one depending on
810    // the date of the added visit.
811    URLDatabase* url_database;
812    VisitDatabase* visit_database;
813    if (IsExpiredVisitTime(i->last_visit())) {
814      if (!archived_db_)
815        return;  // No archived database to save it to, just forget this.
816      url_database = archived_db_.get();
817      visit_database = archived_db_.get();
818    } else {
819      url_database = db_.get();
820      visit_database = db_.get();
821    }
822
823    URLRow existing_url;
824    URLID url_id = url_database->GetRowForURL(i->url(), &existing_url);
825    if (!url_id) {
826      // Add the page if it doesn't exist.
827      url_id = url_database->AddURL(*i);
828      if (!url_id) {
829        NOTREACHED() << "Could not add row to DB";
830        return;
831      }
832
833      if (i->typed_count() > 0) {
834        modified->changed_urls.push_back(*i);
835        modified->changed_urls.back().set_id(url_id);  // *i likely has |id_| 0.
836      }
837    }
838
839    // Sync code manages the visits itself.
840    if (visit_source != SOURCE_SYNCED) {
841      // Make up a visit to correspond to the last visit to the page.
842      VisitRow visit_info(url_id, i->last_visit(), 0,
843                          content::PageTransitionFromInt(
844                              content::PAGE_TRANSITION_LINK |
845                              content::PAGE_TRANSITION_CHAIN_START |
846                              content::PAGE_TRANSITION_CHAIN_END), 0);
847      if (!visit_database->AddVisit(&visit_info, visit_source)) {
848        NOTREACHED() << "Adding visit failed.";
849        return;
850      }
851      NotifyVisitObservers(visit_info);
852
853      if (visit_info.visit_time < first_recorded_time_)
854        first_recorded_time_ = visit_info.visit_time;
855    }
856  }
857
858  if (typed_url_syncable_service_.get())
859    typed_url_syncable_service_->OnUrlsModified(&modified->changed_urls);
860
861  // Broadcast a notification for typed URLs that have been modified. This
862  // will be picked up by the in-memory URL database on the main thread.
863  //
864  // TODO(brettw) bug 1140015: Add an "add page" notification so the history
865  // views can keep in sync.
866  BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URLS_MODIFIED,
867                         modified.release());
868
869  ScheduleCommit();
870}
871
872bool HistoryBackend::IsExpiredVisitTime(const base::Time& time) {
873  return time < expirer_.GetCurrentArchiveTime();
874}
875
876void HistoryBackend::SetPageTitle(const GURL& url,
877                                  const base::string16& title) {
878  if (!db_)
879    return;
880
881  // Search for recent redirects which should get the same title. We make a
882  // dummy list containing the exact URL visited if there are no redirects so
883  // the processing below can be the same.
884  history::RedirectList dummy_list;
885  history::RedirectList* redirects;
886  RedirectCache::iterator iter = recent_redirects_.Get(url);
887  if (iter != recent_redirects_.end()) {
888    redirects = &iter->second;
889
890    // This redirect chain should have the destination URL as the last item.
891    DCHECK(!redirects->empty());
892    DCHECK(redirects->back() == url);
893  } else {
894    // No redirect chain stored, make up one containing the URL we want so we
895    // can use the same logic below.
896    dummy_list.push_back(url);
897    redirects = &dummy_list;
898  }
899
900  scoped_ptr<URLsModifiedDetails> details(new URLsModifiedDetails);
901  for (size_t i = 0; i < redirects->size(); i++) {
902    URLRow row;
903    URLID row_id = db_->GetRowForURL(redirects->at(i), &row);
904    if (row_id && row.title() != title) {
905      row.set_title(title);
906      db_->UpdateURLRow(row_id, row);
907      details->changed_urls.push_back(row);
908    }
909  }
910
911  // Broadcast notifications for any URLs that have changed. This will
912  // update the in-memory database and the InMemoryURLIndex.
913  if (!details->changed_urls.empty()) {
914    if (typed_url_syncable_service_.get())
915      typed_url_syncable_service_->OnUrlsModified(&details->changed_urls);
916    BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URLS_MODIFIED,
917                           details.release());
918    ScheduleCommit();
919  }
920}
921
922void HistoryBackend::AddPageNoVisitForBookmark(const GURL& url,
923                                               const base::string16& title) {
924  if (!db_)
925    return;
926
927  URLRow url_info(url);
928  URLID url_id = db_->GetRowForURL(url, &url_info);
929  if (url_id) {
930    // URL is already known, nothing to do.
931    return;
932  }
933
934  if (!title.empty()) {
935    url_info.set_title(title);
936  } else {
937    url_info.set_title(UTF8ToUTF16(url.spec()));
938  }
939
940  url_info.set_last_visit(Time::Now());
941  // Mark the page hidden. If the user types it in, it'll unhide.
942  url_info.set_hidden(true);
943
944  db_->AddURL(url_info);
945}
946
947void HistoryBackend::IterateURLs(
948    const scoped_refptr<visitedlink::VisitedLinkDelegate::URLEnumerator>&
949    iterator) {
950  if (db_) {
951    HistoryDatabase::URLEnumerator e;
952    if (db_->InitURLEnumeratorForEverything(&e)) {
953      URLRow info;
954      while (e.GetNextURL(&info)) {
955        iterator->OnURL(info.url());
956      }
957      iterator->OnComplete(true);  // Success.
958      return;
959    }
960  }
961  iterator->OnComplete(false);  // Failure.
962}
963
964bool HistoryBackend::GetAllTypedURLs(URLRows* urls) {
965  if (db_)
966    return db_->GetAllTypedUrls(urls);
967  return false;
968}
969
970bool HistoryBackend::GetVisitsForURL(URLID id, VisitVector* visits) {
971  if (db_)
972    return db_->GetVisitsForURL(id, visits);
973  return false;
974}
975
976bool HistoryBackend::GetMostRecentVisitsForURL(URLID id,
977                                               int max_visits,
978                                               VisitVector* visits) {
979  if (db_)
980    return db_->GetMostRecentVisitsForURL(id, max_visits, visits);
981  return false;
982}
983
984bool HistoryBackend::UpdateURL(URLID id, const history::URLRow& url) {
985  if (db_)
986    return db_->UpdateURLRow(id, url);
987  return false;
988}
989
990bool HistoryBackend::AddVisits(const GURL& url,
991                               const std::vector<VisitInfo>& visits,
992                               VisitSource visit_source) {
993  if (db_) {
994    for (std::vector<VisitInfo>::const_iterator visit = visits.begin();
995         visit != visits.end(); ++visit) {
996      if (!AddPageVisit(
997              url, visit->first, 0, visit->second, visit_source).first) {
998        return false;
999      }
1000    }
1001    ScheduleCommit();
1002    return true;
1003  }
1004  return false;
1005}
1006
1007bool HistoryBackend::RemoveVisits(const VisitVector& visits) {
1008  if (!db_)
1009    return false;
1010
1011  expirer_.ExpireVisits(visits);
1012  ScheduleCommit();
1013  return true;
1014}
1015
1016bool HistoryBackend::GetVisitsSource(const VisitVector& visits,
1017                                     VisitSourceMap* sources) {
1018  if (!db_)
1019    return false;
1020
1021  db_->GetVisitsSource(visits, sources);
1022  return true;
1023}
1024
1025bool HistoryBackend::GetURL(const GURL& url, history::URLRow* url_row) {
1026  if (db_)
1027    return db_->GetRowForURL(url, url_row) != 0;
1028  return false;
1029}
1030
1031void HistoryBackend::QueryURL(scoped_refptr<QueryURLRequest> request,
1032                              const GURL& url,
1033                              bool want_visits) {
1034  if (request->canceled())
1035    return;
1036
1037  bool success = false;
1038  URLRow* row = &request->value.a;
1039  VisitVector* visits = &request->value.b;
1040  if (db_) {
1041    if (db_->GetRowForURL(url, row)) {
1042      // Have a row.
1043      success = true;
1044
1045      // Optionally query the visits.
1046      if (want_visits)
1047        db_->GetVisitsForURL(row->id(), visits);
1048    }
1049  }
1050  request->ForwardResult(request->handle(), success, row, visits);
1051}
1052
1053TypedUrlSyncableService* HistoryBackend::GetTypedUrlSyncableService() const {
1054  return typed_url_syncable_service_.get();
1055}
1056
1057// Segment usage ---------------------------------------------------------------
1058
1059void HistoryBackend::DeleteOldSegmentData() {
1060  if (db_)
1061    db_->DeleteSegmentData(Time::Now() -
1062                           TimeDelta::FromDays(kSegmentDataRetention));
1063}
1064
1065void HistoryBackend::QuerySegmentUsage(
1066    scoped_refptr<QuerySegmentUsageRequest> request,
1067    const Time from_time,
1068    int max_result_count) {
1069  if (request->canceled())
1070    return;
1071
1072  if (db_) {
1073    db_->QuerySegmentUsage(from_time, max_result_count, &request->value.get());
1074
1075    // If this is the first time we query segments, invoke
1076    // DeleteOldSegmentData asynchronously. We do this to cleanup old
1077    // entries.
1078    if (!segment_queried_) {
1079      segment_queried_ = true;
1080      base::MessageLoop::current()->PostTask(
1081          FROM_HERE,
1082          base::Bind(&HistoryBackend::DeleteOldSegmentData, this));
1083    }
1084  }
1085  request->ForwardResult(request->handle(), &request->value.get());
1086}
1087
1088void HistoryBackend::IncreaseSegmentDuration(const GURL& url,
1089                                             base::Time time,
1090                                             base::TimeDelta delta) {
1091  if (!db_)
1092    return;
1093
1094  const std::string segment_name(VisitSegmentDatabase::ComputeSegmentName(url));
1095  SegmentID segment_id = db_->GetSegmentNamed(segment_name);
1096  if (!segment_id) {
1097    URLID url_id = db_->GetRowForURL(url, NULL);
1098    if (!url_id)
1099      return;
1100    segment_id = db_->CreateSegment(url_id, segment_name);
1101    if (!segment_id)
1102      return;
1103  }
1104  SegmentDurationID duration_id;
1105  base::TimeDelta total_delta;
1106  if (!db_->GetSegmentDuration(segment_id, time, &duration_id,
1107                               &total_delta)) {
1108    db_->CreateSegmentDuration(segment_id, time, delta);
1109    return;
1110  }
1111  total_delta += delta;
1112  db_->SetSegmentDuration(duration_id, total_delta);
1113}
1114
1115void HistoryBackend::QuerySegmentDuration(
1116    scoped_refptr<QuerySegmentUsageRequest> request,
1117    const base::Time from_time,
1118    int max_result_count) {
1119  if (request->canceled())
1120    return;
1121
1122  if (db_) {
1123    db_->QuerySegmentDuration(from_time, max_result_count,
1124                              &request->value.get());
1125  }
1126  request->ForwardResult(request->handle(), &request->value.get());
1127}
1128
1129// Keyword visits --------------------------------------------------------------
1130
1131void HistoryBackend::SetKeywordSearchTermsForURL(const GURL& url,
1132                                                 TemplateURLID keyword_id,
1133                                                 const base::string16& term) {
1134  if (!db_)
1135    return;
1136
1137  // Get the ID for this URL.
1138  URLID url_id = db_->GetRowForURL(url, NULL);
1139  if (!url_id) {
1140    // There is a small possibility the url was deleted before the keyword
1141    // was added. Ignore the request.
1142    return;
1143  }
1144
1145  db_->SetKeywordSearchTermsForURL(url_id, keyword_id, term);
1146
1147  BroadcastNotifications(
1148      chrome::NOTIFICATION_HISTORY_KEYWORD_SEARCH_TERM_UPDATED,
1149      new KeywordSearchUpdatedDetails(url, keyword_id, term));
1150  ScheduleCommit();
1151}
1152
1153void HistoryBackend::DeleteAllSearchTermsForKeyword(
1154    TemplateURLID keyword_id) {
1155  if (!db_)
1156    return;
1157
1158  db_->DeleteAllSearchTermsForKeyword(keyword_id);
1159  // TODO(sky): bug 1168470. Need to move from archive dbs too.
1160  ScheduleCommit();
1161}
1162
1163void HistoryBackend::GetMostRecentKeywordSearchTerms(
1164    scoped_refptr<GetMostRecentKeywordSearchTermsRequest> request,
1165    TemplateURLID keyword_id,
1166    const base::string16& prefix,
1167    int max_count) {
1168  if (request->canceled())
1169    return;
1170
1171  if (db_) {
1172    db_->GetMostRecentKeywordSearchTerms(keyword_id, prefix, max_count,
1173                                         &(request->value));
1174  }
1175  request->ForwardResult(request->handle(), &request->value);
1176}
1177
1178void HistoryBackend::DeleteKeywordSearchTermForURL(const GURL& url) {
1179  if (!db_)
1180    return;
1181
1182  URLID url_id = db_->GetRowForURL(url, NULL);
1183  if (!url_id)
1184    return;
1185  db_->DeleteKeywordSearchTermForURL(url_id);
1186
1187  BroadcastNotifications(
1188      chrome::NOTIFICATION_HISTORY_KEYWORD_SEARCH_TERM_DELETED,
1189      new KeywordSearchDeletedDetails(url));
1190  ScheduleCommit();
1191}
1192
1193// Downloads -------------------------------------------------------------------
1194
1195void HistoryBackend::GetNextDownloadId(uint32* next_id) {
1196  if (db_)
1197    db_->GetNextDownloadId(next_id);
1198}
1199
1200// Get all the download entries from the database.
1201void HistoryBackend::QueryDownloads(std::vector<DownloadRow>* rows) {
1202  if (db_)
1203    db_->QueryDownloads(rows);
1204}
1205
1206// Update a particular download entry.
1207void HistoryBackend::UpdateDownload(const history::DownloadRow& data) {
1208  if (!db_)
1209    return;
1210  db_->UpdateDownload(data);
1211  ScheduleCommit();
1212}
1213
1214void HistoryBackend::CreateDownload(const history::DownloadRow& history_info,
1215                                    bool* success) {
1216  if (!db_)
1217    return;
1218  *success = db_->CreateDownload(history_info);
1219  ScheduleCommit();
1220}
1221
1222void HistoryBackend::RemoveDownloads(const std::set<uint32>& ids) {
1223  if (!db_)
1224    return;
1225  size_t downloads_count_before = db_->CountDownloads();
1226  base::TimeTicks started_removing = base::TimeTicks::Now();
1227  // HistoryBackend uses a long-running Transaction that is committed
1228  // periodically, so this loop doesn't actually hit the disk too hard.
1229  for (std::set<uint32>::const_iterator it = ids.begin();
1230       it != ids.end(); ++it) {
1231    db_->RemoveDownload(*it);
1232  }
1233  ScheduleCommit();
1234  base::TimeTicks finished_removing = base::TimeTicks::Now();
1235  size_t downloads_count_after = db_->CountDownloads();
1236
1237  DCHECK_LE(downloads_count_after, downloads_count_before);
1238  if (downloads_count_after > downloads_count_before)
1239    return;
1240  size_t num_downloads_deleted = downloads_count_before - downloads_count_after;
1241  UMA_HISTOGRAM_COUNTS("Download.DatabaseRemoveDownloadsCount",
1242                        num_downloads_deleted);
1243  base::TimeDelta micros = (1000 * (finished_removing - started_removing));
1244  UMA_HISTOGRAM_TIMES("Download.DatabaseRemoveDownloadsTime", micros);
1245  if (num_downloads_deleted > 0) {
1246    UMA_HISTOGRAM_TIMES("Download.DatabaseRemoveDownloadsTimePerRecord",
1247                        (1000 * micros) / num_downloads_deleted);
1248  }
1249  DCHECK_GE(ids.size(), num_downloads_deleted);
1250  if (ids.size() < num_downloads_deleted)
1251    return;
1252  UMA_HISTOGRAM_COUNTS("Download.DatabaseRemoveDownloadsCountNotRemoved",
1253                        ids.size() - num_downloads_deleted);
1254}
1255
1256void HistoryBackend::QueryHistory(scoped_refptr<QueryHistoryRequest> request,
1257                                  const base::string16& text_query,
1258                                  const QueryOptions& options) {
1259  if (request->canceled())
1260    return;
1261
1262  TimeTicks beginning_time = TimeTicks::Now();
1263
1264  if (db_) {
1265    if (text_query.empty()) {
1266      // Basic history query for the main database.
1267      QueryHistoryBasic(db_.get(), db_.get(), options, &request->value);
1268
1269      // Now query the archived database. This is a bit tricky because we don't
1270      // want to query it if the queried time range isn't going to find anything
1271      // in it.
1272      // TODO(brettw) bug 1171036: do blimpie querying for the archived database
1273      // as well.
1274      // if (archived_db_.get() &&
1275      //     expirer_.GetCurrentArchiveTime() - TimeDelta::FromDays(7)) {
1276    } else {
1277      // Text history query.
1278      QueryHistoryText(db_.get(), db_.get(), text_query, options,
1279                       &request->value);
1280      if (archived_db_.get() &&
1281          expirer_.GetCurrentArchiveTime() >= options.begin_time) {
1282        QueryHistoryText(archived_db_.get(), archived_db_.get(), text_query,
1283                         options, &request->value);
1284      }
1285    }
1286  }
1287
1288  request->ForwardResult(request->handle(), &request->value);
1289
1290  UMA_HISTOGRAM_TIMES("History.QueryHistory",
1291                      TimeTicks::Now() - beginning_time);
1292}
1293
1294// Basic time-based querying of history.
1295void HistoryBackend::QueryHistoryBasic(URLDatabase* url_db,
1296                                       VisitDatabase* visit_db,
1297                                       const QueryOptions& options,
1298                                       QueryResults* result) {
1299  // First get all visits.
1300  VisitVector visits;
1301  bool has_more_results = visit_db->GetVisibleVisitsInRange(options, &visits);
1302  DCHECK(static_cast<int>(visits.size()) <= options.EffectiveMaxCount());
1303
1304  // Now add them and the URL rows to the results.
1305  URLResult url_result;
1306  for (size_t i = 0; i < visits.size(); i++) {
1307    const VisitRow visit = visits[i];
1308
1309    // Add a result row for this visit, get the URL info from the DB.
1310    if (!url_db->GetURLRow(visit.url_id, &url_result)) {
1311      VLOG(0) << "Failed to get id " << visit.url_id
1312              << " from history.urls.";
1313      continue;  // DB out of sync and URL doesn't exist, try to recover.
1314    }
1315
1316    if (!url_result.url().is_valid()) {
1317      VLOG(0) << "Got invalid URL from history.urls with id "
1318              << visit.url_id << ":  "
1319              << url_result.url().possibly_invalid_spec();
1320      continue;  // Don't report invalid URLs in case of corruption.
1321    }
1322
1323    // The archived database may be out of sync with respect to starring,
1324    // titles, last visit date, etc. Therefore, we query the main DB if the
1325    // current URL database is not the main one.
1326    if (url_db == db_.get()) {
1327      // Currently querying the archived DB, update with the main database to
1328      // catch any interesting stuff. This will update it if it exists in the
1329      // main DB, and do nothing otherwise.
1330      db_->GetRowForURL(url_result.url(), &url_result);
1331    }
1332
1333    url_result.set_visit_time(visit.visit_time);
1334
1335    // Set whether the visit was blocked for a managed user by looking at the
1336    // transition type.
1337    url_result.set_blocked_visit(
1338        (visit.transition & content::PAGE_TRANSITION_BLOCKED) != 0);
1339
1340    // We don't set any of the query-specific parts of the URLResult, since
1341    // snippets and stuff don't apply to basic querying.
1342    result->AppendURLBySwapping(&url_result);
1343  }
1344
1345  if (!has_more_results && options.begin_time <= first_recorded_time_)
1346    result->set_reached_beginning(true);
1347}
1348
1349// Text-based querying of history.
1350void HistoryBackend::QueryHistoryText(URLDatabase* url_db,
1351                                      VisitDatabase* visit_db,
1352                                      const base::string16& text_query,
1353                                      const QueryOptions& options,
1354                                      QueryResults* result) {
1355  URLRows text_matches;
1356  url_db->GetTextMatches(text_query, &text_matches);
1357
1358  std::vector<URLResult> matching_visits;
1359  VisitVector visits;    // Declare outside loop to prevent re-construction.
1360  for (size_t i = 0; i < text_matches.size(); i++) {
1361    const URLRow& text_match = text_matches[i];
1362    // Get all visits for given URL match.
1363    visit_db->GetVisibleVisitsForURL(text_match.id(), options, &visits);
1364    for (size_t j = 0; j < visits.size(); j++) {
1365      URLResult url_result(text_match);
1366      url_result.set_visit_time(visits[j].visit_time);
1367      matching_visits.push_back(url_result);
1368    }
1369  }
1370
1371  std::sort(matching_visits.begin(), matching_visits.end(),
1372            URLResult::CompareVisitTime);
1373
1374  size_t max_results = options.max_count == 0 ?
1375      std::numeric_limits<size_t>::max() : static_cast<int>(options.max_count);
1376  for (std::vector<URLResult>::iterator it = matching_visits.begin();
1377       it != matching_visits.end() && result->size() < max_results; ++it) {
1378    result->AppendURLBySwapping(&(*it));
1379  }
1380
1381  if (matching_visits.size() == result->size() &&
1382      options.begin_time <= first_recorded_time_)
1383    result->set_reached_beginning(true);
1384}
1385
1386// Frontend to GetMostRecentRedirectsFrom from the history thread.
1387void HistoryBackend::QueryRedirectsFrom(
1388    scoped_refptr<QueryRedirectsRequest> request,
1389    const GURL& url) {
1390  if (request->canceled())
1391    return;
1392  bool success = GetMostRecentRedirectsFrom(url, &request->value);
1393  request->ForwardResult(request->handle(), url, success, &request->value);
1394}
1395
1396void HistoryBackend::QueryRedirectsTo(
1397    scoped_refptr<QueryRedirectsRequest> request,
1398    const GURL& url) {
1399  if (request->canceled())
1400    return;
1401  bool success = GetMostRecentRedirectsTo(url, &request->value);
1402  request->ForwardResult(request->handle(), url, success, &request->value);
1403}
1404
1405void HistoryBackend::GetVisibleVisitCountToHost(
1406    scoped_refptr<GetVisibleVisitCountToHostRequest> request,
1407    const GURL& url) {
1408  if (request->canceled())
1409    return;
1410  int count = 0;
1411  Time first_visit;
1412  const bool success = db_.get() &&
1413      db_->GetVisibleVisitCountToHost(url, &count, &first_visit);
1414  request->ForwardResult(request->handle(), success, count, first_visit);
1415}
1416
1417void HistoryBackend::QueryTopURLsAndRedirects(
1418    scoped_refptr<QueryTopURLsAndRedirectsRequest> request,
1419    int result_count) {
1420  if (request->canceled())
1421    return;
1422
1423  if (!db_) {
1424    request->ForwardResult(request->handle(), false, NULL, NULL);
1425    return;
1426  }
1427
1428  std::vector<GURL>* top_urls = &request->value.a;
1429  history::RedirectMap* redirects = &request->value.b;
1430
1431  ScopedVector<PageUsageData> data;
1432  db_->QuerySegmentUsage(base::Time::Now() - base::TimeDelta::FromDays(90),
1433      result_count, &data.get());
1434
1435  for (size_t i = 0; i < data.size(); ++i) {
1436    top_urls->push_back(data[i]->GetURL());
1437    RefCountedVector<GURL>* list = new RefCountedVector<GURL>;
1438    GetMostRecentRedirectsFrom(top_urls->back(), &list->data);
1439    (*redirects)[top_urls->back()] = list;
1440  }
1441
1442  request->ForwardResult(request->handle(), true, top_urls, redirects);
1443}
1444
1445// Will replace QueryTopURLsAndRedirectsRequest.
1446void HistoryBackend::QueryMostVisitedURLs(
1447    scoped_refptr<QueryMostVisitedURLsRequest> request,
1448    int result_count,
1449    int days_back) {
1450  if (request->canceled())
1451    return;
1452
1453  if (!db_) {
1454    // No History Database - return an empty list.
1455    request->ForwardResult(request->handle(), MostVisitedURLList());
1456    return;
1457  }
1458
1459  MostVisitedURLList* result = &request->value;
1460  QueryMostVisitedURLsImpl(result_count, days_back, result);
1461  request->ForwardResult(request->handle(), *result);
1462}
1463
1464void HistoryBackend::QueryFilteredURLs(
1465      scoped_refptr<QueryFilteredURLsRequest> request,
1466      int result_count,
1467      const history::VisitFilter& filter,
1468      bool extended_info)  {
1469  if (request->canceled())
1470    return;
1471
1472  base::Time request_start = base::Time::Now();
1473
1474  if (!db_) {
1475    // No History Database - return an empty list.
1476    request->ForwardResult(request->handle(), FilteredURLList());
1477    return;
1478  }
1479
1480  VisitVector visits;
1481  db_->GetDirectVisitsDuringTimes(filter, 0, &visits);
1482
1483  std::map<URLID, double> score_map;
1484  for (size_t i = 0; i < visits.size(); ++i) {
1485    score_map[visits[i].url_id] += filter.GetVisitScore(visits[i]);
1486  }
1487
1488  // TODO(georgey): experiment with visit_segment database granularity (it is
1489  // currently 24 hours) to use it directly instead of using visits database,
1490  // which is considerably slower.
1491  ScopedVector<PageUsageData> data;
1492  data.reserve(score_map.size());
1493  for (std::map<URLID, double>::iterator it = score_map.begin();
1494       it != score_map.end(); ++it) {
1495    PageUsageData* pud = new PageUsageData(it->first);
1496    pud->SetScore(it->second);
1497    data.push_back(pud);
1498  }
1499
1500  // Limit to the top |result_count| results.
1501  std::sort(data.begin(), data.end(), PageUsageData::Predicate);
1502  if (result_count && implicit_cast<int>(data.size()) > result_count)
1503    data.resize(result_count);
1504
1505  for (size_t i = 0; i < data.size(); ++i) {
1506    URLRow info;
1507    if (db_->GetURLRow(data[i]->GetID(), &info)) {
1508      data[i]->SetURL(info.url());
1509      data[i]->SetTitle(info.title());
1510    }
1511  }
1512
1513  FilteredURLList& result = request->value;
1514  for (size_t i = 0; i < data.size(); ++i) {
1515    PageUsageData* current_data = data[i];
1516    FilteredURL url(*current_data);
1517
1518    if (extended_info) {
1519      VisitVector visits;
1520      db_->GetVisitsForURL(current_data->GetID(), &visits);
1521      if (visits.size() > 0) {
1522        url.extended_info.total_visits = visits.size();
1523        for (size_t i = 0; i < visits.size(); ++i) {
1524          url.extended_info.duration_opened +=
1525              visits[i].visit_duration.InSeconds();
1526          if (visits[i].visit_time > url.extended_info.last_visit_time) {
1527            url.extended_info.last_visit_time = visits[i].visit_time;
1528          }
1529        }
1530        // TODO(macourteau): implement the url.extended_info.visits stat.
1531      }
1532    }
1533    result.push_back(url);
1534  }
1535
1536  int delta_time = std::max(1, std::min(999,
1537      static_cast<int>((base::Time::Now() - request_start).InMilliseconds())));
1538  STATIC_HISTOGRAM_POINTER_BLOCK(
1539      "NewTabPage.SuggestedSitesLoadTime",
1540      Add(delta_time),
1541      base::LinearHistogram::FactoryGet("NewTabPage.SuggestedSitesLoadTime",
1542          1, 1000, 100, base::Histogram::kUmaTargetedHistogramFlag));
1543
1544  request->ForwardResult(request->handle(), result);
1545}
1546
1547void HistoryBackend::QueryMostVisitedURLsImpl(int result_count,
1548                                              int days_back,
1549                                              MostVisitedURLList* result) {
1550  if (!db_)
1551    return;
1552
1553  ScopedVector<PageUsageData> data;
1554  db_->QuerySegmentUsage(base::Time::Now() -
1555                         base::TimeDelta::FromDays(days_back),
1556                         result_count, &data.get());
1557
1558  for (size_t i = 0; i < data.size(); ++i) {
1559    PageUsageData* current_data = data[i];
1560    RedirectList redirects;
1561    GetMostRecentRedirectsFrom(current_data->GetURL(), &redirects);
1562    MostVisitedURL url = MakeMostVisitedURL(*current_data, redirects);
1563    result->push_back(url);
1564  }
1565}
1566
1567void HistoryBackend::GetRedirectsFromSpecificVisit(
1568    VisitID cur_visit, history::RedirectList* redirects) {
1569  // Follow any redirects from the given visit and add them to the list.
1570  // It *should* be impossible to get a circular chain here, but we check
1571  // just in case to avoid infinite loops.
1572  GURL cur_url;
1573  std::set<VisitID> visit_set;
1574  visit_set.insert(cur_visit);
1575  while (db_->GetRedirectFromVisit(cur_visit, &cur_visit, &cur_url)) {
1576    if (visit_set.find(cur_visit) != visit_set.end()) {
1577      NOTREACHED() << "Loop in visit chain, giving up";
1578      return;
1579    }
1580    visit_set.insert(cur_visit);
1581    redirects->push_back(cur_url);
1582  }
1583}
1584
1585void HistoryBackend::GetRedirectsToSpecificVisit(
1586    VisitID cur_visit,
1587    history::RedirectList* redirects) {
1588  // Follow redirects going to cur_visit. These are added to |redirects| in
1589  // the order they are found. If a redirect chain looks like A -> B -> C and
1590  // |cur_visit| = C, redirects will be {B, A} in that order.
1591  if (!db_)
1592    return;
1593
1594  GURL cur_url;
1595  std::set<VisitID> visit_set;
1596  visit_set.insert(cur_visit);
1597  while (db_->GetRedirectToVisit(cur_visit, &cur_visit, &cur_url)) {
1598    if (visit_set.find(cur_visit) != visit_set.end()) {
1599      NOTREACHED() << "Loop in visit chain, giving up";
1600      return;
1601    }
1602    visit_set.insert(cur_visit);
1603    redirects->push_back(cur_url);
1604  }
1605}
1606
1607bool HistoryBackend::GetMostRecentRedirectsFrom(
1608    const GURL& from_url,
1609    history::RedirectList* redirects) {
1610  redirects->clear();
1611  if (!db_)
1612    return false;
1613
1614  URLID from_url_id = db_->GetRowForURL(from_url, NULL);
1615  VisitID cur_visit = db_->GetMostRecentVisitForURL(from_url_id, NULL);
1616  if (!cur_visit)
1617    return false;  // No visits for URL.
1618
1619  GetRedirectsFromSpecificVisit(cur_visit, redirects);
1620  return true;
1621}
1622
1623bool HistoryBackend::GetMostRecentRedirectsTo(
1624    const GURL& to_url,
1625    history::RedirectList* redirects) {
1626  redirects->clear();
1627  if (!db_)
1628    return false;
1629
1630  URLID to_url_id = db_->GetRowForURL(to_url, NULL);
1631  VisitID cur_visit = db_->GetMostRecentVisitForURL(to_url_id, NULL);
1632  if (!cur_visit)
1633    return false;  // No visits for URL.
1634
1635  GetRedirectsToSpecificVisit(cur_visit, redirects);
1636  return true;
1637}
1638
1639void HistoryBackend::ScheduleAutocomplete(HistoryURLProvider* provider,
1640                                          HistoryURLProviderParams* params) {
1641  // ExecuteWithDB should handle the NULL database case.
1642  provider->ExecuteWithDB(this, db_.get(), params);
1643}
1644
1645void HistoryBackend::DeleteFTSIndexDatabases() {
1646  // Find files on disk matching the text databases file pattern so we can
1647  // quickly test for and delete them.
1648  base::FilePath::StringType filepattern =
1649      FILE_PATH_LITERAL("History Index *");
1650  base::FileEnumerator enumerator(
1651      history_dir_, false, base::FileEnumerator::FILES, filepattern);
1652  int num_databases_deleted = 0;
1653  base::FilePath current_file;
1654  while (!(current_file = enumerator.Next()).empty()) {
1655    if (sql::Connection::Delete(current_file))
1656      num_databases_deleted++;
1657  }
1658  UMA_HISTOGRAM_COUNTS("History.DeleteFTSIndexDatabases",
1659                       num_databases_deleted);
1660}
1661
1662void HistoryBackend::GetFavicons(
1663    const std::vector<GURL>& icon_urls,
1664    int icon_types,
1665    int desired_size_in_dip,
1666    const std::vector<ui::ScaleFactor>& desired_scale_factors,
1667    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1668  UpdateFaviconMappingsAndFetchImpl(NULL, icon_urls, icon_types,
1669                                    desired_size_in_dip, desired_scale_factors,
1670                                    bitmap_results);
1671}
1672
1673void HistoryBackend::GetLargestFaviconForURL(
1674      const GURL& page_url,
1675      const std::vector<int>& icon_types,
1676      int minimum_size_in_pixels,
1677      chrome::FaviconBitmapResult* favicon_bitmap_result) {
1678  DCHECK(favicon_bitmap_result);
1679
1680  if (!db_ || !thumbnail_db_)
1681    return;
1682
1683  TimeTicks beginning_time = TimeTicks::Now();
1684
1685  std::vector<IconMapping> icon_mappings;
1686  if (!thumbnail_db_->GetIconMappingsForPageURL(page_url, &icon_mappings) ||
1687      icon_mappings.empty())
1688    return;
1689
1690  int required_icon_types = 0;
1691  for (std::vector<int>::const_iterator i = icon_types.begin();
1692       i != icon_types.end(); ++i) {
1693    required_icon_types |= *i;
1694  }
1695
1696  // Find the largest bitmap for each IconType placing in
1697  // |largest_favicon_bitmaps|.
1698  std::map<chrome::IconType, FaviconBitmap> largest_favicon_bitmaps;
1699  for (std::vector<IconMapping>::const_iterator i = icon_mappings.begin();
1700       i != icon_mappings.end(); ++i) {
1701    if (!(i->icon_type & required_icon_types))
1702      continue;
1703    std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
1704    thumbnail_db_->GetFaviconBitmapIDSizes(i->icon_id, &bitmap_id_sizes);
1705    FaviconBitmap& largest = largest_favicon_bitmaps[i->icon_type];
1706    for (std::vector<FaviconBitmapIDSize>::const_iterator j =
1707             bitmap_id_sizes.begin(); j != bitmap_id_sizes.end(); ++j) {
1708      if (largest.bitmap_id == 0 ||
1709          (largest.pixel_size.width() < j->pixel_size.width() &&
1710           largest.pixel_size.height() < j->pixel_size.height())) {
1711        largest.icon_id = i->icon_id;
1712        largest.bitmap_id = j->bitmap_id;
1713        largest.pixel_size = j->pixel_size;
1714      }
1715    }
1716  }
1717  if (largest_favicon_bitmaps.empty())
1718    return;
1719
1720  // Find an icon which is larger than minimum_size_in_pixels in the order of
1721  // icon_types.
1722  FaviconBitmap largest_icon;
1723  for (std::vector<int>::const_iterator t = icon_types.begin();
1724       t != icon_types.end(); ++t) {
1725    for (std::map<chrome::IconType, FaviconBitmap>::const_iterator f =
1726            largest_favicon_bitmaps.begin(); f != largest_favicon_bitmaps.end();
1727        ++f) {
1728      if (f->first & *t &&
1729          (largest_icon.bitmap_id == 0 ||
1730           (largest_icon.pixel_size.height() < f->second.pixel_size.height() &&
1731            largest_icon.pixel_size.width() < f->second.pixel_size.width()))) {
1732        largest_icon = f->second;
1733      }
1734    }
1735    if (largest_icon.pixel_size.width() > minimum_size_in_pixels &&
1736        largest_icon.pixel_size.height() > minimum_size_in_pixels)
1737      break;
1738  }
1739
1740  GURL icon_url;
1741  chrome::IconType icon_type;
1742  if (!thumbnail_db_->GetFaviconHeader(largest_icon.icon_id, &icon_url,
1743                                       &icon_type)) {
1744    return;
1745  }
1746
1747  base::Time last_updated;
1748  chrome::FaviconBitmapResult bitmap_result;
1749  bitmap_result.icon_url = icon_url;
1750  bitmap_result.icon_type = icon_type;
1751  if (!thumbnail_db_->GetFaviconBitmap(largest_icon.bitmap_id,
1752                                       &last_updated,
1753                                       &bitmap_result.bitmap_data,
1754                                       &bitmap_result.pixel_size)) {
1755    return;
1756  }
1757
1758  bitmap_result.expired = (Time::Now() - last_updated) >
1759      TimeDelta::FromDays(kFaviconRefetchDays);
1760  if (bitmap_result.is_valid())
1761    *favicon_bitmap_result = bitmap_result;
1762
1763  HISTOGRAM_TIMES("History.GetLargestFaviconForURL",
1764                  TimeTicks::Now() - beginning_time);
1765}
1766
1767void HistoryBackend::GetFaviconsForURL(
1768    const GURL& page_url,
1769    int icon_types,
1770    int desired_size_in_dip,
1771    const std::vector<ui::ScaleFactor>& desired_scale_factors,
1772    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1773  DCHECK(bitmap_results);
1774  GetFaviconsFromDB(page_url, icon_types, desired_size_in_dip,
1775                    desired_scale_factors, bitmap_results);
1776}
1777
1778void HistoryBackend::GetFaviconForID(
1779    chrome::FaviconID favicon_id,
1780    int desired_size_in_dip,
1781    ui::ScaleFactor desired_scale_factor,
1782    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1783  std::vector<chrome::FaviconID> favicon_ids;
1784  favicon_ids.push_back(favicon_id);
1785  std::vector<ui::ScaleFactor> desired_scale_factors;
1786  desired_scale_factors.push_back(desired_scale_factor);
1787
1788  // Get results from DB.
1789  GetFaviconBitmapResultsForBestMatch(favicon_ids,
1790                                      desired_size_in_dip,
1791                                      desired_scale_factors,
1792                                      bitmap_results);
1793}
1794
1795void HistoryBackend::UpdateFaviconMappingsAndFetch(
1796    const GURL& page_url,
1797    const std::vector<GURL>& icon_urls,
1798    int icon_types,
1799    int desired_size_in_dip,
1800    const std::vector<ui::ScaleFactor>& desired_scale_factors,
1801    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1802  UpdateFaviconMappingsAndFetchImpl(&page_url, icon_urls, icon_types,
1803                                    desired_size_in_dip, desired_scale_factors,
1804                                    bitmap_results);
1805}
1806
1807void HistoryBackend::MergeFavicon(
1808    const GURL& page_url,
1809    const GURL& icon_url,
1810    chrome::IconType icon_type,
1811    scoped_refptr<base::RefCountedMemory> bitmap_data,
1812    const gfx::Size& pixel_size) {
1813  if (!thumbnail_db_ || !db_)
1814    return;
1815
1816  chrome::FaviconID favicon_id =
1817      thumbnail_db_->GetFaviconIDForFaviconURL(icon_url, icon_type, NULL);
1818
1819  if (!favicon_id) {
1820    // There is no favicon at |icon_url|, create it.
1821    favicon_id = thumbnail_db_->AddFavicon(icon_url, icon_type);
1822  }
1823
1824  std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
1825  thumbnail_db_->GetFaviconBitmapIDSizes(favicon_id, &bitmap_id_sizes);
1826
1827  // If there is already a favicon bitmap of |pixel_size| at |icon_url|,
1828  // replace it.
1829  bool bitmap_identical = false;
1830  bool replaced_bitmap = false;
1831  for (size_t i = 0; i < bitmap_id_sizes.size(); ++i) {
1832    if (bitmap_id_sizes[i].pixel_size == pixel_size) {
1833      if (IsFaviconBitmapDataEqual(bitmap_id_sizes[i].bitmap_id, bitmap_data)) {
1834        thumbnail_db_->SetFaviconBitmapLastUpdateTime(
1835            bitmap_id_sizes[i].bitmap_id, base::Time::Now());
1836        bitmap_identical = true;
1837      } else {
1838        thumbnail_db_->SetFaviconBitmap(bitmap_id_sizes[i].bitmap_id,
1839            bitmap_data, base::Time::Now());
1840        replaced_bitmap = true;
1841      }
1842      break;
1843    }
1844  }
1845
1846  // Create a vector of the pixel sizes of the favicon bitmaps currently at
1847  // |icon_url|.
1848  std::vector<gfx::Size> favicon_sizes;
1849  for (size_t i = 0; i < bitmap_id_sizes.size(); ++i)
1850    favicon_sizes.push_back(bitmap_id_sizes[i].pixel_size);
1851
1852  if (!replaced_bitmap && !bitmap_identical) {
1853    // Set the preexisting favicon bitmaps as expired as the preexisting favicon
1854    // bitmaps are not consistent with the merged in data.
1855    thumbnail_db_->SetFaviconOutOfDate(favicon_id);
1856
1857    // Delete an arbitrary favicon bitmap to avoid going over the limit of
1858    // |kMaxFaviconBitmapsPerIconURL|.
1859    if (bitmap_id_sizes.size() >= kMaxFaviconBitmapsPerIconURL) {
1860      thumbnail_db_->DeleteFaviconBitmap(bitmap_id_sizes[0].bitmap_id);
1861      favicon_sizes.erase(favicon_sizes.begin());
1862    }
1863    thumbnail_db_->AddFaviconBitmap(favicon_id, bitmap_data, base::Time::Now(),
1864                                    pixel_size);
1865    favicon_sizes.push_back(pixel_size);
1866  }
1867
1868  // A site may have changed the favicons that it uses for |page_url|.
1869  // Example Scenario:
1870  //   page_url = news.google.com
1871  //   Initial State: www.google.com/favicon.ico 16x16, 32x32
1872  //   MergeFavicon(news.google.com, news.google.com/news_specific.ico, ...,
1873  //                ..., 16x16)
1874  //
1875  // Difficulties:
1876  // 1. Sync requires that a call to GetFaviconsForURL() returns the
1877  //    |bitmap_data| passed into MergeFavicon().
1878  //    - It is invalid for the 16x16 bitmap for www.google.com/favicon.ico to
1879  //      stay mapped to news.google.com because it would be unclear which 16x16
1880  //      bitmap should be returned via GetFaviconsForURL().
1881  //
1882  // 2. www.google.com/favicon.ico may be mapped to more than just
1883  //    news.google.com (eg www.google.com).
1884  //    - The 16x16 bitmap cannot be deleted from www.google.com/favicon.ico
1885  //
1886  // To resolve these problems, we copy all of the favicon bitmaps previously
1887  // mapped to news.google.com (|page_url|) and add them to the favicon at
1888  // news.google.com/news_specific.ico (|icon_url|). The favicon sizes for
1889  // |icon_url| are set to default to indicate that |icon_url| has incomplete
1890  // / incorrect data.
1891  // Difficulty 1: All but news.google.com/news_specific.ico are unmapped from
1892  //              news.google.com
1893  // Difficulty 2: The favicon bitmaps for www.google.com/favicon.ico are not
1894  //               modified.
1895
1896  std::vector<IconMapping> icon_mappings;
1897  thumbnail_db_->GetIconMappingsForPageURL(page_url, icon_type, &icon_mappings);
1898
1899  // Copy the favicon bitmaps mapped to |page_url| to the favicon at |icon_url|
1900  // till the limit of |kMaxFaviconBitmapsPerIconURL| is reached.
1901  for (size_t i = 0; i < icon_mappings.size(); ++i) {
1902    if (favicon_sizes.size() >= kMaxFaviconBitmapsPerIconURL)
1903      break;
1904
1905    if (icon_mappings[i].icon_url == icon_url)
1906      continue;
1907
1908    std::vector<FaviconBitmap> bitmaps_to_copy;
1909    thumbnail_db_->GetFaviconBitmaps(icon_mappings[i].icon_id,
1910                                     &bitmaps_to_copy);
1911    for (size_t j = 0; j < bitmaps_to_copy.size(); ++j) {
1912      // Do not add a favicon bitmap at a pixel size for which there is already
1913      // a favicon bitmap mapped to |icon_url|. The one there is more correct
1914      // and having multiple equally sized favicon bitmaps for |page_url| is
1915      // ambiguous in terms of GetFaviconsForURL().
1916      std::vector<gfx::Size>::iterator it = std::find(favicon_sizes.begin(),
1917          favicon_sizes.end(), bitmaps_to_copy[j].pixel_size);
1918      if (it != favicon_sizes.end())
1919        continue;
1920
1921      // Add the favicon bitmap as expired as it is not consistent with the
1922      // merged in data.
1923      thumbnail_db_->AddFaviconBitmap(favicon_id,
1924          bitmaps_to_copy[j].bitmap_data, base::Time(),
1925          bitmaps_to_copy[j].pixel_size);
1926      favicon_sizes.push_back(bitmaps_to_copy[j].pixel_size);
1927
1928      if (favicon_sizes.size() >= kMaxFaviconBitmapsPerIconURL)
1929        break;
1930    }
1931  }
1932
1933  // Update the favicon mappings such that only |icon_url| is mapped to
1934  // |page_url|.
1935  bool mapping_changed = false;
1936  if (icon_mappings.size() != 1 || icon_mappings[0].icon_url != icon_url) {
1937    std::vector<chrome::FaviconID> favicon_ids;
1938    favicon_ids.push_back(favicon_id);
1939    SetFaviconMappingsForPageAndRedirects(page_url, icon_type, favicon_ids);
1940    mapping_changed = true;
1941  }
1942
1943  if (mapping_changed || !bitmap_identical)
1944    SendFaviconChangedNotificationForPageAndRedirects(page_url);
1945  ScheduleCommit();
1946}
1947
1948void HistoryBackend::SetFavicons(
1949    const GURL& page_url,
1950    chrome::IconType icon_type,
1951    const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data) {
1952  if (!thumbnail_db_ || !db_)
1953    return;
1954
1955  DCHECK(ValidateSetFaviconsParams(favicon_bitmap_data));
1956
1957  // Build map of FaviconBitmapData for each icon url.
1958  typedef std::map<GURL, std::vector<chrome::FaviconBitmapData> >
1959      BitmapDataByIconURL;
1960  BitmapDataByIconURL grouped_by_icon_url;
1961  for (size_t i = 0; i < favicon_bitmap_data.size(); ++i) {
1962    const GURL& icon_url = favicon_bitmap_data[i].icon_url;
1963    grouped_by_icon_url[icon_url].push_back(favicon_bitmap_data[i]);
1964  }
1965
1966  // Track whether the method modifies or creates any favicon bitmaps, favicons
1967  // or icon mappings.
1968  bool data_modified = false;
1969
1970  std::vector<chrome::FaviconID> icon_ids;
1971  for (BitmapDataByIconURL::const_iterator it = grouped_by_icon_url.begin();
1972       it != grouped_by_icon_url.end(); ++it) {
1973    const GURL& icon_url = it->first;
1974    chrome::FaviconID icon_id =
1975        thumbnail_db_->GetFaviconIDForFaviconURL(icon_url, icon_type, NULL);
1976
1977    if (!icon_id) {
1978      // TODO(pkotwicz): Remove the favicon sizes attribute from
1979      // ThumbnailDatabase::AddFavicon().
1980      icon_id = thumbnail_db_->AddFavicon(icon_url, icon_type);
1981      data_modified = true;
1982    }
1983    icon_ids.push_back(icon_id);
1984
1985    if (!data_modified)
1986      SetFaviconBitmaps(icon_id, it->second, &data_modified);
1987    else
1988      SetFaviconBitmaps(icon_id, it->second, NULL);
1989  }
1990
1991  data_modified |=
1992    SetFaviconMappingsForPageAndRedirects(page_url, icon_type, icon_ids);
1993
1994  if (data_modified) {
1995    // Send notification to the UI as an icon mapping, favicon, or favicon
1996    // bitmap was changed by this function.
1997    SendFaviconChangedNotificationForPageAndRedirects(page_url);
1998  }
1999  ScheduleCommit();
2000}
2001
2002void HistoryBackend::SetFaviconsOutOfDateForPage(const GURL& page_url) {
2003  std::vector<IconMapping> icon_mappings;
2004
2005  if (!thumbnail_db_ ||
2006      !thumbnail_db_->GetIconMappingsForPageURL(page_url,
2007                                                &icon_mappings))
2008    return;
2009
2010  for (std::vector<IconMapping>::iterator m = icon_mappings.begin();
2011       m != icon_mappings.end(); ++m) {
2012    thumbnail_db_->SetFaviconOutOfDate(m->icon_id);
2013  }
2014  ScheduleCommit();
2015}
2016
2017void HistoryBackend::CloneFavicons(const GURL& old_page_url,
2018                                   const GURL& new_page_url) {
2019  if (!thumbnail_db_)
2020    return;
2021
2022  // Prevent cross-domain cloning.
2023  if (old_page_url.GetOrigin() != new_page_url.GetOrigin())
2024    return;
2025
2026  thumbnail_db_->CloneIconMappings(old_page_url, new_page_url);
2027  ScheduleCommit();
2028}
2029
2030void HistoryBackend::SetImportedFavicons(
2031    const std::vector<ImportedFaviconUsage>& favicon_usage) {
2032  if (!db_ || !thumbnail_db_)
2033    return;
2034
2035  Time now = Time::Now();
2036
2037  // Track all URLs that had their favicons set or updated.
2038  std::set<GURL> favicons_changed;
2039
2040  for (size_t i = 0; i < favicon_usage.size(); i++) {
2041    chrome::FaviconID favicon_id = thumbnail_db_->GetFaviconIDForFaviconURL(
2042        favicon_usage[i].favicon_url, chrome::FAVICON, NULL);
2043    if (!favicon_id) {
2044      // This favicon doesn't exist yet, so we create it using the given data.
2045      // TODO(pkotwicz): Pass in real pixel size.
2046      favicon_id = thumbnail_db_->AddFavicon(
2047          favicon_usage[i].favicon_url,
2048          chrome::FAVICON,
2049          new base::RefCountedBytes(favicon_usage[i].png_data),
2050          now,
2051          gfx::Size());
2052    }
2053
2054    // Save the mapping from all the URLs to the favicon.
2055    BookmarkService* bookmark_service = GetBookmarkService();
2056    for (std::set<GURL>::const_iterator url = favicon_usage[i].urls.begin();
2057         url != favicon_usage[i].urls.end(); ++url) {
2058      URLRow url_row;
2059      if (!db_->GetRowForURL(*url, &url_row)) {
2060        // If the URL is present as a bookmark, add the url in history to
2061        // save the favicon mapping. This will match with what history db does
2062        // for regular bookmarked URLs with favicons - when history db is
2063        // cleaned, we keep an entry in the db with 0 visits as long as that
2064        // url is bookmarked.
2065        if (bookmark_service && bookmark_service_->IsBookmarked(*url)) {
2066          URLRow url_info(*url);
2067          url_info.set_visit_count(0);
2068          url_info.set_typed_count(0);
2069          url_info.set_last_visit(base::Time());
2070          url_info.set_hidden(false);
2071          db_->AddURL(url_info);
2072          thumbnail_db_->AddIconMapping(*url, favicon_id);
2073          favicons_changed.insert(*url);
2074        }
2075      } else {
2076        if (!thumbnail_db_->GetIconMappingsForPageURL(
2077                *url, chrome::FAVICON, NULL)) {
2078          // URL is present in history, update the favicon *only* if it is not
2079          // set already.
2080          thumbnail_db_->AddIconMapping(*url, favicon_id);
2081          favicons_changed.insert(*url);
2082        }
2083      }
2084    }
2085  }
2086
2087  if (!favicons_changed.empty()) {
2088    // Send the notification about the changed favicon URLs.
2089    FaviconChangedDetails* changed_details = new FaviconChangedDetails;
2090    changed_details->urls.swap(favicons_changed);
2091    BroadcastNotifications(chrome::NOTIFICATION_FAVICON_CHANGED,
2092                           changed_details);
2093  }
2094}
2095
2096void HistoryBackend::UpdateFaviconMappingsAndFetchImpl(
2097    const GURL* page_url,
2098    const std::vector<GURL>& icon_urls,
2099    int icon_types,
2100    int desired_size_in_dip,
2101    const std::vector<ui::ScaleFactor>& desired_scale_factors,
2102    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
2103  // If |page_url| is specified, |icon_types| must be either a single icon
2104  // type or icon types which are equivalent.
2105  DCHECK(!page_url ||
2106         icon_types == chrome::FAVICON ||
2107         icon_types == chrome::TOUCH_ICON ||
2108         icon_types == chrome::TOUCH_PRECOMPOSED_ICON ||
2109         icon_types == (chrome::TOUCH_ICON | chrome::TOUCH_PRECOMPOSED_ICON));
2110  bitmap_results->clear();
2111
2112  if (!thumbnail_db_) {
2113    return;
2114  }
2115
2116  std::vector<chrome::FaviconID> favicon_ids;
2117
2118  // The icon type for which the mappings will the updated and data will be
2119  // returned.
2120  chrome::IconType selected_icon_type = chrome::INVALID_ICON;
2121
2122  for (size_t i = 0; i < icon_urls.size(); ++i) {
2123    const GURL& icon_url = icon_urls[i];
2124    chrome::IconType icon_type_out;
2125    const chrome::FaviconID favicon_id =
2126        thumbnail_db_->GetFaviconIDForFaviconURL(
2127            icon_url, icon_types, &icon_type_out);
2128
2129    if (favicon_id) {
2130      // Return and update icon mappings only for the largest icon type. As
2131      // |icon_urls| is not sorted in terms of icon type, clear |favicon_ids|
2132      // if an |icon_url| with a larger icon type is found.
2133      if (icon_type_out > selected_icon_type) {
2134        selected_icon_type = icon_type_out;
2135        favicon_ids.clear();
2136      }
2137      if (icon_type_out == selected_icon_type)
2138        favicon_ids.push_back(favicon_id);
2139    }
2140  }
2141
2142  if (page_url && !favicon_ids.empty()) {
2143    bool mappings_updated =
2144        SetFaviconMappingsForPageAndRedirects(*page_url, selected_icon_type,
2145                                              favicon_ids);
2146    if (mappings_updated) {
2147      SendFaviconChangedNotificationForPageAndRedirects(*page_url);
2148      ScheduleCommit();
2149    }
2150  }
2151
2152  GetFaviconBitmapResultsForBestMatch(favicon_ids, desired_size_in_dip,
2153      desired_scale_factors, bitmap_results);
2154}
2155
2156void HistoryBackend::SetFaviconBitmaps(
2157    chrome::FaviconID icon_id,
2158    const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data,
2159    bool* favicon_bitmaps_changed) {
2160  if (favicon_bitmaps_changed)
2161    *favicon_bitmaps_changed = false;
2162
2163  std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
2164  thumbnail_db_->GetFaviconBitmapIDSizes(icon_id, &bitmap_id_sizes);
2165
2166  std::vector<chrome::FaviconBitmapData> to_add = favicon_bitmap_data;
2167
2168  for (size_t i = 0; i < bitmap_id_sizes.size(); ++i) {
2169    const gfx::Size& pixel_size = bitmap_id_sizes[i].pixel_size;
2170    std::vector<chrome::FaviconBitmapData>::iterator match_it = to_add.end();
2171    for (std::vector<chrome::FaviconBitmapData>::iterator it = to_add.begin();
2172         it != to_add.end(); ++it) {
2173      if (it->pixel_size == pixel_size) {
2174        match_it = it;
2175        break;
2176      }
2177    }
2178
2179    FaviconBitmapID bitmap_id = bitmap_id_sizes[i].bitmap_id;
2180    if (match_it == to_add.end()) {
2181      thumbnail_db_->DeleteFaviconBitmap(bitmap_id);
2182
2183      if (favicon_bitmaps_changed)
2184        *favicon_bitmaps_changed = true;
2185    } else {
2186      if (favicon_bitmaps_changed &&
2187          !*favicon_bitmaps_changed &&
2188          IsFaviconBitmapDataEqual(bitmap_id, match_it->bitmap_data)) {
2189        thumbnail_db_->SetFaviconBitmapLastUpdateTime(
2190            bitmap_id, base::Time::Now());
2191      } else {
2192        thumbnail_db_->SetFaviconBitmap(bitmap_id, match_it->bitmap_data,
2193            base::Time::Now());
2194
2195        if (favicon_bitmaps_changed)
2196          *favicon_bitmaps_changed = true;
2197      }
2198      to_add.erase(match_it);
2199    }
2200  }
2201
2202  for (size_t i = 0; i < to_add.size(); ++i) {
2203    thumbnail_db_->AddFaviconBitmap(icon_id, to_add[i].bitmap_data,
2204        base::Time::Now(), to_add[i].pixel_size);
2205
2206    if (favicon_bitmaps_changed)
2207      *favicon_bitmaps_changed = true;
2208  }
2209}
2210
2211bool HistoryBackend::ValidateSetFaviconsParams(
2212    const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data) const {
2213  typedef std::map<GURL, size_t> BitmapsPerIconURL;
2214  BitmapsPerIconURL num_bitmaps_per_icon_url;
2215  for (size_t i = 0; i < favicon_bitmap_data.size(); ++i) {
2216    if (!favicon_bitmap_data[i].bitmap_data.get())
2217      return false;
2218
2219    const GURL& icon_url = favicon_bitmap_data[i].icon_url;
2220    if (!num_bitmaps_per_icon_url.count(icon_url))
2221      num_bitmaps_per_icon_url[icon_url] = 1u;
2222    else
2223      ++num_bitmaps_per_icon_url[icon_url];
2224  }
2225
2226  if (num_bitmaps_per_icon_url.size() > kMaxFaviconsPerPage)
2227    return false;
2228
2229  for (BitmapsPerIconURL::const_iterator it = num_bitmaps_per_icon_url.begin();
2230       it != num_bitmaps_per_icon_url.end(); ++it) {
2231    if (it->second > kMaxFaviconBitmapsPerIconURL)
2232      return false;
2233  }
2234  return true;
2235}
2236
2237bool HistoryBackend::IsFaviconBitmapDataEqual(
2238    FaviconBitmapID bitmap_id,
2239    const scoped_refptr<base::RefCountedMemory>& new_bitmap_data) {
2240  if (!new_bitmap_data.get())
2241    return false;
2242
2243  scoped_refptr<base::RefCountedMemory> original_bitmap_data;
2244  thumbnail_db_->GetFaviconBitmap(bitmap_id,
2245                                  NULL,
2246                                  &original_bitmap_data,
2247                                  NULL);
2248  return new_bitmap_data->Equals(original_bitmap_data);
2249}
2250
2251bool HistoryBackend::GetFaviconsFromDB(
2252    const GURL& page_url,
2253    int icon_types,
2254    int desired_size_in_dip,
2255    const std::vector<ui::ScaleFactor>& desired_scale_factors,
2256    std::vector<chrome::FaviconBitmapResult>* favicon_bitmap_results) {
2257  DCHECK(favicon_bitmap_results);
2258  favicon_bitmap_results->clear();
2259
2260  if (!db_ || !thumbnail_db_)
2261    return false;
2262
2263  // Time the query.
2264  TimeTicks beginning_time = TimeTicks::Now();
2265
2266  // Get FaviconIDs for |page_url| and one of |icon_types|.
2267  std::vector<IconMapping> icon_mappings;
2268  thumbnail_db_->GetIconMappingsForPageURL(page_url, icon_types,
2269                                           &icon_mappings);
2270  std::vector<chrome::FaviconID> favicon_ids;
2271  for (size_t i = 0; i < icon_mappings.size(); ++i)
2272    favicon_ids.push_back(icon_mappings[i].icon_id);
2273
2274  // Populate |favicon_bitmap_results| and |icon_url_sizes|.
2275  bool success = GetFaviconBitmapResultsForBestMatch(favicon_ids,
2276      desired_size_in_dip, desired_scale_factors, favicon_bitmap_results);
2277  UMA_HISTOGRAM_TIMES("History.GetFavIconFromDB",  // historical name
2278                      TimeTicks::Now() - beginning_time);
2279  return success && !favicon_bitmap_results->empty();
2280}
2281
2282bool HistoryBackend::GetFaviconBitmapResultsForBestMatch(
2283    const std::vector<chrome::FaviconID>& candidate_favicon_ids,
2284    int desired_size_in_dip,
2285    const std::vector<ui::ScaleFactor>& desired_scale_factors,
2286    std::vector<chrome::FaviconBitmapResult>* favicon_bitmap_results) {
2287  favicon_bitmap_results->clear();
2288
2289  if (candidate_favicon_ids.empty())
2290    return true;
2291
2292  // Find the FaviconID and the FaviconBitmapIDs which best match
2293  // |desired_size_in_dip| and |desired_scale_factors|.
2294  // TODO(pkotwicz): Select bitmap results from multiple favicons once
2295  // content::FaviconStatus supports multiple icon URLs.
2296  chrome::FaviconID best_favicon_id = 0;
2297  std::vector<FaviconBitmapID> best_bitmap_ids;
2298  float highest_score = kSelectFaviconFramesInvalidScore;
2299  for (size_t i = 0; i < candidate_favicon_ids.size(); ++i) {
2300    std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
2301    thumbnail_db_->GetFaviconBitmapIDSizes(candidate_favicon_ids[i],
2302                                           &bitmap_id_sizes);
2303
2304    // Build vector of gfx::Size from |bitmap_id_sizes|.
2305    std::vector<gfx::Size> sizes;
2306    for (size_t j = 0; j < bitmap_id_sizes.size(); ++j)
2307      sizes.push_back(bitmap_id_sizes[j].pixel_size);
2308
2309    std::vector<size_t> candidate_bitmap_indices;
2310    float score = 0;
2311    SelectFaviconFrameIndices(sizes,
2312                              desired_scale_factors,
2313                              desired_size_in_dip,
2314                              &candidate_bitmap_indices,
2315                              &score);
2316    if (score > highest_score) {
2317      highest_score = score;
2318      best_favicon_id = candidate_favicon_ids[i],
2319      best_bitmap_ids.clear();
2320      for (size_t j = 0; j < candidate_bitmap_indices.size(); ++j) {
2321        size_t candidate_index = candidate_bitmap_indices[j];
2322        best_bitmap_ids.push_back(
2323            bitmap_id_sizes[candidate_index].bitmap_id);
2324      }
2325    }
2326  }
2327
2328  // Construct FaviconBitmapResults from |best_favicon_id| and
2329  // |best_bitmap_ids|.
2330  GURL icon_url;
2331  chrome::IconType icon_type;
2332  if (!thumbnail_db_->GetFaviconHeader(best_favicon_id, &icon_url,
2333                                       &icon_type)) {
2334    return false;
2335  }
2336
2337  for (size_t i = 0; i < best_bitmap_ids.size(); ++i) {
2338    base::Time last_updated;
2339    chrome::FaviconBitmapResult bitmap_result;
2340    bitmap_result.icon_url = icon_url;
2341    bitmap_result.icon_type = icon_type;
2342    if (!thumbnail_db_->GetFaviconBitmap(best_bitmap_ids[i],
2343                                         &last_updated,
2344                                         &bitmap_result.bitmap_data,
2345                                         &bitmap_result.pixel_size)) {
2346      return false;
2347    }
2348
2349    bitmap_result.expired = (Time::Now() - last_updated) >
2350        TimeDelta::FromDays(kFaviconRefetchDays);
2351    if (bitmap_result.is_valid())
2352      favicon_bitmap_results->push_back(bitmap_result);
2353  }
2354  return true;
2355}
2356
2357bool HistoryBackend::SetFaviconMappingsForPageAndRedirects(
2358    const GURL& page_url,
2359    chrome::IconType icon_type,
2360    const std::vector<chrome::FaviconID>& icon_ids) {
2361  if (!thumbnail_db_)
2362    return false;
2363
2364  // Find all the pages whose favicons we should set, we want to set it for
2365  // all the pages in the redirect chain if it redirected.
2366  history::RedirectList redirects;
2367  GetCachedRecentRedirects(page_url, &redirects);
2368
2369  bool mappings_changed = false;
2370
2371  // Save page <-> favicon associations.
2372  for (history::RedirectList::const_iterator i(redirects.begin());
2373       i != redirects.end(); ++i) {
2374    mappings_changed |= SetFaviconMappingsForPage(*i, icon_type, icon_ids);
2375  }
2376  return mappings_changed;
2377}
2378
2379bool HistoryBackend::SetFaviconMappingsForPage(
2380    const GURL& page_url,
2381    chrome::IconType icon_type,
2382    const std::vector<chrome::FaviconID>& icon_ids) {
2383  DCHECK_LE(icon_ids.size(), kMaxFaviconsPerPage);
2384  bool mappings_changed = false;
2385
2386  // Two icon types are considered 'equivalent' if one of the icon types is
2387  // TOUCH_ICON and the other is TOUCH_PRECOMPOSED_ICON.
2388  //
2389  // Sets the icon mappings from |page_url| for |icon_type| to the favicons
2390  // with |icon_ids|. Mappings for |page_url| to favicons of type |icon_type|
2391  // whose FaviconID is not in |icon_ids| are removed. All icon mappings for
2392  // |page_url| to favicons of a type equivalent to |icon_type| are removed.
2393  // Remove any favicons which are orphaned as a result of the removal of the
2394  // icon mappings.
2395
2396  std::vector<chrome::FaviconID> unmapped_icon_ids = icon_ids;
2397
2398  std::vector<IconMapping> icon_mappings;
2399  thumbnail_db_->GetIconMappingsForPageURL(page_url, &icon_mappings);
2400
2401  for (std::vector<IconMapping>::iterator m = icon_mappings.begin();
2402       m != icon_mappings.end(); ++m) {
2403    std::vector<chrome::FaviconID>::iterator icon_id_it = std::find(
2404        unmapped_icon_ids.begin(), unmapped_icon_ids.end(), m->icon_id);
2405
2406    // If the icon mapping already exists, avoid removing it and adding it back.
2407    if (icon_id_it != unmapped_icon_ids.end()) {
2408      unmapped_icon_ids.erase(icon_id_it);
2409      continue;
2410    }
2411
2412    if ((icon_type == chrome::TOUCH_ICON &&
2413         m->icon_type == chrome::TOUCH_PRECOMPOSED_ICON) ||
2414        (icon_type == chrome::TOUCH_PRECOMPOSED_ICON &&
2415         m->icon_type == chrome::TOUCH_ICON) || (icon_type == m->icon_type)) {
2416      thumbnail_db_->DeleteIconMapping(m->mapping_id);
2417
2418      // Removing the icon mapping may have orphaned the associated favicon so
2419      // we must recheck it. This is not super fast, but this case will get
2420      // triggered rarely, since normally a page will always map to the same
2421      // favicon IDs. It will mostly happen for favicons we import.
2422      if (!thumbnail_db_->HasMappingFor(m->icon_id))
2423        thumbnail_db_->DeleteFavicon(m->icon_id);
2424      mappings_changed = true;
2425    }
2426  }
2427
2428  for (size_t i = 0; i < unmapped_icon_ids.size(); ++i) {
2429    thumbnail_db_->AddIconMapping(page_url, unmapped_icon_ids[i]);
2430    mappings_changed = true;
2431  }
2432  return mappings_changed;
2433}
2434
2435void HistoryBackend::GetCachedRecentRedirects(
2436    const GURL& page_url,
2437    history::RedirectList* redirect_list) {
2438  RedirectCache::iterator iter = recent_redirects_.Get(page_url);
2439  if (iter != recent_redirects_.end()) {
2440    *redirect_list = iter->second;
2441
2442    // The redirect chain should have the destination URL as the last item.
2443    DCHECK(!redirect_list->empty());
2444    DCHECK(redirect_list->back() == page_url);
2445  } else {
2446    // No known redirects, construct mock redirect chain containing |page_url|.
2447    redirect_list->push_back(page_url);
2448  }
2449}
2450
2451void HistoryBackend::SendFaviconChangedNotificationForPageAndRedirects(
2452    const GURL& page_url) {
2453  history::RedirectList redirect_list;
2454  GetCachedRecentRedirects(page_url, &redirect_list);
2455
2456  FaviconChangedDetails* changed_details = new FaviconChangedDetails;
2457  for (size_t i = 0; i < redirect_list.size(); ++i)
2458    changed_details->urls.insert(redirect_list[i]);
2459
2460  BroadcastNotifications(chrome::NOTIFICATION_FAVICON_CHANGED,
2461                         changed_details);
2462}
2463
2464void HistoryBackend::Commit() {
2465  if (!db_)
2466    return;
2467
2468  // Note that a commit may not actually have been scheduled if a caller
2469  // explicitly calls this instead of using ScheduleCommit. Likewise, we
2470  // may reset the flag written by a pending commit. But this is OK! It
2471  // will merely cause extra commits (which is kind of the idea). We
2472  // could optimize more for this case (we may get two extra commits in
2473  // some cases) but it hasn't been important yet.
2474  CancelScheduledCommit();
2475
2476  db_->CommitTransaction();
2477  DCHECK(db_->transaction_nesting() == 0) << "Somebody left a transaction open";
2478  db_->BeginTransaction();
2479
2480  if (thumbnail_db_) {
2481    thumbnail_db_->CommitTransaction();
2482    DCHECK(thumbnail_db_->transaction_nesting() == 0) <<
2483        "Somebody left a transaction open";
2484    thumbnail_db_->BeginTransaction();
2485  }
2486
2487  if (archived_db_) {
2488    archived_db_->CommitTransaction();
2489    archived_db_->BeginTransaction();
2490  }
2491}
2492
2493void HistoryBackend::ScheduleCommit() {
2494  if (scheduled_commit_.get())
2495    return;
2496  scheduled_commit_ = new CommitLaterTask(this);
2497  base::MessageLoop::current()->PostDelayedTask(
2498      FROM_HERE,
2499      base::Bind(&CommitLaterTask::RunCommit, scheduled_commit_.get()),
2500      base::TimeDelta::FromSeconds(kCommitIntervalSeconds));
2501}
2502
2503void HistoryBackend::CancelScheduledCommit() {
2504  if (scheduled_commit_.get()) {
2505    scheduled_commit_->Cancel();
2506    scheduled_commit_ = NULL;
2507  }
2508}
2509
2510void HistoryBackend::ProcessDBTaskImpl() {
2511  if (!db_) {
2512    // db went away, release all the refs.
2513    ReleaseDBTasks();
2514    return;
2515  }
2516
2517  // Remove any canceled tasks.
2518  while (!db_task_requests_.empty() && db_task_requests_.front()->canceled()) {
2519    db_task_requests_.front()->Release();
2520    db_task_requests_.pop_front();
2521  }
2522  if (db_task_requests_.empty())
2523    return;
2524
2525  // Run the first task.
2526  HistoryDBTaskRequest* request = db_task_requests_.front();
2527  db_task_requests_.pop_front();
2528  if (request->value->RunOnDBThread(this, db_.get())) {
2529    // The task is done. Notify the callback.
2530    request->ForwardResult();
2531    // We AddRef'd the request before adding, need to release it now.
2532    request->Release();
2533  } else {
2534    // Tasks wants to run some more. Schedule it at the end of current tasks.
2535    db_task_requests_.push_back(request);
2536    // And process it after an invoke later.
2537    base::MessageLoop::current()->PostTask(
2538        FROM_HERE, base::Bind(&HistoryBackend::ProcessDBTaskImpl, this));
2539  }
2540}
2541
2542void HistoryBackend::ReleaseDBTasks() {
2543  for (std::list<HistoryDBTaskRequest*>::iterator i =
2544       db_task_requests_.begin(); i != db_task_requests_.end(); ++i) {
2545    (*i)->Release();
2546  }
2547  db_task_requests_.clear();
2548}
2549
2550////////////////////////////////////////////////////////////////////////////////
2551//
2552// Generic operations
2553//
2554////////////////////////////////////////////////////////////////////////////////
2555
2556void HistoryBackend::DeleteURLs(const std::vector<GURL>& urls) {
2557  expirer_.DeleteURLs(urls);
2558
2559  db_->GetStartDate(&first_recorded_time_);
2560  // Force a commit, if the user is deleting something for privacy reasons, we
2561  // want to get it on disk ASAP.
2562  Commit();
2563}
2564
2565void HistoryBackend::DeleteURL(const GURL& url) {
2566  expirer_.DeleteURL(url);
2567
2568  db_->GetStartDate(&first_recorded_time_);
2569  // Force a commit, if the user is deleting something for privacy reasons, we
2570  // want to get it on disk ASAP.
2571  Commit();
2572}
2573
2574void HistoryBackend::ExpireHistoryBetween(
2575    const std::set<GURL>& restrict_urls,
2576    Time begin_time,
2577    Time end_time) {
2578  if (!db_)
2579    return;
2580
2581  if (begin_time.is_null() && (end_time.is_null() || end_time.is_max()) &&
2582      restrict_urls.empty()) {
2583    // Special case deleting all history so it can be faster and to reduce the
2584    // possibility of an information leak.
2585    DeleteAllHistory();
2586  } else {
2587    // Clearing parts of history, have the expirer do the depend
2588    expirer_.ExpireHistoryBetween(restrict_urls, begin_time, end_time);
2589
2590    // Force a commit, if the user is deleting something for privacy reasons,
2591    // we want to get it on disk ASAP.
2592    Commit();
2593  }
2594
2595  if (begin_time <= first_recorded_time_)
2596    db_->GetStartDate(&first_recorded_time_);
2597}
2598
2599void HistoryBackend::ExpireHistoryForTimes(
2600    const std::set<base::Time>& times,
2601    base::Time begin_time, base::Time end_time) {
2602  if (times.empty() || !db_)
2603    return;
2604
2605  DCHECK(*times.begin() >= begin_time)
2606      << "Min time is before begin time: "
2607      << times.begin()->ToJsTime() << " v.s. " << begin_time.ToJsTime();
2608  DCHECK(*times.rbegin() < end_time)
2609      << "Max time is after end time: "
2610      << times.rbegin()->ToJsTime() << " v.s. " << end_time.ToJsTime();
2611
2612  history::QueryOptions options;
2613  options.begin_time = begin_time;
2614  options.end_time = end_time;
2615  options.duplicate_policy = QueryOptions::KEEP_ALL_DUPLICATES;
2616  QueryResults results;
2617  QueryHistoryBasic(db_.get(), db_.get(), options, &results);
2618
2619  // 1st pass: find URLs that are visited at one of |times|.
2620  std::set<GURL> urls;
2621  for (size_t i = 0; i < results.size(); ++i) {
2622    if (times.count(results[i].visit_time()) > 0)
2623      urls.insert(results[i].url());
2624  }
2625  if (urls.empty())
2626    return;
2627
2628  // 2nd pass: collect all visit times of those URLs.
2629  std::vector<base::Time> times_to_expire;
2630  for (size_t i = 0; i < results.size(); ++i) {
2631    if (urls.count(results[i].url()))
2632      times_to_expire.push_back(results[i].visit_time());
2633  }
2634
2635  // Put the times in reverse chronological order and remove
2636  // duplicates (for expirer_.ExpireHistoryForTimes()).
2637  std::sort(times_to_expire.begin(), times_to_expire.end(),
2638            std::greater<base::Time>());
2639  times_to_expire.erase(
2640      std::unique(times_to_expire.begin(), times_to_expire.end()),
2641      times_to_expire.end());
2642
2643  // Expires by times and commit.
2644  DCHECK(!times_to_expire.empty());
2645  expirer_.ExpireHistoryForTimes(times_to_expire);
2646  Commit();
2647
2648  DCHECK(times_to_expire.back() >= first_recorded_time_);
2649  // Update |first_recorded_time_| if we expired it.
2650  if (times_to_expire.back() == first_recorded_time_)
2651    db_->GetStartDate(&first_recorded_time_);
2652}
2653
2654void HistoryBackend::ExpireHistory(
2655    const std::vector<history::ExpireHistoryArgs>& expire_list) {
2656  if (db_) {
2657    bool update_first_recorded_time = false;
2658
2659    for (std::vector<history::ExpireHistoryArgs>::const_iterator it =
2660         expire_list.begin(); it != expire_list.end(); ++it) {
2661      expirer_.ExpireHistoryBetween(it->urls, it->begin_time, it->end_time);
2662
2663      if (it->begin_time < first_recorded_time_)
2664        update_first_recorded_time = true;
2665    }
2666    Commit();
2667
2668    // Update |first_recorded_time_| if any deletion might have affected it.
2669    if (update_first_recorded_time)
2670      db_->GetStartDate(&first_recorded_time_);
2671  }
2672}
2673
2674void HistoryBackend::URLsNoLongerBookmarked(const std::set<GURL>& urls) {
2675  if (!db_)
2676    return;
2677
2678  for (std::set<GURL>::const_iterator i = urls.begin(); i != urls.end(); ++i) {
2679    URLRow url_row;
2680    if (!db_->GetRowForURL(*i, &url_row))
2681      continue;  // The URL isn't in the db; nothing to do.
2682
2683    VisitVector visits;
2684    db_->GetVisitsForURL(url_row.id(), &visits);
2685
2686    if (visits.empty())
2687      expirer_.DeleteURL(*i);  // There are no more visits; nuke the URL.
2688  }
2689}
2690
2691void HistoryBackend::DatabaseErrorCallback(int error, sql::Statement* stmt) {
2692  if (!scheduled_kill_db_ && sql::IsErrorCatastrophic(error)) {
2693    scheduled_kill_db_ = true;
2694    // Don't just do the close/delete here, as we are being called by |db| and
2695    // that seems dangerous.
2696    // TODO(shess): Consider changing KillHistoryDatabase() to use
2697    // RazeAndClose().  Then it can be cleared immediately.
2698    base::MessageLoop::current()->PostTask(
2699        FROM_HERE,
2700        base::Bind(&HistoryBackend::KillHistoryDatabase, this));
2701  }
2702}
2703
2704void HistoryBackend::KillHistoryDatabase() {
2705  scheduled_kill_db_ = false;
2706  if (!db_)
2707    return;
2708
2709  // Rollback transaction because Raze() cannot be called from within a
2710  // transaction.
2711  db_->RollbackTransaction();
2712  bool success = db_->Raze();
2713  UMA_HISTOGRAM_BOOLEAN("History.KillHistoryDatabaseResult", success);
2714
2715#if defined(OS_ANDROID)
2716  // Release AndroidProviderBackend before other objects.
2717  android_provider_backend_.reset();
2718#endif
2719
2720  // The expirer keeps tabs on the active databases. Tell it about the
2721  // databases which will be closed.
2722  expirer_.SetDatabases(NULL, NULL, NULL);
2723
2724  // Reopen a new transaction for |db_| for the sake of CloseAllDatabases().
2725  db_->BeginTransaction();
2726  CloseAllDatabases();
2727}
2728
2729void HistoryBackend::ProcessDBTask(
2730    scoped_refptr<HistoryDBTaskRequest> request) {
2731  DCHECK(request.get());
2732  if (request->canceled())
2733    return;
2734
2735  bool task_scheduled = !db_task_requests_.empty();
2736  // Make sure we up the refcount of the request. ProcessDBTaskImpl will
2737  // release when done with the task.
2738  request->AddRef();
2739  db_task_requests_.push_back(request.get());
2740  if (!task_scheduled) {
2741    // No other tasks are scheduled. Process request now.
2742    ProcessDBTaskImpl();
2743  }
2744}
2745
2746void HistoryBackend::BroadcastNotifications(
2747    int type,
2748    HistoryDetails* details_deleted) {
2749  // |delegate_| may be NULL if |this| is in the process of closing (closed by
2750  // HistoryService -> HistoryBackend::Closing().
2751  if (delegate_)
2752    delegate_->BroadcastNotifications(type, details_deleted);
2753  else
2754    delete details_deleted;
2755}
2756
2757void HistoryBackend::NotifySyncURLsDeleted(bool all_history,
2758                                           bool archived,
2759                                           URLRows* rows) {
2760  if (typed_url_syncable_service_.get())
2761    typed_url_syncable_service_->OnUrlsDeleted(all_history, archived, rows);
2762}
2763
2764// Deleting --------------------------------------------------------------------
2765
2766void HistoryBackend::DeleteAllHistory() {
2767  // Our approach to deleting all history is:
2768  //  1. Copy the bookmarks and their dependencies to new tables with temporary
2769  //     names.
2770  //  2. Delete the original tables. Since tables can not share pages, we know
2771  //     that any data we don't want to keep is now in an unused page.
2772  //  3. Renaming the temporary tables to match the original.
2773  //  4. Vacuuming the database to delete the unused pages.
2774  //
2775  // Since we are likely to have very few bookmarks and their dependencies
2776  // compared to all history, this is also much faster than just deleting from
2777  // the original tables directly.
2778
2779  // Get the bookmarked URLs.
2780  std::vector<BookmarkService::URLAndTitle> starred_urls;
2781  BookmarkService* bookmark_service = GetBookmarkService();
2782  if (bookmark_service)
2783    bookmark_service_->GetBookmarks(&starred_urls);
2784
2785  URLRows kept_urls;
2786  for (size_t i = 0; i < starred_urls.size(); i++) {
2787    URLRow row;
2788    if (!db_->GetRowForURL(starred_urls[i].url, &row))
2789      continue;
2790
2791    // Clear the last visit time so when we write these rows they are "clean."
2792    row.set_last_visit(Time());
2793    row.set_visit_count(0);
2794    row.set_typed_count(0);
2795    kept_urls.push_back(row);
2796  }
2797
2798  // Clear thumbnail and favicon history. The favicons for the given URLs will
2799  // be kept.
2800  if (!ClearAllThumbnailHistory(kept_urls)) {
2801    LOG(ERROR) << "Thumbnail history could not be cleared";
2802    // We continue in this error case. If the user wants to delete their
2803    // history, we should delete as much as we can.
2804  }
2805
2806  // ClearAllMainHistory will change the IDs of the URLs in kept_urls.
2807  // Therefore, we clear the list afterwards to make sure nobody uses this
2808  // invalid data.
2809  if (!ClearAllMainHistory(kept_urls))
2810    LOG(ERROR) << "Main history could not be cleared";
2811  kept_urls.clear();
2812
2813  // Delete archived history.
2814  if (archived_db_) {
2815    // Close the database and delete the file.
2816    archived_db_.reset();
2817    base::FilePath archived_file_name = GetArchivedFileName();
2818    sql::Connection::Delete(archived_file_name);
2819
2820    // Now re-initialize the database (which may fail).
2821    archived_db_.reset(new ArchivedDatabase());
2822    if (!archived_db_->Init(archived_file_name)) {
2823      LOG(WARNING) << "Could not initialize the archived database.";
2824      archived_db_.reset();
2825    } else {
2826      // Open our long-running transaction on this database.
2827      archived_db_->BeginTransaction();
2828    }
2829  }
2830
2831  db_->GetStartDate(&first_recorded_time_);
2832
2833  // Send out the notification that history is cleared. The in-memory database
2834  // will pick this up and clear itself.
2835  URLsDeletedDetails* details = new URLsDeletedDetails;
2836  details->all_history = true;
2837  NotifySyncURLsDeleted(true, false, NULL);
2838  BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URLS_DELETED, details);
2839}
2840
2841bool HistoryBackend::ClearAllThumbnailHistory(const URLRows& kept_urls) {
2842  if (!thumbnail_db_) {
2843    // When we have no reference to the thumbnail database, maybe there was an
2844    // error opening it. In this case, we just try to blow it away to try to
2845    // fix the error if it exists. This may fail, in which case either the
2846    // file doesn't exist or there's no more we can do.
2847    sql::Connection::Delete(GetFaviconsFileName());
2848
2849    // Older version of the database.
2850    sql::Connection::Delete(GetThumbnailFileName());
2851    return true;
2852  }
2853
2854  // Urls to retain mappings for.
2855  std::vector<GURL> urls_to_keep;
2856  for (URLRows::const_iterator i = kept_urls.begin();
2857       i != kept_urls.end(); ++i) {
2858    urls_to_keep.push_back(i->url());
2859  }
2860
2861  // Isolate from any long-running transaction.
2862  thumbnail_db_->CommitTransaction();
2863  thumbnail_db_->BeginTransaction();
2864
2865  // TODO(shess): If this fails, perhaps the database should be razed
2866  // or deleted.
2867  if (!thumbnail_db_->RetainDataForPageUrls(urls_to_keep)) {
2868    thumbnail_db_->RollbackTransaction();
2869    thumbnail_db_->BeginTransaction();
2870    return false;
2871  }
2872
2873#if defined(OS_ANDROID)
2874  // TODO (michaelbai): Add the unit test once AndroidProviderBackend is
2875  // avaliable in HistoryBackend.
2876  db_->ClearAndroidURLRows();
2877#endif
2878
2879  // Vacuum to remove all the pages associated with the dropped tables. There
2880  // must be no transaction open on the table when we do this. We assume that
2881  // our long-running transaction is open, so we complete it and start it again.
2882  DCHECK(thumbnail_db_->transaction_nesting() == 1);
2883  thumbnail_db_->CommitTransaction();
2884  thumbnail_db_->Vacuum();
2885  thumbnail_db_->BeginTransaction();
2886  return true;
2887}
2888
2889bool HistoryBackend::ClearAllMainHistory(const URLRows& kept_urls) {
2890  // Create the duplicate URL table. We will copy the kept URLs into this.
2891  if (!db_->CreateTemporaryURLTable())
2892    return false;
2893
2894  // Insert the URLs into the temporary table.
2895  for (URLRows::const_iterator i = kept_urls.begin(); i != kept_urls.end();
2896       ++i) {
2897    db_->AddTemporaryURL(*i);
2898  }
2899
2900  // Replace the original URL table with the temporary one.
2901  if (!db_->CommitTemporaryURLTable())
2902    return false;
2903
2904  // Delete the old tables and recreate them empty.
2905  db_->RecreateAllTablesButURL();
2906
2907  // Vacuum to reclaim the space from the dropped tables. This must be done
2908  // when there is no transaction open, and we assume that our long-running
2909  // transaction is currently open.
2910  db_->CommitTransaction();
2911  db_->Vacuum();
2912  db_->BeginTransaction();
2913  db_->GetStartDate(&first_recorded_time_);
2914
2915  return true;
2916}
2917
2918BookmarkService* HistoryBackend::GetBookmarkService() {
2919  if (bookmark_service_)
2920    bookmark_service_->BlockTillLoaded();
2921  return bookmark_service_;
2922}
2923
2924void HistoryBackend::NotifyVisitObservers(const VisitRow& visit) {
2925  BriefVisitInfo info;
2926  info.url_id = visit.url_id;
2927  info.time = visit.visit_time;
2928  info.transition = visit.transition;
2929  // If we don't have a delegate yet during setup or shutdown, we will drop
2930  // these notifications.
2931  if (delegate_)
2932    delegate_->NotifyVisitDBObserversOnAddVisit(info);
2933}
2934
2935#if defined(OS_ANDROID)
2936void HistoryBackend::PopulateMostVisitedURLMap() {
2937  MostVisitedURLList most_visited_urls;
2938  QueryMostVisitedURLsImpl(kPageVisitStatsMaxTopSites, kSegmentDataRetention,
2939                           &most_visited_urls);
2940
2941  DCHECK_LE(most_visited_urls.size(), kPageVisitStatsMaxTopSites);
2942  for (size_t i = 0; i < most_visited_urls.size(); ++i) {
2943    most_visited_urls_map_[most_visited_urls[i].url] = i;
2944    for (size_t j = 0; j < most_visited_urls[i].redirects.size(); ++j)
2945      most_visited_urls_map_[most_visited_urls[i].redirects[j]] = i;
2946  }
2947}
2948
2949void HistoryBackend::RecordTopPageVisitStats(const GURL& url) {
2950  int rank = kPageVisitStatsMaxTopSites;
2951  std::map<GURL, int>::const_iterator it = most_visited_urls_map_.find(url);
2952  if (it != most_visited_urls_map_.end())
2953    rank = (*it).second;
2954  UMA_HISTOGRAM_ENUMERATION("History.TopSitesVisitsByRank",
2955                            rank, kPageVisitStatsMaxTopSites + 1);
2956}
2957#endif
2958
2959}  // namespace history
2960