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->AddLocalizedString("bookmarked", IDS_HISTORY_ENTRY_BOOKMARKED);
177 source->AddLocalizedString("entrySummary", IDS_HISTORY_ENTRY_SUMMARY);
178 source->AddBoolean("isFullHistorySyncEnabled",
179 WebHistoryServiceFactory::GetForProfile(profile) != NULL);
180 source->AddBoolean("groupByDomain",
181 CommandLine::ForCurrentProcess()->HasSwitch(
182 switches::kHistoryEnableGroupByDomain));
183 source->AddBoolean("allowDeletingHistory",
184 prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory));
185 source->AddBoolean("isInstantExtendedApiEnabled",
186 chrome::IsInstantExtendedAPIEnabled());
188 source->SetJsonPath(kStringsJsFile);
189 source->AddResourcePath(kHistoryJsFile, IDR_HISTORY_JS);
190 source->AddResourcePath(kOtherDevicesJsFile, IDR_OTHER_DEVICES_JS);
191 source->SetDefaultResource(IDR_HISTORY_HTML);
192 source->DisableDenyXFrameOptions();
193 source->AddBoolean("isSupervisedProfile", profile->IsSupervised());
194 source->AddBoolean("showDeleteVisitUI", !profile->IsSupervised());
199 // Returns a localized version of |visit_time| including a relative
200 // indicator (e.g. today, yesterday).
201 base::string16 getRelativeDateLocalized(const base::Time& visit_time) {
202 base::Time midnight = base::Time::Now().LocalMidnight();
203 base::string16 date_str = ui::TimeFormat::RelativeDate(visit_time, &midnight);
204 if (date_str.empty()) {
205 date_str = base::TimeFormatFriendlyDate(visit_time);
207 date_str = l10n_util::GetStringFUTF16(
208 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
210 base::TimeFormatFriendlyDate(visit_time));
216 // Sets the correct year when substracting months from a date.
217 void normalizeMonths(base::Time::Exploded* exploded) {
218 // Decrease a year at a time until we have a proper date.
219 while (exploded->month < 1) {
220 exploded->month += 12;
225 // Returns true if |entry| represents a local visit that had no corresponding
226 // visit on the server.
227 bool IsLocalOnlyResult(const BrowsingHistoryHandler::HistoryEntry& entry) {
228 return entry.entry_type == BrowsingHistoryHandler::HistoryEntry::LOCAL_ENTRY;
231 // Gets the name and type of a device for the given sync client ID.
232 // |name| and |type| are out parameters.
233 void GetDeviceNameAndType(const ProfileSyncService* sync_service,
234 const std::string& client_id,
237 // DeviceInfoTracker becomes available when Sync backend gets initialed.
238 // It must exist in order for remote history entries to be available.
239 if (sync_service && sync_service->GetDeviceInfoTracker()) {
240 scoped_ptr<sync_driver::DeviceInfo> device_info =
241 sync_service->GetDeviceInfoTracker()->GetDeviceInfo(client_id);
242 if (device_info.get()) {
243 *name = device_info->client_name();
244 switch (device_info->device_type()) {
245 case sync_pb::SyncEnums::TYPE_PHONE:
246 *type = kDeviceTypePhone;
248 case sync_pb::SyncEnums::TYPE_TABLET:
249 *type = kDeviceTypeTablet;
252 *type = kDeviceTypeLaptop;
257 NOTREACHED() << "Got a remote history entry but no DeviceInfoTracker.";
259 *name = l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE);
260 *type = kDeviceTypeLaptop;
265 ////////////////////////////////////////////////////////////////////////////////
267 // BrowsingHistoryHandler
269 ////////////////////////////////////////////////////////////////////////////////
271 BrowsingHistoryHandler::HistoryEntry::HistoryEntry(
272 BrowsingHistoryHandler::HistoryEntry::EntryType entry_type,
273 const GURL& url, const base::string16& title, base::Time time,
274 const std::string& client_id, bool is_search_result,
275 const base::string16& snippet, bool blocked_visit,
276 const std::string& accept_languages) {
277 this->entry_type = entry_type;
281 this->client_id = client_id;
282 all_timestamps.insert(time.ToInternalValue());
283 this->is_search_result = is_search_result;
284 this->snippet = snippet;
285 this->blocked_visit = blocked_visit;
286 this->accept_languages = accept_languages;
289 BrowsingHistoryHandler::HistoryEntry::HistoryEntry()
290 : entry_type(EMPTY_ENTRY), is_search_result(false), blocked_visit(false) {
293 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() {
296 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle(
297 base::DictionaryValue* result) const {
298 result->SetString("url", url.spec());
300 bool using_url_as_the_title = false;
301 base::string16 title_to_set(title);
303 using_url_as_the_title = true;
304 title_to_set = base::UTF8ToUTF16(url.spec());
307 // Since the title can contain BiDi text, we need to mark the text as either
308 // RTL or LTR, depending on the characters in the string. If we use the URL
309 // as the title, we mark the title as LTR since URLs are always treated as
310 // left to right strings.
311 if (base::i18n::IsRTL()) {
312 if (using_url_as_the_title)
313 base::i18n::WrapStringWithLTRFormatting(&title_to_set);
315 base::i18n::AdjustStringForLocaleDirection(&title_to_set);
317 result->SetString("title", title_to_set);
320 scoped_ptr<base::DictionaryValue> BrowsingHistoryHandler::HistoryEntry::ToValue(
321 BookmarkModel* bookmark_model,
322 SupervisedUserService* supervised_user_service,
323 const ProfileSyncService* sync_service) const {
324 scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
325 SetUrlAndTitle(result.get());
327 base::string16 domain = net::IDNToUnicode(url.host(), accept_languages);
328 // When the domain is empty, use the scheme instead. This allows for a
329 // sensible treatment of e.g. file: URLs when group by domain is on.
331 domain = base::UTF8ToUTF16(url.scheme() + ":");
333 // The items which are to be written into result are also described in
334 // chrome/browser/resources/history/history.js in @typedef for
335 // HistoryEntry. Please update it whenever you add or remove
336 // any keys in result.
337 result->SetString("domain", domain);
338 result->SetDouble("time", time.ToJsTime());
340 // Pass the timestamps in a list.
341 scoped_ptr<base::ListValue> timestamps(new base::ListValue);
342 for (std::set<int64>::const_iterator it = all_timestamps.begin();
343 it != all_timestamps.end(); ++it) {
344 timestamps->AppendDouble(base::Time::FromInternalValue(*it).ToJsTime());
346 result->Set("allTimestamps", timestamps.release());
348 // Always pass the short date since it is needed both in the search and in
350 result->SetString("dateShort", base::TimeFormatShortDate(time));
352 // Only pass in the strings we need (search results need a shortdate
353 // and snippet, browse results need day and time information).
354 if (is_search_result) {
355 result->SetString("snippet", snippet);
357 base::Time midnight = base::Time::Now().LocalMidnight();
358 base::string16 date_str = ui::TimeFormat::RelativeDate(time, &midnight);
359 if (date_str.empty()) {
360 date_str = base::TimeFormatFriendlyDate(time);
362 date_str = l10n_util::GetStringFUTF16(
363 IDS_HISTORY_DATE_WITH_RELATIVE_TIME,
365 base::TimeFormatFriendlyDate(time));
367 result->SetString("dateRelativeDay", date_str);
368 result->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time));
370 result->SetBoolean("starred", bookmark_model->IsBookmarked(url));
372 std::string device_name;
373 std::string device_type;
374 if (!client_id.empty())
375 GetDeviceNameAndType(sync_service, client_id, &device_name, &device_type);
376 result->SetString("deviceName", device_name);
377 result->SetString("deviceType", device_type);
379 #if defined(ENABLE_MANAGED_USERS)
380 if (supervised_user_service) {
381 const SupervisedUserURLFilter* url_filter =
382 supervised_user_service->GetURLFilterForUIThread();
383 int filtering_behavior =
384 url_filter->GetFilteringBehaviorForURL(url.GetWithEmptyPath());
385 result->SetInteger("hostFilteringBehavior", filtering_behavior);
387 result->SetBoolean("blockedVisit", blocked_visit);
391 return result.Pass();
394 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending(
395 const BrowsingHistoryHandler::HistoryEntry& entry1,
396 const BrowsingHistoryHandler::HistoryEntry& entry2) {
397 return entry1.time > entry2.time;
400 BrowsingHistoryHandler::BrowsingHistoryHandler()
401 : has_pending_delete_request_(false),
402 weak_factory_(this) {
405 BrowsingHistoryHandler::~BrowsingHistoryHandler() {
406 query_task_tracker_.TryCancelAll();
407 web_history_request_.reset();
410 void BrowsingHistoryHandler::RegisterMessages() {
411 // Create our favicon data source.
412 Profile* profile = Profile::FromWebUI(web_ui());
413 content::URLDataSource::Add(
414 profile, new FaviconSource(profile, FaviconSource::ANY));
416 // Get notifications when history is cleared.
417 registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED,
418 content::Source<Profile>(profile->GetOriginalProfile()));
420 web_ui()->RegisterMessageCallback("queryHistory",
421 base::Bind(&BrowsingHistoryHandler::HandleQueryHistory,
422 base::Unretained(this)));
423 web_ui()->RegisterMessageCallback("removeVisits",
424 base::Bind(&BrowsingHistoryHandler::HandleRemoveVisits,
425 base::Unretained(this)));
426 web_ui()->RegisterMessageCallback("clearBrowsingData",
427 base::Bind(&BrowsingHistoryHandler::HandleClearBrowsingData,
428 base::Unretained(this)));
429 web_ui()->RegisterMessageCallback("removeBookmark",
430 base::Bind(&BrowsingHistoryHandler::HandleRemoveBookmark,
431 base::Unretained(this)));
434 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(
435 const base::ListValue* value,
439 if (value->GetDouble(index, &double_value)) {
440 *out_int = static_cast<int>(double_value);
447 void BrowsingHistoryHandler::WebHistoryTimeout() {
448 // TODO(dubroy): Communicate the failure to the front end.
449 if (!query_task_tracker_.HasTrackedTasks())
450 ReturnResultsToFrontEnd();
452 UMA_HISTOGRAM_ENUMERATION(
453 "WebHistory.QueryCompletion",
454 WEB_HISTORY_QUERY_TIMED_OUT, NUM_WEB_HISTORY_QUERY_BUCKETS);
457 void BrowsingHistoryHandler::QueryHistory(
458 base::string16 search_text, const history::QueryOptions& options) {
459 Profile* profile = Profile::FromWebUI(web_ui());
461 // Anything in-flight is invalid.
462 query_task_tracker_.TryCancelAll();
463 web_history_request_.reset();
465 query_results_.clear();
466 results_info_value_.Clear();
468 HistoryService* hs = HistoryServiceFactory::GetForProfile(
469 profile, Profile::EXPLICIT_ACCESS);
470 hs->QueryHistory(search_text,
472 base::Bind(&BrowsingHistoryHandler::QueryComplete,
473 base::Unretained(this),
476 &query_task_tracker_);
478 history::WebHistoryService* web_history =
479 WebHistoryServiceFactory::GetForProfile(profile);
481 web_history_query_results_.clear();
482 web_history_request_ = web_history->QueryHistory(
485 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete,
486 base::Unretained(this),
487 search_text, options,
488 base::TimeTicks::Now()));
489 // Start a timer so we know when to give up.
490 web_history_timer_.Start(
491 FROM_HERE, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds),
492 this, &BrowsingHistoryHandler::WebHistoryTimeout);
494 // Set this to false until the results actually arrive.
495 results_info_value_.SetBoolean("hasSyncedResults", false);
499 void BrowsingHistoryHandler::HandleQueryHistory(const base::ListValue* args) {
500 history::QueryOptions options;
502 // Parse the arguments from JavaScript. There are five required arguments:
503 // - the text to search for (may be empty)
504 // - the offset from which the search should start (in multiples of week or
505 // month, set by the next argument).
506 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range
508 // - the end time for the query. Only results older than this time will be
510 // - the maximum number of results to return (may be 0, meaning that there
512 base::string16 search_text = ExtractStringValue(args);
514 if (!args->GetInteger(1, &offset)) {
515 NOTREACHED() << "Failed to convert argument 1. ";
519 if (!args->GetInteger(2, &range)) {
520 NOTREACHED() << "Failed to convert argument 2. ";
524 if (range == BrowsingHistoryHandler::MONTH)
525 SetQueryTimeInMonths(offset, &options);
526 else if (range == BrowsingHistoryHandler::WEEK)
527 SetQueryTimeInWeeks(offset, &options);
530 if (!args->GetDouble(3, &end_time)) {
531 NOTREACHED() << "Failed to convert argument 3. ";
535 options.end_time = base::Time::FromJsTime(end_time);
537 if (!ExtractIntegerValueAtIndex(args, 4, &options.max_count)) {
538 NOTREACHED() << "Failed to convert argument 4.";
542 options.duplicate_policy = history::QueryOptions::REMOVE_DUPLICATES_PER_DAY;
543 QueryHistory(search_text, options);
546 void BrowsingHistoryHandler::HandleRemoveVisits(const base::ListValue* args) {
547 Profile* profile = Profile::FromWebUI(web_ui());
548 // TODO(davidben): history.js is not aware of this failure and will still
549 // override |deleteCompleteCallback_|.
550 if (delete_task_tracker_.HasTrackedTasks() ||
551 has_pending_delete_request_ ||
552 !profile->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory)) {
553 web_ui()->CallJavascriptFunction("deleteFailed");
557 HistoryService* history_service =
558 HistoryServiceFactory::GetForProfile(profile, Profile::EXPLICIT_ACCESS);
559 history::WebHistoryService* web_history =
560 WebHistoryServiceFactory::GetForProfile(profile);
562 base::Time now = base::Time::Now();
563 std::vector<history::ExpireHistoryArgs> expire_list;
564 expire_list.reserve(args->GetSize());
566 DCHECK(urls_to_be_deleted_.empty());
567 for (base::ListValue::const_iterator it = args->begin();
568 it != args->end(); ++it) {
569 base::DictionaryValue* deletion = NULL;
571 base::ListValue* timestamps = NULL;
573 // Each argument is a dictionary with properties "url" and "timestamps".
574 if (!((*it)->GetAsDictionary(&deletion) &&
575 deletion->GetString("url", &url) &&
576 deletion->GetList("timestamps", ×tamps))) {
577 NOTREACHED() << "Unable to extract arguments";
580 DCHECK(timestamps->GetSize() > 0);
582 // In order to ensure that visits will be deleted from the server and other
583 // clients (even if they are offline), create a sync delete directive for
584 // each visit to be deleted.
585 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive;
586 sync_pb::GlobalIdDirective* global_id_directive =
587 delete_directive.mutable_global_id_directive();
590 history::ExpireHistoryArgs* expire_args = NULL;
591 for (base::ListValue::const_iterator ts_iterator = timestamps->begin();
592 ts_iterator != timestamps->end(); ++ts_iterator) {
593 if (!(*ts_iterator)->GetAsDouble(×tamp)) {
594 NOTREACHED() << "Unable to extract visit timestamp.";
597 base::Time visit_time = base::Time::FromJsTime(timestamp);
600 expire_list.resize(expire_list.size() + 1);
601 expire_args = &expire_list.back();
602 expire_args->SetTimeRangeForOneDay(visit_time);
603 expire_args->urls.insert(gurl);
604 urls_to_be_deleted_.insert(gurl);
606 // The local visit time is treated as a global ID for the visit.
607 global_id_directive->add_global_id(visit_time.ToInternalValue());
610 // Set the start and end time in microseconds since the Unix epoch.
611 global_id_directive->set_start_time_usec(
612 (expire_args->begin_time - base::Time::UnixEpoch()).InMicroseconds());
614 // Delete directives shouldn't have an end time in the future.
615 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
616 base::Time end_time = std::min(expire_args->end_time, now);
618 // -1 because end time in delete directives is inclusive.
619 global_id_directive->set_end_time_usec(
620 (end_time - base::Time::UnixEpoch()).InMicroseconds() - 1);
622 // TODO(dubroy): Figure out the proper way to handle an error here.
624 history_service->ProcessLocalDeleteDirective(delete_directive);
627 history_service->ExpireHistory(
629 base::Bind(&BrowsingHistoryHandler::RemoveComplete,
630 base::Unretained(this)),
631 &delete_task_tracker_);
634 has_pending_delete_request_ = true;
635 web_history->ExpireHistory(
637 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete,
638 weak_factory_.GetWeakPtr()));
641 #if defined(ENABLE_EXTENSIONS)
642 // If the profile has activity logging enabled also clean up any URLs from
643 // the extension activity log. The extension activity log contains URLS
644 // which websites an extension has activity on so it will indirectly
645 // contain websites that a user has visited.
646 extensions::ActivityLog* activity_log =
647 extensions::ActivityLog::GetInstance(profile);
648 for (std::vector<history::ExpireHistoryArgs>::const_iterator it =
649 expire_list.begin(); it != expire_list.end(); ++it) {
650 activity_log->RemoveURLs(it->urls);
655 void BrowsingHistoryHandler::HandleClearBrowsingData(
656 const base::ListValue* args) {
657 #if defined(OS_ANDROID)
658 chrome::android::ChromiumApplication::OpenClearBrowsingData(
659 web_ui()->GetWebContents());
661 // TODO(beng): This is an improper direct dependency on Browser. Route this
662 // through some sort of delegate.
663 Browser* browser = chrome::FindBrowserWithWebContents(
664 web_ui()->GetWebContents());
665 chrome::ShowClearBrowsingDataDialog(browser);
669 void BrowsingHistoryHandler::HandleRemoveBookmark(const base::ListValue* args) {
670 base::string16 url = ExtractStringValue(args);
671 Profile* profile = Profile::FromWebUI(web_ui());
672 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile);
673 bookmarks::RemoveAllBookmarks(model, GURL(url));
677 void BrowsingHistoryHandler::MergeDuplicateResults(
678 std::vector<BrowsingHistoryHandler::HistoryEntry>* results) {
679 std::vector<BrowsingHistoryHandler::HistoryEntry> new_results;
680 // Pre-reserve the size of the new vector. Since we're working with pointers
681 // later on not doing this could lead to the vector being resized and to
682 // pointers to invalid locations.
683 new_results.reserve(results->size());
684 // Maps a URL to the most recent entry on a particular day.
685 std::map<GURL, BrowsingHistoryHandler::HistoryEntry*> current_day_entries;
687 // Keeps track of the day that |current_day_urls| is holding the URLs for,
688 // in order to handle removing per-day duplicates.
689 base::Time current_day_midnight;
692 results->begin(), results->end(), HistoryEntry::SortByTimeDescending);
694 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::const_iterator it =
695 results->begin(); it != results->end(); ++it) {
696 // Reset the list of found URLs when a visit from a new day is encountered.
697 if (current_day_midnight != it->time.LocalMidnight()) {
698 current_day_entries.clear();
699 current_day_midnight = it->time.LocalMidnight();
702 // Keep this visit if it's the first visit to this URL on the current day.
703 if (current_day_entries.count(it->url) == 0) {
704 new_results.push_back(*it);
705 current_day_entries[it->url] = &new_results.back();
707 // Keep track of the timestamps of all visits to the URL on the same day.
708 BrowsingHistoryHandler::HistoryEntry* entry =
709 current_day_entries[it->url];
710 entry->all_timestamps.insert(
711 it->all_timestamps.begin(), it->all_timestamps.end());
713 if (entry->entry_type != it->entry_type) {
715 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY;
719 results->swap(new_results);
722 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() {
723 Profile* profile = Profile::FromWebUI(web_ui());
724 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile);
725 SupervisedUserService* supervised_user_service = NULL;
726 #if defined(ENABLE_MANAGED_USERS)
727 if (profile->IsSupervised())
728 supervised_user_service =
729 SupervisedUserServiceFactory::GetForProfile(profile);
731 ProfileSyncService* sync_service =
732 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
734 // Combine the local and remote results into |query_results_|, and remove
736 if (!web_history_query_results_.empty()) {
737 int local_result_count = query_results_.size();
738 query_results_.insert(query_results_.end(),
739 web_history_query_results_.begin(),
740 web_history_query_results_.end());
741 MergeDuplicateResults(&query_results_);
743 if (local_result_count) {
744 // In the best case, we expect that all local results are duplicated on
745 // the server. Keep track of how many are missing.
746 int missing_count = std::count_if(
747 query_results_.begin(), query_results_.end(), IsLocalOnlyResult);
748 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer",
749 missing_count * 100.0 / local_result_count);
753 // Convert the result vector into a ListValue.
754 base::ListValue results_value;
755 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::iterator it =
756 query_results_.begin(); it != query_results_.end(); ++it) {
757 scoped_ptr<base::Value> value(
758 it->ToValue(bookmark_model, supervised_user_service, sync_service));
759 results_value.Append(value.release());
762 web_ui()->CallJavascriptFunction(
763 "historyResult", results_info_value_, results_value);
764 results_info_value_.Clear();
765 query_results_.clear();
766 web_history_query_results_.clear();
769 void BrowsingHistoryHandler::QueryComplete(
770 const base::string16& search_text,
771 const history::QueryOptions& options,
772 history::QueryResults* results) {
773 DCHECK_EQ(0U, query_results_.size());
774 query_results_.reserve(results->size());
775 const std::string accept_languages = GetAcceptLanguages();
777 for (size_t i = 0; i < results->size(); ++i) {
778 history::URLResult const &page = (*results)[i];
779 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready.
780 query_results_.push_back(
782 HistoryEntry::LOCAL_ENTRY,
787 !search_text.empty(),
788 page.snippet().text(),
789 page.blocked_visit(),
793 // The items which are to be written into results_info_value_ are also
794 // described in chrome/browser/resources/history/history.js in @typedef for
795 // HistoryQuery. Please update it whenever you add or remove any keys in
796 // results_info_value_.
797 results_info_value_.SetString("term", search_text);
798 results_info_value_.SetBoolean("finished", results->reached_beginning());
800 // Add the specific dates that were searched to display them.
801 // TODO(sergiu): Put today if the start is in the future.
802 results_info_value_.SetString("queryStartTime",
803 getRelativeDateLocalized(options.begin_time));
804 if (!options.end_time.is_null()) {
805 results_info_value_.SetString("queryEndTime",
806 getRelativeDateLocalized(options.end_time -
807 base::TimeDelta::FromDays(1)));
809 results_info_value_.SetString("queryEndTime",
810 getRelativeDateLocalized(base::Time::Now()));
812 if (!web_history_timer_.IsRunning())
813 ReturnResultsToFrontEnd();
816 void BrowsingHistoryHandler::WebHistoryQueryComplete(
817 const base::string16& search_text,
818 const history::QueryOptions& options,
819 base::TimeTicks start_time,
820 history::WebHistoryService::Request* request,
821 const base::DictionaryValue* results_value) {
822 base::TimeDelta delta = base::TimeTicks::Now() - start_time;
823 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta);
824 const std::string accept_languages = GetAcceptLanguages();
826 // If the response came in too late, do nothing.
827 // TODO(dubroy): Maybe show a banner, and prompt the user to reload?
828 if (!web_history_timer_.IsRunning())
830 web_history_timer_.Stop();
832 UMA_HISTOGRAM_ENUMERATION(
833 "WebHistory.QueryCompletion",
834 results_value ? WEB_HISTORY_QUERY_SUCCEEDED : WEB_HISTORY_QUERY_FAILED,
835 NUM_WEB_HISTORY_QUERY_BUCKETS);
837 DCHECK_EQ(0U, web_history_query_results_.size());
838 const base::ListValue* events = NULL;
839 if (results_value && results_value->GetList("event", &events)) {
840 web_history_query_results_.reserve(events->GetSize());
841 for (unsigned int i = 0; i < events->GetSize(); ++i) {
842 const base::DictionaryValue* event = NULL;
843 const base::DictionaryValue* result = NULL;
844 const base::ListValue* results = NULL;
845 const base::ListValue* ids = NULL;
847 base::string16 title;
848 base::Time visit_time;
850 if (!(events->GetDictionary(i, &event) &&
851 event->GetList("result", &results) &&
852 results->GetDictionary(0, &result) &&
853 result->GetString("url", &url) &&
854 result->GetList("id", &ids) &&
855 ids->GetSize() > 0)) {
856 LOG(WARNING) << "Improperly formed JSON response from history server.";
859 // Title is optional, so the return value is ignored here.
860 result->GetString("title", &title);
862 // Extract the timestamps of all the visits to this URL.
863 // They are referred to as "IDs" by the server.
864 for (int j = 0; j < static_cast<int>(ids->GetSize()); ++j) {
865 const base::DictionaryValue* id = NULL;
866 std::string timestamp_string;
867 int64 timestamp_usec = 0;
869 if (!ids->GetDictionary(j, &id) ||
870 !id->GetString("timestamp_usec", ×tamp_string) ||
871 !base::StringToInt64(timestamp_string, ×tamp_usec)) {
872 NOTREACHED() << "Unable to extract timestamp.";
875 // The timestamp on the server is a Unix time.
876 base::Time time = base::Time::UnixEpoch() +
877 base::TimeDelta::FromMicroseconds(timestamp_usec);
879 // Get the ID of the client that this visit came from.
880 std::string client_id;
881 id->GetString("client_id", &client_id);
883 web_history_query_results_.push_back(
885 HistoryEntry::REMOTE_ENTRY,
890 !search_text.empty(),
892 /* blocked_visit */ false,
896 } else if (results_value) {
897 NOTREACHED() << "Failed to parse JSON response.";
899 results_info_value_.SetBoolean("hasSyncedResults", results_value != NULL);
900 if (!query_task_tracker_.HasTrackedTasks())
901 ReturnResultsToFrontEnd();
904 void BrowsingHistoryHandler::RemoveComplete() {
905 urls_to_be_deleted_.clear();
907 // Notify the page that the deletion request is complete, but only if a web
908 // history delete request is not still pending.
909 if (!has_pending_delete_request_)
910 web_ui()->CallJavascriptFunction("deleteComplete");
913 void BrowsingHistoryHandler::RemoveWebHistoryComplete(bool success) {
914 has_pending_delete_request_ = false;
915 // TODO(dubroy): Should we handle failure somehow? Delete directives will
916 // ensure that the visits are eventually deleted, so maybe it's not necessary.
917 if (!delete_task_tracker_.HasTrackedTasks())
921 void BrowsingHistoryHandler::SetQueryTimeInWeeks(
922 int offset, history::QueryOptions* options) {
923 // LocalMidnight returns the beginning of the current day so get the
924 // beginning of the next one.
925 base::Time midnight = base::Time::Now().LocalMidnight() +
926 base::TimeDelta::FromDays(1);
927 options->end_time = midnight -
928 base::TimeDelta::FromDays(7 * offset);
929 options->begin_time = midnight -
930 base::TimeDelta::FromDays(7 * (offset + 1));
933 void BrowsingHistoryHandler::SetQueryTimeInMonths(
934 int offset, history::QueryOptions* options) {
935 // Configure the begin point of the search to the start of the
937 base::Time::Exploded exploded;
938 base::Time::Now().LocalMidnight().LocalExplode(&exploded);
939 exploded.day_of_month = 1;
942 options->begin_time = base::Time::FromLocalExploded(exploded);
944 // Set the end time of this first search to null (which will
945 // show results from the future, should the user's clock have
946 // been set incorrectly).
947 options->end_time = base::Time();
949 // Go back |offset| months in the past. The end time is not inclusive, so
950 // use the first day of the |offset| - 1 and |offset| months (e.g. for
951 // the last month, |offset| = 1, use the first days of the last month and
952 // the current month.
953 exploded.month -= offset - 1;
954 // Set the correct year.
955 normalizeMonths(&exploded);
956 options->end_time = base::Time::FromLocalExploded(exploded);
959 // Set the correct year
960 normalizeMonths(&exploded);
961 options->begin_time = base::Time::FromLocalExploded(exploded);
965 // Helper function for Observe that determines if there are any differences
966 // between the URLs noticed for deletion and the ones we are expecting.
967 static bool DeletionsDiffer(const history::URLRows& deleted_rows,
968 const std::set<GURL>& urls_to_be_deleted) {
969 if (deleted_rows.size() != urls_to_be_deleted.size())
971 for (history::URLRows::const_iterator i = deleted_rows.begin();
972 i != deleted_rows.end(); ++i) {
973 if (urls_to_be_deleted.find(i->url()) == urls_to_be_deleted.end())
979 void BrowsingHistoryHandler::Observe(
981 const content::NotificationSource& source,
982 const content::NotificationDetails& details) {
983 if (type != chrome::NOTIFICATION_HISTORY_URLS_DELETED) {
987 history::URLsDeletedDetails* deletedDetails =
988 content::Details<history::URLsDeletedDetails>(details).ptr();
989 if (deletedDetails->all_history ||
990 DeletionsDiffer(deletedDetails->rows, urls_to_be_deleted_))
991 web_ui()->CallJavascriptFunction("historyDeleted");
994 std::string BrowsingHistoryHandler::GetAcceptLanguages() const {
995 Profile* profile = Profile::FromWebUI(web_ui());
996 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
999 ////////////////////////////////////////////////////////////////////////////////
1003 ////////////////////////////////////////////////////////////////////////////////
1005 HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) {
1006 web_ui->AddMessageHandler(new BrowsingHistoryHandler());
1007 web_ui->AddMessageHandler(new MetricsHandler());
1009 // On mobile we deal with foreign sessions differently.
1010 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1011 if (chrome::IsInstantExtendedAPIEnabled()) {
1012 web_ui->AddMessageHandler(new browser_sync::ForeignSessionHandler());
1013 web_ui->AddMessageHandler(new NTPLoginHandler());
1017 // Set up the chrome://history-frame/ source.
1018 Profile* profile = Profile::FromWebUI(web_ui);
1019 content::WebUIDataSource::Add(profile, CreateHistoryUIHTMLSource(profile));
1023 base::RefCountedMemory* HistoryUI::GetFaviconResourceBytes(
1024 ui::ScaleFactor scale_factor) {
1025 return ResourceBundle::GetSharedInstance().
1026 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON, scale_factor);