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