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_factory.h"
24 #include "chrome/browser/chrome_notification_types.h"
25 #include "chrome/browser/history/history_notifications.h"
26 #include "chrome/browser/history/history_service_factory.h"
27 #include "chrome/browser/history/web_history_service.h"
28 #include "chrome/browser/history/web_history_service_factory.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/sync/profile_sync_service.h"
31 #include "chrome/browser/sync/profile_sync_service_factory.h"
32 #include "chrome/browser/ui/browser_finder.h"
33 #include "chrome/browser/ui/chrome_pages.h"
34 #include "chrome/browser/ui/webui/favicon_source.h"
35 #include "chrome/browser/ui/webui/metrics_handler.h"
36 #include "chrome/common/chrome_switches.h"
37 #include "chrome/common/pref_names.h"
38 #include "chrome/common/url_constants.h"
39 #include "chrome/grit/generated_resources.h"
40 #include "components/bookmarks/browser/bookmark_model.h"
41 #include "components/bookmarks/browser/bookmark_utils.h"
42 #include "components/history/core/browser/history_types.h"
43 #include "components/search/search.h"
44 #include "components/sync_driver/device_info.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/theme_resources.h"
52 #include "net/base/escape.h"
53 #include "net/base/net_util.h"
54 #include "sync/protocol/history_delete_directive_specifics.pb.h"
55 #include "ui/base/l10n/l10n_util.h"
56 #include "ui/base/l10n/time_format.h"
57 #include "ui/base/resource/resource_bundle.h"
58 #include "ui/base/webui/web_ui_util.h"
60 #if defined(ENABLE_EXTENSIONS)
61 #include "chrome/browser/extensions/activity_log/activity_log.h"
64 #if defined(ENABLE_MANAGED_USERS)
65 #include "chrome/browser/supervised_user/supervised_user_navigation_observer.h"
66 #include "chrome/browser/supervised_user/supervised_user_service.h"
67 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
68 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
71 #if defined(OS_ANDROID)
72 #include "chrome/browser/android/chromium_application.h"
75 #if !defined(OS_ANDROID) && !defined(OS_IOS)
76 #include "chrome/browser/ui/webui/ntp/foreign_session_handler.h"
77 #include "chrome/browser/ui/webui/ntp/ntp_login_handler.h"
80 static const char kStringsJsFile
[] = "strings.js";
81 static const char kHistoryJsFile
[] = "history.js";
82 static const char kOtherDevicesJsFile
[] = "other_devices.js";
84 // The amount of time to wait for a response from the WebHistoryService.
85 static const int kWebHistoryTimeoutSeconds
= 3;
89 // Buckets for UMA histograms.
90 enum WebHistoryQueryBuckets
{
91 WEB_HISTORY_QUERY_FAILED
= 0,
92 WEB_HISTORY_QUERY_SUCCEEDED
,
93 WEB_HISTORY_QUERY_TIMED_OUT
,
94 NUM_WEB_HISTORY_QUERY_BUCKETS
97 #if defined(OS_MACOSX)
98 const char kIncognitoModeShortcut
[] = "("
99 "\xE2\x87\xA7" // Shift symbol (U+21E7 'UPWARDS WHITE ARROW').
100 "\xE2\x8C\x98" // Command symbol (U+2318 'PLACE OF INTEREST SIGN').
102 #elif defined(OS_WIN)
103 const char kIncognitoModeShortcut
[] = "(Ctrl+Shift+N)";
105 const char kIncognitoModeShortcut
[] = "(Shift+Ctrl+N)";
108 // Identifiers for the type of device from which a history entry originated.
109 static const char kDeviceTypeLaptop
[] = "laptop";
110 static const char kDeviceTypePhone
[] = "phone";
111 static const char kDeviceTypeTablet
[] = "tablet";
113 content::WebUIDataSource
* CreateHistoryUIHTMLSource(Profile
* profile
) {
114 PrefService
* prefs
= profile
->GetPrefs();
116 content::WebUIDataSource
* source
=
117 content::WebUIDataSource::Create(chrome::kChromeUIHistoryFrameHost
);
118 source
->AddBoolean("isUserSignedIn",
119 !prefs
->GetString(prefs::kGoogleServicesUsername
).empty());
120 source
->AddLocalizedString("collapseSessionMenuItemText",
121 IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION
);
122 source
->AddLocalizedString("expandSessionMenuItemText",
123 IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION
);
124 source
->AddLocalizedString("restoreSessionMenuItemText",
125 IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL
);
126 source
->AddLocalizedString("xMore", IDS_OTHER_DEVICES_X_MORE
);
127 source
->AddLocalizedString("loading", IDS_HISTORY_LOADING
);
128 source
->AddLocalizedString("title", IDS_HISTORY_TITLE
);
129 source
->AddLocalizedString("newest", IDS_HISTORY_NEWEST
);
130 source
->AddLocalizedString("newer", IDS_HISTORY_NEWER
);
131 source
->AddLocalizedString("older", IDS_HISTORY_OLDER
);
132 source
->AddLocalizedString("searchResultsFor", IDS_HISTORY_SEARCHRESULTSFOR
);
133 source
->AddLocalizedString("history", IDS_HISTORY_BROWSERESULTS
);
134 source
->AddLocalizedString("cont", IDS_HISTORY_CONTINUED
);
135 source
->AddLocalizedString("searchButton", IDS_HISTORY_SEARCH_BUTTON
);
136 source
->AddLocalizedString("noSearchResults", IDS_HISTORY_NO_SEARCH_RESULTS
);
137 source
->AddLocalizedString("noResults", IDS_HISTORY_NO_RESULTS
);
138 source
->AddLocalizedString("historyInterval", IDS_HISTORY_INTERVAL
);
139 source
->AddLocalizedString("removeSelected",
140 IDS_HISTORY_REMOVE_SELECTED_ITEMS
);
141 source
->AddLocalizedString("clearAllHistory",
142 IDS_HISTORY_OPEN_CLEAR_BROWSING_DATA_DIALOG
);
145 l10n_util::GetStringFUTF16(IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING
,
146 base::UTF8ToUTF16(kIncognitoModeShortcut
)));
147 source
->AddLocalizedString("removeBookmark", IDS_HISTORY_REMOVE_BOOKMARK
);
148 source
->AddLocalizedString("actionMenuDescription",
149 IDS_HISTORY_ACTION_MENU_DESCRIPTION
);
150 source
->AddLocalizedString("removeFromHistory", IDS_HISTORY_REMOVE_PAGE
);
151 source
->AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE
);
152 source
->AddLocalizedString("groupByDomainLabel", IDS_GROUP_BY_DOMAIN_LABEL
);
153 source
->AddLocalizedString("rangeLabel", IDS_HISTORY_RANGE_LABEL
);
154 source
->AddLocalizedString("rangeAllTime", IDS_HISTORY_RANGE_ALL_TIME
);
155 source
->AddLocalizedString("rangeWeek", IDS_HISTORY_RANGE_WEEK
);
156 source
->AddLocalizedString("rangeMonth", IDS_HISTORY_RANGE_MONTH
);
157 source
->AddLocalizedString("rangeToday", IDS_HISTORY_RANGE_TODAY
);
158 source
->AddLocalizedString("rangeNext", IDS_HISTORY_RANGE_NEXT
);
159 source
->AddLocalizedString("rangePrevious", IDS_HISTORY_RANGE_PREVIOUS
);
160 source
->AddLocalizedString("numberVisits", IDS_HISTORY_NUMBER_VISITS
);
161 source
->AddLocalizedString("filterAllowed", IDS_HISTORY_FILTER_ALLOWED
);
162 source
->AddLocalizedString("filterBlocked", IDS_HISTORY_FILTER_BLOCKED
);
163 source
->AddLocalizedString("inContentPack", IDS_HISTORY_IN_CONTENT_PACK
);
164 source
->AddLocalizedString("allowItems", IDS_HISTORY_FILTER_ALLOW_ITEMS
);
165 source
->AddLocalizedString("blockItems", IDS_HISTORY_FILTER_BLOCK_ITEMS
);
166 source
->AddLocalizedString("lockButton", IDS_HISTORY_LOCK_BUTTON
);
167 source
->AddLocalizedString("blockedVisitText",
168 IDS_HISTORY_BLOCKED_VISIT_TEXT
);
169 source
->AddLocalizedString("unlockButton", IDS_HISTORY_UNLOCK_BUTTON
);
170 source
->AddLocalizedString("hasSyncedResults",
171 IDS_HISTORY_HAS_SYNCED_RESULTS
);
172 source
->AddLocalizedString("noSyncedResults", IDS_HISTORY_NO_SYNCED_RESULTS
);
173 source
->AddLocalizedString("cancel", IDS_CANCEL
);
174 source
->AddLocalizedString("deleteConfirm",
175 IDS_HISTORY_DELETE_PRIOR_VISITS_CONFIRM_BUTTON
);
176 source
->AddBoolean("isFullHistorySyncEnabled",
177 WebHistoryServiceFactory::GetForProfile(profile
) != NULL
);
178 source
->AddBoolean("groupByDomain",
179 CommandLine::ForCurrentProcess()->HasSwitch(
180 switches::kHistoryEnableGroupByDomain
));
181 source
->AddBoolean("allowDeletingHistory",
182 prefs
->GetBoolean(prefs::kAllowDeletingBrowserHistory
));
183 source
->AddBoolean("isInstantExtendedApiEnabled",
184 chrome::IsInstantExtendedAPIEnabled());
186 source
->SetJsonPath(kStringsJsFile
);
187 source
->AddResourcePath(kHistoryJsFile
, IDR_HISTORY_JS
);
188 source
->AddResourcePath(kOtherDevicesJsFile
, IDR_OTHER_DEVICES_JS
);
189 source
->SetDefaultResource(IDR_HISTORY_HTML
);
190 source
->DisableDenyXFrameOptions();
191 source
->AddBoolean("isSupervisedProfile", profile
->IsSupervised());
192 source
->AddBoolean("showDeleteVisitUI", !profile
->IsSupervised());
197 // Returns a localized version of |visit_time| including a relative
198 // indicator (e.g. today, yesterday).
199 base::string16
getRelativeDateLocalized(const base::Time
& visit_time
) {
200 base::Time midnight
= base::Time::Now().LocalMidnight();
201 base::string16 date_str
= ui::TimeFormat::RelativeDate(visit_time
, &midnight
);
202 if (date_str
.empty()) {
203 date_str
= base::TimeFormatFriendlyDate(visit_time
);
205 date_str
= l10n_util::GetStringFUTF16(
206 IDS_HISTORY_DATE_WITH_RELATIVE_TIME
,
208 base::TimeFormatFriendlyDate(visit_time
));
214 // Sets the correct year when substracting months from a date.
215 void normalizeMonths(base::Time::Exploded
* exploded
) {
216 // Decrease a year at a time until we have a proper date.
217 while (exploded
->month
< 1) {
218 exploded
->month
+= 12;
223 // Returns true if |entry| represents a local visit that had no corresponding
224 // visit on the server.
225 bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry
& entry
) {
226 return entry
.entry_type
== BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY
;
229 // Gets the name and type of a device for the given sync client ID.
230 // |name| and |type| are out parameters.
231 void GetDeviceNameAndType(const ProfileSyncService
* sync_service
,
232 const std::string
& client_id
,
235 // DeviceInfoTracker becomes available when Sync backend gets initialed.
236 // It must exist in order for remote history entries to be available.
237 if (sync_service
&& sync_service
->GetDeviceInfoTracker()) {
238 scoped_ptr
<sync_driver::DeviceInfo
> device_info
=
239 sync_service
->GetDeviceInfoTracker()->GetDeviceInfo(client_id
);
240 if (device_info
.get()) {
241 *name
= device_info
->client_name();
242 switch (device_info
->device_type()) {
243 case sync_pb::SyncEnums::TYPE_PHONE
:
244 *type
= kDeviceTypePhone
;
246 case sync_pb::SyncEnums::TYPE_TABLET
:
247 *type
= kDeviceTypeTablet
;
250 *type
= kDeviceTypeLaptop
;
255 NOTREACHED() << "Got a remote history entry but no DeviceInfoTracker.";
257 *name
= l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE
);
258 *type
= kDeviceTypeLaptop
;
263 ////////////////////////////////////////////////////////////////////////////////
265 // BrowsingHistoryHandler
267 ////////////////////////////////////////////////////////////////////////////////
269 BrowsingHistoryHandler::HistoryEntry::HistoryEntry(
270 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type
,
271 const GURL
& url
, const base::string16
& title
, base::Time time
,
272 const std::string
& client_id
, bool is_search_result
,
273 const base::string16
& snippet
, bool blocked_visit
,
274 const std::string
& accept_languages
) {
275 this->entry_type
= entry_type
;
279 this->client_id
= client_id
;
280 all_timestamps
.insert(time
.ToInternalValue());
281 this->is_search_result
= is_search_result
;
282 this->snippet
= snippet
;
283 this->blocked_visit
= blocked_visit
;
284 this->accept_languages
= accept_languages
;
287 BrowsingHistoryHandler::HistoryEntry::HistoryEntry()
288 : entry_type(EMPTY_ENTRY
), is_search_result(false), blocked_visit(false) {
291 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {
294 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle(
295 base::DictionaryValue
* result
) const {
296 result
->SetString("url", url
.spec());
298 bool using_url_as_the_title
= false;
299 base::string16
title_to_set(title
);
301 using_url_as_the_title
= true;
302 title_to_set
= base::UTF8ToUTF16(url
.spec());
305 // Since the title can contain BiDi text, we need to mark the text as either
306 // RTL or LTR, depending on the characters in the string. If we use the URL
307 // as the title, we mark the title as LTR since URLs are always treated as
308 // left to right strings.
309 if (base::i18n::IsRTL()) {
310 if (using_url_as_the_title
)
311 base::i18n::WrapStringWithLTRFormatting(&title_to_set
);
313 base::i18n::AdjustStringForLocaleDirection(&title_to_set
);
315 result
->SetString("title", title_to_set
);
318 scoped_ptr
<base::DictionaryValue
> BrowsingHistoryHandler::HistoryEntry::ToValue(
319 BookmarkModel
* bookmark_model
,
320 SupervisedUserService
* supervised_user_service
,
321 const ProfileSyncService
* sync_service
) const {
322 scoped_ptr
<base::DictionaryValue
> result(new base::DictionaryValue());
323 SetUrlAndTitle(result
.get());
325 base::string16 domain
= net::IDNToUnicode(url
.host(), accept_languages
);
326 // When the domain is empty, use the scheme instead. This allows for a
327 // sensible treatment of e.g. file: URLs when group by domain is on.
329 domain
= base::UTF8ToUTF16(url
.scheme() + ":");
331 // The items which are to be written into result are also described in
332 // chrome/browser/resources/history/history.js in @typedef for
333 // HistoryEntry. Please update it whenever you add or remove
334 // any keys in result.
335 result
->SetString("domain", domain
);
336 result
->SetDouble("time", time
.ToJsTime());
338 // Pass the timestamps in a list.
339 scoped_ptr
<base::ListValue
> timestamps(new base::ListValue
);
340 for (std::set
<int64
>::const_iterator it
= all_timestamps
.begin();
341 it
!= all_timestamps
.end(); ++it
) {
342 timestamps
->AppendDouble(base::Time::FromInternalValue(*it
).ToJsTime());
344 result
->Set("allTimestamps", timestamps
.release());
346 // Always pass the short date since it is needed both in the search and in
348 result
->SetString("dateShort", base::TimeFormatShortDate(time
));
350 // Only pass in the strings we need (search results need a shortdate
351 // and snippet, browse results need day and time information).
352 if (is_search_result
) {
353 result
->SetString("snippet", snippet
);
355 base::Time midnight
= base::Time::Now().LocalMidnight();
356 base::string16 date_str
= ui::TimeFormat::RelativeDate(time
, &midnight
);
357 if (date_str
.empty()) {
358 date_str
= base::TimeFormatFriendlyDate(time
);
360 date_str
= l10n_util::GetStringFUTF16(
361 IDS_HISTORY_DATE_WITH_RELATIVE_TIME
,
363 base::TimeFormatFriendlyDate(time
));
365 result
->SetString("dateRelativeDay", date_str
);
366 result
->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time
));
368 result
->SetBoolean("starred", bookmark_model
->IsBookmarked(url
));
370 std::string device_name
;
371 std::string device_type
;
372 if (!client_id
.empty())
373 GetDeviceNameAndType(sync_service
, client_id
, &device_name
, &device_type
);
374 result
->SetString("deviceName", device_name
);
375 result
->SetString("deviceType", device_type
);
377 #if defined(ENABLE_MANAGED_USERS)
378 if (supervised_user_service
) {
379 const SupervisedUserURLFilter
* url_filter
=
380 supervised_user_service
->GetURLFilterForUIThread();
381 int filtering_behavior
=
382 url_filter
->GetFilteringBehaviorForURL(url
.GetWithEmptyPath());
383 result
->SetInteger("hostFilteringBehavior", filtering_behavior
);
385 result
->SetBoolean("blockedVisit", blocked_visit
);
389 return result
.Pass();
392 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending(
393 const BrowsingHistoryHandler::HistoryEntry
& entry1
,
394 const BrowsingHistoryHandler::HistoryEntry
& entry2
) {
395 return entry1
.time
> entry2
.time
;
398 BrowsingHistoryHandler::BrowsingHistoryHandler()
399 : has_pending_delete_request_(false),
400 weak_factory_(this) {
403 BrowsingHistoryHandler::~BrowsingHistoryHandler() {
404 query_task_tracker_
.TryCancelAll();
405 web_history_request_
.reset();
408 void BrowsingHistoryHandler::RegisterMessages() {
409 // Create our favicon data source.
410 Profile
* profile
= Profile::FromWebUI(web_ui());
411 content::URLDataSource::Add(
412 profile
, new FaviconSource(profile
, FaviconSource::ANY
));
414 // Get notifications when history is cleared.
415 registrar_
.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED
,
416 content::Source
<Profile
>(profile
->GetOriginalProfile()));
418 web_ui()->RegisterMessageCallback("queryHistory",
419 base::Bind(&BrowsingHistoryHandler::HandleQueryHistory
,
420 base::Unretained(this)));
421 web_ui()->RegisterMessageCallback("removeVisits",
422 base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits
,
423 base::Unretained(this)));
424 web_ui()->RegisterMessageCallback("clearBrowsingData",
425 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData
,
426 base::Unretained(this)));
427 web_ui()->RegisterMessageCallback("removeBookmark",
428 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark
,
429 base::Unretained(this)));
432 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(
433 const base::ListValue
* value
,
437 if (value
->GetDouble(index
, &double_value
)) {
438 *out_int
= static_cast<int>(double_value
);
445 void BrowsingHistoryHandler::WebHistoryTimeout() {
446 // TODO(dubroy): Communicate the failure to the front end.
447 if (!query_task_tracker_
.HasTrackedTasks())
448 ReturnResultsToFrontEnd();
450 UMA_HISTOGRAM_ENUMERATION(
451 "WebHistory.QueryCompletion",
452 WEB_HISTORY_QUERY_TIMED_OUT
, NUM_WEB_HISTORY_QUERY_BUCKETS
);
455 void BrowsingHistoryHandler::QueryHistory(
456 base::string16 search_text
, const history::QueryOptions
& options
) {
457 Profile
* profile
= Profile::FromWebUI(web_ui());
459 // Anything in-flight is invalid.
460 query_task_tracker_
.TryCancelAll();
461 web_history_request_
.reset();
463 query_results_
.clear();
464 results_info_value_
.Clear();
466 HistoryService
* hs
= HistoryServiceFactory::GetForProfile(
467 profile
, Profile::EXPLICIT_ACCESS
);
468 hs
->QueryHistory(search_text
,
470 base::Bind(&BrowsingHistoryHandler::QueryComplete
,
471 base::Unretained(this),
474 &query_task_tracker_
);
476 history::WebHistoryService
* web_history
=
477 WebHistoryServiceFactory::GetForProfile(profile
);
479 web_history_query_results_
.clear();
480 web_history_request_
= web_history
->QueryHistory(
483 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete
,
484 base::Unretained(this),
485 search_text
, options
,
486 base::TimeTicks::Now()));
487 // Start a timer so we know when to give up.
488 web_history_timer_
.Start(
489 FROM_HERE
, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds
),
490 this, &BrowsingHistoryHandler::WebHistoryTimeout
);
492 // Set this to false until the results actually arrive.
493 results_info_value_
.SetBoolean("hasSyncedResults", false);
497 void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue
* args
) {
498 history::QueryOptions options
;
500 // Parse the arguments from JavaScript. There are five required arguments:
501 // - the text to search for (may be empty)
502 // - the offset from which the search should start (in multiples of week or
503 // month, set by the next argument).
504 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range
506 // - the end time for the query. Only results older than this time will be
508 // - the maximum number of results to return (may be 0, meaning that there
510 base::string16 search_text
= ExtractStringValue(args
);
512 if (!args
->GetInteger(1, &offset
)) {
513 NOTREACHED() << "Failed to convert argument 1. ";
517 if (!args
->GetInteger(2, &range
)) {
518 NOTREACHED() << "Failed to convert argument 2. ";
522 if (range
== BrowsingHistoryHandler::MONTH
)
523 SetQueryTimeInMonths(offset
, &options
);
524 else if (range
== BrowsingHistoryHandler::WEEK
)
525 SetQueryTimeInWeeks(offset
, &options
);
528 if (!args
->GetDouble(3, &end_time
)) {
529 NOTREACHED() << "Failed to convert argument 3. ";
533 options
.end_time
= base::Time::FromJsTime(end_time
);
535 if (!ExtractIntegerValueAtIndex(args
, 4, &options
.max_count
)) {
536 NOTREACHED() << "Failed to convert argument 4.";
540 options
.duplicate_policy
= history::QueryOptions::REMOVE_DUPLICATES_PER_DAY
;
541 QueryHistory(search_text
, options
);
544 void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue
* args
) {
545 Profile
* profile
= Profile::FromWebUI(web_ui());
546 // TODO(davidben): history.js is not aware of this failure and will still
547 // override |deleteCompleteCallback_|.
548 if (delete_task_tracker_
.HasTrackedTasks() ||
549 has_pending_delete_request_
||
550 !profile
->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory
)) {
551 web_ui()->CallJavascriptFunction("deleteFailed");
555 HistoryService
* history_service
=
556 HistoryServiceFactory::GetForProfile(profile
, Profile::EXPLICIT_ACCESS
);
557 history::WebHistoryService
* web_history
=
558 WebHistoryServiceFactory::GetForProfile(profile
);
560 base::Time now
= base::Time::Now();
561 std::vector
<history::ExpireHistoryArgs
> expire_list
;
562 expire_list
.reserve(args
->GetSize());
564 DCHECK(urls_to_be_deleted_
.empty());
565 for (base::ListValue::const_iterator it
= args
->begin();
566 it
!= args
->end(); ++it
) {
567 base::DictionaryValue
* deletion
= NULL
;
569 base::ListValue
* timestamps
= NULL
;
571 // Each argument is a dictionary with properties "url" and "timestamps".
572 if (!((*it
)->GetAsDictionary(&deletion
) &&
573 deletion
->GetString("url", &url
) &&
574 deletion
->GetList("timestamps", ×tamps
))) {
575 NOTREACHED() << "Unable to extract arguments";
578 DCHECK(timestamps
->GetSize() > 0);
580 // In order to ensure that visits will be deleted from the server and other
581 // clients (even if they are offline), create a sync delete directive for
582 // each visit to be deleted.
583 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive
;
584 sync_pb::GlobalIdDirective
* global_id_directive
=
585 delete_directive
.mutable_global_id_directive();
588 history::ExpireHistoryArgs
* expire_args
= NULL
;
589 for (base::ListValue::const_iterator ts_iterator
= timestamps
->begin();
590 ts_iterator
!= timestamps
->end(); ++ts_iterator
) {
591 if (!(*ts_iterator
)->GetAsDouble(×tamp
)) {
592 NOTREACHED() << "Unable to extract visit timestamp.";
595 base::Time visit_time
= base::Time::FromJsTime(timestamp
);
598 expire_list
.resize(expire_list
.size() + 1);
599 expire_args
= &expire_list
.back();
600 expire_args
->SetTimeRangeForOneDay(visit_time
);
601 expire_args
->urls
.insert(gurl
);
602 urls_to_be_deleted_
.insert(gurl
);
604 // The local visit time is treated as a global ID for the visit.
605 global_id_directive
->add_global_id(visit_time
.ToInternalValue());
608 // Set the start and end time in microseconds since the Unix epoch.
609 global_id_directive
->set_start_time_usec(
610 (expire_args
->begin_time
- base::Time::UnixEpoch()).InMicroseconds());
612 // Delete directives shouldn't have an end time in the future.
613 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
614 base::Time end_time
= std::min(expire_args
->end_time
, now
);
616 // -1 because end time in delete directives is inclusive.
617 global_id_directive
->set_end_time_usec(
618 (end_time
- base::Time::UnixEpoch()).InMicroseconds() - 1);
620 // TODO(dubroy): Figure out the proper way to handle an error here.
622 history_service
->ProcessLocalDeleteDirective(delete_directive
);
625 history_service
->ExpireHistory(
627 base::Bind(&BrowsingHistoryHandler::RemoveComplete
,
628 base::Unretained(this)),
629 &delete_task_tracker_
);
632 has_pending_delete_request_
= true;
633 web_history
->ExpireHistory(
635 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete
,
636 weak_factory_
.GetWeakPtr()));
639 #if defined(ENABLE_EXTENSIONS)
640 // If the profile has activity logging enabled also clean up any URLs from
641 // the extension activity log. The extension activity log contains URLS
642 // which websites an extension has activity on so it will indirectly
643 // contain websites that a user has visited.
644 extensions::ActivityLog
* activity_log
=
645 extensions::ActivityLog::GetInstance(profile
);
646 for (std::vector
<history::ExpireHistoryArgs
>::const_iterator it
=
647 expire_list
.begin(); it
!= expire_list
.end(); ++it
) {
648 activity_log
->RemoveURLs(it
->urls
);
653 void BrowsingHistoryHandler::HandleClearBrowsingData(
654 const base::ListValue
* args
) {
655 #if defined(OS_ANDROID)
656 chrome::android::ChromiumApplication::OpenClearBrowsingData(
657 web_ui()->GetWebContents());
659 // TODO(beng): This is an improper direct dependency on Browser. Route this
660 // through some sort of delegate.
661 Browser
* browser
= chrome::FindBrowserWithWebContents(
662 web_ui()->GetWebContents());
663 chrome::ShowClearBrowsingDataDialog(browser
);
667 void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue
* args
) {
668 base::string16 url
= ExtractStringValue(args
);
669 Profile
* profile
= Profile::FromWebUI(web_ui());
670 BookmarkModel
* model
= BookmarkModelFactory::GetForProfile(profile
);
671 bookmarks::RemoveAllBookmarks(model
, GURL(url
));
675 void BrowsingHistoryHandler::MergeDuplicateResults(
676 std::vector
<BrowsingHistoryHandler::HistoryEntry
>* results
) {
677 std::vector
<BrowsingHistoryHandler::HistoryEntry
> new_results
;
678 // Pre-reserve the size of the new vector. Since we're working with pointers
679 // later on not doing this could lead to the vector being resized and to
680 // pointers to invalid locations.
681 new_results
.reserve(results
->size());
682 // Maps a URL to the most recent entry on a particular day.
683 std::map
<GURL
, BrowsingHistoryHandler::HistoryEntry
*> current_day_entries
;
685 // Keeps track of the day that |current_day_urls| is holding the URLs for,
686 // in order to handle removing per-day duplicates.
687 base::Time current_day_midnight
;
690 results
->begin(), results
->end(), HistoryEntry::SortByTimeDescending
);
692 for (std::vector
<BrowsingHistoryHandler::HistoryEntry
>::const_iterator it
=
693 results
->begin(); it
!= results
->end(); ++it
) {
694 // Reset the list of found URLs when a visit from a new day is encountered.
695 if (current_day_midnight
!= it
->time
.LocalMidnight()) {
696 current_day_entries
.clear();
697 current_day_midnight
= it
->time
.LocalMidnight();
700 // Keep this visit if it's the first visit to this URL on the current day.
701 if (current_day_entries
.count(it
->url
) == 0) {
702 new_results
.push_back(*it
);
703 current_day_entries
[it
->url
] = &new_results
.back();
705 // Keep track of the timestamps of all visits to the URL on the same day.
706 BrowsingHistoryHandler::HistoryEntry
* entry
=
707 current_day_entries
[it
->url
];
708 entry
->all_timestamps
.insert(
709 it
->all_timestamps
.begin(), it
->all_timestamps
.end());
711 if (entry
->entry_type
!= it
->entry_type
) {
713 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY
;
717 results
->swap(new_results
);
720 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() {
721 Profile
* profile
= Profile::FromWebUI(web_ui());
722 BookmarkModel
* bookmark_model
= BookmarkModelFactory::GetForProfile(profile
);
723 SupervisedUserService
* supervised_user_service
= NULL
;
724 #if defined(ENABLE_MANAGED_USERS)
725 if (profile
->IsSupervised())
726 supervised_user_service
=
727 SupervisedUserServiceFactory::GetForProfile(profile
);
729 ProfileSyncService
* sync_service
=
730 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile
);
732 // Combine the local and remote results into |query_results_|, and remove
734 if (!web_history_query_results_
.empty()) {
735 int local_result_count
= query_results_
.size();
736 query_results_
.insert(query_results_
.end(),
737 web_history_query_results_
.begin(),
738 web_history_query_results_
.end());
739 MergeDuplicateResults(&query_results_
);
741 if (local_result_count
) {
742 // In the best case, we expect that all local results are duplicated on
743 // the server. Keep track of how many are missing.
744 int missing_count
= std::count_if(
745 query_results_
.begin(), query_results_
.end(), IsLocalOnlyResult
);
746 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer",
747 missing_count
* 100.0 / local_result_count
);
751 // Convert the result vector into a ListValue.
752 base::ListValue results_value
;
753 for (std::vector
<BrowsingHistoryHandler::HistoryEntry
>::iterator it
=
754 query_results_
.begin(); it
!= query_results_
.end(); ++it
) {
755 scoped_ptr
<base::Value
> value(
756 it
->ToValue(bookmark_model
, supervised_user_service
, sync_service
));
757 results_value
.Append(value
.release());
760 web_ui()->CallJavascriptFunction(
761 "historyResult", results_info_value_
, results_value
);
762 results_info_value_
.Clear();
763 query_results_
.clear();
764 web_history_query_results_
.clear();
767 void BrowsingHistoryHandler::QueryComplete(
768 const base::string16
& search_text
,
769 const history::QueryOptions
& options
,
770 history::QueryResults
* results
) {
771 DCHECK_EQ(0U, query_results_
.size());
772 query_results_
.reserve(results
->size());
773 const std::string accept_languages
= GetAcceptLanguages();
775 for (size_t i
= 0; i
< results
->size(); ++i
) {
776 history::URLResult
const &page
= (*results
)[i
];
777 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
778 query_results_
.push_back(
780 HistoryEntry::LOCAL_ENTRY
,
785 !search_text
.empty(),
786 page
.snippet().text(),
787 page
.blocked_visit(),
791 // The items which are to be written into results_info_value_ are also
792 // described in chrome/browser/resources/history/history.js in @typedef for
793 // HistoryQuery. Please update it whenever you add or remove any keys in
794 // results_info_value_.
795 results_info_value_
.SetString("term", search_text
);
796 results_info_value_
.SetBoolean("finished", results
->reached_beginning());
798 // Add the specific dates that were searched to display them.
799 // TODO(sergiu): Put today if the start is in the future.
800 results_info_value_
.SetString("queryStartTime",
801 getRelativeDateLocalized(options
.begin_time
));
802 if (!options
.end_time
.is_null()) {
803 results_info_value_
.SetString("queryEndTime",
804 getRelativeDateLocalized(options
.end_time
-
805 base::TimeDelta::FromDays(1)));
807 results_info_value_
.SetString("queryEndTime",
808 getRelativeDateLocalized(base::Time::Now()));
810 if (!web_history_timer_
.IsRunning())
811 ReturnResultsToFrontEnd();
814 void BrowsingHistoryHandler::WebHistoryQueryComplete(
815 const base::string16
& search_text
,
816 const history::QueryOptions
& options
,
817 base::TimeTicks start_time
,
818 history::WebHistoryService::Request
* request
,
819 const base::DictionaryValue
* results_value
) {
820 base::TimeDelta delta
= base::TimeTicks::Now() - start_time
;
821 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta
);
822 const std::string accept_languages
= GetAcceptLanguages();
824 // If the response came in too late, do nothing.
825 // TODO(dubroy): Maybe show a banner, and prompt the user to reload?
826 if (!web_history_timer_
.IsRunning())
828 web_history_timer_
.Stop();
830 UMA_HISTOGRAM_ENUMERATION(
831 "WebHistory.QueryCompletion",
832 results_value
? WEB_HISTORY_QUERY_SUCCEEDED
: WEB_HISTORY_QUERY_FAILED
,
833 NUM_WEB_HISTORY_QUERY_BUCKETS
);
835 DCHECK_EQ(0U, web_history_query_results_
.size());
836 const base::ListValue
* events
= NULL
;
837 if (results_value
&& results_value
->GetList("event", &events
)) {
838 web_history_query_results_
.reserve(events
->GetSize());
839 for (unsigned int i
= 0; i
< events
->GetSize(); ++i
) {
840 const base::DictionaryValue
* event
= NULL
;
841 const base::DictionaryValue
* result
= NULL
;
842 const base::ListValue
* results
= NULL
;
843 const base::ListValue
* ids
= NULL
;
845 base::string16 title
;
846 base::Time visit_time
;
848 if (!(events
->GetDictionary(i
, &event
) &&
849 event
->GetList("result", &results
) &&
850 results
->GetDictionary(0, &result
) &&
851 result
->GetString("url", &url
) &&
852 result
->GetList("id", &ids
) &&
853 ids
->GetSize() > 0)) {
854 LOG(WARNING
) << "Improperly formed JSON response from history server.";
857 // Title is optional, so the return value is ignored here.
858 result
->GetString("title", &title
);
860 // Extract the timestamps of all the visits to this URL.
861 // They are referred to as "IDs" by the server.
862 for (int j
= 0; j
< static_cast<int>(ids
->GetSize()); ++j
) {
863 const base::DictionaryValue
* id
= NULL
;
864 std::string timestamp_string
;
865 int64 timestamp_usec
= 0;
867 if (!ids
->GetDictionary(j
, &id
) ||
868 !id
->GetString("timestamp_usec", ×tamp_string
) ||
869 !base::StringToInt64(timestamp_string
, ×tamp_usec
)) {
870 NOTREACHED() << "Unable to extract timestamp.";
873 // The timestamp on the server is a Unix time.
874 base::Time time
= base::Time::UnixEpoch() +
875 base::TimeDelta::FromMicroseconds(timestamp_usec
);
877 // Get the ID of the client that this visit came from.
878 std::string client_id
;
879 id
->GetString("client_id", &client_id
);
881 web_history_query_results_
.push_back(
883 HistoryEntry::REMOTE_ENTRY
,
888 !search_text
.empty(),
890 /* blocked_visit */ false,
894 } else if (results_value
) {
895 NOTREACHED() << "Failed to parse JSON response.";
897 results_info_value_
.SetBoolean("hasSyncedResults", results_value
!= NULL
);
898 if (!query_task_tracker_
.HasTrackedTasks())
899 ReturnResultsToFrontEnd();
902 void BrowsingHistoryHandler::RemoveComplete() {
903 urls_to_be_deleted_
.clear();
905 // Notify the page that the deletion request is complete, but only if a web
906 // history delete request is not still pending.
907 if (!has_pending_delete_request_
)
908 web_ui()->CallJavascriptFunction("deleteComplete");
911 void BrowsingHistoryHandler::RemoveWebHistoryComplete(bool success
) {
912 has_pending_delete_request_
= false;
913 // TODO(dubroy): Should we handle failure somehow? Delete directives will
914 // ensure that the visits are eventually deleted, so maybe it's not necessary.
915 if (!delete_task_tracker_
.HasTrackedTasks())
919 void BrowsingHistoryHandler::SetQueryTimeInWeeks(
920 int offset
, history::QueryOptions
* options
) {
921 // LocalMidnight returns the beginning of the current day so get the
922 // beginning of the next one.
923 base::Time midnight
= base::Time::Now().LocalMidnight() +
924 base::TimeDelta::FromDays(1);
925 options
->end_time
= midnight
-
926 base::TimeDelta::FromDays(7 * offset
);
927 options
->begin_time
= midnight
-
928 base::TimeDelta::FromDays(7 * (offset
+ 1));
931 void BrowsingHistoryHandler::SetQueryTimeInMonths(
932 int offset
, history::QueryOptions
* options
) {
933 // Configure the begin point of the search to the start of the
935 base::Time::Exploded exploded
;
936 base::Time::Now().LocalMidnight().LocalExplode(&exploded
);
937 exploded
.day_of_month
= 1;
940 options
->begin_time
= base::Time::FromLocalExploded(exploded
);
942 // Set the end time of this first search to null (which will
943 // show results from the future, should the user's clock have
944 // been set incorrectly).
945 options
->end_time
= base::Time();
947 // Go back |offset| months in the past. The end time is not inclusive, so
948 // use the first day of the |offset| - 1 and |offset| months (e.g. for
949 // the last month, |offset| = 1, use the first days of the last month and
950 // the current month.
951 exploded
.month
-= offset
- 1;
952 // Set the correct year.
953 normalizeMonths(&exploded
);
954 options
->end_time
= base::Time::FromLocalExploded(exploded
);
957 // Set the correct year
958 normalizeMonths(&exploded
);
959 options
->begin_time
= base::Time::FromLocalExploded(exploded
);
963 // Helper function for Observe that determines if there are any differences
964 // between the URLs noticed for deletion and the ones we are expecting.
965 static bool DeletionsDiffer(const history::URLRows
& deleted_rows
,
966 const std::set
<GURL
>& urls_to_be_deleted
) {
967 if (deleted_rows
.size() != urls_to_be_deleted
.size())
969 for (history::URLRows::const_iterator i
= deleted_rows
.begin();
970 i
!= deleted_rows
.end(); ++i
) {
971 if (urls_to_be_deleted
.find(i
->url()) == urls_to_be_deleted
.end())
977 void BrowsingHistoryHandler::Observe(
979 const content::NotificationSource
& source
,
980 const content::NotificationDetails
& details
) {
981 if (type
!= chrome::NOTIFICATION_HISTORY_URLS_DELETED
) {
985 history::URLsDeletedDetails
* deletedDetails
=
986 content::Details
<history::URLsDeletedDetails
>(details
).ptr();
987 if (deletedDetails
->all_history
||
988 DeletionsDiffer(deletedDetails
->rows
, urls_to_be_deleted_
))
989 web_ui()->CallJavascriptFunction("historyDeleted");
992 std::string
BrowsingHistoryHandler::GetAcceptLanguages() const {
993 Profile
* profile
= Profile::FromWebUI(web_ui());
994 return profile
->GetPrefs()->GetString(prefs::kAcceptLanguages
);
997 ////////////////////////////////////////////////////////////////////////////////
1001 ////////////////////////////////////////////////////////////////////////////////
1003 HistoryUI::HistoryUI(content::WebUI
* web_ui
) : WebUIController(web_ui
) {
1004 web_ui
->AddMessageHandler(new BrowsingHistoryHandler());
1005 web_ui
->AddMessageHandler(new MetricsHandler());
1007 // On mobile we deal with foreign sessions differently.
1008 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1009 if (chrome::IsInstantExtendedAPIEnabled()) {
1010 web_ui
->AddMessageHandler(new browser_sync::ForeignSessionHandler());
1011 web_ui
->AddMessageHandler(new NTPLoginHandler());
1015 // Set up the chrome://history-frame/ source.
1016 Profile
* profile
= Profile::FromWebUI(web_ui
);
1017 content::WebUIDataSource::Add(profile
, CreateHistoryUIHTMLSource(profile
));
1021 base::RefCountedMemory
* HistoryUI::GetFaviconResourceBytes(
1022 ui::ScaleFactor scale_factor
) {
1023 return ResourceBundle::GetSharedInstance().
1024 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON
, scale_factor
);