history_backend.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
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(base::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
1088// Keyword visits --------------------------------------------------------------
1089
1090void HistoryBackend::SetKeywordSearchTermsForURL(const GURL& url,
1091                                                 TemplateURLID keyword_id,
1092                                                 const base::string16& term) {
1093  if (!db_)
1094    return;
1095
1096  // Get the ID for this URL.
1097  URLID url_id = db_->GetRowForURL(url, NULL);
1098  if (!url_id) {
1099    // There is a small possibility the url was deleted before the keyword
1100    // was added. Ignore the request.
1101    return;
1102  }
1103
1104  db_->SetKeywordSearchTermsForURL(url_id, keyword_id, term);
1105
1106  BroadcastNotifications(
1107      chrome::NOTIFICATION_HISTORY_KEYWORD_SEARCH_TERM_UPDATED,
1108      new KeywordSearchUpdatedDetails(url, keyword_id, term));
1109  ScheduleCommit();
1110}
1111
1112void HistoryBackend::DeleteAllSearchTermsForKeyword(
1113    TemplateURLID keyword_id) {
1114  if (!db_)
1115    return;
1116
1117  db_->DeleteAllSearchTermsForKeyword(keyword_id);
1118  // TODO(sky): bug 1168470. Need to move from archive dbs too.
1119  ScheduleCommit();
1120}
1121
1122void HistoryBackend::GetMostRecentKeywordSearchTerms(
1123    scoped_refptr<GetMostRecentKeywordSearchTermsRequest> request,
1124    TemplateURLID keyword_id,
1125    const base::string16& prefix,
1126    int max_count) {
1127  if (request->canceled())
1128    return;
1129
1130  if (db_) {
1131    db_->GetMostRecentKeywordSearchTerms(keyword_id, prefix, max_count,
1132                                         &(request->value));
1133  }
1134  request->ForwardResult(request->handle(), &request->value);
1135}
1136
1137void HistoryBackend::DeleteKeywordSearchTermForURL(const GURL& url) {
1138  if (!db_)
1139    return;
1140
1141  URLID url_id = db_->GetRowForURL(url, NULL);
1142  if (!url_id)
1143    return;
1144  db_->DeleteKeywordSearchTermForURL(url_id);
1145
1146  BroadcastNotifications(
1147      chrome::NOTIFICATION_HISTORY_KEYWORD_SEARCH_TERM_DELETED,
1148      new KeywordSearchDeletedDetails(url));
1149  ScheduleCommit();
1150}
1151
1152void HistoryBackend::DeleteMatchingURLsForKeyword(TemplateURLID keyword_id,
1153                                                  const base::string16& term) {
1154  if (!db_)
1155    return;
1156
1157  std::vector<KeywordSearchTermRow> rows;
1158  if (db_->GetKeywordSearchTermRows(term, &rows)) {
1159    std::vector<GURL> items_to_delete;
1160    URLRow row;
1161    for (std::vector<KeywordSearchTermRow>::iterator it = rows.begin();
1162         it != rows.end(); ++it) {
1163      if ((it->keyword_id == keyword_id) && db_->GetURLRow(it->url_id, &row))
1164        items_to_delete.push_back(row.url());
1165    }
1166    DeleteURLs(items_to_delete);
1167  }
1168}
1169
1170// Downloads -------------------------------------------------------------------
1171
1172void HistoryBackend::GetNextDownloadId(uint32* next_id) {
1173  if (db_)
1174    db_->GetNextDownloadId(next_id);
1175}
1176
1177// Get all the download entries from the database.
1178void HistoryBackend::QueryDownloads(std::vector<DownloadRow>* rows) {
1179  if (db_)
1180    db_->QueryDownloads(rows);
1181}
1182
1183// Update a particular download entry.
1184void HistoryBackend::UpdateDownload(const history::DownloadRow& data) {
1185  if (!db_)
1186    return;
1187  db_->UpdateDownload(data);
1188  ScheduleCommit();
1189}
1190
1191void HistoryBackend::CreateDownload(const history::DownloadRow& history_info,
1192                                    bool* success) {
1193  if (!db_)
1194    return;
1195  *success = db_->CreateDownload(history_info);
1196  ScheduleCommit();
1197}
1198
1199void HistoryBackend::RemoveDownloads(const std::set<uint32>& ids) {
1200  if (!db_)
1201    return;
1202  size_t downloads_count_before = db_->CountDownloads();
1203  base::TimeTicks started_removing = base::TimeTicks::Now();
1204  // HistoryBackend uses a long-running Transaction that is committed
1205  // periodically, so this loop doesn't actually hit the disk too hard.
1206  for (std::set<uint32>::const_iterator it = ids.begin();
1207       it != ids.end(); ++it) {
1208    db_->RemoveDownload(*it);
1209  }
1210  ScheduleCommit();
1211  base::TimeTicks finished_removing = base::TimeTicks::Now();
1212  size_t downloads_count_after = db_->CountDownloads();
1213
1214  DCHECK_LE(downloads_count_after, downloads_count_before);
1215  if (downloads_count_after > downloads_count_before)
1216    return;
1217  size_t num_downloads_deleted = downloads_count_before - downloads_count_after;
1218  UMA_HISTOGRAM_COUNTS("Download.DatabaseRemoveDownloadsCount",
1219                        num_downloads_deleted);
1220  base::TimeDelta micros = (1000 * (finished_removing - started_removing));
1221  UMA_HISTOGRAM_TIMES("Download.DatabaseRemoveDownloadsTime", micros);
1222  if (num_downloads_deleted > 0) {
1223    UMA_HISTOGRAM_TIMES("Download.DatabaseRemoveDownloadsTimePerRecord",
1224                        (1000 * micros) / num_downloads_deleted);
1225  }
1226  DCHECK_GE(ids.size(), num_downloads_deleted);
1227  if (ids.size() < num_downloads_deleted)
1228    return;
1229  UMA_HISTOGRAM_COUNTS("Download.DatabaseRemoveDownloadsCountNotRemoved",
1230                        ids.size() - num_downloads_deleted);
1231}
1232
1233void HistoryBackend::QueryHistory(scoped_refptr<QueryHistoryRequest> request,
1234                                  const base::string16& text_query,
1235                                  const QueryOptions& options) {
1236  if (request->canceled())
1237    return;
1238
1239  TimeTicks beginning_time = TimeTicks::Now();
1240
1241  if (db_) {
1242    if (text_query.empty()) {
1243      // Basic history query for the main database.
1244      QueryHistoryBasic(db_.get(), db_.get(), options, &request->value);
1245
1246      // Now query the archived database. This is a bit tricky because we don't
1247      // want to query it if the queried time range isn't going to find anything
1248      // in it.
1249      // TODO(brettw) bug 1171036: do blimpie querying for the archived database
1250      // as well.
1251      // if (archived_db_.get() &&
1252      //     expirer_.GetCurrentArchiveTime() - TimeDelta::FromDays(7)) {
1253    } else {
1254      // Text history query.
1255      QueryHistoryText(db_.get(), db_.get(), text_query, options,
1256                       &request->value);
1257      if (archived_db_.get() &&
1258          expirer_.GetCurrentArchiveTime() >= options.begin_time) {
1259        QueryHistoryText(archived_db_.get(), archived_db_.get(), text_query,
1260                         options, &request->value);
1261      }
1262    }
1263  }
1264
1265  request->ForwardResult(request->handle(), &request->value);
1266
1267  UMA_HISTOGRAM_TIMES("History.QueryHistory",
1268                      TimeTicks::Now() - beginning_time);
1269}
1270
1271// Basic time-based querying of history.
1272void HistoryBackend::QueryHistoryBasic(URLDatabase* url_db,
1273                                       VisitDatabase* visit_db,
1274                                       const QueryOptions& options,
1275                                       QueryResults* result) {
1276  // First get all visits.
1277  VisitVector visits;
1278  bool has_more_results = visit_db->GetVisibleVisitsInRange(options, &visits);
1279  DCHECK(static_cast<int>(visits.size()) <= options.EffectiveMaxCount());
1280
1281  // Now add them and the URL rows to the results.
1282  URLResult url_result;
1283  for (size_t i = 0; i < visits.size(); i++) {
1284    const VisitRow visit = visits[i];
1285
1286    // Add a result row for this visit, get the URL info from the DB.
1287    if (!url_db->GetURLRow(visit.url_id, &url_result)) {
1288      VLOG(0) << "Failed to get id " << visit.url_id
1289              << " from history.urls.";
1290      continue;  // DB out of sync and URL doesn't exist, try to recover.
1291    }
1292
1293    if (!url_result.url().is_valid()) {
1294      VLOG(0) << "Got invalid URL from history.urls with id "
1295              << visit.url_id << ":  "
1296              << url_result.url().possibly_invalid_spec();
1297      continue;  // Don't report invalid URLs in case of corruption.
1298    }
1299
1300    // The archived database may be out of sync with respect to starring,
1301    // titles, last visit date, etc. Therefore, we query the main DB if the
1302    // current URL database is not the main one.
1303    if (url_db == db_.get()) {
1304      // Currently querying the archived DB, update with the main database to
1305      // catch any interesting stuff. This will update it if it exists in the
1306      // main DB, and do nothing otherwise.
1307      db_->GetRowForURL(url_result.url(), &url_result);
1308    }
1309
1310    url_result.set_visit_time(visit.visit_time);
1311
1312    // Set whether the visit was blocked for a managed user by looking at the
1313    // transition type.
1314    url_result.set_blocked_visit(
1315        (visit.transition & content::PAGE_TRANSITION_BLOCKED) != 0);
1316
1317    // We don't set any of the query-specific parts of the URLResult, since
1318    // snippets and stuff don't apply to basic querying.
1319    result->AppendURLBySwapping(&url_result);
1320  }
1321
1322  if (!has_more_results && options.begin_time <= first_recorded_time_)
1323    result->set_reached_beginning(true);
1324}
1325
1326// Text-based querying of history.
1327void HistoryBackend::QueryHistoryText(URLDatabase* url_db,
1328                                      VisitDatabase* visit_db,
1329                                      const base::string16& text_query,
1330                                      const QueryOptions& options,
1331                                      QueryResults* result) {
1332  URLRows text_matches;
1333  url_db->GetTextMatches(text_query, &text_matches);
1334
1335  std::vector<URLResult> matching_visits;
1336  VisitVector visits;    // Declare outside loop to prevent re-construction.
1337  for (size_t i = 0; i < text_matches.size(); i++) {
1338    const URLRow& text_match = text_matches[i];
1339    // Get all visits for given URL match.
1340    visit_db->GetVisibleVisitsForURL(text_match.id(), options, &visits);
1341    for (size_t j = 0; j < visits.size(); j++) {
1342      URLResult url_result(text_match);
1343      url_result.set_visit_time(visits[j].visit_time);
1344      matching_visits.push_back(url_result);
1345    }
1346  }
1347
1348  std::sort(matching_visits.begin(), matching_visits.end(),
1349            URLResult::CompareVisitTime);
1350
1351  size_t max_results = options.max_count == 0 ?
1352      std::numeric_limits<size_t>::max() : static_cast<int>(options.max_count);
1353  for (std::vector<URLResult>::iterator it = matching_visits.begin();
1354       it != matching_visits.end() && result->size() < max_results; ++it) {
1355    result->AppendURLBySwapping(&(*it));
1356  }
1357
1358  if (matching_visits.size() == result->size() &&
1359      options.begin_time <= first_recorded_time_)
1360    result->set_reached_beginning(true);
1361}
1362
1363// Frontend to GetMostRecentRedirectsFrom from the history thread.
1364void HistoryBackend::QueryRedirectsFrom(
1365    scoped_refptr<QueryRedirectsRequest> request,
1366    const GURL& url) {
1367  if (request->canceled())
1368    return;
1369  bool success = GetMostRecentRedirectsFrom(url, &request->value);
1370  request->ForwardResult(request->handle(), url, success, &request->value);
1371}
1372
1373void HistoryBackend::QueryRedirectsTo(
1374    scoped_refptr<QueryRedirectsRequest> request,
1375    const GURL& url) {
1376  if (request->canceled())
1377    return;
1378  bool success = GetMostRecentRedirectsTo(url, &request->value);
1379  request->ForwardResult(request->handle(), url, success, &request->value);
1380}
1381
1382void HistoryBackend::GetVisibleVisitCountToHost(
1383    scoped_refptr<GetVisibleVisitCountToHostRequest> request,
1384    const GURL& url) {
1385  if (request->canceled())
1386    return;
1387  int count = 0;
1388  Time first_visit;
1389  const bool success = db_.get() &&
1390      db_->GetVisibleVisitCountToHost(url, &count, &first_visit);
1391  request->ForwardResult(request->handle(), success, count, first_visit);
1392}
1393
1394void HistoryBackend::QueryTopURLsAndRedirects(
1395    scoped_refptr<QueryTopURLsAndRedirectsRequest> request,
1396    int result_count) {
1397  if (request->canceled())
1398    return;
1399
1400  if (!db_) {
1401    request->ForwardResult(request->handle(), false, NULL, NULL);
1402    return;
1403  }
1404
1405  std::vector<GURL>* top_urls = &request->value.a;
1406  history::RedirectMap* redirects = &request->value.b;
1407
1408  ScopedVector<PageUsageData> data;
1409  db_->QuerySegmentUsage(base::Time::Now() - base::TimeDelta::FromDays(90),
1410      result_count, &data.get());
1411
1412  for (size_t i = 0; i < data.size(); ++i) {
1413    top_urls->push_back(data[i]->GetURL());
1414    RefCountedVector<GURL>* list = new RefCountedVector<GURL>;
1415    GetMostRecentRedirectsFrom(top_urls->back(), &list->data);
1416    (*redirects)[top_urls->back()] = list;
1417  }
1418
1419  request->ForwardResult(request->handle(), true, top_urls, redirects);
1420}
1421
1422// Will replace QueryTopURLsAndRedirectsRequest.
1423void HistoryBackend::QueryMostVisitedURLs(
1424    scoped_refptr<QueryMostVisitedURLsRequest> request,
1425    int result_count,
1426    int days_back) {
1427  if (request->canceled())
1428    return;
1429
1430  if (!db_) {
1431    // No History Database - return an empty list.
1432    request->ForwardResult(request->handle(), MostVisitedURLList());
1433    return;
1434  }
1435
1436  MostVisitedURLList* result = &request->value;
1437  QueryMostVisitedURLsImpl(result_count, days_back, result);
1438  request->ForwardResult(request->handle(), *result);
1439}
1440
1441void HistoryBackend::QueryFilteredURLs(
1442      scoped_refptr<QueryFilteredURLsRequest> request,
1443      int result_count,
1444      const history::VisitFilter& filter,
1445      bool extended_info)  {
1446  if (request->canceled())
1447    return;
1448
1449  base::Time request_start = base::Time::Now();
1450
1451  if (!db_) {
1452    // No History Database - return an empty list.
1453    request->ForwardResult(request->handle(), FilteredURLList());
1454    return;
1455  }
1456
1457  VisitVector visits;
1458  db_->GetDirectVisitsDuringTimes(filter, 0, &visits);
1459
1460  std::map<URLID, double> score_map;
1461  for (size_t i = 0; i < visits.size(); ++i) {
1462    score_map[visits[i].url_id] += filter.GetVisitScore(visits[i]);
1463  }
1464
1465  // TODO(georgey): experiment with visit_segment database granularity (it is
1466  // currently 24 hours) to use it directly instead of using visits database,
1467  // which is considerably slower.
1468  ScopedVector<PageUsageData> data;
1469  data.reserve(score_map.size());
1470  for (std::map<URLID, double>::iterator it = score_map.begin();
1471       it != score_map.end(); ++it) {
1472    PageUsageData* pud = new PageUsageData(it->first);
1473    pud->SetScore(it->second);
1474    data.push_back(pud);
1475  }
1476
1477  // Limit to the top |result_count| results.
1478  std::sort(data.begin(), data.end(), PageUsageData::Predicate);
1479  if (result_count && implicit_cast<int>(data.size()) > result_count)
1480    data.resize(result_count);
1481
1482  for (size_t i = 0; i < data.size(); ++i) {
1483    URLRow info;
1484    if (db_->GetURLRow(data[i]->GetID(), &info)) {
1485      data[i]->SetURL(info.url());
1486      data[i]->SetTitle(info.title());
1487    }
1488  }
1489
1490  FilteredURLList& result = request->value;
1491  for (size_t i = 0; i < data.size(); ++i) {
1492    PageUsageData* current_data = data[i];
1493    FilteredURL url(*current_data);
1494
1495    if (extended_info) {
1496      VisitVector visits;
1497      db_->GetVisitsForURL(current_data->GetID(), &visits);
1498      if (visits.size() > 0) {
1499        url.extended_info.total_visits = visits.size();
1500        for (size_t i = 0; i < visits.size(); ++i) {
1501          url.extended_info.duration_opened +=
1502              visits[i].visit_duration.InSeconds();
1503          if (visits[i].visit_time > url.extended_info.last_visit_time) {
1504            url.extended_info.last_visit_time = visits[i].visit_time;
1505          }
1506        }
1507        // TODO(macourteau): implement the url.extended_info.visits stat.
1508      }
1509    }
1510    result.push_back(url);
1511  }
1512
1513  int delta_time = std::max(1, std::min(999,
1514      static_cast<int>((base::Time::Now() - request_start).InMilliseconds())));
1515  STATIC_HISTOGRAM_POINTER_BLOCK(
1516      "NewTabPage.SuggestedSitesLoadTime",
1517      Add(delta_time),
1518      base::LinearHistogram::FactoryGet("NewTabPage.SuggestedSitesLoadTime",
1519          1, 1000, 100, base::Histogram::kUmaTargetedHistogramFlag));
1520
1521  request->ForwardResult(request->handle(), result);
1522}
1523
1524void HistoryBackend::QueryMostVisitedURLsImpl(int result_count,
1525                                              int days_back,
1526                                              MostVisitedURLList* result) {
1527  if (!db_)
1528    return;
1529
1530  ScopedVector<PageUsageData> data;
1531  db_->QuerySegmentUsage(base::Time::Now() -
1532                         base::TimeDelta::FromDays(days_back),
1533                         result_count, &data.get());
1534
1535  for (size_t i = 0; i < data.size(); ++i) {
1536    PageUsageData* current_data = data[i];
1537    RedirectList redirects;
1538    GetMostRecentRedirectsFrom(current_data->GetURL(), &redirects);
1539    MostVisitedURL url = MakeMostVisitedURL(*current_data, redirects);
1540    result->push_back(url);
1541  }
1542}
1543
1544void HistoryBackend::GetRedirectsFromSpecificVisit(
1545    VisitID cur_visit, history::RedirectList* redirects) {
1546  // Follow any redirects from the given visit and add them to the list.
1547  // It *should* be impossible to get a circular chain here, but we check
1548  // just in case to avoid infinite loops.
1549  GURL cur_url;
1550  std::set<VisitID> visit_set;
1551  visit_set.insert(cur_visit);
1552  while (db_->GetRedirectFromVisit(cur_visit, &cur_visit, &cur_url)) {
1553    if (visit_set.find(cur_visit) != visit_set.end()) {
1554      NOTREACHED() << "Loop in visit chain, giving up";
1555      return;
1556    }
1557    visit_set.insert(cur_visit);
1558    redirects->push_back(cur_url);
1559  }
1560}
1561
1562void HistoryBackend::GetRedirectsToSpecificVisit(
1563    VisitID cur_visit,
1564    history::RedirectList* redirects) {
1565  // Follow redirects going to cur_visit. These are added to |redirects| in
1566  // the order they are found. If a redirect chain looks like A -> B -> C and
1567  // |cur_visit| = C, redirects will be {B, A} in that order.
1568  if (!db_)
1569    return;
1570
1571  GURL cur_url;
1572  std::set<VisitID> visit_set;
1573  visit_set.insert(cur_visit);
1574  while (db_->GetRedirectToVisit(cur_visit, &cur_visit, &cur_url)) {
1575    if (visit_set.find(cur_visit) != visit_set.end()) {
1576      NOTREACHED() << "Loop in visit chain, giving up";
1577      return;
1578    }
1579    visit_set.insert(cur_visit);
1580    redirects->push_back(cur_url);
1581  }
1582}
1583
1584bool HistoryBackend::GetMostRecentRedirectsFrom(
1585    const GURL& from_url,
1586    history::RedirectList* redirects) {
1587  redirects->clear();
1588  if (!db_)
1589    return false;
1590
1591  URLID from_url_id = db_->GetRowForURL(from_url, NULL);
1592  VisitID cur_visit = db_->GetMostRecentVisitForURL(from_url_id, NULL);
1593  if (!cur_visit)
1594    return false;  // No visits for URL.
1595
1596  GetRedirectsFromSpecificVisit(cur_visit, redirects);
1597  return true;
1598}
1599
1600bool HistoryBackend::GetMostRecentRedirectsTo(
1601    const GURL& to_url,
1602    history::RedirectList* redirects) {
1603  redirects->clear();
1604  if (!db_)
1605    return false;
1606
1607  URLID to_url_id = db_->GetRowForURL(to_url, NULL);
1608  VisitID cur_visit = db_->GetMostRecentVisitForURL(to_url_id, NULL);
1609  if (!cur_visit)
1610    return false;  // No visits for URL.
1611
1612  GetRedirectsToSpecificVisit(cur_visit, redirects);
1613  return true;
1614}
1615
1616void HistoryBackend::ScheduleAutocomplete(HistoryURLProvider* provider,
1617                                          HistoryURLProviderParams* params) {
1618  // ExecuteWithDB should handle the NULL database case.
1619  provider->ExecuteWithDB(this, db_.get(), params);
1620}
1621
1622void HistoryBackend::DeleteFTSIndexDatabases() {
1623  // Find files on disk matching the text databases file pattern so we can
1624  // quickly test for and delete them.
1625  base::FilePath::StringType filepattern =
1626      FILE_PATH_LITERAL("History Index *");
1627  base::FileEnumerator enumerator(
1628      history_dir_, false, base::FileEnumerator::FILES, filepattern);
1629  int num_databases_deleted = 0;
1630  base::FilePath current_file;
1631  while (!(current_file = enumerator.Next()).empty()) {
1632    if (sql::Connection::Delete(current_file))
1633      num_databases_deleted++;
1634  }
1635  UMA_HISTOGRAM_COUNTS("History.DeleteFTSIndexDatabases",
1636                       num_databases_deleted);
1637}
1638
1639void HistoryBackend::GetFavicons(
1640    const std::vector<GURL>& icon_urls,
1641    int icon_types,
1642    int desired_size_in_dip,
1643    const std::vector<ui::ScaleFactor>& desired_scale_factors,
1644    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1645  UpdateFaviconMappingsAndFetchImpl(NULL, icon_urls, icon_types,
1646                                    desired_size_in_dip, desired_scale_factors,
1647                                    bitmap_results);
1648}
1649
1650void HistoryBackend::GetLargestFaviconForURL(
1651      const GURL& page_url,
1652      const std::vector<int>& icon_types,
1653      int minimum_size_in_pixels,
1654      chrome::FaviconBitmapResult* favicon_bitmap_result) {
1655  DCHECK(favicon_bitmap_result);
1656
1657  if (!db_ || !thumbnail_db_)
1658    return;
1659
1660  TimeTicks beginning_time = TimeTicks::Now();
1661
1662  std::vector<IconMapping> icon_mappings;
1663  if (!thumbnail_db_->GetIconMappingsForPageURL(page_url, &icon_mappings) ||
1664      icon_mappings.empty())
1665    return;
1666
1667  int required_icon_types = 0;
1668  for (std::vector<int>::const_iterator i = icon_types.begin();
1669       i != icon_types.end(); ++i) {
1670    required_icon_types |= *i;
1671  }
1672
1673  // Find the largest bitmap for each IconType placing in
1674  // |largest_favicon_bitmaps|.
1675  std::map<chrome::IconType, FaviconBitmap> largest_favicon_bitmaps;
1676  for (std::vector<IconMapping>::const_iterator i = icon_mappings.begin();
1677       i != icon_mappings.end(); ++i) {
1678    if (!(i->icon_type & required_icon_types))
1679      continue;
1680    std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
1681    thumbnail_db_->GetFaviconBitmapIDSizes(i->icon_id, &bitmap_id_sizes);
1682    FaviconBitmap& largest = largest_favicon_bitmaps[i->icon_type];
1683    for (std::vector<FaviconBitmapIDSize>::const_iterator j =
1684             bitmap_id_sizes.begin(); j != bitmap_id_sizes.end(); ++j) {
1685      if (largest.bitmap_id == 0 ||
1686          (largest.pixel_size.width() < j->pixel_size.width() &&
1687           largest.pixel_size.height() < j->pixel_size.height())) {
1688        largest.icon_id = i->icon_id;
1689        largest.bitmap_id = j->bitmap_id;
1690        largest.pixel_size = j->pixel_size;
1691      }
1692    }
1693  }
1694  if (largest_favicon_bitmaps.empty())
1695    return;
1696
1697  // Find an icon which is larger than minimum_size_in_pixels in the order of
1698  // icon_types.
1699  FaviconBitmap largest_icon;
1700  for (std::vector<int>::const_iterator t = icon_types.begin();
1701       t != icon_types.end(); ++t) {
1702    for (std::map<chrome::IconType, FaviconBitmap>::const_iterator f =
1703            largest_favicon_bitmaps.begin(); f != largest_favicon_bitmaps.end();
1704        ++f) {
1705      if (f->first & *t &&
1706          (largest_icon.bitmap_id == 0 ||
1707           (largest_icon.pixel_size.height() < f->second.pixel_size.height() &&
1708            largest_icon.pixel_size.width() < f->second.pixel_size.width()))) {
1709        largest_icon = f->second;
1710      }
1711    }
1712    if (largest_icon.pixel_size.width() > minimum_size_in_pixels &&
1713        largest_icon.pixel_size.height() > minimum_size_in_pixels)
1714      break;
1715  }
1716
1717  GURL icon_url;
1718  chrome::IconType icon_type;
1719  if (!thumbnail_db_->GetFaviconHeader(largest_icon.icon_id, &icon_url,
1720                                       &icon_type)) {
1721    return;
1722  }
1723
1724  base::Time last_updated;
1725  chrome::FaviconBitmapResult bitmap_result;
1726  bitmap_result.icon_url = icon_url;
1727  bitmap_result.icon_type = icon_type;
1728  if (!thumbnail_db_->GetFaviconBitmap(largest_icon.bitmap_id,
1729                                       &last_updated,
1730                                       &bitmap_result.bitmap_data,
1731                                       &bitmap_result.pixel_size)) {
1732    return;
1733  }
1734
1735  bitmap_result.expired = (Time::Now() - last_updated) >
1736      TimeDelta::FromDays(kFaviconRefetchDays);
1737  if (bitmap_result.is_valid())
1738    *favicon_bitmap_result = bitmap_result;
1739
1740  HISTOGRAM_TIMES("History.GetLargestFaviconForURL",
1741                  TimeTicks::Now() - beginning_time);
1742}
1743
1744void HistoryBackend::GetFaviconsForURL(
1745    const GURL& page_url,
1746    int icon_types,
1747    int desired_size_in_dip,
1748    const std::vector<ui::ScaleFactor>& desired_scale_factors,
1749    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1750  DCHECK(bitmap_results);
1751  GetFaviconsFromDB(page_url, icon_types, desired_size_in_dip,
1752                    desired_scale_factors, bitmap_results);
1753}
1754
1755void HistoryBackend::GetFaviconForID(
1756    chrome::FaviconID favicon_id,
1757    int desired_size_in_dip,
1758    ui::ScaleFactor desired_scale_factor,
1759    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1760  std::vector<chrome::FaviconID> favicon_ids;
1761  favicon_ids.push_back(favicon_id);
1762  std::vector<ui::ScaleFactor> desired_scale_factors;
1763  desired_scale_factors.push_back(desired_scale_factor);
1764
1765  // Get results from DB.
1766  GetFaviconBitmapResultsForBestMatch(favicon_ids,
1767                                      desired_size_in_dip,
1768                                      desired_scale_factors,
1769                                      bitmap_results);
1770}
1771
1772void HistoryBackend::UpdateFaviconMappingsAndFetch(
1773    const GURL& page_url,
1774    const std::vector<GURL>& icon_urls,
1775    int icon_types,
1776    int desired_size_in_dip,
1777    const std::vector<ui::ScaleFactor>& desired_scale_factors,
1778    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
1779  UpdateFaviconMappingsAndFetchImpl(&page_url, icon_urls, icon_types,
1780                                    desired_size_in_dip, desired_scale_factors,
1781                                    bitmap_results);
1782}
1783
1784void HistoryBackend::MergeFavicon(
1785    const GURL& page_url,
1786    const GURL& icon_url,
1787    chrome::IconType icon_type,
1788    scoped_refptr<base::RefCountedMemory> bitmap_data,
1789    const gfx::Size& pixel_size) {
1790  if (!thumbnail_db_ || !db_)
1791    return;
1792
1793  chrome::FaviconID favicon_id =
1794      thumbnail_db_->GetFaviconIDForFaviconURL(icon_url, icon_type, NULL);
1795
1796  if (!favicon_id) {
1797    // There is no favicon at |icon_url|, create it.
1798    favicon_id = thumbnail_db_->AddFavicon(icon_url, icon_type);
1799  }
1800
1801  std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
1802  thumbnail_db_->GetFaviconBitmapIDSizes(favicon_id, &bitmap_id_sizes);
1803
1804  // If there is already a favicon bitmap of |pixel_size| at |icon_url|,
1805  // replace it.
1806  bool bitmap_identical = false;
1807  bool replaced_bitmap = false;
1808  for (size_t i = 0; i < bitmap_id_sizes.size(); ++i) {
1809    if (bitmap_id_sizes[i].pixel_size == pixel_size) {
1810      if (IsFaviconBitmapDataEqual(bitmap_id_sizes[i].bitmap_id, bitmap_data)) {
1811        thumbnail_db_->SetFaviconBitmapLastUpdateTime(
1812            bitmap_id_sizes[i].bitmap_id, base::Time::Now());
1813        bitmap_identical = true;
1814      } else {
1815        thumbnail_db_->SetFaviconBitmap(bitmap_id_sizes[i].bitmap_id,
1816            bitmap_data, base::Time::Now());
1817        replaced_bitmap = true;
1818      }
1819      break;
1820    }
1821  }
1822
1823  // Create a vector of the pixel sizes of the favicon bitmaps currently at
1824  // |icon_url|.
1825  std::vector<gfx::Size> favicon_sizes;
1826  for (size_t i = 0; i < bitmap_id_sizes.size(); ++i)
1827    favicon_sizes.push_back(bitmap_id_sizes[i].pixel_size);
1828
1829  if (!replaced_bitmap && !bitmap_identical) {
1830    // Set the preexisting favicon bitmaps as expired as the preexisting favicon
1831    // bitmaps are not consistent with the merged in data.
1832    thumbnail_db_->SetFaviconOutOfDate(favicon_id);
1833
1834    // Delete an arbitrary favicon bitmap to avoid going over the limit of
1835    // |kMaxFaviconBitmapsPerIconURL|.
1836    if (bitmap_id_sizes.size() >= kMaxFaviconBitmapsPerIconURL) {
1837      thumbnail_db_->DeleteFaviconBitmap(bitmap_id_sizes[0].bitmap_id);
1838      favicon_sizes.erase(favicon_sizes.begin());
1839    }
1840    thumbnail_db_->AddFaviconBitmap(favicon_id, bitmap_data, base::Time::Now(),
1841                                    pixel_size);
1842    favicon_sizes.push_back(pixel_size);
1843  }
1844
1845  // A site may have changed the favicons that it uses for |page_url|.
1846  // Example Scenario:
1847  //   page_url = news.google.com
1848  //   Initial State: www.google.com/favicon.ico 16x16, 32x32
1849  //   MergeFavicon(news.google.com, news.google.com/news_specific.ico, ...,
1850  //                ..., 16x16)
1851  //
1852  // Difficulties:
1853  // 1. Sync requires that a call to GetFaviconsForURL() returns the
1854  //    |bitmap_data| passed into MergeFavicon().
1855  //    - It is invalid for the 16x16 bitmap for www.google.com/favicon.ico to
1856  //      stay mapped to news.google.com because it would be unclear which 16x16
1857  //      bitmap should be returned via GetFaviconsForURL().
1858  //
1859  // 2. www.google.com/favicon.ico may be mapped to more than just
1860  //    news.google.com (eg www.google.com).
1861  //    - The 16x16 bitmap cannot be deleted from www.google.com/favicon.ico
1862  //
1863  // To resolve these problems, we copy all of the favicon bitmaps previously
1864  // mapped to news.google.com (|page_url|) and add them to the favicon at
1865  // news.google.com/news_specific.ico (|icon_url|). The favicon sizes for
1866  // |icon_url| are set to default to indicate that |icon_url| has incomplete
1867  // / incorrect data.
1868  // Difficulty 1: All but news.google.com/news_specific.ico are unmapped from
1869  //              news.google.com
1870  // Difficulty 2: The favicon bitmaps for www.google.com/favicon.ico are not
1871  //               modified.
1872
1873  std::vector<IconMapping> icon_mappings;
1874  thumbnail_db_->GetIconMappingsForPageURL(page_url, icon_type, &icon_mappings);
1875
1876  // Copy the favicon bitmaps mapped to |page_url| to the favicon at |icon_url|
1877  // till the limit of |kMaxFaviconBitmapsPerIconURL| is reached.
1878  for (size_t i = 0; i < icon_mappings.size(); ++i) {
1879    if (favicon_sizes.size() >= kMaxFaviconBitmapsPerIconURL)
1880      break;
1881
1882    if (icon_mappings[i].icon_url == icon_url)
1883      continue;
1884
1885    std::vector<FaviconBitmap> bitmaps_to_copy;
1886    thumbnail_db_->GetFaviconBitmaps(icon_mappings[i].icon_id,
1887                                     &bitmaps_to_copy);
1888    for (size_t j = 0; j < bitmaps_to_copy.size(); ++j) {
1889      // Do not add a favicon bitmap at a pixel size for which there is already
1890      // a favicon bitmap mapped to |icon_url|. The one there is more correct
1891      // and having multiple equally sized favicon bitmaps for |page_url| is
1892      // ambiguous in terms of GetFaviconsForURL().
1893      std::vector<gfx::Size>::iterator it = std::find(favicon_sizes.begin(),
1894          favicon_sizes.end(), bitmaps_to_copy[j].pixel_size);
1895      if (it != favicon_sizes.end())
1896        continue;
1897
1898      // Add the favicon bitmap as expired as it is not consistent with the
1899      // merged in data.
1900      thumbnail_db_->AddFaviconBitmap(favicon_id,
1901          bitmaps_to_copy[j].bitmap_data, base::Time(),
1902          bitmaps_to_copy[j].pixel_size);
1903      favicon_sizes.push_back(bitmaps_to_copy[j].pixel_size);
1904
1905      if (favicon_sizes.size() >= kMaxFaviconBitmapsPerIconURL)
1906        break;
1907    }
1908  }
1909
1910  // Update the favicon mappings such that only |icon_url| is mapped to
1911  // |page_url|.
1912  bool mapping_changed = false;
1913  if (icon_mappings.size() != 1 || icon_mappings[0].icon_url != icon_url) {
1914    std::vector<chrome::FaviconID> favicon_ids;
1915    favicon_ids.push_back(favicon_id);
1916    SetFaviconMappingsForPageAndRedirects(page_url, icon_type, favicon_ids);
1917    mapping_changed = true;
1918  }
1919
1920  if (mapping_changed || !bitmap_identical)
1921    SendFaviconChangedNotificationForPageAndRedirects(page_url);
1922  ScheduleCommit();
1923}
1924
1925void HistoryBackend::SetFavicons(
1926    const GURL& page_url,
1927    chrome::IconType icon_type,
1928    const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data) {
1929  if (!thumbnail_db_ || !db_)
1930    return;
1931
1932  DCHECK(ValidateSetFaviconsParams(favicon_bitmap_data));
1933
1934  // Build map of FaviconBitmapData for each icon url.
1935  typedef std::map<GURL, std::vector<chrome::FaviconBitmapData> >
1936      BitmapDataByIconURL;
1937  BitmapDataByIconURL grouped_by_icon_url;
1938  for (size_t i = 0; i < favicon_bitmap_data.size(); ++i) {
1939    const GURL& icon_url = favicon_bitmap_data[i].icon_url;
1940    grouped_by_icon_url[icon_url].push_back(favicon_bitmap_data[i]);
1941  }
1942
1943  // Track whether the method modifies or creates any favicon bitmaps, favicons
1944  // or icon mappings.
1945  bool data_modified = false;
1946
1947  std::vector<chrome::FaviconID> icon_ids;
1948  for (BitmapDataByIconURL::const_iterator it = grouped_by_icon_url.begin();
1949       it != grouped_by_icon_url.end(); ++it) {
1950    const GURL& icon_url = it->first;
1951    chrome::FaviconID icon_id =
1952        thumbnail_db_->GetFaviconIDForFaviconURL(icon_url, icon_type, NULL);
1953
1954    if (!icon_id) {
1955      // TODO(pkotwicz): Remove the favicon sizes attribute from
1956      // ThumbnailDatabase::AddFavicon().
1957      icon_id = thumbnail_db_->AddFavicon(icon_url, icon_type);
1958      data_modified = true;
1959    }
1960    icon_ids.push_back(icon_id);
1961
1962    if (!data_modified)
1963      SetFaviconBitmaps(icon_id, it->second, &data_modified);
1964    else
1965      SetFaviconBitmaps(icon_id, it->second, NULL);
1966  }
1967
1968  data_modified |=
1969    SetFaviconMappingsForPageAndRedirects(page_url, icon_type, icon_ids);
1970
1971  if (data_modified) {
1972    // Send notification to the UI as an icon mapping, favicon, or favicon
1973    // bitmap was changed by this function.
1974    SendFaviconChangedNotificationForPageAndRedirects(page_url);
1975  }
1976  ScheduleCommit();
1977}
1978
1979void HistoryBackend::SetFaviconsOutOfDateForPage(const GURL& page_url) {
1980  std::vector<IconMapping> icon_mappings;
1981
1982  if (!thumbnail_db_ ||
1983      !thumbnail_db_->GetIconMappingsForPageURL(page_url,
1984                                                &icon_mappings))
1985    return;
1986
1987  for (std::vector<IconMapping>::iterator m = icon_mappings.begin();
1988       m != icon_mappings.end(); ++m) {
1989    thumbnail_db_->SetFaviconOutOfDate(m->icon_id);
1990  }
1991  ScheduleCommit();
1992}
1993
1994void HistoryBackend::CloneFavicons(const GURL& old_page_url,
1995                                   const GURL& new_page_url) {
1996  if (!thumbnail_db_)
1997    return;
1998
1999  // Prevent cross-domain cloning.
2000  if (old_page_url.GetOrigin() != new_page_url.GetOrigin())
2001    return;
2002
2003  thumbnail_db_->CloneIconMappings(old_page_url, new_page_url);
2004  ScheduleCommit();
2005}
2006
2007void HistoryBackend::SetImportedFavicons(
2008    const std::vector<ImportedFaviconUsage>& favicon_usage) {
2009  if (!db_ || !thumbnail_db_)
2010    return;
2011
2012  Time now = Time::Now();
2013
2014  // Track all URLs that had their favicons set or updated.
2015  std::set<GURL> favicons_changed;
2016
2017  for (size_t i = 0; i < favicon_usage.size(); i++) {
2018    chrome::FaviconID favicon_id = thumbnail_db_->GetFaviconIDForFaviconURL(
2019        favicon_usage[i].favicon_url, chrome::FAVICON, NULL);
2020    if (!favicon_id) {
2021      // This favicon doesn't exist yet, so we create it using the given data.
2022      // TODO(pkotwicz): Pass in real pixel size.
2023      favicon_id = thumbnail_db_->AddFavicon(
2024          favicon_usage[i].favicon_url,
2025          chrome::FAVICON,
2026          new base::RefCountedBytes(favicon_usage[i].png_data),
2027          now,
2028          gfx::Size());
2029    }
2030
2031    // Save the mapping from all the URLs to the favicon.
2032    BookmarkService* bookmark_service = GetBookmarkService();
2033    for (std::set<GURL>::const_iterator url = favicon_usage[i].urls.begin();
2034         url != favicon_usage[i].urls.end(); ++url) {
2035      URLRow url_row;
2036      if (!db_->GetRowForURL(*url, &url_row)) {
2037        // If the URL is present as a bookmark, add the url in history to
2038        // save the favicon mapping. This will match with what history db does
2039        // for regular bookmarked URLs with favicons - when history db is
2040        // cleaned, we keep an entry in the db with 0 visits as long as that
2041        // url is bookmarked.
2042        if (bookmark_service && bookmark_service_->IsBookmarked(*url)) {
2043          URLRow url_info(*url);
2044          url_info.set_visit_count(0);
2045          url_info.set_typed_count(0);
2046          url_info.set_last_visit(base::Time());
2047          url_info.set_hidden(false);
2048          db_->AddURL(url_info);
2049          thumbnail_db_->AddIconMapping(*url, favicon_id);
2050          favicons_changed.insert(*url);
2051        }
2052      } else {
2053        if (!thumbnail_db_->GetIconMappingsForPageURL(
2054                *url, chrome::FAVICON, NULL)) {
2055          // URL is present in history, update the favicon *only* if it is not
2056          // set already.
2057          thumbnail_db_->AddIconMapping(*url, favicon_id);
2058          favicons_changed.insert(*url);
2059        }
2060      }
2061    }
2062  }
2063
2064  if (!favicons_changed.empty()) {
2065    // Send the notification about the changed favicon URLs.
2066    FaviconChangedDetails* changed_details = new FaviconChangedDetails;
2067    changed_details->urls.swap(favicons_changed);
2068    BroadcastNotifications(chrome::NOTIFICATION_FAVICON_CHANGED,
2069                           changed_details);
2070  }
2071}
2072
2073void HistoryBackend::UpdateFaviconMappingsAndFetchImpl(
2074    const GURL* page_url,
2075    const std::vector<GURL>& icon_urls,
2076    int icon_types,
2077    int desired_size_in_dip,
2078    const std::vector<ui::ScaleFactor>& desired_scale_factors,
2079    std::vector<chrome::FaviconBitmapResult>* bitmap_results) {
2080  // If |page_url| is specified, |icon_types| must be either a single icon
2081  // type or icon types which are equivalent.
2082  DCHECK(!page_url ||
2083         icon_types == chrome::FAVICON ||
2084         icon_types == chrome::TOUCH_ICON ||
2085         icon_types == chrome::TOUCH_PRECOMPOSED_ICON ||
2086         icon_types == (chrome::TOUCH_ICON | chrome::TOUCH_PRECOMPOSED_ICON));
2087  bitmap_results->clear();
2088
2089  if (!thumbnail_db_) {
2090    return;
2091  }
2092
2093  std::vector<chrome::FaviconID> favicon_ids;
2094
2095  // The icon type for which the mappings will the updated and data will be
2096  // returned.
2097  chrome::IconType selected_icon_type = chrome::INVALID_ICON;
2098
2099  for (size_t i = 0; i < icon_urls.size(); ++i) {
2100    const GURL& icon_url = icon_urls[i];
2101    chrome::IconType icon_type_out;
2102    const chrome::FaviconID favicon_id =
2103        thumbnail_db_->GetFaviconIDForFaviconURL(
2104            icon_url, icon_types, &icon_type_out);
2105
2106    if (favicon_id) {
2107      // Return and update icon mappings only for the largest icon type. As
2108      // |icon_urls| is not sorted in terms of icon type, clear |favicon_ids|
2109      // if an |icon_url| with a larger icon type is found.
2110      if (icon_type_out > selected_icon_type) {
2111        selected_icon_type = icon_type_out;
2112        favicon_ids.clear();
2113      }
2114      if (icon_type_out == selected_icon_type)
2115        favicon_ids.push_back(favicon_id);
2116    }
2117  }
2118
2119  if (page_url && !favicon_ids.empty()) {
2120    bool mappings_updated =
2121        SetFaviconMappingsForPageAndRedirects(*page_url, selected_icon_type,
2122                                              favicon_ids);
2123    if (mappings_updated) {
2124      SendFaviconChangedNotificationForPageAndRedirects(*page_url);
2125      ScheduleCommit();
2126    }
2127  }
2128
2129  GetFaviconBitmapResultsForBestMatch(favicon_ids, desired_size_in_dip,
2130      desired_scale_factors, bitmap_results);
2131}
2132
2133void HistoryBackend::SetFaviconBitmaps(
2134    chrome::FaviconID icon_id,
2135    const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data,
2136    bool* favicon_bitmaps_changed) {
2137  if (favicon_bitmaps_changed)
2138    *favicon_bitmaps_changed = false;
2139
2140  std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
2141  thumbnail_db_->GetFaviconBitmapIDSizes(icon_id, &bitmap_id_sizes);
2142
2143  std::vector<chrome::FaviconBitmapData> to_add = favicon_bitmap_data;
2144
2145  for (size_t i = 0; i < bitmap_id_sizes.size(); ++i) {
2146    const gfx::Size& pixel_size = bitmap_id_sizes[i].pixel_size;
2147    std::vector<chrome::FaviconBitmapData>::iterator match_it = to_add.end();
2148    for (std::vector<chrome::FaviconBitmapData>::iterator it = to_add.begin();
2149         it != to_add.end(); ++it) {
2150      if (it->pixel_size == pixel_size) {
2151        match_it = it;
2152        break;
2153      }
2154    }
2155
2156    FaviconBitmapID bitmap_id = bitmap_id_sizes[i].bitmap_id;
2157    if (match_it == to_add.end()) {
2158      thumbnail_db_->DeleteFaviconBitmap(bitmap_id);
2159
2160      if (favicon_bitmaps_changed)
2161        *favicon_bitmaps_changed = true;
2162    } else {
2163      if (favicon_bitmaps_changed &&
2164          !*favicon_bitmaps_changed &&
2165          IsFaviconBitmapDataEqual(bitmap_id, match_it->bitmap_data)) {
2166        thumbnail_db_->SetFaviconBitmapLastUpdateTime(
2167            bitmap_id, base::Time::Now());
2168      } else {
2169        thumbnail_db_->SetFaviconBitmap(bitmap_id, match_it->bitmap_data,
2170            base::Time::Now());
2171
2172        if (favicon_bitmaps_changed)
2173          *favicon_bitmaps_changed = true;
2174      }
2175      to_add.erase(match_it);
2176    }
2177  }
2178
2179  for (size_t i = 0; i < to_add.size(); ++i) {
2180    thumbnail_db_->AddFaviconBitmap(icon_id, to_add[i].bitmap_data,
2181        base::Time::Now(), to_add[i].pixel_size);
2182
2183    if (favicon_bitmaps_changed)
2184      *favicon_bitmaps_changed = true;
2185  }
2186}
2187
2188bool HistoryBackend::ValidateSetFaviconsParams(
2189    const std::vector<chrome::FaviconBitmapData>& favicon_bitmap_data) const {
2190  typedef std::map<GURL, size_t> BitmapsPerIconURL;
2191  BitmapsPerIconURL num_bitmaps_per_icon_url;
2192  for (size_t i = 0; i < favicon_bitmap_data.size(); ++i) {
2193    if (!favicon_bitmap_data[i].bitmap_data.get())
2194      return false;
2195
2196    const GURL& icon_url = favicon_bitmap_data[i].icon_url;
2197    if (!num_bitmaps_per_icon_url.count(icon_url))
2198      num_bitmaps_per_icon_url[icon_url] = 1u;
2199    else
2200      ++num_bitmaps_per_icon_url[icon_url];
2201  }
2202
2203  if (num_bitmaps_per_icon_url.size() > kMaxFaviconsPerPage)
2204    return false;
2205
2206  for (BitmapsPerIconURL::const_iterator it = num_bitmaps_per_icon_url.begin();
2207       it != num_bitmaps_per_icon_url.end(); ++it) {
2208    if (it->second > kMaxFaviconBitmapsPerIconURL)
2209      return false;
2210  }
2211  return true;
2212}
2213
2214bool HistoryBackend::IsFaviconBitmapDataEqual(
2215    FaviconBitmapID bitmap_id,
2216    const scoped_refptr<base::RefCountedMemory>& new_bitmap_data) {
2217  if (!new_bitmap_data.get())
2218    return false;
2219
2220  scoped_refptr<base::RefCountedMemory> original_bitmap_data;
2221  thumbnail_db_->GetFaviconBitmap(bitmap_id,
2222                                  NULL,
2223                                  &original_bitmap_data,
2224                                  NULL);
2225  return new_bitmap_data->Equals(original_bitmap_data);
2226}
2227
2228bool HistoryBackend::GetFaviconsFromDB(
2229    const GURL& page_url,
2230    int icon_types,
2231    int desired_size_in_dip,
2232    const std::vector<ui::ScaleFactor>& desired_scale_factors,
2233    std::vector<chrome::FaviconBitmapResult>* favicon_bitmap_results) {
2234  DCHECK(favicon_bitmap_results);
2235  favicon_bitmap_results->clear();
2236
2237  if (!db_ || !thumbnail_db_)
2238    return false;
2239
2240  // Time the query.
2241  TimeTicks beginning_time = TimeTicks::Now();
2242
2243  // Get FaviconIDs for |page_url| and one of |icon_types|.
2244  std::vector<IconMapping> icon_mappings;
2245  thumbnail_db_->GetIconMappingsForPageURL(page_url, icon_types,
2246                                           &icon_mappings);
2247  std::vector<chrome::FaviconID> favicon_ids;
2248  for (size_t i = 0; i < icon_mappings.size(); ++i)
2249    favicon_ids.push_back(icon_mappings[i].icon_id);
2250
2251  // Populate |favicon_bitmap_results| and |icon_url_sizes|.
2252  bool success = GetFaviconBitmapResultsForBestMatch(favicon_ids,
2253      desired_size_in_dip, desired_scale_factors, favicon_bitmap_results);
2254  UMA_HISTOGRAM_TIMES("History.GetFavIconFromDB",  // historical name
2255                      TimeTicks::Now() - beginning_time);
2256  return success && !favicon_bitmap_results->empty();
2257}
2258
2259bool HistoryBackend::GetFaviconBitmapResultsForBestMatch(
2260    const std::vector<chrome::FaviconID>& candidate_favicon_ids,
2261    int desired_size_in_dip,
2262    const std::vector<ui::ScaleFactor>& desired_scale_factors,
2263    std::vector<chrome::FaviconBitmapResult>* favicon_bitmap_results) {
2264  favicon_bitmap_results->clear();
2265
2266  if (candidate_favicon_ids.empty())
2267    return true;
2268
2269  // Find the FaviconID and the FaviconBitmapIDs which best match
2270  // |desired_size_in_dip| and |desired_scale_factors|.
2271  // TODO(pkotwicz): Select bitmap results from multiple favicons once
2272  // content::FaviconStatus supports multiple icon URLs.
2273  chrome::FaviconID best_favicon_id = 0;
2274  std::vector<FaviconBitmapID> best_bitmap_ids;
2275  float highest_score = kSelectFaviconFramesInvalidScore;
2276  for (size_t i = 0; i < candidate_favicon_ids.size(); ++i) {
2277    std::vector<FaviconBitmapIDSize> bitmap_id_sizes;
2278    thumbnail_db_->GetFaviconBitmapIDSizes(candidate_favicon_ids[i],
2279                                           &bitmap_id_sizes);
2280
2281    // Build vector of gfx::Size from |bitmap_id_sizes|.
2282    std::vector<gfx::Size> sizes;
2283    for (size_t j = 0; j < bitmap_id_sizes.size(); ++j)
2284      sizes.push_back(bitmap_id_sizes[j].pixel_size);
2285
2286    std::vector<size_t> candidate_bitmap_indices;
2287    float score = 0;
2288    SelectFaviconFrameIndices(sizes,
2289                              desired_scale_factors,
2290                              desired_size_in_dip,
2291                              &candidate_bitmap_indices,
2292                              &score);
2293    if (score > highest_score) {
2294      highest_score = score;
2295      best_favicon_id = candidate_favicon_ids[i],
2296      best_bitmap_ids.clear();
2297      for (size_t j = 0; j < candidate_bitmap_indices.size(); ++j) {
2298        size_t candidate_index = candidate_bitmap_indices[j];
2299        best_bitmap_ids.push_back(
2300            bitmap_id_sizes[candidate_index].bitmap_id);
2301      }
2302    }
2303  }
2304
2305  // Construct FaviconBitmapResults from |best_favicon_id| and
2306  // |best_bitmap_ids|.
2307  GURL icon_url;
2308  chrome::IconType icon_type;
2309  if (!thumbnail_db_->GetFaviconHeader(best_favicon_id, &icon_url,
2310                                       &icon_type)) {
2311    return false;
2312  }
2313
2314  for (size_t i = 0; i < best_bitmap_ids.size(); ++i) {
2315    base::Time last_updated;
2316    chrome::FaviconBitmapResult bitmap_result;
2317    bitmap_result.icon_url = icon_url;
2318    bitmap_result.icon_type = icon_type;
2319    if (!thumbnail_db_->GetFaviconBitmap(best_bitmap_ids[i],
2320                                         &last_updated,
2321                                         &bitmap_result.bitmap_data,
2322                                         &bitmap_result.pixel_size)) {
2323      return false;
2324    }
2325
2326    bitmap_result.expired = (Time::Now() - last_updated) >
2327        TimeDelta::FromDays(kFaviconRefetchDays);
2328    if (bitmap_result.is_valid())
2329      favicon_bitmap_results->push_back(bitmap_result);
2330  }
2331  return true;
2332}
2333
2334bool HistoryBackend::SetFaviconMappingsForPageAndRedirects(
2335    const GURL& page_url,
2336    chrome::IconType icon_type,
2337    const std::vector<chrome::FaviconID>& icon_ids) {
2338  if (!thumbnail_db_)
2339    return false;
2340
2341  // Find all the pages whose favicons we should set, we want to set it for
2342  // all the pages in the redirect chain if it redirected.
2343  history::RedirectList redirects;
2344  GetCachedRecentRedirects(page_url, &redirects);
2345
2346  bool mappings_changed = false;
2347
2348  // Save page <-> favicon associations.
2349  for (history::RedirectList::const_iterator i(redirects.begin());
2350       i != redirects.end(); ++i) {
2351    mappings_changed |= SetFaviconMappingsForPage(*i, icon_type, icon_ids);
2352  }
2353  return mappings_changed;
2354}
2355
2356bool HistoryBackend::SetFaviconMappingsForPage(
2357    const GURL& page_url,
2358    chrome::IconType icon_type,
2359    const std::vector<chrome::FaviconID>& icon_ids) {
2360  DCHECK_LE(icon_ids.size(), kMaxFaviconsPerPage);
2361  bool mappings_changed = false;
2362
2363  // Two icon types are considered 'equivalent' if one of the icon types is
2364  // TOUCH_ICON and the other is TOUCH_PRECOMPOSED_ICON.
2365  //
2366  // Sets the icon mappings from |page_url| for |icon_type| to the favicons
2367  // with |icon_ids|. Mappings for |page_url| to favicons of type |icon_type|
2368  // whose FaviconID is not in |icon_ids| are removed. All icon mappings for
2369  // |page_url| to favicons of a type equivalent to |icon_type| are removed.
2370  // Remove any favicons which are orphaned as a result of the removal of the
2371  // icon mappings.
2372
2373  std::vector<chrome::FaviconID> unmapped_icon_ids = icon_ids;
2374
2375  std::vector<IconMapping> icon_mappings;
2376  thumbnail_db_->GetIconMappingsForPageURL(page_url, &icon_mappings);
2377
2378  for (std::vector<IconMapping>::iterator m = icon_mappings.begin();
2379       m != icon_mappings.end(); ++m) {
2380    std::vector<chrome::FaviconID>::iterator icon_id_it = std::find(
2381        unmapped_icon_ids.begin(), unmapped_icon_ids.end(), m->icon_id);
2382
2383    // If the icon mapping already exists, avoid removing it and adding it back.
2384    if (icon_id_it != unmapped_icon_ids.end()) {
2385      unmapped_icon_ids.erase(icon_id_it);
2386      continue;
2387    }
2388
2389    if ((icon_type == chrome::TOUCH_ICON &&
2390         m->icon_type == chrome::TOUCH_PRECOMPOSED_ICON) ||
2391        (icon_type == chrome::TOUCH_PRECOMPOSED_ICON &&
2392         m->icon_type == chrome::TOUCH_ICON) || (icon_type == m->icon_type)) {
2393      thumbnail_db_->DeleteIconMapping(m->mapping_id);
2394
2395      // Removing the icon mapping may have orphaned the associated favicon so
2396      // we must recheck it. This is not super fast, but this case will get
2397      // triggered rarely, since normally a page will always map to the same
2398      // favicon IDs. It will mostly happen for favicons we import.
2399      if (!thumbnail_db_->HasMappingFor(m->icon_id))
2400        thumbnail_db_->DeleteFavicon(m->icon_id);
2401      mappings_changed = true;
2402    }
2403  }
2404
2405  for (size_t i = 0; i < unmapped_icon_ids.size(); ++i) {
2406    thumbnail_db_->AddIconMapping(page_url, unmapped_icon_ids[i]);
2407    mappings_changed = true;
2408  }
2409  return mappings_changed;
2410}
2411
2412void HistoryBackend::GetCachedRecentRedirects(
2413    const GURL& page_url,
2414    history::RedirectList* redirect_list) {
2415  RedirectCache::iterator iter = recent_redirects_.Get(page_url);
2416  if (iter != recent_redirects_.end()) {
2417    *redirect_list = iter->second;
2418
2419    // The redirect chain should have the destination URL as the last item.
2420    DCHECK(!redirect_list->empty());
2421    DCHECK(redirect_list->back() == page_url);
2422  } else {
2423    // No known redirects, construct mock redirect chain containing |page_url|.
2424    redirect_list->push_back(page_url);
2425  }
2426}
2427
2428void HistoryBackend::SendFaviconChangedNotificationForPageAndRedirects(
2429    const GURL& page_url) {
2430  history::RedirectList redirect_list;
2431  GetCachedRecentRedirects(page_url, &redirect_list);
2432
2433  FaviconChangedDetails* changed_details = new FaviconChangedDetails;
2434  for (size_t i = 0; i < redirect_list.size(); ++i)
2435    changed_details->urls.insert(redirect_list[i]);
2436
2437  BroadcastNotifications(chrome::NOTIFICATION_FAVICON_CHANGED,
2438                         changed_details);
2439}
2440
2441void HistoryBackend::Commit() {
2442  if (!db_)
2443    return;
2444
2445  // Note that a commit may not actually have been scheduled if a caller
2446  // explicitly calls this instead of using ScheduleCommit. Likewise, we
2447  // may reset the flag written by a pending commit. But this is OK! It
2448  // will merely cause extra commits (which is kind of the idea). We
2449  // could optimize more for this case (we may get two extra commits in
2450  // some cases) but it hasn't been important yet.
2451  CancelScheduledCommit();
2452
2453  db_->CommitTransaction();
2454  DCHECK(db_->transaction_nesting() == 0) << "Somebody left a transaction open";
2455  db_->BeginTransaction();
2456
2457  if (thumbnail_db_) {
2458    thumbnail_db_->CommitTransaction();
2459    DCHECK(thumbnail_db_->transaction_nesting() == 0) <<
2460        "Somebody left a transaction open";
2461    thumbnail_db_->BeginTransaction();
2462  }
2463
2464  if (archived_db_) {
2465    archived_db_->CommitTransaction();
2466    archived_db_->BeginTransaction();
2467  }
2468}
2469
2470void HistoryBackend::ScheduleCommit() {
2471  if (scheduled_commit_.get())
2472    return;
2473  scheduled_commit_ = new CommitLaterTask(this);
2474  base::MessageLoop::current()->PostDelayedTask(
2475      FROM_HERE,
2476      base::Bind(&CommitLaterTask::RunCommit, scheduled_commit_.get()),
2477      base::TimeDelta::FromSeconds(kCommitIntervalSeconds));
2478}
2479
2480void HistoryBackend::CancelScheduledCommit() {
2481  if (scheduled_commit_.get()) {
2482    scheduled_commit_->Cancel();
2483    scheduled_commit_ = NULL;
2484  }
2485}
2486
2487void HistoryBackend::ProcessDBTaskImpl() {
2488  if (!db_) {
2489    // db went away, release all the refs.
2490    ReleaseDBTasks();
2491    return;
2492  }
2493
2494  // Remove any canceled tasks.
2495  while (!db_task_requests_.empty() && db_task_requests_.front()->canceled()) {
2496    db_task_requests_.front()->Release();
2497    db_task_requests_.pop_front();
2498  }
2499  if (db_task_requests_.empty())
2500    return;
2501
2502  // Run the first task.
2503  HistoryDBTaskRequest* request = db_task_requests_.front();
2504  db_task_requests_.pop_front();
2505  if (request->value->RunOnDBThread(this, db_.get())) {
2506    // The task is done. Notify the callback.
2507    request->ForwardResult();
2508    // We AddRef'd the request before adding, need to release it now.
2509    request->Release();
2510  } else {
2511    // Tasks wants to run some more. Schedule it at the end of current tasks.
2512    db_task_requests_.push_back(request);
2513    // And process it after an invoke later.
2514    base::MessageLoop::current()->PostTask(
2515        FROM_HERE, base::Bind(&HistoryBackend::ProcessDBTaskImpl, this));
2516  }
2517}
2518
2519void HistoryBackend::ReleaseDBTasks() {
2520  for (std::list<HistoryDBTaskRequest*>::iterator i =
2521       db_task_requests_.begin(); i != db_task_requests_.end(); ++i) {
2522    (*i)->Release();
2523  }
2524  db_task_requests_.clear();
2525}
2526
2527////////////////////////////////////////////////////////////////////////////////
2528//
2529// Generic operations
2530//
2531////////////////////////////////////////////////////////////////////////////////
2532
2533void HistoryBackend::DeleteURLs(const std::vector<GURL>& urls) {
2534  expirer_.DeleteURLs(urls);
2535
2536  db_->GetStartDate(&first_recorded_time_);
2537  // Force a commit, if the user is deleting something for privacy reasons, we
2538  // want to get it on disk ASAP.
2539  Commit();
2540}
2541
2542void HistoryBackend::DeleteURL(const GURL& url) {
2543  expirer_.DeleteURL(url);
2544
2545  db_->GetStartDate(&first_recorded_time_);
2546  // Force a commit, if the user is deleting something for privacy reasons, we
2547  // want to get it on disk ASAP.
2548  Commit();
2549}
2550
2551void HistoryBackend::ExpireHistoryBetween(
2552    const std::set<GURL>& restrict_urls,
2553    Time begin_time,
2554    Time end_time) {
2555  if (!db_)
2556    return;
2557
2558  if (begin_time.is_null() && (end_time.is_null() || end_time.is_max()) &&
2559      restrict_urls.empty()) {
2560    // Special case deleting all history so it can be faster and to reduce the
2561    // possibility of an information leak.
2562    DeleteAllHistory();
2563  } else {
2564    // Clearing parts of history, have the expirer do the depend
2565    expirer_.ExpireHistoryBetween(restrict_urls, begin_time, end_time);
2566
2567    // Force a commit, if the user is deleting something for privacy reasons,
2568    // we want to get it on disk ASAP.
2569    Commit();
2570  }
2571
2572  if (begin_time <= first_recorded_time_)
2573    db_->GetStartDate(&first_recorded_time_);
2574}
2575
2576void HistoryBackend::ExpireHistoryForTimes(
2577    const std::set<base::Time>& times,
2578    base::Time begin_time, base::Time end_time) {
2579  if (times.empty() || !db_)
2580    return;
2581
2582  DCHECK(*times.begin() >= begin_time)
2583      << "Min time is before begin time: "
2584      << times.begin()->ToJsTime() << " v.s. " << begin_time.ToJsTime();
2585  DCHECK(*times.rbegin() < end_time)
2586      << "Max time is after end time: "
2587      << times.rbegin()->ToJsTime() << " v.s. " << end_time.ToJsTime();
2588
2589  history::QueryOptions options;
2590  options.begin_time = begin_time;
2591  options.end_time = end_time;
2592  options.duplicate_policy = QueryOptions::KEEP_ALL_DUPLICATES;
2593  QueryResults results;
2594  QueryHistoryBasic(db_.get(), db_.get(), options, &results);
2595
2596  // 1st pass: find URLs that are visited at one of |times|.
2597  std::set<GURL> urls;
2598  for (size_t i = 0; i < results.size(); ++i) {
2599    if (times.count(results[i].visit_time()) > 0)
2600      urls.insert(results[i].url());
2601  }
2602  if (urls.empty())
2603    return;
2604
2605  // 2nd pass: collect all visit times of those URLs.
2606  std::vector<base::Time> times_to_expire;
2607  for (size_t i = 0; i < results.size(); ++i) {
2608    if (urls.count(results[i].url()))
2609      times_to_expire.push_back(results[i].visit_time());
2610  }
2611
2612  // Put the times in reverse chronological order and remove
2613  // duplicates (for expirer_.ExpireHistoryForTimes()).
2614  std::sort(times_to_expire.begin(), times_to_expire.end(),
2615            std::greater<base::Time>());
2616  times_to_expire.erase(
2617      std::unique(times_to_expire.begin(), times_to_expire.end()),
2618      times_to_expire.end());
2619
2620  // Expires by times and commit.
2621  DCHECK(!times_to_expire.empty());
2622  expirer_.ExpireHistoryForTimes(times_to_expire);
2623  Commit();
2624
2625  DCHECK(times_to_expire.back() >= first_recorded_time_);
2626  // Update |first_recorded_time_| if we expired it.
2627  if (times_to_expire.back() == first_recorded_time_)
2628    db_->GetStartDate(&first_recorded_time_);
2629}
2630
2631void HistoryBackend::ExpireHistory(
2632    const std::vector<history::ExpireHistoryArgs>& expire_list) {
2633  if (db_) {
2634    bool update_first_recorded_time = false;
2635
2636    for (std::vector<history::ExpireHistoryArgs>::const_iterator it =
2637         expire_list.begin(); it != expire_list.end(); ++it) {
2638      expirer_.ExpireHistoryBetween(it->urls, it->begin_time, it->end_time);
2639
2640      if (it->begin_time < first_recorded_time_)
2641        update_first_recorded_time = true;
2642    }
2643    Commit();
2644
2645    // Update |first_recorded_time_| if any deletion might have affected it.
2646    if (update_first_recorded_time)
2647      db_->GetStartDate(&first_recorded_time_);
2648  }
2649}
2650
2651void HistoryBackend::URLsNoLongerBookmarked(const std::set<GURL>& urls) {
2652  if (!db_)
2653    return;
2654
2655  for (std::set<GURL>::const_iterator i = urls.begin(); i != urls.end(); ++i) {
2656    URLRow url_row;
2657    if (!db_->GetRowForURL(*i, &url_row))
2658      continue;  // The URL isn't in the db; nothing to do.
2659
2660    VisitVector visits;
2661    db_->GetVisitsForURL(url_row.id(), &visits);
2662
2663    if (visits.empty())
2664      expirer_.DeleteURL(*i);  // There are no more visits; nuke the URL.
2665  }
2666}
2667
2668void HistoryBackend::DatabaseErrorCallback(int error, sql::Statement* stmt) {
2669  if (!scheduled_kill_db_ && sql::IsErrorCatastrophic(error)) {
2670    scheduled_kill_db_ = true;
2671    // Don't just do the close/delete here, as we are being called by |db| and
2672    // that seems dangerous.
2673    // TODO(shess): Consider changing KillHistoryDatabase() to use
2674    // RazeAndClose().  Then it can be cleared immediately.
2675    base::MessageLoop::current()->PostTask(
2676        FROM_HERE,
2677        base::Bind(&HistoryBackend::KillHistoryDatabase, this));
2678  }
2679}
2680
2681void HistoryBackend::KillHistoryDatabase() {
2682  scheduled_kill_db_ = false;
2683  if (!db_)
2684    return;
2685
2686  // Rollback transaction because Raze() cannot be called from within a
2687  // transaction.
2688  db_->RollbackTransaction();
2689  bool success = db_->Raze();
2690  UMA_HISTOGRAM_BOOLEAN("History.KillHistoryDatabaseResult", success);
2691
2692#if defined(OS_ANDROID)
2693  // Release AndroidProviderBackend before other objects.
2694  android_provider_backend_.reset();
2695#endif
2696
2697  // The expirer keeps tabs on the active databases. Tell it about the
2698  // databases which will be closed.
2699  expirer_.SetDatabases(NULL, NULL, NULL);
2700
2701  // Reopen a new transaction for |db_| for the sake of CloseAllDatabases().
2702  db_->BeginTransaction();
2703  CloseAllDatabases();
2704}
2705
2706void HistoryBackend::ProcessDBTask(
2707    scoped_refptr<HistoryDBTaskRequest> request) {
2708  DCHECK(request.get());
2709  if (request->canceled())
2710    return;
2711
2712  bool task_scheduled = !db_task_requests_.empty();
2713  // Make sure we up the refcount of the request. ProcessDBTaskImpl will
2714  // release when done with the task.
2715  request->AddRef();
2716  db_task_requests_.push_back(request.get());
2717  if (!task_scheduled) {
2718    // No other tasks are scheduled. Process request now.
2719    ProcessDBTaskImpl();
2720  }
2721}
2722
2723void HistoryBackend::BroadcastNotifications(
2724    int type,
2725    HistoryDetails* details_deleted) {
2726  // |delegate_| may be NULL if |this| is in the process of closing (closed by
2727  // HistoryService -> HistoryBackend::Closing().
2728  if (delegate_)
2729    delegate_->BroadcastNotifications(type, details_deleted);
2730  else
2731    delete details_deleted;
2732}
2733
2734void HistoryBackend::NotifySyncURLsDeleted(bool all_history,
2735                                           bool archived,
2736                                           URLRows* rows) {
2737  if (typed_url_syncable_service_.get())
2738    typed_url_syncable_service_->OnUrlsDeleted(all_history, archived, rows);
2739}
2740
2741// Deleting --------------------------------------------------------------------
2742
2743void HistoryBackend::DeleteAllHistory() {
2744  // Our approach to deleting all history is:
2745  //  1. Copy the bookmarks and their dependencies to new tables with temporary
2746  //     names.
2747  //  2. Delete the original tables. Since tables can not share pages, we know
2748  //     that any data we don't want to keep is now in an unused page.
2749  //  3. Renaming the temporary tables to match the original.
2750  //  4. Vacuuming the database to delete the unused pages.
2751  //
2752  // Since we are likely to have very few bookmarks and their dependencies
2753  // compared to all history, this is also much faster than just deleting from
2754  // the original tables directly.
2755
2756  // Get the bookmarked URLs.
2757  std::vector<BookmarkService::URLAndTitle> starred_urls;
2758  BookmarkService* bookmark_service = GetBookmarkService();
2759  if (bookmark_service)
2760    bookmark_service_->GetBookmarks(&starred_urls);
2761
2762  URLRows kept_urls;
2763  for (size_t i = 0; i < starred_urls.size(); i++) {
2764    URLRow row;
2765    if (!db_->GetRowForURL(starred_urls[i].url, &row))
2766      continue;
2767
2768    // Clear the last visit time so when we write these rows they are "clean."
2769    row.set_last_visit(Time());
2770    row.set_visit_count(0);
2771    row.set_typed_count(0);
2772    kept_urls.push_back(row);
2773  }
2774
2775  // Clear thumbnail and favicon history. The favicons for the given URLs will
2776  // be kept.
2777  if (!ClearAllThumbnailHistory(kept_urls)) {
2778    LOG(ERROR) << "Thumbnail history could not be cleared";
2779    // We continue in this error case. If the user wants to delete their
2780    // history, we should delete as much as we can.
2781  }
2782
2783  // ClearAllMainHistory will change the IDs of the URLs in kept_urls.
2784  // Therefore, we clear the list afterwards to make sure nobody uses this
2785  // invalid data.
2786  if (!ClearAllMainHistory(kept_urls))
2787    LOG(ERROR) << "Main history could not be cleared";
2788  kept_urls.clear();
2789
2790  // Delete archived history.
2791  if (archived_db_) {
2792    // Close the database and delete the file.
2793    archived_db_.reset();
2794    base::FilePath archived_file_name = GetArchivedFileName();
2795    sql::Connection::Delete(archived_file_name);
2796
2797    // Now re-initialize the database (which may fail).
2798    archived_db_.reset(new ArchivedDatabase());
2799    if (!archived_db_->Init(archived_file_name)) {
2800      LOG(WARNING) << "Could not initialize the archived database.";
2801      archived_db_.reset();
2802    } else {
2803      // Open our long-running transaction on this database.
2804      archived_db_->BeginTransaction();
2805    }
2806  }
2807
2808  db_->GetStartDate(&first_recorded_time_);
2809
2810  // Send out the notification that history is cleared. The in-memory database
2811  // will pick this up and clear itself.
2812  URLsDeletedDetails* details = new URLsDeletedDetails;
2813  details->all_history = true;
2814  NotifySyncURLsDeleted(true, false, NULL);
2815  BroadcastNotifications(chrome::NOTIFICATION_HISTORY_URLS_DELETED, details);
2816}
2817
2818bool HistoryBackend::ClearAllThumbnailHistory(const URLRows& kept_urls) {
2819  if (!thumbnail_db_) {
2820    // When we have no reference to the thumbnail database, maybe there was an
2821    // error opening it. In this case, we just try to blow it away to try to
2822    // fix the error if it exists. This may fail, in which case either the
2823    // file doesn't exist or there's no more we can do.
2824    sql::Connection::Delete(GetFaviconsFileName());
2825
2826    // Older version of the database.
2827    sql::Connection::Delete(GetThumbnailFileName());
2828    return true;
2829  }
2830
2831  // Urls to retain mappings for.
2832  std::vector<GURL> urls_to_keep;
2833  for (URLRows::const_iterator i = kept_urls.begin();
2834       i != kept_urls.end(); ++i) {
2835    urls_to_keep.push_back(i->url());
2836  }
2837
2838  // Isolate from any long-running transaction.
2839  thumbnail_db_->CommitTransaction();
2840  thumbnail_db_->BeginTransaction();
2841
2842  // TODO(shess): If this fails, perhaps the database should be razed
2843  // or deleted.
2844  if (!thumbnail_db_->RetainDataForPageUrls(urls_to_keep)) {
2845    thumbnail_db_->RollbackTransaction();
2846    thumbnail_db_->BeginTransaction();
2847    return false;
2848  }
2849
2850#if defined(OS_ANDROID)
2851  // TODO (michaelbai): Add the unit test once AndroidProviderBackend is
2852  // avaliable in HistoryBackend.
2853  db_->ClearAndroidURLRows();
2854#endif
2855
2856  // Vacuum to remove all the pages associated with the dropped tables. There
2857  // must be no transaction open on the table when we do this. We assume that
2858  // our long-running transaction is open, so we complete it and start it again.
2859  DCHECK(thumbnail_db_->transaction_nesting() == 1);
2860  thumbnail_db_->CommitTransaction();
2861  thumbnail_db_->Vacuum();
2862  thumbnail_db_->BeginTransaction();
2863  return true;
2864}
2865
2866bool HistoryBackend::ClearAllMainHistory(const URLRows& kept_urls) {
2867  // Create the duplicate URL table. We will copy the kept URLs into this.
2868  if (!db_->CreateTemporaryURLTable())
2869    return false;
2870
2871  // Insert the URLs into the temporary table.
2872  for (URLRows::const_iterator i = kept_urls.begin(); i != kept_urls.end();
2873       ++i) {
2874    db_->AddTemporaryURL(*i);
2875  }
2876
2877  // Replace the original URL table with the temporary one.
2878  if (!db_->CommitTemporaryURLTable())
2879    return false;
2880
2881  // Delete the old tables and recreate them empty.
2882  db_->RecreateAllTablesButURL();
2883
2884  // Vacuum to reclaim the space from the dropped tables. This must be done
2885  // when there is no transaction open, and we assume that our long-running
2886  // transaction is currently open.
2887  db_->CommitTransaction();
2888  db_->Vacuum();
2889  db_->BeginTransaction();
2890  db_->GetStartDate(&first_recorded_time_);
2891
2892  return true;
2893}
2894
2895BookmarkService* HistoryBackend::GetBookmarkService() {
2896  if (bookmark_service_)
2897    bookmark_service_->BlockTillLoaded();
2898  return bookmark_service_;
2899}
2900
2901void HistoryBackend::NotifyVisitObservers(const VisitRow& visit) {
2902  BriefVisitInfo info;
2903  info.url_id = visit.url_id;
2904  info.time = visit.visit_time;
2905  info.transition = visit.transition;
2906  // If we don't have a delegate yet during setup or shutdown, we will drop
2907  // these notifications.
2908  if (delegate_)
2909    delegate_->NotifyVisitDBObserversOnAddVisit(info);
2910}
2911
2912#if defined(OS_ANDROID)
2913void HistoryBackend::PopulateMostVisitedURLMap() {
2914  MostVisitedURLList most_visited_urls;
2915  QueryMostVisitedURLsImpl(kPageVisitStatsMaxTopSites, kSegmentDataRetention,
2916                           &most_visited_urls);
2917
2918  DCHECK_LE(most_visited_urls.size(), kPageVisitStatsMaxTopSites);
2919  for (size_t i = 0; i < most_visited_urls.size(); ++i) {
2920    most_visited_urls_map_[most_visited_urls[i].url] = i;
2921    for (size_t j = 0; j < most_visited_urls[i].redirects.size(); ++j)
2922      most_visited_urls_map_[most_visited_urls[i].redirects[j]] = i;
2923  }
2924}
2925
2926void HistoryBackend::RecordTopPageVisitStats(const GURL& url) {
2927  int rank = kPageVisitStatsMaxTopSites;
2928  std::map<GURL, int>::const_iterator it = most_visited_urls_map_.find(url);
2929  if (it != most_visited_urls_map_.end())
2930    rank = (*it).second;
2931  UMA_HISTOGRAM_ENUMERATION("History.TopSitesVisitsByRank",
2932                            rank, kPageVisitStatsMaxTopSites + 1);
2933}
2934#endif
2935
2936}  // namespace history
2937