personal_data_manager.h revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
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.
4
5#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
6#define COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
7
8#include <set>
9#include <vector>
10
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_metrics.h"
18#include "components/autofill/core/browser/autofill_profile.h"
19#include "components/autofill/core/browser/credit_card.h"
20#include "components/autofill/core/browser/field_types.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"
25
26class PrefService;
27class RemoveAutofillTester;
28
29namespace autofill {
30class AutofillInteractiveTest;
31class AutofillTest;
32class FormStructure;
33class PersonalDataManagerObserver;
34class PersonalDataManagerFactory;
35}  // namespace autofill
36
37namespace autofill_helper {
38void SetProfiles(int, std::vector<autofill::AutofillProfile>*);
39void SetCreditCards(int, std::vector<autofill::CreditCard>*);
40}  // namespace autofill_helper
41
42namespace autofill {
43
44// Handles loading and saving Autofill profile information to the web database.
45// This class also stores the profiles loaded from the database for use during
46// Autofill.
47class PersonalDataManager : public KeyedService,
48                            public WebDataServiceConsumer,
49                            public AutofillWebDataServiceObserverOnUIThread {
50 public:
51  // A pair of GUID and variant index. Represents a single FormGroup and a
52  // specific data variant.
53  typedef std::pair<std::string, size_t> GUIDPair;
54
55  explicit PersonalDataManager(const std::string& app_locale);
56  virtual ~PersonalDataManager();
57
58  // Kicks off asynchronous loading of profiles and credit cards.
59  // |pref_service| must outlive this instance.  |is_off_the_record| informs
60  // this instance whether the user is currently operating in an off-the-record
61  // context.
62  void Init(scoped_refptr<AutofillWebDataService> database,
63            PrefService* pref_service,
64            bool is_off_the_record);
65
66  // WebDataServiceConsumer:
67  virtual void OnWebDataServiceRequestDone(
68      WebDataServiceBase::Handle h,
69      const WDTypedResult* result) OVERRIDE;
70
71  // AutofillWebDataServiceObserverOnUIThread:
72  virtual void AutofillMultipleChanged() OVERRIDE;
73
74  // Adds a listener to be notified of PersonalDataManager events.
75  virtual void AddObserver(PersonalDataManagerObserver* observer);
76
77  // Removes |observer| as an observer of this PersonalDataManager.
78  virtual void RemoveObserver(PersonalDataManagerObserver* observer);
79
80  // Scans the given |form| for importable Autofill data. If the form includes
81  // sufficient address data, it is immediately imported. If the form includes
82  // sufficient credit card data, it is stored into |credit_card|, so that we
83  // can prompt the user whether to save this data.
84  // Returns |true| if sufficient address or credit card data was found.
85  bool ImportFormData(const FormStructure& form,
86                      scoped_ptr<CreditCard>* credit_card);
87
88  // Saves |imported_profile| to the WebDB if it exists. Returns the guid of
89  // the new or updated profile, or the empty string if no profile was saved.
90  virtual std::string SaveImportedProfile(
91      const AutofillProfile& imported_profile);
92
93  // Saves a credit card value detected in |ImportedFormData|. Returns the guid
94  // of the new or updated card, or the empty string if no card was saved.
95  virtual std::string SaveImportedCreditCard(
96      const CreditCard& imported_credit_card);
97
98  // Adds |profile| to the web database.
99  void AddProfile(const AutofillProfile& profile);
100
101  // Updates |profile| which already exists in the web database.
102  void UpdateProfile(const AutofillProfile& profile);
103
104  // Removes the profile or credit card represented by |guid|.
105  virtual void RemoveByGUID(const std::string& guid);
106
107  // Returns the profile with the specified |guid|, or NULL if there is no
108  // profile with the specified |guid|. Both web and auxiliary profiles may
109  // be returned.
110  AutofillProfile* GetProfileByGUID(const std::string& guid);
111
112  // Adds |credit_card| to the web database.
113  void AddCreditCard(const CreditCard& credit_card);
114
115  // Updates |credit_card| which already exists in the web database.
116  void UpdateCreditCard(const CreditCard& credit_card);
117
118  // Returns the credit card with the specified |guid|, or NULL if there is
119  // no credit card with the specified |guid|.
120  CreditCard* GetCreditCardByGUID(const std::string& guid);
121
122  // Gets the field types availabe in the stored address and credit card data.
123  void GetNonEmptyTypes(ServerFieldTypeSet* non_empty_types);
124
125  // Returns true if the credit card information is stored with a password.
126  bool HasPassword();
127
128  // Returns whether the personal data has been loaded from the web database.
129  virtual bool IsDataLoaded() const;
130
131  // This PersonalDataManager owns these profiles and credit cards.  Their
132  // lifetime is until the web database is updated with new profile and credit
133  // card information, respectively.  |GetProfiles()| returns both web and
134  // auxiliary profiles.  |web_profiles()| returns only web profiles.
135  virtual const std::vector<AutofillProfile*>& GetProfiles() const;
136  virtual const std::vector<AutofillProfile*>& web_profiles() const;
137  virtual const std::vector<CreditCard*>& GetCreditCards() const;
138
139  // Loads profiles that can suggest data for |type|. |field_contents| is the
140  // part the user has already typed. |field_is_autofilled| is true if the field
141  // has already been autofilled. |other_field_types| represents the rest of
142  // form. |filter| is run on each potential suggestion. If |filter| returns
143  // true, the profile added to the last four outparams (else it's omitted).
144  void GetProfileSuggestions(
145      const AutofillType& type,
146      const base::string16& field_contents,
147      bool field_is_autofilled,
148      const std::vector<ServerFieldType>& other_field_types,
149      const base::Callback<bool(const AutofillProfile&)>& filter,
150      std::vector<base::string16>* values,
151      std::vector<base::string16>* labels,
152      std::vector<base::string16>* icons,
153      std::vector<GUIDPair>* guid_pairs);
154
155  // Gets credit cards that can suggest data for |type|. See
156  // GetProfileSuggestions for argument descriptions. The variant in each
157  // GUID pair should be ignored.
158  void GetCreditCardSuggestions(
159      const AutofillType& type,
160      const base::string16& field_contents,
161      std::vector<base::string16>* values,
162      std::vector<base::string16>* labels,
163      std::vector<base::string16>* icons,
164      std::vector<GUIDPair>* guid_pairs);
165
166  // Re-loads profiles and credit cards from the WebDatabase asynchronously.
167  // In the general case, this is a no-op and will re-create the same
168  // in-memory model as existed prior to the call.  If any change occurred to
169  // profiles in the WebDatabase directly, as is the case if the browser sync
170  // engine processed a change from the cloud, we will learn of these as a
171  // result of this call.
172  //
173  // Also see SetProfile for more details.
174  virtual void Refresh();
175
176  const std::string& app_locale() const { return app_locale_; }
177
178  // Checks suitability of |profile| for adding to the user's set of profiles.
179  static bool IsValidLearnableProfile(const AutofillProfile& profile,
180                                      const std::string& app_locale);
181
182  // Merges |new_profile| into one of the |existing_profiles| if possible;
183  // otherwise appends |new_profile| to the end of that list. Fills
184  // |merged_profiles| with the result. Returns the |guid| of the new or updated
185  // profile.
186  static std::string MergeProfile(
187      const AutofillProfile& new_profile,
188      const std::vector<AutofillProfile*>& existing_profiles,
189      const std::string& app_locale,
190      std::vector<AutofillProfile>* merged_profiles);
191
192  // Returns true if |country_code| is a country that the user is likely to
193  // be associated with the user. More concretely, it checks if there are any
194  // addresses with this country or if the user's system timezone is in the
195  // given country.
196  virtual bool IsCountryOfInterest(const std::string& country_code) const;
197
198  // Returns our best guess for the country a user is likely to use when
199  // inputting a new address. The value is calculated once and cached, so it
200  // will only update when Chrome is restarted.
201  virtual const std::string& GetDefaultCountryCodeForNewAddress() const;
202
203 protected:
204  // Only PersonalDataManagerFactory and certain tests can create instances of
205  // PersonalDataManager.
206  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FirstMiddleLast);
207  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtStartup);
208  FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
209                           AggregateExistingAuxiliaryProfile);
210  friend class autofill::AutofillInteractiveTest;
211  friend class autofill::AutofillTest;
212  friend class autofill::PersonalDataManagerFactory;
213  friend class PersonalDataManagerTest;
214  friend class ProfileSyncServiceAutofillTest;
215  friend class ::RemoveAutofillTester;
216  friend class TestingAutomationProvider;
217  friend struct base::DefaultDeleter<PersonalDataManager>;
218  friend void autofill_helper::SetProfiles(
219      int, std::vector<autofill::AutofillProfile>*);
220  friend void autofill_helper::SetCreditCards(
221      int, std::vector<autofill::CreditCard>*);
222
223  // Sets |web_profiles_| to the contents of |profiles| and updates the web
224  // database by adding, updating and removing profiles.
225  // The relationship between this and Refresh is subtle.
226  // A call to |SetProfiles| could include out-of-date data that may conflict
227  // if we didn't refresh-to-latest before an Autofill window was opened for
228  // editing. |SetProfiles| is implemented to make a "best effort" to apply the
229  // changes, but in extremely rare edge cases it is possible not all of the
230  // updates in |profiles| make it to the DB.  This is why SetProfiles will
231  // invoke Refresh after finishing, to ensure we get into a
232  // consistent state.  See Refresh for details.
233  void SetProfiles(std::vector<AutofillProfile>* profiles);
234
235  // Sets |credit_cards_| to the contents of |credit_cards| and updates the web
236  // database by adding, updating and removing credit cards.
237  void SetCreditCards(std::vector<CreditCard>* credit_cards);
238
239  // Loads the saved profiles from the web database.
240  virtual void LoadProfiles();
241
242  // Loads the auxiliary profiles.  Currently Mac and Android only.
243  virtual void LoadAuxiliaryProfiles() const;
244
245  // Loads the saved credit cards from the web database.
246  virtual void LoadCreditCards();
247
248  // Receives the loaded profiles from the web data service and stores them in
249  // |credit_cards_|.
250  void ReceiveLoadedProfiles(WebDataServiceBase::Handle h,
251                             const WDTypedResult* result);
252
253  // Receives the loaded credit cards from the web data service and stores them
254  // in |credit_cards_|.
255  void ReceiveLoadedCreditCards(WebDataServiceBase::Handle h,
256                                const WDTypedResult* result);
257
258  // Cancels a pending query to the web database.  |handle| is a pointer to the
259  // query handle.
260  void CancelPendingQuery(WebDataServiceBase::Handle* handle);
261
262  // Notifies observers that personal data has changed.
263  void NotifyPersonalDataChanged();
264
265  // The first time this is called, logs an UMA metrics for the number of
266  // profiles the user has. On subsequent calls, does nothing.
267  void LogProfileCount() const;
268
269  // Returns the value of the AutofillEnabled pref.
270  virtual bool IsAutofillEnabled() const;
271
272  // Overrideable for testing.
273  virtual std::string CountryCodeForCurrentTimezone() const;
274
275  // Sets which PrefService to use and observe. |pref_service| is not owned by
276  // this class and must outlive |this|.
277  void SetPrefService(PrefService* pref_service);
278
279  // For tests.
280  const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
281
282  void set_database(scoped_refptr<AutofillWebDataService> database) {
283    database_ = database;
284  }
285
286  void set_metric_logger(const AutofillMetrics* metric_logger) {
287    metric_logger_.reset(metric_logger);
288  }
289
290  // The backing database that this PersonalDataManager uses.
291  scoped_refptr<AutofillWebDataService> database_;
292
293  // True if personal data has been loaded from the web database.
294  bool is_data_loaded_;
295
296  // The loaded web profiles.
297  ScopedVector<AutofillProfile> web_profiles_;
298
299  // Auxiliary profiles.
300  mutable ScopedVector<AutofillProfile> auxiliary_profiles_;
301
302  // Storage for combined web and auxiliary profiles.  Contents are weak
303  // references.  Lifetime managed by |web_profiles_| and |auxiliary_profiles_|.
304  mutable std::vector<AutofillProfile*> profiles_;
305
306  // The loaded credit cards.
307  ScopedVector<CreditCard> credit_cards_;
308
309  // When the manager makes a request from WebDataServiceBase, the database
310  // is queried on another thread, we record the query handle until we
311  // get called back.  We store handles for both profile and credit card queries
312  // so they can be loaded at the same time.
313  WebDataServiceBase::Handle pending_profiles_query_;
314  WebDataServiceBase::Handle pending_creditcards_query_;
315
316  // The observers.
317  ObserverList<PersonalDataManagerObserver> observers_;
318
319 private:
320  // Finds the country code that occurs most frequently among all profiles.
321  // Prefers verified profiles over unverified ones.
322  std::string MostCommonCountryCodeFromProfiles() const;
323
324  // Called when the value of prefs::kAutofillEnabled changes.
325  void EnabledPrefChanged();
326
327  const std::string app_locale_;
328
329  // The default country code for new addresses.
330  mutable std::string default_country_code_;
331
332  // For logging UMA metrics. Overridden by metrics tests.
333  scoped_ptr<const AutofillMetrics> metric_logger_;
334
335  // The PrefService that this instance uses. Must outlive this instance.
336  PrefService* pref_service_;
337
338  // Whether the user is currently operating in an off-the-record context.
339  // Default value is false.
340  bool is_off_the_record_;
341
342  // Whether we have already logged the number of profiles this session.
343  mutable bool has_logged_profile_count_;
344
345  // An observer to listen for changes to prefs::kAutofillEnabled.
346  scoped_ptr<BooleanPrefMember> enabled_pref_;
347
348  DISALLOW_COPY_AND_ASSIGN(PersonalDataManager);
349};
350
351}  // namespace autofill
352
353#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
354