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
;
31 class AutofillInteractiveTest
;
34 class PersonalDataManagerObserver
;
35 class PersonalDataManagerFactory
;
36 } // namespace autofill
38 namespace autofill_helper
{
39 void SetProfiles(int, std::vector
<autofill::AutofillProfile
>*);
40 void SetCreditCards(int, std::vector
<autofill::CreditCard
>*);
41 } // namespace autofill_helper
45 // Handles loading and saving Autofill profile information to the web database.
46 // This class also stores the profiles loaded from the database for use during
48 class PersonalDataManager
: public KeyedService
,
49 public WebDataServiceConsumer
,
50 public AutofillWebDataServiceObserverOnUIThread
{
52 explicit PersonalDataManager(const std::string
& app_locale
);
53 ~PersonalDataManager() override
;
55 // Kicks off asynchronous loading of profiles and credit cards.
56 // |pref_service| must outlive this instance. |is_off_the_record| informs
57 // this instance whether the user is currently operating in an off-the-record
59 void Init(scoped_refptr
<AutofillWebDataService
> database
,
60 PrefService
* pref_service
,
61 bool is_off_the_record
);
63 // WebDataServiceConsumer:
64 void OnWebDataServiceRequestDone(WebDataServiceBase::Handle h
,
65 const WDTypedResult
* result
) override
;
67 // AutofillWebDataServiceObserverOnUIThread:
68 void AutofillMultipleChanged() override
;
70 // Adds a listener to be notified of PersonalDataManager events.
71 virtual void AddObserver(PersonalDataManagerObserver
* observer
);
73 // Removes |observer| as an observer of this PersonalDataManager.
74 virtual void RemoveObserver(PersonalDataManagerObserver
* observer
);
76 // Scans the given |form| for importable Autofill data. If the form includes
77 // sufficient address data, it is immediately imported. If the form includes
78 // sufficient credit card data, it is stored into |credit_card|, so that we
79 // can prompt the user whether to save this data.
80 // Returns |true| if sufficient address or credit card data was found.
81 bool ImportFormData(const FormStructure
& form
,
82 scoped_ptr
<CreditCard
>* credit_card
);
84 // Called to indicate |data_model| was used (to fill in a form). Updates
85 // the database accordingly. Can invalidate |data_model|, particularly if
86 // it's a Mac address book entry.
87 virtual void RecordUseOf(const AutofillDataModel
& data_model
);
89 // Saves |imported_profile| to the WebDB if it exists. Returns the guid of
90 // the new or updated profile, or the empty string if no profile was saved.
91 virtual std::string
SaveImportedProfile(
92 const AutofillProfile
& imported_profile
);
94 // Saves a credit card value detected in |ImportedFormData|. Returns the guid
95 // of the new or updated card, or the empty string if no card was saved.
96 virtual std::string
SaveImportedCreditCard(
97 const CreditCard
& imported_credit_card
);
99 // Adds |profile| to the web database.
100 void AddProfile(const AutofillProfile
& profile
);
102 // Updates |profile| which already exists in the web database.
103 void UpdateProfile(const AutofillProfile
& profile
);
105 // Removes the profile or credit card represented by |guid|.
106 virtual void RemoveByGUID(const std::string
& guid
);
108 // Returns the profile with the specified |guid|, or NULL if there is no
109 // profile with the specified |guid|. Both web and auxiliary profiles may
111 AutofillProfile
* GetProfileByGUID(const std::string
& guid
);
113 // Adds |credit_card| to the web database.
114 void AddCreditCard(const CreditCard
& credit_card
);
116 // Updates |credit_card| which already exists in the web database. This
117 // can only be used on local credit cards.
118 void UpdateCreditCard(const CreditCard
& credit_card
);
120 // Update a server card. Only the full number and masked/unmasked
121 // status can be changed.
122 void UpdateServerCreditCard(const CreditCard
& credit_card
);
124 // Resets all unmasked cards to the masked state.
125 void ResetFullServerCards();
127 // Returns the credit card with the specified |guid|, or NULL if there is
128 // no credit card with the specified |guid|.
129 CreditCard
* GetCreditCardByGUID(const std::string
& guid
);
131 // Gets the field types availabe in the stored address and credit card data.
132 void GetNonEmptyTypes(ServerFieldTypeSet
* non_empty_types
);
134 // Returns true if the credit card information is stored with a password.
137 // Returns whether the personal data has been loaded from the web database.
138 virtual bool IsDataLoaded() const;
140 // This PersonalDataManager owns these profiles and credit cards. Their
141 // lifetime is until the web database is updated with new profile and credit
142 // card information, respectively. |GetProfiles()| returns both web and
143 // auxiliary profiles. |web_profiles()| returns only web profiles.
144 virtual const std::vector
<AutofillProfile
*>& GetProfiles() const;
145 virtual const std::vector
<AutofillProfile
*>& web_profiles() const;
146 // Returns just LOCAL_CARD cards.
147 virtual const std::vector
<CreditCard
*>& GetLocalCreditCards() const;
148 // Returns all credit cards, server and local.
149 virtual const std::vector
<CreditCard
*>& GetCreditCards() const;
151 // Loads profiles that can suggest data for |type|. |field_contents| is the
152 // part the user has already typed. |field_is_autofilled| is true if the field
153 // has already been autofilled. |other_field_types| represents the rest of
155 std::vector
<Suggestion
> GetProfileSuggestions(
156 const AutofillType
& type
,
157 const base::string16
& field_contents
,
158 bool field_is_autofilled
,
159 const std::vector
<ServerFieldType
>& other_field_types
);
161 // Gets credit cards that can suggest data for |type|. See
162 // GetProfileSuggestions for argument descriptions. The variant in each
163 // GUID pair should be ignored.
164 std::vector
<Suggestion
> GetCreditCardSuggestions(
165 const AutofillType
& type
,
166 const base::string16
& field_contents
);
168 // Re-loads profiles and credit cards from the WebDatabase asynchronously.
169 // In the general case, this is a no-op and will re-create the same
170 // in-memory model as existed prior to the call. If any change occurred to
171 // profiles in the WebDatabase directly, as is the case if the browser sync
172 // engine processed a change from the cloud, we will learn of these as a
173 // result of this call.
175 // Also see SetProfile for more details.
176 virtual void Refresh();
178 const std::string
& app_locale() const { return app_locale_
; }
180 // Checks suitability of |profile| for adding to the user's set of profiles.
181 static bool IsValidLearnableProfile(const AutofillProfile
& profile
,
182 const std::string
& app_locale
);
184 // Merges |new_profile| into one of the |existing_profiles| if possible;
185 // otherwise appends |new_profile| to the end of that list. Fills
186 // |merged_profiles| with the result. Returns the |guid| of the new or updated
188 static std::string
MergeProfile(
189 const AutofillProfile
& new_profile
,
190 const std::vector
<AutofillProfile
*>& existing_profiles
,
191 const std::string
& app_locale
,
192 std::vector
<AutofillProfile
>* merged_profiles
);
194 // Returns true if |country_code| is a country that the user is likely to
195 // be associated with the user. More concretely, it checks if there are any
196 // addresses with this country or if the user's system timezone is in the
198 virtual bool IsCountryOfInterest(const std::string
& country_code
) const;
200 // Returns our best guess for the country a user is likely to use when
201 // inputting a new address. The value is calculated once and cached, so it
202 // will only update when Chrome is restarted.
203 virtual const std::string
& GetDefaultCountryCodeForNewAddress() const;
205 #if defined(OS_MACOSX) && !defined(OS_IOS)
206 // If Chrome has not prompted for access to the user's address book, the
207 // method prompts the user for permission and blocks the process. Otherwise,
208 // this method has no effect. The return value reflects whether the user was
209 // prompted with a modal dialog.
210 bool AccessAddressBook();
212 // Whether an autofill suggestion should be displayed to prompt the user to
213 // grant Chrome access to the user's address book.
214 bool ShouldShowAccessAddressBookSuggestion(AutofillType type
);
216 // The access Address Book prompt was shown for a form.
217 void ShowedAccessAddressBookPrompt();
219 // The number of times that the access address book prompt was shown.
220 int AccessAddressBookPromptCount();
222 // The Chrome binary is in the process of being changed, or has been changed.
223 // Future attempts to access the Address Book might incorrectly present a
225 void BinaryChanging();
226 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
228 // Returns true if the wallet integration feature is enabled. Note that the
229 // feature can still disabled by a user pref.
230 bool IsExperimentalWalletIntegrationEnabled() const;
233 // Only PersonalDataManagerFactory and certain tests can create instances of
234 // PersonalDataManager.
235 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, FirstMiddleLast
);
236 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AutofillIsEnabledAtStartup
);
237 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest
,
238 AggregateExistingAuxiliaryProfile
);
239 friend class autofill::AutofillInteractiveTest
;
240 friend class autofill::AutofillTest
;
241 friend class autofill::PersonalDataManagerFactory
;
242 friend class PersonalDataManagerTest
;
243 friend class ProfileSyncServiceAutofillTest
;
244 friend class ::RemoveAutofillTester
;
245 friend struct base::DefaultDeleter
<PersonalDataManager
>;
246 friend void autofill_helper::SetProfiles(
247 int, std::vector
<autofill::AutofillProfile
>*);
248 friend void autofill_helper::SetCreditCards(
249 int, std::vector
<autofill::CreditCard
>*);
250 friend void SetTestProfiles(
251 Browser
* browser
, std::vector
<AutofillProfile
>* profiles
);
253 // Sets |web_profiles_| to the contents of |profiles| and updates the web
254 // database by adding, updating and removing profiles.
255 // The relationship between this and Refresh is subtle.
256 // A call to |SetProfiles| could include out-of-date data that may conflict
257 // if we didn't refresh-to-latest before an Autofill window was opened for
258 // editing. |SetProfiles| is implemented to make a "best effort" to apply the
259 // changes, but in extremely rare edge cases it is possible not all of the
260 // updates in |profiles| make it to the DB. This is why SetProfiles will
261 // invoke Refresh after finishing, to ensure we get into a
262 // consistent state. See Refresh for details.
263 void SetProfiles(std::vector
<AutofillProfile
>* profiles
);
265 // Sets |credit_cards_| to the contents of |credit_cards| and updates the web
266 // database by adding, updating and removing credit cards.
267 void SetCreditCards(std::vector
<CreditCard
>* credit_cards
);
269 // Loads the saved profiles from the web database.
270 virtual void LoadProfiles();
272 // Loads the auxiliary profiles. Currently Mac and Android only.
273 virtual void LoadAuxiliaryProfiles(bool record_metrics
) const;
275 // Loads the saved credit cards from the web database.
276 virtual void LoadCreditCards();
278 // Cancels a pending query to the web database. |handle| is a pointer to the
280 void CancelPendingQuery(WebDataServiceBase::Handle
* handle
);
282 // Notifies observers that personal data has changed.
283 void NotifyPersonalDataChanged();
285 // The first time this is called, logs an UMA metrics for the number of
286 // profiles the user has. On subsequent calls, does nothing.
287 void LogProfileCount() const;
289 // Returns the value of the AutofillEnabled pref.
290 virtual bool IsAutofillEnabled() const;
292 // Overrideable for testing.
293 virtual std::string
CountryCodeForCurrentTimezone() const;
295 // Sets which PrefService to use and observe. |pref_service| is not owned by
296 // this class and must outlive |this|.
297 void SetPrefService(PrefService
* pref_service
);
299 void set_database(scoped_refptr
<AutofillWebDataService
> database
) {
300 database_
= database
;
303 // The backing database that this PersonalDataManager uses.
304 scoped_refptr
<AutofillWebDataService
> database_
;
306 // True if personal data has been loaded from the web database.
307 bool is_data_loaded_
;
309 // The loaded web profiles. These are constructed from entries on web pages
310 // and from manually editing in the settings.
311 ScopedVector
<AutofillProfile
> web_profiles_
;
313 // Auxiliary profiles. On some systems, these are loaded from the system
315 mutable ScopedVector
<AutofillProfile
> auxiliary_profiles_
;
317 // Profiles read from the user's account stored on the server.
318 mutable ScopedVector
<AutofillProfile
> server_profiles_
;
320 // Storage for combined web and auxiliary profiles. Contents are weak
321 // references. Lifetime managed by |web_profiles_| and |auxiliary_profiles_|.
322 mutable std::vector
<AutofillProfile
*> profiles_
;
324 // Cached versions of the local and server credit cards.
325 ScopedVector
<CreditCard
> local_credit_cards_
;
326 ScopedVector
<CreditCard
> server_credit_cards_
;
328 // A combination of local and server credit cards. The pointers are owned
329 // by the local/sverver_credit_cards_ vectors.
330 mutable std::vector
<CreditCard
*> credit_cards_
;
332 // When the manager makes a request from WebDataServiceBase, the database
333 // is queried on another thread, we record the query handle until we
334 // get called back. We store handles for both profile and credit card queries
335 // so they can be loaded at the same time.
336 WebDataServiceBase::Handle pending_profiles_query_
;
337 WebDataServiceBase::Handle pending_server_profiles_query_
;
338 WebDataServiceBase::Handle pending_creditcards_query_
;
339 WebDataServiceBase::Handle pending_server_creditcards_query_
;
342 ObserverList
<PersonalDataManagerObserver
> observers_
;
345 // Finds the country code that occurs most frequently among all profiles.
346 // Prefers verified profiles over unverified ones.
347 std::string
MostCommonCountryCodeFromProfiles() const;
349 // Called when the value of prefs::kAutofillEnabled changes.
350 void EnabledPrefChanged();
352 // Functionally equivalent to GetProfiles(), but also records metrics if
353 // |record_metrics| is true. Metrics should be recorded when the returned
354 // profiles will be used to populate the fields shown in an Autofill popup.
355 const std::vector
<AutofillProfile
*>& GetProfiles(
356 bool record_metrics
) const;
358 const std::string app_locale_
;
360 // The default country code for new addresses.
361 mutable std::string default_country_code_
;
363 // The PrefService that this instance uses. Must outlive this instance.
364 PrefService
* pref_service_
;
366 // Whether the user is currently operating in an off-the-record context.
367 // Default value is false.
368 bool is_off_the_record_
;
370 // Whether we have already logged the number of profiles this session.
371 mutable bool has_logged_profile_count_
;
373 // An observer to listen for changes to prefs::kAutofillEnabled.
374 scoped_ptr
<BooleanPrefMember
> enabled_pref_
;
376 DISALLOW_COPY_AND_ASSIGN(PersonalDataManager
);
379 } // namespace autofill
381 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_