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/bookmarks/bookmark_model.h"
24 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
25 #include "chrome/browser/bookmarks/bookmark_utils.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/extensions/activity_log/activity_log.h"
28 #include "chrome/browser/history/history_notifications.h"
29 #include "chrome/browser/history/history_service_factory.h"
30 #include "chrome/browser/history/history_types.h"
31 #include "chrome/browser/history/web_history_service.h"
32 #include "chrome/browser/history/web_history_service_factory.h"
33 #include "chrome/browser/profiles/profile.h"
34 #include "chrome/browser/search/search.h"
35 #include "chrome/browser/sync/glue/device_info.h"
36 #include "chrome/browser/sync/profile_sync_service.h"
37 #include "chrome/browser/sync/profile_sync_service_factory.h"
38 #include "chrome/browser/ui/browser_finder.h"
39 #include "chrome/browser/ui/chrome_pages.h"
40 #include "chrome/browser/ui/webui/favicon_source.h"
41 #include "chrome/browser/ui/webui/metrics_handler.h"
42 #include "chrome/common/chrome_switches.h"
43 #include "chrome/common/pref_names.h"
44 #include "chrome/common/url_constants.h"
45 #include "content/public/browser/notification_details.h"
46 #include "content/public/browser/notification_source.h"
47 #include "content/public/browser/url_data_source.h"
48 #include "content/public/browser/web_ui.h"
49 #include "content/public/browser/web_ui_data_source.h"
50 #include "grit/browser_resources.h"
51 #include "grit/generated_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"
60 #if defined(ENABLE_MANAGED_USERS)
61 #include "chrome/browser/managed_mode/managed_mode_navigation_observer.h"
62 #include "chrome/browser/managed_mode/managed_mode_url_filter.h"
63 #include "chrome/browser/managed_mode/managed_user_service.h"
64 #include "chrome/browser/managed_mode/managed_user_service_factory.h"
67 #if defined(OS_ANDROID)
68 #include "chrome/browser/ui/android/tab_model/tab_model.h"
69 #include "chrome/browser/ui/android/tab_model/tab_model_list.h"
72 #if !defined(OS_ANDROID) && !defined(OS_IOS)
73 #include "chrome/browser/ui/webui/ntp/foreign_session_handler.h"
74 #include "chrome/browser/ui/webui/ntp/ntp_login_handler.h"
77 static const char kStringsJsFile
[] = "strings.js";
78 static const char kHistoryJsFile
[] = "history.js";
79 static const char kOtherDevicesJsFile
[] = "other_devices.js";
81 // The amount of time to wait for a response from the WebHistoryService.
82 static const int kWebHistoryTimeoutSeconds
= 3;
86 // Buckets for UMA histograms.
87 enum WebHistoryQueryBuckets
{
88 WEB_HISTORY_QUERY_FAILED
= 0,
89 WEB_HISTORY_QUERY_SUCCEEDED
,
90 WEB_HISTORY_QUERY_TIMED_OUT
,
91 NUM_WEB_HISTORY_QUERY_BUCKETS
94 #if defined(OS_MACOSX)
95 const char kIncognitoModeShortcut
[] = "("
96 "\xE2\x87\xA7" // Shift symbol (U+21E7 'UPWARDS WHITE ARROW').
97 "\xE2\x8C\x98" // Command symbol (U+2318 'PLACE OF INTEREST SIGN').
100 const char kIncognitoModeShortcut
[] = "(Ctrl+Shift+N)";
102 const char kIncognitoModeShortcut
[] = "(Shift+Ctrl+N)";
105 // Identifiers for the type of device from which a history entry originated.
106 static const char kDeviceTypeLaptop
[] = "laptop";
107 static const char kDeviceTypePhone
[] = "phone";
108 static const char kDeviceTypeTablet
[] = "tablet";
110 content::WebUIDataSource
* CreateHistoryUIHTMLSource(Profile
* profile
) {
111 PrefService
* prefs
= profile
->GetPrefs();
113 content::WebUIDataSource
* source
=
114 content::WebUIDataSource::Create(chrome::kChromeUIHistoryFrameHost
);
115 source
->AddBoolean("isUserSignedIn",
116 !prefs
->GetString(prefs::kGoogleServicesUsername
).empty());
117 source
->AddLocalizedString("collapseSessionMenuItemText",
118 IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION
);
119 source
->AddLocalizedString("expandSessionMenuItemText",
120 IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION
);
121 source
->AddLocalizedString("restoreSessionMenuItemText",
122 IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL
);
123 source
->AddLocalizedString("xMore", IDS_OTHER_DEVICES_X_MORE
);
124 source
->AddLocalizedString("loading", IDS_HISTORY_LOADING
);
125 source
->AddLocalizedString("title", IDS_HISTORY_TITLE
);
126 source
->AddLocalizedString("newest", IDS_HISTORY_NEWEST
);
127 source
->AddLocalizedString("newer", IDS_HISTORY_NEWER
);
128 source
->AddLocalizedString("older", IDS_HISTORY_OLDER
);
129 source
->AddLocalizedString("searchResultsFor", IDS_HISTORY_SEARCHRESULTSFOR
);
130 source
->AddLocalizedString("history", IDS_HISTORY_BROWSERESULTS
);
131 source
->AddLocalizedString("cont", IDS_HISTORY_CONTINUED
);
132 source
->AddLocalizedString("searchButton", IDS_HISTORY_SEARCH_BUTTON
);
133 source
->AddLocalizedString("noSearchResults", IDS_HISTORY_NO_SEARCH_RESULTS
);
134 source
->AddLocalizedString("noResults", IDS_HISTORY_NO_RESULTS
);
135 source
->AddLocalizedString("historyInterval", IDS_HISTORY_INTERVAL
);
136 source
->AddLocalizedString("removeSelected",
137 IDS_HISTORY_REMOVE_SELECTED_ITEMS
);
138 source
->AddLocalizedString("clearAllHistory",
139 IDS_HISTORY_OPEN_CLEAR_BROWSING_DATA_DIALOG
);
142 l10n_util::GetStringFUTF16(IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING
,
143 base::UTF8ToUTF16(kIncognitoModeShortcut
)));
144 source
->AddLocalizedString("actionMenuDescription",
145 IDS_HISTORY_ACTION_MENU_DESCRIPTION
);
146 source
->AddLocalizedString("removeFromHistory", IDS_HISTORY_REMOVE_PAGE
);
147 source
->AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE
);
148 source
->AddLocalizedString("groupByDomainLabel", IDS_GROUP_BY_DOMAIN_LABEL
);
149 source
->AddLocalizedString("rangeLabel", IDS_HISTORY_RANGE_LABEL
);
150 source
->AddLocalizedString("rangeAllTime", IDS_HISTORY_RANGE_ALL_TIME
);
151 source
->AddLocalizedString("rangeWeek", IDS_HISTORY_RANGE_WEEK
);
152 source
->AddLocalizedString("rangeMonth", IDS_HISTORY_RANGE_MONTH
);
153 source
->AddLocalizedString("rangeToday", IDS_HISTORY_RANGE_TODAY
);
154 source
->AddLocalizedString("rangeNext", IDS_HISTORY_RANGE_NEXT
);
155 source
->AddLocalizedString("rangePrevious", IDS_HISTORY_RANGE_PREVIOUS
);
156 source
->AddLocalizedString("numberVisits", IDS_HISTORY_NUMBER_VISITS
);
157 source
->AddLocalizedString("filterAllowed", IDS_HISTORY_FILTER_ALLOWED
);
158 source
->AddLocalizedString("filterBlocked", IDS_HISTORY_FILTER_BLOCKED
);
159 source
->AddLocalizedString("inContentPack", IDS_HISTORY_IN_CONTENT_PACK
);
160 source
->AddLocalizedString("allowItems", IDS_HISTORY_FILTER_ALLOW_ITEMS
);
161 source
->AddLocalizedString("blockItems", IDS_HISTORY_FILTER_BLOCK_ITEMS
);
162 source
->AddLocalizedString("lockButton", IDS_HISTORY_LOCK_BUTTON
);
163 source
->AddLocalizedString("blockedVisitText",
164 IDS_HISTORY_BLOCKED_VISIT_TEXT
);
165 source
->AddLocalizedString("unlockButton", IDS_HISTORY_UNLOCK_BUTTON
);
166 source
->AddLocalizedString("hasSyncedResults",
167 IDS_HISTORY_HAS_SYNCED_RESULTS
);
168 source
->AddLocalizedString("noSyncedResults", IDS_HISTORY_NO_SYNCED_RESULTS
);
169 source
->AddLocalizedString("cancel", IDS_CANCEL
);
170 source
->AddLocalizedString("deleteConfirm",
171 IDS_HISTORY_DELETE_PRIOR_VISITS_CONFIRM_BUTTON
);
172 source
->AddBoolean("isFullHistorySyncEnabled",
173 WebHistoryServiceFactory::GetForProfile(profile
) != NULL
);
174 source
->AddBoolean("groupByDomain",
175 CommandLine::ForCurrentProcess()->HasSwitch(
176 switches::kHistoryEnableGroupByDomain
));
177 source
->AddBoolean("allowDeletingHistory",
178 prefs
->GetBoolean(prefs::kAllowDeletingBrowserHistory
));
179 source
->AddBoolean("isInstantExtendedApiEnabled",
180 chrome::IsInstantExtendedAPIEnabled());
182 source
->SetJsonPath(kStringsJsFile
);
183 source
->AddResourcePath(kHistoryJsFile
, IDR_HISTORY_JS
);
184 source
->AddResourcePath(kOtherDevicesJsFile
, IDR_OTHER_DEVICES_JS
);
185 source
->SetDefaultResource(IDR_HISTORY_HTML
);
186 source
->SetUseJsonJSFormatV2();
187 source
->DisableDenyXFrameOptions();
188 source
->AddBoolean("isManagedProfile", profile
->IsManaged());
189 source
->AddBoolean("showDeleteVisitUI", !profile
->IsManaged());
194 // Returns a localized version of |visit_time| including a relative
195 // indicator (e.g. today, yesterday).
196 base::string16
getRelativeDateLocalized(const base::Time
& visit_time
) {
197 base::Time midnight
= base::Time::Now().LocalMidnight();
198 base::string16 date_str
= ui::TimeFormat::RelativeDate(visit_time
, &midnight
);
199 if (date_str
.empty()) {
200 date_str
= base::TimeFormatFriendlyDate(visit_time
);
202 date_str
= l10n_util::GetStringFUTF16(
203 IDS_HISTORY_DATE_WITH_RELATIVE_TIME
,
205 base::TimeFormatFriendlyDate(visit_time
));
211 // Sets the correct year when substracting months from a date.
212 void normalizeMonths(base::Time::Exploded
* exploded
) {
213 // Decrease a year at a time until we have a proper date.
214 while (exploded
->month
< 1) {
215 exploded
->month
+= 12;
220 // Returns true if |entry| represents a local visit that had no corresponding
221 // visit on the server.
222 bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry
& entry
) {
223 return entry
.entry_type
== BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY
;
226 // Gets the name and type of a device for the given sync client ID.
227 // |name| and |type| are out parameters.
228 void GetDeviceNameAndType(const ProfileSyncService
* sync_service
,
229 const std::string
& client_id
,
232 if (sync_service
&& sync_service
->sync_initialized()) {
233 scoped_ptr
<browser_sync::DeviceInfo
> device_info
=
234 sync_service
->GetDeviceInfo(client_id
);
235 if (device_info
.get()) {
236 *name
= device_info
->client_name();
237 switch (device_info
->device_type()) {
238 case sync_pb::SyncEnums::TYPE_PHONE
:
239 *type
= kDeviceTypePhone
;
241 case sync_pb::SyncEnums::TYPE_TABLET
:
242 *type
= kDeviceTypeTablet
;
245 *type
= kDeviceTypeLaptop
;
250 NOTREACHED() << "Got a remote history entry but no ProfileSyncService.";
252 *name
= l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE
);
253 *type
= kDeviceTypeLaptop
;
258 ////////////////////////////////////////////////////////////////////////////////
260 // BrowsingHistoryHandler
262 ////////////////////////////////////////////////////////////////////////////////
264 BrowsingHistoryHandler::HistoryEntry::HistoryEntry(
265 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type
,
266 const GURL
& url
, const base::string16
& title
, base::Time time
,
267 const std::string
& client_id
, bool is_search_result
,
268 const base::string16
& snippet
, bool blocked_visit
,
269 const std::string
& accept_languages
) {
270 this->entry_type
= entry_type
;
274 this->client_id
= client_id
;
275 all_timestamps
.insert(time
.ToInternalValue());
276 this->is_search_result
= is_search_result
;
277 this->snippet
= snippet
;
278 this->blocked_visit
= blocked_visit
;
279 this->accept_languages
= accept_languages
;
282 BrowsingHistoryHandler::HistoryEntry::HistoryEntry()
283 : entry_type(EMPTY_ENTRY
), is_search_result(false), blocked_visit(false) {
286 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {
289 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle(
290 base::DictionaryValue
* result
) const {
291 result
->SetString("url", url
.spec());
293 bool using_url_as_the_title
= false;
294 base::string16
title_to_set(title
);
296 using_url_as_the_title
= true;
297 title_to_set
= base::UTF8ToUTF16(url
.spec());
300 // Since the title can contain BiDi text, we need to mark the text as either
301 // RTL or LTR, depending on the characters in the string. If we use the URL
302 // as the title, we mark the title as LTR since URLs are always treated as
303 // left to right strings.
304 if (base::i18n::IsRTL()) {
305 if (using_url_as_the_title
)
306 base::i18n::WrapStringWithLTRFormatting(&title_to_set
);
308 base::i18n::AdjustStringForLocaleDirection(&title_to_set
);
310 result
->SetString("title", title_to_set
);
313 scoped_ptr
<base::DictionaryValue
> BrowsingHistoryHandler::HistoryEntry::ToValue(
314 BookmarkModel
* bookmark_model
,
315 ManagedUserService
* managed_user_service
,
316 const ProfileSyncService
* sync_service
) const {
317 scoped_ptr
<base::DictionaryValue
> result(new base::DictionaryValue());
318 SetUrlAndTitle(result
.get());
320 base::string16 domain
= net::IDNToUnicode(url
.host(), accept_languages
);
321 // When the domain is empty, use the scheme instead. This allows for a
322 // sensible treatment of e.g. file: URLs when group by domain is on.
324 domain
= base::UTF8ToUTF16(url
.scheme() + ":");
326 result
->SetString("domain", domain
);
327 result
->SetDouble("time", time
.ToJsTime());
329 // Pass the timestamps in a list.
330 scoped_ptr
<base::ListValue
> timestamps(new base::ListValue
);
331 for (std::set
<int64
>::const_iterator it
= all_timestamps
.begin();
332 it
!= all_timestamps
.end(); ++it
) {
333 timestamps
->AppendDouble(base::Time::FromInternalValue(*it
).ToJsTime());
335 result
->Set("allTimestamps", timestamps
.release());
337 // Always pass the short date since it is needed both in the search and in
339 result
->SetString("dateShort", base::TimeFormatShortDate(time
));
341 // Only pass in the strings we need (search results need a shortdate
342 // and snippet, browse results need day and time information).
343 if (is_search_result
) {
344 result
->SetString("snippet", snippet
);
346 base::Time midnight
= base::Time::Now().LocalMidnight();
347 base::string16 date_str
= ui::TimeFormat::RelativeDate(time
, &midnight
);
348 if (date_str
.empty()) {
349 date_str
= base::TimeFormatFriendlyDate(time
);
351 date_str
= l10n_util::GetStringFUTF16(
352 IDS_HISTORY_DATE_WITH_RELATIVE_TIME
,
354 base::TimeFormatFriendlyDate(time
));
356 result
->SetString("dateRelativeDay", date_str
);
357 result
->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time
));
359 result
->SetBoolean("starred", bookmark_model
->IsBookmarked(url
));
361 std::string device_name
;
362 std::string device_type
;
363 if (!client_id
.empty())
364 GetDeviceNameAndType(sync_service
, client_id
, &device_name
, &device_type
);
365 result
->SetString("deviceName", device_name
);
366 result
->SetString("deviceType", device_type
);
368 #if defined(ENABLE_MANAGED_USERS)
369 if (managed_user_service
) {
370 const ManagedModeURLFilter
* url_filter
=
371 managed_user_service
->GetURLFilterForUIThread();
372 int filtering_behavior
=
373 url_filter
->GetFilteringBehaviorForURL(url
.GetWithEmptyPath());
374 result
->SetInteger("hostFilteringBehavior", filtering_behavior
);
376 result
->SetBoolean("blockedVisit", blocked_visit
);
380 return result
.Pass();
383 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending(
384 const BrowsingHistoryHandler::HistoryEntry
& entry1
,
385 const BrowsingHistoryHandler::HistoryEntry
& entry2
) {
386 return entry1
.time
> entry2
.time
;
389 BrowsingHistoryHandler::BrowsingHistoryHandler() {}
391 BrowsingHistoryHandler::~BrowsingHistoryHandler() {
392 history_request_consumer_
.CancelAllRequests();
393 web_history_request_
.reset();
396 void BrowsingHistoryHandler::RegisterMessages() {
397 // Create our favicon data source.
398 Profile
* profile
= Profile::FromWebUI(web_ui());
399 content::URLDataSource::Add(
400 profile
, new FaviconSource(profile
, FaviconSource::ANY
));
402 // Get notifications when history is cleared.
403 registrar_
.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED
,
404 content::Source
<Profile
>(profile
->GetOriginalProfile()));
406 web_ui()->RegisterMessageCallback("queryHistory",
407 base::Bind(&BrowsingHistoryHandler::HandleQueryHistory
,
408 base::Unretained(this)));
409 web_ui()->RegisterMessageCallback("removeVisits",
410 base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits
,
411 base::Unretained(this)));
412 web_ui()->RegisterMessageCallback("clearBrowsingData",
413 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData
,
414 base::Unretained(this)));
415 web_ui()->RegisterMessageCallback("removeBookmark",
416 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark
,
417 base::Unretained(this)));
420 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(
421 const base::ListValue
* value
,
425 if (value
->GetDouble(index
, &double_value
)) {
426 *out_int
= static_cast<int>(double_value
);
433 void BrowsingHistoryHandler::WebHistoryTimeout() {
434 // TODO(dubroy): Communicate the failure to the front end.
435 if (!history_request_consumer_
.HasPendingRequests())
436 ReturnResultsToFrontEnd();
438 UMA_HISTOGRAM_ENUMERATION(
439 "WebHistory.QueryCompletion",
440 WEB_HISTORY_QUERY_TIMED_OUT
, NUM_WEB_HISTORY_QUERY_BUCKETS
);
443 void BrowsingHistoryHandler::QueryHistory(
444 base::string16 search_text
, const history::QueryOptions
& options
) {
445 Profile
* profile
= Profile::FromWebUI(web_ui());
447 // Anything in-flight is invalid.
448 history_request_consumer_
.CancelAllRequests();
449 web_history_request_
.reset();
451 query_results_
.clear();
452 results_info_value_
.Clear();
454 HistoryService
* hs
= HistoryServiceFactory::GetForProfile(
455 profile
, Profile::EXPLICIT_ACCESS
);
456 hs
->QueryHistory(search_text
,
458 &history_request_consumer_
,
459 base::Bind(&BrowsingHistoryHandler::QueryComplete
,
460 base::Unretained(this), search_text
, options
));
462 history::WebHistoryService
* web_history
=
463 WebHistoryServiceFactory::GetForProfile(profile
);
465 web_history_query_results_
.clear();
466 web_history_request_
= web_history
->QueryHistory(
469 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete
,
470 base::Unretained(this),
471 search_text
, options
,
472 base::TimeTicks::Now()));
473 // Start a timer so we know when to give up.
474 web_history_timer_
.Start(
475 FROM_HERE
, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds
),
476 this, &BrowsingHistoryHandler::WebHistoryTimeout
);
478 // Set this to false until the results actually arrive.
479 results_info_value_
.SetBoolean("hasSyncedResults", false);
483 void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue
* args
) {
484 history::QueryOptions options
;
486 // Parse the arguments from JavaScript. There are five required arguments:
487 // - the text to search for (may be empty)
488 // - the offset from which the search should start (in multiples of week or
489 // month, set by the next argument).
490 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range
492 // - the end time for the query. Only results older than this time will be
494 // - the maximum number of results to return (may be 0, meaning that there
496 base::string16 search_text
= ExtractStringValue(args
);
498 if (!args
->GetInteger(1, &offset
)) {
499 NOTREACHED() << "Failed to convert argument 1. ";
503 if (!args
->GetInteger(2, &range
)) {
504 NOTREACHED() << "Failed to convert argument 2. ";
508 if (range
== BrowsingHistoryHandler::MONTH
)
509 SetQueryTimeInMonths(offset
, &options
);
510 else if (range
== BrowsingHistoryHandler::WEEK
)
511 SetQueryTimeInWeeks(offset
, &options
);
514 if (!args
->GetDouble(3, &end_time
)) {
515 NOTREACHED() << "Failed to convert argument 3. ";
519 options
.end_time
= base::Time::FromJsTime(end_time
);
521 if (!ExtractIntegerValueAtIndex(args
, 4, &options
.max_count
)) {
522 NOTREACHED() << "Failed to convert argument 4.";
526 options
.duplicate_policy
= history::QueryOptions::REMOVE_DUPLICATES_PER_DAY
;
527 QueryHistory(search_text
, options
);
530 void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue
* args
) {
531 Profile
* profile
= Profile::FromWebUI(web_ui());
532 if (delete_task_tracker_
.HasTrackedTasks() ||
533 !profile
->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory
)) {
534 web_ui()->CallJavascriptFunction("deleteFailed");
538 HistoryService
* history_service
=
539 HistoryServiceFactory::GetForProfile(profile
, Profile::EXPLICIT_ACCESS
);
540 history::WebHistoryService
* web_history
=
541 WebHistoryServiceFactory::GetForProfile(profile
);
543 base::Time now
= base::Time::Now();
544 std::vector
<history::ExpireHistoryArgs
> expire_list
;
545 expire_list
.reserve(args
->GetSize());
547 DCHECK(urls_to_be_deleted_
.empty());
548 for (base::ListValue::const_iterator it
= args
->begin();
549 it
!= args
->end(); ++it
) {
550 base::DictionaryValue
* deletion
= NULL
;
552 base::ListValue
* timestamps
= NULL
;
554 // Each argument is a dictionary with properties "url" and "timestamps".
555 if (!((*it
)->GetAsDictionary(&deletion
) &&
556 deletion
->GetString("url", &url
) &&
557 deletion
->GetList("timestamps", ×tamps
))) {
558 NOTREACHED() << "Unable to extract arguments";
561 DCHECK(timestamps
->GetSize() > 0);
563 // In order to ensure that visits will be deleted from the server and other
564 // clients (even if they are offline), create a sync delete directive for
565 // each visit to be deleted.
566 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive
;
567 sync_pb::GlobalIdDirective
* global_id_directive
=
568 delete_directive
.mutable_global_id_directive();
571 history::ExpireHistoryArgs
* expire_args
= NULL
;
572 for (base::ListValue::const_iterator ts_iterator
= timestamps
->begin();
573 ts_iterator
!= timestamps
->end(); ++ts_iterator
) {
574 if (!(*ts_iterator
)->GetAsDouble(×tamp
)) {
575 NOTREACHED() << "Unable to extract visit timestamp.";
578 base::Time visit_time
= base::Time::FromJsTime(timestamp
);
581 expire_list
.resize(expire_list
.size() + 1);
582 expire_args
= &expire_list
.back();
583 expire_args
->SetTimeRangeForOneDay(visit_time
);
584 expire_args
->urls
.insert(gurl
);
585 urls_to_be_deleted_
.insert(gurl
);
587 // The local visit time is treated as a global ID for the visit.
588 global_id_directive
->add_global_id(visit_time
.ToInternalValue());
591 // Set the start and end time in microseconds since the Unix epoch.
592 global_id_directive
->set_start_time_usec(
593 (expire_args
->begin_time
- base::Time::UnixEpoch()).InMicroseconds());
595 // Delete directives shouldn't have an end time in the future.
596 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
597 base::Time end_time
= std::min(expire_args
->end_time
, now
);
599 // -1 because end time in delete directives is inclusive.
600 global_id_directive
->set_end_time_usec(
601 (end_time
- base::Time::UnixEpoch()).InMicroseconds() - 1);
603 // TODO(dubroy): Figure out the proper way to handle an error here.
605 history_service
->ProcessLocalDeleteDirective(delete_directive
);
608 history_service
->ExpireHistory(
610 base::Bind(&BrowsingHistoryHandler::RemoveComplete
,
611 base::Unretained(this)),
612 &delete_task_tracker_
);
615 web_history_delete_request_
= web_history
->ExpireHistory(
617 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete
,
618 base::Unretained(this)));
621 #if defined(ENABLE_EXTENSIONS)
622 // If the profile has activity logging enabled also clean up any URLs from
623 // the extension activity log. The extension activity log contains URLS
624 // which websites an extension has activity on so it will indirectly
625 // contain websites that a user has visited.
626 extensions::ActivityLog
* activity_log
=
627 extensions::ActivityLog::GetInstance(profile
);
628 for (std::vector
<history::ExpireHistoryArgs
>::const_iterator it
=
629 expire_list
.begin(); it
!= expire_list
.end(); ++it
) {
630 activity_log
->RemoveURLs(it
->urls
);
635 void BrowsingHistoryHandler::HandleClearBrowsingData(
636 const base::ListValue
* args
) {
637 #if defined(OS_ANDROID)
638 Profile
* profile
= Profile::FromWebUI(web_ui());
639 const TabModel
* tab_model
=
640 TabModelList::GetTabModelWithProfile(profile
);
642 tab_model
->OpenClearBrowsingData();
644 // TODO(beng): This is an improper direct dependency on Browser. Route this
645 // through some sort of delegate.
646 Browser
* browser
= chrome::FindBrowserWithWebContents(
647 web_ui()->GetWebContents());
648 chrome::ShowClearBrowsingDataDialog(browser
);
652 void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue
* args
) {
653 base::string16 url
= ExtractStringValue(args
);
654 Profile
* profile
= Profile::FromWebUI(web_ui());
655 BookmarkModel
* model
= BookmarkModelFactory::GetForProfile(profile
);
656 bookmark_utils::RemoveAllBookmarks(model
, GURL(url
));
660 void BrowsingHistoryHandler::MergeDuplicateResults(
661 std::vector
<BrowsingHistoryHandler::HistoryEntry
>* results
) {
662 std::vector
<BrowsingHistoryHandler::HistoryEntry
> new_results
;
663 // Pre-reserve the size of the new vector. Since we're working with pointers
664 // later on not doing this could lead to the vector being resized and to
665 // pointers to invalid locations.
666 new_results
.reserve(results
->size());
667 // Maps a URL to the most recent entry on a particular day.
668 std::map
<GURL
,BrowsingHistoryHandler::HistoryEntry
*>
671 // Keeps track of the day that |current_day_urls| is holding the URLs for,
672 // in order to handle removing per-day duplicates.
673 base::Time current_day_midnight
;
676 results
->begin(), results
->end(), HistoryEntry::SortByTimeDescending
);
678 for (std::vector
<BrowsingHistoryHandler::HistoryEntry
>::const_iterator it
=
679 results
->begin(); it
!= results
->end(); ++it
) {
680 // Reset the list of found URLs when a visit from a new day is encountered.
681 if (current_day_midnight
!= it
->time
.LocalMidnight()) {
682 current_day_entries
.clear();
683 current_day_midnight
= it
->time
.LocalMidnight();
686 // Keep this visit if it's the first visit to this URL on the current day.
687 if (current_day_entries
.count(it
->url
) == 0) {
688 new_results
.push_back(*it
);
689 current_day_entries
[it
->url
] = &new_results
.back();
691 // Keep track of the timestamps of all visits to the URL on the same day.
692 BrowsingHistoryHandler::HistoryEntry
* entry
=
693 current_day_entries
[it
->url
];
694 entry
->all_timestamps
.insert(
695 it
->all_timestamps
.begin(), it
->all_timestamps
.end());
697 if (entry
->entry_type
!= it
->entry_type
) {
699 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY
;
703 results
->swap(new_results
);
706 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() {
707 Profile
* profile
= Profile::FromWebUI(web_ui());
708 BookmarkModel
* bookmark_model
= BookmarkModelFactory::GetForProfile(profile
);
709 ManagedUserService
* managed_user_service
= NULL
;
710 #if defined(ENABLE_MANAGED_USERS)
711 if (profile
->IsManaged())
712 managed_user_service
= ManagedUserServiceFactory::GetForProfile(profile
);
714 ProfileSyncService
* sync_service
=
715 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile
);
717 // Combine the local and remote results into |query_results_|, and remove
719 if (!web_history_query_results_
.empty()) {
720 int local_result_count
= query_results_
.size();
721 query_results_
.insert(query_results_
.end(),
722 web_history_query_results_
.begin(),
723 web_history_query_results_
.end());
724 MergeDuplicateResults(&query_results_
);
726 if (local_result_count
) {
727 // In the best case, we expect that all local results are duplicated on
728 // the server. Keep track of how many are missing.
729 int missing_count
= std::count_if(
730 query_results_
.begin(), query_results_
.end(), IsLocalOnlyResult
);
731 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer",
732 missing_count
* 100.0 / local_result_count
);
736 // Convert the result vector into a ListValue.
737 base::ListValue results_value
;
738 for (std::vector
<BrowsingHistoryHandler::HistoryEntry
>::iterator it
=
739 query_results_
.begin(); it
!= query_results_
.end(); ++it
) {
740 scoped_ptr
<base::Value
> value(
741 it
->ToValue(bookmark_model
, managed_user_service
, sync_service
));
742 results_value
.Append(value
.release());
745 web_ui()->CallJavascriptFunction(
746 "historyResult", results_info_value_
, results_value
);
747 results_info_value_
.Clear();
748 query_results_
.clear();
749 web_history_query_results_
.clear();
752 void BrowsingHistoryHandler::QueryComplete(
753 const base::string16
& search_text
,
754 const history::QueryOptions
& options
,
755 HistoryService::Handle request_handle
,
756 history::QueryResults
* results
) {
757 DCHECK_EQ(0U, query_results_
.size());
758 query_results_
.reserve(results
->size());
759 const std::string accept_languages
= GetAcceptLanguages();
761 for (size_t i
= 0; i
< results
->size(); ++i
) {
762 history::URLResult
const &page
= (*results
)[i
];
763 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
764 query_results_
.push_back(
766 HistoryEntry::LOCAL_ENTRY
,
771 !search_text
.empty(),
772 page
.snippet().text(),
773 page
.blocked_visit(),
777 results_info_value_
.SetString("term", search_text
);
778 results_info_value_
.SetBoolean("finished", results
->reached_beginning());
780 // Add the specific dates that were searched to display them.
781 // TODO(sergiu): Put today if the start is in the future.
782 results_info_value_
.SetString("queryStartTime",
783 getRelativeDateLocalized(options
.begin_time
));
784 if (!options
.end_time
.is_null()) {
785 results_info_value_
.SetString("queryEndTime",
786 getRelativeDateLocalized(options
.end_time
-
787 base::TimeDelta::FromDays(1)));
789 results_info_value_
.SetString("queryEndTime",
790 getRelativeDateLocalized(base::Time::Now()));
792 if (!web_history_timer_
.IsRunning())
793 ReturnResultsToFrontEnd();
796 void BrowsingHistoryHandler::WebHistoryQueryComplete(
797 const base::string16
& search_text
,
798 const history::QueryOptions
& options
,
799 base::TimeTicks start_time
,
800 history::WebHistoryService::Request
* request
,
801 const base::DictionaryValue
* results_value
) {
802 base::TimeDelta delta
= base::TimeTicks::Now() - start_time
;
803 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta
);
804 const std::string accept_languages
= GetAcceptLanguages();
806 // If the response came in too late, do nothing.
807 // TODO(dubroy): Maybe show a banner, and prompt the user to reload?
808 if (!web_history_timer_
.IsRunning())
810 web_history_timer_
.Stop();
812 UMA_HISTOGRAM_ENUMERATION(
813 "WebHistory.QueryCompletion",
814 results_value
? WEB_HISTORY_QUERY_SUCCEEDED
: WEB_HISTORY_QUERY_FAILED
,
815 NUM_WEB_HISTORY_QUERY_BUCKETS
);
817 DCHECK_EQ(0U, web_history_query_results_
.size());
818 const base::ListValue
* events
= NULL
;
819 if (results_value
&& results_value
->GetList("event", &events
)) {
820 web_history_query_results_
.reserve(events
->GetSize());
821 for (unsigned int i
= 0; i
< events
->GetSize(); ++i
) {
822 const base::DictionaryValue
* event
= NULL
;
823 const base::DictionaryValue
* result
= NULL
;
824 const base::ListValue
* results
= NULL
;
825 const base::ListValue
* ids
= NULL
;
827 base::string16 title
;
828 base::Time visit_time
;
830 if (!(events
->GetDictionary(i
, &event
) &&
831 event
->GetList("result", &results
) &&
832 results
->GetDictionary(0, &result
) &&
833 result
->GetString("url", &url
) &&
834 result
->GetList("id", &ids
) &&
835 ids
->GetSize() > 0)) {
836 LOG(WARNING
) << "Improperly formed JSON response from history server.";
839 // Title is optional, so the return value is ignored here.
840 result
->GetString("title", &title
);
842 // Extract the timestamps of all the visits to this URL.
843 // They are referred to as "IDs" by the server.
844 for (int j
= 0; j
< static_cast<int>(ids
->GetSize()); ++j
) {
845 const base::DictionaryValue
* id
= NULL
;
846 std::string timestamp_string
;
847 int64 timestamp_usec
;
849 if (!(ids
->GetDictionary(j
, &id
) &&
850 id
->GetString("timestamp_usec", ×tamp_string
) &&
851 base::StringToInt64(timestamp_string
, ×tamp_usec
))) {
852 NOTREACHED() << "Unable to extract timestamp.";
855 // The timestamp on the server is a Unix time.
856 base::Time time
= base::Time::UnixEpoch() +
857 base::TimeDelta::FromMicroseconds(timestamp_usec
);
859 // Get the ID of the client that this visit came from.
860 std::string client_id
;
861 id
->GetString("client_id", &client_id
);
863 web_history_query_results_
.push_back(
865 HistoryEntry::REMOTE_ENTRY
,
870 !search_text
.empty(),
872 /* blocked_visit */ false,
876 } else if (results_value
) {
877 NOTREACHED() << "Failed to parse JSON response.";
879 results_info_value_
.SetBoolean("hasSyncedResults", results_value
!= NULL
);
880 if (!history_request_consumer_
.HasPendingRequests())
881 ReturnResultsToFrontEnd();
884 void BrowsingHistoryHandler::RemoveComplete() {
885 urls_to_be_deleted_
.clear();
887 // Notify the page that the deletion request is complete, but only if a web
888 // history delete request is not still pending.
889 if (!(web_history_delete_request_
.get() &&
890 web_history_delete_request_
->is_pending())) {
891 web_ui()->CallJavascriptFunction("deleteComplete");
895 void BrowsingHistoryHandler::RemoveWebHistoryComplete(
896 history::WebHistoryService::Request
* request
, bool success
) {
897 // TODO(dubroy): Should we handle failure somehow? Delete directives will
898 // ensure that the visits are eventually deleted, so maybe it's not necessary.
899 if (!delete_task_tracker_
.HasTrackedTasks())
903 void BrowsingHistoryHandler::SetQueryTimeInWeeks(
904 int offset
, history::QueryOptions
* options
) {
905 // LocalMidnight returns the beginning of the current day so get the
906 // beginning of the next one.
907 base::Time midnight
= base::Time::Now().LocalMidnight() +
908 base::TimeDelta::FromDays(1);
909 options
->end_time
= midnight
-
910 base::TimeDelta::FromDays(7 * offset
);
911 options
->begin_time
= midnight
-
912 base::TimeDelta::FromDays(7 * (offset
+ 1));
915 void BrowsingHistoryHandler::SetQueryTimeInMonths(
916 int offset
, history::QueryOptions
* options
) {
917 // Configure the begin point of the search to the start of the
919 base::Time::Exploded exploded
;
920 base::Time::Now().LocalMidnight().LocalExplode(&exploded
);
921 exploded
.day_of_month
= 1;
924 options
->begin_time
= base::Time::FromLocalExploded(exploded
);
926 // Set the end time of this first search to null (which will
927 // show results from the future, should the user's clock have
928 // been set incorrectly).
929 options
->end_time
= base::Time();
931 // Go back |offset| months in the past. The end time is not inclusive, so
932 // use the first day of the |offset| - 1 and |offset| months (e.g. for
933 // the last month, |offset| = 1, use the first days of the last month and
934 // the current month.
935 exploded
.month
-= offset
- 1;
936 // Set the correct year.
937 normalizeMonths(&exploded
);
938 options
->end_time
= base::Time::FromLocalExploded(exploded
);
941 // Set the correct year
942 normalizeMonths(&exploded
);
943 options
->begin_time
= base::Time::FromLocalExploded(exploded
);
947 // Helper function for Observe that determines if there are any differences
948 // between the URLs noticed for deletion and the ones we are expecting.
949 static bool DeletionsDiffer(const history::URLRows
& deleted_rows
,
950 const std::set
<GURL
>& urls_to_be_deleted
) {
951 if (deleted_rows
.size() != urls_to_be_deleted
.size())
953 for (history::URLRows::const_iterator i
= deleted_rows
.begin();
954 i
!= deleted_rows
.end(); ++i
) {
955 if (urls_to_be_deleted
.find(i
->url()) == urls_to_be_deleted
.end())
961 void BrowsingHistoryHandler::Observe(
963 const content::NotificationSource
& source
,
964 const content::NotificationDetails
& details
) {
965 if (type
!= chrome::NOTIFICATION_HISTORY_URLS_DELETED
) {
969 history::URLsDeletedDetails
* deletedDetails
=
970 content::Details
<history::URLsDeletedDetails
>(details
).ptr();
971 if (deletedDetails
->all_history
||
972 DeletionsDiffer(deletedDetails
->rows
, urls_to_be_deleted_
))
973 web_ui()->CallJavascriptFunction("historyDeleted");
976 std::string
BrowsingHistoryHandler::GetAcceptLanguages() const {
977 Profile
* profile
= Profile::FromWebUI(web_ui());
978 return profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
);
981 ////////////////////////////////////////////////////////////////////////////////
985 ////////////////////////////////////////////////////////////////////////////////
987 HistoryUI::HistoryUI(content::WebUI
* web_ui
) : WebUIController(web_ui
) {
988 web_ui
->AddMessageHandler(new BrowsingHistoryHandler());
989 web_ui
->AddMessageHandler(new MetricsHandler());
991 // On mobile we deal with foreign sessions differently.
992 #if !defined(OS_ANDROID) && !defined(OS_IOS)
993 if (chrome::IsInstantExtendedAPIEnabled()) {
994 web_ui
->AddMessageHandler(new browser_sync::ForeignSessionHandler());
995 web_ui
->AddMessageHandler(new NTPLoginHandler());
999 // Set up the chrome://history-frame/ source.
1000 Profile
* profile
= Profile::FromWebUI(web_ui
);
1001 content::WebUIDataSource::Add(profile
, CreateHistoryUIHTMLSource(profile
));
1005 const GURL
HistoryUI::GetHistoryURLWithSearchText(const base::string16
& text
) {
1006 return GURL(std::string(chrome::kChromeUIHistoryURL
) + "#q=" +
1007 net::EscapeQueryParamValue(base::UTF16ToUTF8(text
), true));
1011 base::RefCountedMemory
* HistoryUI::GetFaviconResourceBytes(
1012 ui::ScaleFactor scale_factor
) {
1013 return ResourceBundle::GetSharedInstance().
1014 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON
, scale_factor
);