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.
5 #include "chrome/browser/ui/webui/history_ui.h"
10 #include "base/bind_helpers.h"
11 #include "base/command_line.h"
12 #include "base/i18n/rtl.h"
13 #include "base/i18n/time_formatting.h"
14 #include "base/memory/singleton.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/metrics/histogram.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "base/values.h"
23 #include "chrome/browser/banners/app_banner_settings_helper.h"
24 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/history/history_service.h"
27 #include "chrome/browser/history/history_service_factory.h"
28 #include "chrome/browser/history/web_history_service_factory.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/signin/signin_manager_factory.h"
31 #include "chrome/browser/sync/profile_sync_service.h"
32 #include "chrome/browser/sync/profile_sync_service_factory.h"
33 #include "chrome/browser/ui/browser_finder.h"
34 #include "chrome/browser/ui/chrome_pages.h"
35 #include "chrome/browser/ui/webui/favicon_source.h"
36 #include "chrome/browser/ui/webui/metrics_handler.h"
37 #include "chrome/common/chrome_switches.h"
38 #include "chrome/common/pref_names.h"
39 #include "chrome/common/url_constants.h"
40 #include "chrome/grit/generated_resources.h"
41 #include "components/bookmarks/browser/bookmark_model.h"
42 #include "components/bookmarks/browser/bookmark_utils.h"
43 #include "components/history/core/browser/history_types.h"
44 #include "components/history/core/browser/web_history_service.h"
45 #include "components/search/search.h"
46 #include "components/signin/core/browser/signin_manager.h"
47 #include "components/sync_driver/device_info.h"
48 #include "content/public/browser/url_data_source.h"
49 #include "content/public/browser/web_ui.h"
50 #include "content/public/browser/web_ui_data_source.h"
51 #include "grit/browser_resources.h"
52 #include "grit/theme_resources.h"
53 #include "net/base/escape.h"
54 #include "net/base/net_util.h"
55 #include "sync/protocol/history_delete_directive_specifics.pb.h"
56 #include "ui/base/l10n/l10n_util.h"
57 #include "ui/base/l10n/time_format.h"
58 #include "ui/base/resource/resource_bundle.h"
59 #include "ui/base/webui/web_ui_util.h"
61 #if defined(ENABLE_EXTENSIONS)
62 #include "chrome/browser/extensions/activity_log/activity_log.h"
65 #if defined(ENABLE_SUPERVISED_USERS)
66 #include "chrome/browser/supervised_user/supervised_user_navigation_observer.h"
67 #include "chrome/browser/supervised_user/supervised_user_service.h"
68 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
69 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
72 #if defined(OS_ANDROID)
73 #include "chrome/browser/android/chromium_application.h"
76 #if !defined(OS_ANDROID) && !defined(OS_IOS)
77 #include "chrome/browser/ui/webui/ntp/foreign_session_handler.h"
78 #include "chrome/browser/ui/webui/ntp/ntp_login_handler.h"
81 using bookmarks::BookmarkModel
;
83 static const char kStringsJsFile
[] = "strings.js";
84 static const char kHistoryJsFile
[] = "history.js";
85 static const char kOtherDevicesJsFile
[] = "other_devices.js";
87 // The amount of time to wait for a response from the WebHistoryService.
88 static const int kWebHistoryTimeoutSeconds
= 3;
92 // Buckets for UMA histograms.
93 enum WebHistoryQueryBuckets
{
94 WEB_HISTORY_QUERY_FAILED
= 0,
95 WEB_HISTORY_QUERY_SUCCEEDED
,
96 WEB_HISTORY_QUERY_TIMED_OUT
,
97 NUM_WEB_HISTORY_QUERY_BUCKETS
100 #if defined(OS_MACOSX)
101 const char kIncognitoModeShortcut
[] = "("
102 "\xE2\x87\xA7" // Shift symbol (U+21E7 'UPWARDS WHITE ARROW').
103 "\xE2\x8C\x98" // Command symbol (U+2318 'PLACE OF INTEREST SIGN').
105 #elif defined(OS_WIN)
106 const char kIncognitoModeShortcut
[] = "(Ctrl+Shift+N)";
108 const char kIncognitoModeShortcut
[] = "(Shift+Ctrl+N)";
111 // Identifiers for the type of device from which a history entry originated.
112 static const char kDeviceTypeLaptop
[] = "laptop";
113 static const char kDeviceTypePhone
[] = "phone";
114 static const char kDeviceTypeTablet
[] = "tablet";
116 content::WebUIDataSource
* CreateHistoryUIHTMLSource(Profile
* profile
) {
117 PrefService
* prefs
= profile
->GetPrefs();
119 // Check if the profile is authenticated. Guest profiles or incognito
120 // windows may not have a sign in manager, and are considered not
122 SigninManagerBase
* signin_manager
=
123 SigninManagerFactory::GetForProfile(profile
);
124 bool is_authenticated
= signin_manager
!= nullptr &&
125 signin_manager
->IsAuthenticated();
127 content::WebUIDataSource
* source
=
128 content::WebUIDataSource::Create(chrome::kChromeUIHistoryFrameHost
);
129 source
->AddBoolean("isUserSignedIn", is_authenticated
);
130 source
->AddLocalizedString("collapseSessionMenuItemText",
131 IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION
);
132 source
->AddLocalizedString("expandSessionMenuItemText",
133 IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION
);
134 source
->AddLocalizedString("restoreSessionMenuItemText",
135 IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL
);
136 source
->AddLocalizedString("xMore", IDS_OTHER_DEVICES_X_MORE
);
137 source
->AddLocalizedString("loading", IDS_HISTORY_LOADING
);
138 source
->AddLocalizedString("title", IDS_HISTORY_TITLE
);
139 source
->AddLocalizedString("newest", IDS_HISTORY_NEWEST
);
140 source
->AddLocalizedString("newer", IDS_HISTORY_NEWER
);
141 source
->AddLocalizedString("older", IDS_HISTORY_OLDER
);
142 source
->AddLocalizedString("searchResultsFor", IDS_HISTORY_SEARCHRESULTSFOR
);
143 source
->AddLocalizedString("searchResult", IDS_HISTORY_SEARCH_RESULT
);
144 source
->AddLocalizedString("searchResults", IDS_HISTORY_SEARCH_RESULTS
);
145 source
->AddLocalizedString("foundSearchResults",
146 IDS_HISTORY_FOUND_SEARCH_RESULTS
);
147 source
->AddLocalizedString("history", IDS_HISTORY_BROWSERESULTS
);
148 source
->AddLocalizedString("cont", IDS_HISTORY_CONTINUED
);
149 source
->AddLocalizedString("searchButton", IDS_HISTORY_SEARCH_BUTTON
);
150 source
->AddLocalizedString("noSearchResults", IDS_HISTORY_NO_SEARCH_RESULTS
);
151 source
->AddLocalizedString("noResults", IDS_HISTORY_NO_RESULTS
);
152 source
->AddLocalizedString("historyInterval", IDS_HISTORY_INTERVAL
);
153 source
->AddLocalizedString("removeSelected",
154 IDS_HISTORY_REMOVE_SELECTED_ITEMS
);
155 source
->AddLocalizedString("clearAllHistory",
156 IDS_HISTORY_OPEN_CLEAR_BROWSING_DATA_DIALOG
);
159 l10n_util::GetStringFUTF16(IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING
,
160 base::UTF8ToUTF16(kIncognitoModeShortcut
)));
161 source
->AddLocalizedString("removeBookmark", IDS_HISTORY_REMOVE_BOOKMARK
);
162 source
->AddLocalizedString("actionMenuDescription",
163 IDS_HISTORY_ACTION_MENU_DESCRIPTION
);
164 source
->AddLocalizedString("removeFromHistory", IDS_HISTORY_REMOVE_PAGE
);
165 source
->AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE
);
166 source
->AddLocalizedString("groupByDomainLabel", IDS_GROUP_BY_DOMAIN_LABEL
);
167 source
->AddLocalizedString("rangeLabel", IDS_HISTORY_RANGE_LABEL
);
168 source
->AddLocalizedString("rangeAllTime", IDS_HISTORY_RANGE_ALL_TIME
);
169 source
->AddLocalizedString("rangeWeek", IDS_HISTORY_RANGE_WEEK
);
170 source
->AddLocalizedString("rangeMonth", IDS_HISTORY_RANGE_MONTH
);
171 source
->AddLocalizedString("rangeToday", IDS_HISTORY_RANGE_TODAY
);
172 source
->AddLocalizedString("rangeNext", IDS_HISTORY_RANGE_NEXT
);
173 source
->AddLocalizedString("rangePrevious", IDS_HISTORY_RANGE_PREVIOUS
);
174 source
->AddLocalizedString("numberVisits", IDS_HISTORY_NUMBER_VISITS
);
175 source
->AddLocalizedString("filterAllowed", IDS_HISTORY_FILTER_ALLOWED
);
176 source
->AddLocalizedString("filterBlocked", IDS_HISTORY_FILTER_BLOCKED
);
177 source
->AddLocalizedString("inContentPack", IDS_HISTORY_IN_CONTENT_PACK
);
178 source
->AddLocalizedString("allowItems", IDS_HISTORY_FILTER_ALLOW_ITEMS
);
179 source
->AddLocalizedString("blockItems", IDS_HISTORY_FILTER_BLOCK_ITEMS
);
180 source
->AddLocalizedString("lockButton", IDS_HISTORY_LOCK_BUTTON
);
181 source
->AddLocalizedString("blockedVisitText",
182 IDS_HISTORY_BLOCKED_VISIT_TEXT
);
183 source
->AddLocalizedString("unlockButton", IDS_HISTORY_UNLOCK_BUTTON
);
184 source
->AddLocalizedString("hasSyncedResults",
185 IDS_HISTORY_HAS_SYNCED_RESULTS
);
186 source
->AddLocalizedString("noSyncedResults", IDS_HISTORY_NO_SYNCED_RESULTS
);
187 source
->AddLocalizedString("cancel", IDS_CANCEL
);
188 source
->AddLocalizedString("deleteConfirm",
189 IDS_HISTORY_DELETE_PRIOR_VISITS_CONFIRM_BUTTON
);
190 source
->AddLocalizedString("bookmarked", IDS_HISTORY_ENTRY_BOOKMARKED
);
191 source
->AddLocalizedString("entrySummary", IDS_HISTORY_ENTRY_SUMMARY
);
192 source
->AddBoolean("isFullHistorySyncEnabled",
193 WebHistoryServiceFactory::GetForProfile(profile
) != NULL
);
194 source
->AddBoolean("groupByDomain",
195 profile
->IsSupervised() ||
196 base::CommandLine::ForCurrentProcess()->HasSwitch(
197 switches::kHistoryEnableGroupByDomain
));
198 bool allow_deleting_history
=
199 prefs
->GetBoolean(prefs::kAllowDeletingBrowserHistory
);
200 source
->AddBoolean("allowDeletingHistory", allow_deleting_history
);
201 source
->AddBoolean("isInstantExtendedApiEnabled",
202 chrome::IsInstantExtendedAPIEnabled());
203 source
->AddBoolean("isSupervisedProfile", profile
->IsSupervised());
204 source
->AddBoolean("hideDeleteVisitUI",
205 profile
->IsSupervised() && !allow_deleting_history
);
207 source
->SetJsonPath(kStringsJsFile
);
208 source
->AddResourcePath(kHistoryJsFile
, IDR_HISTORY_JS
);
209 source
->AddResourcePath(kOtherDevicesJsFile
, IDR_OTHER_DEVICES_JS
);
210 source
->SetDefaultResource(IDR_HISTORY_HTML
);
211 source
->DisableDenyXFrameOptions();
216 // Returns a localized version of |visit_time| including a relative
217 // indicator (e.g. today, yesterday).
218 base::string16
getRelativeDateLocalized(const base::Time
& visit_time
) {
219 base::Time midnight
= base::Time::Now().LocalMidnight();
220 base::string16 date_str
= ui::TimeFormat::RelativeDate(visit_time
, &midnight
);
221 if (date_str
.empty()) {
222 date_str
= base::TimeFormatFriendlyDate(visit_time
);
224 date_str
= l10n_util::GetStringFUTF16(
225 IDS_HISTORY_DATE_WITH_RELATIVE_TIME
,
227 base::TimeFormatFriendlyDate(visit_time
));
233 // Sets the correct year when substracting months from a date.
234 void normalizeMonths(base::Time::Exploded
* exploded
) {
235 // Decrease a year at a time until we have a proper date.
236 while (exploded
->month
< 1) {
237 exploded
->month
+= 12;
242 // Returns true if |entry| represents a local visit that had no corresponding
243 // visit on the server.
244 bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry
& entry
) {
245 return entry
.entry_type
== BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY
;
248 // Gets the name and type of a device for the given sync client ID.
249 // |name| and |type| are out parameters.
250 void GetDeviceNameAndType(const ProfileSyncService
* sync_service
,
251 const std::string
& client_id
,
254 // DeviceInfoTracker must be syncing in order for remote history entries to
256 DCHECK(sync_service
);
257 DCHECK(sync_service
->GetDeviceInfoTracker());
258 DCHECK(sync_service
->GetDeviceInfoTracker()->IsSyncing());
260 scoped_ptr
<sync_driver::DeviceInfo
> device_info
=
261 sync_service
->GetDeviceInfoTracker()->GetDeviceInfo(client_id
);
262 if (device_info
.get()) {
263 *name
= device_info
->client_name();
264 switch (device_info
->device_type()) {
265 case sync_pb::SyncEnums::TYPE_PHONE
:
266 *type
= kDeviceTypePhone
;
268 case sync_pb::SyncEnums::TYPE_TABLET
:
269 *type
= kDeviceTypeTablet
;
272 *type
= kDeviceTypeLaptop
;
277 *name
= l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE
);
278 *type
= kDeviceTypeLaptop
;
283 ////////////////////////////////////////////////////////////////////////////////
285 // BrowsingHistoryHandler
287 ////////////////////////////////////////////////////////////////////////////////
289 BrowsingHistoryHandler::HistoryEntry::HistoryEntry(
290 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type
,
291 const GURL
& url
, const base::string16
& title
, base::Time time
,
292 const std::string
& client_id
, bool is_search_result
,
293 const base::string16
& snippet
, bool blocked_visit
,
294 const std::string
& accept_languages
) {
295 this->entry_type
= entry_type
;
299 this->client_id
= client_id
;
300 all_timestamps
.insert(time
.ToInternalValue());
301 this->is_search_result
= is_search_result
;
302 this->snippet
= snippet
;
303 this->blocked_visit
= blocked_visit
;
304 this->accept_languages
= accept_languages
;
307 BrowsingHistoryHandler::HistoryEntry::HistoryEntry()
308 : entry_type(EMPTY_ENTRY
), is_search_result(false), blocked_visit(false) {
311 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {
314 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle(
315 base::DictionaryValue
* result
) const {
316 result
->SetString("url", url
.spec());
318 bool using_url_as_the_title
= false;
319 base::string16
title_to_set(title
);
321 using_url_as_the_title
= true;
322 title_to_set
= base::UTF8ToUTF16(url
.spec());
325 // Since the title can contain BiDi text, we need to mark the text as either
326 // RTL or LTR, depending on the characters in the string. If we use the URL
327 // as the title, we mark the title as LTR since URLs are always treated as
328 // left to right strings.
329 if (base::i18n::IsRTL()) {
330 if (using_url_as_the_title
)
331 base::i18n::WrapStringWithLTRFormatting(&title_to_set
);
333 base::i18n::AdjustStringForLocaleDirection(&title_to_set
);
335 result
->SetString("title", title_to_set
);
338 scoped_ptr
<base::DictionaryValue
> BrowsingHistoryHandler::HistoryEntry::ToValue(
339 BookmarkModel
* bookmark_model
,
340 SupervisedUserService
* supervised_user_service
,
341 const ProfileSyncService
* sync_service
) const {
342 scoped_ptr
<base::DictionaryValue
> result(new base::DictionaryValue());
343 SetUrlAndTitle(result
.get());
345 base::string16 domain
= net::IDNToUnicode(url
.host(), accept_languages
);
346 // When the domain is empty, use the scheme instead. This allows for a
347 // sensible treatment of e.g. file: URLs when group by domain is on.
349 domain
= base::UTF8ToUTF16(url
.scheme() + ":");
351 // The items which are to be written into result are also described in
352 // chrome/browser/resources/history/history.js in @typedef for
353 // HistoryEntry. Please update it whenever you add or remove
354 // any keys in result.
355 result
->SetString("domain", domain
);
356 result
->SetDouble("time", time
.ToJsTime());
358 // Pass the timestamps in a list.
359 scoped_ptr
<base::ListValue
> timestamps(new base::ListValue
);
360 for (std::set
<int64
>::const_iterator it
= all_timestamps
.begin();
361 it
!= all_timestamps
.end(); ++it
) {
362 timestamps
->AppendDouble(base::Time::FromInternalValue(*it
).ToJsTime());
364 result
->Set("allTimestamps", timestamps
.release());
366 // Always pass the short date since it is needed both in the search and in
368 result
->SetString("dateShort", base::TimeFormatShortDate(time
));
370 // Only pass in the strings we need (search results need a shortdate
371 // and snippet, browse results need day and time information).
372 if (is_search_result
) {
373 result
->SetString("snippet", snippet
);
375 base::Time midnight
= base::Time::Now().LocalMidnight();
376 base::string16 date_str
= ui::TimeFormat::RelativeDate(time
, &midnight
);
377 if (date_str
.empty()) {
378 date_str
= base::TimeFormatFriendlyDate(time
);
380 date_str
= l10n_util::GetStringFUTF16(
381 IDS_HISTORY_DATE_WITH_RELATIVE_TIME
,
383 base::TimeFormatFriendlyDate(time
));
385 result
->SetString("dateRelativeDay", date_str
);
386 result
->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time
));
388 result
->SetBoolean("starred", bookmark_model
->IsBookmarked(url
));
390 std::string device_name
;
391 std::string device_type
;
392 if (!client_id
.empty())
393 GetDeviceNameAndType(sync_service
, client_id
, &device_name
, &device_type
);
394 result
->SetString("deviceName", device_name
);
395 result
->SetString("deviceType", device_type
);
397 #if defined(ENABLE_SUPERVISED_USERS)
398 if (supervised_user_service
) {
399 const SupervisedUserURLFilter
* url_filter
=
400 supervised_user_service
->GetURLFilterForUIThread();
401 int filtering_behavior
=
402 url_filter
->GetFilteringBehaviorForURL(url
.GetWithEmptyPath());
403 result
->SetInteger("hostFilteringBehavior", filtering_behavior
);
405 result
->SetBoolean("blockedVisit", blocked_visit
);
409 return result
.Pass();
412 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending(
413 const BrowsingHistoryHandler::HistoryEntry
& entry1
,
414 const BrowsingHistoryHandler::HistoryEntry
& entry2
) {
415 return entry1
.time
> entry2
.time
;
418 BrowsingHistoryHandler::BrowsingHistoryHandler()
419 : has_pending_delete_request_(false),
420 history_service_observer_(this),
421 weak_factory_(this) {
424 BrowsingHistoryHandler::~BrowsingHistoryHandler() {
425 query_task_tracker_
.TryCancelAll();
426 web_history_request_
.reset();
429 void BrowsingHistoryHandler::RegisterMessages() {
430 // Create our favicon data source.
431 Profile
* profile
= Profile::FromWebUI(web_ui());
432 content::URLDataSource::Add(
433 profile
, new FaviconSource(profile
, FaviconSource::ANY
));
435 // Get notifications when history is cleared.
436 HistoryService
* hs
= HistoryServiceFactory::GetForProfile(
437 profile
, ServiceAccessType::EXPLICIT_ACCESS
);
439 history_service_observer_
.Add(hs
);
441 web_ui()->RegisterMessageCallback("queryHistory",
442 base::Bind(&BrowsingHistoryHandler::HandleQueryHistory
,
443 base::Unretained(this)));
444 web_ui()->RegisterMessageCallback("removeVisits",
445 base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits
,
446 base::Unretained(this)));
447 web_ui()->RegisterMessageCallback("clearBrowsingData",
448 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData
,
449 base::Unretained(this)));
450 web_ui()->RegisterMessageCallback("removeBookmark",
451 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark
,
452 base::Unretained(this)));
455 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(
456 const base::ListValue
* value
,
460 if (value
->GetDouble(index
, &double_value
)) {
461 *out_int
= static_cast<int>(double_value
);
468 void BrowsingHistoryHandler::WebHistoryTimeout() {
469 // TODO(dubroy): Communicate the failure to the front end.
470 if (!query_task_tracker_
.HasTrackedTasks())
471 ReturnResultsToFrontEnd();
473 UMA_HISTOGRAM_ENUMERATION(
474 "WebHistory.QueryCompletion",
475 WEB_HISTORY_QUERY_TIMED_OUT
, NUM_WEB_HISTORY_QUERY_BUCKETS
);
478 void BrowsingHistoryHandler::QueryHistory(
479 base::string16 search_text
, const history::QueryOptions
& options
) {
480 Profile
* profile
= Profile::FromWebUI(web_ui());
482 // Anything in-flight is invalid.
483 query_task_tracker_
.TryCancelAll();
484 web_history_request_
.reset();
486 query_results_
.clear();
487 results_info_value_
.Clear();
489 HistoryService
* hs
= HistoryServiceFactory::GetForProfile(
490 profile
, ServiceAccessType::EXPLICIT_ACCESS
);
491 hs
->QueryHistory(search_text
,
493 base::Bind(&BrowsingHistoryHandler::QueryComplete
,
494 base::Unretained(this),
497 &query_task_tracker_
);
499 history::WebHistoryService
* web_history
=
500 WebHistoryServiceFactory::GetForProfile(profile
);
502 web_history_query_results_
.clear();
503 web_history_request_
= web_history
->QueryHistory(
506 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete
,
507 base::Unretained(this),
508 search_text
, options
,
509 base::TimeTicks::Now()));
510 // Start a timer so we know when to give up.
511 web_history_timer_
.Start(
512 FROM_HERE
, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds
),
513 this, &BrowsingHistoryHandler::WebHistoryTimeout
);
515 // Set this to false until the results actually arrive.
516 results_info_value_
.SetBoolean("hasSyncedResults", false);
520 void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue
* args
) {
521 history::QueryOptions options
;
523 // Parse the arguments from JavaScript. There are five required arguments:
524 // - the text to search for (may be empty)
525 // - the offset from which the search should start (in multiples of week or
526 // month, set by the next argument).
527 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range
529 // - the end time for the query. Only results older than this time will be
531 // - the maximum number of results to return (may be 0, meaning that there
533 base::string16 search_text
= ExtractStringValue(args
);
535 if (!args
->GetInteger(1, &offset
)) {
536 NOTREACHED() << "Failed to convert argument 1. ";
540 if (!args
->GetInteger(2, &range
)) {
541 NOTREACHED() << "Failed to convert argument 2. ";
545 if (range
== BrowsingHistoryHandler::MONTH
)
546 SetQueryTimeInMonths(offset
, &options
);
547 else if (range
== BrowsingHistoryHandler::WEEK
)
548 SetQueryTimeInWeeks(offset
, &options
);
551 if (!args
->GetDouble(3, &end_time
)) {
552 NOTREACHED() << "Failed to convert argument 3. ";
556 options
.end_time
= base::Time::FromJsTime(end_time
);
558 if (!ExtractIntegerValueAtIndex(args
, 4, &options
.max_count
)) {
559 NOTREACHED() << "Failed to convert argument 4.";
563 options
.duplicate_policy
= history::QueryOptions::REMOVE_DUPLICATES_PER_DAY
;
564 QueryHistory(search_text
, options
);
567 void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue
* args
) {
568 Profile
* profile
= Profile::FromWebUI(web_ui());
569 // TODO(davidben): history.js is not aware of this failure and will still
570 // override |deleteCompleteCallback_|.
571 if (delete_task_tracker_
.HasTrackedTasks() ||
572 has_pending_delete_request_
||
573 !profile
->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory
)) {
574 web_ui()->CallJavascriptFunction("deleteFailed");
578 HistoryService
* history_service
= HistoryServiceFactory::GetForProfile(
579 profile
, ServiceAccessType::EXPLICIT_ACCESS
);
580 history::WebHistoryService
* web_history
=
581 WebHistoryServiceFactory::GetForProfile(profile
);
583 base::Time now
= base::Time::Now();
584 std::vector
<history::ExpireHistoryArgs
> expire_list
;
585 expire_list
.reserve(args
->GetSize());
587 DCHECK(urls_to_be_deleted_
.empty());
588 for (base::ListValue::const_iterator it
= args
->begin();
589 it
!= args
->end(); ++it
) {
590 base::DictionaryValue
* deletion
= NULL
;
592 base::ListValue
* timestamps
= NULL
;
594 // Each argument is a dictionary with properties "url" and "timestamps".
595 if (!((*it
)->GetAsDictionary(&deletion
) &&
596 deletion
->GetString("url", &url
) &&
597 deletion
->GetList("timestamps", ×tamps
))) {
598 NOTREACHED() << "Unable to extract arguments";
601 DCHECK(timestamps
->GetSize() > 0);
603 // In order to ensure that visits will be deleted from the server and other
604 // clients (even if they are offline), create a sync delete directive for
605 // each visit to be deleted.
606 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive
;
607 sync_pb::GlobalIdDirective
* global_id_directive
=
608 delete_directive
.mutable_global_id_directive();
611 history::ExpireHistoryArgs
* expire_args
= NULL
;
612 for (base::ListValue::const_iterator ts_iterator
= timestamps
->begin();
613 ts_iterator
!= timestamps
->end(); ++ts_iterator
) {
614 if (!(*ts_iterator
)->GetAsDouble(×tamp
)) {
615 NOTREACHED() << "Unable to extract visit timestamp.";
618 base::Time visit_time
= base::Time::FromJsTime(timestamp
);
621 expire_list
.resize(expire_list
.size() + 1);
622 expire_args
= &expire_list
.back();
623 expire_args
->SetTimeRangeForOneDay(visit_time
);
624 expire_args
->urls
.insert(gurl
);
625 urls_to_be_deleted_
.insert(gurl
);
627 // The local visit time is treated as a global ID for the visit.
628 global_id_directive
->add_global_id(visit_time
.ToInternalValue());
631 // Set the start and end time in microseconds since the Unix epoch.
632 global_id_directive
->set_start_time_usec(
633 (expire_args
->begin_time
- base::Time::UnixEpoch()).InMicroseconds());
635 // Delete directives shouldn't have an end time in the future.
636 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
637 base::Time end_time
= std::min(expire_args
->end_time
, now
);
639 // -1 because end time in delete directives is inclusive.
640 global_id_directive
->set_end_time_usec(
641 (end_time
- base::Time::UnixEpoch()).InMicroseconds() - 1);
643 // TODO(dubroy): Figure out the proper way to handle an error here.
645 history_service
->ProcessLocalDeleteDirective(delete_directive
);
648 history_service
->ExpireHistory(
650 base::Bind(&BrowsingHistoryHandler::RemoveComplete
,
651 base::Unretained(this)),
652 &delete_task_tracker_
);
655 has_pending_delete_request_
= true;
656 web_history
->ExpireHistory(
658 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete
,
659 weak_factory_
.GetWeakPtr()));
662 #if defined(ENABLE_EXTENSIONS)
663 // If the profile has activity logging enabled also clean up any URLs from
664 // the extension activity log. The extension activity log contains URLS
665 // which websites an extension has activity on so it will indirectly
666 // contain websites that a user has visited.
667 extensions::ActivityLog
* activity_log
=
668 extensions::ActivityLog::GetInstance(profile
);
669 for (std::vector
<history::ExpireHistoryArgs
>::const_iterator it
=
670 expire_list
.begin(); it
!= expire_list
.end(); ++it
) {
671 activity_log
->RemoveURLs(it
->urls
);
675 for (const history::ExpireHistoryArgs
& expire_entry
: expire_list
)
676 AppBannerSettingsHelper::ClearHistoryForURLs(profile
, expire_entry
.urls
);
679 void BrowsingHistoryHandler::HandleClearBrowsingData(
680 const base::ListValue
* args
) {
681 #if defined(OS_ANDROID)
682 chrome::android::ChromiumApplication::OpenClearBrowsingData(
683 web_ui()->GetWebContents());
685 // TODO(beng): This is an improper direct dependency on Browser. Route this
686 // through some sort of delegate.
687 Browser
* browser
= chrome::FindBrowserWithWebContents(
688 web_ui()->GetWebContents());
689 chrome::ShowClearBrowsingDataDialog(browser
);
693 void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue
* args
) {
694 base::string16 url
= ExtractStringValue(args
);
695 Profile
* profile
= Profile::FromWebUI(web_ui());
696 BookmarkModel
* model
= BookmarkModelFactory::GetForProfile(profile
);
697 bookmarks::RemoveAllBookmarks(model
, GURL(url
));
701 void BrowsingHistoryHandler::MergeDuplicateResults(
702 std::vector
<BrowsingHistoryHandler::HistoryEntry
>* results
) {
703 std::vector
<BrowsingHistoryHandler::HistoryEntry
> new_results
;
704 // Pre-reserve the size of the new vector. Since we're working with pointers
705 // later on not doing this could lead to the vector being resized and to
706 // pointers to invalid locations.
707 new_results
.reserve(results
->size());
708 // Maps a URL to the most recent entry on a particular day.
709 std::map
<GURL
, BrowsingHistoryHandler::HistoryEntry
*> current_day_entries
;
711 // Keeps track of the day that |current_day_urls| is holding the URLs for,
712 // in order to handle removing per-day duplicates.
713 base::Time current_day_midnight
;
716 results
->begin(), results
->end(), HistoryEntry::SortByTimeDescending
);
718 for (std::vector
<BrowsingHistoryHandler::HistoryEntry
>::const_iterator it
=
719 results
->begin(); it
!= results
->end(); ++it
) {
720 // Reset the list of found URLs when a visit from a new day is encountered.
721 if (current_day_midnight
!= it
->time
.LocalMidnight()) {
722 current_day_entries
.clear();
723 current_day_midnight
= it
->time
.LocalMidnight();
726 // Keep this visit if it's the first visit to this URL on the current day.
727 if (current_day_entries
.count(it
->url
) == 0) {
728 new_results
.push_back(*it
);
729 current_day_entries
[it
->url
] = &new_results
.back();
731 // Keep track of the timestamps of all visits to the URL on the same day.
732 BrowsingHistoryHandler::HistoryEntry
* entry
=
733 current_day_entries
[it
->url
];
734 entry
->all_timestamps
.insert(
735 it
->all_timestamps
.begin(), it
->all_timestamps
.end());
737 if (entry
->entry_type
!= it
->entry_type
) {
739 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY
;
743 results
->swap(new_results
);
746 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() {
747 Profile
* profile
= Profile::FromWebUI(web_ui());
748 BookmarkModel
* bookmark_model
= BookmarkModelFactory::GetForProfile(profile
);
749 SupervisedUserService
* supervised_user_service
= NULL
;
750 #if defined(ENABLE_SUPERVISED_USERS)
751 if (profile
->IsSupervised())
752 supervised_user_service
=
753 SupervisedUserServiceFactory::GetForProfile(profile
);
755 ProfileSyncService
* sync_service
=
756 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile
);
758 // Combine the local and remote results into |query_results_|, and remove
760 if (!web_history_query_results_
.empty()) {
761 int local_result_count
= query_results_
.size();
762 query_results_
.insert(query_results_
.end(),
763 web_history_query_results_
.begin(),
764 web_history_query_results_
.end());
765 MergeDuplicateResults(&query_results_
);
767 if (local_result_count
) {
768 // In the best case, we expect that all local results are duplicated on
769 // the server. Keep track of how many are missing.
770 int missing_count
= std::count_if(
771 query_results_
.begin(), query_results_
.end(), IsLocalOnlyResult
);
772 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer",
773 missing_count
* 100.0 / local_result_count
);
777 // Convert the result vector into a ListValue.
778 base::ListValue results_value
;
779 for (std::vector
<BrowsingHistoryHandler::HistoryEntry
>::iterator it
=
780 query_results_
.begin(); it
!= query_results_
.end(); ++it
) {
781 scoped_ptr
<base::Value
> value(
782 it
->ToValue(bookmark_model
, supervised_user_service
, sync_service
));
783 results_value
.Append(value
.release());
786 web_ui()->CallJavascriptFunction(
787 "historyResult", results_info_value_
, results_value
);
788 results_info_value_
.Clear();
789 query_results_
.clear();
790 web_history_query_results_
.clear();
793 void BrowsingHistoryHandler::QueryComplete(
794 const base::string16
& search_text
,
795 const history::QueryOptions
& options
,
796 history::QueryResults
* results
) {
797 DCHECK_EQ(0U, query_results_
.size());
798 query_results_
.reserve(results
->size());
799 const std::string accept_languages
= GetAcceptLanguages();
801 for (size_t i
= 0; i
< results
->size(); ++i
) {
802 history::URLResult
const &page
= (*results
)[i
];
803 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
804 query_results_
.push_back(
806 HistoryEntry::LOCAL_ENTRY
,
811 !search_text
.empty(),
812 page
.snippet().text(),
813 page
.blocked_visit(),
817 // The items which are to be written into results_info_value_ are also
818 // described in chrome/browser/resources/history/history.js in @typedef for
819 // HistoryQuery. Please update it whenever you add or remove any keys in
820 // results_info_value_.
821 results_info_value_
.SetString("term", search_text
);
822 results_info_value_
.SetBoolean("finished", results
->reached_beginning());
824 // Add the specific dates that were searched to display them.
825 // TODO(sergiu): Put today if the start is in the future.
826 results_info_value_
.SetString("queryStartTime",
827 getRelativeDateLocalized(options
.begin_time
));
828 if (!options
.end_time
.is_null()) {
829 results_info_value_
.SetString("queryEndTime",
830 getRelativeDateLocalized(options
.end_time
-
831 base::TimeDelta::FromDays(1)));
833 results_info_value_
.SetString("queryEndTime",
834 getRelativeDateLocalized(base::Time::Now()));
836 if (!web_history_timer_
.IsRunning())
837 ReturnResultsToFrontEnd();
840 void BrowsingHistoryHandler::WebHistoryQueryComplete(
841 const base::string16
& search_text
,
842 const history::QueryOptions
& options
,
843 base::TimeTicks start_time
,
844 history::WebHistoryService::Request
* request
,
845 const base::DictionaryValue
* results_value
) {
846 base::TimeDelta delta
= base::TimeTicks::Now() - start_time
;
847 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta
);
848 const std::string accept_languages
= GetAcceptLanguages();
850 // If the response came in too late, do nothing.
851 // TODO(dubroy): Maybe show a banner, and prompt the user to reload?
852 if (!web_history_timer_
.IsRunning())
854 web_history_timer_
.Stop();
856 UMA_HISTOGRAM_ENUMERATION(
857 "WebHistory.QueryCompletion",
858 results_value
? WEB_HISTORY_QUERY_SUCCEEDED
: WEB_HISTORY_QUERY_FAILED
,
859 NUM_WEB_HISTORY_QUERY_BUCKETS
);
861 DCHECK_EQ(0U, web_history_query_results_
.size());
862 const base::ListValue
* events
= NULL
;
863 if (results_value
&& results_value
->GetList("event", &events
)) {
864 web_history_query_results_
.reserve(events
->GetSize());
865 for (unsigned int i
= 0; i
< events
->GetSize(); ++i
) {
866 const base::DictionaryValue
* event
= NULL
;
867 const base::DictionaryValue
* result
= NULL
;
868 const base::ListValue
* results
= NULL
;
869 const base::ListValue
* ids
= NULL
;
871 base::string16 title
;
872 base::Time visit_time
;
874 if (!(events
->GetDictionary(i
, &event
) &&
875 event
->GetList("result", &results
) &&
876 results
->GetDictionary(0, &result
) &&
877 result
->GetString("url", &url
) &&
878 result
->GetList("id", &ids
) &&
879 ids
->GetSize() > 0)) {
880 LOG(WARNING
) << "Improperly formed JSON response from history server.";
883 // Title is optional, so the return value is ignored here.
884 result
->GetString("title", &title
);
886 // Extract the timestamps of all the visits to this URL.
887 // They are referred to as "IDs" by the server.
888 for (int j
= 0; j
< static_cast<int>(ids
->GetSize()); ++j
) {
889 const base::DictionaryValue
* id
= NULL
;
890 std::string timestamp_string
;
891 int64 timestamp_usec
= 0;
893 if (!ids
->GetDictionary(j
, &id
) ||
894 !id
->GetString("timestamp_usec", ×tamp_string
) ||
895 !base::StringToInt64(timestamp_string
, ×tamp_usec
)) {
896 NOTREACHED() << "Unable to extract timestamp.";
899 // The timestamp on the server is a Unix time.
900 base::Time time
= base::Time::UnixEpoch() +
901 base::TimeDelta::FromMicroseconds(timestamp_usec
);
903 // Get the ID of the client that this visit came from.
904 std::string client_id
;
905 id
->GetString("client_id", &client_id
);
907 web_history_query_results_
.push_back(
909 HistoryEntry::REMOTE_ENTRY
,
914 !search_text
.empty(),
916 /* blocked_visit */ false,
920 } else if (results_value
) {
921 NOTREACHED() << "Failed to parse JSON response.";
923 results_info_value_
.SetBoolean("hasSyncedResults", results_value
!= NULL
);
924 if (!query_task_tracker_
.HasTrackedTasks())
925 ReturnResultsToFrontEnd();
928 void BrowsingHistoryHandler::RemoveComplete() {
929 urls_to_be_deleted_
.clear();
931 // Notify the page that the deletion request is complete, but only if a web
932 // history delete request is not still pending.
933 if (!has_pending_delete_request_
)
934 web_ui()->CallJavascriptFunction("deleteComplete");
937 void BrowsingHistoryHandler::RemoveWebHistoryComplete(bool success
) {
938 has_pending_delete_request_
= false;
939 // TODO(dubroy): Should we handle failure somehow? Delete directives will
940 // ensure that the visits are eventually deleted, so maybe it's not necessary.
941 if (!delete_task_tracker_
.HasTrackedTasks())
945 void BrowsingHistoryHandler::SetQueryTimeInWeeks(
946 int offset
, history::QueryOptions
* options
) {
947 // LocalMidnight returns the beginning of the current day so get the
948 // beginning of the next one.
949 base::Time midnight
= base::Time::Now().LocalMidnight() +
950 base::TimeDelta::FromDays(1);
951 options
->end_time
= midnight
-
952 base::TimeDelta::FromDays(7 * offset
);
953 options
->begin_time
= midnight
-
954 base::TimeDelta::FromDays(7 * (offset
+ 1));
957 void BrowsingHistoryHandler::SetQueryTimeInMonths(
958 int offset
, history::QueryOptions
* options
) {
959 // Configure the begin point of the search to the start of the
961 base::Time::Exploded exploded
;
962 base::Time::Now().LocalMidnight().LocalExplode(&exploded
);
963 exploded
.day_of_month
= 1;
966 options
->begin_time
= base::Time::FromLocalExploded(exploded
);
968 // Set the end time of this first search to null (which will
969 // show results from the future, should the user's clock have
970 // been set incorrectly).
971 options
->end_time
= base::Time();
973 // Go back |offset| months in the past. The end time is not inclusive, so
974 // use the first day of the |offset| - 1 and |offset| months (e.g. for
975 // the last month, |offset| = 1, use the first days of the last month and
976 // the current month.
977 exploded
.month
-= offset
- 1;
978 // Set the correct year.
979 normalizeMonths(&exploded
);
980 options
->end_time
= base::Time::FromLocalExploded(exploded
);
983 // Set the correct year
984 normalizeMonths(&exploded
);
985 options
->begin_time
= base::Time::FromLocalExploded(exploded
);
989 // Helper function for Observe that determines if there are any differences
990 // between the URLs noticed for deletion and the ones we are expecting.
991 static bool DeletionsDiffer(const history::URLRows
& deleted_rows
,
992 const std::set
<GURL
>& urls_to_be_deleted
) {
993 if (deleted_rows
.size() != urls_to_be_deleted
.size())
995 for (const auto& i
: deleted_rows
) {
996 if (urls_to_be_deleted
.find(i
.url()) == urls_to_be_deleted
.end())
1002 std::string
BrowsingHistoryHandler::GetAcceptLanguages() const {
1003 Profile
* profile
= Profile::FromWebUI(web_ui());
1004 return profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
);
1007 void BrowsingHistoryHandler::OnURLsDeleted(HistoryService
* history_service
,
1010 const history::URLRows
& deleted_rows
,
1011 const std::set
<GURL
>& favicon_urls
) {
1012 if (all_history
|| DeletionsDiffer(deleted_rows
, urls_to_be_deleted_
))
1013 web_ui()->CallJavascriptFunction("historyDeleted");
1016 ////////////////////////////////////////////////////////////////////////////////
1020 ////////////////////////////////////////////////////////////////////////////////
1022 HistoryUI::HistoryUI(content::WebUI
* web_ui
) : WebUIController(web_ui
) {
1023 web_ui
->AddMessageHandler(new BrowsingHistoryHandler());
1024 web_ui
->AddMessageHandler(new MetricsHandler());
1026 // On mobile we deal with foreign sessions differently.
1027 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1028 if (chrome::IsInstantExtendedAPIEnabled()) {
1029 web_ui
->AddMessageHandler(new browser_sync::ForeignSessionHandler());
1030 web_ui
->AddMessageHandler(new NTPLoginHandler());
1034 // Set up the chrome://history-frame/ source.
1035 Profile
* profile
= Profile::FromWebUI(web_ui
);
1036 content::WebUIDataSource::Add(profile
, CreateHistoryUIHTMLSource(profile
));
1040 base::RefCountedMemory
* HistoryUI::GetFaviconResourceBytes(
1041 ui::ScaleFactor scale_factor
) {
1042 return ResourceBundle::GetSharedInstance().
1043 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON
, scale_factor
);