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_field.h"
7 #include "base/command_line.h"
8 #include "base/logging.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_split.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "components/autofill/core/browser/autofill_country.h"
15 #include "components/autofill/core/browser/autofill_type.h"
16 #include "components/autofill/core/browser/phone_number.h"
17 #include "components/autofill/core/browser/state_names.h"
18 #include "components/autofill/core/common/autofill_switches.h"
19 #include "grit/components_strings.h"
20 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
21 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h"
22 #include "ui/base/l10n/l10n_util.h"
24 using ::i18n::addressinput::AddressData;
25 using ::i18n::addressinput::GetStreetAddressLinesAsSingleLine;
26 using base::ASCIIToUTF16;
27 using base::StringToInt;
32 const char* const kMonthsAbbreviated[] = {
33 NULL, // Padding so index 1 = month 1 = January.
34 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
35 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
38 const char* const kMonthsFull[] = {
39 NULL, // Padding so index 1 = month 1 = January.
40 "January", "February", "March", "April", "May", "June",
41 "July", "August", "September", "October", "November", "December",
44 // Returns true if the value was successfully set, meaning |value| was found in
45 // the list of select options in |field|.
46 bool SetSelectControlValue(const base::string16& value,
47 FormFieldData* field) {
48 base::string16 value_lowercase = base::StringToLowerASCII(value);
50 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
51 base::string16 best_match;
52 for (size_t i = 0; i < field->option_values.size(); ++i) {
53 if (value == field->option_values[i] ||
54 value == field->option_contents[i]) {
55 // An exact match, use it.
56 best_match = field->option_values[i];
60 if (value_lowercase == base::StringToLowerASCII(field->option_values[i]) ||
62 base::StringToLowerASCII(field->option_contents[i])) {
63 // A match, but not in the same case. Save it in case an exact match is
65 best_match = field->option_values[i];
69 if (best_match.empty())
72 field->value = best_match;
76 // Like SetSelectControlValue, but searches within the field values and options
77 // for |value|. For example, "NC - North Carolina" would match "north carolina".
78 bool SetSelectControlValueSubstringMatch(const base::string16& value,
79 FormFieldData* field) {
80 base::string16 value_lowercase = base::StringToLowerASCII(value);
81 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
84 for (size_t i = 0; i < field->option_values.size(); ++i) {
85 if (base::StringToLowerASCII(field->option_values[i]).find(value_lowercase) !=
87 base::StringToLowerASCII(field->option_contents[i]).find(
88 value_lowercase) != std::string::npos) {
89 // The best match is the shortest one.
90 if (best_match == -1 ||
91 field->option_values[best_match].size() >
92 field->option_values[i].size()) {
98 if (best_match >= 0) {
99 field->value = field->option_values[best_match];
106 // Like SetSelectControlValue, but searches within the field values and options
107 // for |value|. First it tokenizes the options, then tries to match against
108 // tokens. For example, "NC - North Carolina" would match "nc" but not "ca".
109 bool SetSelectControlValueTokenMatch(const base::string16& value,
110 FormFieldData* field) {
111 base::string16 value_lowercase = base::StringToLowerASCII(value);
112 std::vector<base::string16> tokenized;
113 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
115 for (size_t i = 0; i < field->option_values.size(); ++i) {
116 base::SplitStringAlongWhitespace(
117 base::StringToLowerASCII(field->option_values[i]), &tokenized);
118 if (std::find(tokenized.begin(), tokenized.end(), value_lowercase) !=
120 field->value = field->option_values[i];
124 base::SplitStringAlongWhitespace(
125 base::StringToLowerASCII(field->option_contents[i]), &tokenized);
126 if (std::find(tokenized.begin(), tokenized.end(), value_lowercase) !=
128 field->value = field->option_values[i];
136 // Try to fill a numeric |value| into the given |field|.
137 bool FillNumericSelectControl(int value,
138 FormFieldData* field) {
139 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
140 for (size_t i = 0; i < field->option_values.size(); ++i) {
142 if ((StringToInt(field->option_values[i], &option) && option == value) ||
143 (StringToInt(field->option_contents[i], &option) && option == value)) {
144 field->value = field->option_values[i];
152 bool FillStateSelectControl(const base::string16& value,
153 FormFieldData* field) {
154 base::string16 full, abbreviation;
155 state_names::GetNameAndAbbreviation(value, &full, &abbreviation);
157 // Try an exact match of the abbreviation first.
158 if (!abbreviation.empty() && SetSelectControlValue(abbreviation, field)) {
162 // Try an exact match of the full name.
163 if (!full.empty() && SetSelectControlValue(full, field)) {
167 // Then try an inexact match of the full name.
168 if (!full.empty() && SetSelectControlValueSubstringMatch(full, field)) {
172 // Then try an inexact match of the abbreviation name.
173 return !abbreviation.empty() &&
174 SetSelectControlValueTokenMatch(abbreviation, field);
177 bool FillCountrySelectControl(const base::string16& value,
178 const std::string& app_locale,
179 FormFieldData* field_data) {
180 std::string country_code = AutofillCountry::GetCountryCode(value, app_locale);
181 if (country_code.empty())
184 DCHECK_EQ(field_data->option_values.size(),
185 field_data->option_contents.size());
186 for (size_t i = 0; i < field_data->option_values.size(); ++i) {
187 // Canonicalize each <option> value to a country code, and compare to the
188 // target country code.
189 base::string16 value = field_data->option_values[i];
190 base::string16 contents = field_data->option_contents[i];
191 if (country_code == AutofillCountry::GetCountryCode(value, app_locale) ||
192 country_code == AutofillCountry::GetCountryCode(contents, app_locale)) {
193 field_data->value = value;
201 bool FillExpirationMonthSelectControl(const base::string16& value,
202 FormFieldData* field) {
204 if (!StringToInt(value, &index) ||
206 static_cast<size_t>(index) >= arraysize(kMonthsFull))
210 SetSelectControlValue(ASCIIToUTF16(kMonthsAbbreviated[index]), field) ||
211 SetSelectControlValue(ASCIIToUTF16(kMonthsFull[index]), field) ||
212 FillNumericSelectControl(index, field);
216 // Returns true if the last two digits in |year| match those in |str|.
217 bool LastTwoDigitsMatch(const base::string16& year,
218 const base::string16& str) {
221 if (!StringToInt(year, &year_int) || !StringToInt(str, &str_int))
224 return (year_int % 100) == (str_int % 100);
227 // Try to fill a year |value| into the given |field| by comparing the last two
228 // digits of the year to the field's options.
229 bool FillYearSelectControl(const base::string16& value,
230 FormFieldData* field) {
231 if (value.size() != 2U && value.size() != 4U)
234 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
235 for (size_t i = 0; i < field->option_values.size(); ++i) {
236 if (LastTwoDigitsMatch(value, field->option_values[i]) ||
237 LastTwoDigitsMatch(value, field->option_contents[i])) {
238 field->value = field->option_values[i];
246 // Try to fill a credit card type |value| (Visa, MasterCard, etc.) into the
248 bool FillCreditCardTypeSelectControl(const base::string16& value,
249 FormFieldData* field) {
250 // Try stripping off spaces.
251 base::string16 value_stripped;
252 base::RemoveChars(base::StringToLowerASCII(value), base::kWhitespaceUTF16,
255 for (size_t i = 0; i < field->option_values.size(); ++i) {
256 base::string16 option_value_lowercase;
257 base::RemoveChars(base::StringToLowerASCII(field->option_values[i]),
258 base::kWhitespaceUTF16, &option_value_lowercase);
259 base::string16 option_contents_lowercase;
260 base::RemoveChars(base::StringToLowerASCII(field->option_contents[i]),
261 base::kWhitespaceUTF16, &option_contents_lowercase);
263 // Perform a case-insensitive comparison; but fill the form with the
264 // original text, not the lowercased version.
265 if (value_stripped == option_value_lowercase ||
266 value_stripped == option_contents_lowercase) {
267 field->value = field->option_values[i];
272 // For American Express, also try filling as "AmEx".
273 if (value == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX))
274 return FillCreditCardTypeSelectControl(ASCIIToUTF16("AmEx"), field);
279 // Set |field_data|'s value to |number|, or possibly an appropriate substring of
280 // |number|. The |field| specifies the type of the phone and whether this is a
281 // phone prefix or suffix.
282 void FillPhoneNumberField(const AutofillField& field,
283 const base::string16& number,
284 FormFieldData* field_data) {
286 AutofillField::GetPhoneNumberValue(field, number, *field_data);
289 // Set |field_data|'s value to |number|, or possibly an appropriate substring
290 // of |number| for cases where credit card number splits across multiple HTML
291 // form input fields.
292 // The |field| specifies the |credit_card_number_offset_| to the substring
293 // within credit card number.
294 void FillCreditCardNumberField(const AutofillField& field,
295 const base::string16& number,
296 FormFieldData* field_data) {
297 base::string16 value = number;
299 // |field|'s max_length truncates credit card number to fit within.
300 if (field.credit_card_number_offset() < value.length())
301 value = value.substr(field.credit_card_number_offset());
303 field_data->value = value;
306 // Fills in the select control |field| with |value|. If an exact match is not
307 // found, falls back to alternate filling strategies based on the |type|.
308 bool FillSelectControl(const AutofillType& type,
309 const base::string16& value,
310 const std::string& app_locale,
311 FormFieldData* field) {
312 DCHECK_EQ("select-one", field->form_control_type);
314 // Guard against corrupted values passed over IPC.
315 if (field->option_values.size() != field->option_contents.size())
321 // First, search for exact matches.
322 if (SetSelectControlValue(value, field))
325 // If that fails, try specific fallbacks based on the field type.
326 ServerFieldType storable_type = type.GetStorableType();
327 if (storable_type == ADDRESS_HOME_STATE) {
328 return FillStateSelectControl(value, field);
329 } else if (storable_type == ADDRESS_HOME_COUNTRY) {
330 return FillCountrySelectControl(value, app_locale, field);
331 } else if (storable_type == CREDIT_CARD_EXP_MONTH) {
332 return FillExpirationMonthSelectControl(value, field);
333 } else if (storable_type == CREDIT_CARD_EXP_2_DIGIT_YEAR ||
334 storable_type == CREDIT_CARD_EXP_4_DIGIT_YEAR) {
335 return FillYearSelectControl(value, field);
336 } else if (storable_type == CREDIT_CARD_TYPE) {
337 return FillCreditCardTypeSelectControl(value, field);
343 // Fills in the month control |field| with |value|. |value| should be a date
344 // formatted as MM/YYYY. If it isn't, filling will fail.
345 bool FillMonthControl(const base::string16& value, FormFieldData* field) {
346 // Autofill formats a combined date as month/year.
347 std::vector<base::string16> pieces;
348 base::SplitString(value, base::char16('/'), &pieces);
349 if (pieces.size() != 2)
352 // HTML5 input="month" is formatted as year-month.
353 base::string16 month = pieces[0];
354 base::string16 year = pieces[1];
355 if ((month.size() != 1 && month.size() != 2) || year.size() != 4)
358 // HTML5 input="month" expects zero-padded months.
359 if (month.size() == 1)
360 month = ASCIIToUTF16("0") + month;
362 field->value = year + ASCIIToUTF16("-") + month;
366 // Fills |field| with the street address in |value|. Translates newlines into
367 // equivalent separators when necessary, i.e. when filling a single-line field.
368 // The separators depend on |address_language_code|.
369 void FillStreetAddress(const base::string16& value,
370 const std::string& address_language_code,
371 FormFieldData* field) {
372 if (field->form_control_type == "textarea") {
373 field->value = value;
377 AddressData address_data;
378 address_data.language_code = address_language_code;
379 base::SplitString(base::UTF16ToUTF8(value), '\n', &address_data.address_line);
381 GetStreetAddressLinesAsSingleLine(address_data, &line);
382 field->value = base::UTF8ToUTF16(line);
385 std::string Hash32Bit(const std::string& str) {
386 std::string hash_bin = base::SHA1HashString(str);
387 DCHECK_EQ(20U, hash_bin.length());
389 uint32 hash32 = ((hash_bin[0] & 0xFF) << 24) |
390 ((hash_bin[1] & 0xFF) << 16) |
391 ((hash_bin[2] & 0xFF) << 8) |
392 (hash_bin[3] & 0xFF);
394 return base::UintToString(hash32);
399 AutofillField::AutofillField()
400 : server_type_(NO_SERVER_DATA),
401 heuristic_type_(UNKNOWN_TYPE),
402 html_type_(HTML_TYPE_UNKNOWN),
403 html_mode_(HTML_MODE_NONE),
404 phone_part_(IGNORED),
405 credit_card_number_offset_(0) {
408 AutofillField::AutofillField(const FormFieldData& field,
409 const base::string16& unique_name)
410 : FormFieldData(field),
411 unique_name_(unique_name),
412 server_type_(NO_SERVER_DATA),
413 heuristic_type_(UNKNOWN_TYPE),
414 html_type_(HTML_TYPE_UNKNOWN),
415 html_mode_(HTML_MODE_NONE),
416 phone_part_(IGNORED),
417 credit_card_number_offset_(0) {
420 AutofillField::~AutofillField() {}
422 void AutofillField::set_heuristic_type(ServerFieldType type) {
423 if (type >= 0 && type < MAX_VALID_FIELD_TYPE &&
424 type != FIELD_WITH_DEFAULT_VALUE) {
425 heuristic_type_ = type;
428 // This case should not be reachable; but since this has potential
429 // implications on data uploaded to the server, better safe than sorry.
430 heuristic_type_ = UNKNOWN_TYPE;
434 void AutofillField::set_server_type(ServerFieldType type) {
435 // Chrome no longer supports fax numbers, but the server still does.
436 if (type >= PHONE_FAX_NUMBER && type <= PHONE_FAX_WHOLE_NUMBER)
442 void AutofillField::SetHtmlType(HtmlFieldType type, HtmlFieldMode mode) {
446 if (type == HTML_TYPE_TEL_LOCAL_PREFIX)
447 phone_part_ = PHONE_PREFIX;
448 else if (type == HTML_TYPE_TEL_LOCAL_SUFFIX)
449 phone_part_ = PHONE_SUFFIX;
451 phone_part_ = IGNORED;
454 AutofillType AutofillField::Type() const {
455 if (html_type_ != HTML_TYPE_UNKNOWN)
456 return AutofillType(html_type_, html_mode_);
458 if (server_type_ != NO_SERVER_DATA)
459 return AutofillType(server_type_);
461 return AutofillType(heuristic_type_);
464 bool AutofillField::IsEmpty() const {
465 return value.empty();
468 std::string AutofillField::FieldSignature() const {
469 std::string field_name = base::UTF16ToUTF8(name);
470 std::string field_string = field_name + "&" + form_control_type;
471 return Hash32Bit(field_string);
474 bool AutofillField::IsFieldFillable() const {
475 return (should_autocomplete ||
476 base::CommandLine::ForCurrentProcess()->HasSwitch(
477 switches::kIgnoreAutocompleteOffForAutofill)) &&
482 bool AutofillField::FillFormField(const AutofillField& field,
483 const base::string16& value,
484 const std::string& address_language_code,
485 const std::string& app_locale,
486 FormFieldData* field_data) {
487 AutofillType type = field.Type();
489 if (type.GetStorableType() == PHONE_HOME_NUMBER) {
490 FillPhoneNumberField(field, value, field_data);
492 } else if (field_data->form_control_type == "select-one") {
493 return FillSelectControl(type, value, app_locale, field_data);
494 } else if (field_data->form_control_type == "month") {
495 return FillMonthControl(value, field_data);
496 } else if (type.GetStorableType() == ADDRESS_HOME_STREET_ADDRESS) {
497 FillStreetAddress(value, address_language_code, field_data);
499 } else if (type.GetStorableType() == CREDIT_CARD_NUMBER) {
500 FillCreditCardNumberField(field, value, field_data);
504 field_data->value = value;
508 base::string16 AutofillField::GetPhoneNumberValue(
509 const AutofillField& field,
510 const base::string16& number,
511 const FormFieldData& field_data) {
512 // Check to see if the size field matches the "prefix" or "suffix" size.
513 // If so, return the appropriate substring.
514 if (number.length() !=
515 PhoneNumber::kPrefixLength + PhoneNumber::kSuffixLength) {
519 if (field.phone_part() == AutofillField::PHONE_PREFIX ||
520 field_data.max_length == PhoneNumber::kPrefixLength) {
522 number.substr(PhoneNumber::kPrefixOffset, PhoneNumber::kPrefixLength);
525 if (field.phone_part() == AutofillField::PHONE_SUFFIX ||
526 field_data.max_length == PhoneNumber::kSuffixLength) {
528 number.substr(PhoneNumber::kSuffixOffset, PhoneNumber::kSuffixLength);
534 } // namespace autofill