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 access Address Book prompt was shown for a form. 215 void ShowedAccessAddressBookPrompt(); 216 217 // The number of times that the access address book prompt was shown. 218 int AccessAddressBookPromptCount(); 219 220 // The Chrome binary is in the process of being changed, or has been changed. 221 // Future attempts to access the Address Book might incorrectly present a 222 // blocking dialog. 223 void BinaryChanging(); 224 #endif // defined(OS_MACOSX) && !defined(OS_IOS) 225 226 protected: 227 // Only PersonalDataManagerFactory and certain tests can create instances of 228 // PersonalDataManager. 229 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FirstMiddleLast); 230 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtStartup); 231 FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest, 232 AggregateExistingAuxiliaryProfile); 233 friend class autofill::AutofillInteractiveTest; 234 friend class autofill::AutofillTest; 235 friend class autofill::PersonalDataManagerFactory; 236 friend class PersonalDataManagerTest; 237 friend class ProfileSyncServiceAutofillTest; 238 friend class ::RemoveAutofillTester; 239 friend class TestingAutomationProvider; 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 246 // Sets |web_profiles_| to the contents of |profiles| and updates the web 247 // database by adding, updating and removing profiles. 248 // The relationship between this and Refresh is subtle. 249 // A call to |SetProfiles| could include out-of-date data that may conflict 250 // if we didn't refresh-to-latest before an Autofill window was opened for 251 // editing. |SetProfiles| is implemented to make a "best effort" to apply the 252 // changes, but in extremely rare edge cases it is possible not all of the 253 // updates in |profiles| make it to the DB. This is why SetProfiles will 254 // invoke Refresh after finishing, to ensure we get into a 255 // consistent state. See Refresh for details. 256 void SetProfiles(std::vector<AutofillProfile>* profiles); 257 258 // Sets |credit_cards_| to the contents of |credit_cards| and updates the web 259 // database by adding, updating and removing credit cards. 260 void SetCreditCards(std::vector<CreditCard>* credit_cards); 261 262 // Loads the saved profiles from the web database. 263 virtual void LoadProfiles(); 264 265 // Loads the auxiliary profiles. Currently Mac and Android only. 266 virtual void LoadAuxiliaryProfiles(bool record_metrics) const; 267 268 // Loads the saved credit cards from the web database. 269 virtual void LoadCreditCards(); 270 271 // Receives the loaded profiles from the web data service and stores them in 272 // |credit_cards_|. 273 void ReceiveLoadedProfiles(WebDataServiceBase::Handle h, 274 const WDTypedResult* result); 275 276 // Receives the loaded credit cards from the web data service and stores them 277 // in |credit_cards_|. 278 void ReceiveLoadedCreditCards(WebDataServiceBase::Handle h, 279 const WDTypedResult* result); 280 281 // Cancels a pending query to the web database. |handle| is a pointer to the 282 // query handle. 283 void CancelPendingQuery(WebDataServiceBase::Handle* handle); 284 285 // Notifies observers that personal data has changed. 286 void NotifyPersonalDataChanged(); 287 288 // The first time this is called, logs an UMA metrics for the number of 289 // profiles the user has. On subsequent calls, does nothing. 290 void LogProfileCount() const; 291 292 // Returns the value of the AutofillEnabled pref. 293 virtual bool IsAutofillEnabled() const; 294 295 // Overrideable for testing. 296 virtual std::string CountryCodeForCurrentTimezone() const; 297 298 // Sets which PrefService to use and observe. |pref_service| is not owned by 299 // this class and must outlive |this|. 300 void SetPrefService(PrefService* pref_service); 301 302 // For tests. 303 const AutofillMetrics* metric_logger() const { return metric_logger_.get(); } 304 305 void set_database(scoped_refptr<AutofillWebDataService> database) { 306 database_ = database; 307 } 308 309 void set_metric_logger(const AutofillMetrics* metric_logger) { 310 metric_logger_.reset(metric_logger); 311 } 312 313 // The backing database that this PersonalDataManager uses. 314 scoped_refptr<AutofillWebDataService> database_; 315 316 // True if personal data has been loaded from the web database. 317 bool is_data_loaded_; 318 319 // The loaded web profiles. 320 ScopedVector<AutofillProfile> web_profiles_; 321 322 // Auxiliary profiles. 323 mutable ScopedVector<AutofillProfile> auxiliary_profiles_; 324 325 // Storage for combined web and auxiliary profiles. Contents are weak 326 // references. Lifetime managed by |web_profiles_| and |auxiliary_profiles_|. 327 mutable std::vector<AutofillProfile*> profiles_; 328 329 // The loaded credit cards. 330 ScopedVector<CreditCard> credit_cards_; 331 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_creditcards_query_; 338 339 // The observers. 340 ObserverList<PersonalDataManagerObserver> observers_; 341 342 private: 343 // Finds the country code that occurs most frequently among all profiles. 344 // Prefers verified profiles over unverified ones. 345 std::string MostCommonCountryCodeFromProfiles() const; 346 347 // Called when the value of prefs::kAutofillEnabled changes. 348 void EnabledPrefChanged(); 349 350 // Functionally equivalent to GetProfiles(), but also records metrics if 351 // |record_metrics| is true. Metrics should be recorded when the returned 352 // profiles will be used to populate the fields shown in an Autofill popup. 353 const std::vector<AutofillProfile*>& GetProfiles( 354 bool record_metrics) const; 355 356 const std::string app_locale_; 357 358 // The default country code for new addresses. 359 mutable std::string default_country_code_; 360 361 // For logging UMA metrics. Overridden by metrics tests. 362 scoped_ptr<const AutofillMetrics> metric_logger_; 363 364 // The PrefService that this instance uses. Must outlive this instance. 365 PrefService* pref_service_; 366 367 // Whether the user is currently operating in an off-the-record context. 368 // Default value is false. 369 bool is_off_the_record_; 370 371 // Whether we have already logged the number of profiles this session. 372 mutable bool has_logged_profile_count_; 373 374 // An observer to listen for changes to prefs::kAutofillEnabled. 375 scoped_ptr<BooleanPrefMember> enabled_pref_; 376 377 DISALLOW_COPY_AND_ASSIGN(PersonalDataManager); 378 }; 379 380 } // namespace autofill 381 382 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_ 383