Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / components / autofill / core / browser / autofill_field.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/autofill/core/browser/autofill_field.h"
6
7 #include "base/command_line.h"
8 #include "base/logging.h"
9 #include "base/sha1.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"
23
24 using ::i18n::addressinput::AddressData;
25 using ::i18n::addressinput::GetStreetAddressLinesAsSingleLine;
26 using base::ASCIIToUTF16;
27 using base::StringToInt;
28
29 namespace autofill {
30 namespace {
31
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",
36 };
37
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",
42 };
43
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);
49
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];
57       break;
58     }
59
60     if (value_lowercase == base::StringToLowerASCII(field->option_values[i]) ||
61         value_lowercase ==
62             base::StringToLowerASCII(field->option_contents[i])) {
63       // A match, but not in the same case. Save it in case an exact match is
64       // not found.
65       best_match = field->option_values[i];
66     }
67   }
68
69   if (best_match.empty())
70     return false;
71
72   field->value = best_match;
73   return true;
74 }
75
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());
82   int best_match = -1;
83
84   for (size_t i = 0; i < field->option_values.size(); ++i) {
85     if (base::StringToLowerASCII(field->option_values[i]).find(value_lowercase) !=
86             std::string::npos ||
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()) {
93         best_match = i;
94       }
95     }
96   }
97
98   if (best_match >= 0) {
99     field->value = field->option_values[best_match];
100     return true;
101   }
102
103   return false;
104 }
105
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());
114
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) !=
119         tokenized.end()) {
120       field->value = field->option_values[i];
121       return true;
122     }
123
124     base::SplitStringAlongWhitespace(
125         base::StringToLowerASCII(field->option_contents[i]), &tokenized);
126     if (std::find(tokenized.begin(), tokenized.end(), value_lowercase) !=
127         tokenized.end()) {
128       field->value = field->option_values[i];
129       return true;
130     }
131   }
132
133   return false;
134 }
135
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) {
141     int option;
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];
145       return true;
146     }
147   }
148
149   return false;
150 }
151
152 bool FillStateSelectControl(const base::string16& value,
153                             FormFieldData* field) {
154   base::string16 full, abbreviation;
155   state_names::GetNameAndAbbreviation(value, &full, &abbreviation);
156
157   // Try an exact match of the abbreviation first.
158   if (!abbreviation.empty() && SetSelectControlValue(abbreviation, field)) {
159     return true;
160   }
161
162   // Try an exact match of the full name.
163   if (!full.empty() && SetSelectControlValue(full, field)) {
164     return true;
165   }
166
167   // Then try an inexact match of the full name.
168   if (!full.empty() && SetSelectControlValueSubstringMatch(full, field)) {
169     return true;
170   }
171
172   // Then try an inexact match of the abbreviation name.
173   return !abbreviation.empty() &&
174       SetSelectControlValueTokenMatch(abbreviation, field);
175 }
176
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())
182     return false;
183
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;
194       return true;
195     }
196   }
197
198   return false;
199 }
200
201 bool FillExpirationMonthSelectControl(const base::string16& value,
202                                       FormFieldData* field) {
203   int index = 0;
204   if (!StringToInt(value, &index) ||
205       index <= 0 ||
206       static_cast<size_t>(index) >= arraysize(kMonthsFull))
207     return false;
208
209   bool filled =
210       SetSelectControlValue(ASCIIToUTF16(kMonthsAbbreviated[index]), field) ||
211       SetSelectControlValue(ASCIIToUTF16(kMonthsFull[index]), field) ||
212       FillNumericSelectControl(index, field);
213   return filled;
214 }
215
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) {
219   int year_int;
220   int str_int;
221   if (!StringToInt(year, &year_int) || !StringToInt(str, &str_int))
222     return false;
223
224   return (year_int % 100) == (str_int % 100);
225 }
226
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)
232     return false;
233
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];
239       return true;
240     }
241   }
242
243   return false;
244 }
245
246 // Try to fill a credit card type |value| (Visa, MasterCard, etc.) into the
247 // given |field|.
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,
253                     &value_stripped);
254
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);
262
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];
268       return true;
269     }
270   }
271
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);
275
276   return false;
277 }
278
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) {
285   field_data->value =
286       AutofillField::GetPhoneNumberValue(field, number, *field_data);
287 }
288
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;
298
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());
302
303   field_data->value = value;
304 }
305
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);
313
314   // Guard against corrupted values passed over IPC.
315   if (field->option_values.size() != field->option_contents.size())
316     return false;
317
318   if (value.empty())
319     return false;
320
321   // First, search for exact matches.
322   if (SetSelectControlValue(value, field))
323     return true;
324
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);
338   }
339
340   return false;
341 }
342
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)
350     return false;
351
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)
356     return false;
357
358   // HTML5 input="month" expects zero-padded months.
359   if (month.size() == 1)
360     month = ASCIIToUTF16("0") + month;
361
362   field->value = year + ASCIIToUTF16("-") + month;
363   return true;
364 }
365
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;
374     return;
375   }
376
377   AddressData address_data;
378   address_data.language_code = address_language_code;
379   base::SplitString(base::UTF16ToUTF8(value), '\n', &address_data.address_line);
380   std::string line;
381   GetStreetAddressLinesAsSingleLine(address_data, &line);
382   field->value = base::UTF8ToUTF16(line);
383 }
384
385 std::string Hash32Bit(const std::string& str) {
386   std::string hash_bin = base::SHA1HashString(str);
387   DCHECK_EQ(20U, hash_bin.length());
388
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);
393
394   return base::UintToString(hash32);
395 }
396
397 }  // namespace
398
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) {
406 }
407
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) {
418 }
419
420 AutofillField::~AutofillField() {}
421
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;
426   } else {
427     NOTREACHED();
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;
431   }
432 }
433
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)
437     return;
438
439   server_type_ = type;
440 }
441
442 void AutofillField::SetHtmlType(HtmlFieldType type, HtmlFieldMode mode) {
443   html_type_ = type;
444   html_mode_ = mode;
445
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;
450   else
451     phone_part_ = IGNORED;
452 }
453
454 AutofillType AutofillField::Type() const {
455   if (html_type_ != HTML_TYPE_UNKNOWN)
456     return AutofillType(html_type_, html_mode_);
457
458   if (server_type_ != NO_SERVER_DATA)
459     return AutofillType(server_type_);
460
461   return AutofillType(heuristic_type_);
462 }
463
464 bool AutofillField::IsEmpty() const {
465   return value.empty();
466 }
467
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);
472 }
473
474 bool AutofillField::IsFieldFillable() const {
475   return (should_autocomplete ||
476           base::CommandLine::ForCurrentProcess()->HasSwitch(
477               switches::kIgnoreAutocompleteOffForAutofill)) &&
478          !Type().IsUnknown();
479 }
480
481 // static
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();
488
489   if (type.GetStorableType() == PHONE_HOME_NUMBER) {
490     FillPhoneNumberField(field, value, field_data);
491     return true;
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);
498     return true;
499   } else if (type.GetStorableType() == CREDIT_CARD_NUMBER) {
500     FillCreditCardNumberField(field, value, field_data);
501     return true;
502   }
503
504   field_data->value = value;
505   return true;
506 }
507
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) {
516     return number;
517   }
518
519   if (field.phone_part() == AutofillField::PHONE_PREFIX ||
520       field_data.max_length == PhoneNumber::kPrefixLength) {
521     return
522         number.substr(PhoneNumber::kPrefixOffset, PhoneNumber::kPrefixLength);
523   }
524
525   if (field.phone_part() == AutofillField::PHONE_SUFFIX ||
526       field_data.max_length == PhoneNumber::kSuffixLength) {
527     return
528         number.substr(PhoneNumber::kSuffixOffset, PhoneNumber::kSuffixLength);
529   }
530
531   return number;
532 }
533
534 }  // namespace autofill