• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
26 class PrefService;
27 class RemoveAutofillTester;
28 
29 namespace autofill {
30 class AutofillInteractiveTest;
31 class AutofillTest;
32 class FormStructure;
33 class PersonalDataManagerObserver;
34 class PersonalDataManagerFactory;
35 }  // namespace autofill
36 
37 namespace autofill_helper {
38 void SetProfiles(int, std::vector<autofill::AutofillProfile>*);
39 void SetCreditCards(int, std::vector<autofill::CreditCard>*);
40 }  // namespace autofill_helper
41 
42 namespace 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.
47 class 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 
app_locale()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 #if defined(OS_MACOSX) && !defined(OS_IOS)
204   // If Chrome has not prompted for access to the user's address book, the
205   // method prompts the user for permission and blocks the process. Otherwise,
206   // this method has no effect. The return value reflects whether the user was
207   // prompted with a modal dialog.
208   bool AccessAddressBook();
209 
210   // Whether an autofill suggestion should be displayed to prompt the user to
211   // grant Chrome access to the user's address book.
212   bool ShouldShowAccessAddressBookSuggestion(AutofillType type);
213 
214   // The Chrome binary is in the process of being changed, or has been changed.
215   // Future attempts to access the Address Book might incorrectly present a
216   // blocking dialog.
217   void BinaryChanging();
218 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
219 
220  protected:
221   // Only PersonalDataManagerFactory and certain tests can create instances of
222   // PersonalDataManager.
223   FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FirstMiddleLast);
224   FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtStartup);
225   FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
226                            AggregateExistingAuxiliaryProfile);
227   friend class autofill::AutofillInteractiveTest;
228   friend class autofill::AutofillTest;
229   friend class autofill::PersonalDataManagerFactory;
230   friend class PersonalDataManagerTest;
231   friend class ProfileSyncServiceAutofillTest;
232   friend class ::RemoveAutofillTester;
233   friend class TestingAutomationProvider;
234   friend struct base::DefaultDeleter<PersonalDataManager>;
235   friend void autofill_helper::SetProfiles(
236       int, std::vector<autofill::AutofillProfile>*);
237   friend void autofill_helper::SetCreditCards(
238       int, std::vector<autofill::CreditCard>*);
239 
240   // Sets |web_profiles_| to the contents of |profiles| and updates the web
241   // database by adding, updating and removing profiles.
242   // The relationship between this and Refresh is subtle.
243   // A call to |SetProfiles| could include out-of-date data that may conflict
244   // if we didn't refresh-to-latest before an Autofill window was opened for
245   // editing. |SetProfiles| is implemented to make a "best effort" to apply the
246   // changes, but in extremely rare edge cases it is possible not all of the
247   // updates in |profiles| make it to the DB.  This is why SetProfiles will
248   // invoke Refresh after finishing, to ensure we get into a
249   // consistent state.  See Refresh for details.
250   void SetProfiles(std::vector<AutofillProfile>* profiles);
251 
252   // Sets |credit_cards_| to the contents of |credit_cards| and updates the web
253   // database by adding, updating and removing credit cards.
254   void SetCreditCards(std::vector<CreditCard>* credit_cards);
255 
256   // Loads the saved profiles from the web database.
257   virtual void LoadProfiles();
258 
259   // Loads the auxiliary profiles.  Currently Mac and Android only.
260   virtual void LoadAuxiliaryProfiles() const;
261 
262   // Loads the saved credit cards from the web database.
263   virtual void LoadCreditCards();
264 
265   // Receives the loaded profiles from the web data service and stores them in
266   // |credit_cards_|.
267   void ReceiveLoadedProfiles(WebDataServiceBase::Handle h,
268                              const WDTypedResult* result);
269 
270   // Receives the loaded credit cards from the web data service and stores them
271   // in |credit_cards_|.
272   void ReceiveLoadedCreditCards(WebDataServiceBase::Handle h,
273                                 const WDTypedResult* result);
274 
275   // Cancels a pending query to the web database.  |handle| is a pointer to the
276   // query handle.
277   void CancelPendingQuery(WebDataServiceBase::Handle* handle);
278 
279   // Notifies observers that personal data has changed.
280   void NotifyPersonalDataChanged();
281 
282   // The first time this is called, logs an UMA metrics for the number of
283   // profiles the user has. On subsequent calls, does nothing.
284   void LogProfileCount() const;
285 
286   // Returns the value of the AutofillEnabled pref.
287   virtual bool IsAutofillEnabled() const;
288 
289   // Overrideable for testing.
290   virtual std::string CountryCodeForCurrentTimezone() const;
291 
292   // Sets which PrefService to use and observe. |pref_service| is not owned by
293   // this class and must outlive |this|.
294   void SetPrefService(PrefService* pref_service);
295 
296   // For tests.
297   const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
298 
299   void set_database(scoped_refptr<AutofillWebDataService> database) {
300     database_ = database;
301   }
302 
303   void set_metric_logger(const AutofillMetrics* metric_logger) {
304     metric_logger_.reset(metric_logger);
305   }
306 
307   // The backing database that this PersonalDataManager uses.
308   scoped_refptr<AutofillWebDataService> database_;
309 
310   // True if personal data has been loaded from the web database.
311   bool is_data_loaded_;
312 
313   // The loaded web profiles.
314   ScopedVector<AutofillProfile> web_profiles_;
315 
316   // Auxiliary profiles.
317   mutable ScopedVector<AutofillProfile> auxiliary_profiles_;
318 
319   // Storage for combined web and auxiliary profiles.  Contents are weak
320   // references.  Lifetime managed by |web_profiles_| and |auxiliary_profiles_|.
321   mutable std::vector<AutofillProfile*> profiles_;
322 
323   // The loaded credit cards.
324   ScopedVector<CreditCard> credit_cards_;
325 
326   // When the manager makes a request from WebDataServiceBase, the database
327   // is queried on another thread, we record the query handle until we
328   // get called back.  We store handles for both profile and credit card queries
329   // so they can be loaded at the same time.
330   WebDataServiceBase::Handle pending_profiles_query_;
331   WebDataServiceBase::Handle pending_creditcards_query_;
332 
333   // The observers.
334   ObserverList<PersonalDataManagerObserver> observers_;
335 
336  private:
337   // Finds the country code that occurs most frequently among all profiles.
338   // Prefers verified profiles over unverified ones.
339   std::string MostCommonCountryCodeFromProfiles() const;
340 
341   // Called when the value of prefs::kAutofillEnabled changes.
342   void EnabledPrefChanged();
343 
344   const std::string app_locale_;
345 
346   // The default country code for new addresses.
347   mutable std::string default_country_code_;
348 
349   // For logging UMA metrics. Overridden by metrics tests.
350   scoped_ptr<const AutofillMetrics> metric_logger_;
351 
352   // The PrefService that this instance uses. Must outlive this instance.
353   PrefService* pref_service_;
354 
355   // Whether the user is currently operating in an off-the-record context.
356   // Default value is false.
357   bool is_off_the_record_;
358 
359   // Whether we have already logged the number of profiles this session.
360   mutable bool has_logged_profile_count_;
361 
362   // An observer to listen for changes to prefs::kAutofillEnabled.
363   scoped_ptr<BooleanPrefMember> enabled_pref_;
364 
365   DISALLOW_COPY_AND_ASSIGN(PersonalDataManager);
366 };
367 
368 }  // namespace autofill
369 
370 #endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
371