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.
5 #include "components/autofill/core/browser/autofill_manager.h"
14 #include "base/bind.h"
15 #include "base/command_line.h"
16 #include "base/containers/adapters.h"
17 #include "base/files/file_util.h"
18 #include "base/guid.h"
19 #include "base/logging.h"
20 #include "base/message_loop/message_loop.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/path_service.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/strings/string16.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/threading/sequenced_worker_pool.h"
29 #include "base/threading/thread_restrictions.h"
30 #include "components/autofill/core/browser/autocomplete_history_manager.h"
31 #include "components/autofill/core/browser/autofill_client.h"
32 #include "components/autofill/core/browser/autofill_data_model.h"
33 #include "components/autofill/core/browser/autofill_experiments.h"
34 #include "components/autofill/core/browser/autofill_external_delegate.h"
35 #include "components/autofill/core/browser/autofill_field.h"
36 #include "components/autofill/core/browser/autofill_manager_test_delegate.h"
37 #include "components/autofill/core/browser/autofill_metrics.h"
38 #include "components/autofill/core/browser/autofill_profile.h"
39 #include "components/autofill/core/browser/autofill_type.h"
40 #include "components/autofill/core/browser/credit_card.h"
41 #include "components/autofill/core/browser/field_types.h"
42 #include "components/autofill/core/browser/form_structure.h"
43 #include "components/autofill/core/browser/personal_data_manager.h"
44 #include "components/autofill/core/browser/phone_number.h"
45 #include "components/autofill/core/browser/phone_number_i18n.h"
46 #include "components/autofill/core/browser/popup_item_ids.h"
47 #include "components/autofill/core/common/autofill_data_validation.h"
48 #include "components/autofill/core/common/autofill_pref_names.h"
49 #include "components/autofill/core/common/autofill_switches.h"
50 #include "components/autofill/core/common/form_data.h"
51 #include "components/autofill/core/common/form_data_predictions.h"
52 #include "components/autofill/core/common/form_field_data.h"
53 #include "components/autofill/core/common/password_form_fill_data.h"
54 #include "components/pref_registry/pref_registry_syncable.h"
55 #include "grit/components_strings.h"
56 #include "ui/base/l10n/l10n_util.h"
57 #include "ui/gfx/geometry/rect.h"
61 #include "components/autofill/ios/browser/autofill_field_trial_ios.h"
62 #include "components/autofill/ios/browser/keyboard_accessory_metrics_logger.h"
67 using base::TimeTicks
;
71 // We only send a fraction of the forms to upload server.
72 // The rate for positive/negative matches potentially could be different.
73 const double kAutofillPositiveUploadRateDefaultValue
= 0.20;
74 const double kAutofillNegativeUploadRateDefaultValue
= 0.20;
76 const size_t kMaxRecentFormSignaturesToRemember
= 3;
78 // Set a conservative upper bound on the number of forms we are willing to
79 // cache, simply to prevent unbounded memory consumption.
80 const size_t kMaxFormCacheSize
= 100;
82 // Precondition: |form_structure| and |form| should correspond to the same
83 // logical form. Returns true if any field in the given |section| within |form|
85 bool SectionIsAutofilled(const FormStructure
& form_structure
,
87 const std::string
& section
) {
88 DCHECK_EQ(form_structure
.field_count(), form
.fields
.size());
89 for (size_t i
= 0; i
< form_structure
.field_count(); ++i
) {
90 if (form_structure
.field(i
)->section() == section
&&
91 form
.fields
[i
].is_autofilled
) {
99 // Uses the existing personal data in |profiles| and |credit_cards| to determine
100 // possible field types for the |submitted_form|. This is potentially
101 // expensive -- on the order of 50ms even for a small set of |stored_data|.
102 // Hence, it should not run on the UI thread -- to avoid locking up the UI --
103 // nor on the IO thread -- to avoid blocking IPC calls.
104 void DeterminePossibleFieldTypesForUpload(
105 const std::vector
<AutofillProfile
>& profiles
,
106 const std::vector
<CreditCard
>& credit_cards
,
107 const std::string
& app_locale
,
108 FormStructure
* submitted_form
) {
109 // For each field in the |submitted_form|, extract the value. Then for each
110 // profile or credit card, identify any stored types that match the value.
111 for (size_t i
= 0; i
< submitted_form
->field_count(); ++i
) {
112 AutofillField
* field
= submitted_form
->field(i
);
113 ServerFieldTypeSet matching_types
;
115 base::string16 value
;
116 base::TrimWhitespace(field
->value
, base::TRIM_ALL
, &value
);
117 for (const AutofillProfile
& profile
: profiles
)
118 profile
.GetMatchingTypes(value
, app_locale
, &matching_types
);
119 for (const CreditCard
& card
: credit_cards
)
120 card
.GetMatchingTypes(value
, app_locale
, &matching_types
);
122 if (matching_types
.empty())
123 matching_types
.insert(UNKNOWN_TYPE
);
125 field
->set_possible_types(matching_types
);
131 AutofillManager::AutofillManager(
132 AutofillDriver
* driver
,
133 AutofillClient
* client
,
134 const std::string
& app_locale
,
135 AutofillDownloadManagerState enable_download_manager
)
138 real_pan_client_(driver
->GetURLRequestContext(), this),
139 app_locale_(app_locale
),
140 personal_data_(client
->GetPersonalDataManager()),
141 autocomplete_history_manager_(
142 new AutocompleteHistoryManager(driver
, client
)),
143 address_form_event_logger_(
144 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */)),
145 credit_card_form_event_logger_(
146 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */)),
147 has_logged_autofill_enabled_(false),
148 has_logged_address_suggestions_count_(false),
149 did_show_suggestions_(false),
150 user_did_type_(false),
151 user_did_autofill_(false),
152 user_did_edit_autofilled_field_(false),
153 external_delegate_(NULL
),
154 test_delegate_(NULL
),
155 weak_ptr_factory_(this) {
156 if (enable_download_manager
== ENABLE_AUTOFILL_DOWNLOAD_MANAGER
) {
157 download_manager_
.reset(
158 new AutofillDownloadManager(driver
, client_
->GetPrefs(), this));
162 AutofillManager::~AutofillManager() {}
165 void AutofillManager::RegisterProfilePrefs(
166 user_prefs::PrefRegistrySyncable
* registry
) {
167 registry
->RegisterBooleanPref(
168 prefs::kAutofillEnabled
,
170 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
171 registry
->RegisterBooleanPref(prefs::kAutofillWalletSyncExperimentEnabled
,
173 // TODO(estade): Should this be syncable?
174 registry
->RegisterBooleanPref(
175 prefs::kAutofillWalletImportEnabled
,
177 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
178 // This choice is made on a per-device basis, so it's not syncable.
179 registry
->RegisterBooleanPref(
180 prefs::kAutofillWalletImportStorageCheckboxState
, true);
181 registry
->RegisterDoublePref(prefs::kAutofillPositiveUploadRate
,
182 kAutofillPositiveUploadRateDefaultValue
);
183 registry
->RegisterDoublePref(prefs::kAutofillNegativeUploadRate
,
184 kAutofillNegativeUploadRateDefaultValue
);
187 void AutofillManager::SetExternalDelegate(AutofillExternalDelegate
* delegate
) {
188 // TODO(jrg): consider passing delegate into the ctor. That won't
189 // work if the delegate has a pointer to the AutofillManager, but
190 // future directions may not need such a pointer.
191 external_delegate_
= delegate
;
192 autocomplete_history_manager_
->SetExternalDelegate(delegate
);
195 void AutofillManager::ShowAutofillSettings() {
196 client_
->ShowAutofillSettings();
199 bool AutofillManager::ShouldShowScanCreditCard(const FormData
& form
,
200 const FormFieldData
& field
) {
201 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
202 autofill::switches::kEnableCreditCardScan
) &&
203 (base::FieldTrialList::FindFullName("CreditCardScan") != "Enabled" ||
204 base::CommandLine::ForCurrentProcess()->HasSwitch(
205 autofill::switches::kDisableCreditCardScan
))) {
209 if (!client_
->HasCreditCardScanFeature())
212 AutofillField
* autofill_field
= GetAutofillField(form
, field
);
213 if (!autofill_field
||
214 autofill_field
->Type().GetStorableType() != CREDIT_CARD_NUMBER
) {
218 static const int kShowScanCreditCardMaxValueLength
= 6;
219 return field
.value
.size() <= kShowScanCreditCardMaxValueLength
&&
220 base::ContainsOnlyChars(CreditCard::StripSeparators(field
.value
),
221 base::ASCIIToUTF16("0123456789"));
224 bool AutofillManager::OnWillSubmitForm(const FormData
& form
,
225 const TimeTicks
& timestamp
) {
226 if (!IsValidFormData(form
))
229 // We will always give Autocomplete a chance to save the data.
230 scoped_ptr
<FormStructure
> submitted_form
= ValidateSubmittedForm(form
);
231 if (!submitted_form
) {
232 autocomplete_history_manager_
->OnWillSubmitForm(form
);
236 // However, if Autofill has recognized a field as CVC, that shouldn't be
238 FormData form_for_autocomplete
= submitted_form
->ToFormData();
239 for (size_t i
= 0; i
< submitted_form
->field_count(); ++i
) {
240 if (submitted_form
->field(i
)->Type().GetStorableType() ==
241 CREDIT_CARD_VERIFICATION_CODE
) {
242 form_for_autocomplete
.fields
[i
].should_autocomplete
= false;
245 autocomplete_history_manager_
->OnWillSubmitForm(form_for_autocomplete
);
247 address_form_event_logger_
->OnWillSubmitForm();
248 credit_card_form_event_logger_
->OnWillSubmitForm();
250 // Only upload server statistics and UMA metrics if at least some local data
251 // is available to use as a baseline.
252 const std::vector
<AutofillProfile
*>& profiles
= personal_data_
->GetProfiles();
253 if (submitted_form
->IsAutofillable()) {
254 AutofillMetrics::LogNumberOfProfilesAtAutofillableFormSubmission(
255 personal_data_
->GetProfiles().size());
257 const std::vector
<CreditCard
*>& credit_cards
=
258 personal_data_
->GetCreditCards();
259 if (!profiles
.empty() || !credit_cards
.empty()) {
260 // Copy the profile and credit card data, so that it can be accessed on a
262 std::vector
<AutofillProfile
> copied_profiles
;
263 copied_profiles
.reserve(profiles
.size());
264 for (const AutofillProfile
* profile
: profiles
)
265 copied_profiles
.push_back(*profile
);
267 std::vector
<CreditCard
> copied_credit_cards
;
268 copied_credit_cards
.reserve(credit_cards
.size());
269 for (const CreditCard
* card
: credit_cards
)
270 copied_credit_cards
.push_back(*card
);
272 // Note that ownership of |submitted_form| is passed to the second task,
273 // using |base::Owned|.
274 FormStructure
* raw_submitted_form
= submitted_form
.get();
275 driver_
->GetBlockingPool()->PostTaskAndReply(
277 base::Bind(&DeterminePossibleFieldTypesForUpload
,
282 base::Bind(&AutofillManager::UploadFormDataAsyncCallback
,
283 weak_ptr_factory_
.GetWeakPtr(),
284 base::Owned(submitted_form
.release()),
285 forms_loaded_timestamps_
[form
],
286 initial_interaction_timestamp_
,
293 bool AutofillManager::OnFormSubmitted(const FormData
& form
) {
294 if (!IsValidFormData(form
))
297 // We will always give Autocomplete a chance to save the data.
298 scoped_ptr
<FormStructure
> submitted_form
= ValidateSubmittedForm(form
);
299 if (!submitted_form
) {
303 address_form_event_logger_
->OnFormSubmitted();
304 credit_card_form_event_logger_
->OnFormSubmitted();
306 // Update Personal Data with the form's submitted data.
307 if (submitted_form
->IsAutofillable())
308 ImportFormData(*submitted_form
);
310 recently_unmasked_cards_
.clear();
315 void AutofillManager::OnFormsSeen(const std::vector
<FormData
>& forms
,
316 const TimeTicks
& timestamp
) {
317 if (!IsValidFormDataVector(forms
))
320 if (!driver_
->RendererIsAvailable())
323 bool enabled
= IsAutofillEnabled();
324 if (!has_logged_autofill_enabled_
) {
325 AutofillMetrics::LogIsAutofillEnabledAtPageLoad(enabled
);
326 has_logged_autofill_enabled_
= true;
332 for (size_t i
= 0; i
< forms
.size(); ++i
) {
333 forms_loaded_timestamps_
[forms
[i
]] = timestamp
;
339 void AutofillManager::OnTextFieldDidChange(const FormData
& form
,
340 const FormFieldData
& field
,
341 const TimeTicks
& timestamp
) {
342 if (!IsValidFormData(form
) || !IsValidFormFieldData(field
))
345 FormStructure
* form_structure
= NULL
;
346 AutofillField
* autofill_field
= NULL
;
347 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
350 if (!user_did_type_
) {
351 user_did_type_
= true;
352 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::USER_DID_TYPE
);
355 if (autofill_field
->is_autofilled
) {
356 autofill_field
->is_autofilled
= false;
357 autofill_field
->set_previously_autofilled(true);
358 AutofillMetrics::LogUserHappinessMetric(
359 AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD
);
361 if (!user_did_edit_autofilled_field_
) {
362 user_did_edit_autofilled_field_
= true;
363 AutofillMetrics::LogUserHappinessMetric(
364 AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD_ONCE
);
368 UpdateInitialInteractionTimestamp(timestamp
);
371 void AutofillManager::OnQueryFormFieldAutofill(int query_id
,
372 const FormData
& form
,
373 const FormFieldData
& field
,
374 const gfx::RectF
& bounding_box
) {
375 if (!IsValidFormData(form
) || !IsValidFormFieldData(field
))
378 std::vector
<Suggestion
> suggestions
;
380 external_delegate_
->OnQuery(query_id
, form
, field
, bounding_box
);
382 // Need to refresh models before using the form_event_loggers.
383 bool is_autofill_possible
= RefreshDataModels();
385 FormStructure
* form_structure
= NULL
;
386 AutofillField
* autofill_field
= NULL
;
387 bool got_autofillable_form
=
388 GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
) &&
389 // Don't send suggestions or track forms that aren't auto-fillable.
390 form_structure
->IsAutofillable();
392 // Logging interactions of forms that are autofillable.
393 if (got_autofillable_form
) {
394 if (autofill_field
->Type().group() == CREDIT_CARD
)
395 credit_card_form_event_logger_
->OnDidInteractWithAutofillableForm();
397 address_form_event_logger_
->OnDidInteractWithAutofillableForm();
400 if (is_autofill_possible
&&
401 driver_
->RendererIsAvailable() &&
402 got_autofillable_form
) {
403 AutofillType type
= autofill_field
->Type();
404 bool is_filling_credit_card
= (type
.group() == CREDIT_CARD
);
405 if (is_filling_credit_card
) {
406 suggestions
= GetCreditCardSuggestions(field
, type
);
409 GetProfileSuggestions(*form_structure
, field
, *autofill_field
);
411 if (!suggestions
.empty()) {
412 // Don't provide credit card suggestions for non-secure pages. However,
413 // do provide a warning to the user. This will generate warnings on pages
414 // with mixed content (which includes forms with an http target).
415 if (is_filling_credit_card
&&
416 !client_
->IsContextSecure(form_structure
->source_url())) {
417 Suggestion
warning_suggestion(l10n_util::GetStringUTF16(
418 IDS_AUTOFILL_WARNING_INSECURE_CONNECTION
));
419 warning_suggestion
.frontend_id
= POPUP_ITEM_ID_WARNING_MESSAGE
;
420 suggestions
.assign(1, warning_suggestion
);
422 bool section_is_autofilled
=
423 SectionIsAutofilled(*form_structure
, form
,
424 autofill_field
->section());
425 if (section_is_autofilled
) {
426 // If the relevant section is auto-filled and the renderer is querying
427 // for suggestions, then the user is editing the value of a field.
428 // In this case, mimic autocomplete: don't display labels or icons,
429 // as that information is redundant.
430 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
431 suggestions
[i
].label
= base::string16();
432 suggestions
[i
].icon
= base::string16();
436 // The first time we show suggestions on this page, log the number of
437 // suggestions available.
438 // TODO(mathp): Differentiate between number of suggestions available
439 // (current metric) and number shown to the user.
440 if (!has_logged_address_suggestions_count_
&& !section_is_autofilled
) {
441 AutofillMetrics::LogAddressSuggestionsCount(suggestions
.size());
442 has_logged_address_suggestions_count_
= true;
448 if (field
.should_autocomplete
) {
449 // Add the results from AutoComplete. They come back asynchronously, so we
450 // hand off what we generated and they will send the results back to the
452 autocomplete_history_manager_
->OnGetAutocompleteSuggestions(
453 query_id
, field
.name
, field
.value
, field
.form_control_type
,
456 // Autocomplete is disabled for this field; only pass back Autofill
458 autocomplete_history_manager_
->CancelPendingQuery();
459 external_delegate_
->OnSuggestionsReturned(
460 query_id
, suggestions
);
464 bool AutofillManager::WillFillCreditCardNumber(const FormData
& form
,
465 const FormFieldData
& field
) {
466 FormStructure
* form_structure
= nullptr;
467 AutofillField
* autofill_field
= nullptr;
468 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
471 if (autofill_field
->Type().GetStorableType() == CREDIT_CARD_NUMBER
)
475 // On iOS, we only fill out one field at a time (assuming the new full-form
476 // feature isn't enabled). So we only need to check the current field.
477 if (!AutofillFieldTrialIOS::IsFullFormAutofillEnabled())
481 // If the relevant section is already autofilled, the new fill operation will
482 // only fill |autofill_field|.
483 if (SectionIsAutofilled(*form_structure
, form
, autofill_field
->section()))
486 DCHECK_EQ(form_structure
->field_count(), form
.fields
.size());
487 for (size_t i
= 0; i
< form_structure
->field_count(); ++i
) {
488 if (form_structure
->field(i
)->section() == autofill_field
->section() &&
489 form_structure
->field(i
)->Type().GetStorableType() ==
490 CREDIT_CARD_NUMBER
&&
491 form
.fields
[i
].value
.empty()) {
499 void AutofillManager::FillOrPreviewCreditCardForm(
500 AutofillDriver::RendererFormDataAction action
,
502 const FormData
& form
,
503 const FormFieldData
& field
,
504 const CreditCard
& credit_card
) {
505 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
) {
506 if (credit_card
.record_type() == CreditCard::MASKED_SERVER_CARD
&&
507 WillFillCreditCardNumber(form
, field
)) {
508 unmasking_card_
= credit_card
;
509 unmasking_query_id_
= query_id
;
510 unmasking_form_
= form
;
511 unmasking_field_
= field
;
512 real_pan_client_
.Prepare();
513 client()->ShowUnmaskPrompt(unmasking_card_
,
514 weak_ptr_factory_
.GetWeakPtr());
515 credit_card_form_event_logger_
->OnDidSelectMaskedServerCardSuggestion();
518 credit_card_form_event_logger_
->OnDidFillSuggestion(credit_card
);
521 FillOrPreviewDataModelForm(action
, query_id
, form
, field
, credit_card
,
522 true /* is_credit_card */);
525 void AutofillManager::FillOrPreviewProfileForm(
526 AutofillDriver::RendererFormDataAction action
,
528 const FormData
& form
,
529 const FormFieldData
& field
,
530 const AutofillProfile
& profile
) {
531 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
)
532 address_form_event_logger_
->OnDidFillSuggestion(profile
);
534 FillOrPreviewDataModelForm(action
, query_id
, form
, field
, profile
,
535 false /* is_credit_card */);
538 void AutofillManager::FillOrPreviewForm(
539 AutofillDriver::RendererFormDataAction action
,
541 const FormData
& form
,
542 const FormFieldData
& field
,
544 if (!IsValidFormData(form
) || !IsValidFormFieldData(field
))
547 // NOTE: RefreshDataModels may invalidate |data_model| because it causes the
548 // PersonalDataManager to reload Mac address book entries. Thus it must come
549 // before GetProfile or GetCreditCard.
550 if (!RefreshDataModels() || !driver_
->RendererIsAvailable())
553 const CreditCard
* credit_card
= nullptr;
554 const AutofillProfile
* profile
= nullptr;
555 if (GetCreditCard(unique_id
, &credit_card
))
556 FillOrPreviewCreditCardForm(action
, query_id
, form
, field
, *credit_card
);
557 else if (GetProfile(unique_id
, &profile
))
558 FillOrPreviewProfileForm(action
, query_id
, form
, field
, *profile
);
561 void AutofillManager::FillCreditCardForm(int query_id
,
562 const FormData
& form
,
563 const FormFieldData
& field
,
564 const CreditCard
& credit_card
) {
565 if (!IsValidFormData(form
) || !IsValidFormFieldData(field
) ||
566 !driver_
->RendererIsAvailable()) {
570 FillOrPreviewDataModelForm(AutofillDriver::FORM_DATA_ACTION_FILL
, query_id
,
571 form
, field
, credit_card
, true);
574 void AutofillManager::OnDidPreviewAutofillFormData() {
576 test_delegate_
->DidPreviewFormData();
579 void AutofillManager::OnDidFillAutofillFormData(const TimeTicks
& timestamp
) {
581 test_delegate_
->DidFillFormData();
583 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::USER_DID_AUTOFILL
);
584 if (!user_did_autofill_
) {
585 user_did_autofill_
= true;
586 AutofillMetrics::LogUserHappinessMetric(
587 AutofillMetrics::USER_DID_AUTOFILL_ONCE
);
590 UpdateInitialInteractionTimestamp(timestamp
);
593 void AutofillManager::DidShowSuggestions(bool is_new_popup
,
594 const FormData
& form
,
595 const FormFieldData
& field
) {
597 test_delegate_
->DidShowSuggestions();
598 FormStructure
* form_structure
= NULL
;
599 AutofillField
* autofill_field
= NULL
;
600 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
604 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN
);
606 if (!did_show_suggestions_
) {
607 did_show_suggestions_
= true;
608 AutofillMetrics::LogUserHappinessMetric(
609 AutofillMetrics::SUGGESTIONS_SHOWN_ONCE
);
612 if (autofill_field
->Type().group() == CREDIT_CARD
)
613 credit_card_form_event_logger_
->OnDidShowSuggestions();
615 address_form_event_logger_
->OnDidShowSuggestions();
619 void AutofillManager::OnHidePopup() {
620 if (!IsAutofillEnabled())
623 autocomplete_history_manager_
->CancelPendingQuery();
624 client_
->HideAutofillPopup();
627 bool AutofillManager::GetDeletionConfirmationText(const base::string16
& value
,
629 base::string16
* title
,
630 base::string16
* body
) {
631 if (identifier
== POPUP_ITEM_ID_AUTOCOMPLETE_ENTRY
) {
633 title
->assign(value
);
635 body
->assign(l10n_util::GetStringUTF16(
636 IDS_AUTOFILL_DELETE_AUTOCOMPLETE_SUGGESTION_CONFIRMATION_BODY
));
645 const CreditCard
* credit_card
= nullptr;
646 const AutofillProfile
* profile
= nullptr;
647 if (GetCreditCard(identifier
, &credit_card
)) {
648 if (credit_card
->record_type() != CreditCard::LOCAL_CARD
)
652 title
->assign(credit_card
->TypeAndLastFourDigits());
654 body
->assign(l10n_util::GetStringUTF16(
655 IDS_AUTOFILL_DELETE_CREDIT_CARD_SUGGESTION_CONFIRMATION_BODY
));
659 } else if (GetProfile(identifier
, &profile
)) {
660 if (profile
->record_type() != AutofillProfile::LOCAL_PROFILE
)
664 base::string16 street_address
= profile
->GetRawInfo(ADDRESS_HOME_CITY
);
665 if (!street_address
.empty())
666 title
->swap(street_address
);
668 title
->assign(value
);
671 body
->assign(l10n_util::GetStringUTF16(
672 IDS_AUTOFILL_DELETE_PROFILE_SUGGESTION_CONFIRMATION_BODY
));
682 bool AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id
) {
684 const CreditCard
* credit_card
= nullptr;
685 const AutofillProfile
* profile
= nullptr;
686 if (GetCreditCard(unique_id
, &credit_card
)) {
687 if (credit_card
->record_type() != CreditCard::LOCAL_CARD
)
690 guid
= credit_card
->guid();
691 } else if (GetProfile(unique_id
, &profile
)) {
692 if (profile
->record_type() != AutofillProfile::LOCAL_PROFILE
)
695 guid
= profile
->guid();
701 personal_data_
->RemoveByGUID(guid
);
705 void AutofillManager::RemoveAutocompleteEntry(const base::string16
& name
,
706 const base::string16
& value
) {
707 autocomplete_history_manager_
->OnRemoveAutocompleteEntry(name
, value
);
710 bool AutofillManager::IsShowingUnmaskPrompt() {
711 return unmasking_card_
.Compare(CreditCard()) != 0;
714 const std::vector
<FormStructure
*>& AutofillManager::GetFormStructures() {
715 return form_structures_
.get();
718 void AutofillManager::SetTestDelegate(AutofillManagerTestDelegate
* delegate
) {
719 test_delegate_
= delegate
;
722 void AutofillManager::OnSetDataList(const std::vector
<base::string16
>& values
,
723 const std::vector
<base::string16
>& labels
) {
724 if (!IsValidString16Vector(values
) ||
725 !IsValidString16Vector(labels
) ||
726 values
.size() != labels
.size())
729 external_delegate_
->SetCurrentDataListValues(values
, labels
);
732 void AutofillManager::OnLoadedServerPredictions(
733 const std::string
& response_xml
) {
734 // Parse and store the server predictions.
735 FormStructure::ParseQueryResponse(response_xml
, form_structures_
.get(),
736 client_
->GetRapporService());
738 // Forward form structures to the password generation manager to detect
739 // account creation forms.
740 driver_
->PropagateAutofillPredictions(form_structures_
.get());
742 // If the corresponding flag is set, annotate forms with the predicted types.
743 driver_
->SendAutofillTypePredictionsToRenderer(form_structures_
.get());
746 void AutofillManager::OnUnmaskResponse(const UnmaskResponse
& response
) {
747 unmask_response_
= response
;
748 real_pan_request_timestamp_
= base::Time::Now();
749 real_pan_client_
.UnmaskCard(unmasking_card_
, response
);
752 void AutofillManager::OnUnmaskPromptClosed() {
753 real_pan_client_
.CancelRequest();
754 driver_
->RendererShouldClearPreviewedForm();
755 unmasking_card_
= CreditCard();
756 unmask_response_
= UnmaskResponse();
759 IdentityProvider
* AutofillManager::GetIdentityProvider() {
760 return client()->GetIdentityProvider();
763 void AutofillManager::OnDidGetRealPan(AutofillClient::GetRealPanResult result
,
764 const std::string
& real_pan
) {
765 AutofillMetrics::LogRealPanDuration(
766 base::Time::Now() - real_pan_request_timestamp_
, result
);
767 if (!real_pan
.empty()) {
768 DCHECK_EQ(AutofillClient::SUCCESS
, result
);
769 credit_card_form_event_logger_
->OnDidFillSuggestion(unmasking_card_
);
770 recently_unmasked_cards_
.push_back(unmasking_card_
);
771 unmasking_card_
.set_record_type(CreditCard::FULL_SERVER_CARD
);
772 unmasking_card_
.SetNumber(base::UTF8ToUTF16(real_pan
));
773 if (!unmask_response_
.exp_month
.empty()) {
774 unmasking_card_
.SetRawInfo(CREDIT_CARD_EXP_MONTH
,
775 unmask_response_
.exp_month
);
777 if (!unmask_response_
.exp_year
.empty()) {
778 unmasking_card_
.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR
,
779 unmask_response_
.exp_year
);
781 if (unmask_response_
.should_store_pan
)
782 personal_data_
->UpdateServerCreditCard(unmasking_card_
);
784 FillCreditCardForm(unmasking_query_id_
, unmasking_form_
, unmasking_field_
,
788 client()->OnUnmaskVerificationResult(result
);
791 void AutofillManager::OnDidEndTextFieldEditing() {
792 external_delegate_
->DidEndTextFieldEditing();
795 bool AutofillManager::IsAutofillEnabled() const {
796 return ::autofill::IsAutofillEnabled(client_
->GetPrefs());
799 void AutofillManager::ImportFormData(const FormStructure
& submitted_form
) {
800 scoped_ptr
<CreditCard
> imported_credit_card
;
801 if (!personal_data_
->ImportFormData(submitted_form
, &imported_credit_card
))
804 #ifdef ENABLE_FORM_DEBUG_DUMP
805 // Debug code for research on what autofill Chrome extracts from the last few
806 // forms when submitting credit card data. See DumpAutofillData().
807 bool dump_data
= base::CommandLine::ForCurrentProcess()->HasSwitch(
808 "dump-autofill-data");
810 // Save the form data for future dumping.
812 if (recently_autofilled_forms_
.size() > 5)
813 recently_autofilled_forms_
.erase(recently_autofilled_forms_
.begin());
815 recently_autofilled_forms_
.push_back(
816 std::map
<std::string
, base::string16
>());
817 auto& map
= recently_autofilled_forms_
.back();
818 for (const auto& field
: submitted_form
) {
819 AutofillType type
= field
->Type();
820 // Even though this is for development only, mask full credit card #'s.
821 if (type
.GetStorableType() == CREDIT_CARD_NUMBER
&&
822 field
->value
.size() > 4) {
823 map
[type
.ToString()] = base::ASCIIToUTF16("...(omitted)...") +
824 field
->value
.substr(field
->value
.size() - 4, 4);
826 map
[type
.ToString()] = field
->value
;
830 DumpAutofillData(imported_credit_card
);
832 #endif // ENABLE_FORM_DEBUG_DUMP
834 // If credit card information was submitted, we need to confirm whether to
836 if (imported_credit_card
) {
837 // Don't offer to save any cards that were recently unmasked.
838 for (const CreditCard
& unmasked_card
: recently_unmasked_cards_
) {
839 if (unmasked_card
.TypeAndLastFourDigits() ==
840 imported_credit_card
->TypeAndLastFourDigits())
843 client_
->ConfirmSaveCreditCard(
845 base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard
),
846 base::Unretained(personal_data_
),
847 *imported_credit_card
));
851 // Note that |submitted_form| is passed as a pointer rather than as a reference
852 // so that we can get memory management right across threads. Note also that we
853 // explicitly pass in all the time stamps of interest, as the cached ones might
854 // get reset before this method executes.
855 void AutofillManager::UploadFormDataAsyncCallback(
856 const FormStructure
* submitted_form
,
857 const TimeTicks
& load_time
,
858 const TimeTicks
& interaction_time
,
859 const TimeTicks
& submission_time
) {
860 submitted_form
->LogQualityMetrics(load_time
, interaction_time
,
862 client_
->GetRapporService());
864 if (submitted_form
->ShouldBeCrowdsourced())
865 UploadFormData(*submitted_form
);
868 void AutofillManager::UploadFormData(const FormStructure
& submitted_form
) {
869 if (!download_manager_
)
872 // Check if the form is among the forms that were recently auto-filled.
873 bool was_autofilled
= false;
874 std::string form_signature
= submitted_form
.FormSignature();
875 for (const std::string
& cur_sig
: autofilled_form_signatures_
) {
876 if (cur_sig
== form_signature
) {
877 was_autofilled
= true;
882 ServerFieldTypeSet non_empty_types
;
883 personal_data_
->GetNonEmptyTypes(&non_empty_types
);
885 download_manager_
->StartUploadRequest(
886 submitted_form
, was_autofilled
, non_empty_types
,
887 std::string() /* login_form_signature */);
890 bool AutofillManager::UploadPasswordForm(
891 const FormData
& form
,
892 const base::string16
& username_field
,
893 const ServerFieldType
& password_type
,
894 const std::string
& login_form_signature
) {
895 FormStructure
form_structure(form
);
897 if (!ShouldUploadForm(form_structure
))
900 if (!form_structure
.ShouldBeCrowdsourced())
903 // Find the first password field to label. If the provided username field name
904 // is not empty, then also find the first field with that name to label.
905 // We don't try to label anything else.
906 bool found_password_field
= false;
907 bool found_username_field
= username_field
.empty();
908 for (size_t i
= 0; i
< form_structure
.field_count(); ++i
) {
909 AutofillField
* field
= form_structure
.field(i
);
911 ServerFieldTypeSet types
;
912 if (!found_password_field
&& field
->form_control_type
== "password") {
913 types
.insert(password_type
);
914 found_password_field
= true;
915 } else if (!found_username_field
&& field
->name
== username_field
) {
916 types
.insert(USERNAME
);
917 found_username_field
= true;
919 types
.insert(UNKNOWN_TYPE
);
921 field
->set_possible_types(types
);
923 DCHECK(found_password_field
);
925 // Only the USERNAME type and one password field type should be present.
926 ServerFieldTypeSet available_field_types
;
927 available_field_types
.insert(password_type
);
928 available_field_types
.insert(USERNAME
);
930 // Force uploading as these events are relatively rare and we want to make
931 // sure to receive them. It also makes testing easier if these requests
933 form_structure
.set_upload_required(UPLOAD_REQUIRED
);
935 if (!download_manager_
)
938 return download_manager_
->StartUploadRequest(
939 form_structure
, false /* was_autofilled */, available_field_types
,
940 login_form_signature
);
943 void AutofillManager::Reset() {
944 form_structures_
.clear();
945 address_form_event_logger_
.reset(
946 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */));
947 credit_card_form_event_logger_
.reset(
948 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */));
949 has_logged_autofill_enabled_
= false;
950 has_logged_address_suggestions_count_
= false;
951 did_show_suggestions_
= false;
952 user_did_type_
= false;
953 user_did_autofill_
= false;
954 user_did_edit_autofilled_field_
= false;
955 unmasking_card_
= CreditCard();
956 unmasking_query_id_
= -1;
957 unmasking_form_
= FormData();
958 unmasking_field_
= FormFieldData();
959 forms_loaded_timestamps_
.clear();
960 initial_interaction_timestamp_
= TimeTicks();
961 external_delegate_
->Reset();
964 AutofillManager::AutofillManager(AutofillDriver
* driver
,
965 AutofillClient
* client
,
966 PersonalDataManager
* personal_data
)
969 real_pan_client_(driver
->GetURLRequestContext(), this),
970 app_locale_("en-US"),
971 personal_data_(personal_data
),
972 autocomplete_history_manager_(
973 new AutocompleteHistoryManager(driver
, client
)),
974 address_form_event_logger_(
975 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */)),
976 credit_card_form_event_logger_(
977 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */)),
978 has_logged_autofill_enabled_(false),
979 has_logged_address_suggestions_count_(false),
980 did_show_suggestions_(false),
981 user_did_type_(false),
982 user_did_autofill_(false),
983 user_did_edit_autofilled_field_(false),
984 unmasking_query_id_(-1),
985 external_delegate_(NULL
),
986 test_delegate_(NULL
),
987 weak_ptr_factory_(this) {
992 bool AutofillManager::RefreshDataModels() {
993 if (!IsAutofillEnabled())
996 // No autofill data to return if the profiles are empty.
997 const std::vector
<AutofillProfile
*>& profiles
=
998 personal_data_
->GetProfiles();
999 const std::vector
<CreditCard
*>& credit_cards
=
1000 personal_data_
->GetCreditCards();
1002 // Updating the FormEventLoggers for addresses and credit cards.
1004 bool is_server_data_available
= false;
1005 bool is_local_data_available
= false;
1006 for (CreditCard
* credit_card
: credit_cards
) {
1007 if (credit_card
->record_type() == CreditCard::LOCAL_CARD
)
1008 is_local_data_available
= true;
1010 is_server_data_available
= true;
1012 credit_card_form_event_logger_
->set_is_server_data_available(
1013 is_server_data_available
);
1014 credit_card_form_event_logger_
->set_is_local_data_available(
1015 is_local_data_available
);
1018 bool is_server_data_available
= false;
1019 bool is_local_data_available
= false;
1020 for (AutofillProfile
* profile
: profiles
) {
1021 if (profile
->record_type() == AutofillProfile::LOCAL_PROFILE
)
1022 is_local_data_available
= true;
1023 else if (profile
->record_type() == AutofillProfile::SERVER_PROFILE
)
1024 is_server_data_available
= true;
1026 address_form_event_logger_
->set_is_server_data_available(
1027 is_server_data_available
);
1028 address_form_event_logger_
->set_is_local_data_available(
1029 is_local_data_available
);
1032 if (profiles
.empty() && credit_cards
.empty())
1038 bool AutofillManager::IsCreditCard(int unique_id
) {
1039 // Unpack the |unique_id| into component parts.
1040 std::string credit_card_id
;
1041 std::string profile_id
;
1042 SplitFrontendID(unique_id
, &credit_card_id
, &profile_id
);
1043 DCHECK(!base::IsValidGUID(credit_card_id
) || !base::IsValidGUID(profile_id
));
1044 return base::IsValidGUID(credit_card_id
);
1047 bool AutofillManager::GetProfile(int unique_id
,
1048 const AutofillProfile
** profile
) {
1049 // Unpack the |unique_id| into component parts.
1050 std::string credit_card_id
;
1051 std::string profile_id
;
1052 SplitFrontendID(unique_id
, &credit_card_id
, &profile_id
);
1054 if (base::IsValidGUID(profile_id
))
1055 *profile
= personal_data_
->GetProfileByGUID(profile_id
);
1059 bool AutofillManager::GetCreditCard(int unique_id
,
1060 const CreditCard
** credit_card
) {
1061 // Unpack the |unique_id| into component parts.
1062 std::string credit_card_id
;
1063 std::string profile_id
;
1064 SplitFrontendID(unique_id
, &credit_card_id
, &profile_id
);
1065 *credit_card
= NULL
;
1066 if (base::IsValidGUID(credit_card_id
))
1067 *credit_card
= personal_data_
->GetCreditCardByGUID(credit_card_id
);
1068 return !!*credit_card
;
1071 void AutofillManager::FillOrPreviewDataModelForm(
1072 AutofillDriver::RendererFormDataAction action
,
1074 const FormData
& form
,
1075 const FormFieldData
& field
,
1076 const AutofillDataModel
& data_model
,
1077 bool is_credit_card
) {
1078 FormStructure
* form_structure
= NULL
;
1079 AutofillField
* autofill_field
= NULL
;
1080 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
1083 DCHECK(form_structure
);
1084 DCHECK(autofill_field
);
1086 FormData result
= form
;
1088 base::string16 profile_full_name
;
1089 std::string profile_language_code
;
1090 if (!is_credit_card
) {
1091 profile_full_name
= data_model
.GetInfo(
1092 AutofillType(NAME_FULL
), app_locale_
);
1093 profile_language_code
=
1094 static_cast<const AutofillProfile
*>(&data_model
)->language_code();
1097 // If the relevant section is auto-filled, we should fill |field| but not the
1098 // rest of the form.
1099 if (SectionIsAutofilled(*form_structure
, form
, autofill_field
->section())) {
1100 for (std::vector
<FormFieldData
>::iterator iter
= result
.fields
.begin();
1101 iter
!= result
.fields
.end(); ++iter
) {
1102 if (iter
->SameFieldAs(field
)) {
1103 base::string16 value
=
1104 data_model
.GetInfo(autofill_field
->Type(), app_locale_
);
1105 if (AutofillField::FillFormField(*autofill_field
,
1107 profile_language_code
,
1110 // Mark the cached field as autofilled, so that we can detect when a
1111 // user edits an autofilled field (for metrics).
1112 autofill_field
->is_autofilled
= true;
1114 // Mark the field as autofilled when a non-empty value is assigned to
1115 // it. This allows the renderer to distinguish autofilled fields from
1116 // fields with non-empty values, such as select-one fields.
1117 iter
->is_autofilled
= true;
1119 if (!is_credit_card
&& !value
.empty())
1120 client_
->DidFillOrPreviewField(value
, profile_full_name
);
1126 // Note that this may invalidate |data_model|, particularly if it is a Mac
1127 // address book entry.
1128 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
)
1129 personal_data_
->RecordUseOf(data_model
);
1131 driver_
->SendFormDataToRenderer(query_id
, action
, result
);
1135 DCHECK_EQ(form_structure
->field_count(), form
.fields
.size());
1136 for (size_t i
= 0; i
< form_structure
->field_count(); ++i
) {
1137 if (form_structure
->field(i
)->section() != autofill_field
->section())
1140 DCHECK(form_structure
->field(i
)->SameFieldAs(result
.fields
[i
]));
1142 const AutofillField
* cached_field
= form_structure
->field(i
);
1143 FieldTypeGroup field_group_type
= cached_field
->Type().group();
1145 if (field_group_type
== NO_GROUP
)
1148 base::string16 value
=
1149 data_model
.GetInfo(cached_field
->Type(), app_locale_
);
1150 if (is_credit_card
&&
1151 cached_field
->Type().GetStorableType() ==
1152 CREDIT_CARD_VERIFICATION_CODE
) {
1153 // If this is |unmasking_card_|, |unmask_response_.cvc| should be
1154 // non-empty and vice versa.
1155 value
= unmask_response_
.cvc
;
1156 DCHECK_EQ(&unmasking_card_
== &data_model
, !value
.empty());
1159 // Must match ForEachMatchingFormField() in form_autofill_util.cc.
1160 // Only notify autofilling of empty fields and the field that initiated
1161 // the filling (note that "select-one" controls may not be empty but will
1162 // still be autofilled).
1163 bool should_notify
=
1166 (result
.fields
[i
].SameFieldAs(field
) ||
1167 result
.fields
[i
].form_control_type
== "select-one" ||
1168 result
.fields
[i
].value
.empty());
1169 if (AutofillField::FillFormField(*cached_field
,
1171 profile_language_code
,
1173 &result
.fields
[i
])) {
1174 // Mark the cached field as autofilled, so that we can detect when a
1175 // user edits an autofilled field (for metrics).
1176 form_structure
->field(i
)->is_autofilled
= true;
1178 // Mark the field as autofilled when a non-empty value is assigned to
1179 // it. This allows the renderer to distinguish autofilled fields from
1180 // fields with non-empty values, such as select-one fields.
1181 result
.fields
[i
].is_autofilled
= true;
1184 client_
->DidFillOrPreviewField(value
, profile_full_name
);
1188 autofilled_form_signatures_
.push_front(form_structure
->FormSignature());
1189 // Only remember the last few forms that we've seen, both to avoid false
1190 // positives and to avoid wasting memory.
1191 if (autofilled_form_signatures_
.size() > kMaxRecentFormSignaturesToRemember
)
1192 autofilled_form_signatures_
.pop_back();
1194 // Note that this may invalidate |data_model|, particularly if it is a Mac
1195 // address book entry.
1196 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
)
1197 personal_data_
->RecordUseOf(data_model
);
1199 driver_
->SendFormDataToRenderer(query_id
, action
, result
);
1202 scoped_ptr
<FormStructure
> AutofillManager::ValidateSubmittedForm(
1203 const FormData
& form
) {
1204 scoped_ptr
<FormStructure
> submitted_form(new FormStructure(form
));
1205 if (!ShouldUploadForm(*submitted_form
))
1206 return scoped_ptr
<FormStructure
>();
1208 // Ignore forms not present in our cache. These are typically forms with
1209 // wonky JavaScript that also makes them not auto-fillable.
1210 FormStructure
* cached_submitted_form
;
1211 if (!FindCachedForm(form
, &cached_submitted_form
))
1212 return scoped_ptr
<FormStructure
>();
1214 submitted_form
->UpdateFromCache(*cached_submitted_form
);
1215 return submitted_form
.Pass();
1218 bool AutofillManager::FindCachedForm(const FormData
& form
,
1219 FormStructure
** form_structure
) const {
1220 // Find the FormStructure that corresponds to |form|.
1221 // Scan backward through the cached |form_structures_|, as updated versions of
1222 // forms are added to the back of the list, whereas original versions of these
1223 // forms might appear toward the beginning of the list. The communication
1224 // protocol with the crowdsourcing server does not permit us to discard the
1225 // original versions of the forms.
1226 *form_structure
= NULL
;
1227 for (FormStructure
* cur_form
: base::Reversed(form_structures_
)) {
1228 if (*cur_form
== form
) {
1229 *form_structure
= cur_form
;
1231 // The same form might be cached with multiple field counts: in some
1232 // cases, non-autofillable fields are filtered out, whereas in other cases
1233 // they are not. To avoid thrashing the cache, keep scanning until we
1234 // find a cached version with the same number of fields, if there is one.
1235 if (cur_form
->field_count() == form
.fields
.size())
1240 if (!(*form_structure
))
1246 bool AutofillManager::GetCachedFormAndField(const FormData
& form
,
1247 const FormFieldData
& field
,
1248 FormStructure
** form_structure
,
1249 AutofillField
** autofill_field
) {
1250 // Find the FormStructure that corresponds to |form|.
1251 // If we do not have this form in our cache but it is parseable, we'll add it
1252 // in the call to |UpdateCachedForm()|.
1253 if (!FindCachedForm(form
, form_structure
) &&
1254 !FormStructure(form
).ShouldBeParsed()) {
1258 // Update the cached form to reflect any dynamic changes to the form data, if
1260 if (!UpdateCachedForm(form
, *form_structure
, form_structure
))
1263 // No data to return if there are no auto-fillable fields.
1264 if (!(*form_structure
)->autofill_count())
1267 // Find the AutofillField that corresponds to |field|.
1268 *autofill_field
= NULL
;
1269 for (AutofillField
* current
: **form_structure
) {
1270 if (current
->SameFieldAs(field
)) {
1271 *autofill_field
= current
;
1276 // Even though we always update the cache, the field might not exist if the
1277 // website disables autocomplete while the user is interacting with the form.
1278 // See http://crbug.com/160476
1279 return *autofill_field
!= NULL
;
1282 AutofillField
* AutofillManager::GetAutofillField(const FormData
& form
,
1283 const FormFieldData
& field
) {
1284 if (!personal_data_
)
1287 FormStructure
* form_structure
= NULL
;
1288 AutofillField
* autofill_field
= NULL
;
1289 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
1292 if (!form_structure
->IsAutofillable())
1295 return autofill_field
;
1298 bool AutofillManager::UpdateCachedForm(const FormData
& live_form
,
1299 const FormStructure
* cached_form
,
1300 FormStructure
** updated_form
) {
1303 live_form
.fields
.size() != cached_form
->field_count());
1304 for (size_t i
= 0; !needs_update
&& i
< cached_form
->field_count(); ++i
)
1305 needs_update
= !cached_form
->field(i
)->SameFieldAs(live_form
.fields
[i
]);
1310 if (form_structures_
.size() >= kMaxFormCacheSize
)
1313 // Add the new or updated form to our cache.
1314 form_structures_
.push_back(new FormStructure(live_form
));
1315 *updated_form
= *form_structures_
.rbegin();
1316 (*updated_form
)->DetermineHeuristicTypes();
1318 // If we have cached data, propagate it to the updated form.
1320 std::map
<base::string16
, const AutofillField
*> cached_fields
;
1321 for (size_t i
= 0; i
< cached_form
->field_count(); ++i
) {
1322 const AutofillField
* field
= cached_form
->field(i
);
1323 cached_fields
[field
->unique_name()] = field
;
1326 for (size_t i
= 0; i
< (*updated_form
)->field_count(); ++i
) {
1327 AutofillField
* field
= (*updated_form
)->field(i
);
1328 auto cached_field
= cached_fields
.find(field
->unique_name());
1329 if (cached_field
!= cached_fields
.end()) {
1330 field
->set_server_type(cached_field
->second
->server_type());
1331 field
->is_autofilled
= cached_field
->second
->is_autofilled
;
1332 field
->set_previously_autofilled(
1333 cached_field
->second
->previously_autofilled());
1337 // Note: We _must not_ remove the original version of the cached form from
1338 // the list of |form_structures_|. Otherwise, we break parsing of the
1339 // crowdsourcing server's response to our query.
1342 // Annotate the updated form with its predicted types.
1343 std::vector
<FormStructure
*> forms(1, *updated_form
);
1344 driver_
->SendAutofillTypePredictionsToRenderer(forms
);
1349 std::vector
<Suggestion
> AutofillManager::GetProfileSuggestions(
1350 const FormStructure
& form
,
1351 const FormFieldData
& field
,
1352 const AutofillField
& autofill_field
) const {
1353 std::vector
<ServerFieldType
> field_types(form
.field_count());
1354 for (size_t i
= 0; i
< form
.field_count(); ++i
) {
1355 field_types
.push_back(form
.field(i
)->Type().GetStorableType());
1358 std::vector
<Suggestion
> suggestions
= personal_data_
->GetProfileSuggestions(
1359 autofill_field
.Type(), field
.value
, field
.is_autofilled
, field_types
);
1361 // Adjust phone number to display in prefix/suffix case.
1362 if (autofill_field
.Type().GetStorableType() == PHONE_HOME_NUMBER
) {
1363 for (size_t i
= 0; i
< suggestions
.size(); ++i
) {
1364 suggestions
[i
].value
= AutofillField::GetPhoneNumberValue(
1365 autofill_field
, suggestions
[i
].value
, field
);
1369 for (size_t i
= 0; i
< suggestions
.size(); ++i
) {
1370 suggestions
[i
].frontend_id
=
1371 MakeFrontendID(std::string(), suggestions
[i
].backend_id
);
1376 std::vector
<Suggestion
> AutofillManager::GetCreditCardSuggestions(
1377 const FormFieldData
& field
,
1378 const AutofillType
& type
) const {
1379 std::vector
<Suggestion
> suggestions
=
1380 personal_data_
->GetCreditCardSuggestions(type
, field
.value
);
1381 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
1382 suggestions
[i
].frontend_id
=
1383 MakeFrontendID(suggestions
[i
].backend_id
, std::string());
1388 void AutofillManager::ParseForms(const std::vector
<FormData
>& forms
) {
1389 std::vector
<FormStructure
*> non_queryable_forms
;
1390 for (const FormData
& form
: forms
) {
1391 scoped_ptr
<FormStructure
> form_structure(new FormStructure(form
));
1393 if (!form_structure
->ShouldBeParsed()) {
1394 if (form_structure
->has_password_field()) {
1395 AutofillMetrics::LogPasswordFormQueryVolume(
1396 AutofillMetrics::NEW_PASSWORD_QUERY
);
1401 form_structure
->DetermineHeuristicTypes();
1403 if (form_structure
->ShouldBeCrowdsourced()) {
1404 AutofillMetrics::LogPasswordFormQueryVolume(
1405 AutofillMetrics::CURRENT_QUERY
);
1406 form_structures_
.push_back(form_structure
.release());
1408 non_queryable_forms
.push_back(form_structure
.release());
1411 if (!form_structures_
.empty() && download_manager_
) {
1412 // Query the server if at least one of the forms was parsed.
1413 download_manager_
->StartQueryRequest(form_structures_
.get());
1416 for (FormStructure
* structure
: non_queryable_forms
)
1417 form_structures_
.push_back(structure
);
1419 if (!form_structures_
.empty()) {
1420 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED
);
1422 // Log this from same location as AutofillMetrics::FORMS_LOADED to ensure
1423 // that KeyboardAccessoryButtonsIOS and UserHappiness UMA metrics will be
1424 // directly comparable.
1425 KeyboardAccessoryMetricsLogger::OnFormsLoaded();
1429 // For the |non_queryable_forms|, we have all the field type info we're ever
1430 // going to get about them. For the other forms, we'll wait until we get a
1431 // response from the server.
1432 driver_
->SendAutofillTypePredictionsToRenderer(non_queryable_forms
);
1435 int AutofillManager::BackendIDToInt(const std::string
& backend_id
) const {
1436 if (!base::IsValidGUID(backend_id
))
1439 const auto found
= backend_to_int_map_
.find(backend_id
);
1440 if (found
== backend_to_int_map_
.end()) {
1441 // Unknown one, make a new entry.
1442 int int_id
= backend_to_int_map_
.size() + 1;
1443 backend_to_int_map_
[backend_id
] = int_id
;
1444 int_to_backend_map_
[int_id
] = backend_id
;
1447 return found
->second
;
1450 std::string
AutofillManager::IntToBackendID(int int_id
) const {
1452 return std::string();
1454 const auto found
= int_to_backend_map_
.find(int_id
);
1455 if (found
== int_to_backend_map_
.end()) {
1457 return std::string();
1459 return found
->second
;
1462 // When sending IDs (across processes) to the renderer we pack credit card and
1463 // profile IDs into a single integer. Credit card IDs are sent in the high
1464 // word and profile IDs are sent in the low word.
1465 int AutofillManager::MakeFrontendID(
1466 const std::string
& cc_backend_id
,
1467 const std::string
& profile_backend_id
) const {
1468 int cc_int_id
= BackendIDToInt(cc_backend_id
);
1469 int profile_int_id
= BackendIDToInt(profile_backend_id
);
1471 // Should fit in signed 16-bit integers. We use 16-bits each when combining
1472 // below, and negative frontend IDs have special meaning so we can never use
1474 DCHECK(cc_int_id
<= std::numeric_limits
<int16_t>::max());
1475 DCHECK(profile_int_id
<= std::numeric_limits
<int16_t>::max());
1477 // Put CC in the high half of the bits.
1478 return (cc_int_id
<< std::numeric_limits
<uint16_t>::digits
) | profile_int_id
;
1481 // When receiving IDs (across processes) from the renderer we unpack credit card
1482 // and profile IDs from a single integer. Credit card IDs are stored in the
1483 // high word and profile IDs are stored in the low word.
1484 void AutofillManager::SplitFrontendID(int frontend_id
,
1485 std::string
* cc_backend_id
,
1486 std::string
* profile_backend_id
) const {
1487 int cc_int_id
= (frontend_id
>> std::numeric_limits
<uint16_t>::digits
) &
1488 std::numeric_limits
<uint16_t>::max();
1489 int profile_int_id
= frontend_id
& std::numeric_limits
<uint16_t>::max();
1491 *cc_backend_id
= IntToBackendID(cc_int_id
);
1492 *profile_backend_id
= IntToBackendID(profile_int_id
);
1495 void AutofillManager::UpdateInitialInteractionTimestamp(
1496 const TimeTicks
& interaction_timestamp
) {
1497 if (initial_interaction_timestamp_
.is_null() ||
1498 interaction_timestamp
< initial_interaction_timestamp_
) {
1499 initial_interaction_timestamp_
= interaction_timestamp
;
1503 bool AutofillManager::ShouldUploadForm(const FormStructure
& form
) {
1504 if (!IsAutofillEnabled())
1507 if (driver_
->IsOffTheRecord())
1510 // Disregard forms that we wouldn't ever autofill in the first place.
1511 if (!form
.ShouldBeParsed())
1517 #ifdef ENABLE_FORM_DEBUG_DUMP
1518 void AutofillManager::DumpAutofillData(bool imported_cc
) const {
1519 base::ThreadRestrictions::ScopedAllowIO allow_id
;
1521 // This code dumps the last few forms seen on the current tab to a file on
1522 // the desktop. This is only enabled when a specific command line flag is
1523 // passed for manual analysis of the address context information available
1524 // when offering to save credit cards in a checkout session. This is to
1525 // help developers experimenting with better card saving features.
1526 base::FilePath path
;
1527 if (!PathService::Get(base::DIR_USER_DESKTOP
, &path
))
1529 path
= path
.Append(FILE_PATH_LITERAL("autofill_debug_dump.txt"));
1530 FILE* file
= base::OpenFile(path
, "a");
1534 fputs("------------------------------------------------------\n", file
);
1536 fputs("Got a new credit card on CC form:\n", file
);
1538 fputs("Submitted form:\n", file
);
1539 for (int i
= static_cast<int>(recently_autofilled_forms_
.size()) - 1;
1541 for (const auto& pair
: recently_autofilled_forms_
[i
]) {
1543 fputs(pair
.first
.c_str(), file
);
1545 fputs(base::UTF16ToUTF8(pair
.second
).c_str(), file
);
1549 fputs("Next oldest form:\n", file
);
1555 #endif // ENABLE_FORM_DEBUG_DUMP
1557 } // namespace autofill