1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
6 #define COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
12 #include <unordered_set>
15 #include "base/gtest_prod_util.h"
16 #include "base/macros.h"
17 #include "base/observer_list.h"
18 #include "base/strings/string16.h"
19 #include "build/build_config.h"
20 #include "components/autofill/core/browser/autofill_profile.h"
21 #include "components/autofill/core/browser/credit_card.h"
22 #include "components/autofill/core/browser/field_types.h"
23 #include "components/autofill/core/browser/suggestion.h"
24 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
25 #include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h"
26 #include "components/keyed_service/core/keyed_service.h"
27 #include "components/prefs/pref_member.h"
28 #include "components/webdata/common/web_data_service_consumer.h"
29 #if defined(OS_ANDROID)
30 #include "net/url_request/url_request_context_getter.h"
33 class AccountTrackerService;
36 class RemoveAutofillTester;
37 class SigninManagerBase;
40 class AutofillInteractiveTest;
43 class PersonalDataManagerObserver;
44 class PersonalDataManagerFactory;
45 } // namespace autofill
47 namespace autofill_helper {
48 void SetProfiles(int, std::vector<autofill::AutofillProfile>*);
49 void SetCreditCards(int, std::vector<autofill::CreditCard>*);
50 } // namespace autofill_helper
58 extern const char kFrecencyFieldTrialName[];
59 extern const char kFrecencyFieldTrialStateEnabled[];
60 extern const char kFrecencyFieldTrialLimitParam[];
62 // Handles loading and saving Autofill profile information to the web database.
63 // This class also stores the profiles loaded from the database for use during
65 class PersonalDataManager : public KeyedService,
66 public WebDataServiceConsumer,
67 public AutofillWebDataServiceObserverOnUIThread {
69 explicit PersonalDataManager(const std::string& app_locale);
70 ~PersonalDataManager() override;
72 // Kicks off asynchronous loading of profiles and credit cards.
73 // |pref_service| must outlive this instance. |is_off_the_record| informs
74 // this instance whether the user is currently operating in an off-the-record
76 void Init(scoped_refptr<AutofillWebDataService> database,
77 PrefService* pref_service,
78 AccountTrackerService* account_tracker,
79 SigninManagerBase* signin_manager,
80 bool is_off_the_record);
82 // Called once the sync service is known to be instantiated. Note that it may
83 // not be started, but it's preferences can be queried.
84 void OnSyncServiceInitialized(syncer::SyncService* sync_service);
86 // WebDataServiceConsumer:
87 void OnWebDataServiceRequestDone(
88 WebDataServiceBase::Handle h,
89 std::unique_ptr<WDTypedResult> result) override;
91 // AutofillWebDataServiceObserverOnUIThread:
92 void AutofillMultipleChanged() override;
93 void SyncStarted(syncer::ModelType model_type) override;
95 // Adds a listener to be notified of PersonalDataManager events.
96 virtual void AddObserver(PersonalDataManagerObserver* observer);
98 // Removes |observer| as an observer of this PersonalDataManager.
99 virtual void RemoveObserver(PersonalDataManagerObserver* observer);
101 // Scans the given |form| for importable Autofill data. If the form includes
102 // sufficient address data for a new profile, it is immediately imported. If
103 // the form includes sufficient credit card data for a new credit card, it is
104 // stored into |imported_credit_card| so that we can prompt the user whether
105 // to save this data. If the form contains credit card data already present in
106 // a local credit card entry *and* |should_return_local_card| is true, the
107 // data is stored into |imported_credit_card| so that we can prompt the user
108 // whether to upload it.
109 // Returns |true| if sufficient address or credit card data was found.
110 bool ImportFormData(const FormStructure& form,
111 bool should_return_local_card,
112 std::unique_ptr<CreditCard>* imported_credit_card);
114 // Called to indicate |data_model| was used (to fill in a form). Updates
115 // the database accordingly. Can invalidate |data_model|, particularly if
116 // it's a Mac address book entry.
117 virtual void RecordUseOf(const AutofillDataModel& data_model);
119 // Saves |imported_profile| to the WebDB if it exists. Returns the guid of
120 // the new or updated profile, or the empty string if no profile was saved.
121 virtual std::string SaveImportedProfile(
122 const AutofillProfile& imported_profile);
124 // Saves |imported_credit_card| to the WebDB if it exists. Returns the guid of
125 // of the new or updated card, or the empty string if no card was saved.
126 virtual std::string SaveImportedCreditCard(
127 const CreditCard& imported_credit_card);
129 // Adds |profile| to the web database.
130 void AddProfile(const AutofillProfile& profile);
132 // Updates |profile| which already exists in the web database.
133 void UpdateProfile(const AutofillProfile& profile);
135 // Removes the profile or credit card represented by |guid|.
136 virtual void RemoveByGUID(const std::string& guid);
138 // Returns the profile with the specified |guid|, or NULL if there is no
139 // profile with the specified |guid|. Both web and auxiliary profiles may
141 AutofillProfile* GetProfileByGUID(const std::string& guid);
143 // Adds |credit_card| to the web database.
144 void AddCreditCard(const CreditCard& credit_card);
146 // Updates |credit_card| which already exists in the web database. This
147 // can only be used on local credit cards.
148 virtual void UpdateCreditCard(const CreditCard& credit_card);
150 // Update a server card. Only the full number and masked/unmasked
151 // status can be changed. Looks up the card by server ID.
152 virtual void UpdateServerCreditCard(const CreditCard& credit_card);
154 // Updates the billing address for the server |credit_card|. Looks up the card
156 void UpdateServerCardBillingAddress(const CreditCard& credit_card);
158 // Resets the card for |guid| to the masked state.
159 void ResetFullServerCard(const std::string& guid);
161 // Resets all unmasked cards to the masked state.
162 void ResetFullServerCards();
164 // Deletes all server profiles and cards (both masked and unmasked).
165 void ClearAllServerData();
167 // Sets a server credit card for test.
168 void AddServerCreditCardForTest(std::unique_ptr<CreditCard> credit_card);
170 // Returns the credit card with the specified |guid|, or NULL if there is
171 // no credit card with the specified |guid|.
172 virtual CreditCard* GetCreditCardByGUID(const std::string& guid);
174 // Gets the field types availabe in the stored address and credit card data.
175 void GetNonEmptyTypes(ServerFieldTypeSet* non_empty_types);
177 // Returns true if the credit card information is stored with a password.
180 // Returns whether the personal data has been loaded from the web database.
181 virtual bool IsDataLoaded() const;
183 // This PersonalDataManager owns these profiles and credit cards. Their
184 // lifetime is until the web database is updated with new profile and credit
185 // card information, respectively. |GetProfiles()| returns both web and
186 // auxiliary profiles. |web_profiles()| returns only web profiles.
187 virtual const std::vector<AutofillProfile*>& GetProfiles() const;
188 virtual std::vector<AutofillProfile*> web_profiles() const;
189 // Returns just LOCAL_CARD cards.
190 virtual std::vector<CreditCard*> GetLocalCreditCards() const;
191 // Returns all credit cards, server and local.
192 virtual const std::vector<CreditCard*>& GetCreditCards() const;
194 // Returns true if there is some data synced from Wallet.
195 bool HasServerData() const;
197 // Returns the profiles to suggest to the user, ordered by frecency.
198 const std::vector<AutofillProfile*> GetProfilesToSuggest() const;
200 // Loads profiles that can suggest data for |type|. |field_contents| is the
201 // part the user has already typed. |field_is_autofilled| is true if the field
202 // has already been autofilled. |other_field_types| represents the rest of
204 std::vector<Suggestion> GetProfileSuggestions(
205 const AutofillType& type,
206 const base::string16& field_contents,
207 bool field_is_autofilled,
208 const std::vector<ServerFieldType>& other_field_types);
210 // Returns the credit cards to suggest to the user. Those have been deduped
211 // and ordered by frecency with the expired cards put at the end of the
213 const std::vector<CreditCard*> GetCreditCardsToSuggest() const;
215 // Gets credit cards that can suggest data for |type|. See
216 // GetProfileSuggestions for argument descriptions. The variant in each
217 // GUID pair should be ignored.
218 std::vector<Suggestion> GetCreditCardSuggestions(
219 const AutofillType& type,
220 const base::string16& field_contents);
222 // Re-loads profiles and credit cards from the WebDatabase asynchronously.
223 // In the general case, this is a no-op and will re-create the same
224 // in-memory model as existed prior to the call. If any change occurred to
225 // profiles in the WebDatabase directly, as is the case if the browser sync
226 // engine processed a change from the cloud, we will learn of these as a
227 // result of this call.
229 // Also see SetProfile for more details.
230 virtual void Refresh();
232 const std::string& app_locale() const { return app_locale_; }
234 // Checks suitability of |profile| for adding to the user's set of profiles.
235 static bool IsValidLearnableProfile(const AutofillProfile& profile,
236 const std::string& app_locale);
238 // Merges |new_profile| into one of the |existing_profiles| if possible;
239 // otherwise appends |new_profile| to the end of that list. Fills
240 // |merged_profiles| with the result. Returns the |guid| of the new or updated
242 std::string MergeProfile(
243 const AutofillProfile& new_profile,
244 std::vector<std::unique_ptr<AutofillProfile>>* existing_profiles,
245 const std::string& app_locale,
246 std::vector<AutofillProfile>* merged_profiles);
248 // Returns true if |country_code| is a country that the user is likely to
249 // be associated with the user. More concretely, it checks if there are any
250 // addresses with this country or if the user's system timezone is in the
252 virtual bool IsCountryOfInterest(const std::string& country_code) const;
254 // Returns our best guess for the country a user is likely to use when
255 // inputting a new address. The value is calculated once and cached, so it
256 // will only update when Chrome is restarted.
257 virtual const std::string& GetDefaultCountryCodeForNewAddress() const;
259 // De-dupe credit card to suggest. Full server cards are preferred over their
260 // local duplicates, and local cards are preferred over their masked server
262 static void DedupeCreditCardToSuggest(
263 std::list<CreditCard*>* cards_to_suggest);
265 // Notifies test observers that personal data has changed.
266 void NotifyPersonalDataChangedForTest() {
267 NotifyPersonalDataChanged();
270 #if defined(OS_ANDROID)
271 // Sets the URL request context getter to be used when normalizing addresses
272 // with libaddressinput's address validator.
273 void SetURLRequestContextGetter(
274 net::URLRequestContextGetter* context_getter) {
275 context_getter_ = context_getter;
278 // Returns the class used to fetch the address validation rules.
279 net::URLRequestContextGetter* GetURLRequestContextGetter() const {
280 return context_getter_.get();
285 // Only PersonalDataManagerFactory and certain tests can create instances of
286 // PersonalDataManager.
287 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FirstMiddleLast);
288 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtStartup);
289 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
290 DedupeProfiles_ProfilesToDelete);
291 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest, ApplyProfileUseDatesFix);
292 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
293 ApplyProfileUseDatesFix_NotAppliedTwice);
294 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
295 ApplyDedupingRoutine_MergedProfileValues);
296 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
297 ApplyDedupingRoutine_VerifiedProfileFirst);
298 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
299 ApplyDedupingRoutine_VerifiedProfileLast);
300 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
301 ApplyDedupingRoutine_MultipleVerifiedProfiles);
302 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
303 ApplyDedupingRoutine_FeatureDisabled);
304 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
305 ApplyDedupingRoutine_NopIfZeroProfiles);
306 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
307 ApplyDedupingRoutine_NopIfOneProfile);
308 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
309 ApplyDedupingRoutine_OncePerVersion);
310 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
311 ApplyDedupingRoutine_MultipleDedupes);
312 friend class autofill::AutofillInteractiveTest;
313 friend class autofill::AutofillTest;
314 friend class autofill::PersonalDataManagerFactory;
315 friend class PersonalDataManagerTest;
316 friend class ProfileSyncServiceAutofillTest;
317 friend class ::RemoveAutofillTester;
318 friend std::default_delete<PersonalDataManager>;
319 friend void autofill_helper::SetProfiles(
320 int, std::vector<autofill::AutofillProfile>*);
321 friend void autofill_helper::SetCreditCards(
322 int, std::vector<autofill::CreditCard>*);
323 friend void SetTestProfiles(
324 Browser* browser, std::vector<AutofillProfile>* profiles);
326 // Sets |web_profiles_| to the contents of |profiles| and updates the web
327 // database by adding, updating and removing profiles.
328 // The relationship between this and Refresh is subtle.
329 // A call to |SetProfiles| could include out-of-date data that may conflict
330 // if we didn't refresh-to-latest before an Autofill window was opened for
331 // editing. |SetProfiles| is implemented to make a "best effort" to apply the
332 // changes, but in extremely rare edge cases it is possible not all of the
333 // updates in |profiles| make it to the DB. This is why SetProfiles will
334 // invoke Refresh after finishing, to ensure we get into a
335 // consistent state. See Refresh for details.
336 virtual void SetProfiles(std::vector<AutofillProfile>* profiles);
338 // Sets |credit_cards_| to the contents of |credit_cards| and updates the web
339 // database by adding, updating and removing credit cards.
340 void SetCreditCards(std::vector<CreditCard>* credit_cards);
342 // Loads the saved profiles from the web database.
343 virtual void LoadProfiles();
345 // Loads the saved credit cards from the web database.
346 virtual void LoadCreditCards();
348 // Cancels a pending query to the web database. |handle| is a pointer to the
350 void CancelPendingQuery(WebDataServiceBase::Handle* handle);
352 // Notifies observers that personal data has changed.
353 void NotifyPersonalDataChanged();
355 // The first time this is called, logs an UMA metric for the number of
356 // profiles the user has. On subsequent calls, does nothing.
357 void LogProfileCount() const;
359 // The first time this is called, logs an UMA metric for the number of local
360 // credit cards the user has. On subsequent calls, does nothing.
361 void LogLocalCreditCardCount() const;
363 // The first time this is called, logs an UMA metric for the number of server
364 // credit cards the user has (both masked and unmasked). On subsequent calls,
366 void LogServerCreditCardCounts() const;
368 // Returns the value of the AutofillEnabled pref.
369 virtual bool IsAutofillEnabled() const;
371 // Overrideable for testing.
372 virtual std::string CountryCodeForCurrentTimezone() const;
374 // Sets which PrefService to use and observe. |pref_service| is not owned by
375 // this class and must outlive |this|.
376 void SetPrefService(PrefService* pref_service);
378 void set_database(scoped_refptr<AutofillWebDataService> database) {
379 database_ = database;
382 void set_account_tracker(AccountTrackerService* account_tracker) {
383 account_tracker_ = account_tracker;
386 void set_signin_manager(SigninManagerBase* signin_manager) {
387 signin_manager_ = signin_manager;
390 // The backing database that this PersonalDataManager uses.
391 scoped_refptr<AutofillWebDataService> database_;
393 // True if personal data has been loaded from the web database.
394 bool is_data_loaded_;
396 // The loaded web profiles. These are constructed from entries on web pages
397 // and from manually editing in the settings.
398 std::vector<std::unique_ptr<AutofillProfile>> web_profiles_;
400 // Profiles read from the user's account stored on the server.
401 mutable std::vector<std::unique_ptr<AutofillProfile>> server_profiles_;
403 // Storage for web profiles. Contents are weak references. Lifetime managed
404 // by |web_profiles_|.
405 mutable std::vector<AutofillProfile*> profiles_;
407 // Cached versions of the local and server credit cards.
408 std::vector<std::unique_ptr<CreditCard>> local_credit_cards_;
409 std::vector<std::unique_ptr<CreditCard>> server_credit_cards_;
411 // A combination of local and server credit cards. The pointers are owned
412 // by the local/sverver_credit_cards_ vectors.
413 mutable std::vector<CreditCard*> credit_cards_;
415 // When the manager makes a request from WebDataServiceBase, the database
416 // is queried on another thread, we record the query handle until we
417 // get called back. We store handles for both profile and credit card queries
418 // so they can be loaded at the same time.
419 WebDataServiceBase::Handle pending_profiles_query_;
420 WebDataServiceBase::Handle pending_server_profiles_query_;
421 WebDataServiceBase::Handle pending_creditcards_query_;
422 WebDataServiceBase::Handle pending_server_creditcards_query_;
425 base::ObserverList<PersonalDataManagerObserver> observers_;
428 // Finds the country code that occurs most frequently among all profiles.
429 // Prefers verified profiles over unverified ones.
430 std::string MostCommonCountryCodeFromProfiles() const;
432 // Called when the value of prefs::kAutofillEnabled changes.
433 void EnabledPrefChanged();
435 // Go through the |form| fields and attempt to extract and import valid
436 // address profiles. Returns true on extraction success of at least one
437 // profile. There are many reasons that extraction may fail (see
439 bool ImportAddressProfiles(const FormStructure& form);
441 // Helper method for ImportAddressProfiles which only considers the fields for
442 // a specified |section|.
443 bool ImportAddressProfileForSection(const FormStructure& form,
444 const std::string& section);
446 // Go through the |form| fields and attempt to extract a new credit card in
447 // |imported_credit_card|, or update an existing card.
448 // |should_return_local_card| will indicate whether |imported_credit_card| is
449 // filled even if an existing card was updated. Success is defined as having a
450 // new card to import, or having merged with an existing card.
451 bool ImportCreditCard(const FormStructure& form,
452 bool should_return_local_card,
453 std::unique_ptr<CreditCard>* imported_credit_card);
455 // Functionally equivalent to GetProfiles(), but also records metrics if
456 // |record_metrics| is true. Metrics should be recorded when the returned
457 // profiles will be used to populate the fields shown in an Autofill popup.
458 const std::vector<AutofillProfile*>& GetProfiles(
459 bool record_metrics) const;
461 // Returns credit card suggestions based on the |cards_to_suggest| and the
462 // |type| and |field_contents| of the credit card field.
463 std::vector<Suggestion> GetSuggestionsForCards(
464 const AutofillType& type,
465 const base::string16& field_contents,
466 const std::vector<CreditCard*>& cards_to_suggest) const;
468 // Runs the Autofill use date fix routine if it's never been done. Returns
469 // whether the routine was run.
470 void ApplyProfileUseDatesFix();
472 // Applies the deduping routine once per major version if the feature is
473 // enabled. Calls DedupeProfiles with the content of |web_profiles_| as a
474 // parameter. Removes the profiles to delete from the database and updates the
475 // others. Returns true if the routine was run.
476 bool ApplyDedupingRoutine();
478 // Goes through all the |existing_profiles| and merges all similar unverified
479 // profiles together. Also discards unverified profiles that are similar to a
480 // verified profile. All the profiles except the results of the merges will be
481 // added to |profile_guids_to_delete|. This routine should be run once per
484 // This method should only be called by ApplyDedupingRoutine. It is split for
487 std::vector<std::unique_ptr<AutofillProfile>>* existing_profiles,
488 std::unordered_set<AutofillProfile*>* profile_guids_to_delete);
490 const std::string app_locale_;
492 // The default country code for new addresses.
493 mutable std::string default_country_code_;
495 // The PrefService that this instance uses. Must outlive this instance.
496 PrefService* pref_service_;
498 // The AccountTrackerService that this instance uses. Must outlive this
500 AccountTrackerService* account_tracker_;
502 // The signin manager that this instance uses. Must outlive this instance.
503 SigninManagerBase* signin_manager_;
505 // Whether the user is currently operating in an off-the-record context.
506 // Default value is false.
507 bool is_off_the_record_;
509 // Whether we have already logged the number of profiles this session.
510 mutable bool has_logged_profile_count_;
512 // Whether we have already logged the number of local credit cards this
514 mutable bool has_logged_local_credit_card_count_;
516 // Whether we have already logged the number of server credit cards this
518 mutable bool has_logged_server_credit_card_counts_;
520 // An observer to listen for changes to prefs::kAutofillEnabled.
521 std::unique_ptr<BooleanPrefMember> enabled_pref_;
523 // An observer to listen for changes to prefs::kAutofillWalletImportEnabled.
524 std::unique_ptr<BooleanPrefMember> wallet_enabled_pref_;
526 // Set to true if autofill profile deduplication is enabled and needs to be
527 // performed on the next data refresh.
528 bool is_autofill_profile_dedupe_pending_ = false;
530 #if defined(OS_ANDROID)
531 // The context for the request to be used to fetch libaddressinput's address
533 scoped_refptr<net::URLRequestContextGetter> context_getter_;
536 DISALLOW_COPY_AND_ASSIGN(PersonalDataManager);
539 } // namespace autofill
541 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_