autofill_manager.cc revision f8ee788a64d60abd8f2d742a5fdedde054ecd910
1// Copyright 2013 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 "components/autofill/core/browser/autofill_manager.h" 6 7#include <stddef.h> 8 9#include <limits> 10#include <map> 11#include <set> 12#include <utility> 13 14#include "base/bind.h" 15#include "base/command_line.h" 16#include "base/guid.h" 17#include "base/logging.h" 18#include "base/prefs/pref_service.h" 19#include "base/strings/string16.h" 20#include "base/strings/string_util.h" 21#include "base/strings/utf_string_conversions.h" 22#include "base/threading/sequenced_worker_pool.h" 23#include "components/autofill/core/browser/autocomplete_history_manager.h" 24#include "components/autofill/core/browser/autofill_client.h" 25#include "components/autofill/core/browser/autofill_data_model.h" 26#include "components/autofill/core/browser/autofill_external_delegate.h" 27#include "components/autofill/core/browser/autofill_field.h" 28#include "components/autofill/core/browser/autofill_manager_test_delegate.h" 29#include "components/autofill/core/browser/autofill_metrics.h" 30#include "components/autofill/core/browser/autofill_profile.h" 31#include "components/autofill/core/browser/autofill_type.h" 32#include "components/autofill/core/browser/credit_card.h" 33#include "components/autofill/core/browser/form_structure.h" 34#include "components/autofill/core/browser/personal_data_manager.h" 35#include "components/autofill/core/browser/phone_number.h" 36#include "components/autofill/core/browser/phone_number_i18n.h" 37#include "components/autofill/core/browser/popup_item_ids.h" 38#include "components/autofill/core/common/autofill_data_validation.h" 39#include "components/autofill/core/common/autofill_pref_names.h" 40#include "components/autofill/core/common/autofill_switches.h" 41#include "components/autofill/core/common/form_data.h" 42#include "components/autofill/core/common/form_data_predictions.h" 43#include "components/autofill/core/common/form_field_data.h" 44#include "components/autofill/core/common/password_form_fill_data.h" 45#include "components/pref_registry/pref_registry_syncable.h" 46#include "grit/components_strings.h" 47#include "ui/base/l10n/l10n_util.h" 48#include "ui/gfx/rect.h" 49#include "url/gurl.h" 50 51namespace autofill { 52 53typedef PersonalDataManager::GUIDPair GUIDPair; 54 55using base::TimeTicks; 56 57namespace { 58 59// We only send a fraction of the forms to upload server. 60// The rate for positive/negative matches potentially could be different. 61const double kAutofillPositiveUploadRateDefaultValue = 0.20; 62const double kAutofillNegativeUploadRateDefaultValue = 0.20; 63 64const size_t kMaxRecentFormSignaturesToRemember = 3; 65 66// Set a conservative upper bound on the number of forms we are willing to 67// cache, simply to prevent unbounded memory consumption. 68const size_t kMaxFormCacheSize = 100; 69 70// Removes duplicate suggestions whilst preserving their original order. 71void RemoveDuplicateSuggestions(std::vector<base::string16>* values, 72 std::vector<base::string16>* labels, 73 std::vector<base::string16>* icons, 74 std::vector<int>* unique_ids) { 75 DCHECK_EQ(values->size(), labels->size()); 76 DCHECK_EQ(values->size(), icons->size()); 77 DCHECK_EQ(values->size(), unique_ids->size()); 78 79 std::set<std::pair<base::string16, base::string16> > seen_suggestions; 80 std::vector<base::string16> values_copy; 81 std::vector<base::string16> labels_copy; 82 std::vector<base::string16> icons_copy; 83 std::vector<int> unique_ids_copy; 84 85 for (size_t i = 0; i < values->size(); ++i) { 86 const std::pair<base::string16, base::string16> suggestion( 87 (*values)[i], (*labels)[i]); 88 if (seen_suggestions.insert(suggestion).second) { 89 values_copy.push_back((*values)[i]); 90 labels_copy.push_back((*labels)[i]); 91 icons_copy.push_back((*icons)[i]); 92 unique_ids_copy.push_back((*unique_ids)[i]); 93 } 94 } 95 96 values->swap(values_copy); 97 labels->swap(labels_copy); 98 icons->swap(icons_copy); 99 unique_ids->swap(unique_ids_copy); 100} 101 102// Precondition: |form_structure| and |form| should correspond to the same 103// logical form. Returns true if any field in the given |section| within |form| 104// is auto-filled. 105bool SectionIsAutofilled(const FormStructure& form_structure, 106 const FormData& form, 107 const std::string& section) { 108 DCHECK_EQ(form_structure.field_count(), form.fields.size()); 109 for (size_t i = 0; i < form_structure.field_count(); ++i) { 110 if (form_structure.field(i)->section() == section && 111 form.fields[i].is_autofilled) { 112 return true; 113 } 114 } 115 116 return false; 117} 118 119bool FormIsHTTPS(const FormStructure& form) { 120 // TODO(blundell): Change this to use a constant once crbug.com/306258 is 121 // fixed. 122 return form.source_url().SchemeIs("https"); 123} 124 125// Uses the existing personal data in |profiles| and |credit_cards| to determine 126// possible field types for the |submitted_form|. This is potentially 127// expensive -- on the order of 50ms even for a small set of |stored_data|. 128// Hence, it should not run on the UI thread -- to avoid locking up the UI -- 129// nor on the IO thread -- to avoid blocking IPC calls. 130void DeterminePossibleFieldTypesForUpload( 131 const std::vector<AutofillProfile>& profiles, 132 const std::vector<CreditCard>& credit_cards, 133 const std::string& app_locale, 134 FormStructure* submitted_form) { 135 // For each field in the |submitted_form|, extract the value. Then for each 136 // profile or credit card, identify any stored types that match the value. 137 for (size_t i = 0; i < submitted_form->field_count(); ++i) { 138 AutofillField* field = submitted_form->field(i); 139 ServerFieldTypeSet matching_types; 140 141 // If it's a password field, set the type directly. 142 if (field->form_control_type == "password") { 143 matching_types.insert(PASSWORD); 144 } else { 145 base::string16 value; 146 base::TrimWhitespace(field->value, base::TRIM_ALL, &value); 147 for (std::vector<AutofillProfile>::const_iterator it = profiles.begin(); 148 it != profiles.end(); ++it) { 149 it->GetMatchingTypes(value, app_locale, &matching_types); 150 } 151 for (std::vector<CreditCard>::const_iterator it = credit_cards.begin(); 152 it != credit_cards.end(); ++it) { 153 it->GetMatchingTypes(value, app_locale, &matching_types); 154 } 155 } 156 157 if (matching_types.empty()) 158 matching_types.insert(UNKNOWN_TYPE); 159 160 field->set_possible_types(matching_types); 161 } 162} 163 164} // namespace 165 166AutofillManager::AutofillManager( 167 AutofillDriver* driver, 168 AutofillClient* client, 169 const std::string& app_locale, 170 AutofillDownloadManagerState enable_download_manager) 171 : driver_(driver), 172 client_(client), 173 app_locale_(app_locale), 174 personal_data_(client->GetPersonalDataManager()), 175 autocomplete_history_manager_( 176 new AutocompleteHistoryManager(driver, client)), 177 metric_logger_(new AutofillMetrics), 178 has_logged_autofill_enabled_(false), 179 has_logged_address_suggestions_count_(false), 180 did_show_suggestions_(false), 181 user_did_type_(false), 182 user_did_autofill_(false), 183 user_did_edit_autofilled_field_(false), 184 external_delegate_(NULL), 185 test_delegate_(NULL), 186 weak_ptr_factory_(this) { 187 if (enable_download_manager == ENABLE_AUTOFILL_DOWNLOAD_MANAGER) { 188 download_manager_.reset( 189 new AutofillDownloadManager(driver, client_->GetPrefs(), this)); 190 } 191} 192 193AutofillManager::~AutofillManager() {} 194 195// static 196void AutofillManager::RegisterProfilePrefs( 197 user_prefs::PrefRegistrySyncable* registry) { 198 registry->RegisterBooleanPref( 199 prefs::kAutofillEnabled, 200 true, 201 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); 202#if defined(OS_MACOSX) || defined(OS_ANDROID) 203 registry->RegisterBooleanPref( 204 prefs::kAutofillAuxiliaryProfilesEnabled, 205 true, 206 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); 207#else // defined(OS_MACOSX) || defined(OS_ANDROID) 208 registry->RegisterBooleanPref( 209 prefs::kAutofillAuxiliaryProfilesEnabled, 210 false, 211 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 212#endif // defined(OS_MACOSX) || defined(OS_ANDROID) 213#if defined(OS_MACOSX) 214 registry->RegisterBooleanPref( 215 prefs::kAutofillMacAddressBookQueried, 216 false, 217 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 218#endif // defined(OS_MACOSX) 219 registry->RegisterDoublePref( 220 prefs::kAutofillPositiveUploadRate, 221 kAutofillPositiveUploadRateDefaultValue, 222 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 223 registry->RegisterDoublePref( 224 prefs::kAutofillNegativeUploadRate, 225 kAutofillNegativeUploadRateDefaultValue, 226 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 227 228#if defined(OS_MACOSX) && !defined(OS_IOS) 229 registry->RegisterBooleanPref( 230 prefs::kAutofillUseMacAddressBook, 231 false, 232 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 233#endif // defined(OS_MACOSX) && !defined(OS_IOS) 234} 235 236#if defined(OS_MACOSX) && !defined(OS_IOS) 237void AutofillManager::MigrateUserPrefs(PrefService* prefs) { 238 const PrefService::Preference* pref = 239 prefs->FindPreference(prefs::kAutofillUseMacAddressBook); 240 241 // If the pref is not its default value, then the migration has already been 242 // performed. 243 if (!pref->IsDefaultValue()) 244 return; 245 246 // Whether Chrome has already tried to access the user's Address Book. 247 const PrefService::Preference* pref_accessed = 248 prefs->FindPreference(prefs::kAutofillMacAddressBookQueried); 249 // Whether the user wants to use the Address Book to populate Autofill. 250 const PrefService::Preference* pref_enabled = 251 prefs->FindPreference(prefs::kAutofillAuxiliaryProfilesEnabled); 252 253 if (pref_accessed->IsDefaultValue() && pref_enabled->IsDefaultValue()) { 254 // This is likely a new user. Reset the default value to prevent the 255 // migration from happening again. 256 prefs->SetBoolean(prefs::kAutofillUseMacAddressBook, 257 prefs->GetBoolean(prefs::kAutofillUseMacAddressBook)); 258 return; 259 } 260 261 bool accessed; 262 bool enabled; 263 bool success = pref_accessed->GetValue()->GetAsBoolean(&accessed); 264 DCHECK(success); 265 success = pref_enabled->GetValue()->GetAsBoolean(&enabled); 266 DCHECK(success); 267 268 prefs->SetBoolean(prefs::kAutofillUseMacAddressBook, accessed && enabled); 269} 270#endif // defined(OS_MACOSX) && !defined(OS_IOS) 271 272void AutofillManager::SetExternalDelegate(AutofillExternalDelegate* delegate) { 273 // TODO(jrg): consider passing delegate into the ctor. That won't 274 // work if the delegate has a pointer to the AutofillManager, but 275 // future directions may not need such a pointer. 276 external_delegate_ = delegate; 277 autocomplete_history_manager_->SetExternalDelegate(delegate); 278} 279 280void AutofillManager::ShowAutofillSettings() { 281 client_->ShowAutofillSettings(); 282} 283 284#if defined(OS_MACOSX) && !defined(OS_IOS) 285bool AutofillManager::ShouldShowAccessAddressBookSuggestion( 286 const FormData& form, 287 const FormFieldData& field) { 288 if (!personal_data_) 289 return false; 290 FormStructure* form_structure = NULL; 291 AutofillField* autofill_field = NULL; 292 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field)) 293 return false; 294 295 return personal_data_->ShouldShowAccessAddressBookSuggestion( 296 autofill_field->Type()); 297} 298 299bool AutofillManager::AccessAddressBook() { 300 if (!personal_data_) 301 return false; 302 return personal_data_->AccessAddressBook(); 303} 304#endif // defined(OS_MACOSX) && !defined(OS_IOS) 305 306bool AutofillManager::OnFormSubmitted(const FormData& form, 307 const TimeTicks& timestamp) { 308 if (!IsValidFormData(form)) 309 return false; 310 311 // Let Autocomplete know as well. 312 autocomplete_history_manager_->OnFormSubmitted(form); 313 314 // Grab a copy of the form data. 315 scoped_ptr<FormStructure> submitted_form(new FormStructure(form)); 316 317 if (!ShouldUploadForm(*submitted_form)) 318 return false; 319 320 // Don't save data that was submitted through JavaScript. 321 if (!form.user_submitted) 322 return false; 323 324 // Ignore forms not present in our cache. These are typically forms with 325 // wonky JavaScript that also makes them not auto-fillable. 326 FormStructure* cached_submitted_form; 327 if (!FindCachedForm(form, &cached_submitted_form)) 328 return false; 329 330 submitted_form->UpdateFromCache(*cached_submitted_form); 331 if (submitted_form->IsAutofillable(true)) 332 ImportFormData(*submitted_form); 333 334 // Only upload server statistics and UMA metrics if at least some local data 335 // is available to use as a baseline. 336 const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles(); 337 const std::vector<CreditCard*>& credit_cards = 338 personal_data_->GetCreditCards(); 339 if (!profiles.empty() || !credit_cards.empty()) { 340 // Copy the profile and credit card data, so that it can be accessed on a 341 // separate thread. 342 std::vector<AutofillProfile> copied_profiles; 343 copied_profiles.reserve(profiles.size()); 344 for (std::vector<AutofillProfile*>::const_iterator it = profiles.begin(); 345 it != profiles.end(); ++it) { 346 copied_profiles.push_back(**it); 347 } 348 349 std::vector<CreditCard> copied_credit_cards; 350 copied_credit_cards.reserve(credit_cards.size()); 351 for (std::vector<CreditCard*>::const_iterator it = credit_cards.begin(); 352 it != credit_cards.end(); ++it) { 353 copied_credit_cards.push_back(**it); 354 } 355 356 // Note that ownership of |submitted_form| is passed to the second task, 357 // using |base::Owned|. 358 FormStructure* raw_submitted_form = submitted_form.get(); 359 driver_->GetBlockingPool()->PostTaskAndReply( 360 FROM_HERE, 361 base::Bind(&DeterminePossibleFieldTypesForUpload, 362 copied_profiles, 363 copied_credit_cards, 364 app_locale_, 365 raw_submitted_form), 366 base::Bind(&AutofillManager::UploadFormDataAsyncCallback, 367 weak_ptr_factory_.GetWeakPtr(), 368 base::Owned(submitted_form.release()), 369 forms_loaded_timestamps_[form], 370 initial_interaction_timestamp_, 371 timestamp)); 372 } 373 374 return true; 375} 376 377void AutofillManager::OnFormsSeen(const std::vector<FormData>& forms, 378 const TimeTicks& timestamp) { 379 if (!IsValidFormDataVector(forms)) 380 return; 381 382 if (!driver_->RendererIsAvailable()) 383 return; 384 385 bool enabled = IsAutofillEnabled(); 386 if (!has_logged_autofill_enabled_) { 387 metric_logger_->LogIsAutofillEnabledAtPageLoad(enabled); 388 has_logged_autofill_enabled_ = true; 389 } 390 391 if (!enabled) 392 return; 393 394 for (size_t i = 0; i < forms.size(); ++i) { 395 forms_loaded_timestamps_[forms[i]] = timestamp; 396 } 397 398 ParseForms(forms); 399} 400 401void AutofillManager::OnTextFieldDidChange(const FormData& form, 402 const FormFieldData& field, 403 const TimeTicks& timestamp) { 404 if (!IsValidFormData(form) || !IsValidFormFieldData(field)) 405 return; 406 407 FormStructure* form_structure = NULL; 408 AutofillField* autofill_field = NULL; 409 if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field)) 410 return; 411 412 if (!user_did_type_) { 413 user_did_type_ = true; 414 metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_TYPE); 415 } 416 417 if (autofill_field->is_autofilled) { 418 autofill_field->is_autofilled = false; 419 metric_logger_->LogUserHappinessMetric( 420 AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD); 421 422 if (!user_did_edit_autofilled_field_) { 423 user_did_edit_autofilled_field_ = true; 424 metric_logger_->LogUserHappinessMetric( 425 AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD_ONCE); 426 } 427 } 428 429 UpdateInitialInteractionTimestamp(timestamp); 430} 431 432void AutofillManager::OnQueryFormFieldAutofill(int query_id, 433 const FormData& form, 434 const FormFieldData& field, 435 const gfx::RectF& bounding_box, 436 bool display_warning) { 437 if (!IsValidFormData(form) || !IsValidFormFieldData(field)) 438 return; 439 440 std::vector<base::string16> values; 441 std::vector<base::string16> labels; 442 std::vector<base::string16> icons; 443 std::vector<int> unique_ids; 444 445 external_delegate_->OnQuery(query_id, 446 form, 447 field, 448 bounding_box, 449 display_warning); 450 FormStructure* form_structure = NULL; 451 AutofillField* autofill_field = NULL; 452 if (RefreshDataModels() && 453 driver_->RendererIsAvailable() && 454 GetCachedFormAndField(form, field, &form_structure, &autofill_field) && 455 // Don't send suggestions for forms that aren't auto-fillable. 456 form_structure->IsAutofillable(false)) { 457 AutofillType type = autofill_field->Type(); 458 bool is_filling_credit_card = (type.group() == CREDIT_CARD); 459 if (is_filling_credit_card) { 460 GetCreditCardSuggestions( 461 field, type, &values, &labels, &icons, &unique_ids); 462 } else { 463 GetProfileSuggestions( 464 form_structure, field, type, &values, &labels, &icons, &unique_ids); 465 } 466 467 DCHECK_EQ(values.size(), labels.size()); 468 DCHECK_EQ(values.size(), icons.size()); 469 DCHECK_EQ(values.size(), unique_ids.size()); 470 471 if (!values.empty()) { 472 // Don't provide Autofill suggestions when Autofill is disabled, and don't 473 // provide credit card suggestions for non-HTTPS pages. However, provide a 474 // warning to the user in these cases. 475 int warning = 0; 476 if (!form_structure->IsAutofillable(true)) 477 warning = IDS_AUTOFILL_WARNING_FORM_DISABLED; 478 else if (is_filling_credit_card && !FormIsHTTPS(*form_structure)) 479 warning = IDS_AUTOFILL_WARNING_INSECURE_CONNECTION; 480 if (warning) { 481 values.assign(1, l10n_util::GetStringUTF16(warning)); 482 labels.assign(1, base::string16()); 483 icons.assign(1, base::string16()); 484 unique_ids.assign(1, POPUP_ITEM_ID_WARNING_MESSAGE); 485 } else { 486 bool section_is_autofilled = 487 SectionIsAutofilled(*form_structure, form, 488 autofill_field->section()); 489 if (section_is_autofilled) { 490 // If the relevant section is auto-filled and the renderer is querying 491 // for suggestions, then the user is editing the value of a field. 492 // In this case, mimic autocomplete: don't display labels or icons, 493 // as that information is redundant. 494 labels.assign(labels.size(), base::string16()); 495 icons.assign(icons.size(), base::string16()); 496 } 497 498 // When filling credit card suggestions, the values and labels are 499 // typically obfuscated, which makes detecting duplicates hard. Since 500 // duplicates only tend to be a problem when filling address forms 501 // anyway, only don't de-dup credit card suggestions. 502 if (!is_filling_credit_card) 503 RemoveDuplicateSuggestions(&values, &labels, &icons, &unique_ids); 504 505 // The first time we show suggestions on this page, log the number of 506 // suggestions shown. 507 if (!has_logged_address_suggestions_count_ && !section_is_autofilled) { 508 metric_logger_->LogAddressSuggestionsCount(values.size()); 509 has_logged_address_suggestions_count_ = true; 510 } 511 } 512 } 513 } 514 515 // Add the results from AutoComplete. They come back asynchronously, so we 516 // hand off what we generated and they will send the results back to the 517 // renderer. 518 autocomplete_history_manager_->OnGetAutocompleteSuggestions( 519 query_id, field.name, field.value, field.form_control_type, values, 520 labels, icons, unique_ids); 521} 522 523void AutofillManager::FillOrPreviewForm( 524 AutofillDriver::RendererFormDataAction action, 525 int query_id, 526 const FormData& form, 527 const FormFieldData& field, 528 int unique_id) { 529 if (!IsValidFormData(form) || !IsValidFormFieldData(field)) 530 return; 531 532 const AutofillDataModel* data_model = NULL; 533 size_t variant = 0; 534 FormStructure* form_structure = NULL; 535 AutofillField* autofill_field = NULL; 536 bool is_credit_card = false; 537 // NOTE: RefreshDataModels may invalidate |data_model| because it causes the 538 // PersonalDataManager to reload Mac address book entries. Thus it must come 539 // before GetProfileOrCreditCard. 540 if (!RefreshDataModels() || 541 !driver_->RendererIsAvailable() || 542 !GetProfileOrCreditCard( 543 unique_id, &data_model, &variant, &is_credit_card) || 544 !GetCachedFormAndField(form, field, &form_structure, &autofill_field)) 545 return; 546 547 DCHECK(form_structure); 548 DCHECK(autofill_field); 549 550 FormData result = form; 551 552 base::string16 profile_full_name; 553 if (!is_credit_card) { 554 profile_full_name = data_model->GetInfo( 555 AutofillType(NAME_FULL), app_locale_); 556 } 557 558 // If the relevant section is auto-filled, we should fill |field| but not the 559 // rest of the form. 560 if (SectionIsAutofilled(*form_structure, form, autofill_field->section())) { 561 for (std::vector<FormFieldData>::iterator iter = result.fields.begin(); 562 iter != result.fields.end(); ++iter) { 563 if ((*iter) == field) { 564 base::string16 value = data_model->GetInfoForVariant( 565 autofill_field->Type(), variant, app_locale_); 566 if (AutofillField::FillFormField( 567 *autofill_field, value, app_locale_, &(*iter))) { 568 // Mark the cached field as autofilled, so that we can detect when a 569 // user edits an autofilled field (for metrics). 570 autofill_field->is_autofilled = true; 571 572 if (!is_credit_card && !value.empty()) 573 client_->DidFillOrPreviewField(value, profile_full_name); 574 } 575 break; 576 } 577 } 578 579 driver_->SendFormDataToRenderer(query_id, action, result); 580 return; 581 } 582 583 // Cache the field type for the field from which the user initiated autofill. 584 FieldTypeGroup initiating_group_type = autofill_field->Type().group(); 585 DCHECK_EQ(form_structure->field_count(), form.fields.size()); 586 for (size_t i = 0; i < form_structure->field_count(); ++i) { 587 if (form_structure->field(i)->section() != autofill_field->section()) 588 continue; 589 590 DCHECK_EQ(*form_structure->field(i), result.fields[i]); 591 592 const AutofillField* cached_field = form_structure->field(i); 593 FieldTypeGroup field_group_type = cached_field->Type().group(); 594 if (field_group_type != NO_GROUP) { 595 // If the field being filled is either 596 // (a) the field that the user initiated the fill from, or 597 // (b) part of the same logical unit, e.g. name or phone number, 598 // then take the multi-profile "variant" into account. 599 // Otherwise fill with the default (zeroth) variant. 600 size_t use_variant = 0; 601 if (result.fields[i] == field || 602 field_group_type == initiating_group_type) { 603 use_variant = variant; 604 } 605 base::string16 value = data_model->GetInfoForVariant( 606 cached_field->Type(), use_variant, app_locale_); 607 608 // Must match ForEachMatchingFormField() in form_autofill_util.cc. 609 // Only notify autofilling of empty fields and the field that initiated 610 // the filling (note that "select-one" controls may not be empty but will 611 // still be autofilled). 612 bool should_notify = 613 !is_credit_card && 614 !value.empty() && 615 (result.fields[i] == field || 616 result.fields[i].form_control_type == "select-one" || 617 result.fields[i].value.empty()); 618 if (AutofillField::FillFormField( 619 *cached_field, value, app_locale_, &result.fields[i])) { 620 // Mark the cached field as autofilled, so that we can detect when a 621 // user edits an autofilled field (for metrics). 622 form_structure->field(i)->is_autofilled = true; 623 624 // Mark the field as autofilled when a non-empty value is assigned to 625 // it. This allows the renderer to distinguish autofilled fields from 626 // fields with non-empty values, such as select-one fields. 627 result.fields[i].is_autofilled = true; 628 629 if (should_notify) 630 client_->DidFillOrPreviewField(value, profile_full_name); 631 } 632 } 633 } 634 635 autofilled_form_signatures_.push_front(form_structure->FormSignature()); 636 // Only remember the last few forms that we've seen, both to avoid false 637 // positives and to avoid wasting memory. 638 if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember) 639 autofilled_form_signatures_.pop_back(); 640 641 driver_->SendFormDataToRenderer(query_id, action, result); 642} 643 644void AutofillManager::OnDidPreviewAutofillFormData() { 645 if (test_delegate_) 646 test_delegate_->DidPreviewFormData(); 647} 648 649void AutofillManager::OnDidFillAutofillFormData(const TimeTicks& timestamp) { 650 if (test_delegate_) 651 test_delegate_->DidFillFormData(); 652 653 metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_AUTOFILL); 654 if (!user_did_autofill_) { 655 user_did_autofill_ = true; 656 metric_logger_->LogUserHappinessMetric( 657 AutofillMetrics::USER_DID_AUTOFILL_ONCE); 658 } 659 660 UpdateInitialInteractionTimestamp(timestamp); 661} 662 663void AutofillManager::DidShowSuggestions(bool is_new_popup) { 664 if (test_delegate_) 665 test_delegate_->DidShowSuggestions(); 666 667 if (is_new_popup) { 668 metric_logger_->LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN); 669 670 if (!did_show_suggestions_) { 671 did_show_suggestions_ = true; 672 metric_logger_->LogUserHappinessMetric( 673 AutofillMetrics::SUGGESTIONS_SHOWN_ONCE); 674 } 675 } 676} 677 678void AutofillManager::OnHidePopup() { 679 if (!IsAutofillEnabled()) 680 return; 681 682 client_->HideAutofillPopup(); 683} 684 685void AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id) { 686 const AutofillDataModel* data_model = NULL; 687 size_t variant = 0; 688 bool unused_is_credit_card = false; 689 if (!GetProfileOrCreditCard( 690 unique_id, &data_model, &variant, &unused_is_credit_card)) { 691 NOTREACHED(); 692 return; 693 } 694 695 // TODO(csharp): If we are dealing with a variant only the variant should 696 // be deleted, instead of doing nothing. 697 // http://crbug.com/124211 698 if (variant != 0) 699 return; 700 701 personal_data_->RemoveByGUID(data_model->guid()); 702} 703 704void AutofillManager::RemoveAutocompleteEntry(const base::string16& name, 705 const base::string16& value) { 706 autocomplete_history_manager_->OnRemoveAutocompleteEntry(name, value); 707} 708 709const std::vector<FormStructure*>& AutofillManager::GetFormStructures() { 710 return form_structures_.get(); 711} 712 713void AutofillManager::SetTestDelegate(AutofillManagerTestDelegate* delegate) { 714 test_delegate_ = delegate; 715} 716 717void AutofillManager::OnSetDataList(const std::vector<base::string16>& values, 718 const std::vector<base::string16>& labels) { 719 if (!IsValidString16Vector(values) || 720 !IsValidString16Vector(labels) || 721 values.size() != labels.size()) 722 return; 723 724 external_delegate_->SetCurrentDataListValues(values, labels); 725} 726 727void AutofillManager::OnLoadedServerPredictions( 728 const std::string& response_xml) { 729 // Parse and store the server predictions. 730 FormStructure::ParseQueryResponse(response_xml, 731 form_structures_.get(), 732 *metric_logger_); 733 734 // Forward form structures to the password generation manager to detect 735 // account creation forms. 736 client_->DetectAccountCreationForms(form_structures_.get()); 737 738 // If the corresponding flag is set, annotate forms with the predicted types. 739 driver_->SendAutofillTypePredictionsToRenderer(form_structures_.get()); 740} 741 742void AutofillManager::OnDidEndTextFieldEditing() { 743 external_delegate_->DidEndTextFieldEditing(); 744} 745 746bool AutofillManager::IsAutofillEnabled() const { 747 return client_->GetPrefs()->GetBoolean(prefs::kAutofillEnabled); 748} 749 750void AutofillManager::ImportFormData(const FormStructure& submitted_form) { 751 scoped_ptr<CreditCard> imported_credit_card; 752 if (!personal_data_->ImportFormData(submitted_form, &imported_credit_card)) 753 return; 754 755 // If credit card information was submitted, we need to confirm whether to 756 // save it. 757 if (imported_credit_card) { 758 client_->ConfirmSaveCreditCard( 759 *metric_logger_, 760 base::Bind( 761 base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard), 762 base::Unretained(personal_data_), 763 *imported_credit_card)); 764 } 765} 766 767// Note that |submitted_form| is passed as a pointer rather than as a reference 768// so that we can get memory management right across threads. Note also that we 769// explicitly pass in all the time stamps of interest, as the cached ones might 770// get reset before this method executes. 771void AutofillManager::UploadFormDataAsyncCallback( 772 const FormStructure* submitted_form, 773 const TimeTicks& load_time, 774 const TimeTicks& interaction_time, 775 const TimeTicks& submission_time) { 776 submitted_form->LogQualityMetrics(*metric_logger_, 777 load_time, 778 interaction_time, 779 submission_time); 780 781 if (submitted_form->ShouldBeCrowdsourced()) 782 UploadFormData(*submitted_form); 783} 784 785void AutofillManager::UploadFormData(const FormStructure& submitted_form) { 786 if (!download_manager_) 787 return; 788 789 // Check if the form is among the forms that were recently auto-filled. 790 bool was_autofilled = false; 791 std::string form_signature = submitted_form.FormSignature(); 792 for (std::list<std::string>::const_iterator it = 793 autofilled_form_signatures_.begin(); 794 it != autofilled_form_signatures_.end() && !was_autofilled; 795 ++it) { 796 if (*it == form_signature) 797 was_autofilled = true; 798 } 799 800 ServerFieldTypeSet non_empty_types; 801 personal_data_->GetNonEmptyTypes(&non_empty_types); 802 // Always add PASSWORD to |non_empty_types| so that if |submitted_form| 803 // contains a password field it will be uploaded to the server. If 804 // |submitted_form| doesn't contain a password field, there is no side 805 // effect from adding PASSWORD to |non_empty_types|. 806 non_empty_types.insert(PASSWORD); 807 808 download_manager_->StartUploadRequest(submitted_form, was_autofilled, 809 non_empty_types); 810} 811 812bool AutofillManager::UploadPasswordGenerationForm(const FormData& form) { 813 FormStructure form_structure(form); 814 815 if (!ShouldUploadForm(form_structure)) 816 return false; 817 818 if (!form_structure.ShouldBeCrowdsourced()) 819 return false; 820 821 // TODO(gcasto): Check that PasswordGeneration is enabled? 822 823 // Find the first password field to label. We don't try to label anything 824 // else. 825 bool found_password_field = false; 826 for (size_t i = 0; i < form_structure.field_count(); ++i) { 827 AutofillField* field = form_structure.field(i); 828 829 ServerFieldTypeSet types; 830 if (!found_password_field && field->form_control_type == "password") { 831 types.insert(ACCOUNT_CREATION_PASSWORD); 832 found_password_field = true; 833 } else { 834 types.insert(UNKNOWN_TYPE); 835 } 836 field->set_possible_types(types); 837 } 838 DCHECK(found_password_field); 839 840 // Only one field type should be present. 841 ServerFieldTypeSet available_field_types; 842 available_field_types.insert(ACCOUNT_CREATION_PASSWORD); 843 844 // Force uploading as these events are relatively rare and we want to make 845 // sure to receive them. It also makes testing easier if these requests 846 // always pass. 847 form_structure.set_upload_required(UPLOAD_REQUIRED); 848 849 if (!download_manager_) 850 return false; 851 852 return download_manager_->StartUploadRequest(form_structure, 853 false /* was_autofilled */, 854 available_field_types); 855} 856 857void AutofillManager::Reset() { 858 form_structures_.clear(); 859 has_logged_autofill_enabled_ = false; 860 has_logged_address_suggestions_count_ = false; 861 did_show_suggestions_ = false; 862 user_did_type_ = false; 863 user_did_autofill_ = false; 864 user_did_edit_autofilled_field_ = false; 865 forms_loaded_timestamps_.clear(); 866 initial_interaction_timestamp_ = TimeTicks(); 867 external_delegate_->Reset(); 868} 869 870AutofillManager::AutofillManager(AutofillDriver* driver, 871 AutofillClient* client, 872 PersonalDataManager* personal_data) 873 : driver_(driver), 874 client_(client), 875 app_locale_("en-US"), 876 personal_data_(personal_data), 877 autocomplete_history_manager_( 878 new AutocompleteHistoryManager(driver, client)), 879 metric_logger_(new AutofillMetrics), 880 has_logged_autofill_enabled_(false), 881 has_logged_address_suggestions_count_(false), 882 did_show_suggestions_(false), 883 user_did_type_(false), 884 user_did_autofill_(false), 885 user_did_edit_autofilled_field_(false), 886 external_delegate_(NULL), 887 test_delegate_(NULL), 888 weak_ptr_factory_(this) { 889 DCHECK(driver_); 890 DCHECK(client_); 891} 892 893void AutofillManager::set_metric_logger(const AutofillMetrics* metric_logger) { 894 metric_logger_.reset(metric_logger); 895} 896 897bool AutofillManager::RefreshDataModels() const { 898 if (!IsAutofillEnabled()) 899 return false; 900 901 // No autofill data to return if the profiles are empty. 902 if (personal_data_->GetProfiles().empty() && 903 personal_data_->GetCreditCards().empty()) { 904 return false; 905 } 906 907 return true; 908} 909 910bool AutofillManager::GetProfileOrCreditCard( 911 int unique_id, 912 const AutofillDataModel** data_model, 913 size_t* variant, 914 bool* is_credit_card) const { 915 // Unpack the |unique_id| into component parts. 916 GUIDPair credit_card_guid; 917 GUIDPair profile_guid; 918 UnpackGUIDs(unique_id, &credit_card_guid, &profile_guid); 919 DCHECK(!base::IsValidGUID(credit_card_guid.first) || 920 !base::IsValidGUID(profile_guid.first)); 921 *is_credit_card = false; 922 923 // Find the profile that matches the |profile_guid|, if one is specified. 924 // Otherwise find the credit card that matches the |credit_card_guid|, 925 // if specified. 926 if (base::IsValidGUID(profile_guid.first)) { 927 *data_model = personal_data_->GetProfileByGUID(profile_guid.first); 928 *variant = profile_guid.second; 929 } else if (base::IsValidGUID(credit_card_guid.first)) { 930 *data_model = personal_data_->GetCreditCardByGUID(credit_card_guid.first); 931 *variant = credit_card_guid.second; 932 *is_credit_card = true; 933 } 934 935 return !!*data_model; 936} 937 938bool AutofillManager::FindCachedForm(const FormData& form, 939 FormStructure** form_structure) const { 940 // Find the FormStructure that corresponds to |form|. 941 // Scan backward through the cached |form_structures_|, as updated versions of 942 // forms are added to the back of the list, whereas original versions of these 943 // forms might appear toward the beginning of the list. The communication 944 // protocol with the crowdsourcing server does not permit us to discard the 945 // original versions of the forms. 946 *form_structure = NULL; 947 for (std::vector<FormStructure*>::const_reverse_iterator iter = 948 form_structures_.rbegin(); 949 iter != form_structures_.rend(); ++iter) { 950 if (**iter == form) { 951 *form_structure = *iter; 952 953 // The same form might be cached with multiple field counts: in some 954 // cases, non-autofillable fields are filtered out, whereas in other cases 955 // they are not. To avoid thrashing the cache, keep scanning until we 956 // find a cached version with the same number of fields, if there is one. 957 if ((*iter)->field_count() == form.fields.size()) 958 break; 959 } 960 } 961 962 if (!(*form_structure)) 963 return false; 964 965 return true; 966} 967 968bool AutofillManager::GetCachedFormAndField(const FormData& form, 969 const FormFieldData& field, 970 FormStructure** form_structure, 971 AutofillField** autofill_field) { 972 // Find the FormStructure that corresponds to |form|. 973 // If we do not have this form in our cache but it is parseable, we'll add it 974 // in the call to |UpdateCachedForm()|. 975 if (!FindCachedForm(form, form_structure) && 976 !FormStructure(form).ShouldBeParsed(false)) { 977 return false; 978 } 979 980 // Update the cached form to reflect any dynamic changes to the form data, if 981 // necessary. 982 if (!UpdateCachedForm(form, *form_structure, form_structure)) 983 return false; 984 985 // No data to return if there are no auto-fillable fields. 986 if (!(*form_structure)->autofill_count()) 987 return false; 988 989 // Find the AutofillField that corresponds to |field|. 990 *autofill_field = NULL; 991 for (std::vector<AutofillField*>::const_iterator iter = 992 (*form_structure)->begin(); 993 iter != (*form_structure)->end(); ++iter) { 994 if ((**iter) == field) { 995 *autofill_field = *iter; 996 break; 997 } 998 } 999 1000 // Even though we always update the cache, the field might not exist if the 1001 // website disables autocomplete while the user is interacting with the form. 1002 // See http://crbug.com/160476 1003 return *autofill_field != NULL; 1004} 1005 1006bool AutofillManager::UpdateCachedForm(const FormData& live_form, 1007 const FormStructure* cached_form, 1008 FormStructure** updated_form) { 1009 bool needs_update = 1010 (!cached_form || 1011 live_form.fields.size() != cached_form->field_count()); 1012 for (size_t i = 0; !needs_update && i < cached_form->field_count(); ++i) { 1013 needs_update = *cached_form->field(i) != live_form.fields[i]; 1014 } 1015 1016 if (!needs_update) 1017 return true; 1018 1019 if (form_structures_.size() >= kMaxFormCacheSize) 1020 return false; 1021 1022 // Add the new or updated form to our cache. 1023 form_structures_.push_back(new FormStructure(live_form)); 1024 *updated_form = *form_structures_.rbegin(); 1025 (*updated_form)->DetermineHeuristicTypes(*metric_logger_); 1026 1027 // If we have cached data, propagate it to the updated form. 1028 if (cached_form) { 1029 std::map<base::string16, const AutofillField*> cached_fields; 1030 for (size_t i = 0; i < cached_form->field_count(); ++i) { 1031 const AutofillField* field = cached_form->field(i); 1032 cached_fields[field->unique_name()] = field; 1033 } 1034 1035 for (size_t i = 0; i < (*updated_form)->field_count(); ++i) { 1036 AutofillField* field = (*updated_form)->field(i); 1037 std::map<base::string16, const AutofillField*>::iterator cached_field = 1038 cached_fields.find(field->unique_name()); 1039 if (cached_field != cached_fields.end()) { 1040 field->set_server_type(cached_field->second->server_type()); 1041 field->is_autofilled = cached_field->second->is_autofilled; 1042 } 1043 } 1044 1045 // Note: We _must not_ remove the original version of the cached form from 1046 // the list of |form_structures_|. Otherwise, we break parsing of the 1047 // crowdsourcing server's response to our query. 1048 } 1049 1050 // Annotate the updated form with its predicted types. 1051 std::vector<FormStructure*> forms(1, *updated_form); 1052 driver_->SendAutofillTypePredictionsToRenderer(forms); 1053 1054 return true; 1055} 1056 1057void AutofillManager::GetProfileSuggestions( 1058 FormStructure* form, 1059 const FormFieldData& field, 1060 const AutofillType& type, 1061 std::vector<base::string16>* values, 1062 std::vector<base::string16>* labels, 1063 std::vector<base::string16>* icons, 1064 std::vector<int>* unique_ids) const { 1065 std::vector<ServerFieldType> field_types(form->field_count()); 1066 for (size_t i = 0; i < form->field_count(); ++i) { 1067 field_types.push_back(form->field(i)->Type().GetStorableType()); 1068 } 1069 std::vector<GUIDPair> guid_pairs; 1070 1071 personal_data_->GetProfileSuggestions( 1072 type, field.value, field.is_autofilled, field_types, 1073 base::Callback<bool(const AutofillProfile&)>(), 1074 values, labels, icons, &guid_pairs); 1075 1076 for (size_t i = 0; i < guid_pairs.size(); ++i) { 1077 unique_ids->push_back(PackGUIDs(GUIDPair(std::string(), 0), 1078 guid_pairs[i])); 1079 } 1080} 1081 1082void AutofillManager::GetCreditCardSuggestions( 1083 const FormFieldData& field, 1084 const AutofillType& type, 1085 std::vector<base::string16>* values, 1086 std::vector<base::string16>* labels, 1087 std::vector<base::string16>* icons, 1088 std::vector<int>* unique_ids) const { 1089 std::vector<GUIDPair> guid_pairs; 1090 personal_data_->GetCreditCardSuggestions( 1091 type, field.value, values, labels, icons, &guid_pairs); 1092 1093 for (size_t i = 0; i < guid_pairs.size(); ++i) { 1094 unique_ids->push_back(PackGUIDs(guid_pairs[i], GUIDPair(std::string(), 0))); 1095 } 1096} 1097 1098void AutofillManager::ParseForms(const std::vector<FormData>& forms) { 1099 std::vector<FormStructure*> non_queryable_forms; 1100 for (std::vector<FormData>::const_iterator iter = forms.begin(); 1101 iter != forms.end(); ++iter) { 1102 scoped_ptr<FormStructure> form_structure(new FormStructure(*iter)); 1103 if (!form_structure->ShouldBeParsed(false)) 1104 continue; 1105 1106 form_structure->DetermineHeuristicTypes(*metric_logger_); 1107 1108 // Set aside forms with method GET or author-specified types, so that they 1109 // are not included in the query to the server. 1110 if (form_structure->ShouldBeCrowdsourced()) 1111 form_structures_.push_back(form_structure.release()); 1112 else 1113 non_queryable_forms.push_back(form_structure.release()); 1114 } 1115 1116 if (!form_structures_.empty() && download_manager_) { 1117 // Query the server if we have at least one of the forms were parsed. 1118 download_manager_->StartQueryRequest(form_structures_.get(), 1119 *metric_logger_); 1120 } 1121 1122 for (std::vector<FormStructure*>::const_iterator iter = 1123 non_queryable_forms.begin(); 1124 iter != non_queryable_forms.end(); ++iter) { 1125 form_structures_.push_back(*iter); 1126 } 1127 1128 if (!form_structures_.empty()) 1129 metric_logger_->LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED); 1130 1131 // For the |non_queryable_forms|, we have all the field type info we're ever 1132 // going to get about them. For the other forms, we'll wait until we get a 1133 // response from the server. 1134 driver_->SendAutofillTypePredictionsToRenderer(non_queryable_forms); 1135} 1136 1137int AutofillManager::GUIDToID(const GUIDPair& guid) const { 1138 if (!base::IsValidGUID(guid.first)) 1139 return 0; 1140 1141 std::map<GUIDPair, int>::const_iterator iter = guid_id_map_.find(guid); 1142 if (iter == guid_id_map_.end()) { 1143 int id = guid_id_map_.size() + 1; 1144 guid_id_map_[guid] = id; 1145 id_guid_map_[id] = guid; 1146 return id; 1147 } else { 1148 return iter->second; 1149 } 1150} 1151 1152const GUIDPair AutofillManager::IDToGUID(int id) const { 1153 if (id == 0) 1154 return GUIDPair(std::string(), 0); 1155 1156 std::map<int, GUIDPair>::const_iterator iter = id_guid_map_.find(id); 1157 if (iter == id_guid_map_.end()) { 1158 NOTREACHED(); 1159 return GUIDPair(std::string(), 0); 1160 } 1161 1162 return iter->second; 1163} 1164 1165// When sending IDs (across processes) to the renderer we pack credit card and 1166// profile IDs into a single integer. Credit card IDs are sent in the high 1167// word and profile IDs are sent in the low word. 1168int AutofillManager::PackGUIDs(const GUIDPair& cc_guid, 1169 const GUIDPair& profile_guid) const { 1170 int cc_id = GUIDToID(cc_guid); 1171 int profile_id = GUIDToID(profile_guid); 1172 1173 DCHECK(cc_id <= std::numeric_limits<unsigned short>::max()); 1174 DCHECK(profile_id <= std::numeric_limits<unsigned short>::max()); 1175 1176 return cc_id << std::numeric_limits<unsigned short>::digits | profile_id; 1177} 1178 1179// When receiving IDs (across processes) from the renderer we unpack credit card 1180// and profile IDs from a single integer. Credit card IDs are stored in the 1181// high word and profile IDs are stored in the low word. 1182void AutofillManager::UnpackGUIDs(int id, 1183 GUIDPair* cc_guid, 1184 GUIDPair* profile_guid) const { 1185 int cc_id = id >> std::numeric_limits<unsigned short>::digits & 1186 std::numeric_limits<unsigned short>::max(); 1187 int profile_id = id & std::numeric_limits<unsigned short>::max(); 1188 1189 *cc_guid = IDToGUID(cc_id); 1190 *profile_guid = IDToGUID(profile_id); 1191} 1192 1193void AutofillManager::UpdateInitialInteractionTimestamp( 1194 const TimeTicks& interaction_timestamp) { 1195 if (initial_interaction_timestamp_.is_null() || 1196 interaction_timestamp < initial_interaction_timestamp_) { 1197 initial_interaction_timestamp_ = interaction_timestamp; 1198 } 1199} 1200 1201bool AutofillManager::ShouldUploadForm(const FormStructure& form) { 1202 if (!IsAutofillEnabled()) 1203 return false; 1204 1205 if (driver_->IsOffTheRecord()) 1206 return false; 1207 1208 // Disregard forms that we wouldn't ever autofill in the first place. 1209 if (!form.ShouldBeParsed(true)) 1210 return false; 1211 1212 return true; 1213} 1214 1215} // namespace autofill 1216