[Media Router] Add integration tests and e2e tests for media router and presentation...
[chromium-blink-merge.git] / components / autofill / core / browser / autofill_field.cc
blob33e5b6ee9c3009064b8646e74ee249f4e31fe470
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/i18n/string_search.h"
9 #include "base/logging.h"
10 #include "base/metrics/field_trial.h"
11 #include "base/sha1.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "components/autofill/core/browser/autofill_country.h"
17 #include "components/autofill/core/browser/autofill_type.h"
18 #include "components/autofill/core/browser/credit_card.h"
19 #include "components/autofill/core/browser/phone_number.h"
20 #include "components/autofill/core/browser/state_names.h"
21 #include "components/autofill/core/common/autofill_l10n_util.h"
22 #include "components/autofill/core/common/autofill_switches.h"
23 #include "grit/components_strings.h"
24 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
25 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h"
26 #include "ui/base/l10n/l10n_util.h"
28 using ::i18n::addressinput::AddressData;
29 using ::i18n::addressinput::GetStreetAddressLinesAsSingleLine;
30 using base::ASCIIToUTF16;
31 using base::StringToInt;
33 namespace autofill {
34 namespace {
36 // Returns true if the value was successfully set, meaning |value| was found in
37 // the list of select options in |field|.
38 bool SetSelectControlValue(const base::string16& value,
39 FormFieldData* field) {
40 l10n::CaseInsensitiveCompare compare;
42 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
43 base::string16 best_match;
44 for (size_t i = 0; i < field->option_values.size(); ++i) {
45 if (value == field->option_values[i] ||
46 value == field->option_contents[i]) {
47 // An exact match, use it.
48 best_match = field->option_values[i];
49 break;
52 if (compare.StringsEqual(value, field->option_values[i]) ||
53 compare.StringsEqual(value, field->option_contents[i])) {
54 // A match, but not in the same case. Save it in case an exact match is
55 // not found.
56 best_match = field->option_values[i];
60 if (best_match.empty())
61 return false;
63 field->value = best_match;
64 return true;
67 // Like SetSelectControlValue, but searches within the field values and options
68 // for |value|. For example, "NC - North Carolina" would match "north carolina".
69 bool SetSelectControlValueSubstringMatch(const base::string16& value,
70 FormFieldData* field) {
71 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
72 int best_match = -1;
74 base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents searcher(value);
75 for (size_t i = 0; i < field->option_values.size(); ++i) {
76 if (searcher.Search(field->option_values[i], nullptr, nullptr) ||
77 searcher.Search(field->option_contents[i], nullptr, nullptr)) {
78 // The best match is the shortest one.
79 if (best_match == -1 ||
80 field->option_values[best_match].size() >
81 field->option_values[i].size()) {
82 best_match = i;
87 if (best_match >= 0) {
88 field->value = field->option_values[best_match];
89 return true;
92 return false;
95 // Like SetSelectControlValue, but searches within the field values and options
96 // for |value|. First it tokenizes the options, then tries to match against
97 // tokens. For example, "NC - North Carolina" would match "nc" but not "ca".
98 bool SetSelectControlValueTokenMatch(const base::string16& value,
99 FormFieldData* field) {
100 std::vector<base::string16> tokenized;
101 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
102 l10n::CaseInsensitiveCompare compare;
104 for (size_t i = 0; i < field->option_values.size(); ++i) {
105 base::SplitStringAlongWhitespace(field->option_values[i], &tokenized);
106 if (std::find_if(tokenized.begin(), tokenized.end(),
107 [&compare, value](base::string16& rhs) {
108 return compare.StringsEqual(value, rhs);
109 }) != tokenized.end()) {
110 field->value = field->option_values[i];
111 return true;
114 base::SplitStringAlongWhitespace(field->option_contents[i], &tokenized);
115 if (std::find_if(tokenized.begin(), tokenized.end(),
116 [&compare, value](base::string16& rhs) {
117 return compare.StringsEqual(value, rhs);
118 }) != tokenized.end()) {
119 field->value = field->option_values[i];
120 return true;
124 return false;
127 // Try to fill a numeric |value| into the given |field|.
128 bool FillNumericSelectControl(int value,
129 FormFieldData* field) {
130 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
131 for (size_t i = 0; i < field->option_values.size(); ++i) {
132 int option;
133 if ((StringToInt(field->option_values[i], &option) && option == value) ||
134 (StringToInt(field->option_contents[i], &option) && option == value)) {
135 field->value = field->option_values[i];
136 return true;
140 return false;
143 bool FillStateSelectControl(const base::string16& value,
144 FormFieldData* field) {
145 base::string16 full, abbreviation;
146 state_names::GetNameAndAbbreviation(value, &full, &abbreviation);
148 // Try an exact match of the abbreviation first.
149 if (!abbreviation.empty() && SetSelectControlValue(abbreviation, field)) {
150 return true;
153 // Try an exact match of the full name.
154 if (!full.empty() && SetSelectControlValue(full, field)) {
155 return true;
158 // Then try an inexact match of the full name.
159 if (!full.empty() && SetSelectControlValueSubstringMatch(full, field)) {
160 return true;
163 // Then try an inexact match of the abbreviation name.
164 return !abbreviation.empty() &&
165 SetSelectControlValueTokenMatch(abbreviation, field);
168 bool FillCountrySelectControl(const base::string16& value,
169 const std::string& app_locale,
170 FormFieldData* field_data) {
171 std::string country_code = AutofillCountry::GetCountryCode(value, app_locale);
172 if (country_code.empty())
173 return false;
175 DCHECK_EQ(field_data->option_values.size(),
176 field_data->option_contents.size());
177 for (size_t i = 0; i < field_data->option_values.size(); ++i) {
178 // Canonicalize each <option> value to a country code, and compare to the
179 // target country code.
180 base::string16 value = field_data->option_values[i];
181 base::string16 contents = field_data->option_contents[i];
182 if (country_code == AutofillCountry::GetCountryCode(value, app_locale) ||
183 country_code == AutofillCountry::GetCountryCode(contents, app_locale)) {
184 field_data->value = value;
185 return true;
189 return false;
192 bool FillExpirationMonthSelectControl(const base::string16& value,
193 const std::string& app_locale,
194 FormFieldData* field) {
195 int index = 0;
196 if (!StringToInt(value, &index) || index <= 0 || index > 12)
197 return false;
199 for (const base::string16& option_value : field->option_values) {
200 int converted_value = 0;
201 if (CreditCard::ConvertMonth(option_value, app_locale, &converted_value) &&
202 index == converted_value) {
203 field->value = option_value;
204 return true;
208 for (const base::string16& option_contents : field->option_contents) {
209 int converted_contents = 0;
210 if (CreditCard::ConvertMonth(option_contents, app_locale,
211 &converted_contents) &&
212 index == converted_contents) {
213 field->value = option_contents;
214 return true;
218 return FillNumericSelectControl(index, field);
221 // Returns true if the last two digits in |year| match those in |str|.
222 bool LastTwoDigitsMatch(const base::string16& year,
223 const base::string16& str) {
224 int year_int;
225 int str_int;
226 if (!StringToInt(year, &year_int) || !StringToInt(str, &str_int))
227 return false;
229 return (year_int % 100) == (str_int % 100);
232 // Try to fill a year |value| into the given |field| by comparing the last two
233 // digits of the year to the field's options.
234 bool FillYearSelectControl(const base::string16& value,
235 FormFieldData* field) {
236 if (value.size() != 2U && value.size() != 4U)
237 return false;
239 DCHECK_EQ(field->option_values.size(), field->option_contents.size());
240 for (size_t i = 0; i < field->option_values.size(); ++i) {
241 if (LastTwoDigitsMatch(value, field->option_values[i]) ||
242 LastTwoDigitsMatch(value, field->option_contents[i])) {
243 field->value = field->option_values[i];
244 return true;
248 return false;
251 // Try to fill a credit card type |value| (Visa, MasterCard, etc.) into the
252 // given |field|.
253 bool FillCreditCardTypeSelectControl(const base::string16& value,
254 FormFieldData* field) {
255 size_t idx;
256 if (AutofillField::FindValueInSelectControl(*field, value, &idx)) {
257 field->value = field->option_values[idx];
258 return true;
261 // For American Express, also try filling as "AmEx".
262 if (value == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX))
263 return FillCreditCardTypeSelectControl(ASCIIToUTF16("AmEx"), field);
265 return false;
268 // Set |field_data|'s value to |number|, or possibly an appropriate substring of
269 // |number|. The |field| specifies the type of the phone and whether this is a
270 // phone prefix or suffix.
271 void FillPhoneNumberField(const AutofillField& field,
272 const base::string16& number,
273 FormFieldData* field_data) {
274 field_data->value =
275 AutofillField::GetPhoneNumberValue(field, number, *field_data);
278 // Set |field_data|'s value to |number|, or possibly an appropriate substring
279 // of |number| for cases where credit card number splits across multiple HTML
280 // form input fields.
281 // The |field| specifies the |credit_card_number_offset_| to the substring
282 // within credit card number.
283 void FillCreditCardNumberField(const AutofillField& field,
284 const base::string16& number,
285 FormFieldData* field_data) {
286 base::string16 value = number;
288 // |field|'s max_length truncates credit card number to fit within.
289 if (field.credit_card_number_offset() < value.length())
290 value = value.substr(field.credit_card_number_offset());
292 field_data->value = value;
295 // Fills in the select control |field| with |value|. If an exact match is not
296 // found, falls back to alternate filling strategies based on the |type|.
297 bool FillSelectControl(const AutofillType& type,
298 const base::string16& value,
299 const std::string& app_locale,
300 FormFieldData* field) {
301 DCHECK_EQ("select-one", field->form_control_type);
303 // Guard against corrupted values passed over IPC.
304 if (field->option_values.size() != field->option_contents.size())
305 return false;
307 if (value.empty())
308 return false;
310 // First, search for exact matches.
311 if (SetSelectControlValue(value, field))
312 return true;
314 // If that fails, try specific fallbacks based on the field type.
315 ServerFieldType storable_type = type.GetStorableType();
316 if (storable_type == ADDRESS_HOME_STATE) {
317 return FillStateSelectControl(value, field);
318 } else if (storable_type == ADDRESS_HOME_COUNTRY) {
319 return FillCountrySelectControl(value, app_locale, field);
320 } else if (storable_type == CREDIT_CARD_EXP_MONTH) {
321 return FillExpirationMonthSelectControl(value, app_locale, field);
322 } else if (storable_type == CREDIT_CARD_EXP_2_DIGIT_YEAR ||
323 storable_type == CREDIT_CARD_EXP_4_DIGIT_YEAR) {
324 return FillYearSelectControl(value, field);
325 } else if (storable_type == CREDIT_CARD_TYPE) {
326 return FillCreditCardTypeSelectControl(value, field);
329 return false;
332 // Fills in the month control |field| with |value|. |value| should be a date
333 // formatted as MM/YYYY. If it isn't, filling will fail.
334 bool FillMonthControl(const base::string16& value, FormFieldData* field) {
335 // Autofill formats a combined date as month/year.
336 std::vector<base::string16> pieces;
337 base::SplitString(value, base::char16('/'), &pieces);
338 if (pieces.size() != 2)
339 return false;
341 // HTML5 input="month" is formatted as year-month.
342 base::string16 month = pieces[0];
343 base::string16 year = pieces[1];
344 if ((month.size() != 1 && month.size() != 2) || year.size() != 4)
345 return false;
347 // HTML5 input="month" expects zero-padded months.
348 if (month.size() == 1)
349 month = ASCIIToUTF16("0") + month;
351 field->value = year + ASCIIToUTF16("-") + month;
352 return true;
355 // Fills |field| with the street address in |value|. Translates newlines into
356 // equivalent separators when necessary, i.e. when filling a single-line field.
357 // The separators depend on |address_language_code|.
358 void FillStreetAddress(const base::string16& value,
359 const std::string& address_language_code,
360 FormFieldData* field) {
361 if (field->form_control_type == "textarea") {
362 field->value = value;
363 return;
366 AddressData address_data;
367 address_data.language_code = address_language_code;
368 base::SplitString(base::UTF16ToUTF8(value), '\n', &address_data.address_line);
369 std::string line;
370 GetStreetAddressLinesAsSingleLine(address_data, &line);
371 field->value = base::UTF8ToUTF16(line);
374 std::string Hash32Bit(const std::string& str) {
375 std::string hash_bin = base::SHA1HashString(str);
376 DCHECK_EQ(base::kSHA1Length, hash_bin.length());
378 uint32 hash32 = ((hash_bin[0] & 0xFF) << 24) |
379 ((hash_bin[1] & 0xFF) << 16) |
380 ((hash_bin[2] & 0xFF) << 8) |
381 (hash_bin[3] & 0xFF);
383 return base::UintToString(hash32);
386 base::string16 RemoveWhitespace(const base::string16& value) {
387 base::string16 stripped_value;
388 base::RemoveChars(value, base::kWhitespaceUTF16, &stripped_value);
389 return stripped_value;
392 } // namespace
394 AutofillField::AutofillField()
395 : server_type_(NO_SERVER_DATA),
396 heuristic_type_(UNKNOWN_TYPE),
397 html_type_(HTML_TYPE_UNKNOWN),
398 html_mode_(HTML_MODE_NONE),
399 phone_part_(IGNORED),
400 credit_card_number_offset_(0) {
403 AutofillField::AutofillField(const FormFieldData& field,
404 const base::string16& unique_name)
405 : FormFieldData(field),
406 unique_name_(unique_name),
407 server_type_(NO_SERVER_DATA),
408 heuristic_type_(UNKNOWN_TYPE),
409 html_type_(HTML_TYPE_UNKNOWN),
410 html_mode_(HTML_MODE_NONE),
411 phone_part_(IGNORED),
412 credit_card_number_offset_(0) {
415 AutofillField::~AutofillField() {}
417 void AutofillField::set_heuristic_type(ServerFieldType type) {
418 if (type >= 0 && type < MAX_VALID_FIELD_TYPE &&
419 type != FIELD_WITH_DEFAULT_VALUE) {
420 heuristic_type_ = type;
421 } else {
422 NOTREACHED();
423 // This case should not be reachable; but since this has potential
424 // implications on data uploaded to the server, better safe than sorry.
425 heuristic_type_ = UNKNOWN_TYPE;
429 void AutofillField::set_server_type(ServerFieldType type) {
430 // Chrome no longer supports fax numbers, but the server still does.
431 if (type >= PHONE_FAX_NUMBER && type <= PHONE_FAX_WHOLE_NUMBER)
432 return;
434 server_type_ = type;
437 void AutofillField::SetHtmlType(HtmlFieldType type, HtmlFieldMode mode) {
438 html_type_ = type;
439 html_mode_ = mode;
441 if (type == HTML_TYPE_TEL_LOCAL_PREFIX)
442 phone_part_ = PHONE_PREFIX;
443 else if (type == HTML_TYPE_TEL_LOCAL_SUFFIX)
444 phone_part_ = PHONE_SUFFIX;
445 else
446 phone_part_ = IGNORED;
449 AutofillType AutofillField::Type() const {
450 if (html_type_ != HTML_TYPE_UNKNOWN)
451 return AutofillType(html_type_, html_mode_);
453 if (server_type_ != NO_SERVER_DATA) {
454 // See http://crbug.com/429236 for background on why we might not always
455 // believe the server.
456 // See http://crbug.com/441488 for potential improvements to the server
457 // which may obviate the need for this logic.
458 bool believe_server =
459 !(server_type_ == NAME_FULL && heuristic_type_ == CREDIT_CARD_NAME) &&
460 !(server_type_ == CREDIT_CARD_NAME && heuristic_type_ == NAME_FULL) &&
461 // CVC is sometimes type="password", which tricks the server.
462 // See http://crbug.com/469007
463 !(AutofillType(server_type_).group() == PASSWORD_FIELD &&
464 heuristic_type_ == CREDIT_CARD_VERIFICATION_CODE);
465 if (believe_server)
466 return AutofillType(server_type_);
469 return AutofillType(heuristic_type_);
472 bool AutofillField::IsEmpty() const {
473 return value.empty();
476 std::string AutofillField::FieldSignature() const {
477 std::string field_name = base::UTF16ToUTF8(name);
478 std::string field_string = field_name + "&" + form_control_type;
479 return Hash32Bit(field_string);
482 bool AutofillField::IsFieldFillable() const {
483 return !Type().IsUnknown();
486 // static
487 bool AutofillField::FillFormField(const AutofillField& field,
488 const base::string16& value,
489 const std::string& address_language_code,
490 const std::string& app_locale,
491 FormFieldData* field_data) {
492 AutofillType type = field.Type();
494 if (type.GetStorableType() == PHONE_HOME_NUMBER) {
495 FillPhoneNumberField(field, value, field_data);
496 return true;
497 } else if (field_data->form_control_type == "select-one") {
498 return FillSelectControl(type, value, app_locale, field_data);
499 } else if (field_data->form_control_type == "month") {
500 return FillMonthControl(value, field_data);
501 } else if (type.GetStorableType() == ADDRESS_HOME_STREET_ADDRESS) {
502 FillStreetAddress(value, address_language_code, field_data);
503 return true;
504 } else if (type.GetStorableType() == CREDIT_CARD_NUMBER) {
505 FillCreditCardNumberField(field, value, field_data);
506 return true;
509 field_data->value = value;
510 return true;
513 base::string16 AutofillField::GetPhoneNumberValue(
514 const AutofillField& field,
515 const base::string16& number,
516 const FormFieldData& field_data) {
517 // Check to see if the size field matches the "prefix" or "suffix" size.
518 // If so, return the appropriate substring.
519 if (number.length() !=
520 PhoneNumber::kPrefixLength + PhoneNumber::kSuffixLength) {
521 return number;
524 if (field.phone_part() == AutofillField::PHONE_PREFIX ||
525 field_data.max_length == PhoneNumber::kPrefixLength) {
526 return
527 number.substr(PhoneNumber::kPrefixOffset, PhoneNumber::kPrefixLength);
530 if (field.phone_part() == AutofillField::PHONE_SUFFIX ||
531 field_data.max_length == PhoneNumber::kSuffixLength) {
532 return
533 number.substr(PhoneNumber::kSuffixOffset, PhoneNumber::kSuffixLength);
536 return number;
539 // static
540 bool AutofillField::FindValueInSelectControl(const FormFieldData& field,
541 const base::string16& value,
542 size_t* index) {
543 l10n::CaseInsensitiveCompare compare;
544 // Strip off spaces for all values in the comparisons.
545 const base::string16 value_stripped = RemoveWhitespace(value);
547 for (size_t i = 0; i < field.option_values.size(); ++i) {
548 base::string16 option_value = RemoveWhitespace(field.option_values[i]);
549 if (compare.StringsEqual(value_stripped, option_value)) {
550 if (index)
551 *index = i;
552 return true;
555 base::string16 option_contents = RemoveWhitespace(field.option_contents[i]);
556 if (compare.StringsEqual(value_stripped, option_contents)) {
557 if (index)
558 *index = i;
559 return true;
562 return false;
565 } // namespace autofill