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 // TODO(sdefresne): Remove this. See http://crbug.com/513344.
33 class PersonalDataManagerFactory
;
37 class AutofillInteractiveTest
;
40 class PersonalDataManagerObserver
;
41 class PersonalDataManagerFactory
;
42 } // namespace autofill
44 namespace autofill_helper
{
45 void SetProfiles(int, std::vector
<autofill::AutofillProfile
>*);
46 void SetCreditCards(int, std::vector
<autofill::CreditCard
>*);
47 } // namespace autofill_helper
51 // Handles loading and saving Autofill profile information to the web database.
52 // This class also stores the profiles loaded from the database for use during
54 class PersonalDataManager
: public KeyedService
,
55 public WebDataServiceConsumer
,
56 public AutofillWebDataServiceObserverOnUIThread
{
58 explicit PersonalDataManager(const std::string
& app_locale
);
59 ~PersonalDataManager() override
;
61 // Kicks off asynchronous loading of profiles and credit cards.
62 // |pref_service| must outlive this instance. |is_off_the_record| informs
63 // this instance whether the user is currently operating in an off-the-record
65 void Init(scoped_refptr
<AutofillWebDataService
> database
,
66 PrefService
* pref_service
,
67 AccountTrackerService
* account_tracker
,
68 bool is_off_the_record
);
70 // WebDataServiceConsumer:
71 void OnWebDataServiceRequestDone(WebDataServiceBase::Handle h
,
72 const WDTypedResult
* result
) override
;
74 // AutofillWebDataServiceObserverOnUIThread:
75 void AutofillMultipleChanged() override
;
77 // Adds a listener to be notified of PersonalDataManager events.
78 virtual void AddObserver(PersonalDataManagerObserver
* observer
);
80 // Removes |observer| as an observer of this PersonalDataManager.
81 virtual void RemoveObserver(PersonalDataManagerObserver
* observer
);
83 // Scans the given |form| for importable Autofill data. If the form includes
84 // sufficient address data, it is immediately imported. If the form includes
85 // sufficient credit card data, it is stored into |credit_card|, so that we
86 // can prompt the user whether to save this data.
87 // Returns |true| if sufficient address or credit card data was found.
88 bool ImportFormData(const FormStructure
& form
,
89 scoped_ptr
<CreditCard
>* credit_card
);
91 // Called to indicate |data_model| was used (to fill in a form). Updates
92 // the database accordingly. Can invalidate |data_model|, particularly if
93 // it's a Mac address book entry.
94 virtual void RecordUseOf(const AutofillDataModel
& data_model
);
96 // Saves |imported_profile| to the WebDB if it exists. Returns the guid of
97 // the new or updated profile, or the empty string if no profile was saved.
98 virtual std::string
SaveImportedProfile(
99 const AutofillProfile
& imported_profile
);
101 // Saves a credit card value detected in |ImportedFormData|. Returns the guid
102 // of the new or updated card, or the empty string if no card was saved.
103 virtual std::string
SaveImportedCreditCard(
104 const CreditCard
& imported_credit_card
);
106 // Adds |profile| to the web database.
107 void AddProfile(const AutofillProfile
& profile
);
109 // Updates |profile| which already exists in the web database.
110 void UpdateProfile(const AutofillProfile
& profile
);
112 // Removes the profile or credit card represented by |guid|.
113 virtual void RemoveByGUID(const std::string
& guid
);
115 // Returns the profile with the specified |guid|, or NULL if there is no
116 // profile with the specified |guid|. Both web and auxiliary profiles may
118 AutofillProfile
* GetProfileByGUID(const std::string
& guid
);
120 // Adds |credit_card| to the web database.
121 void AddCreditCard(const CreditCard
& credit_card
);
123 // Updates |credit_card| which already exists in the web database. This
124 // can only be used on local credit cards.
125 void UpdateCreditCard(const CreditCard
& credit_card
);
127 // Update a server card. Only the full number and masked/unmasked
128 // status can be changed.
129 void UpdateServerCreditCard(const CreditCard
& credit_card
);
131 // Resets the card for |guid| to the masked state.
132 void ResetFullServerCard(const std::string
& guid
);
134 // Resets all unmasked cards to the masked state.
135 void ResetFullServerCards();
137 // Deletes all server profiles and cards (both masked and unmasked).
138 void ClearAllServerData();
140 // Returns the credit card with the specified |guid|, or NULL if there is
141 // no credit card with the specified |guid|.
142 CreditCard
* GetCreditCardByGUID(const std::string
& guid
);
144 // Gets the field types availabe in the stored address and credit card data.
145 void GetNonEmptyTypes(ServerFieldTypeSet
* non_empty_types
);
147 // Returns true if the credit card information is stored with a password.
150 // Returns whether the personal data has been loaded from the web database.
151 virtual bool IsDataLoaded() const;
153 // This PersonalDataManager owns these profiles and credit cards. Their
154 // lifetime is until the web database is updated with new profile and credit
155 // card information, respectively. |GetProfiles()| returns both web and
156 // auxiliary profiles. |web_profiles()| returns only web profiles.
157 virtual const std::vector
<AutofillProfile
*>& GetProfiles() const;
158 virtual const std::vector
<AutofillProfile
*>& web_profiles() const;
159 // Returns just LOCAL_CARD cards.
160 virtual const std::vector
<CreditCard
*>& GetLocalCreditCards() const;
161 // Returns all credit cards, server and local.
162 virtual const std::vector
<CreditCard
*>& GetCreditCards() const;
164 // Returns true if there is some data synced from Wallet.
165 bool HasServerData() const;
167 // Loads profiles that can suggest data for |type|. |field_contents| is the
168 // part the user has already typed. |field_is_autofilled| is true if the field
169 // has already been autofilled. |other_field_types| represents the rest of
171 std::vector
<Suggestion
> GetProfileSuggestions(
172 const AutofillType
& type
,
173 const base::string16
& field_contents
,
174 bool field_is_autofilled
,
175 const std::vector
<ServerFieldType
>& other_field_types
);
177 // Gets credit cards that can suggest data for |type|. See
178 // GetProfileSuggestions for argument descriptions. The variant in each
179 // GUID pair should be ignored.
180 std::vector
<Suggestion
> GetCreditCardSuggestions(
181 const AutofillType
& type
,
182 const base::string16
& field_contents
);
184 // Re-loads profiles and credit cards from the WebDatabase asynchronously.
185 // In the general case, this is a no-op and will re-create the same
186 // in-memory model as existed prior to the call. If any change occurred to
187 // profiles in the WebDatabase directly, as is the case if the browser sync
188 // engine processed a change from the cloud, we will learn of these as a
189 // result of this call.
191 // Also see SetProfile for more details.
192 virtual void Refresh();
194 const std::string
& app_locale() const { return app_locale_
; }
196 // Checks suitability of |profile| for adding to the user's set of profiles.
197 static bool IsValidLearnableProfile(const AutofillProfile
& profile
,
198 const std::string
& app_locale
);
200 // Merges |new_profile| into one of the |existing_profiles| if possible;
201 // otherwise appends |new_profile| to the end of that list. Fills
202 // |merged_profiles| with the result. Returns the |guid| of the new or updated
204 static std::string
MergeProfile(
205 const AutofillProfile
& new_profile
,
206 const std::vector
<AutofillProfile
*>& existing_profiles
,
207 const std::string
& app_locale
,
208 std::vector
<AutofillProfile
>* merged_profiles
);
210 // Returns true if |country_code| is a country that the user is likely to
211 // be associated with the user. More concretely, it checks if there are any
212 // addresses with this country or if the user's system timezone is in the
214 virtual bool IsCountryOfInterest(const std::string
& country_code
) const;
216 // Returns our best guess for the country a user is likely to use when
217 // inputting a new address. The value is calculated once and cached, so it
218 // will only update when Chrome is restarted.
219 virtual const std::string
& GetDefaultCountryCodeForNewAddress() const;
221 // Returns true if the wallet integration feature is enabled. Note that the
222 // feature can still disabled by a user pref.
223 bool IsExperimentalWalletIntegrationEnabled() const;
226 // Only PersonalDataManagerFactory and certain tests can create instances of
227 // PersonalDataManager.
228 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, FirstMiddleLast
);
229 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AutofillIsEnabledAtStartup
);
230 friend class autofill::AutofillInteractiveTest
;
231 friend class autofill::AutofillTest
;
232 friend class autofill::PersonalDataManagerFactory
;
233 friend class PersonalDataManagerTest
;
235 // TODO(sdefresne): Remove this. See http://crbug.com/513344.
236 friend class ::PersonalDataManagerFactory
;
238 friend class ProfileSyncServiceAutofillTest
;
239 friend class ::RemoveAutofillTester
;
240 friend struct base::DefaultDeleter
<PersonalDataManager
>;
241 friend void autofill_helper::SetProfiles(
242 int, std::vector
<autofill::AutofillProfile
>*);
243 friend void autofill_helper::SetCreditCards(
244 int, std::vector
<autofill::CreditCard
>*);
245 friend void SetTestProfiles(
246 Browser
* browser
, std::vector
<AutofillProfile
>* profiles
);
248 // Sets |web_profiles_| to the contents of |profiles| and updates the web
249 // database by adding, updating and removing profiles.
250 // The relationship between this and Refresh is subtle.
251 // A call to |SetProfiles| could include out-of-date data that may conflict
252 // if we didn't refresh-to-latest before an Autofill window was opened for
253 // editing. |SetProfiles| is implemented to make a "best effort" to apply the
254 // changes, but in extremely rare edge cases it is possible not all of the
255 // updates in |profiles| make it to the DB. This is why SetProfiles will
256 // invoke Refresh after finishing, to ensure we get into a
257 // consistent state. See Refresh for details.
258 void SetProfiles(std::vector
<AutofillProfile
>* profiles
);
260 // Sets |credit_cards_| to the contents of |credit_cards| and updates the web
261 // database by adding, updating and removing credit cards.
262 void SetCreditCards(std::vector
<CreditCard
>* credit_cards
);
264 // Loads the saved profiles from the web database.
265 virtual void LoadProfiles();
267 // Loads the saved credit cards from the web database.
268 virtual void LoadCreditCards();
270 // Cancels a pending query to the web database. |handle| is a pointer to the
272 void CancelPendingQuery(WebDataServiceBase::Handle
* handle
);
274 // Notifies observers that personal data has changed.
275 void NotifyPersonalDataChanged();
277 // The first time this is called, logs an UMA metrics for the number of
278 // profiles the user has. On subsequent calls, does nothing.
279 void LogProfileCount() const;
281 // Returns the value of the AutofillEnabled pref.
282 virtual bool IsAutofillEnabled() const;
284 // Overrideable for testing.
285 virtual std::string
CountryCodeForCurrentTimezone() const;
287 // Sets which PrefService to use and observe. |pref_service| is not owned by
288 // this class and must outlive |this|.
289 void SetPrefService(PrefService
* pref_service
);
291 void set_database(scoped_refptr
<AutofillWebDataService
> database
) {
292 database_
= database
;
295 void set_account_tracker(AccountTrackerService
* account_tracker
) {
296 account_tracker_
= account_tracker
;
299 // The backing database that this PersonalDataManager uses.
300 scoped_refptr
<AutofillWebDataService
> database_
;
302 // True if personal data has been loaded from the web database.
303 bool is_data_loaded_
;
305 // The loaded web profiles. These are constructed from entries on web pages
306 // and from manually editing in the settings.
307 ScopedVector
<AutofillProfile
> web_profiles_
;
309 // Profiles read from the user's account stored on the server.
310 mutable ScopedVector
<AutofillProfile
> server_profiles_
;
312 // Storage for web profiles. Contents are weak references. Lifetime managed
313 // by |web_profiles_|.
314 mutable std::vector
<AutofillProfile
*> profiles_
;
316 // Cached versions of the local and server credit cards.
317 ScopedVector
<CreditCard
> local_credit_cards_
;
318 ScopedVector
<CreditCard
> server_credit_cards_
;
320 // A combination of local and server credit cards. The pointers are owned
321 // by the local/sverver_credit_cards_ vectors.
322 mutable std::vector
<CreditCard
*> credit_cards_
;
324 // When the manager makes a request from WebDataServiceBase, the database
325 // is queried on another thread, we record the query handle until we
326 // get called back. We store handles for both profile and credit card queries
327 // so they can be loaded at the same time.
328 WebDataServiceBase::Handle pending_profiles_query_
;
329 WebDataServiceBase::Handle pending_server_profiles_query_
;
330 WebDataServiceBase::Handle pending_creditcards_query_
;
331 WebDataServiceBase::Handle pending_server_creditcards_query_
;
334 base::ObserverList
<PersonalDataManagerObserver
> observers_
;
337 // Finds the country code that occurs most frequently among all profiles.
338 // Prefers verified profiles over unverified ones.
339 std::string
MostCommonCountryCodeFromProfiles() const;
341 // Called when the value of prefs::kAutofillEnabled changes.
342 void EnabledPrefChanged();
344 // Functionally equivalent to GetProfiles(), but also records metrics if
345 // |record_metrics| is true. Metrics should be recorded when the returned
346 // profiles will be used to populate the fields shown in an Autofill popup.
347 const std::vector
<AutofillProfile
*>& GetProfiles(
348 bool record_metrics
) const;
350 const std::string app_locale_
;
352 // The default country code for new addresses.
353 mutable std::string default_country_code_
;
355 // The PrefService that this instance uses. Must outlive this instance.
356 PrefService
* pref_service_
;
358 // The AccountTrackerService that this instance uses. Must outlive this
360 AccountTrackerService
* account_tracker_
;
362 // Whether the user is currently operating in an off-the-record context.
363 // Default value is false.
364 bool is_off_the_record_
;
366 // Whether we have already logged the number of profiles this session.
367 mutable bool has_logged_profile_count_
;
369 // An observer to listen for changes to prefs::kAutofillEnabled.
370 scoped_ptr
<BooleanPrefMember
> enabled_pref_
;
372 // An observer to listen for changes to prefs::kAutofillWalletImportEnabled.
373 scoped_ptr
<BooleanPrefMember
> wallet_enabled_pref_
;
375 DISALLOW_COPY_AND_ASSIGN(PersonalDataManager
);
378 } // namespace autofill
380 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_