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