1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "chrome/browser/ui/webui/history_ui.h" 6 7 #include <set> 8 9 #include "base/bind.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" 59 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" 65 #endif 66 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" 70 #endif 71 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" 75 #endif 76 77 static const char kStringsJsFile[] = "strings.js"; 78 static const char kHistoryJsFile[] = "history.js"; 79 static const char kOtherDevicesJsFile[] = "other_devices.js"; 80 81 // The amount of time to wait for a response from the WebHistoryService. 82 static const int kWebHistoryTimeoutSeconds = 3; 83 84 namespace { 85 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 92 }; 93 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'). 98 "N)"; 99 #elif defined(OS_WIN) 100 const char kIncognitoModeShortcut[] = "(Ctrl+Shift+N)"; 101 #else 102 const char kIncognitoModeShortcut[] = "(Shift+Ctrl+N)"; 103 #endif 104 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"; 109 110 content::WebUIDataSource* CreateHistoryUIHTMLSource(Profile* profile) { 111 PrefService* prefs = profile->GetPrefs(); 112 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); 140 source->AddString( 141 "deleteWarning", 142 l10n_util::GetStringFUTF16(IDS_HISTORY_DELETE_PRIOR_VISITS_WARNING, 143 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()); 181 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()); 190 191 return source; 192 } 193 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); 201 } else { 202 date_str = l10n_util::GetStringFUTF16( 203 IDS_HISTORY_DATE_WITH_RELATIVE_TIME, 204 date_str, 205 base::TimeFormatFriendlyDate(visit_time)); 206 } 207 return date_str; 208 } 209 210 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; 216 exploded->year--; 217 } 218 } 219 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; 224 } 225 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, 230 std::string* name, 231 std::string* type) { 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; 240 break; 241 case sync_pb::SyncEnums::TYPE_TABLET: 242 *type = kDeviceTypeTablet; 243 break; 244 default: 245 *type = kDeviceTypeLaptop; 246 } 247 return; 248 } 249 } else { 250 NOTREACHED() << "Got a remote history entry but no ProfileSyncService."; 251 } 252 *name = l10n_util::GetStringUTF8(IDS_HISTORY_UNKNOWN_DEVICE); 253 *type = kDeviceTypeLaptop; 254 } 255 256 } // namespace 257 258 //////////////////////////////////////////////////////////////////////////////// 259 // 260 // BrowsingHistoryHandler 261 // 262 //////////////////////////////////////////////////////////////////////////////// 263 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; 271 this->url = url; 272 this->title = title; 273 this->time = time; 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; 280 } 281 282 BrowsingHistoryHandler::HistoryEntry::HistoryEntry() 283 : entry_type(EMPTY_ENTRY), is_search_result(false), blocked_visit(false) { 284 } 285 286 BrowsingHistoryHandler::HistoryEntry::~HistoryEntry() { 287 } 288 289 void BrowsingHistoryHandler::HistoryEntry::SetUrlAndTitle( 290 DictionaryValue* result) const { 291 result->SetString("url", url.spec()); 292 293 bool using_url_as_the_title = false; 294 base::string16 title_to_set(title); 295 if (title.empty()) { 296 using_url_as_the_title = true; 297 title_to_set = UTF8ToUTF16(url.spec()); 298 } 299 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); 307 else 308 base::i18n::AdjustStringForLocaleDirection(&title_to_set); 309 } 310 result->SetString("title", title_to_set); 311 } 312 313 scoped_ptr<DictionaryValue> BrowsingHistoryHandler::HistoryEntry::ToValue( 314 BookmarkModel* bookmark_model, 315 ManagedUserService* managed_user_service, 316 const ProfileSyncService* sync_service) const { 317 scoped_ptr<DictionaryValue> result(new DictionaryValue()); 318 SetUrlAndTitle(result.get()); 319 320 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. 323 if (domain.empty()) 324 domain = UTF8ToUTF16(url.scheme() + ":"); 325 326 result->SetString("domain", domain); 327 result->SetDouble("time", time.ToJsTime()); 328 329 // Pass the timestamps in a list. 330 scoped_ptr<ListValue> timestamps(new 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()); 334 } 335 result->Set("allTimestamps", timestamps.release()); 336 337 // Always pass the short date since it is needed both in the search and in 338 // the monthly view. 339 result->SetString("dateShort", base::TimeFormatShortDate(time)); 340 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); 345 } else { 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); 350 } else { 351 date_str = l10n_util::GetStringFUTF16( 352 IDS_HISTORY_DATE_WITH_RELATIVE_TIME, 353 date_str, 354 base::TimeFormatFriendlyDate(time)); 355 } 356 result->SetString("dateRelativeDay", date_str); 357 result->SetString("dateTimeOfDay", base::TimeFormatTimeOfDay(time)); 358 } 359 result->SetBoolean("starred", bookmark_model->IsBookmarked(url)); 360 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); 367 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); 375 376 result->SetBoolean("blockedVisit", blocked_visit); 377 } 378 #endif 379 380 return result.Pass(); 381 } 382 383 bool BrowsingHistoryHandler::HistoryEntry::SortByTimeDescending( 384 const BrowsingHistoryHandler::HistoryEntry& entry1, 385 const BrowsingHistoryHandler::HistoryEntry& entry2) { 386 return entry1.time > entry2.time; 387 } 388 389 BrowsingHistoryHandler::BrowsingHistoryHandler() {} 390 391 BrowsingHistoryHandler::~BrowsingHistoryHandler() { 392 history_request_consumer_.CancelAllRequests(); 393 web_history_request_.reset(); 394 } 395 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)); 401 402 // Get notifications when history is cleared. 403 registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED, 404 content::Source<Profile>(profile->GetOriginalProfile())); 405 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))); 418 } 419 420 bool BrowsingHistoryHandler::ExtractIntegerValueAtIndex(const ListValue* value, 421 int index, 422 int* out_int) { 423 double double_value; 424 if (value->GetDouble(index, &double_value)) { 425 *out_int = static_cast<int>(double_value); 426 return true; 427 } 428 NOTREACHED(); 429 return false; 430 } 431 432 void BrowsingHistoryHandler::WebHistoryTimeout() { 433 // TODO(dubroy): Communicate the failure to the front end. 434 if (!history_request_consumer_.HasPendingRequests()) 435 ReturnResultsToFrontEnd(); 436 437 UMA_HISTOGRAM_ENUMERATION( 438 "WebHistory.QueryCompletion", 439 WEB_HISTORY_QUERY_TIMED_OUT, NUM_WEB_HISTORY_QUERY_BUCKETS); 440 } 441 442 void BrowsingHistoryHandler::QueryHistory( 443 base::string16 search_text, const history::QueryOptions& options) { 444 Profile* profile = Profile::FromWebUI(web_ui()); 445 446 // Anything in-flight is invalid. 447 history_request_consumer_.CancelAllRequests(); 448 web_history_request_.reset(); 449 450 query_results_.clear(); 451 results_info_value_.Clear(); 452 453 HistoryService* hs = HistoryServiceFactory::GetForProfile( 454 profile, Profile::EXPLICIT_ACCESS); 455 hs->QueryHistory(search_text, 456 options, 457 &history_request_consumer_, 458 base::Bind(&BrowsingHistoryHandler::QueryComplete, 459 base::Unretained(this), search_text, options)); 460 461 history::WebHistoryService* web_history = 462 WebHistoryServiceFactory::GetForProfile(profile); 463 if (web_history) { 464 web_history_query_results_.clear(); 465 web_history_request_ = web_history->QueryHistory( 466 search_text, 467 options, 468 base::Bind(&BrowsingHistoryHandler::WebHistoryQueryComplete, 469 base::Unretained(this), 470 search_text, options, 471 base::TimeTicks::Now())); 472 // Start a timer so we know when to give up. 473 web_history_timer_.Start( 474 FROM_HERE, base::TimeDelta::FromSeconds(kWebHistoryTimeoutSeconds), 475 this, &BrowsingHistoryHandler::WebHistoryTimeout); 476 477 // Set this to false until the results actually arrive. 478 results_info_value_.SetBoolean("hasSyncedResults", false); 479 } 480 } 481 482 void BrowsingHistoryHandler::HandleQueryHistory(const ListValue* args) { 483 history::QueryOptions options; 484 485 // Parse the arguments from JavaScript. There are five required arguments: 486 // - the text to search for (may be empty) 487 // - the offset from which the search should start (in multiples of week or 488 // month, set by the next argument). 489 // - the range (BrowsingHistoryHandler::Range) Enum value that sets the range 490 // of the query. 491 // - the end time for the query. Only results older than this time will be 492 // returned. 493 // - the maximum number of results to return (may be 0, meaning that there 494 // is no maximum). 495 base::string16 search_text = ExtractStringValue(args); 496 int offset; 497 if (!args->GetInteger(1, &offset)) { 498 NOTREACHED() << "Failed to convert argument 1. "; 499 return; 500 } 501 int range; 502 if (!args->GetInteger(2, &range)) { 503 NOTREACHED() << "Failed to convert argument 2. "; 504 return; 505 } 506 507 if (range == BrowsingHistoryHandler::MONTH) 508 SetQueryTimeInMonths(offset, &options); 509 else if (range == BrowsingHistoryHandler::WEEK) 510 SetQueryTimeInWeeks(offset, &options); 511 512 double end_time; 513 if (!args->GetDouble(3, &end_time)) { 514 NOTREACHED() << "Failed to convert argument 3. "; 515 return; 516 } 517 if (end_time) 518 options.end_time = base::Time::FromJsTime(end_time); 519 520 if (!ExtractIntegerValueAtIndex(args, 4, &options.max_count)) { 521 NOTREACHED() << "Failed to convert argument 4."; 522 return; 523 } 524 525 options.duplicate_policy = history::QueryOptions::REMOVE_DUPLICATES_PER_DAY; 526 QueryHistory(search_text, options); 527 } 528 529 void BrowsingHistoryHandler::HandleRemoveVisits(const ListValue* args) { 530 Profile* profile = Profile::FromWebUI(web_ui()); 531 if (delete_task_tracker_.HasTrackedTasks() || 532 !profile->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory)) { 533 web_ui()->CallJavascriptFunction("deleteFailed"); 534 return; 535 } 536 537 HistoryService* history_service = 538 HistoryServiceFactory::GetForProfile(profile, Profile::EXPLICIT_ACCESS); 539 history::WebHistoryService* web_history = 540 WebHistoryServiceFactory::GetForProfile(profile); 541 542 base::Time now = base::Time::Now(); 543 std::vector<history::ExpireHistoryArgs> expire_list; 544 expire_list.reserve(args->GetSize()); 545 546 DCHECK(urls_to_be_deleted_.empty()); 547 for (ListValue::const_iterator it = args->begin(); it != args->end(); ++it) { 548 DictionaryValue* deletion = NULL; 549 base::string16 url; 550 ListValue* timestamps = NULL; 551 552 // Each argument is a dictionary with properties "url" and "timestamps". 553 if (!((*it)->GetAsDictionary(&deletion) && 554 deletion->GetString("url", &url) && 555 deletion->GetList("timestamps", ×tamps))) { 556 NOTREACHED() << "Unable to extract arguments"; 557 return; 558 } 559 DCHECK(timestamps->GetSize() > 0); 560 561 // In order to ensure that visits will be deleted from the server and other 562 // clients (even if they are offline), create a sync delete directive for 563 // each visit to be deleted. 564 sync_pb::HistoryDeleteDirectiveSpecifics delete_directive; 565 sync_pb::GlobalIdDirective* global_id_directive = 566 delete_directive.mutable_global_id_directive(); 567 568 double timestamp; 569 history::ExpireHistoryArgs* expire_args = NULL; 570 for (ListValue::const_iterator ts_iterator = timestamps->begin(); 571 ts_iterator != timestamps->end(); ++ts_iterator) { 572 if (!(*ts_iterator)->GetAsDouble(×tamp)) { 573 NOTREACHED() << "Unable to extract visit timestamp."; 574 continue; 575 } 576 base::Time visit_time = base::Time::FromJsTime(timestamp); 577 if (!expire_args) { 578 GURL gurl(url); 579 expire_list.resize(expire_list.size() + 1); 580 expire_args = &expire_list.back(); 581 expire_args->SetTimeRangeForOneDay(visit_time); 582 expire_args->urls.insert(gurl); 583 urls_to_be_deleted_.insert(gurl); 584 } 585 // The local visit time is treated as a global ID for the visit. 586 global_id_directive->add_global_id(visit_time.ToInternalValue()); 587 } 588 589 // Set the start and end time in microseconds since the Unix epoch. 590 global_id_directive->set_start_time_usec( 591 (expire_args->begin_time - base::Time::UnixEpoch()).InMicroseconds()); 592 593 // Delete directives shouldn't have an end time in the future. 594 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready. 595 base::Time end_time = std::min(expire_args->end_time, now); 596 597 // -1 because end time in delete directives is inclusive. 598 global_id_directive->set_end_time_usec( 599 (end_time - base::Time::UnixEpoch()).InMicroseconds() - 1); 600 601 // TODO(dubroy): Figure out the proper way to handle an error here. 602 if (web_history) 603 history_service->ProcessLocalDeleteDirective(delete_directive); 604 } 605 606 history_service->ExpireHistory( 607 expire_list, 608 base::Bind(&BrowsingHistoryHandler::RemoveComplete, 609 base::Unretained(this)), 610 &delete_task_tracker_); 611 612 if (web_history) { 613 web_history_delete_request_ = web_history->ExpireHistory( 614 expire_list, 615 base::Bind(&BrowsingHistoryHandler::RemoveWebHistoryComplete, 616 base::Unretained(this))); 617 } 618 619 #if defined(ENABLE_EXTENSIONS) 620 // If the profile has activity logging enabled also clean up any URLs from 621 // the extension activity log. The extension activity log contains URLS 622 // which websites an extension has activity on so it will indirectly 623 // contain websites that a user has visited. 624 extensions::ActivityLog* activity_log = 625 extensions::ActivityLog::GetInstance(profile); 626 for (std::vector<history::ExpireHistoryArgs>::const_iterator it = 627 expire_list.begin(); it != expire_list.end(); ++it) { 628 activity_log->RemoveURLs(it->urls); 629 } 630 #endif 631 } 632 633 void BrowsingHistoryHandler::HandleClearBrowsingData(const ListValue* args) { 634 #if defined(OS_ANDROID) 635 Profile* profile = Profile::FromWebUI(web_ui()); 636 const TabModel* tab_model = 637 TabModelList::GetTabModelWithProfile(profile); 638 if (tab_model) 639 tab_model->OpenClearBrowsingData(); 640 #else 641 // TODO(beng): This is an improper direct dependency on Browser. Route this 642 // through some sort of delegate. 643 Browser* browser = chrome::FindBrowserWithWebContents( 644 web_ui()->GetWebContents()); 645 chrome::ShowClearBrowsingDataDialog(browser); 646 #endif 647 } 648 649 void BrowsingHistoryHandler::HandleRemoveBookmark(const ListValue* args) { 650 base::string16 url = ExtractStringValue(args); 651 Profile* profile = Profile::FromWebUI(web_ui()); 652 BookmarkModel* model = BookmarkModelFactory::GetForProfile(profile); 653 bookmark_utils::RemoveAllBookmarks(model, GURL(url)); 654 } 655 656 // static 657 void BrowsingHistoryHandler::MergeDuplicateResults( 658 std::vector<BrowsingHistoryHandler::HistoryEntry>* results) { 659 std::vector<BrowsingHistoryHandler::HistoryEntry> new_results; 660 // Pre-reserve the size of the new vector. Since we're working with pointers 661 // later on not doing this could lead to the vector being resized and to 662 // pointers to invalid locations. 663 new_results.reserve(results->size()); 664 // Maps a URL to the most recent entry on a particular day. 665 std::map<GURL,BrowsingHistoryHandler::HistoryEntry*> 666 current_day_entries; 667 668 // Keeps track of the day that |current_day_urls| is holding the URLs for, 669 // in order to handle removing per-day duplicates. 670 base::Time current_day_midnight; 671 672 std::sort( 673 results->begin(), results->end(), HistoryEntry::SortByTimeDescending); 674 675 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::const_iterator it = 676 results->begin(); it != results->end(); ++it) { 677 // Reset the list of found URLs when a visit from a new day is encountered. 678 if (current_day_midnight != it->time.LocalMidnight()) { 679 current_day_entries.clear(); 680 current_day_midnight = it->time.LocalMidnight(); 681 } 682 683 // Keep this visit if it's the first visit to this URL on the current day. 684 if (current_day_entries.count(it->url) == 0) { 685 new_results.push_back(*it); 686 current_day_entries[it->url] = &new_results.back(); 687 } else { 688 // Keep track of the timestamps of all visits to the URL on the same day. 689 BrowsingHistoryHandler::HistoryEntry* entry = 690 current_day_entries[it->url]; 691 entry->all_timestamps.insert( 692 it->all_timestamps.begin(), it->all_timestamps.end()); 693 694 if (entry->entry_type != it->entry_type) { 695 entry->entry_type = 696 BrowsingHistoryHandler::HistoryEntry::COMBINED_ENTRY; 697 } 698 } 699 } 700 results->swap(new_results); 701 } 702 703 void BrowsingHistoryHandler::ReturnResultsToFrontEnd() { 704 Profile* profile = Profile::FromWebUI(web_ui()); 705 BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile); 706 ManagedUserService* managed_user_service = NULL; 707 #if defined(ENABLE_MANAGED_USERS) 708 if (profile->IsManaged()) 709 managed_user_service = ManagedUserServiceFactory::GetForProfile(profile); 710 #endif 711 ProfileSyncService* sync_service = 712 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile); 713 714 // Combine the local and remote results into |query_results_|, and remove 715 // any duplicates. 716 if (!web_history_query_results_.empty()) { 717 int local_result_count = query_results_.size(); 718 query_results_.insert(query_results_.end(), 719 web_history_query_results_.begin(), 720 web_history_query_results_.end()); 721 MergeDuplicateResults(&query_results_); 722 723 if (local_result_count) { 724 // In the best case, we expect that all local results are duplicated on 725 // the server. Keep track of how many are missing. 726 int missing_count = std::count_if( 727 query_results_.begin(), query_results_.end(), IsLocalOnlyResult); 728 UMA_HISTOGRAM_PERCENTAGE("WebHistory.LocalResultMissingOnServer", 729 missing_count * 100.0 / local_result_count); 730 } 731 } 732 733 // Convert the result vector into a ListValue. 734 ListValue results_value; 735 for (std::vector<BrowsingHistoryHandler::HistoryEntry>::iterator it = 736 query_results_.begin(); it != query_results_.end(); ++it) { 737 scoped_ptr<base::Value> value( 738 it->ToValue(bookmark_model, managed_user_service, sync_service)); 739 results_value.Append(value.release()); 740 } 741 742 web_ui()->CallJavascriptFunction( 743 "historyResult", results_info_value_, results_value); 744 results_info_value_.Clear(); 745 query_results_.clear(); 746 web_history_query_results_.clear(); 747 } 748 749 void BrowsingHistoryHandler::QueryComplete( 750 const base::string16& search_text, 751 const history::QueryOptions& options, 752 HistoryService::Handle request_handle, 753 history::QueryResults* results) { 754 DCHECK_EQ(0U, query_results_.size()); 755 query_results_.reserve(results->size()); 756 const std::string accept_languages = GetAcceptLanguages(); 757 758 for (size_t i = 0; i < results->size(); ++i) { 759 history::URLResult const &page = (*results)[i]; 760 // TODO(dubroy): Use sane time (crbug.com/146090) here when it's ready. 761 query_results_.push_back( 762 HistoryEntry( 763 HistoryEntry::LOCAL_ENTRY, 764 page.url(), 765 page.title(), 766 page.visit_time(), 767 std::string(), 768 !search_text.empty(), 769 page.snippet().text(), 770 page.blocked_visit(), 771 accept_languages)); 772 } 773 774 results_info_value_.SetString("term", search_text); 775 results_info_value_.SetBoolean("finished", results->reached_beginning()); 776 777 // Add the specific dates that were searched to display them. 778 // TODO(sergiu): Put today if the start is in the future. 779 results_info_value_.SetString("queryStartTime", 780 getRelativeDateLocalized(options.begin_time)); 781 if (!options.end_time.is_null()) { 782 results_info_value_.SetString("queryEndTime", 783 getRelativeDateLocalized(options.end_time - 784 base::TimeDelta::FromDays(1))); 785 } else { 786 results_info_value_.SetString("queryEndTime", 787 getRelativeDateLocalized(base::Time::Now())); 788 } 789 if (!web_history_timer_.IsRunning()) 790 ReturnResultsToFrontEnd(); 791 } 792 793 void BrowsingHistoryHandler::WebHistoryQueryComplete( 794 const base::string16& search_text, 795 const history::QueryOptions& options, 796 base::TimeTicks start_time, 797 history::WebHistoryService::Request* request, 798 const DictionaryValue* results_value) { 799 base::TimeDelta delta = base::TimeTicks::Now() - start_time; 800 UMA_HISTOGRAM_TIMES("WebHistory.ResponseTime", delta); 801 const std::string accept_languages = GetAcceptLanguages(); 802 803 // If the response came in too late, do nothing. 804 // TODO(dubroy): Maybe show a banner, and prompt the user to reload? 805 if (!web_history_timer_.IsRunning()) 806 return; 807 web_history_timer_.Stop(); 808 809 UMA_HISTOGRAM_ENUMERATION( 810 "WebHistory.QueryCompletion", 811 results_value ? WEB_HISTORY_QUERY_SUCCEEDED : WEB_HISTORY_QUERY_FAILED, 812 NUM_WEB_HISTORY_QUERY_BUCKETS); 813 814 DCHECK_EQ(0U, web_history_query_results_.size()); 815 const ListValue* events = NULL; 816 if (results_value && results_value->GetList("event", &events)) { 817 web_history_query_results_.reserve(events->GetSize()); 818 for (unsigned int i = 0; i < events->GetSize(); ++i) { 819 const DictionaryValue* event = NULL; 820 const DictionaryValue* result = NULL; 821 const ListValue* results = NULL; 822 const ListValue* ids = NULL; 823 base::string16 url; 824 base::string16 title; 825 base::Time visit_time; 826 827 if (!(events->GetDictionary(i, &event) && 828 event->GetList("result", &results) && 829 results->GetDictionary(0, &result) && 830 result->GetString("url", &url) && 831 result->GetList("id", &ids) && 832 ids->GetSize() > 0)) { 833 LOG(WARNING) << "Improperly formed JSON response from history server."; 834 continue; 835 } 836 // Title is optional, so the return value is ignored here. 837 result->GetString("title", &title); 838 839 // Extract the timestamps of all the visits to this URL. 840 // They are referred to as "IDs" by the server. 841 for (int j = 0; j < static_cast<int>(ids->GetSize()); ++j) { 842 const DictionaryValue* id = NULL; 843 std::string timestamp_string; 844 int64 timestamp_usec; 845 846 if (!(ids->GetDictionary(j, &id) && 847 id->GetString("timestamp_usec", ×tamp_string) && 848 base::StringToInt64(timestamp_string, ×tamp_usec))) { 849 NOTREACHED() << "Unable to extract timestamp."; 850 continue; 851 } 852 // The timestamp on the server is a Unix time. 853 base::Time time = base::Time::UnixEpoch() + 854 base::TimeDelta::FromMicroseconds(timestamp_usec); 855 856 // Get the ID of the client that this visit came from. 857 std::string client_id; 858 id->GetString("client_id", &client_id); 859 860 web_history_query_results_.push_back( 861 HistoryEntry( 862 HistoryEntry::REMOTE_ENTRY, 863 GURL(url), 864 title, 865 time, 866 client_id, 867 !search_text.empty(), 868 base::string16(), 869 /* blocked_visit */ false, 870 accept_languages)); 871 } 872 } 873 } else if (results_value) { 874 NOTREACHED() << "Failed to parse JSON response."; 875 } 876 results_info_value_.SetBoolean("hasSyncedResults", results_value != NULL); 877 if (!history_request_consumer_.HasPendingRequests()) 878 ReturnResultsToFrontEnd(); 879 } 880 881 void BrowsingHistoryHandler::RemoveComplete() { 882 urls_to_be_deleted_.clear(); 883 884 // Notify the page that the deletion request is complete, but only if a web 885 // history delete request is not still pending. 886 if (!(web_history_delete_request_.get() && 887 web_history_delete_request_->is_pending())) { 888 web_ui()->CallJavascriptFunction("deleteComplete"); 889 } 890 } 891 892 void BrowsingHistoryHandler::RemoveWebHistoryComplete( 893 history::WebHistoryService::Request* request, bool success) { 894 // TODO(dubroy): Should we handle failure somehow? Delete directives will 895 // ensure that the visits are eventually deleted, so maybe it's not necessary. 896 if (!delete_task_tracker_.HasTrackedTasks()) 897 RemoveComplete(); 898 } 899 900 void BrowsingHistoryHandler::SetQueryTimeInWeeks( 901 int offset, history::QueryOptions* options) { 902 // LocalMidnight returns the beginning of the current day so get the 903 // beginning of the next one. 904 base::Time midnight = base::Time::Now().LocalMidnight() + 905 base::TimeDelta::FromDays(1); 906 options->end_time = midnight - 907 base::TimeDelta::FromDays(7 * offset); 908 options->begin_time = midnight - 909 base::TimeDelta::FromDays(7 * (offset + 1)); 910 } 911 912 void BrowsingHistoryHandler::SetQueryTimeInMonths( 913 int offset, history::QueryOptions* options) { 914 // Configure the begin point of the search to the start of the 915 // current month. 916 base::Time::Exploded exploded; 917 base::Time::Now().LocalMidnight().LocalExplode(&exploded); 918 exploded.day_of_month = 1; 919 920 if (offset == 0) { 921 options->begin_time = base::Time::FromLocalExploded(exploded); 922 923 // Set the end time of this first search to null (which will 924 // show results from the future, should the user's clock have 925 // been set incorrectly). 926 options->end_time = base::Time(); 927 } else { 928 // Go back |offset| months in the past. The end time is not inclusive, so 929 // use the first day of the |offset| - 1 and |offset| months (e.g. for 930 // the last month, |offset| = 1, use the first days of the last month and 931 // the current month. 932 exploded.month -= offset - 1; 933 // Set the correct year. 934 normalizeMonths(&exploded); 935 options->end_time = base::Time::FromLocalExploded(exploded); 936 937 exploded.month -= 1; 938 // Set the correct year 939 normalizeMonths(&exploded); 940 options->begin_time = base::Time::FromLocalExploded(exploded); 941 } 942 } 943 944 // Helper function for Observe that determines if there are any differences 945 // between the URLs noticed for deletion and the ones we are expecting. 946 static bool DeletionsDiffer(const history::URLRows& deleted_rows, 947 const std::set<GURL>& urls_to_be_deleted) { 948 if (deleted_rows.size() != urls_to_be_deleted.size()) 949 return true; 950 for (history::URLRows::const_iterator i = deleted_rows.begin(); 951 i != deleted_rows.end(); ++i) { 952 if (urls_to_be_deleted.find(i->url()) == urls_to_be_deleted.end()) 953 return true; 954 } 955 return false; 956 } 957 958 void BrowsingHistoryHandler::Observe( 959 int type, 960 const content::NotificationSource& source, 961 const content::NotificationDetails& details) { 962 if (type != chrome::NOTIFICATION_HISTORY_URLS_DELETED) { 963 NOTREACHED(); 964 return; 965 } 966 history::URLsDeletedDetails* deletedDetails = 967 content::Details<history::URLsDeletedDetails>(details).ptr(); 968 if (deletedDetails->all_history || 969 DeletionsDiffer(deletedDetails->rows, urls_to_be_deleted_)) 970 web_ui()->CallJavascriptFunction("historyDeleted"); 971 } 972 973 std::string BrowsingHistoryHandler::GetAcceptLanguages() const { 974 Profile* profile = Profile::FromWebUI(web_ui()); 975 return profile->GetPrefs()->GetString(prefs::kAcceptLanguages); 976 } 977 978 //////////////////////////////////////////////////////////////////////////////// 979 // 980 // HistoryUI 981 // 982 //////////////////////////////////////////////////////////////////////////////// 983 984 HistoryUI::HistoryUI(content::WebUI* web_ui) : WebUIController(web_ui) { 985 web_ui->AddMessageHandler(new BrowsingHistoryHandler()); 986 web_ui->AddMessageHandler(new MetricsHandler()); 987 988 // On mobile we deal with foreign sessions differently. 989 #if !defined(OS_ANDROID) && !defined(OS_IOS) 990 if (chrome::IsInstantExtendedAPIEnabled()) { 991 web_ui->AddMessageHandler(new browser_sync::ForeignSessionHandler()); 992 web_ui->AddMessageHandler(new NTPLoginHandler()); 993 } 994 #endif 995 996 // Set up the chrome://history-frame/ source. 997 Profile* profile = Profile::FromWebUI(web_ui); 998 content::WebUIDataSource::Add(profile, CreateHistoryUIHTMLSource(profile)); 999 } 1000 1001 // static 1002 const GURL HistoryUI::GetHistoryURLWithSearchText(const base::string16& text) { 1003 return GURL(std::string(chrome::kChromeUIHistoryURL) + "#q=" + 1004 net::EscapeQueryParamValue(UTF16ToUTF8(text), true)); 1005 } 1006 1007 // static 1008 base::RefCountedMemory* HistoryUI::GetFaviconResourceBytes( 1009 ui::ScaleFactor scale_factor) { 1010 return ResourceBundle::GetSharedInstance(). 1011 LoadDataResourceBytesForScale(IDR_HISTORY_FAVICON, scale_factor); 1012 } 1013