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_
11 #include "base/basictypes.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/observer_list.h"
15 #include "base/prefs/pref_member.h"
16 #include "base/strings/string16.h"
17 #include "components/autofill/core/browser/autofill_profile.h"
18 #include "components/autofill/core/browser/credit_card.h"
19 #include "components/autofill/core/browser/field_types.h"
20 #include "components/autofill/core/browser/suggestion.h"
21 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
22 #include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h"
23 #include "components/keyed_service/core/keyed_service.h"
24 #include "components/webdata/common/web_data_service_consumer.h"
28 class RemoveAutofillTester
;
29 class AccountTrackerService
;
32 class AutofillInteractiveTest
;
35 class PersonalDataManagerObserver
;
36 class PersonalDataManagerFactory
;
37 } // namespace autofill
39 namespace autofill_helper
{
40 void SetProfiles(int, std::vector
<autofill::AutofillProfile
>*);
41 void SetCreditCards(int, std::vector
<autofill::CreditCard
>*);
42 } // namespace autofill_helper
46 // Handles loading and saving Autofill profile information to the web database.
47 // This class also stores the profiles loaded from the database for use during
49 class PersonalDataManager
: public KeyedService
,
50 public WebDataServiceConsumer
,
51 public AutofillWebDataServiceObserverOnUIThread
{
53 explicit PersonalDataManager(const std::string
& app_locale
);
54 ~PersonalDataManager() override
;
56 // Kicks off asynchronous loading of profiles and credit cards.
57 // |pref_service| must outlive this instance. |is_off_the_record| informs
58 // this instance whether the user is currently operating in an off-the-record
60 void Init(scoped_refptr
<AutofillWebDataService
> database
,
61 PrefService
* pref_service
,
62 AccountTrackerService
* account_tracker
,
63 bool is_off_the_record
);
65 // WebDataServiceConsumer:
66 void OnWebDataServiceRequestDone(WebDataServiceBase::Handle h
,
67 const WDTypedResult
* result
) override
;
69 // AutofillWebDataServiceObserverOnUIThread:
70 void AutofillMultipleChanged() override
;
72 // Adds a listener to be notified of PersonalDataManager events.
73 virtual void AddObserver(PersonalDataManagerObserver
* observer
);
75 // Removes |observer| as an observer of this PersonalDataManager.
76 virtual void RemoveObserver(PersonalDataManagerObserver
* observer
);
78 // Scans the given |form| for importable Autofill data. If the form includes
79 // sufficient address data, it is immediately imported. If the form includes
80 // sufficient credit card data, it is stored into |credit_card|, so that we
81 // can prompt the user whether to save this data.
82 // Returns |true| if sufficient address or credit card data was found.
83 bool ImportFormData(const FormStructure
& form
,
84 scoped_ptr
<CreditCard
>* credit_card
);
86 // Called to indicate |data_model| was used (to fill in a form). Updates
87 // the database accordingly. Can invalidate |data_model|, particularly if
88 // it's a Mac address book entry.
89 virtual void RecordUseOf(const AutofillDataModel
& data_model
);
91 // Saves |imported_profile| to the WebDB if it exists. Returns the guid of
92 // the new or updated profile, or the empty string if no profile was saved.
93 virtual std::string
SaveImportedProfile(
94 const AutofillProfile
& imported_profile
);
96 // Saves a credit card value detected in |ImportedFormData|. Returns the guid
97 // of the new or updated card, or the empty string if no card was saved.
98 virtual std::string
SaveImportedCreditCard(
99 const CreditCard
& imported_credit_card
);
101 // Adds |profile| to the web database.
102 void AddProfile(const AutofillProfile
& profile
);
104 // Updates |profile| which already exists in the web database.
105 void UpdateProfile(const AutofillProfile
& profile
);
107 // Removes the profile or credit card represented by |guid|.
108 virtual void RemoveByGUID(const std::string
& guid
);
110 // Returns the profile with the specified |guid|, or NULL if there is no
111 // profile with the specified |guid|. Both web and auxiliary profiles may
113 AutofillProfile
* GetProfileByGUID(const std::string
& guid
);
115 // Adds |credit_card| to the web database.
116 void AddCreditCard(const CreditCard
& credit_card
);
118 // Updates |credit_card| which already exists in the web database. This
119 // can only be used on local credit cards.
120 void UpdateCreditCard(const CreditCard
& credit_card
);
122 // Update a server card. Only the full number and masked/unmasked
123 // status can be changed.
124 void UpdateServerCreditCard(const CreditCard
& credit_card
);
126 // Resets the card for |guid| to the masked state.
127 void ResetFullServerCard(const std::string
& guid
);
129 // Resets all unmasked cards to the masked state.
130 void ResetFullServerCards();
132 // Deletes all server profiles and cards (both masked and unmasked).
133 void ClearAllServerData();
135 // Returns the credit card with the specified |guid|, or NULL if there is
136 // no credit card with the specified |guid|.
137 CreditCard
* GetCreditCardByGUID(const std::string
& guid
);
139 // Gets the field types availabe in the stored address and credit card data.
140 void GetNonEmptyTypes(ServerFieldTypeSet
* non_empty_types
);
142 // Returns true if the credit card information is stored with a password.
145 // Returns whether the personal data has been loaded from the web database.
146 virtual bool IsDataLoaded() const;
148 // This PersonalDataManager owns these profiles and credit cards. Their
149 // lifetime is until the web database is updated with new profile and credit
150 // card information, respectively. |GetProfiles()| returns both web and
151 // auxiliary profiles. |web_profiles()| returns only web profiles.
152 virtual const std::vector
<AutofillProfile
*>& GetProfiles() const;
153 virtual const std::vector
<AutofillProfile
*>& web_profiles() const;
154 // Returns just LOCAL_CARD cards.
155 virtual const std::vector
<CreditCard
*>& GetLocalCreditCards() const;
156 // Returns all credit cards, server and local.
157 virtual const std::vector
<CreditCard
*>& GetCreditCards() const;
159 // Returns true if there is some data synced from Wallet.
160 bool HasServerData() const;
162 // Loads profiles that can suggest data for |type|. |field_contents| is the
163 // part the user has already typed. |field_is_autofilled| is true if the field
164 // has already been autofilled. |other_field_types| represents the rest of
166 std::vector
<Suggestion
> GetProfileSuggestions(
167 const AutofillType
& type
,
168 const base::string16
& field_contents
,
169 bool field_is_autofilled
,
170 const std::vector
<ServerFieldType
>& other_field_types
);
172 // Gets credit cards that can suggest data for |type|. See
173 // GetProfileSuggestions for argument descriptions. The variant in each
174 // GUID pair should be ignored.
175 std::vector
<Suggestion
> GetCreditCardSuggestions(
176 const AutofillType
& type
,
177 const base::string16
& field_contents
);
179 // Re-loads profiles and credit cards from the WebDatabase asynchronously.
180 // In the general case, this is a no-op and will re-create the same
181 // in-memory model as existed prior to the call. If any change occurred to
182 // profiles in the WebDatabase directly, as is the case if the browser sync
183 // engine processed a change from the cloud, we will learn of these as a
184 // result of this call.
186 // Also see SetProfile for more details.
187 virtual void Refresh();
189 const std::string
& app_locale() const { return app_locale_
; }
191 // Checks suitability of |profile| for adding to the user's set of profiles.
192 static bool IsValidLearnableProfile(const AutofillProfile
& profile
,
193 const std::string
& app_locale
);
195 // Merges |new_profile| into one of the |existing_profiles| if possible;
196 // otherwise appends |new_profile| to the end of that list. Fills
197 // |merged_profiles| with the result. Returns the |guid| of the new or updated
199 static std::string
MergeProfile(
200 const AutofillProfile
& new_profile
,
201 const std::vector
<AutofillProfile
*>& existing_profiles
,
202 const std::string
& app_locale
,
203 std::vector
<AutofillProfile
>* merged_profiles
);
205 // Returns true if |country_code| is a country that the user is likely to
206 // be associated with the user. More concretely, it checks if there are any
207 // addresses with this country or if the user's system timezone is in the
209 virtual bool IsCountryOfInterest(const std::string
& country_code
) const;
211 // Returns our best guess for the country a user is likely to use when
212 // inputting a new address. The value is calculated once and cached, so it
213 // will only update when Chrome is restarted.
214 virtual const std::string
& GetDefaultCountryCodeForNewAddress() const;
216 #if defined(OS_MACOSX) && !defined(OS_IOS)
217 // If Chrome has not prompted for access to the user's address book, the
218 // method prompts the user for permission and blocks the process. Otherwise,
219 // this method has no effect. The return value reflects whether the user was
220 // prompted with a modal dialog.
221 bool AccessAddressBook();
223 // Whether an autofill suggestion should be displayed to prompt the user to
224 // grant Chrome access to the user's address book.
225 bool ShouldShowAccessAddressBookSuggestion(AutofillType type
);
227 // The access Address Book prompt was shown for a form.
228 void ShowedAccessAddressBookPrompt();
230 // The number of times that the access address book prompt was shown.
231 int AccessAddressBookPromptCount();
233 // The Chrome binary is in the process of being changed, or has been changed.
234 // Future attempts to access the Address Book might incorrectly present a
236 void BinaryChanging();
237 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
239 // Returns true if the wallet integration feature is enabled. Note that the
240 // feature can still disabled by a user pref.
241 bool IsExperimentalWalletIntegrationEnabled() const;
244 // Only PersonalDataManagerFactory and certain tests can create instances of
245 // PersonalDataManager.
246 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, FirstMiddleLast
);
247 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AutofillIsEnabledAtStartup
);
248 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest
,
249 AggregateExistingAuxiliaryProfile
);
250 friend class autofill::AutofillInteractiveTest
;
251 friend class autofill::AutofillTest
;
252 friend class autofill::PersonalDataManagerFactory
;
253 friend class PersonalDataManagerTest
;
254 friend class ProfileSyncServiceAutofillTest
;
255 friend class ::RemoveAutofillTester
;
256 friend struct base::DefaultDeleter
<PersonalDataManager
>;
257 friend void autofill_helper::SetProfiles(
258 int, std::vector
<autofill::AutofillProfile
>*);
259 friend void autofill_helper::SetCreditCards(
260 int, std::vector
<autofill::CreditCard
>*);
261 friend void SetTestProfiles(
262 Browser
* browser
, std::vector
<AutofillProfile
>* profiles
);
264 // Sets |web_profiles_| to the contents of |profiles| and updates the web
265 // database by adding, updating and removing profiles.
266 // The relationship between this and Refresh is subtle.
267 // A call to |SetProfiles| could include out-of-date data that may conflict
268 // if we didn't refresh-to-latest before an Autofill window was opened for
269 // editing. |SetProfiles| is implemented to make a "best effort" to apply the
270 // changes, but in extremely rare edge cases it is possible not all of the
271 // updates in |profiles| make it to the DB. This is why SetProfiles will
272 // invoke Refresh after finishing, to ensure we get into a
273 // consistent state. See Refresh for details.
274 void SetProfiles(std::vector
<AutofillProfile
>* profiles
);
276 // Sets |credit_cards_| to the contents of |credit_cards| and updates the web
277 // database by adding, updating and removing credit cards.
278 void SetCreditCards(std::vector
<CreditCard
>* credit_cards
);
280 // Loads the saved profiles from the web database.
281 virtual void LoadProfiles();
283 // Loads the auxiliary profiles. Currently Mac and Android only.
284 virtual void LoadAuxiliaryProfiles(bool record_metrics
) const;
286 // Loads the saved credit cards from the web database.
287 virtual void LoadCreditCards();
289 // Cancels a pending query to the web database. |handle| is a pointer to the
291 void CancelPendingQuery(WebDataServiceBase::Handle
* handle
);
293 // Notifies observers that personal data has changed.
294 void NotifyPersonalDataChanged();
296 // The first time this is called, logs an UMA metrics for the number of
297 // profiles the user has. On subsequent calls, does nothing.
298 void LogProfileCount() const;
300 // Returns the value of the AutofillEnabled pref.
301 virtual bool IsAutofillEnabled() const;
303 // Overrideable for testing.
304 virtual std::string
CountryCodeForCurrentTimezone() const;
306 // Sets which PrefService to use and observe. |pref_service| is not owned by
307 // this class and must outlive |this|.
308 void SetPrefService(PrefService
* pref_service
);
310 void set_database(scoped_refptr
<AutofillWebDataService
> database
) {
311 database_
= database
;
314 void set_account_tracker(AccountTrackerService
* account_tracker
) {
315 account_tracker_
= account_tracker
;
318 // The backing database that this PersonalDataManager uses.
319 scoped_refptr
<AutofillWebDataService
> database_
;
321 // True if personal data has been loaded from the web database.
322 bool is_data_loaded_
;
324 // The loaded web profiles. These are constructed from entries on web pages
325 // and from manually editing in the settings.
326 ScopedVector
<AutofillProfile
> web_profiles_
;
328 // Auxiliary profiles. On some systems, these are loaded from the system
330 mutable ScopedVector
<AutofillProfile
> auxiliary_profiles_
;
332 // Profiles read from the user's account stored on the server.
333 mutable ScopedVector
<AutofillProfile
> server_profiles_
;
335 // Storage for combined web and auxiliary profiles. Contents are weak
336 // references. Lifetime managed by |web_profiles_| and |auxiliary_profiles_|.
337 mutable std::vector
<AutofillProfile
*> profiles_
;
339 // Cached versions of the local and server credit cards.
340 ScopedVector
<CreditCard
> local_credit_cards_
;
341 ScopedVector
<CreditCard
> server_credit_cards_
;
343 // A combination of local and server credit cards. The pointers are owned
344 // by the local/sverver_credit_cards_ vectors.
345 mutable std::vector
<CreditCard
*> credit_cards_
;
347 // When the manager makes a request from WebDataServiceBase, the database
348 // is queried on another thread, we record the query handle until we
349 // get called back. We store handles for both profile and credit card queries
350 // so they can be loaded at the same time.
351 WebDataServiceBase::Handle pending_profiles_query_
;
352 WebDataServiceBase::Handle pending_server_profiles_query_
;
353 WebDataServiceBase::Handle pending_creditcards_query_
;
354 WebDataServiceBase::Handle pending_server_creditcards_query_
;
357 base::ObserverList
<PersonalDataManagerObserver
> observers_
;
360 // Finds the country code that occurs most frequently among all profiles.
361 // Prefers verified profiles over unverified ones.
362 std::string
MostCommonCountryCodeFromProfiles() const;
364 // Called when the value of prefs::kAutofillEnabled changes.
365 void EnabledPrefChanged();
367 // Functionally equivalent to GetProfiles(), but also records metrics if
368 // |record_metrics| is true. Metrics should be recorded when the returned
369 // profiles will be used to populate the fields shown in an Autofill popup.
370 const std::vector
<AutofillProfile
*>& GetProfiles(
371 bool record_metrics
) const;
373 const std::string app_locale_
;
375 // The default country code for new addresses.
376 mutable std::string default_country_code_
;
378 // The PrefService that this instance uses. Must outlive this instance.
379 PrefService
* pref_service_
;
381 // The AccountTrackerService that this instance uses. Must outlive this
383 AccountTrackerService
* account_tracker_
;
385 // Whether the user is currently operating in an off-the-record context.
386 // Default value is false.
387 bool is_off_the_record_
;
389 // Whether we have already logged the number of profiles this session.
390 mutable bool has_logged_profile_count_
;
392 // An observer to listen for changes to prefs::kAutofillEnabled.
393 scoped_ptr
<BooleanPrefMember
> enabled_pref_
;
395 // An observer to listen for changes to prefs::kAutofillWalletImportEnabled.
396 scoped_ptr
<BooleanPrefMember
> wallet_enabled_pref_
;
398 DISALLOW_COPY_AND_ASSIGN(PersonalDataManager
);
401 } // namespace autofill
403 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_