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 switches::kEnableCreditCardScan
) &&
203 (base::FieldTrialList::FindFullName("CreditCardScan") != "Enabled" ||
204 base::CommandLine::ForCurrentProcess()->HasSwitch(
205 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. Moreover, filter out duplicate
431 std::set
<base::string16
> seen_values
;
432 for (auto iter
= suggestions
.begin(); iter
!= suggestions
.end();) {
433 if (!seen_values
.insert(iter
->value
).second
) {
434 // If we've seen this suggestion value before, remove it.
435 iter
= suggestions
.erase(iter
);
444 // The first time we show suggestions on this page, log the number of
445 // suggestions available.
446 // TODO(mathp): Differentiate between number of suggestions available
447 // (current metric) and number shown to the user.
448 if (!has_logged_address_suggestions_count_
&& !section_is_autofilled
) {
449 AutofillMetrics::LogAddressSuggestionsCount(suggestions
.size());
450 has_logged_address_suggestions_count_
= true;
456 if (field
.should_autocomplete
) {
457 // Add the results from AutoComplete. They come back asynchronously, so we
458 // hand off what we generated and they will send the results back to the
460 autocomplete_history_manager_
->OnGetAutocompleteSuggestions(
461 query_id
, field
.name
, field
.value
, field
.form_control_type
,
464 // Autocomplete is disabled for this field; only pass back Autofill
466 autocomplete_history_manager_
->CancelPendingQuery();
467 external_delegate_
->OnSuggestionsReturned(
468 query_id
, suggestions
);
472 bool AutofillManager::WillFillCreditCardNumber(const FormData
& form
,
473 const FormFieldData
& field
) {
474 FormStructure
* form_structure
= nullptr;
475 AutofillField
* autofill_field
= nullptr;
476 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
479 if (autofill_field
->Type().GetStorableType() == CREDIT_CARD_NUMBER
)
483 // On iOS, we only fill out one field at a time (assuming the new full-form
484 // feature isn't enabled). So we only need to check the current field.
485 if (!AutofillFieldTrialIOS::IsFullFormAutofillEnabled())
489 // If the relevant section is already autofilled, the new fill operation will
490 // only fill |autofill_field|.
491 if (SectionIsAutofilled(*form_structure
, form
, autofill_field
->section()))
494 DCHECK_EQ(form_structure
->field_count(), form
.fields
.size());
495 for (size_t i
= 0; i
< form_structure
->field_count(); ++i
) {
496 if (form_structure
->field(i
)->section() == autofill_field
->section() &&
497 form_structure
->field(i
)->Type().GetStorableType() ==
498 CREDIT_CARD_NUMBER
&&
499 form
.fields
[i
].value
.empty()) {
507 void AutofillManager::FillOrPreviewCreditCardForm(
508 AutofillDriver::RendererFormDataAction action
,
510 const FormData
& form
,
511 const FormFieldData
& field
,
512 const CreditCard
& credit_card
) {
513 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
) {
514 if (credit_card
.record_type() == CreditCard::MASKED_SERVER_CARD
&&
515 WillFillCreditCardNumber(form
, field
)) {
516 unmasking_card_
= credit_card
;
517 unmasking_query_id_
= query_id
;
518 unmasking_form_
= form
;
519 unmasking_field_
= field
;
520 real_pan_client_
.Prepare();
521 client()->ShowUnmaskPrompt(unmasking_card_
,
522 weak_ptr_factory_
.GetWeakPtr());
523 credit_card_form_event_logger_
->OnDidSelectMaskedServerCardSuggestion();
526 credit_card_form_event_logger_
->OnDidFillSuggestion(credit_card
);
529 FillOrPreviewDataModelForm(action
, query_id
, form
, field
, credit_card
,
530 true /* is_credit_card */);
533 void AutofillManager::FillOrPreviewProfileForm(
534 AutofillDriver::RendererFormDataAction action
,
536 const FormData
& form
,
537 const FormFieldData
& field
,
538 const AutofillProfile
& profile
) {
539 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
)
540 address_form_event_logger_
->OnDidFillSuggestion(profile
);
542 FillOrPreviewDataModelForm(action
, query_id
, form
, field
, profile
,
543 false /* is_credit_card */);
546 void AutofillManager::FillOrPreviewForm(
547 AutofillDriver::RendererFormDataAction action
,
549 const FormData
& form
,
550 const FormFieldData
& field
,
552 if (!IsValidFormData(form
) || !IsValidFormFieldData(field
))
555 // NOTE: RefreshDataModels may invalidate |data_model| because it causes the
556 // PersonalDataManager to reload Mac address book entries. Thus it must come
557 // before GetProfile or GetCreditCard.
558 if (!RefreshDataModels() || !driver_
->RendererIsAvailable())
561 const CreditCard
* credit_card
= nullptr;
562 const AutofillProfile
* profile
= nullptr;
563 if (GetCreditCard(unique_id
, &credit_card
))
564 FillOrPreviewCreditCardForm(action
, query_id
, form
, field
, *credit_card
);
565 else if (GetProfile(unique_id
, &profile
))
566 FillOrPreviewProfileForm(action
, query_id
, form
, field
, *profile
);
569 void AutofillManager::FillCreditCardForm(int query_id
,
570 const FormData
& form
,
571 const FormFieldData
& field
,
572 const CreditCard
& credit_card
) {
573 if (!IsValidFormData(form
) || !IsValidFormFieldData(field
) ||
574 !driver_
->RendererIsAvailable()) {
578 FillOrPreviewDataModelForm(AutofillDriver::FORM_DATA_ACTION_FILL
, query_id
,
579 form
, field
, credit_card
, true);
582 void AutofillManager::OnDidPreviewAutofillFormData() {
584 test_delegate_
->DidPreviewFormData();
587 void AutofillManager::OnDidFillAutofillFormData(const TimeTicks
& timestamp
) {
589 test_delegate_
->DidFillFormData();
591 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::USER_DID_AUTOFILL
);
592 if (!user_did_autofill_
) {
593 user_did_autofill_
= true;
594 AutofillMetrics::LogUserHappinessMetric(
595 AutofillMetrics::USER_DID_AUTOFILL_ONCE
);
598 UpdateInitialInteractionTimestamp(timestamp
);
601 void AutofillManager::DidShowSuggestions(bool is_new_popup
,
602 const FormData
& form
,
603 const FormFieldData
& field
) {
605 test_delegate_
->DidShowSuggestions();
606 FormStructure
* form_structure
= NULL
;
607 AutofillField
* autofill_field
= NULL
;
608 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
612 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN
);
614 if (!did_show_suggestions_
) {
615 did_show_suggestions_
= true;
616 AutofillMetrics::LogUserHappinessMetric(
617 AutofillMetrics::SUGGESTIONS_SHOWN_ONCE
);
620 if (autofill_field
->Type().group() == CREDIT_CARD
)
621 credit_card_form_event_logger_
->OnDidShowSuggestions();
623 address_form_event_logger_
->OnDidShowSuggestions();
627 void AutofillManager::OnHidePopup() {
628 if (!IsAutofillEnabled())
631 autocomplete_history_manager_
->CancelPendingQuery();
632 client_
->HideAutofillPopup();
635 bool AutofillManager::GetDeletionConfirmationText(const base::string16
& value
,
637 base::string16
* title
,
638 base::string16
* body
) {
639 if (identifier
== POPUP_ITEM_ID_AUTOCOMPLETE_ENTRY
) {
641 title
->assign(value
);
643 body
->assign(l10n_util::GetStringUTF16(
644 IDS_AUTOFILL_DELETE_AUTOCOMPLETE_SUGGESTION_CONFIRMATION_BODY
));
653 const CreditCard
* credit_card
= nullptr;
654 const AutofillProfile
* profile
= nullptr;
655 if (GetCreditCard(identifier
, &credit_card
)) {
656 if (credit_card
->record_type() != CreditCard::LOCAL_CARD
)
660 title
->assign(credit_card
->TypeAndLastFourDigits());
662 body
->assign(l10n_util::GetStringUTF16(
663 IDS_AUTOFILL_DELETE_CREDIT_CARD_SUGGESTION_CONFIRMATION_BODY
));
667 } else if (GetProfile(identifier
, &profile
)) {
668 if (profile
->record_type() != AutofillProfile::LOCAL_PROFILE
)
672 base::string16 street_address
= profile
->GetRawInfo(ADDRESS_HOME_CITY
);
673 if (!street_address
.empty())
674 title
->swap(street_address
);
676 title
->assign(value
);
679 body
->assign(l10n_util::GetStringUTF16(
680 IDS_AUTOFILL_DELETE_PROFILE_SUGGESTION_CONFIRMATION_BODY
));
690 bool AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id
) {
692 const CreditCard
* credit_card
= nullptr;
693 const AutofillProfile
* profile
= nullptr;
694 if (GetCreditCard(unique_id
, &credit_card
)) {
695 if (credit_card
->record_type() != CreditCard::LOCAL_CARD
)
698 guid
= credit_card
->guid();
699 } else if (GetProfile(unique_id
, &profile
)) {
700 if (profile
->record_type() != AutofillProfile::LOCAL_PROFILE
)
703 guid
= profile
->guid();
709 personal_data_
->RemoveByGUID(guid
);
713 void AutofillManager::RemoveAutocompleteEntry(const base::string16
& name
,
714 const base::string16
& value
) {
715 autocomplete_history_manager_
->OnRemoveAutocompleteEntry(name
, value
);
718 bool AutofillManager::IsShowingUnmaskPrompt() {
719 return unmasking_card_
.Compare(CreditCard()) != 0;
722 const std::vector
<FormStructure
*>& AutofillManager::GetFormStructures() {
723 return form_structures_
.get();
726 void AutofillManager::SetTestDelegate(AutofillManagerTestDelegate
* delegate
) {
727 test_delegate_
= delegate
;
730 void AutofillManager::OnSetDataList(const std::vector
<base::string16
>& values
,
731 const std::vector
<base::string16
>& labels
) {
732 if (!IsValidString16Vector(values
) ||
733 !IsValidString16Vector(labels
) ||
734 values
.size() != labels
.size())
737 external_delegate_
->SetCurrentDataListValues(values
, labels
);
740 void AutofillManager::OnLoadedServerPredictions(
741 const std::string
& response_xml
) {
742 // Parse and store the server predictions.
743 FormStructure::ParseQueryResponse(response_xml
, form_structures_
.get(),
744 client_
->GetRapporService());
746 // Forward form structures to the password generation manager to detect
747 // account creation forms.
748 driver_
->PropagateAutofillPredictions(form_structures_
.get());
750 // If the corresponding flag is set, annotate forms with the predicted types.
751 driver_
->SendAutofillTypePredictionsToRenderer(form_structures_
.get());
754 void AutofillManager::OnUnmaskResponse(const UnmaskResponse
& response
) {
755 unmask_response_
= response
;
756 real_pan_request_timestamp_
= base::Time::Now();
757 real_pan_client_
.UnmaskCard(unmasking_card_
, response
);
760 void AutofillManager::OnUnmaskPromptClosed() {
761 real_pan_client_
.CancelRequest();
762 driver_
->RendererShouldClearPreviewedForm();
763 unmasking_card_
= CreditCard();
764 unmask_response_
= UnmaskResponse();
767 IdentityProvider
* AutofillManager::GetIdentityProvider() {
768 return client()->GetIdentityProvider();
771 void AutofillManager::OnDidGetRealPan(AutofillClient::GetRealPanResult result
,
772 const std::string
& real_pan
) {
773 AutofillMetrics::LogRealPanDuration(
774 base::Time::Now() - real_pan_request_timestamp_
, result
);
775 if (!real_pan
.empty()) {
776 DCHECK_EQ(AutofillClient::SUCCESS
, result
);
777 credit_card_form_event_logger_
->OnDidFillSuggestion(unmasking_card_
);
778 recently_unmasked_cards_
.push_back(unmasking_card_
);
779 unmasking_card_
.set_record_type(CreditCard::FULL_SERVER_CARD
);
780 unmasking_card_
.SetNumber(base::UTF8ToUTF16(real_pan
));
781 if (!unmask_response_
.exp_month
.empty()) {
782 unmasking_card_
.SetRawInfo(CREDIT_CARD_EXP_MONTH
,
783 unmask_response_
.exp_month
);
785 if (!unmask_response_
.exp_year
.empty()) {
786 unmasking_card_
.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR
,
787 unmask_response_
.exp_year
);
789 if (unmask_response_
.should_store_pan
)
790 personal_data_
->UpdateServerCreditCard(unmasking_card_
);
792 FillCreditCardForm(unmasking_query_id_
, unmasking_form_
, unmasking_field_
,
796 client()->OnUnmaskVerificationResult(result
);
799 void AutofillManager::OnDidEndTextFieldEditing() {
800 external_delegate_
->DidEndTextFieldEditing();
803 bool AutofillManager::IsAutofillEnabled() const {
804 return ::autofill::IsAutofillEnabled(client_
->GetPrefs());
807 void AutofillManager::ImportFormData(const FormStructure
& submitted_form
) {
808 scoped_ptr
<CreditCard
> imported_credit_card
;
809 if (!personal_data_
->ImportFormData(submitted_form
, &imported_credit_card
))
812 #ifdef ENABLE_FORM_DEBUG_DUMP
813 // Debug code for research on what autofill Chrome extracts from the last few
814 // forms when submitting credit card data. See DumpAutofillData().
815 bool dump_data
= base::CommandLine::ForCurrentProcess()->HasSwitch(
816 "dump-autofill-data");
818 // Save the form data for future dumping.
820 if (recently_autofilled_forms_
.size() > 5)
821 recently_autofilled_forms_
.erase(recently_autofilled_forms_
.begin());
823 recently_autofilled_forms_
.push_back(
824 std::map
<std::string
, base::string16
>());
825 auto& map
= recently_autofilled_forms_
.back();
826 for (const auto& field
: submitted_form
) {
827 AutofillType type
= field
->Type();
828 // Even though this is for development only, mask full credit card #'s.
829 if (type
.GetStorableType() == CREDIT_CARD_NUMBER
&&
830 field
->value
.size() > 4) {
831 map
[type
.ToString()] = base::ASCIIToUTF16("...(omitted)...") +
832 field
->value
.substr(field
->value
.size() - 4, 4);
834 map
[type
.ToString()] = field
->value
;
838 DumpAutofillData(imported_credit_card
);
840 #endif // ENABLE_FORM_DEBUG_DUMP
842 // If credit card information was submitted, we need to confirm whether to
844 if (imported_credit_card
) {
845 // Don't offer to save any cards that were recently unmasked.
846 for (const CreditCard
& unmasked_card
: recently_unmasked_cards_
) {
847 if (unmasked_card
.TypeAndLastFourDigits() ==
848 imported_credit_card
->TypeAndLastFourDigits())
851 client_
->ConfirmSaveCreditCard(
853 base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard
),
854 base::Unretained(personal_data_
),
855 *imported_credit_card
));
859 // Note that |submitted_form| is passed as a pointer rather than as a reference
860 // so that we can get memory management right across threads. Note also that we
861 // explicitly pass in all the time stamps of interest, as the cached ones might
862 // get reset before this method executes.
863 void AutofillManager::UploadFormDataAsyncCallback(
864 const FormStructure
* submitted_form
,
865 const TimeTicks
& load_time
,
866 const TimeTicks
& interaction_time
,
867 const TimeTicks
& submission_time
) {
868 submitted_form
->LogQualityMetrics(load_time
, interaction_time
,
870 client_
->GetRapporService());
872 if (submitted_form
->ShouldBeCrowdsourced())
873 UploadFormData(*submitted_form
);
876 void AutofillManager::UploadFormData(const FormStructure
& submitted_form
) {
877 if (!download_manager_
)
880 // Check if the form is among the forms that were recently auto-filled.
881 bool was_autofilled
= false;
882 std::string form_signature
= submitted_form
.FormSignature();
883 for (const std::string
& cur_sig
: autofilled_form_signatures_
) {
884 if (cur_sig
== form_signature
) {
885 was_autofilled
= true;
890 ServerFieldTypeSet non_empty_types
;
891 personal_data_
->GetNonEmptyTypes(&non_empty_types
);
893 download_manager_
->StartUploadRequest(
894 submitted_form
, was_autofilled
, non_empty_types
,
895 std::string() /* login_form_signature */);
898 bool AutofillManager::UploadPasswordForm(
899 const FormData
& form
,
900 const base::string16
& username_field
,
901 const ServerFieldType
& password_type
,
902 const std::string
& login_form_signature
) {
903 FormStructure
form_structure(form
);
905 if (!ShouldUploadForm(form_structure
))
908 if (!form_structure
.ShouldBeCrowdsourced())
911 // Find the first password field to label. If the provided username field name
912 // is not empty, then also find the first field with that name to label.
913 // We don't try to label anything else.
914 bool found_password_field
= false;
915 bool found_username_field
= username_field
.empty();
916 for (size_t i
= 0; i
< form_structure
.field_count(); ++i
) {
917 AutofillField
* field
= form_structure
.field(i
);
919 ServerFieldTypeSet types
;
920 if (!found_password_field
&& field
->form_control_type
== "password") {
921 types
.insert(password_type
);
922 found_password_field
= true;
923 } else if (!found_username_field
&& field
->name
== username_field
) {
924 types
.insert(USERNAME
);
925 found_username_field
= true;
927 types
.insert(UNKNOWN_TYPE
);
929 field
->set_possible_types(types
);
931 DCHECK(found_password_field
);
933 // Only the USERNAME type and one password field type should be present.
934 ServerFieldTypeSet available_field_types
;
935 available_field_types
.insert(password_type
);
936 available_field_types
.insert(USERNAME
);
938 // Force uploading as these events are relatively rare and we want to make
939 // sure to receive them. It also makes testing easier if these requests
941 form_structure
.set_upload_required(UPLOAD_REQUIRED
);
943 if (!download_manager_
)
946 return download_manager_
->StartUploadRequest(
947 form_structure
, false /* was_autofilled */, available_field_types
,
948 login_form_signature
);
951 void AutofillManager::Reset() {
952 form_structures_
.clear();
953 address_form_event_logger_
.reset(
954 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */));
955 credit_card_form_event_logger_
.reset(
956 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */));
957 has_logged_autofill_enabled_
= false;
958 has_logged_address_suggestions_count_
= false;
959 did_show_suggestions_
= false;
960 user_did_type_
= false;
961 user_did_autofill_
= false;
962 user_did_edit_autofilled_field_
= false;
963 unmasking_card_
= CreditCard();
964 unmasking_query_id_
= -1;
965 unmasking_form_
= FormData();
966 unmasking_field_
= FormFieldData();
967 forms_loaded_timestamps_
.clear();
968 initial_interaction_timestamp_
= TimeTicks();
969 external_delegate_
->Reset();
972 AutofillManager::AutofillManager(AutofillDriver
* driver
,
973 AutofillClient
* client
,
974 PersonalDataManager
* personal_data
)
977 real_pan_client_(driver
->GetURLRequestContext(), this),
978 app_locale_("en-US"),
979 personal_data_(personal_data
),
980 autocomplete_history_manager_(
981 new AutocompleteHistoryManager(driver
, client
)),
982 address_form_event_logger_(
983 new AutofillMetrics::FormEventLogger(false /* is_for_credit_card */)),
984 credit_card_form_event_logger_(
985 new AutofillMetrics::FormEventLogger(true /* is_for_credit_card */)),
986 has_logged_autofill_enabled_(false),
987 has_logged_address_suggestions_count_(false),
988 did_show_suggestions_(false),
989 user_did_type_(false),
990 user_did_autofill_(false),
991 user_did_edit_autofilled_field_(false),
992 unmasking_query_id_(-1),
993 external_delegate_(NULL
),
994 test_delegate_(NULL
),
995 weak_ptr_factory_(this) {
1000 bool AutofillManager::RefreshDataModels() {
1001 if (!IsAutofillEnabled())
1004 // No autofill data to return if the profiles are empty.
1005 const std::vector
<AutofillProfile
*>& profiles
=
1006 personal_data_
->GetProfiles();
1007 const std::vector
<CreditCard
*>& credit_cards
=
1008 personal_data_
->GetCreditCards();
1010 // Updating the FormEventLoggers for addresses and credit cards.
1012 bool is_server_data_available
= false;
1013 bool is_local_data_available
= false;
1014 for (CreditCard
* credit_card
: credit_cards
) {
1015 if (credit_card
->record_type() == CreditCard::LOCAL_CARD
)
1016 is_local_data_available
= true;
1018 is_server_data_available
= true;
1020 credit_card_form_event_logger_
->set_is_server_data_available(
1021 is_server_data_available
);
1022 credit_card_form_event_logger_
->set_is_local_data_available(
1023 is_local_data_available
);
1026 bool is_server_data_available
= false;
1027 bool is_local_data_available
= false;
1028 for (AutofillProfile
* profile
: profiles
) {
1029 if (profile
->record_type() == AutofillProfile::LOCAL_PROFILE
)
1030 is_local_data_available
= true;
1031 else if (profile
->record_type() == AutofillProfile::SERVER_PROFILE
)
1032 is_server_data_available
= true;
1034 address_form_event_logger_
->set_is_server_data_available(
1035 is_server_data_available
);
1036 address_form_event_logger_
->set_is_local_data_available(
1037 is_local_data_available
);
1040 if (profiles
.empty() && credit_cards
.empty())
1046 bool AutofillManager::IsCreditCard(int unique_id
) {
1047 // Unpack the |unique_id| into component parts.
1048 std::string credit_card_id
;
1049 std::string profile_id
;
1050 SplitFrontendID(unique_id
, &credit_card_id
, &profile_id
);
1051 DCHECK(!base::IsValidGUID(credit_card_id
) || !base::IsValidGUID(profile_id
));
1052 return base::IsValidGUID(credit_card_id
);
1055 bool AutofillManager::GetProfile(int unique_id
,
1056 const AutofillProfile
** profile
) {
1057 // Unpack the |unique_id| into component parts.
1058 std::string credit_card_id
;
1059 std::string profile_id
;
1060 SplitFrontendID(unique_id
, &credit_card_id
, &profile_id
);
1062 if (base::IsValidGUID(profile_id
))
1063 *profile
= personal_data_
->GetProfileByGUID(profile_id
);
1067 bool AutofillManager::GetCreditCard(int unique_id
,
1068 const CreditCard
** credit_card
) {
1069 // Unpack the |unique_id| into component parts.
1070 std::string credit_card_id
;
1071 std::string profile_id
;
1072 SplitFrontendID(unique_id
, &credit_card_id
, &profile_id
);
1073 *credit_card
= NULL
;
1074 if (base::IsValidGUID(credit_card_id
))
1075 *credit_card
= personal_data_
->GetCreditCardByGUID(credit_card_id
);
1076 return !!*credit_card
;
1079 void AutofillManager::FillOrPreviewDataModelForm(
1080 AutofillDriver::RendererFormDataAction action
,
1082 const FormData
& form
,
1083 const FormFieldData
& field
,
1084 const AutofillDataModel
& data_model
,
1085 bool is_credit_card
) {
1086 FormStructure
* form_structure
= NULL
;
1087 AutofillField
* autofill_field
= NULL
;
1088 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
1091 DCHECK(form_structure
);
1092 DCHECK(autofill_field
);
1094 FormData result
= form
;
1096 base::string16 profile_full_name
;
1097 std::string profile_language_code
;
1098 if (!is_credit_card
) {
1099 profile_full_name
= data_model
.GetInfo(
1100 AutofillType(NAME_FULL
), app_locale_
);
1101 profile_language_code
=
1102 static_cast<const AutofillProfile
*>(&data_model
)->language_code();
1105 // If the relevant section is auto-filled, we should fill |field| but not the
1106 // rest of the form.
1107 if (SectionIsAutofilled(*form_structure
, form
, autofill_field
->section())) {
1108 for (std::vector
<FormFieldData
>::iterator iter
= result
.fields
.begin();
1109 iter
!= result
.fields
.end(); ++iter
) {
1110 if (iter
->SameFieldAs(field
)) {
1111 base::string16 value
=
1112 data_model
.GetInfo(autofill_field
->Type(), app_locale_
);
1113 if (AutofillField::FillFormField(*autofill_field
,
1115 profile_language_code
,
1118 // Mark the cached field as autofilled, so that we can detect when a
1119 // user edits an autofilled field (for metrics).
1120 autofill_field
->is_autofilled
= true;
1122 // Mark the field as autofilled when a non-empty value is assigned to
1123 // it. This allows the renderer to distinguish autofilled fields from
1124 // fields with non-empty values, such as select-one fields.
1125 iter
->is_autofilled
= true;
1127 if (!is_credit_card
&& !value
.empty())
1128 client_
->DidFillOrPreviewField(value
, profile_full_name
);
1134 // Note that this may invalidate |data_model|, particularly if it is a Mac
1135 // address book entry.
1136 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
)
1137 personal_data_
->RecordUseOf(data_model
);
1139 driver_
->SendFormDataToRenderer(query_id
, action
, result
);
1143 DCHECK_EQ(form_structure
->field_count(), form
.fields
.size());
1144 for (size_t i
= 0; i
< form_structure
->field_count(); ++i
) {
1145 if (form_structure
->field(i
)->section() != autofill_field
->section())
1148 DCHECK(form_structure
->field(i
)->SameFieldAs(result
.fields
[i
]));
1150 const AutofillField
* cached_field
= form_structure
->field(i
);
1151 FieldTypeGroup field_group_type
= cached_field
->Type().group();
1153 if (field_group_type
== NO_GROUP
)
1156 base::string16 value
=
1157 data_model
.GetInfo(cached_field
->Type(), app_locale_
);
1158 if (is_credit_card
&&
1159 cached_field
->Type().GetStorableType() ==
1160 CREDIT_CARD_VERIFICATION_CODE
) {
1161 // If this is |unmasking_card_|, |unmask_response_.cvc| should be
1162 // non-empty and vice versa.
1163 value
= unmask_response_
.cvc
;
1164 DCHECK_EQ(&unmasking_card_
== &data_model
, !value
.empty());
1167 // Must match ForEachMatchingFormField() in form_autofill_util.cc.
1168 // Only notify autofilling of empty fields and the field that initiated
1169 // the filling (note that "select-one" controls may not be empty but will
1170 // still be autofilled).
1171 bool should_notify
=
1174 (result
.fields
[i
].SameFieldAs(field
) ||
1175 result
.fields
[i
].form_control_type
== "select-one" ||
1176 result
.fields
[i
].value
.empty());
1177 if (AutofillField::FillFormField(*cached_field
,
1179 profile_language_code
,
1181 &result
.fields
[i
])) {
1182 // Mark the cached field as autofilled, so that we can detect when a
1183 // user edits an autofilled field (for metrics).
1184 form_structure
->field(i
)->is_autofilled
= true;
1186 // Mark the field as autofilled when a non-empty value is assigned to
1187 // it. This allows the renderer to distinguish autofilled fields from
1188 // fields with non-empty values, such as select-one fields.
1189 result
.fields
[i
].is_autofilled
= true;
1192 client_
->DidFillOrPreviewField(value
, profile_full_name
);
1196 autofilled_form_signatures_
.push_front(form_structure
->FormSignature());
1197 // Only remember the last few forms that we've seen, both to avoid false
1198 // positives and to avoid wasting memory.
1199 if (autofilled_form_signatures_
.size() > kMaxRecentFormSignaturesToRemember
)
1200 autofilled_form_signatures_
.pop_back();
1202 // Note that this may invalidate |data_model|, particularly if it is a Mac
1203 // address book entry.
1204 if (action
== AutofillDriver::FORM_DATA_ACTION_FILL
)
1205 personal_data_
->RecordUseOf(data_model
);
1207 driver_
->SendFormDataToRenderer(query_id
, action
, result
);
1210 scoped_ptr
<FormStructure
> AutofillManager::ValidateSubmittedForm(
1211 const FormData
& form
) {
1212 scoped_ptr
<FormStructure
> submitted_form(new FormStructure(form
));
1213 if (!ShouldUploadForm(*submitted_form
))
1214 return scoped_ptr
<FormStructure
>();
1216 // Ignore forms not present in our cache. These are typically forms with
1217 // wonky JavaScript that also makes them not auto-fillable.
1218 FormStructure
* cached_submitted_form
;
1219 if (!FindCachedForm(form
, &cached_submitted_form
))
1220 return scoped_ptr
<FormStructure
>();
1222 submitted_form
->UpdateFromCache(*cached_submitted_form
);
1223 return submitted_form
.Pass();
1226 bool AutofillManager::FindCachedForm(const FormData
& form
,
1227 FormStructure
** form_structure
) const {
1228 // Find the FormStructure that corresponds to |form|.
1229 // Scan backward through the cached |form_structures_|, as updated versions of
1230 // forms are added to the back of the list, whereas original versions of these
1231 // forms might appear toward the beginning of the list. The communication
1232 // protocol with the crowdsourcing server does not permit us to discard the
1233 // original versions of the forms.
1234 *form_structure
= NULL
;
1235 for (FormStructure
* cur_form
: base::Reversed(form_structures_
)) {
1236 if (*cur_form
== form
) {
1237 *form_structure
= cur_form
;
1239 // The same form might be cached with multiple field counts: in some
1240 // cases, non-autofillable fields are filtered out, whereas in other cases
1241 // they are not. To avoid thrashing the cache, keep scanning until we
1242 // find a cached version with the same number of fields, if there is one.
1243 if (cur_form
->field_count() == form
.fields
.size())
1248 if (!(*form_structure
))
1254 bool AutofillManager::GetCachedFormAndField(const FormData
& form
,
1255 const FormFieldData
& field
,
1256 FormStructure
** form_structure
,
1257 AutofillField
** autofill_field
) {
1258 // Find the FormStructure that corresponds to |form|.
1259 // If we do not have this form in our cache but it is parseable, we'll add it
1260 // in the call to |UpdateCachedForm()|.
1261 if (!FindCachedForm(form
, form_structure
) &&
1262 !FormStructure(form
).ShouldBeParsed()) {
1266 // Update the cached form to reflect any dynamic changes to the form data, if
1268 if (!UpdateCachedForm(form
, *form_structure
, form_structure
))
1271 // No data to return if there are no auto-fillable fields.
1272 if (!(*form_structure
)->autofill_count())
1275 // Find the AutofillField that corresponds to |field|.
1276 *autofill_field
= NULL
;
1277 for (AutofillField
* current
: **form_structure
) {
1278 if (current
->SameFieldAs(field
)) {
1279 *autofill_field
= current
;
1284 // Even though we always update the cache, the field might not exist if the
1285 // website disables autocomplete while the user is interacting with the form.
1286 // See http://crbug.com/160476
1287 return *autofill_field
!= NULL
;
1290 AutofillField
* AutofillManager::GetAutofillField(const FormData
& form
,
1291 const FormFieldData
& field
) {
1292 if (!personal_data_
)
1295 FormStructure
* form_structure
= NULL
;
1296 AutofillField
* autofill_field
= NULL
;
1297 if (!GetCachedFormAndField(form
, field
, &form_structure
, &autofill_field
))
1300 if (!form_structure
->IsAutofillable())
1303 return autofill_field
;
1306 bool AutofillManager::UpdateCachedForm(const FormData
& live_form
,
1307 const FormStructure
* cached_form
,
1308 FormStructure
** updated_form
) {
1311 live_form
.fields
.size() != cached_form
->field_count());
1312 for (size_t i
= 0; !needs_update
&& i
< cached_form
->field_count(); ++i
)
1313 needs_update
= !cached_form
->field(i
)->SameFieldAs(live_form
.fields
[i
]);
1318 if (form_structures_
.size() >= kMaxFormCacheSize
)
1321 // Add the new or updated form to our cache.
1322 form_structures_
.push_back(new FormStructure(live_form
));
1323 *updated_form
= *form_structures_
.rbegin();
1324 (*updated_form
)->DetermineHeuristicTypes();
1326 // If we have cached data, propagate it to the updated form.
1328 std::map
<base::string16
, const AutofillField
*> cached_fields
;
1329 for (size_t i
= 0; i
< cached_form
->field_count(); ++i
) {
1330 const AutofillField
* field
= cached_form
->field(i
);
1331 cached_fields
[field
->unique_name()] = field
;
1334 for (size_t i
= 0; i
< (*updated_form
)->field_count(); ++i
) {
1335 AutofillField
* field
= (*updated_form
)->field(i
);
1336 auto cached_field
= cached_fields
.find(field
->unique_name());
1337 if (cached_field
!= cached_fields
.end()) {
1338 field
->set_server_type(cached_field
->second
->server_type());
1339 field
->is_autofilled
= cached_field
->second
->is_autofilled
;
1340 field
->set_previously_autofilled(
1341 cached_field
->second
->previously_autofilled());
1345 // Note: We _must not_ remove the original version of the cached form from
1346 // the list of |form_structures_|. Otherwise, we break parsing of the
1347 // crowdsourcing server's response to our query.
1350 // Annotate the updated form with its predicted types.
1351 std::vector
<FormStructure
*> forms(1, *updated_form
);
1352 driver_
->SendAutofillTypePredictionsToRenderer(forms
);
1357 std::vector
<Suggestion
> AutofillManager::GetProfileSuggestions(
1358 const FormStructure
& form
,
1359 const FormFieldData
& field
,
1360 const AutofillField
& autofill_field
) const {
1361 std::vector
<ServerFieldType
> field_types(form
.field_count());
1362 for (size_t i
= 0; i
< form
.field_count(); ++i
) {
1363 field_types
.push_back(form
.field(i
)->Type().GetStorableType());
1366 std::vector
<Suggestion
> suggestions
= personal_data_
->GetProfileSuggestions(
1367 autofill_field
.Type(), field
.value
, field
.is_autofilled
, field_types
);
1369 // Adjust phone number to display in prefix/suffix case.
1370 if (autofill_field
.Type().GetStorableType() == PHONE_HOME_NUMBER
) {
1371 for (size_t i
= 0; i
< suggestions
.size(); ++i
) {
1372 suggestions
[i
].value
= AutofillField::GetPhoneNumberValue(
1373 autofill_field
, suggestions
[i
].value
, field
);
1377 for (size_t i
= 0; i
< suggestions
.size(); ++i
) {
1378 suggestions
[i
].frontend_id
=
1379 MakeFrontendID(std::string(), suggestions
[i
].backend_id
);
1384 std::vector
<Suggestion
> AutofillManager::GetCreditCardSuggestions(
1385 const FormFieldData
& field
,
1386 const AutofillType
& type
) const {
1387 std::vector
<Suggestion
> suggestions
=
1388 personal_data_
->GetCreditCardSuggestions(type
, field
.value
);
1389 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
1390 suggestions
[i
].frontend_id
=
1391 MakeFrontendID(suggestions
[i
].backend_id
, std::string());
1396 void AutofillManager::ParseForms(const std::vector
<FormData
>& forms
) {
1397 std::vector
<FormStructure
*> non_queryable_forms
;
1398 for (const FormData
& form
: forms
) {
1399 scoped_ptr
<FormStructure
> form_structure(new FormStructure(form
));
1401 if (!form_structure
->ShouldBeParsed()) {
1402 if (form_structure
->has_password_field()) {
1403 AutofillMetrics::LogPasswordFormQueryVolume(
1404 AutofillMetrics::NEW_PASSWORD_QUERY
);
1409 form_structure
->DetermineHeuristicTypes();
1411 if (form_structure
->ShouldBeCrowdsourced()) {
1412 AutofillMetrics::LogPasswordFormQueryVolume(
1413 AutofillMetrics::CURRENT_QUERY
);
1414 form_structures_
.push_back(form_structure
.release());
1416 non_queryable_forms
.push_back(form_structure
.release());
1420 if (!form_structures_
.empty() && download_manager_
) {
1421 // Query the server if at least one of the forms was parsed.
1422 download_manager_
->StartQueryRequest(form_structures_
.get());
1425 for (FormStructure
* structure
: non_queryable_forms
)
1426 form_structures_
.push_back(structure
);
1428 if (!form_structures_
.empty()) {
1429 AutofillMetrics::LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED
);
1431 // Log this from same location as AutofillMetrics::FORMS_LOADED to ensure
1432 // that KeyboardAccessoryButtonsIOS and UserHappiness UMA metrics will be
1433 // directly comparable.
1434 KeyboardAccessoryMetricsLogger::OnFormsLoaded();
1438 // For the |non_queryable_forms|, we have all the field type info we're ever
1439 // going to get about them. For the other forms, we'll wait until we get a
1440 // response from the server.
1441 driver_
->SendAutofillTypePredictionsToRenderer(non_queryable_forms
);
1444 int AutofillManager::BackendIDToInt(const std::string
& backend_id
) const {
1445 if (!base::IsValidGUID(backend_id
))
1448 const auto found
= backend_to_int_map_
.find(backend_id
);
1449 if (found
== backend_to_int_map_
.end()) {
1450 // Unknown one, make a new entry.
1451 int int_id
= backend_to_int_map_
.size() + 1;
1452 backend_to_int_map_
[backend_id
] = int_id
;
1453 int_to_backend_map_
[int_id
] = backend_id
;
1456 return found
->second
;
1459 std::string
AutofillManager::IntToBackendID(int int_id
) const {
1461 return std::string();
1463 const auto found
= int_to_backend_map_
.find(int_id
);
1464 if (found
== int_to_backend_map_
.end()) {
1466 return std::string();
1468 return found
->second
;
1471 // When sending IDs (across processes) to the renderer we pack credit card and
1472 // profile IDs into a single integer. Credit card IDs are sent in the high
1473 // word and profile IDs are sent in the low word.
1474 int AutofillManager::MakeFrontendID(
1475 const std::string
& cc_backend_id
,
1476 const std::string
& profile_backend_id
) const {
1477 int cc_int_id
= BackendIDToInt(cc_backend_id
);
1478 int profile_int_id
= BackendIDToInt(profile_backend_id
);
1480 // Should fit in signed 16-bit integers. We use 16-bits each when combining
1481 // below, and negative frontend IDs have special meaning so we can never use
1483 DCHECK(cc_int_id
<= std::numeric_limits
<int16_t>::max());
1484 DCHECK(profile_int_id
<= std::numeric_limits
<int16_t>::max());
1486 // Put CC in the high half of the bits.
1487 return (cc_int_id
<< std::numeric_limits
<uint16_t>::digits
) | profile_int_id
;
1490 // When receiving IDs (across processes) from the renderer we unpack credit card
1491 // and profile IDs from a single integer. Credit card IDs are stored in the
1492 // high word and profile IDs are stored in the low word.
1493 void AutofillManager::SplitFrontendID(int frontend_id
,
1494 std::string
* cc_backend_id
,
1495 std::string
* profile_backend_id
) const {
1496 int cc_int_id
= (frontend_id
>> std::numeric_limits
<uint16_t>::digits
) &
1497 std::numeric_limits
<uint16_t>::max();
1498 int profile_int_id
= frontend_id
& std::numeric_limits
<uint16_t>::max();
1500 *cc_backend_id
= IntToBackendID(cc_int_id
);
1501 *profile_backend_id
= IntToBackendID(profile_int_id
);
1504 void AutofillManager::UpdateInitialInteractionTimestamp(
1505 const TimeTicks
& interaction_timestamp
) {
1506 if (initial_interaction_timestamp_
.is_null() ||
1507 interaction_timestamp
< initial_interaction_timestamp_
) {
1508 initial_interaction_timestamp_
= interaction_timestamp
;
1512 bool AutofillManager::ShouldUploadForm(const FormStructure
& form
) {
1513 if (!IsAutofillEnabled())
1516 if (driver_
->IsOffTheRecord())
1519 // Disregard forms that we wouldn't ever autofill in the first place.
1520 if (!form
.ShouldBeParsed())
1526 #ifdef ENABLE_FORM_DEBUG_DUMP
1527 void AutofillManager::DumpAutofillData(bool imported_cc
) const {
1528 base::ThreadRestrictions::ScopedAllowIO allow_id
;
1530 // This code dumps the last few forms seen on the current tab to a file on
1531 // the desktop. This is only enabled when a specific command line flag is
1532 // passed for manual analysis of the address context information available
1533 // when offering to save credit cards in a checkout session. This is to
1534 // help developers experimenting with better card saving features.
1535 base::FilePath path
;
1536 if (!PathService::Get(base::DIR_USER_DESKTOP
, &path
))
1538 path
= path
.Append(FILE_PATH_LITERAL("autofill_debug_dump.txt"));
1539 FILE* file
= base::OpenFile(path
, "a");
1543 fputs("------------------------------------------------------\n", file
);
1545 fputs("Got a new credit card on CC form:\n", file
);
1547 fputs("Submitted form:\n", file
);
1548 for (int i
= static_cast<int>(recently_autofilled_forms_
.size()) - 1;
1550 for (const auto& pair
: recently_autofilled_forms_
[i
]) {
1552 fputs(pair
.first
.c_str(), file
);
1554 fputs(base::UTF16ToUTF8(pair
.second
).c_str(), file
);
1558 fputs("Next oldest form:\n", file
);
1564 #endif // ENABLE_FORM_DEBUG_DUMP
1566 } // namespace autofill