1 // Copyright (c) 2011 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 "chrome/browser/autofill/autofill_manager.h" 6 7 #include <stddef.h> 8 9 #include <limits> 10 #include <map> 11 #include <set> 12 #include <utility> 13 14 #include "base/logging.h" 15 #include "base/string16.h" 16 #include "base/string_util.h" 17 #include "base/utf_string_conversions.h" 18 #ifndef ANDROID 19 #include "chrome/browser/autocomplete_history_manager.h" 20 #include "chrome/browser/autofill/autofill_cc_infobar_delegate.h" 21 #endif 22 #include "chrome/browser/autofill/autofill_field.h" 23 #include "chrome/browser/autofill/autofill_metrics.h" 24 #include "chrome/browser/autofill/autofill_profile.h" 25 #include "chrome/browser/autofill/autofill_type.h" 26 #include "chrome/browser/autofill/credit_card.h" 27 #include "chrome/browser/autofill/form_structure.h" 28 #include "chrome/browser/autofill/personal_data_manager.h" 29 #include "chrome/browser/autofill/phone_number.h" 30 #include "chrome/browser/autofill/select_control_handler.h" 31 #include "chrome/browser/prefs/pref_service.h" 32 #include "chrome/browser/profiles/profile.h" 33 #ifndef ANDROID 34 #include "chrome/browser/ui/browser.h" 35 #include "chrome/browser/ui/browser_list.h" 36 #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" 37 #include "chrome/common/autofill_messages.h" 38 #endif 39 #include "chrome/common/guid.h" 40 #include "chrome/common/pref_names.h" 41 #include "chrome/common/url_constants.h" 42 #ifndef ANDROID 43 #include "content/browser/renderer_host/render_view_host.h" 44 #include "content/browser/tab_contents/tab_contents.h" 45 #include "content/common/notification_service.h" 46 #include "content/common/notification_source.h" 47 #include "content/common/notification_type.h" 48 #endif 49 #include "googleurl/src/gurl.h" 50 #include "grit/generated_resources.h" 51 #ifndef ANDROID 52 #include "ipc/ipc_message_macros.h" 53 #endif 54 #include "ui/base/l10n/l10n_util.h" 55 #include "webkit/glue/form_data.h" 56 #include "webkit/glue/form_field.h" 57 58 using webkit_glue::FormData; 59 using webkit_glue::FormField; 60 61 namespace { 62 63 // We only send a fraction of the forms to upload server. 64 // The rate for positive/negative matches potentially could be different. 65 const double kAutofillPositiveUploadRateDefaultValue = 0.20; 66 const double kAutofillNegativeUploadRateDefaultValue = 0.20; 67 68 const string16::value_type kCreditCardPrefix[] = {'*', 0}; 69 70 // Removes duplicate suggestions whilst preserving their original order. 71 void RemoveDuplicateSuggestions(std::vector<string16>* values, 72 std::vector<string16>* labels, 73 std::vector<string16>* icons, 74 std::vector<int>* unique_ids) { 75 DCHECK_EQ(values->size(), labels->size()); 76 DCHECK_EQ(values->size(), icons->size()); 77 DCHECK_EQ(values->size(), unique_ids->size()); 78 79 std::set<std::pair<string16, string16> > seen_suggestions; 80 std::vector<string16> values_copy; 81 std::vector<string16> labels_copy; 82 std::vector<string16> icons_copy; 83 std::vector<int> unique_ids_copy; 84 85 for (size_t i = 0; i < values->size(); ++i) { 86 const std::pair<string16, string16> suggestion((*values)[i], (*labels)[i]); 87 if (seen_suggestions.insert(suggestion).second) { 88 values_copy.push_back((*values)[i]); 89 labels_copy.push_back((*labels)[i]); 90 icons_copy.push_back((*icons)[i]); 91 unique_ids_copy.push_back((*unique_ids)[i]); 92 } 93 } 94 95 values->swap(values_copy); 96 labels->swap(labels_copy); 97 icons->swap(icons_copy); 98 unique_ids->swap(unique_ids_copy); 99 } 100 101 // Precondition: |form| should be the cached version of the form that is to be 102 // autofilled, and |field| should be the field in the |form| that corresponds to 103 // the initiating field. |is_filling_credit_card| should be true if filling 104 // credit card data, false otherwise. 105 // Fills |section_start| and |section_end| so that [section_start, section_end) 106 // gives the bounds of logical section within |form| that includes |field|. 107 // Logical sections are identified by two heuristics: 108 // 1. The fields in the section must all be profile or credit card fields, 109 // depending on whether |is_filling_credit_card| is true. 110 // 2. A logical section should not include multiple fields of the same autofill 111 // type (except for phone/fax numbers, as described below). 112 void FindSectionBounds(const FormStructure& form, 113 const AutofillField& field, 114 bool is_filling_credit_card, 115 size_t* section_start, 116 size_t* section_end) { 117 DCHECK(section_start); 118 DCHECK(section_end); 119 120 // By default, the relevant section is the entire form. 121 *section_start = 0; 122 *section_end = form.field_count(); 123 124 std::set<AutofillFieldType> seen_types; 125 bool initiating_field_is_in_current_section = false; 126 for (size_t i = 0; i < form.field_count(); ++i) { 127 const AutofillField* current_field = form.field(i); 128 const AutofillFieldType current_type = 129 AutofillType::GetEquivalentFieldType(current_field->type()); 130 131 // Fields of unknown type don't help us to distinguish sections. 132 if (current_type == UNKNOWN_TYPE) 133 continue; 134 135 bool already_saw_current_type = seen_types.count(current_type) > 0; 136 // Forms often ask for multiple phone numbers -- e.g. both a daytime and 137 // evening phone number. Our phone and fax number detection is also 138 // generally a little off. Hence, ignore both field types as a signal here. 139 // Likewise, forms often ask for multiple email addresses, so ignore this 140 // field type as well. 141 AutofillType::FieldTypeGroup current_type_group = 142 AutofillType(current_type).group(); 143 if (current_type_group == AutofillType::PHONE_HOME || 144 current_type_group == AutofillType::PHONE_FAX || 145 current_type_group == AutofillType::EMAIL) 146 already_saw_current_type = false; 147 148 // If we are filling credit card data, the relevant section should include 149 // only credit card fields; and similarly for profile data. 150 bool is_credit_card_field = current_type_group == AutofillType::CREDIT_CARD; 151 bool is_appropriate_type = is_credit_card_field == is_filling_credit_card; 152 153 if (already_saw_current_type || !is_appropriate_type) { 154 if (initiating_field_is_in_current_section) { 155 // We reached the end of the section containing the initiating field. 156 *section_end = i; 157 break; 158 } 159 160 // We reached the end of a section, so start a new section. 161 seen_types.clear(); 162 163 // Only include the current field in the new section if it matches the 164 // type of data we are filling. 165 if (is_appropriate_type) { 166 *section_start = i; 167 } else { 168 *section_start = i + 1; 169 continue; 170 } 171 } 172 173 seen_types.insert(current_type); 174 175 if (current_field == &field) 176 initiating_field_is_in_current_section = true; 177 } 178 179 // We should have found the initiating field. 180 DCHECK(initiating_field_is_in_current_section); 181 } 182 183 // Precondition: |form_structure| and |form| should correspond to the same 184 // logical form. Returns true if the relevant portion of |form| is auto-filled. 185 // The "relevant" fields in |form| are ones corresponding to fields in 186 // |form_structure| with indices in the range [section_start, section_end). 187 bool SectionIsAutofilled(const FormStructure* form_structure, 188 const webkit_glue::FormData& form, 189 size_t section_start, 190 size_t section_end) { 191 // TODO(isherman): It would be nice to share most of this code with the loop 192 // in |FillAutofillFormData()|, but I don't see a particularly clean way to do 193 // that. 194 195 // The list of fields in |form_structure| and |form.fields| often match 196 // directly and we can fill these corresponding fields; however, when the 197 // |form_structure| and |form.fields| do not match directly we search 198 // ahead in the |form_structure| for the matching field. 199 for (size_t i = section_start, j = 0; 200 i < section_end && j < form.fields.size(); 201 j++) { 202 size_t k = i; 203 204 // Search forward in the |form_structure| for a corresponding field. 205 while (k < form_structure->field_count() && 206 *form_structure->field(k) != form.fields[j]) { 207 k++; 208 } 209 210 // If we didn't find a match, continue on to the next |form| field. 211 if (k >= form_structure->field_count()) 212 continue; 213 214 AutofillType autofill_type(form_structure->field(k)->type()); 215 if (form.fields[j].is_autofilled) 216 return true; 217 218 // We found a matching field in the |form_structure| so we 219 // proceed to the next |form| field, and the next |form_structure|. 220 ++i; 221 } 222 223 return false; 224 } 225 226 bool FormIsHTTPS(FormStructure* form) { 227 return form->source_url().SchemeIs(chrome::kHttpsScheme); 228 } 229 230 } // namespace 231 232 AutofillManager::AutofillManager(TabContents* tab_contents) 233 : TabContentsObserver(tab_contents), 234 personal_data_(NULL), 235 download_manager_(tab_contents->profile()), 236 disable_download_manager_requests_(false), 237 metric_logger_(new AutofillMetrics), 238 has_logged_autofill_enabled_(false), 239 has_logged_address_suggestions_count_(false) { 240 DCHECK(tab_contents); 241 242 // |personal_data_| is NULL when using TestTabContents. 243 personal_data_ = 244 tab_contents->profile()->GetOriginalProfile()->GetPersonalDataManager(); 245 download_manager_.SetObserver(this); 246 } 247 248 AutofillManager::~AutofillManager() { 249 download_manager_.SetObserver(NULL); 250 } 251 252 #ifndef ANDROID 253 // static 254 void AutofillManager::RegisterBrowserPrefs(PrefService* prefs) { 255 prefs->RegisterDictionaryPref(prefs::kAutofillDialogPlacement); 256 } 257 #endif 258 259 #ifndef ANDROID 260 // static 261 void AutofillManager::RegisterUserPrefs(PrefService* prefs) { 262 prefs->RegisterBooleanPref(prefs::kAutofillEnabled, true); 263 #if defined(OS_MACOSX) 264 prefs->RegisterBooleanPref(prefs::kAutofillAuxiliaryProfilesEnabled, true); 265 #else 266 prefs->RegisterBooleanPref(prefs::kAutofillAuxiliaryProfilesEnabled, false); 267 #endif 268 prefs->RegisterDoublePref(prefs::kAutofillPositiveUploadRate, 269 kAutofillPositiveUploadRateDefaultValue); 270 prefs->RegisterDoublePref(prefs::kAutofillNegativeUploadRate, 271 kAutofillNegativeUploadRateDefaultValue); 272 } 273 #endif 274 275 #ifndef ANDROID 276 void AutofillManager::DidNavigateMainFramePostCommit( 277 const NavigationController::LoadCommittedDetails& details, 278 const ViewHostMsg_FrameNavigate_Params& params) { 279 Reset(); 280 } 281 #endif 282 283 #ifndef ANDROID 284 bool AutofillManager::OnMessageReceived(const IPC::Message& message) { 285 bool handled = true; 286 IPC_BEGIN_MESSAGE_MAP(AutofillManager, message) 287 IPC_MESSAGE_HANDLER(AutofillHostMsg_FormsSeen, OnFormsSeen) 288 IPC_MESSAGE_HANDLER(AutofillHostMsg_FormSubmitted, OnFormSubmitted) 289 IPC_MESSAGE_HANDLER(AutofillHostMsg_QueryFormFieldAutofill, 290 OnQueryFormFieldAutofill) 291 IPC_MESSAGE_HANDLER(AutofillHostMsg_ShowAutofillDialog, 292 OnShowAutofillDialog) 293 IPC_MESSAGE_HANDLER(AutofillHostMsg_FillAutofillFormData, 294 OnFillAutofillFormData) 295 IPC_MESSAGE_HANDLER(AutofillHostMsg_DidFillAutofillFormData, 296 OnDidFillAutofillFormData) 297 IPC_MESSAGE_HANDLER(AutofillHostMsg_DidShowAutofillSuggestions, 298 OnDidShowAutofillSuggestions) 299 IPC_MESSAGE_UNHANDLED(handled = false) 300 IPC_END_MESSAGE_MAP() 301 302 return handled; 303 } 304 #endif 305 306 void AutofillManager::OnFormSubmitted(const FormData& form) { 307 // Let AutoComplete know as well. 308 #ifndef ANDROID 309 TabContentsWrapper* wrapper = 310 TabContentsWrapper::GetCurrentWrapperForContents(tab_contents()); 311 wrapper->autocomplete_history_manager()->OnFormSubmitted(form); 312 #endif 313 314 if (!IsAutofillEnabled()) 315 return; 316 317 if (tab_contents()->profile()->IsOffTheRecord()) 318 return; 319 320 // Don't save data that was submitted through JavaScript. 321 if (!form.user_submitted) 322 return; 323 324 // Grab a copy of the form data. 325 FormStructure submitted_form(form); 326 327 // Disregard forms that we wouldn't ever autofill in the first place. 328 if (!submitted_form.ShouldBeParsed(true)) 329 return; 330 331 // Ignore forms not present in our cache. These are typically forms with 332 // wonky JavaScript that also makes them not auto-fillable. 333 FormStructure* cached_submitted_form; 334 if (!FindCachedForm(form, &cached_submitted_form)) 335 return; 336 337 DeterminePossibleFieldTypesForUpload(&submitted_form); 338 UploadFormData(submitted_form); 339 340 submitted_form.UpdateFromCache(*cached_submitted_form); 341 submitted_form.LogQualityMetrics(*metric_logger_); 342 343 if (!submitted_form.IsAutofillable(true)) 344 return; 345 346 ImportFormData(submitted_form); 347 } 348 349 void AutofillManager::OnFormsSeen(const std::vector<FormData>& forms) { 350 bool enabled = IsAutofillEnabled(); 351 if (!has_logged_autofill_enabled_) { 352 metric_logger_->LogIsAutofillEnabledAtPageLoad(enabled); 353 has_logged_autofill_enabled_ = true; 354 } 355 356 if (!enabled) 357 return; 358 359 ParseForms(forms); 360 } 361 362 #ifdef ANDROID 363 bool AutofillManager::OnQueryFormFieldAutofill( 364 #else 365 void AutofillManager::OnQueryFormFieldAutofill( 366 #endif 367 int query_id, 368 const webkit_glue::FormData& form, 369 const webkit_glue::FormField& field) { 370 std::vector<string16> values; 371 std::vector<string16> labels; 372 std::vector<string16> icons; 373 std::vector<int> unique_ids; 374 375 #ifdef ANDROID 376 AutoFillHost* host = NULL; 377 #else 378 RenderViewHost* host = NULL; 379 #endif 380 FormStructure* form_structure = NULL; 381 AutofillField* autofill_field = NULL; 382 if (GetHost( 383 personal_data_->profiles(), personal_data_->credit_cards(), &host) && 384 FindCachedFormAndField(form, field, &form_structure, &autofill_field) && 385 // Don't send suggestions for forms that aren't auto-fillable. 386 form_structure->IsAutofillable(false)) { 387 AutofillFieldType type = autofill_field->type(); 388 bool is_filling_credit_card = 389 (AutofillType(type).group() == AutofillType::CREDIT_CARD); 390 if (is_filling_credit_card) { 391 GetCreditCardSuggestions( 392 form_structure, field, type, &values, &labels, &icons, &unique_ids); 393 } else { 394 GetProfileSuggestions( 395 form_structure, field, type, &values, &labels, &icons, &unique_ids); 396 } 397 398 DCHECK_EQ(values.size(), labels.size()); 399 DCHECK_EQ(values.size(), icons.size()); 400 DCHECK_EQ(values.size(), unique_ids.size()); 401 402 if (!values.empty()) { 403 #ifndef ANDROID 404 // Don't provide Autofill suggestions when Autofill is disabled, and don't 405 // provide credit card suggestions for non-HTTPS pages. However, provide a 406 // warning to the user in these cases. 407 int warning = 0; 408 if (!form_structure->IsAutofillable(true)) 409 warning = IDS_AUTOFILL_WARNING_FORM_DISABLED; 410 else if (is_filling_credit_card && !FormIsHTTPS(form_structure)) 411 warning = IDS_AUTOFILL_WARNING_INSECURE_CONNECTION; 412 if (warning) { 413 values.assign(1, l10n_util::GetStringUTF16(warning)); 414 labels.assign(1, string16()); 415 icons.assign(1, string16()); 416 unique_ids.assign(1, -1); 417 } else { 418 size_t section_start, section_end; 419 FindSectionBounds(*form_structure, *autofill_field, 420 is_filling_credit_card, §ion_start, §ion_end); 421 422 bool section_is_autofilled = SectionIsAutofilled(form_structure, 423 form, 424 section_start, 425 section_end); 426 if (section_is_autofilled) { 427 // If the relevant section is auto-filled and the renderer is querying 428 // for suggestions, then the user is editing the value of a field. 429 // In this case, mimic autocomplete: don't display labels or icons, 430 // as that information is redundant. 431 labels.assign(labels.size(), string16()); 432 icons.assign(icons.size(), string16()); 433 } 434 435 // When filling credit card suggestions, the values and labels are 436 // typically obfuscated, which makes detecting duplicates hard. Since 437 // duplicates only tend to be a problem when filling address forms 438 // anyway, only don't de-dup credit card suggestions. 439 if (!is_filling_credit_card) 440 RemoveDuplicateSuggestions(&values, &labels, &icons, &unique_ids); 441 442 // The first time we show suggestions on this page, log the number of 443 // suggestions shown. 444 if (!has_logged_address_suggestions_count_ && !section_is_autofilled) { 445 metric_logger_->LogAddressSuggestionsCount(values.size()); 446 has_logged_address_suggestions_count_ = true; 447 } 448 } 449 #endif 450 } 451 #ifdef ANDROID 452 else { 453 return false; 454 } 455 #endif 456 } 457 #ifdef ANDROID 458 else { 459 return false; 460 } 461 #endif 462 463 #ifdef ANDROID 464 host->AutoFillSuggestionsReturned(values, labels, icons, unique_ids); 465 return true; 466 #else 467 // Add the results from AutoComplete. They come back asynchronously, so we 468 // hand off what we generated and they will send the results back to the 469 // renderer. 470 TabContentsWrapper* wrapper = 471 TabContentsWrapper::GetCurrentWrapperForContents(tab_contents()); 472 wrapper->autocomplete_history_manager()->OnGetAutocompleteSuggestions( 473 query_id, field.name, field.value, values, labels, icons, unique_ids); 474 #endif 475 } 476 477 void AutofillManager::OnFillAutofillFormData(int query_id, 478 const FormData& form, 479 const FormField& field, 480 int unique_id) { 481 const std::vector<AutofillProfile*>& profiles = personal_data_->profiles(); 482 const std::vector<CreditCard*>& credit_cards = personal_data_->credit_cards(); 483 #ifdef ANDROID 484 AutoFillHost* host = NULL; 485 #else 486 RenderViewHost* host = NULL; 487 #endif 488 FormStructure* form_structure = NULL; 489 AutofillField* autofill_field = NULL; 490 if (!GetHost(profiles, credit_cards, &host) || 491 !FindCachedFormAndField(form, field, &form_structure, &autofill_field)) 492 return; 493 494 DCHECK(host); 495 DCHECK(form_structure); 496 DCHECK(autofill_field); 497 498 // Unpack the |unique_id| into component parts. 499 GUIDPair cc_guid; 500 GUIDPair profile_guid; 501 UnpackGUIDs(unique_id, &cc_guid, &profile_guid); 502 DCHECK(!guid::IsValidGUID(cc_guid.first) || 503 !guid::IsValidGUID(profile_guid.first)); 504 505 // Find the profile that matches the |profile_id|, if one is specified. 506 const AutofillProfile* profile = NULL; 507 if (guid::IsValidGUID(profile_guid.first)) { 508 for (std::vector<AutofillProfile*>::const_iterator iter = profiles.begin(); 509 iter != profiles.end(); ++iter) { 510 if ((*iter)->guid() == profile_guid.first) { 511 profile = *iter; 512 break; 513 } 514 } 515 DCHECK(profile); 516 } 517 518 // Find the credit card that matches the |cc_id|, if one is specified. 519 const CreditCard* credit_card = NULL; 520 if (guid::IsValidGUID(cc_guid.first)) { 521 for (std::vector<CreditCard*>::const_iterator iter = credit_cards.begin(); 522 iter != credit_cards.end(); ++iter) { 523 if ((*iter)->guid() == cc_guid.first) { 524 credit_card = *iter; 525 break; 526 } 527 } 528 DCHECK(credit_card); 529 } 530 531 if (!profile && !credit_card) 532 return; 533 534 // Find the section of the form that we are autofilling. 535 size_t section_start, section_end; 536 FindSectionBounds(*form_structure, *autofill_field, (credit_card != NULL), 537 §ion_start, §ion_end); 538 539 FormData result = form; 540 541 // If the relevant section is auto-filled, we should fill |field| but not the 542 // rest of the form. 543 if (SectionIsAutofilled(form_structure, form, section_start, section_end)) { 544 for (std::vector<FormField>::iterator iter = result.fields.begin(); 545 iter != result.fields.end(); ++iter) { 546 if ((*iter) == field) { 547 AutofillFieldType field_type = autofill_field->type(); 548 if (profile) { 549 DCHECK_NE(AutofillType::CREDIT_CARD, 550 AutofillType(field_type).group()); 551 FillFormField(profile, field_type, profile_guid.second, &(*iter)); 552 } else { 553 DCHECK_EQ(AutofillType::CREDIT_CARD, 554 AutofillType(field_type).group()); 555 FillCreditCardFormField(credit_card, field_type, &(*iter)); 556 } 557 break; 558 } 559 } 560 561 #ifdef ANDROID 562 host->AutoFillFormDataFilled(query_id, result); 563 #else 564 host->Send(new AutofillMsg_FormDataFilled(host->routing_id(), query_id, 565 result)); 566 #endif 567 return; 568 } 569 570 // The list of fields in |form_structure| and |result.fields| often match 571 // directly and we can fill these corresponding fields; however, when the 572 // |form_structure| and |result.fields| do not match directly we search 573 // ahead in the |form_structure| for the matching field. 574 // See unit tests: AutofillManagerTest.FormChangesRemoveField and 575 // AutofillManagerTest.FormChangesAddField for usage. 576 for (size_t i = section_start, j = 0; 577 i < section_end && j < result.fields.size(); 578 j++) { 579 size_t k = i; 580 581 // Search forward in the |form_structure| for a corresponding field. 582 while (k < section_end && *form_structure->field(k) != result.fields[j]) { 583 k++; 584 } 585 586 // If we've found a match then fill the |result| field with the found 587 // field in the |form_structure|. 588 if (k >= section_end) 589 continue; 590 591 AutofillFieldType field_type = form_structure->field(k)->type(); 592 FieldTypeGroup field_group_type = AutofillType(field_type).group(); 593 if (field_group_type != AutofillType::NO_GROUP) { 594 if (profile) { 595 DCHECK_NE(AutofillType::CREDIT_CARD, field_group_type); 596 // If the field being filled is the field that the user initiated the 597 // fill from, then take the multi-profile "variant" into account. 598 // Otherwise fill with the default (zeroth) variant. 599 if (result.fields[j] == field) { 600 FillFormField(profile, field_type, profile_guid.second, 601 &result.fields[j]); 602 } else { 603 FillFormField(profile, field_type, 0, &result.fields[j]); 604 } 605 } else { 606 DCHECK_EQ(AutofillType::CREDIT_CARD, field_group_type); 607 FillCreditCardFormField(credit_card, field_type, &result.fields[j]); 608 } 609 } 610 611 // We found a matching field in the |form_structure| so we 612 // proceed to the next |result| field, and the next |form_structure|. 613 ++i; 614 } 615 autofilled_forms_signatures_.push_front(form_structure->FormSignature()); 616 617 #ifdef ANDROID 618 host->AutoFillFormDataFilled(query_id, result); 619 #else 620 host->Send(new AutofillMsg_FormDataFilled( 621 host->routing_id(), query_id, result)); 622 #endif 623 } 624 625 void AutofillManager::OnShowAutofillDialog() { 626 #ifndef ANDROID 627 Browser* browser = BrowserList::GetLastActive(); 628 if (browser) 629 browser->ShowOptionsTab(chrome::kAutofillSubPage); 630 #endif 631 } 632 633 void AutofillManager::OnDidFillAutofillFormData() { 634 #ifndef ANDROID 635 NotificationService::current()->Notify( 636 NotificationType::AUTOFILL_DID_FILL_FORM_DATA, 637 Source<RenderViewHost>(tab_contents()->render_view_host()), 638 NotificationService::NoDetails()); 639 #endif 640 } 641 642 void AutofillManager::OnDidShowAutofillSuggestions() { 643 #ifndef ANDROID 644 NotificationService::current()->Notify( 645 NotificationType::AUTOFILL_DID_SHOW_SUGGESTIONS, 646 Source<RenderViewHost>(tab_contents()->render_view_host()), 647 NotificationService::NoDetails()); 648 #endif 649 } 650 651 void AutofillManager::OnLoadedAutofillHeuristics( 652 const std::string& heuristic_xml) { 653 // TODO(jhawkins): Store |upload_required| in the AutofillManager. 654 UploadRequired upload_required; 655 FormStructure::ParseQueryResponse(heuristic_xml, 656 form_structures_.get(), 657 &upload_required, 658 *metric_logger_); 659 } 660 661 void AutofillManager::OnUploadedAutofillHeuristics( 662 const std::string& form_signature) { 663 } 664 665 void AutofillManager::OnHeuristicsRequestError( 666 const std::string& form_signature, 667 AutofillDownloadManager::AutofillRequestType request_type, 668 int http_error) { 669 } 670 671 bool AutofillManager::IsAutofillEnabled() const { 672 #ifdef ANDROID 673 // TODO: This should be a setting in the android UI. 674 return true; 675 #else 676 return const_cast<AutofillManager*>(this)->tab_contents()->profile()-> 677 GetPrefs()->GetBoolean(prefs::kAutofillEnabled); 678 #endif 679 } 680 681 void AutofillManager::DeterminePossibleFieldTypesForUpload( 682 FormStructure* submitted_form) { 683 for (size_t i = 0; i < submitted_form->field_count(); i++) { 684 const AutofillField* field = submitted_form->field(i); 685 FieldTypeSet field_types; 686 personal_data_->GetPossibleFieldTypes(field->value, &field_types); 687 688 DCHECK(!field_types.empty()); 689 submitted_form->set_possible_types(i, field_types); 690 } 691 } 692 693 void AutofillManager::ImportFormData(const FormStructure& submitted_form) { 694 std::vector<const FormStructure*> submitted_forms; 695 submitted_forms.push_back(&submitted_form); 696 697 const CreditCard* imported_credit_card; 698 if (!personal_data_->ImportFormData(submitted_forms, &imported_credit_card)) 699 return; 700 701 #ifndef ANDROID 702 // If credit card information was submitted, show an infobar to offer to save 703 // it. 704 scoped_ptr<const CreditCard> scoped_credit_card(imported_credit_card); 705 if (imported_credit_card && tab_contents()) { 706 tab_contents()->AddInfoBar( 707 new AutofillCCInfoBarDelegate(tab_contents(), 708 scoped_credit_card.release(), 709 personal_data_, 710 metric_logger_.get())); 711 } 712 #endif 713 } 714 715 void AutofillManager::UploadFormData(const FormStructure& submitted_form) { 716 if (!disable_download_manager_requests_) { 717 bool was_autofilled = false; 718 // Check if the form among last 3 forms that were auto-filled. 719 // Clear older signatures. 720 std::list<std::string>::iterator it; 721 int total_form_checked = 0; 722 for (it = autofilled_forms_signatures_.begin(); 723 it != autofilled_forms_signatures_.end() && total_form_checked < 3; 724 ++it, ++total_form_checked) { 725 if (*it == submitted_form.FormSignature()) 726 was_autofilled = true; 727 } 728 // Remove outdated form signatures. 729 if (total_form_checked == 3 && it != autofilled_forms_signatures_.end()) { 730 autofilled_forms_signatures_.erase(it, 731 autofilled_forms_signatures_.end()); 732 } 733 download_manager_.StartUploadRequest(submitted_form, was_autofilled); 734 } 735 } 736 737 void AutofillManager::Reset() { 738 form_structures_.reset(); 739 has_logged_autofill_enabled_ = false; 740 has_logged_address_suggestions_count_ = false; 741 } 742 743 AutofillManager::AutofillManager(TabContents* tab_contents, 744 PersonalDataManager* personal_data) 745 : TabContentsObserver(tab_contents), 746 personal_data_(personal_data), 747 download_manager_(NULL), 748 disable_download_manager_requests_(true), 749 metric_logger_(new AutofillMetrics), 750 has_logged_autofill_enabled_(false), 751 has_logged_address_suggestions_count_(false) { 752 DCHECK(tab_contents); 753 } 754 755 void AutofillManager::set_metric_logger( 756 const AutofillMetrics* metric_logger) { 757 metric_logger_.reset(metric_logger); 758 } 759 760 bool AutofillManager::GetHost(const std::vector<AutofillProfile*>& profiles, 761 const std::vector<CreditCard*>& credit_cards, 762 #ifdef ANDROID 763 AutoFillHost** host) { 764 #else 765 RenderViewHost** host) const { 766 #endif 767 if (!IsAutofillEnabled()) 768 return false; 769 770 // No autofill data to return if the profiles are empty. 771 if (profiles.empty() && credit_cards.empty()) 772 return false; 773 774 #ifdef ANDROID 775 *host = tab_contents()->autofill_host(); 776 #else 777 *host = tab_contents()->render_view_host(); 778 #endif 779 if (!*host) 780 return false; 781 782 return true; 783 } 784 785 bool AutofillManager::FindCachedForm(const FormData& form, 786 FormStructure** form_structure) const { 787 // Find the FormStructure that corresponds to |form|. 788 *form_structure = NULL; 789 for (std::vector<FormStructure*>::const_iterator iter = 790 form_structures_.begin(); 791 iter != form_structures_.end(); ++iter) { 792 if (**iter == form) { 793 *form_structure = *iter; 794 break; 795 } 796 } 797 798 if (!(*form_structure)) 799 return false; 800 801 return true; 802 } 803 804 bool AutofillManager::FindCachedFormAndField(const FormData& form, 805 const FormField& field, 806 FormStructure** form_structure, 807 AutofillField** autofill_field) { 808 // Find the FormStructure that corresponds to |form|. 809 if (!FindCachedForm(form, form_structure)) 810 return false; 811 812 // No data to return if there are no auto-fillable fields. 813 if (!(*form_structure)->autofill_count()) 814 return false; 815 816 // Find the AutofillField that corresponds to |field|. 817 *autofill_field = NULL; 818 for (std::vector<AutofillField*>::const_iterator iter = 819 (*form_structure)->begin(); 820 iter != (*form_structure)->end(); ++iter) { 821 // The field list is terminated with a NULL AutofillField, so don't try to 822 // dereference it. 823 if (!*iter) 824 break; 825 826 if ((**iter) == field) { 827 *autofill_field = *iter; 828 break; 829 } 830 } 831 832 if (!(*autofill_field)) 833 return false; 834 835 return true; 836 } 837 838 void AutofillManager::GetProfileSuggestions(FormStructure* form, 839 const FormField& field, 840 AutofillFieldType type, 841 std::vector<string16>* values, 842 std::vector<string16>* labels, 843 std::vector<string16>* icons, 844 std::vector<int>* unique_ids) { 845 const std::vector<AutofillProfile*>& profiles = personal_data_->profiles(); 846 if (!field.is_autofilled) { 847 std::vector<AutofillProfile*> matched_profiles; 848 for (std::vector<AutofillProfile*>::const_iterator iter = profiles.begin(); 849 iter != profiles.end(); ++iter) { 850 AutofillProfile* profile = *iter; 851 852 // The value of the stored data for this field type in the |profile|. 853 std::vector<string16> multi_values; 854 profile->GetMultiInfo(type, &multi_values); 855 856 for (size_t i = 0; i < multi_values.size(); ++i) { 857 if (!multi_values[i].empty() && 858 StartsWith(multi_values[i], field.value, false)) { 859 matched_profiles.push_back(profile); 860 values->push_back(multi_values[i]); 861 unique_ids->push_back(PackGUIDs(GUIDPair(std::string(), 0), 862 GUIDPair(profile->guid(), i))); 863 break; 864 } 865 } 866 } 867 868 std::vector<AutofillFieldType> form_fields; 869 form_fields.reserve(form->field_count()); 870 for (std::vector<AutofillField*>::const_iterator iter = form->begin(); 871 iter != form->end(); ++iter) { 872 // The field list is terminated with a NULL AutofillField, so don't try to 873 // dereference it. 874 if (!*iter) 875 break; 876 form_fields.push_back((*iter)->type()); 877 } 878 879 AutofillProfile::CreateInferredLabels(&matched_profiles, &form_fields, 880 type, 1, labels); 881 882 // No icons for profile suggestions. 883 icons->resize(values->size()); 884 } else { 885 for (std::vector<AutofillProfile*>::const_iterator iter = profiles.begin(); 886 iter != profiles.end(); ++iter) { 887 AutofillProfile* profile = *iter; 888 889 // The value of the stored data for this field type in the |profile|. 890 std::vector<string16> multi_values; 891 profile->GetMultiInfo(type, &multi_values); 892 893 for (size_t i = 0; i < multi_values.size(); ++i) { 894 if (!multi_values[i].empty() && 895 StringToLowerASCII(multi_values[i]) 896 == StringToLowerASCII(field.value)) { 897 for (size_t j = 0; j < multi_values.size(); ++j) { 898 if (!multi_values[j].empty()) { 899 values->push_back(multi_values[j]); 900 unique_ids->push_back(PackGUIDs(GUIDPair(std::string(), 0), 901 GUIDPair(profile->guid(), j))); 902 } 903 } 904 // We've added all the values for this profile so move on to the next. 905 break; 906 } 907 } 908 } 909 910 // No labels for previously filled fields. 911 labels->resize(values->size()); 912 913 // No icons for profile suggestions. 914 icons->resize(values->size()); 915 } 916 } 917 918 void AutofillManager::GetCreditCardSuggestions(FormStructure* form, 919 const FormField& field, 920 AutofillFieldType type, 921 std::vector<string16>* values, 922 std::vector<string16>* labels, 923 std::vector<string16>* icons, 924 std::vector<int>* unique_ids) { 925 for (std::vector<CreditCard*>::const_iterator iter = 926 personal_data_->credit_cards().begin(); 927 iter != personal_data_->credit_cards().end(); ++iter) { 928 CreditCard* credit_card = *iter; 929 930 // The value of the stored data for this field type in the |credit_card|. 931 string16 creditcard_field_value = credit_card->GetInfo(type); 932 if (!creditcard_field_value.empty() && 933 StartsWith(creditcard_field_value, field.value, false)) { 934 if (type == CREDIT_CARD_NUMBER) 935 creditcard_field_value = credit_card->ObfuscatedNumber(); 936 937 string16 label; 938 if (credit_card->number().empty()) { 939 // If there is no CC number, return name to show something. 940 label = credit_card->GetInfo(CREDIT_CARD_NAME); 941 } else { 942 label = kCreditCardPrefix; 943 label.append(credit_card->LastFourDigits()); 944 } 945 946 values->push_back(creditcard_field_value); 947 labels->push_back(label); 948 icons->push_back(UTF8ToUTF16(credit_card->type())); 949 unique_ids->push_back(PackGUIDs(GUIDPair(credit_card->guid(), 0), 950 GUIDPair(std::string(), 0))); 951 } 952 } 953 } 954 955 void AutofillManager::FillCreditCardFormField(const CreditCard* credit_card, 956 AutofillFieldType type, 957 webkit_glue::FormField* field) { 958 DCHECK(credit_card); 959 DCHECK_EQ(AutofillType::CREDIT_CARD, AutofillType(type).group()); 960 DCHECK(field); 961 962 if (field->form_control_type == ASCIIToUTF16("select-one")) { 963 autofill::FillSelectControl(*credit_card, type, field); 964 } else if (field->form_control_type == ASCIIToUTF16("month")) { 965 // HTML5 input="month" consists of year-month. 966 string16 year = credit_card->GetInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR); 967 string16 month = credit_card->GetInfo(CREDIT_CARD_EXP_MONTH); 968 if (!year.empty() && !month.empty()) { 969 // Fill the value only if |credit_card| includes both year and month 970 // information. 971 field->value = year + ASCIIToUTF16("-") + month; 972 } 973 } else { 974 string16 value = credit_card->GetInfo(type); 975 if (type == CREDIT_CARD_NUMBER) 976 value = CreditCard::StripSeparators(value); 977 field->value = value; 978 } 979 } 980 981 void AutofillManager::FillFormField(const AutofillProfile* profile, 982 AutofillFieldType type, 983 size_t variant, 984 webkit_glue::FormField* field) { 985 DCHECK(profile); 986 DCHECK_NE(AutofillType::CREDIT_CARD, AutofillType(type).group()); 987 DCHECK(field); 988 989 if (AutofillType(type).subgroup() == AutofillType::PHONE_NUMBER) { 990 FillPhoneNumberField(profile, type, variant, field); 991 } else { 992 if (field->form_control_type == ASCIIToUTF16("select-one")) { 993 autofill::FillSelectControl(*profile, type, field); 994 } else { 995 std::vector<string16> values; 996 profile->GetMultiInfo(type, &values); 997 DCHECK(variant < values.size()); 998 field->value = values[variant]; 999 } 1000 } 1001 } 1002 1003 void AutofillManager::FillPhoneNumberField(const AutofillProfile* profile, 1004 AutofillFieldType type, 1005 size_t variant, 1006 webkit_glue::FormField* field) { 1007 // If we are filling a phone number, check to see if the size field 1008 // matches the "prefix" or "suffix" sizes and fill accordingly. 1009 std::vector<string16> values; 1010 profile->GetMultiInfo(type, &values); 1011 DCHECK(variant < values.size()); 1012 string16 number = values[variant]; 1013 bool has_valid_suffix_and_prefix = (number.length() == 1014 static_cast<size_t>(PhoneNumber::kPrefixLength + 1015 PhoneNumber::kSuffixLength)); 1016 if (has_valid_suffix_and_prefix && 1017 field->max_length == PhoneNumber::kPrefixLength) { 1018 number = number.substr(PhoneNumber::kPrefixOffset, 1019 PhoneNumber::kPrefixLength); 1020 field->value = number; 1021 } else if (has_valid_suffix_and_prefix && 1022 field->max_length == PhoneNumber::kSuffixLength) { 1023 number = number.substr(PhoneNumber::kSuffixOffset, 1024 PhoneNumber::kSuffixLength); 1025 field->value = number; 1026 } else { 1027 field->value = number; 1028 } 1029 } 1030 1031 void AutofillManager::ParseForms(const std::vector<FormData>& forms) { 1032 std::vector<FormStructure*> non_queryable_forms; 1033 for (std::vector<FormData>::const_iterator iter = forms.begin(); 1034 iter != forms.end(); ++iter) { 1035 scoped_ptr<FormStructure> form_structure(new FormStructure(*iter)); 1036 if (!form_structure->ShouldBeParsed(false)) 1037 continue; 1038 1039 form_structure->DetermineHeuristicTypes(); 1040 1041 // Set aside forms with method GET so that they are not included in the 1042 // query to the server. 1043 if (form_structure->ShouldBeParsed(true)) 1044 form_structures_.push_back(form_structure.release()); 1045 else 1046 non_queryable_forms.push_back(form_structure.release()); 1047 } 1048 1049 // If none of the forms were parsed, no use querying the server. 1050 if (!form_structures_.empty() && !disable_download_manager_requests_) 1051 download_manager_.StartQueryRequest(form_structures_, *metric_logger_); 1052 1053 for (std::vector<FormStructure*>::const_iterator iter = 1054 non_queryable_forms.begin(); 1055 iter != non_queryable_forms.end(); ++iter) { 1056 form_structures_.push_back(*iter); 1057 } 1058 } 1059 1060 int AutofillManager::GUIDToID(const GUIDPair& guid) { 1061 static int last_id = 1; 1062 1063 if (!guid::IsValidGUID(guid.first)) 1064 return 0; 1065 1066 std::map<GUIDPair, int>::const_iterator iter = guid_id_map_.find(guid); 1067 if (iter == guid_id_map_.end()) { 1068 guid_id_map_[guid] = last_id; 1069 id_guid_map_[last_id] = guid; 1070 return last_id++; 1071 } else { 1072 return iter->second; 1073 } 1074 } 1075 1076 const AutofillManager::GUIDPair AutofillManager::IDToGUID(int id) { 1077 if (id == 0) 1078 return GUIDPair(std::string(), 0); 1079 1080 std::map<int, GUIDPair>::const_iterator iter = id_guid_map_.find(id); 1081 if (iter == id_guid_map_.end()) { 1082 NOTREACHED(); 1083 return GUIDPair(std::string(), 0); 1084 } 1085 1086 return iter->second; 1087 } 1088 1089 // When sending IDs (across processes) to the renderer we pack credit card and 1090 // profile IDs into a single integer. Credit card IDs are sent in the high 1091 // word and profile IDs are sent in the low word. 1092 int AutofillManager::PackGUIDs(const GUIDPair& cc_guid, 1093 const GUIDPair& profile_guid) { 1094 int cc_id = GUIDToID(cc_guid); 1095 int profile_id = GUIDToID(profile_guid); 1096 1097 DCHECK(cc_id <= std::numeric_limits<unsigned short>::max()); 1098 DCHECK(profile_id <= std::numeric_limits<unsigned short>::max()); 1099 1100 return cc_id << std::numeric_limits<unsigned short>::digits | profile_id; 1101 } 1102 1103 // When receiving IDs (across processes) from the renderer we unpack credit card 1104 // and profile IDs from a single integer. Credit card IDs are stored in the 1105 // high word and profile IDs are stored in the low word. 1106 void AutofillManager::UnpackGUIDs(int id, 1107 GUIDPair* cc_guid, 1108 GUIDPair* profile_guid) { 1109 int cc_id = id >> std::numeric_limits<unsigned short>::digits & 1110 std::numeric_limits<unsigned short>::max(); 1111 int profile_id = id & std::numeric_limits<unsigned short>::max(); 1112 1113 *cc_guid = IDToGUID(cc_id); 1114 *profile_guid = IDToGUID(profile_id); 1115 } 1116