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 #include "components/autofill/core/browser/personal_data_manager.h"
6 
7 #include <stddef.h>
8 
9 #include <algorithm>
10 #include <list>
11 #include <map>
12 #include <memory>
13 #include <string>
14 #include <utility>
15 
16 #include "base/bind.h"
17 #include "base/callback.h"
18 #include "base/feature_list.h"
19 #include "base/i18n/case_conversion.h"
20 #include "base/i18n/timezone.h"
21 #include "base/metrics/histogram_functions.h"
22 #include "base/ranges/algorithm.h"
23 #include "base/stl_util.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "build/build_config.h"
29 #include "components/autofill/core/browser/autofill_data_util.h"
30 #include "components/autofill/core/browser/autofill_download_manager.h"
31 #include "components/autofill/core/browser/autofill_experiments.h"
32 #include "components/autofill/core/browser/autofill_field.h"
33 #include "components/autofill/core/browser/autofill_metrics.h"
34 #include "components/autofill/core/browser/data_model/autofill_profile_comparator.h"
35 #include "components/autofill/core/browser/data_model/phone_number.h"
36 #include "components/autofill/core/browser/form_structure.h"
37 #include "components/autofill/core/browser/geo/address_i18n.h"
38 #include "components/autofill/core/browser/geo/autofill_country.h"
39 #include "components/autofill/core/browser/geo/country_data.h"
40 #include "components/autofill/core/browser/geo/country_names.h"
41 #include "components/autofill/core/browser/geo/phone_number_i18n.h"
42 #include "components/autofill/core/browser/personal_data_manager_observer.h"
43 #include "components/autofill/core/browser/ui/label_formatter.h"
44 #include "components/autofill/core/browser/ui/label_formatter_utils.h"
45 #include "components/autofill/core/browser/ui/suggestion_selection.h"
46 #include "components/autofill/core/browser/validation.h"
47 #include "components/autofill/core/common/autofill_clock.h"
48 #include "components/autofill/core/common/autofill_constants.h"
49 #include "components/autofill/core/common/autofill_features.h"
50 #include "components/autofill/core/common/autofill_payments_features.h"
51 #include "components/autofill/core/common/autofill_prefs.h"
52 #include "components/autofill/core/common/autofill_switches.h"
53 #include "components/autofill/core/common/autofill_util.h"
54 #include "components/history/core/browser/history_service.h"
55 #include "components/prefs/pref_service.h"
56 #include "components/signin/public/identity_manager/identity_manager.h"
57 #include "components/sync/driver/sync_auth_util.h"
58 #include "components/sync/driver/sync_service.h"
59 #include "components/sync/driver/sync_service_utils.h"
60 #include "components/version_info/version_info.h"
61 #include "google_apis/gaia/gaia_auth_util.h"
62 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
63 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h"
64 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/source.h"
65 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/storage.h"
66 
67 namespace autofill {
68 
69 namespace {
70 
71 using ::i18n::addressinput::AddressField;
72 using ::i18n::addressinput::GetStreetAddressLinesAsSingleLine;
73 using ::i18n::addressinput::STREET_ADDRESS;
74 
75 // These values are persisted to logs. Entries should not be renumbered and
76 // numeric values should never be reused.
77 enum class MigrateUserOptedInWalletSyncType {
78   kNotMigrated = 0,
79   kMigratedFromCanonicalEmail = 1,
80   kMigratedFromNonCanonicalEmail = 2,
81   kNotMigratedUnexpectedPrimaryAccountIdWithEmail = 3,
82   kMaxValue = kNotMigratedUnexpectedPrimaryAccountIdWithEmail,
83 };
84 
85 template <typename T>
Deref(T * x)86 const T& Deref(T* x) {
87   return *x;
88 }
89 
90 template <typename T>
Deref(const std::unique_ptr<T> & x)91 const T& Deref(const std::unique_ptr<T>& x) {
92   return *x;
93 }
94 
95 template <typename T>
Deref(const T & x)96 const T& Deref(const T& x) {
97   return x;
98 }
99 
100 template <typename C, typename StringType>
FindElementByGUID(const C & container,const StringType & guid)101 typename C::const_iterator FindElementByGUID(const C& container,
102                                              const StringType& guid) {
103   return std::find_if(
104       std::begin(container), std::end(container),
105       [&guid](const auto& element) { return Deref(element).guid() == guid; });
106 }
107 
108 template <typename C, typename StringType>
FindByGUID(const C & container,const StringType & guid)109 bool FindByGUID(const C& container, const StringType& guid) {
110   return FindElementByGUID(container, guid) != container.end();
111 }
112 
113 template <typename C, typename T>
FindByContents(const C & container,const T & needle)114 bool FindByContents(const C& container, const T& needle) {
115   return base::ranges::any_of(container, [&needle](const auto& element) {
116     return element->Compare(needle) == 0;
117   });
118 }
119 
IsSyncEnabledFor(const syncer::SyncService * sync_service,syncer::ModelType model_type)120 bool IsSyncEnabledFor(const syncer::SyncService* sync_service,
121                       syncer::ModelType model_type) {
122   return sync_service != nullptr && sync_service->CanSyncFeatureStart() &&
123          sync_service->GetPreferredDataTypes().Has(model_type);
124 }
125 
126 // Receives the loaded profiles from the web data service and stores them in
127 // |*dest|. The pending handle is the address of the pending handle
128 // corresponding to this request type. This function is used to save bShouldoth
129 // server and local profiles and credit cards.
130 template <typename ValueType>
ReceiveLoadedDbValues(WebDataServiceBase::Handle h,WDTypedResult * result,WebDataServiceBase::Handle * pending_handle,std::vector<std::unique_ptr<ValueType>> * dest)131 void ReceiveLoadedDbValues(WebDataServiceBase::Handle h,
132                            WDTypedResult* result,
133                            WebDataServiceBase::Handle* pending_handle,
134                            std::vector<std::unique_ptr<ValueType>>* dest) {
135   DCHECK_EQ(*pending_handle, h);
136   *pending_handle = 0;
137 
138   *dest = std::move(
139       static_cast<WDResult<std::vector<std::unique_ptr<ValueType>>>*>(result)
140           ->GetValue());
141 }
142 
143 // A helper function for finding the maximum value in a string->int map.
CompareVotes(const std::pair<std::string,int> & a,const std::pair<std::string,int> & b)144 static bool CompareVotes(const std::pair<std::string, int>& a,
145                          const std::pair<std::string, int>& b) {
146   return a.second < b.second;
147 }
148 }  // namespace
149 
150 // Helper class to abstract the switching between account and profile storage
151 // for server cards away from the rest of PersonalDataManager.
152 class PersonalDatabaseHelper
153     : public AutofillWebDataServiceObserverOnUISequence {
154  public:
PersonalDatabaseHelper(PersonalDataManager * personal_data_manager)155   explicit PersonalDatabaseHelper(PersonalDataManager* personal_data_manager)
156       : personal_data_manager_(personal_data_manager) {}
157 
Init(scoped_refptr<AutofillWebDataService> profile_database,scoped_refptr<AutofillWebDataService> account_database)158   void Init(scoped_refptr<AutofillWebDataService> profile_database,
159             scoped_refptr<AutofillWebDataService> account_database) {
160     profile_database_ = profile_database;
161     account_database_ = account_database;
162 
163     if (!profile_database_) {
164       // In some tests, there are no dbs.
165       return;
166     }
167 
168     // Start observing the profile database. Don't observe the account database
169     // until we know that we should use it.
170     profile_database_->AddObserver(personal_data_manager_);
171 
172     // If we don't have an account_database , we always use the profile database
173     // for server data.
174     if (!account_database_) {
175       server_database_ = profile_database_;
176     } else {
177       // Wait for the call to SetUseAccountStorageForServerData to decide
178       // which database to use for server data.
179       server_database_ = nullptr;
180     }
181   }
182 
~PersonalDatabaseHelper()183   ~PersonalDatabaseHelper() override {
184     if (profile_database_) {
185       profile_database_->RemoveObserver(personal_data_manager_);
186     }
187 
188     // If we have a different server database, also remove its observer.
189     if (server_database_ && server_database_ != profile_database_) {
190       server_database_->RemoveObserver(personal_data_manager_);
191     }
192   }
193 
194   // Returns the database that should be used for storing local data.
GetLocalDatabase()195   scoped_refptr<AutofillWebDataService> GetLocalDatabase() {
196     return profile_database_;
197   }
198 
199   // Returns the database that should be used for storing server data.
GetServerDatabase()200   scoped_refptr<AutofillWebDataService> GetServerDatabase() {
201     return server_database_;
202   }
203 
204   // Whether we're currently using the ephemeral account storage for saving
205   // server data.
IsUsingAccountStorageForServerData()206   bool IsUsingAccountStorageForServerData() {
207     return server_database_ != profile_database_;
208   }
209 
210   // Set whether this should use the passed in account storage for server
211   // addresses. If false, this will use the profile_storage.
212   // It's an error to call this if no account storage was passed in at
213   // construction time.
SetUseAccountStorageForServerData(bool use_account_storage_for_server_cards)214   void SetUseAccountStorageForServerData(
215       bool use_account_storage_for_server_cards) {
216     if (!profile_database_) {
217       // In some tests, there are no dbs.
218       return;
219     }
220     scoped_refptr<AutofillWebDataService> new_server_database =
221         use_account_storage_for_server_cards ? account_database_
222                                              : profile_database_;
223     DCHECK(new_server_database != nullptr)
224         << "SetUseAccountStorageForServerData("
225         << use_account_storage_for_server_cards << "): storage not available.";
226 
227     if (new_server_database == server_database_) {
228       // Nothing to do :)
229       return;
230     }
231 
232     if (server_database_ != nullptr) {
233       if (server_database_ != profile_database_) {
234         // Remove the previous observer if we had any.
235         server_database_->RemoveObserver(personal_data_manager_);
236       }
237       personal_data_manager_->CancelPendingServerQueries();
238     }
239     server_database_ = new_server_database;
240     // We don't need to add an observer if server_database_ is equal to
241     // profile_database_, because we're already observing that.
242     if (server_database_ != profile_database_) {
243       server_database_->AddObserver(personal_data_manager_);
244     }
245     // Notify the manager that the database changed.
246     personal_data_manager_->Refresh();
247   }
248 
249  private:
250   scoped_refptr<AutofillWebDataService> profile_database_;
251   scoped_refptr<AutofillWebDataService> account_database_;
252 
253   // The database that should be used for server data. This will always be equal
254   // to either profile_database_, or account_database_.
255   scoped_refptr<AutofillWebDataService> server_database_;
256 
257   PersonalDataManager* personal_data_manager_;
258 
259   DISALLOW_COPY_AND_ASSIGN(PersonalDatabaseHelper);
260 };
261 
PersonalDataManager(const std::string & app_locale,const std::string & variations_country_code)262 PersonalDataManager::PersonalDataManager(
263     const std::string& app_locale,
264     const std::string& variations_country_code)
265     : app_locale_(app_locale),
266       variations_country_code_(variations_country_code),
267       test_data_creator_(kDisusedDataModelDeletionTimeDelta, app_locale_) {
268   database_helper_ = std::make_unique<PersonalDatabaseHelper>(this);
269 }
270 
PersonalDataManager(const std::string & app_locale)271 PersonalDataManager::PersonalDataManager(const std::string& app_locale)
272     : PersonalDataManager(app_locale, std::string()) {}
273 
Init(scoped_refptr<AutofillWebDataService> profile_database,scoped_refptr<AutofillWebDataService> account_database,PrefService * pref_service,signin::IdentityManager * identity_manager,AutofillProfileValidator * client_profile_validator,history::HistoryService * history_service,bool is_off_the_record)274 void PersonalDataManager::Init(
275     scoped_refptr<AutofillWebDataService> profile_database,
276     scoped_refptr<AutofillWebDataService> account_database,
277     PrefService* pref_service,
278     signin::IdentityManager* identity_manager,
279     AutofillProfileValidator* client_profile_validator,
280     history::HistoryService* history_service,
281     bool is_off_the_record) {
282   CountryNames::SetLocaleString(app_locale_);
283   database_helper_->Init(profile_database, account_database);
284 
285   SetPrefService(pref_service);
286 
287   // Listen for the preference changes.
288   pref_registrar_.Init(pref_service);
289   pref_registrar_.Add(
290       prefs::kAutofillProfileValidity,
291       base::BindRepeating(&PersonalDataManager::ResetProfileValidity,
292                           base::Unretained(this)));
293 
294   // Listen for URL deletions from browsing history.
295   history_service_ = history_service;
296   if (history_service_)
297     history_service_->AddObserver(this);
298 
299   // Listen for account cookie deletion by the user.
300   identity_manager_ = identity_manager;
301   if (identity_manager_)
302     identity_manager_->AddObserver(this);
303 
304   is_off_the_record_ = is_off_the_record;
305 
306   if (!is_off_the_record_) {
307     AutofillMetrics::LogIsAutofillEnabledAtStartup(IsAutofillEnabled());
308     AutofillMetrics::LogIsAutofillProfileEnabledAtStartup(
309         IsAutofillProfileEnabled());
310     AutofillMetrics::LogIsAutofillCreditCardEnabledAtStartup(
311         IsAutofillCreditCardEnabled());
312   }
313 
314   client_profile_validator_ = client_profile_validator;
315 
316   // WebDataService may not be available in tests.
317   if (!database_helper_->GetLocalDatabase()) {
318     return;
319   }
320 
321   database_helper_->GetLocalDatabase()->SetAutofillProfileChangedCallback(
322       base::BindRepeating(&PersonalDataManager::OnAutofillProfileChanged,
323                           weak_factory_.GetWeakPtr()));
324 
325   Refresh();
326 
327   // Check if profile cleanup has already been performed this major version.
328   is_autofill_profile_cleanup_pending_ =
329       pref_service_->GetInteger(prefs::kAutofillLastVersionDeduped) >=
330       CHROME_VERSION_MAJOR;
331   DVLOG(1) << "Autofill profile cleanup "
332            << (is_autofill_profile_cleanup_pending_ ? "needs to be"
333                                                     : "has already been")
334            << " performed for this version";
335 }
336 
~PersonalDataManager()337 PersonalDataManager::~PersonalDataManager() {
338   CancelPendingLocalQuery(&pending_profiles_query_);
339   CancelPendingLocalQuery(&pending_creditcards_query_);
340   CancelPendingLocalQuery(&pending_upi_ids_query_);
341   CancelPendingServerQueries();
342 }
343 
Shutdown()344 void PersonalDataManager::Shutdown() {
345   if (sync_service_)
346     sync_service_->RemoveObserver(this);
347   sync_service_ = nullptr;
348 
349   if (history_service_)
350     history_service_->RemoveObserver(this);
351   history_service_ = nullptr;
352 
353   if (identity_manager_)
354     identity_manager_->RemoveObserver(this);
355   identity_manager_ = nullptr;
356 }
357 
OnSyncServiceInitialized(syncer::SyncService * sync_service)358 void PersonalDataManager::OnSyncServiceInitialized(
359     syncer::SyncService* sync_service) {
360   if (sync_service_ != sync_service) {
361     // Before the sync service pointer gets changed, remove the observer.
362     if (sync_service_)
363       sync_service_->RemoveObserver(this);
364 
365     sync_service_ = sync_service;
366 
367     if (!sync_service_) {
368       ResetFullServerCards();
369       return;
370     }
371 
372     sync_service_->AddObserver(this);
373     // Re-mask all server cards if the upload state is not active.
374     bool is_upload_not_active =
375         syncer::GetUploadToGoogleState(
376             sync_service_, syncer::ModelType::AUTOFILL_WALLET_DATA) ==
377         syncer::UploadState::NOT_ACTIVE;
378     if (is_upload_not_active) {
379       ResetFullServerCards();
380     }
381     if (base::FeatureList::IsEnabled(
382             autofill::features::kAutofillEnableAccountWalletStorage)) {
383       // Use the ephemeral account storage when the user didn't enable the sync
384       // feature explicitly.
385       database_helper_->SetUseAccountStorageForServerData(
386           !sync_service->IsSyncFeatureEnabled());
387     }
388 
389     MigrateUserOptedInWalletSyncTransportIfNeeded();
390   }
391 }
392 
OnURLsDeleted(history::HistoryService *,const history::DeletionInfo & deletion_info)393 void PersonalDataManager::OnURLsDeleted(
394     history::HistoryService* /* history_service */,
395     const history::DeletionInfo& deletion_info) {
396   if (!deletion_info.is_from_expiration() && deletion_info.IsAllHistory()) {
397     AutofillDownloadManager::ClearUploadHistory(pref_service_);
398   }
399 }
400 
OnWebDataServiceRequestDone(WebDataServiceBase::Handle h,std::unique_ptr<WDTypedResult> result)401 void PersonalDataManager::OnWebDataServiceRequestDone(
402     WebDataServiceBase::Handle h,
403     std::unique_ptr<WDTypedResult> result) {
404   DCHECK(pending_profiles_query_ || pending_server_profiles_query_ ||
405          pending_creditcards_query_ || pending_server_creditcards_query_ ||
406          pending_server_creditcard_cloud_token_data_query_ ||
407          pending_customer_data_query_ || pending_upi_ids_query_ ||
408          pending_offer_data_query_);
409 
410   if (!result) {
411     // Error from the web database.
412     if (h == pending_creditcards_query_)
413       pending_creditcards_query_ = 0;
414     else if (h == pending_profiles_query_)
415       pending_profiles_query_ = 0;
416     else if (h == pending_server_creditcards_query_)
417       pending_server_creditcards_query_ = 0;
418     else if (h == pending_server_profiles_query_)
419       pending_server_profiles_query_ = 0;
420     else if (h == pending_server_creditcard_cloud_token_data_query_)
421       pending_server_creditcard_cloud_token_data_query_ = 0;
422     else if (h == pending_customer_data_query_)
423       pending_customer_data_query_ = 0;
424     else if (h == pending_upi_ids_query_)
425       pending_upi_ids_query_ = 0;
426     else if (h == pending_offer_data_query_)
427       pending_offer_data_query_ = 0;
428   } else {
429     switch (result->GetType()) {
430       case AUTOFILL_PROFILES_RESULT:
431         if (h == pending_profiles_query_) {
432           ReceiveLoadedDbValues(h, result.get(), &pending_profiles_query_,
433                                 &web_profiles_);
434         } else {
435           DCHECK_EQ(h, pending_server_profiles_query_)
436               << "received profiles from invalid request.";
437           ReceiveLoadedDbValues(h, result.get(),
438                                 &pending_server_profiles_query_,
439                                 &server_profiles_);
440         }
441         break;
442       case AUTOFILL_CREDITCARDS_RESULT:
443         if (h == pending_creditcards_query_) {
444           ReceiveLoadedDbValues(h, result.get(), &pending_creditcards_query_,
445                                 &local_credit_cards_);
446         } else {
447           DCHECK_EQ(h, pending_server_creditcards_query_)
448               << "received creditcards from invalid request.";
449           ReceiveLoadedDbValues(h, result.get(),
450                                 &pending_server_creditcards_query_,
451                                 &server_credit_cards_);
452         }
453         break;
454       case AUTOFILL_CLOUDTOKEN_RESULT:
455         DCHECK_EQ(h, pending_server_creditcard_cloud_token_data_query_)
456             << "received credit card cloud token data from invalid request.";
457         ReceiveLoadedDbValues(
458             h, result.get(), &pending_server_creditcard_cloud_token_data_query_,
459             &server_credit_card_cloud_token_data_);
460         break;
461       case AUTOFILL_CUSTOMERDATA_RESULT:
462         DCHECK_EQ(h, pending_customer_data_query_)
463             << "received customer data from invalid request.";
464         pending_customer_data_query_ = 0;
465 
466         payments_customer_data_ =
467             static_cast<WDResult<std::unique_ptr<PaymentsCustomerData>>*>(
468                 result.get())
469                 ->GetValue();
470         break;
471       case AUTOFILL_UPI_RESULT:
472         DCHECK_EQ(h, pending_upi_ids_query_)
473             << "received UPI IDs from invalid request.";
474         pending_upi_ids_query_ = 0;
475 
476         upi_ids_ =
477             static_cast<WDResult<std::vector<std::string>>*>(result.get())
478                 ->GetValue();
479         break;
480       case AUTOFILL_OFFER_DATA:
481         DCHECK_EQ(h, pending_offer_data_query_)
482             << "received autofill offer data from invalid request.";
483         ReceiveLoadedDbValues(h, result.get(), &pending_offer_data_query_,
484                               &autofill_offer_data_);
485         break;
486       default:
487         NOTREACHED();
488     }
489   }
490 
491   // If all requests have responded, then all personal data is loaded.
492   // We need to check if the server database is set here, because we won't have
493   // the server data yet if we don't have the database.
494   if (!HasPendingQueries() && database_helper_->GetServerDatabase()) {
495     // On initial data load, is_data_loaded_ will be false here.
496     if (!is_data_loaded_) {
497       // If sync is enabled for addresses, defer running cleanups until address
498       // sync has started; otherwise, do it now.
499       if (!IsSyncEnabledFor(sync_service_, syncer::AUTOFILL_PROFILE))
500         ApplyAddressFixesAndCleanups();
501 
502       // If sync is enabled for credit cards, defer running cleanups until card
503       // sync has started; otherwise, do it now.
504       if (!IsSyncEnabledFor(sync_service_, syncer::AUTOFILL_WALLET_DATA))
505         ApplyCardFixesAndCleanups();
506 
507       // Log address, credit card and offer startup metrics.
508       LogStoredProfileMetrics();
509       LogStoredCreditCardMetrics();
510       LogStoredOfferMetrics();
511     }
512 
513     is_data_loaded_ = true;
514     NotifyPersonalDataObserver();
515   }
516 }
517 
AutofillMultipleChangedBySync()518 void PersonalDataManager::AutofillMultipleChangedBySync() {
519   // After each change coming from sync we go through a two-step process:
520   //  - First, we post a task on the DB sequence to (potentially) convert server
521   // addresses to local addresses and update cards accordingly.
522   //  - This conversion task is concluded by a
523   //  AutofillAddressConversionCompleted() notification. As a second step, we
524   // need to refresh the PDM's view of the data.
525   ConvertWalletAddressesAndUpdateWalletCards();
526 }
527 
AutofillAddressConversionCompleted()528 void PersonalDataManager::AutofillAddressConversionCompleted() {
529   Refresh();
530 }
531 
SyncStarted(syncer::ModelType model_type)532 void PersonalDataManager::SyncStarted(syncer::ModelType model_type) {
533   // Run deferred autofill address profile startup code.
534   // See: OnSyncServiceInitialized
535   if (model_type == syncer::AUTOFILL_PROFILE)
536     ApplyAddressFixesAndCleanups();
537 
538   // Run deferred credit card startup code.
539   // See: OnSyncServiceInitialized
540   if (model_type == syncer::AUTOFILL_WALLET_DATA)
541     ApplyCardFixesAndCleanups();
542 }
543 
OnStateChanged(syncer::SyncService * sync_service)544 void PersonalDataManager::OnStateChanged(syncer::SyncService* sync_service) {
545   if (base::FeatureList::IsEnabled(
546           autofill::features::kAutofillEnableAccountWalletStorage)) {
547     // Use the ephemeral account storage when the user didn't enable the sync
548     // feature explicitly.
549     database_helper_->SetUseAccountStorageForServerData(
550         !sync_service->IsSyncFeatureEnabled());
551   }
552 }
553 
OnSyncShutdown(syncer::SyncService * sync_service)554 void PersonalDataManager::OnSyncShutdown(syncer::SyncService* sync_service) {
555   DCHECK_EQ(sync_service_, sync_service);
556   sync_service_->RemoveObserver(this);
557   sync_service_ = nullptr;
558 }
559 
GetAccountInfoForPaymentsServer() const560 CoreAccountInfo PersonalDataManager::GetAccountInfoForPaymentsServer() const {
561   // Return the account of the active signed-in user irrespective of whether
562   // they enabled sync or not.
563   // However if there is no |sync_service_| (e.g. in incognito), return the
564   // latest cached AccountInfo of the user's primary account, which is empty if
565   // the user has disabled sync.
566   // In both cases, the AccountInfo will be empty if the user is not signed in.
567   return sync_service_ ? sync_service_->GetAuthenticatedAccountInfo()
568                        : identity_manager_->GetPrimaryAccountInfo();
569 }
570 
571 // TODO(crbug.com/903914): Clean up this function so that it's more clear what
572 // it's checking. It should not check the database helper.
IsSyncFeatureEnabled() const573 bool PersonalDataManager::IsSyncFeatureEnabled() const {
574   if (!sync_service_)
575     return false;
576 
577   return !sync_service_->GetAuthenticatedAccountInfo().IsEmpty() &&
578          !database_helper_->IsUsingAccountStorageForServerData();
579 }
580 
OnAccountsCookieDeletedByUserAction()581 void PersonalDataManager::OnAccountsCookieDeletedByUserAction() {
582   // Clear all the Sync Transport feature opt-ins.
583   ::autofill::prefs::ClearSyncTransportOptIns(pref_service_);
584 }
585 
586 // TODO(crbug.com/903896): Generalize this to all the possible states relavant
587 // to Autofill.
GetSyncSigninState() const588 AutofillSyncSigninState PersonalDataManager::GetSyncSigninState() const {
589   // Check if the user is signed out.
590   if (!sync_service_ || !identity_manager_ ||
591       syncer::DetermineAccountToUse(identity_manager_).account_info.IsEmpty()) {
592     return AutofillSyncSigninState::kSignedOut;
593   }
594 
595   // Check if the user has turned on sync.
596   if (sync_service_->IsSyncFeatureEnabled()) {
597     // TODO(crbug.com/906995): Remove this once the kStopSyncInPausedState
598     // feature is launched.
599     if (syncer::IsWebSignout(sync_service_->GetAuthError())) {
600       return AutofillSyncSigninState::kSyncPaused;
601     }
602     return AutofillSyncSigninState::kSignedInAndSyncFeatureEnabled;
603   }
604 
605   if (sync_service_->GetTransportState() ==
606       syncer::SyncService::TransportState::PAUSED) {
607     return AutofillSyncSigninState::kSyncPaused;
608   }
609 
610   // Check if the feature is enabled and if Wallet data types are supported.
611   if (base::FeatureList::IsEnabled(
612           features::kAutofillEnableAccountWalletStorage) &&
613       sync_service_->GetActiveDataTypes().Has(syncer::AUTOFILL_WALLET_DATA)) {
614     return AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled;
615   }
616 
617   return AutofillSyncSigninState::kSignedIn;
618 }
619 
AddObserver(PersonalDataManagerObserver * observer)620 void PersonalDataManager::AddObserver(PersonalDataManagerObserver* observer) {
621   observers_.AddObserver(observer);
622 }
623 
RemoveObserver(PersonalDataManagerObserver * observer)624 void PersonalDataManager::RemoveObserver(
625     PersonalDataManagerObserver* observer) {
626   observers_.RemoveObserver(observer);
627 }
628 
MarkObserversInsufficientFormDataForImport()629 void PersonalDataManager::MarkObserversInsufficientFormDataForImport() {
630   for (PersonalDataManagerObserver& observer : observers_)
631     observer.OnInsufficientFormData();
632 }
633 
RecordUseOf(const AutofillDataModel & data_model)634 void PersonalDataManager::RecordUseOf(const AutofillDataModel& data_model) {
635   if (is_off_the_record_)
636     return;
637 
638   CreditCard* credit_card = GetCreditCardByGUID(data_model.guid());
639   if (credit_card) {
640     credit_card->RecordAndLogUse();
641 
642     if (credit_card->record_type() == CreditCard::LOCAL_CARD) {
643       // Fail silently if there's no local database, because we need to support
644       // this for tests.
645       if (database_helper_->GetLocalDatabase()) {
646         database_helper_->GetLocalDatabase()->UpdateCreditCard(*credit_card);
647       }
648     } else {
649       DCHECK(database_helper_->GetServerDatabase())
650           << "Recording use of server card without server storage.";
651       database_helper_->GetServerDatabase()->UpdateServerCardMetadata(
652           *credit_card);
653     }
654 
655     Refresh();
656     return;
657   }
658 
659   AutofillProfile* profile = GetProfileByGUID(data_model.guid());
660   if (profile) {
661     profile->RecordAndLogUse();
662 
663     switch (profile->record_type()) {
664       case AutofillProfile::LOCAL_PROFILE:
665         UpdateProfileInDB(*profile, /*enforced=*/true);
666         break;
667       case AutofillProfile::SERVER_PROFILE:
668         DCHECK(database_helper_->GetServerDatabase())
669             << "Recording use of server address without server storage.";
670         database_helper_->GetServerDatabase()->UpdateServerAddressMetadata(
671             *profile);
672         Refresh();
673         break;
674     }
675   }
676 }
677 
AddUpiId(const std::string & upi_id)678 void PersonalDataManager::AddUpiId(const std::string& upi_id) {
679   DCHECK(!upi_id.empty());
680   if (is_off_the_record_ || !database_helper_->GetLocalDatabase())
681     return;
682 
683   // Don't add a duplicate.
684   if (std::find(upi_ids_.begin(), upi_ids_.end(), upi_id) != upi_ids_.end())
685     return;
686 
687   database_helper_->GetLocalDatabase()->AddUpiId(upi_id);
688 
689   // Refresh our local cache and send notifications to observers.
690   Refresh();
691 }
692 
GetUpiIds()693 std::vector<std::string> PersonalDataManager::GetUpiIds() {
694   return upi_ids_;
695 }
696 
AddProfile(const AutofillProfile & profile)697 void PersonalDataManager::AddProfile(const AutofillProfile& profile) {
698   if (!IsAutofillProfileEnabled())
699     return;
700 
701   if (is_off_the_record_)
702     return;
703 
704   if (!database_helper_->GetLocalDatabase())
705     return;
706 
707   AddProfileToDB(profile);
708 }
709 
UpdateProfile(const AutofillProfile & profile)710 void PersonalDataManager::UpdateProfile(const AutofillProfile& profile) {
711   if (is_off_the_record_)
712     return;
713 
714   if (profile.IsEmpty(app_locale_)) {
715     RemoveByGUID(profile.guid());
716     return;
717   }
718 
719   if (!database_helper_->GetLocalDatabase())
720     return;
721 
722   UpdateProfileInDB(profile);
723 }
724 
GetProfileByGUID(const std::string & guid)725 AutofillProfile* PersonalDataManager::GetProfileByGUID(
726     const std::string& guid) {
727   return GetProfileFromProfilesByGUID(guid, GetProfiles());
728 }
729 
730 // static
GetProfileFromProfilesByGUID(const std::string & guid,const std::vector<AutofillProfile * > & profiles)731 AutofillProfile* PersonalDataManager::GetProfileFromProfilesByGUID(
732     const std::string& guid,
733     const std::vector<AutofillProfile*>& profiles) {
734   auto iter = FindElementByGUID(profiles, guid);
735   return iter != profiles.end() ? *iter : nullptr;
736 }
737 
AddCreditCard(const CreditCard & credit_card)738 void PersonalDataManager::AddCreditCard(const CreditCard& credit_card) {
739   if (!IsAutofillCreditCardEnabled())
740     return;
741 
742   if (is_off_the_record_)
743     return;
744 
745   if (credit_card.IsEmpty(app_locale_))
746     return;
747 
748   if (FindByGUID(local_credit_cards_, credit_card.guid()))
749     return;
750 
751   if (!database_helper_->GetLocalDatabase())
752     return;
753 
754   // Don't add a duplicate.
755   if (FindByContents(local_credit_cards_, credit_card))
756     return;
757 
758   // Add the new credit card to the web database.
759   database_helper_->GetLocalDatabase()->AddCreditCard(credit_card);
760 
761   // Refresh our local cache and send notifications to observers.
762   Refresh();
763 }
764 
DeleteLocalCreditCards(const std::vector<CreditCard> & cards)765 void PersonalDataManager::DeleteLocalCreditCards(
766     const std::vector<CreditCard>& cards) {
767   DCHECK(database_helper_);
768   DCHECK(database_helper_->GetLocalDatabase())
769       << "Use of local card without local storage.";
770 
771   for (const auto& card : cards)
772     database_helper_->GetLocalDatabase()->RemoveCreditCard(card.guid());
773 
774   // Refresh the database, so latest state is reflected in all consumers.
775   if (!cards.empty())
776     Refresh();
777 }
778 
UpdateCreditCard(const CreditCard & credit_card)779 void PersonalDataManager::UpdateCreditCard(const CreditCard& credit_card) {
780   DCHECK_EQ(CreditCard::LOCAL_CARD, credit_card.record_type());
781   if (is_off_the_record_)
782     return;
783 
784   CreditCard* existing_credit_card = GetCreditCardByGUID(credit_card.guid());
785   if (!existing_credit_card)
786     return;
787 
788   // Don't overwrite the origin for a credit card that is already stored.
789   if (existing_credit_card->Compare(credit_card) == 0)
790     return;
791 
792   if (credit_card.IsEmpty(app_locale_)) {
793     RemoveByGUID(credit_card.guid());
794     return;
795   }
796 
797   // Update the cached version.
798   *existing_credit_card = credit_card;
799 
800   if (!database_helper_->GetLocalDatabase())
801     return;
802 
803   // Make the update.
804   database_helper_->GetLocalDatabase()->UpdateCreditCard(credit_card);
805 
806   // Refresh our local cache and send notifications to observers.
807   Refresh();
808 }
809 
AddFullServerCreditCard(const CreditCard & credit_card)810 void PersonalDataManager::AddFullServerCreditCard(
811     const CreditCard& credit_card) {
812   DCHECK_EQ(CreditCard::FULL_SERVER_CARD, credit_card.record_type());
813   DCHECK(!credit_card.IsEmpty(app_locale_));
814   DCHECK(!credit_card.server_id().empty());
815 
816   if (is_off_the_record_)
817     return;
818 
819   DCHECK(database_helper_->GetServerDatabase())
820       << "Adding server card without server storage.";
821 
822   // Don't add a duplicate.
823   if (FindByGUID(server_credit_cards_, credit_card.guid()) ||
824       FindByContents(server_credit_cards_, credit_card))
825     return;
826 
827   // Add the new credit card to the web database.
828   database_helper_->GetServerDatabase()->AddFullServerCreditCard(credit_card);
829 
830   // Refresh our local cache and send notifications to observers.
831   Refresh();
832 }
833 
UpdateServerCreditCard(const CreditCard & credit_card)834 void PersonalDataManager::UpdateServerCreditCard(
835     const CreditCard& credit_card) {
836   DCHECK_NE(CreditCard::LOCAL_CARD, credit_card.record_type());
837 
838   if (is_off_the_record_ || !database_helper_->GetServerDatabase())
839     return;
840 
841   // Look up by server id, not GUID.
842   const CreditCard* existing_credit_card = nullptr;
843   for (const auto& server_card : server_credit_cards_) {
844     if (credit_card.server_id() == server_card->server_id()) {
845       existing_credit_card = server_card.get();
846       break;
847     }
848   }
849   if (!existing_credit_card)
850     return;
851 
852   DCHECK_NE(existing_credit_card->record_type(), credit_card.record_type());
853   DCHECK_EQ(existing_credit_card->Label(), credit_card.Label());
854   if (existing_credit_card->record_type() == CreditCard::MASKED_SERVER_CARD) {
855     database_helper_->GetServerDatabase()->UnmaskServerCreditCard(
856         credit_card, credit_card.number());
857   } else {
858     database_helper_->GetServerDatabase()->MaskServerCreditCard(
859         credit_card.server_id());
860   }
861 
862   Refresh();
863 }
864 
UpdateServerCardMetadata(const CreditCard & credit_card)865 void PersonalDataManager::UpdateServerCardMetadata(
866     const CreditCard& credit_card) {
867   DCHECK_NE(CreditCard::LOCAL_CARD, credit_card.record_type());
868 
869   if (is_off_the_record_)
870     return;
871 
872   DCHECK(database_helper_->GetServerDatabase())
873       << "Updating server card metadata without server storage.";
874 
875   database_helper_->GetServerDatabase()->UpdateServerCardMetadata(credit_card);
876 
877   Refresh();
878 }
879 
ResetFullServerCard(const std::string & guid)880 void PersonalDataManager::ResetFullServerCard(const std::string& guid) {
881   for (const auto& card : server_credit_cards_) {
882     if (card->guid() == guid) {
883       DCHECK_EQ(card->record_type(), CreditCard::FULL_SERVER_CARD);
884       CreditCard card_copy = *card;
885       card_copy.set_record_type(CreditCard::MASKED_SERVER_CARD);
886       card_copy.SetNumber(card->LastFourDigits());
887       UpdateServerCreditCard(card_copy);
888       break;
889     }
890   }
891 }
892 
ResetFullServerCards()893 void PersonalDataManager::ResetFullServerCards() {
894   for (const auto& card : server_credit_cards_) {
895     if (card->record_type() == CreditCard::FULL_SERVER_CARD) {
896       CreditCard card_copy = *card;
897       card_copy.set_record_type(CreditCard::MASKED_SERVER_CARD);
898       card_copy.SetNumber(card->LastFourDigits());
899       UpdateServerCreditCard(card_copy);
900     }
901   }
902 }
903 
ClearAllServerData()904 void PersonalDataManager::ClearAllServerData() {
905   // This could theoretically be called before we get the data back from the
906   // database on startup, and it could get called when the wallet pref is
907   // off (meaning this class won't even query for the server data) so don't
908   // check the server_credit_cards_/profiles_ before posting to the DB.
909 
910   // TODO(crbug.com/864519): Move this nullcheck logic to the database helper.
911   // The server database can be null for a limited amount of time before the
912   // sync service gets initialized. Not clearing it does not matter in that case
913   // since it will not have been created yet (nothing to clear).
914   if (database_helper_->GetServerDatabase())
915     database_helper_->GetServerDatabase()->ClearAllServerData();
916 
917   // The above call will eventually clear our server data by notifying us
918   // that the data changed and then this class will re-fetch. Preemptively
919   // clear so that tests can synchronously verify that this data was cleared.
920   server_credit_cards_.clear();
921   server_profiles_.clear();
922   payments_customer_data_.reset();
923   server_credit_card_cloud_token_data_.clear();
924   autofill_offer_data_.clear();
925 }
926 
ClearAllLocalData()927 void PersonalDataManager::ClearAllLocalData() {
928   database_helper_->GetLocalDatabase()->ClearAllLocalData();
929   local_credit_cards_.clear();
930   web_profiles_.clear();
931 }
932 
AddServerCreditCardForTest(std::unique_ptr<CreditCard> credit_card)933 void PersonalDataManager::AddServerCreditCardForTest(
934     std::unique_ptr<CreditCard> credit_card) {
935   server_credit_cards_.push_back(std::move(credit_card));
936 }
937 
IsUsingAccountStorageForServerDataForTest() const938 bool PersonalDataManager::IsUsingAccountStorageForServerDataForTest() const {
939   return database_helper_->IsUsingAccountStorageForServerData();
940 }
941 
SetSyncServiceForTest(syncer::SyncService * sync_service)942 void PersonalDataManager::SetSyncServiceForTest(
943     syncer::SyncService* sync_service) {
944   if (sync_service_)
945     sync_service_->RemoveObserver(this);
946 
947   sync_service_ = sync_service;
948 
949   if (sync_service_)
950     sync_service_->AddObserver(this);
951 }
952 
953 void PersonalDataManager::
RemoveAutofillProfileByGUIDAndBlankCreditCardReference(const std::string & guid)954     RemoveAutofillProfileByGUIDAndBlankCreditCardReference(
955         const std::string& guid) {
956   RemoveProfileFromDB(guid);
957 
958   // Reset the billing_address_id of any card that refered to this profile.
959   for (CreditCard* credit_card : GetCreditCards()) {
960     if (credit_card->billing_address_id() == guid) {
961       credit_card->set_billing_address_id("");
962 
963       if (credit_card->record_type() == CreditCard::LOCAL_CARD) {
964         database_helper_->GetLocalDatabase()->UpdateCreditCard(*credit_card);
965       } else {
966         DCHECK(database_helper_->GetServerDatabase())
967             << "Updating metadata on null server db.";
968         database_helper_->GetServerDatabase()->UpdateServerCardMetadata(
969             *credit_card);
970       }
971     }
972   }
973 }
974 
RemoveByGUID(const std::string & guid)975 void PersonalDataManager::RemoveByGUID(const std::string& guid) {
976   if (is_off_the_record_)
977     return;
978 
979   if (!database_helper_->GetLocalDatabase())
980     return;
981 
982   bool is_credit_card = FindByGUID(local_credit_cards_, guid);
983   if (is_credit_card) {
984     database_helper_->GetLocalDatabase()->RemoveCreditCard(guid);
985     // Refresh our local cache and send notifications to observers.
986     Refresh();
987   } else {
988     RemoveAutofillProfileByGUIDAndBlankCreditCardReference(guid);
989   }
990 }
991 
GetCreditCardByGUID(const std::string & guid)992 CreditCard* PersonalDataManager::GetCreditCardByGUID(const std::string& guid) {
993   const std::vector<CreditCard*>& credit_cards = GetCreditCards();
994   auto iter = FindElementByGUID(credit_cards, guid);
995   return iter != credit_cards.end() ? *iter : nullptr;
996 }
997 
GetCreditCardByNumber(const std::string & number)998 CreditCard* PersonalDataManager::GetCreditCardByNumber(
999     const std::string& number) {
1000   CreditCard numbered_card;
1001   numbered_card.SetNumber(base::ASCIIToUTF16(number));
1002   for (CreditCard* credit_card : GetCreditCards()) {
1003     DCHECK(credit_card);
1004     if (credit_card->HasSameNumberAs(numbered_card))
1005       return credit_card;
1006   }
1007   return nullptr;
1008 }
1009 
GetNonEmptyTypes(ServerFieldTypeSet * non_empty_types) const1010 void PersonalDataManager::GetNonEmptyTypes(
1011     ServerFieldTypeSet* non_empty_types) const {
1012   for (AutofillProfile* profile : GetProfiles())
1013     profile->GetNonEmptyTypes(app_locale_, non_empty_types);
1014   for (CreditCard* card : GetCreditCards())
1015     card->GetNonEmptyTypes(app_locale_, non_empty_types);
1016 }
1017 
IsDataLoaded() const1018 bool PersonalDataManager::IsDataLoaded() const {
1019   return is_data_loaded_;
1020 }
1021 
GetProfiles() const1022 std::vector<AutofillProfile*> PersonalDataManager::GetProfiles() const {
1023   std::vector<AutofillProfile*> result;
1024   result.reserve(web_profiles_.size());
1025   for (const auto& profile : web_profiles_)
1026     result.push_back(profile.get());
1027   return result;
1028 }
1029 
UpdateProfilesServerValidityMapsIfNeeded(const std::vector<AutofillProfile * > & profiles)1030 void PersonalDataManager::UpdateProfilesServerValidityMapsIfNeeded(
1031     const std::vector<AutofillProfile*>& profiles) {
1032   if (!profiles_server_validities_need_update_)
1033     return;
1034   profiles_server_validities_need_update_ = false;
1035   for (auto* profile : profiles) {
1036     profile->UpdateServerValidityMap(GetProfileValidityByGUID(profile->guid()));
1037   }
1038 }
1039 
UpdateClientValidityStates(const std::vector<AutofillProfile * > & profiles)1040 void PersonalDataManager::UpdateClientValidityStates(
1041     const std::vector<AutofillProfile*>& profiles) {
1042   if (!base::FeatureList::IsEnabled(
1043           autofill::features::kAutofillProfileClientValidation))
1044     return;
1045 
1046   if (!client_profile_validator_)
1047     return;
1048 
1049   // The profiles' validity states need to be updated for each major version, to
1050   // keep up with the validation logic.
1051   bool update_validation =
1052       pref_service_->GetInteger(prefs::kAutofillLastVersionValidated) <
1053       CHROME_VERSION_MAJOR;
1054 
1055   DVLOG(1) << "Autofill profile client validation "
1056            << (update_validation ? "needs to be" : "has already been")
1057            << " performed for this version";
1058 
1059   for (const auto* profile : profiles) {
1060     if (!profile->is_client_validity_states_updated() || update_validation) {
1061       profile->set_is_client_validity_states_updated(false);
1062       ongoing_profile_changes_[profile->guid()].push_back(
1063           AutofillProfileDeepChange(AutofillProfileChange::UPDATE, *profile));
1064       ongoing_profile_changes_[profile->guid()].back().set_enforced();
1065       client_profile_validator_->StartProfileValidation(
1066           profile, base::BindOnce(&PersonalDataManager::OnValidated,
1067                                   weak_factory_.GetWeakPtr()));
1068     }
1069   }
1070 
1071   // Set the pref to the current major version if already not set.
1072   if (update_validation)
1073     pref_service_->SetInteger(prefs::kAutofillLastVersionValidated,
1074                               CHROME_VERSION_MAJOR);
1075 }
1076 
UpdateClientValidityStates(const AutofillProfile & profile)1077 bool PersonalDataManager::UpdateClientValidityStates(
1078     const AutofillProfile& profile) {
1079   if (!base::FeatureList::IsEnabled(
1080           autofill::features::kAutofillProfileClientValidation) ||
1081       !client_profile_validator_ ||
1082       profile.is_client_validity_states_updated()) {
1083     OnValidated(&profile);
1084     return false;
1085   }
1086 
1087   client_profile_validator_->StartProfileValidation(
1088       &profile, base::BindOnce(&PersonalDataManager::OnValidated,
1089                                weak_factory_.GetWeakPtr()));
1090   return true;
1091 }
1092 
GetServerProfiles() const1093 std::vector<AutofillProfile*> PersonalDataManager::GetServerProfiles() const {
1094   std::vector<AutofillProfile*> result;
1095   if (!IsAutofillProfileEnabled())
1096     return result;
1097   result.reserve(server_profiles_.size());
1098   for (const auto& profile : server_profiles_)
1099     result.push_back(profile.get());
1100   return result;
1101 }
1102 
GetLocalCreditCards() const1103 std::vector<CreditCard*> PersonalDataManager::GetLocalCreditCards() const {
1104   std::vector<CreditCard*> result;
1105   result.reserve(local_credit_cards_.size());
1106   for (const auto& card : local_credit_cards_)
1107     result.push_back(card.get());
1108   return result;
1109 }
1110 
GetServerCreditCards() const1111 std::vector<CreditCard*> PersonalDataManager::GetServerCreditCards() const {
1112   std::vector<CreditCard*> result;
1113   if (!IsAutofillWalletImportEnabled())
1114     return result;
1115 
1116   result.reserve(server_credit_cards_.size());
1117   for (const auto& card : server_credit_cards_) {
1118     // Do not add Google issued credit card if experiment is disabled.
1119     if (card.get()->IsGoogleIssuedCard() &&
1120         !base::FeatureList::IsEnabled(
1121             autofill::features::kAutofillEnableGoogleIssuedCard)) {
1122       continue;
1123     }
1124     result.push_back(card.get());
1125   }
1126   return result;
1127 }
1128 
GetCreditCards() const1129 std::vector<CreditCard*> PersonalDataManager::GetCreditCards() const {
1130   std::vector<CreditCard*> result;
1131 
1132   result.reserve(local_credit_cards_.size() + server_credit_cards_.size());
1133   for (const auto& card : local_credit_cards_)
1134     result.push_back(card.get());
1135   if (IsAutofillWalletImportEnabled()) {
1136     for (const auto& card : server_credit_cards_) {
1137       // Do not add Google issued credit card if experiment is disabled.
1138       if (card.get()->IsGoogleIssuedCard() &&
1139           !base::FeatureList::IsEnabled(
1140               autofill::features::kAutofillEnableGoogleIssuedCard)) {
1141         continue;
1142       }
1143       result.push_back(card.get());
1144     }
1145   }
1146   return result;
1147 }
1148 
GetPaymentsCustomerData() const1149 PaymentsCustomerData* PersonalDataManager::GetPaymentsCustomerData() const {
1150   return payments_customer_data_ ? payments_customer_data_.get() : nullptr;
1151 }
1152 
1153 std::vector<CreditCardCloudTokenData*>
GetCreditCardCloudTokenData() const1154 PersonalDataManager::GetCreditCardCloudTokenData() const {
1155   std::vector<CreditCardCloudTokenData*> result;
1156   if (!IsAutofillWalletImportEnabled())
1157     return result;
1158 
1159   result.reserve(server_credit_card_cloud_token_data_.size());
1160   for (const auto& data : server_credit_card_cloud_token_data_)
1161     result.push_back(data.get());
1162   return result;
1163 }
1164 
GetCreditCardOffers() const1165 std::vector<AutofillOfferData*> PersonalDataManager::GetCreditCardOffers()
1166     const {
1167   if (!IsAutofillWalletImportEnabled())
1168     return {};
1169 
1170   std::vector<AutofillOfferData*> result;
1171   result.reserve(autofill_offer_data_.size());
1172   for (const auto& data : autofill_offer_data_)
1173     result.push_back(data.get());
1174   return result;
1175 }
1176 
Refresh()1177 void PersonalDataManager::Refresh() {
1178   LoadProfiles();
1179   LoadCreditCards();
1180   LoadCreditCardCloudTokenData();
1181   LoadPaymentsCustomerData();
1182   LoadUpiIds();
1183   LoadCreditCardOffers();
1184 }
1185 
GetProfilesToSuggest() const1186 std::vector<AutofillProfile*> PersonalDataManager::GetProfilesToSuggest()
1187     const {
1188   if (!IsAutofillProfileEnabled())
1189     return std::vector<AutofillProfile*>{};
1190 
1191   std::vector<AutofillProfile*> profiles = GetProfiles();
1192 
1193   bool use_server_validation = base::FeatureList::IsEnabled(
1194       autofill::features::kAutofillProfileServerValidation);
1195   bool use_client_validation = base::FeatureList::IsEnabled(
1196       autofill::features::kAutofillProfileClientValidation);
1197 
1198   // Rank the suggestions by frescocency (see AutofillDataModel for details).
1199   // Frescocency is frecency + validity score.
1200   const base::Time comparison_time = AutofillClock::Now();
1201   std::sort(profiles.begin(), profiles.end(),
1202             [comparison_time, use_client_validation, use_server_validation](
1203                 const AutofillProfile* a, const AutofillProfile* b) {
1204               return a->HasGreaterFrescocencyThan(b, comparison_time,
1205                                                   use_client_validation,
1206                                                   use_server_validation);
1207             });
1208 
1209   return profiles;
1210 }
1211 
GetProfileSuggestions(const AutofillType & type,const base::string16 & field_contents,bool field_is_autofilled,const std::vector<ServerFieldType> & field_types)1212 std::vector<Suggestion> PersonalDataManager::GetProfileSuggestions(
1213     const AutofillType& type,
1214     const base::string16& field_contents,
1215     bool field_is_autofilled,
1216     const std::vector<ServerFieldType>& field_types) {
1217   if (IsInAutofillSuggestionsDisabledExperiment())
1218     return std::vector<Suggestion>();
1219 
1220   const AutofillProfileComparator comparator(app_locale_);
1221   base::string16 field_contents_canon =
1222       comparator.NormalizeForComparison(field_contents);
1223 
1224   if (base::FeatureList::IsEnabled(
1225           autofill::features::kAutofillProfileServerValidation)) {
1226     UpdateProfilesServerValidityMapsIfNeeded(GetProfiles());
1227   }
1228 
1229   // Get the profiles to suggest, which are already sorted.
1230   std::vector<AutofillProfile*> sorted_profiles = GetProfilesToSuggest();
1231 
1232   // When suggesting with no prefix to match, suppress disused address
1233   // suggestions as well as those based on invalid profile data.
1234   if (field_contents_canon.empty()) {
1235     const base::Time min_last_used =
1236         AutofillClock::Now() - kDisusedDataModelTimeDelta;
1237     suggestion_selection::RemoveProfilesNotUsedSinceTimestamp(min_last_used,
1238                                                               &sorted_profiles);
1239   }
1240 
1241   std::vector<AutofillProfile*> matched_profiles;
1242   std::vector<Suggestion> suggestions =
1243       suggestion_selection::GetPrefixMatchedSuggestions(
1244           type, field_contents, field_contents_canon, comparator,
1245           field_is_autofilled, sorted_profiles, &matched_profiles);
1246 
1247   // Don't show two suggestions if one is a subset of the other.
1248   std::vector<AutofillProfile*> unique_matched_profiles;
1249   std::vector<Suggestion> unique_suggestions =
1250       suggestion_selection::GetUniqueSuggestions(
1251           field_types, comparator, app_locale_, matched_profiles, suggestions,
1252           &unique_matched_profiles);
1253 
1254   std::unique_ptr<LabelFormatter> formatter;
1255   bool use_formatter;
1256 
1257 #if !defined(OS_ANDROID) && !defined(OS_IOS)
1258   use_formatter = base::FeatureList::IsEnabled(
1259       autofill::features::kAutofillUseImprovedLabelDisambiguation);
1260 #else
1261   use_formatter = base::FeatureList::IsEnabled(
1262       autofill::features::kAutofillUseMobileLabelDisambiguation);
1263 #endif  // !defined(OS_ANDROID) && !defined(OS_IOS)
1264 
1265   // The formatter stores a constant reference to |unique_matched_profiles|.
1266   // This is safe since the formatter is destroyed when this function returns.
1267   formatter = use_formatter
1268                   ? LabelFormatter::Create(unique_matched_profiles, app_locale_,
1269                                            type.GetStorableType(), field_types)
1270                   : nullptr;
1271 
1272   // Generate disambiguating labels based on the list of matches.
1273   std::vector<base::string16> labels;
1274   if (formatter) {
1275     labels = formatter->GetLabels();
1276   } else {
1277     AutofillProfile::CreateInferredLabels(unique_matched_profiles, &field_types,
1278                                           type.GetStorableType(), 1,
1279                                           app_locale_, &labels);
1280   }
1281 
1282   if (use_formatter && !unique_suggestions.empty()) {
1283     AutofillMetrics::LogProfileSuggestionsMadeWithFormatter(formatter !=
1284                                                             nullptr);
1285   }
1286 
1287   suggestion_selection::PrepareSuggestions(labels, &unique_suggestions,
1288                                            comparator);
1289 
1290   return unique_suggestions;
1291 }
1292 
1293 // TODO(crbug.com/613187): Investigate if it would be more efficient to dedupe
1294 // with a vector instead of a list.
GetCreditCardsToSuggest(bool include_server_cards) const1295 const std::vector<CreditCard*> PersonalDataManager::GetCreditCardsToSuggest(
1296     bool include_server_cards) const {
1297   if (!IsAutofillCreditCardEnabled())
1298     return std::vector<CreditCard*>{};
1299 
1300   std::vector<CreditCard*> credit_cards;
1301   if (include_server_cards && ShouldSuggestServerCards()) {
1302     credit_cards = GetCreditCards();
1303   } else {
1304     credit_cards = GetLocalCreditCards();
1305   }
1306 
1307   std::list<CreditCard*> cards_to_dedupe(credit_cards.begin(),
1308                                          credit_cards.end());
1309 
1310   DedupeCreditCardToSuggest(&cards_to_dedupe);
1311 
1312   std::vector<CreditCard*> cards_to_suggest(
1313       std::make_move_iterator(std::begin(cards_to_dedupe)),
1314       std::make_move_iterator(std::end(cards_to_dedupe)));
1315 
1316   // Rank the cards by frecency (see AutofillDataModel for details). All expired
1317   // cards should be suggested last, also by frecency.
1318   base::Time comparison_time = AutofillClock::Now();
1319   std::stable_sort(cards_to_suggest.begin(), cards_to_suggest.end(),
1320                    [comparison_time](const CreditCard* a, const CreditCard* b) {
1321                      bool a_is_expired = a->IsExpired(comparison_time);
1322                      if (a_is_expired != b->IsExpired(comparison_time))
1323                        return !a_is_expired;
1324 
1325                      return a->HasGreaterFrecencyThan(b, comparison_time);
1326                    });
1327 
1328   return cards_to_suggest;
1329 }
1330 
1331 // static
RemoveExpiredCreditCardsNotUsedSinceTimestamp(base::Time comparison_time,base::Time min_last_used,std::vector<CreditCard * > * cards)1332 void PersonalDataManager::RemoveExpiredCreditCardsNotUsedSinceTimestamp(
1333     base::Time comparison_time,
1334     base::Time min_last_used,
1335     std::vector<CreditCard*>* cards) {
1336   const size_t original_size = cards->size();
1337   // Split the vector into [unexpired-or-expired-but-after-timestamp,
1338   // expired-and-before-timestamp], then delete the latter.
1339   cards->erase(std::stable_partition(
1340                    cards->begin(), cards->end(),
1341                    [comparison_time, min_last_used](const CreditCard* c) {
1342                      return !c->IsExpired(comparison_time) ||
1343                             c->use_date() > min_last_used;
1344                    }),
1345                cards->end());
1346   const size_t num_cards_supressed = original_size - cards->size();
1347   AutofillMetrics::LogNumberOfCreditCardsSuppressedForDisuse(
1348       num_cards_supressed);
1349 }
1350 
GetCreditCardSuggestions(const AutofillType & type,const base::string16 & field_contents,bool include_server_cards)1351 std::vector<Suggestion> PersonalDataManager::GetCreditCardSuggestions(
1352     const AutofillType& type,
1353     const base::string16& field_contents,
1354     bool include_server_cards) {
1355   if (IsInAutofillSuggestionsDisabledExperiment())
1356     return std::vector<Suggestion>();
1357   std::vector<CreditCard*> cards =
1358       GetCreditCardsToSuggest(include_server_cards);
1359   // Suppress disused address profiles when triggered from an empty field.
1360   if (field_contents.empty()) {
1361     const base::Time min_last_used =
1362         AutofillClock::Now() - kDisusedDataModelTimeDelta;
1363     RemoveExpiredCreditCardsNotUsedSinceTimestamp(AutofillClock::Now(),
1364                                                   min_last_used, &cards);
1365   }
1366 
1367   return GetSuggestionsForCards(type, field_contents, cards);
1368 }
1369 
IsAutofillEnabled() const1370 bool PersonalDataManager::IsAutofillEnabled() const {
1371   return IsAutofillProfileEnabled() || IsAutofillCreditCardEnabled();
1372 }
1373 
IsAutofillProfileEnabled() const1374 bool PersonalDataManager::IsAutofillProfileEnabled() const {
1375   return ::autofill::prefs::IsAutofillProfileEnabled(pref_service_);
1376 }
1377 
IsAutofillCreditCardEnabled() const1378 bool PersonalDataManager::IsAutofillCreditCardEnabled() const {
1379   return ::autofill::prefs::IsAutofillCreditCardEnabled(pref_service_);
1380 }
1381 
IsAutofillWalletImportEnabled() const1382 bool PersonalDataManager::IsAutofillWalletImportEnabled() const {
1383   return ::autofill::prefs::IsPaymentsIntegrationEnabled(pref_service_);
1384 }
1385 
ShouldSuggestServerCards() const1386 bool PersonalDataManager::ShouldSuggestServerCards() const {
1387   if (!IsAutofillWalletImportEnabled())
1388     return false;
1389 
1390   if (is_syncing_for_test_)
1391     return true;
1392 
1393   if (!sync_service_)
1394     return false;
1395 
1396   // Check if the user is in sync transport mode for wallet data.
1397   if (!sync_service_->IsSyncFeatureEnabled() &&
1398       base::FeatureList::IsEnabled(
1399           features::kAutofillEnableAccountWalletStorage)) {
1400     // For SyncTransport, only show server cards if the user has opted in to
1401     // seeing them in the dropdown.
1402     if (!prefs::IsUserOptedInWalletSyncTransport(
1403             pref_service_,
1404             sync_service_->GetAuthenticatedAccountInfo().account_id)) {
1405       return false;
1406     }
1407   }
1408 
1409   // Server cards should be suggested if the sync service is active.
1410   return sync_service_->GetActiveDataTypes().Has(syncer::AUTOFILL_WALLET_DATA);
1411 }
1412 
CountryCodeForCurrentTimezone() const1413 std::string PersonalDataManager::CountryCodeForCurrentTimezone() const {
1414   return base::CountryCodeForCurrentTimezone();
1415 }
1416 
SetPrefService(PrefService * pref_service)1417 void PersonalDataManager::SetPrefService(PrefService* pref_service) {
1418   wallet_enabled_pref_ = std::make_unique<BooleanPrefMember>();
1419   profile_enabled_pref_ = std::make_unique<BooleanPrefMember>();
1420   credit_card_enabled_pref_ = std::make_unique<BooleanPrefMember>();
1421   pref_service_ = pref_service;
1422   // |pref_service_| can be nullptr in tests. Using base::Unretained(this) is
1423   // safe because observer instances are destroyed once |this| is destroyed.
1424   if (pref_service_) {
1425     credit_card_enabled_pref_->Init(
1426         prefs::kAutofillCreditCardEnabled, pref_service_,
1427         base::BindRepeating(&PersonalDataManager::EnableAutofillPrefChanged,
1428                             base::Unretained(this)));
1429     profile_enabled_pref_->Init(
1430         prefs::kAutofillProfileEnabled, pref_service_,
1431         base::BindRepeating(&PersonalDataManager::EnableAutofillPrefChanged,
1432                             base::Unretained(this)));
1433     wallet_enabled_pref_->Init(
1434         prefs::kAutofillWalletImportEnabled, pref_service_,
1435         base::BindRepeating(
1436             &PersonalDataManager::EnableWalletIntegrationPrefChanged,
1437             base::Unretained(this)));
1438   }
1439 }
1440 
ClearProfileNonSettingsOrigins()1441 void PersonalDataManager::ClearProfileNonSettingsOrigins() {
1442   for (AutofillProfile* profile : GetProfiles()) {
1443     if (profile->origin() != kSettingsOrigin && !profile->origin().empty()) {
1444       profile->set_origin(std::string());
1445       UpdateProfileInDB(*profile, /*enforced=*/true);
1446     }
1447   }
1448 }
1449 
ClearCreditCardNonSettingsOrigins()1450 void PersonalDataManager::ClearCreditCardNonSettingsOrigins() {
1451   bool has_updated = false;
1452 
1453   for (CreditCard* card : GetLocalCreditCards()) {
1454     if (card->origin() != kSettingsOrigin && !card->origin().empty()) {
1455       card->set_origin(std::string());
1456       database_helper_->GetLocalDatabase()->UpdateCreditCard(*card);
1457       has_updated = true;
1458     }
1459   }
1460 
1461   // Refresh the local cache and send notifications to observers if a changed
1462   // was made.
1463   if (has_updated)
1464     Refresh();
1465 }
1466 
OnValidated(const AutofillProfile * profile)1467 void PersonalDataManager::OnValidated(const AutofillProfile* profile) {
1468   if (!profile)
1469     return;
1470 
1471   if (!ProfileChangesAreOngoing(profile->guid()))
1472     return;
1473 
1474   // Set the validity states updated, only when the validation has occurred. If
1475   // the rules were not loaded for any reason, don't set the flag.
1476   bool validity_updated =
1477       (profile->GetValidityState(ServerFieldType::ADDRESS_HOME_COUNTRY,
1478                                  AutofillProfile::CLIENT) !=
1479        AutofillProfile::UNVALIDATED);
1480 
1481   // For every relevant profile change on the ongoing_profile_changes_, mark the
1482   // change to show that the validation is done, and set the validity of the
1483   // profile if the validity was updated.
1484   for (const auto& change : ongoing_profile_changes_[profile->guid()]) {
1485     if (!profile->EqualsForClientValidationPurpose(*(change.profile())))
1486       continue;
1487 
1488     change.validation_effort_made();
1489 
1490     if (validity_updated) {
1491       change.profile()->set_is_client_validity_states_updated(true);
1492       change.profile()->SetClientValidityFromBitfieldValue(
1493           profile->GetClientValidityBitfieldValue());
1494     }
1495   }
1496 
1497   HandleNextProfileChange(profile->guid());
1498 }
1499 
GetProfileValidityByGUID(const std::string & guid)1500 const ProfileValidityMap& PersonalDataManager::GetProfileValidityByGUID(
1501     const std::string& guid) {
1502   static const ProfileValidityMap& empty_validity_map = ProfileValidityMap();
1503   if (!synced_profile_validity_) {
1504     profiles_server_validities_need_update_ = true;
1505     synced_profile_validity_ = std::make_unique<UserProfileValidityMap>();
1506     if (!synced_profile_validity_->ParseFromString(
1507             ::autofill::prefs::GetAllProfilesValidityMapsEncodedString(
1508                 pref_service_))) {
1509       return empty_validity_map;
1510     }
1511   }
1512 
1513   auto it = synced_profile_validity_->profile_validity().find(guid);
1514   if (it != synced_profile_validity_->profile_validity().end()) {
1515     return it->second;
1516   }
1517 
1518   return empty_validity_map;
1519 }
1520 
GetDefaultCountryCodeForNewAddress() const1521 const std::string& PersonalDataManager::GetDefaultCountryCodeForNewAddress()
1522     const {
1523   if (default_country_code_.empty())
1524     default_country_code_ = MostCommonCountryCodeFromProfiles();
1525 
1526   // Failing that, use the country code from variations service.
1527   if (default_country_code_.empty())
1528     default_country_code_ = variations_country_code_;
1529 
1530   // Failing that, guess based on system timezone.
1531   if (default_country_code_.empty())
1532     default_country_code_ = CountryCodeForCurrentTimezone();
1533 
1534   // Failing that, guess based on locale.
1535   if (default_country_code_.empty())
1536     default_country_code_ = AutofillCountry::CountryCodeForLocale(app_locale());
1537 
1538   return default_country_code_;
1539 }
1540 
1541 // static
DedupeCreditCardToSuggest(std::list<CreditCard * > * cards_to_suggest)1542 void PersonalDataManager::DedupeCreditCardToSuggest(
1543     std::list<CreditCard*>* cards_to_suggest) {
1544   for (auto outer_it = cards_to_suggest->begin();
1545        outer_it != cards_to_suggest->end(); ++outer_it) {
1546     // If considering a full server card, look for local cards that are
1547     // duplicates of it and remove them.
1548     if ((*outer_it)->record_type() == CreditCard::FULL_SERVER_CARD) {
1549       for (auto inner_it = cards_to_suggest->begin();
1550            inner_it != cards_to_suggest->end();) {
1551         auto inner_it_copy = inner_it++;
1552         if ((*inner_it_copy)->IsLocalDuplicateOfServerCard(**outer_it))
1553           cards_to_suggest->erase(inner_it_copy);
1554       }
1555       // If considering a local card, look for masked server cards that are
1556       // duplicates of it and remove them.
1557     } else if ((*outer_it)->record_type() == CreditCard::LOCAL_CARD) {
1558       for (auto inner_it = cards_to_suggest->begin();
1559            inner_it != cards_to_suggest->end();) {
1560         auto inner_it_copy = inner_it++;
1561         if ((*inner_it_copy)->record_type() == CreditCard::MASKED_SERVER_CARD &&
1562             (*outer_it)->IsLocalDuplicateOfServerCard(**inner_it_copy)) {
1563           cards_to_suggest->erase(inner_it_copy);
1564         }
1565       }
1566     }
1567   }
1568 }
1569 
SetProfiles(std::vector<AutofillProfile> * profiles)1570 void PersonalDataManager::SetProfiles(std::vector<AutofillProfile>* profiles) {
1571   if (is_off_the_record_) {
1572     // TODO(crbug.com/997629): Remove after investigation is over.
1573     DLOG(WARNING) << "Cannot SetProfiles because off-the-record";
1574     return;
1575   }
1576   if (!database_helper_->GetLocalDatabase()) {
1577     // TODO(crbug.com/997629): Remove after investigation is over.
1578     DLOG(WARNING) << "Cannot SetProfiles because no local DB";
1579     return;
1580   }
1581 
1582   ClearOnGoingProfileChanges();
1583 
1584   // Means that a profile was added, removed or updated.
1585   bool change_happened = false;
1586 
1587   // Any profiles that are not in the new profile list should be removed from
1588   // the web database
1589   for (const auto& it : web_profiles_) {
1590     if (!FindByGUID(*profiles, it->guid())) {
1591       RemoveProfileFromDB(it->guid());
1592       change_happened = true;
1593     }
1594   }
1595 
1596   // Update the web database with the new and existing profiles.
1597   for (const AutofillProfile& it : *profiles) {
1598     const auto* existing_profile = GetProfileByGUID(it.guid());
1599     // In SetProfiles, exceptionally, profiles are directly added/updated on the
1600     // web_profiles_ before they are ready to be added or get updated in the
1601     // database. Enforce the changes to make sure the database is also updated.
1602     if (existing_profile) {
1603       if (!existing_profile->EqualsForUpdatePurposes(it)) {
1604         UpdateProfileInDB(it, /*enforced=*/true);
1605         change_happened = true;
1606       }
1607     } else if (!FindByContents(web_profiles_, it)) {
1608       AddProfileToDB(it, /*enforced=*/true);
1609       change_happened = true;
1610     }
1611   }
1612 
1613   if (change_happened) {
1614     // Copy in the new profiles.
1615     web_profiles_.clear();
1616     for (const AutofillProfile& it : *profiles) {
1617       web_profiles_.push_back(std::make_unique<AutofillProfile>(it));
1618     }
1619   } else {
1620     // When a change happens (add, update, remove), we would consequently call
1621     // the NotifyPersonalDataChanged which notifies the tests to stop waiting.
1622     // Otherwise, we need to stop them by calling the function directly.
1623     NotifyPersonalDataObserver();
1624   }
1625 }
1626 
SetCreditCards(std::vector<CreditCard> * credit_cards)1627 void PersonalDataManager::SetCreditCards(
1628     std::vector<CreditCard>* credit_cards) {
1629   if (is_off_the_record_)
1630     return;
1631 
1632   // Remove empty credit cards from input.
1633   base::EraseIf(*credit_cards, [this](const CreditCard& credit_card) {
1634     return credit_card.IsEmpty(app_locale_);
1635   });
1636 
1637   if (!database_helper_->GetLocalDatabase())
1638     return;
1639 
1640   // Any credit cards that are not in the new credit card list should be
1641   // removed.
1642   for (const auto& card : local_credit_cards_) {
1643     if (!FindByGUID(*credit_cards, card->guid()))
1644       database_helper_->GetLocalDatabase()->RemoveCreditCard(card->guid());
1645   }
1646 
1647   // Update the web database with the existing credit cards.
1648   for (const CreditCard& card : *credit_cards) {
1649     if (FindByGUID(local_credit_cards_, card.guid()))
1650       database_helper_->GetLocalDatabase()->UpdateCreditCard(card);
1651   }
1652 
1653   // Add the new credit cards to the web database.  Don't add a duplicate.
1654   for (const CreditCard& card : *credit_cards) {
1655     if (!FindByGUID(local_credit_cards_, card.guid()) &&
1656         !FindByContents(local_credit_cards_, card))
1657       database_helper_->GetLocalDatabase()->AddCreditCard(card);
1658   }
1659 
1660   // Copy in the new credit cards.
1661   local_credit_cards_.clear();
1662   for (const CreditCard& card : *credit_cards)
1663     local_credit_cards_.push_back(std::make_unique<CreditCard>(card));
1664 
1665   // Refresh our local cache and send notifications to observers.
1666   Refresh();
1667 }
1668 
LoadProfiles()1669 void PersonalDataManager::LoadProfiles() {
1670   if (!database_helper_->GetLocalDatabase()) {
1671     NOTREACHED();
1672     return;
1673   }
1674 
1675   CancelPendingLocalQuery(&pending_profiles_query_);
1676   CancelPendingServerQuery(&pending_server_profiles_query_);
1677 
1678   pending_profiles_query_ =
1679       database_helper_->GetLocalDatabase()->GetAutofillProfiles(this);
1680   if (database_helper_->GetServerDatabase()) {
1681     pending_server_profiles_query_ =
1682         database_helper_->GetServerDatabase()->GetServerProfiles(this);
1683   }
1684 }
1685 
LoadCreditCards()1686 void PersonalDataManager::LoadCreditCards() {
1687   if (!database_helper_->GetLocalDatabase()) {
1688     NOTREACHED();
1689     return;
1690   }
1691 
1692   CancelPendingLocalQuery(&pending_creditcards_query_);
1693   CancelPendingServerQuery(&pending_server_creditcards_query_);
1694 
1695   pending_creditcards_query_ =
1696       database_helper_->GetLocalDatabase()->GetCreditCards(this);
1697   if (database_helper_->GetServerDatabase()) {
1698     pending_server_creditcards_query_ =
1699         database_helper_->GetServerDatabase()->GetServerCreditCards(this);
1700   }
1701 }
1702 
LoadCreditCardCloudTokenData()1703 void PersonalDataManager::LoadCreditCardCloudTokenData() {
1704   if (!database_helper_->GetServerDatabase())
1705     return;
1706 
1707   CancelPendingServerQuery(&pending_server_creditcard_cloud_token_data_query_);
1708 
1709   pending_server_creditcard_cloud_token_data_query_ =
1710       database_helper_->GetServerDatabase()->GetCreditCardCloudTokenData(this);
1711 }
1712 
LoadUpiIds()1713 void PersonalDataManager::LoadUpiIds() {
1714   if (!database_helper_->GetLocalDatabase())
1715     return;
1716 
1717   CancelPendingLocalQuery(&pending_upi_ids_query_);
1718 
1719   pending_upi_ids_query_ =
1720       database_helper_->GetLocalDatabase()->GetAllUpiIds(this);
1721 }
1722 
LoadCreditCardOffers()1723 void PersonalDataManager::LoadCreditCardOffers() {
1724   if (!database_helper_->GetServerDatabase())
1725     return;
1726 
1727   CancelPendingServerQuery(&pending_offer_data_query_);
1728 
1729   pending_offer_data_query_ =
1730       database_helper_->GetServerDatabase()->GetCreditCardOffers(this);
1731 }
1732 
CancelPendingLocalQuery(WebDataServiceBase::Handle * handle)1733 void PersonalDataManager::CancelPendingLocalQuery(
1734     WebDataServiceBase::Handle* handle) {
1735   if (*handle) {
1736     if (!database_helper_->GetLocalDatabase()) {
1737       NOTREACHED();
1738       return;
1739     }
1740     database_helper_->GetLocalDatabase()->CancelRequest(*handle);
1741   }
1742   *handle = 0;
1743 }
1744 
CancelPendingServerQuery(WebDataServiceBase::Handle * handle)1745 void PersonalDataManager::CancelPendingServerQuery(
1746     WebDataServiceBase::Handle* handle) {
1747   if (*handle) {
1748     if (!database_helper_->GetServerDatabase()) {
1749       NOTREACHED();
1750       return;
1751     }
1752     database_helper_->GetServerDatabase()->CancelRequest(*handle);
1753   }
1754   *handle = 0;
1755 }
1756 
CancelPendingServerQueries()1757 void PersonalDataManager::CancelPendingServerQueries() {
1758   CancelPendingServerQuery(&pending_server_profiles_query_);
1759   CancelPendingServerQuery(&pending_server_creditcards_query_);
1760   CancelPendingServerQuery(&pending_customer_data_query_);
1761   CancelPendingServerQuery(&pending_server_creditcard_cloud_token_data_query_);
1762   CancelPendingServerQuery(&pending_offer_data_query_);
1763 }
1764 
HasPendingQueriesForTesting()1765 bool PersonalDataManager::HasPendingQueriesForTesting() {
1766   return HasPendingQueries();
1767 }
1768 
LoadPaymentsCustomerData()1769 void PersonalDataManager::LoadPaymentsCustomerData() {
1770   if (!database_helper_->GetServerDatabase())
1771     return;
1772 
1773   CancelPendingServerQuery(&pending_customer_data_query_);
1774 
1775   pending_customer_data_query_ =
1776       database_helper_->GetServerDatabase()->GetPaymentsCustomerData(this);
1777 }
1778 
SaveImportedProfile(const AutofillProfile & imported_profile)1779 std::string PersonalDataManager::SaveImportedProfile(
1780     const AutofillProfile& imported_profile) {
1781   if (is_off_the_record_)
1782     return std::string();
1783 
1784   std::vector<AutofillProfile> profiles;
1785   std::string guid = AutofillProfileComparator::MergeProfile(
1786       imported_profile, web_profiles_, app_locale_, &profiles);
1787   SetProfiles(&profiles);
1788   return guid;
1789 }
1790 
OnAcceptedLocalCreditCardSave(const CreditCard & imported_card)1791 std::string PersonalDataManager::OnAcceptedLocalCreditCardSave(
1792     const CreditCard& imported_card) {
1793   DCHECK(!imported_card.number().empty());
1794   if (is_off_the_record_)
1795     return std::string();
1796 
1797   return SaveImportedCreditCard(imported_card);
1798 }
1799 
SaveImportedCreditCard(const CreditCard & imported_card)1800 std::string PersonalDataManager::SaveImportedCreditCard(
1801     const CreditCard& imported_card) {
1802   // Set to true if |imported_card| is merged into the credit card list.
1803   bool merged = false;
1804 
1805   std::string guid = imported_card.guid();
1806   std::vector<CreditCard> credit_cards;
1807   for (auto& card : local_credit_cards_) {
1808     // If |imported_card| has not yet been merged, check whether it should be
1809     // with the current |card|.
1810     if (!merged && card->UpdateFromImportedCard(imported_card, app_locale_)) {
1811       guid = card->guid();
1812       merged = true;
1813     }
1814 
1815     credit_cards.push_back(*card);
1816   }
1817 
1818   if (!merged)
1819     credit_cards.push_back(imported_card);
1820 
1821   SetCreditCards(&credit_cards);
1822 
1823   // After a card is saved locally, notifies the observers.
1824   OnCreditCardSaved(/*is_local_card=*/true);
1825 
1826   return guid;
1827 }
1828 
LogStoredProfileMetrics() const1829 void PersonalDataManager::LogStoredProfileMetrics() const {
1830   if (!has_logged_stored_profile_metrics_) {
1831     // Update the histogram of how many addresses the user has stored.
1832     AutofillMetrics::LogStoredProfileCount(web_profiles_.size());
1833 
1834     // If the user has stored addresses, log the distribution of days since
1835     // their last use and how many would be considered disused.
1836     if (!web_profiles_.empty()) {
1837       size_t num_disused_profiles = 0;
1838       const base::Time now = AutofillClock::Now();
1839       for (const std::unique_ptr<AutofillProfile>& profile : web_profiles_) {
1840         const base::TimeDelta time_since_last_use = now - profile->use_date();
1841         AutofillMetrics::LogStoredProfileDaysSinceLastUse(
1842             time_since_last_use.InDays());
1843         if (time_since_last_use > kDisusedDataModelTimeDelta)
1844           ++num_disused_profiles;
1845       }
1846       AutofillMetrics::LogStoredProfileDisusedCount(num_disused_profiles);
1847     }
1848 
1849     // Only log this info once per chrome user profile load.
1850     has_logged_stored_profile_metrics_ = true;
1851   }
1852 }
1853 
LogStoredCreditCardMetrics() const1854 void PersonalDataManager::LogStoredCreditCardMetrics() const {
1855   if (!has_logged_stored_credit_card_metrics_) {
1856     AutofillMetrics::LogStoredCreditCardMetrics(
1857         local_credit_cards_, server_credit_cards_, kDisusedDataModelTimeDelta);
1858 
1859     // Only log this info once per chrome user profile load.
1860     has_logged_stored_credit_card_metrics_ = true;
1861   }
1862 }
1863 
LogStoredOfferMetrics() const1864 void PersonalDataManager::LogStoredOfferMetrics() const {
1865   if (!has_logged_stored_offer_metrics_) {
1866     AutofillMetrics::LogStoredOfferMetrics(autofill_offer_data_);
1867     // Only log this info once per chrome user profile load.
1868     has_logged_stored_offer_metrics_ = true;
1869   }
1870 }
1871 
MostCommonCountryCodeFromProfiles() const1872 std::string PersonalDataManager::MostCommonCountryCodeFromProfiles() const {
1873   if (!IsAutofillEnabled())
1874     return std::string();
1875 
1876   // Count up country codes from existing profiles.
1877   std::map<std::string, int> votes;
1878   // TODO(estade): can we make this GetProfiles() instead? It seems to cause
1879   // errors in tests on mac trybots. See http://crbug.com/57221
1880   const std::vector<AutofillProfile*>& profiles = GetProfiles();
1881   const std::vector<std::string>& country_codes =
1882       CountryDataMap::GetInstance()->country_codes();
1883   for (size_t i = 0; i < profiles.size(); ++i) {
1884     std::string country_code = base::ToUpperASCII(
1885         base::UTF16ToASCII(profiles[i]->GetRawInfo(ADDRESS_HOME_COUNTRY)));
1886 
1887     if (base::Contains(country_codes, country_code)) {
1888       // Verified profiles count 100x more than unverified ones.
1889       votes[country_code] += profiles[i]->IsVerified() ? 100 : 1;
1890     }
1891   }
1892 
1893   // Take the most common country code.
1894   if (!votes.empty()) {
1895     auto iter = std::max_element(votes.begin(), votes.end(), CompareVotes);
1896     return iter->first;
1897   }
1898 
1899   return std::string();
1900 }
1901 
EnableWalletIntegrationPrefChanged()1902 void PersonalDataManager::EnableWalletIntegrationPrefChanged() {
1903   if (!prefs::IsPaymentsIntegrationEnabled(pref_service_)) {
1904     // Re-mask all server cards when the user turns off wallet card
1905     // integration.
1906     ResetFullServerCards();
1907     NotifyPersonalDataObserver();
1908   }
1909 }
1910 
EnableAutofillPrefChanged()1911 void PersonalDataManager::EnableAutofillPrefChanged() {
1912   default_country_code_.clear();
1913 
1914   // Refresh our local cache and send notifications to observers.
1915   Refresh();
1916 }
1917 
IsKnownCard(const CreditCard & credit_card) const1918 bool PersonalDataManager::IsKnownCard(const CreditCard& credit_card) const {
1919   const auto stripped_pan = CreditCard::StripSeparators(credit_card.number());
1920   for (const auto& card : local_credit_cards_) {
1921     if (stripped_pan == CreditCard::StripSeparators(card->number()))
1922       return true;
1923   }
1924 
1925   const auto masked_info = credit_card.NetworkAndLastFourDigits();
1926   for (const auto& card : server_credit_cards_) {
1927     switch (card->record_type()) {
1928       case CreditCard::FULL_SERVER_CARD:
1929         if (stripped_pan == CreditCard::StripSeparators(card->number()))
1930           return true;
1931         break;
1932       case CreditCard::MASKED_SERVER_CARD:
1933         if (masked_info == card->NetworkAndLastFourDigits())
1934           return true;
1935         break;
1936       default:
1937         NOTREACHED();
1938     }
1939   }
1940 
1941   return false;
1942 }
1943 
IsServerCard(const CreditCard * credit_card) const1944 bool PersonalDataManager::IsServerCard(const CreditCard* credit_card) const {
1945   // Check whether the current card itself is a server card.
1946   if (credit_card->record_type() != autofill::CreditCard::LOCAL_CARD)
1947     return true;
1948 
1949   std::vector<CreditCard*> server_credit_cards = GetServerCreditCards();
1950   // Check whether the current card is already uploaded.
1951   for (const CreditCard* server_card : server_credit_cards) {
1952     if (credit_card->HasSameNumberAs(*server_card))
1953       return true;
1954   }
1955   return false;
1956 }
1957 
ShouldShowCardsFromAccountOption() const1958 bool PersonalDataManager::ShouldShowCardsFromAccountOption() const {
1959 // The feature is only for Linux, Windows and Mac.
1960 #if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_WIN) || defined(OS_BSD) || \
1961     defined(OS_APPLE)
1962   // This option should only be shown for users that have not enabled the Sync
1963   // Feature and that have server credit cards available.
1964   if (!sync_service_ || sync_service_->IsSyncFeatureEnabled() ||
1965       GetServerCreditCards().empty()) {
1966     return false;
1967   }
1968 
1969   // If we have not returned yet, it should mean that the user is in Sync
1970   // Transport mode for Wallet data (Sync Feature disabled but has server
1971   // cards). This should only happen if that feature is enabled.
1972   DCHECK(base::FeatureList::IsEnabled(
1973       features::kAutofillEnableAccountWalletStorage));
1974 
1975   bool is_opted_in = prefs::IsUserOptedInWalletSyncTransport(
1976       pref_service_, sync_service_->GetAuthenticatedAccountInfo().account_id);
1977 
1978   AutofillMetrics::LogWalletSyncTransportCardsOptIn(is_opted_in);
1979 
1980   // The option should only be shown if the user has not already opted-in.
1981   return !is_opted_in;
1982 #else
1983   return false;
1984 #endif  // #if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_WIN) || defined(OS_BSD) || \
1985        //     defined(OS_APPLE)
1986 }
1987 
OnUserAcceptedCardsFromAccountOption()1988 void PersonalDataManager::OnUserAcceptedCardsFromAccountOption() {
1989   DCHECK_EQ(AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled,
1990             GetSyncSigninState());
1991   prefs::SetUserOptedInWalletSyncTransport(
1992       pref_service_, sync_service_->GetAuthenticatedAccountInfo().account_id,
1993       /*opted_in=*/true);
1994 }
1995 
OnAutofillProfileChanged(const AutofillProfileDeepChange & change)1996 void PersonalDataManager::OnAutofillProfileChanged(
1997     const AutofillProfileDeepChange& change) {
1998   const auto& guid = change.key();
1999   const auto& change_type = change.type();
2000   const auto& profile = *(change.profile());
2001   DCHECK(guid == profile.guid());
2002   // Happens only in tests.
2003   if (!ProfileChangesAreOngoing(guid)) {
2004     DVLOG(1) << "Received an unexpected response from database.";
2005     return;
2006   }
2007 
2008   const auto* existing_profile = GetProfileByGUID(guid);
2009   const bool profile_exists = (existing_profile != nullptr);
2010   switch (change_type) {
2011     case AutofillProfileChange::ADD:
2012       profiles_server_validities_need_update_ = true;
2013       if (!profile_exists && !FindByContents(web_profiles_, profile)) {
2014         web_profiles_.push_back(std::make_unique<AutofillProfile>(profile));
2015       }
2016       break;
2017     case AutofillProfileChange::UPDATE:
2018       profiles_server_validities_need_update_ = true;
2019       if (profile_exists &&
2020           (change.enforced() ||
2021            !existing_profile->EqualsForUpdatePurposes(profile))) {
2022         web_profiles_.erase(FindElementByGUID(web_profiles_, guid));
2023         web_profiles_.push_back(std::make_unique<AutofillProfile>(profile));
2024       }
2025       break;
2026     case AutofillProfileChange::REMOVE:
2027       if (profile_exists) {
2028         web_profiles_.erase(FindElementByGUID(web_profiles_, guid));
2029       }
2030       break;
2031     default:
2032       NOTREACHED();
2033   }
2034 
2035   OnProfileChangeDone(guid);
2036 }
2037 
LogServerCardLinkClicked() const2038 void PersonalDataManager::LogServerCardLinkClicked() const {
2039   AutofillMetrics::LogServerCardLinkClicked(GetSyncSigninState());
2040 }
2041 
OnUserAcceptedUpstreamOffer()2042 void PersonalDataManager::OnUserAcceptedUpstreamOffer() {
2043   // If the user is in sync transport mode for Wallet, record an opt-in.
2044   if (GetSyncSigninState() ==
2045       AutofillSyncSigninState::kSignedInAndWalletSyncTransportEnabled) {
2046     prefs::SetUserOptedInWalletSyncTransport(
2047         pref_service_, sync_service_->GetAuthenticatedAccountInfo().account_id,
2048         /*opted_in=*/true);
2049   }
2050 }
2051 
NotifyPersonalDataObserver()2052 void PersonalDataManager::NotifyPersonalDataObserver() {
2053   bool profile_changes_are_ongoing = ProfileChangesAreOngoing();
2054   for (PersonalDataManagerObserver& observer : observers_) {
2055     observer.OnPersonalDataChanged();
2056   }
2057   if (!profile_changes_are_ongoing) {
2058     // Call OnPersonalDataFinishedProfileTasks in a separate loop as
2059     // the observers might have removed themselves in OnPersonalDataChanged
2060     for (PersonalDataManagerObserver& observer : observers_) {
2061       observer.OnPersonalDataFinishedProfileTasks();
2062     }
2063   }
2064 }
2065 
OnCreditCardSaved(bool is_local_card)2066 void PersonalDataManager::OnCreditCardSaved(bool is_local_card) {
2067   if (!base::FeatureList::IsEnabled(
2068           features::kAutofillCreditCardUploadFeedback)) {
2069     return;
2070   }
2071   for (PersonalDataManagerObserver& observer : observers_)
2072     observer.OnCreditCardSaved(
2073         /*should_show_sign_in_promo_if_applicable=*/is_local_card);
2074 }
2075 
GetSuggestionsForCards(const AutofillType & type,const base::string16 & field_contents,const std::vector<CreditCard * > & cards_to_suggest) const2076 std::vector<Suggestion> PersonalDataManager::GetSuggestionsForCards(
2077     const AutofillType& type,
2078     const base::string16& field_contents,
2079     const std::vector<CreditCard*>& cards_to_suggest) const {
2080   std::vector<Suggestion> suggestions;
2081   base::string16 field_contents_lower = base::i18n::ToLower(field_contents);
2082 
2083   for (const CreditCard* credit_card : cards_to_suggest) {
2084     // The value of the stored data for this field type in the |credit_card|.
2085     base::string16 creditcard_field_value =
2086         credit_card->GetInfo(type, app_locale_);
2087     if (creditcard_field_value.empty())
2088       continue;
2089 
2090     bool prefix_matched_suggestion;
2091     if (suggestion_selection::IsValidSuggestionForFieldContents(
2092             base::i18n::ToLower(creditcard_field_value), field_contents_lower,
2093             type, credit_card->record_type() == CreditCard::MASKED_SERVER_CARD,
2094             &prefix_matched_suggestion)) {
2095       // Make a new suggestion.
2096       suggestions.push_back(Suggestion());
2097       Suggestion* suggestion = &suggestions.back();
2098 
2099       suggestion->value = credit_card->GetInfo(type, app_locale_);
2100       suggestion->icon = credit_card->CardIconStringForAutofillSuggestion();
2101       suggestion->backend_id = credit_card->guid();
2102       suggestion->match = prefix_matched_suggestion
2103                               ? Suggestion::PREFIX_MATCH
2104                               : Suggestion::SUBSTRING_MATCH;
2105 
2106       // Get the nickname for the card suggestion, which may not be the same as
2107       // the card's nickname if there are duplicates of the card on file.
2108       base::string16 suggestion_nickname =
2109           GetDisplayNicknameForCreditCard(*credit_card);
2110 
2111       // If the value is the card number, the label is the expiration date.
2112       // Otherwise the label is the card number, or if that is empty the
2113       // cardholder name. The label should never repeat the value.
2114       if (type.GetStorableType() == CREDIT_CARD_NUMBER) {
2115         suggestion->value = credit_card->CardIdentifierStringForAutofillDisplay(
2116             suggestion_nickname);
2117 
2118 #if defined(OS_ANDROID) || defined(OS_IOS)
2119         suggestion->label = credit_card->GetInfo(
2120             AutofillType(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR), app_locale_);
2121 #else
2122         suggestion->label = credit_card->DescriptiveExpiration(app_locale_);
2123 #endif  // defined(OS_ANDROID) || defined(OS_IOS)
2124 
2125       } else if (credit_card->number().empty()) {
2126         DCHECK_EQ(credit_card->record_type(), CreditCard::LOCAL_CARD);
2127         if (credit_card->HasNonEmptyValidNickname()) {
2128           suggestion->label = credit_card->nickname();
2129         } else if (type.GetStorableType() != CREDIT_CARD_NAME_FULL) {
2130           suggestion->label = credit_card->GetInfo(
2131               AutofillType(CREDIT_CARD_NAME_FULL), app_locale_);
2132         }
2133       } else {
2134 #if defined(OS_ANDROID)
2135         // On Android devices, the label is formatted as
2136         // "Nickname/Network  ••••1234" when the keyboard accessory experiment
2137         // is disabled and as "••••1234" when it's enabled.
2138         suggestion->label =
2139             base::FeatureList::IsEnabled(features::kAutofillKeyboardAccessory)
2140                 ? credit_card->ObfuscatedLastFourDigits()
2141                 : credit_card->CardIdentifierStringForAutofillDisplay(
2142                       suggestion_nickname);
2143 #elif defined(OS_IOS)
2144         // E.g. "••••1234"".
2145         suggestion->label = credit_card->ObfuscatedLastFourDigits();
2146 #else
2147         // E.g. "Nickname/Network  ••••1234, expires on 01/25".
2148         suggestion->label =
2149             credit_card->CardIdentifierStringAndDescriptiveExpiration(
2150                 app_locale_);
2151 #endif
2152       }
2153     }
2154   }
2155 
2156   // Prefix matches should precede other token matches.
2157   if (IsFeatureSubstringMatchEnabled()) {
2158     std::stable_sort(suggestions.begin(), suggestions.end(),
2159                      [](const Suggestion& a, const Suggestion& b) {
2160                        return a.match < b.match;
2161                      });
2162   }
2163 
2164   return suggestions;
2165 }
2166 
RemoveOrphanAutofillTableRows()2167 void PersonalDataManager::RemoveOrphanAutofillTableRows() {
2168   // Don't run if the fix has already been applied.
2169   if (pref_service_->GetBoolean(prefs::kAutofillOrphanRowsRemoved))
2170     return;
2171 
2172   if (!database_helper_->GetLocalDatabase())
2173     return;
2174 
2175   database_helper_->GetLocalDatabase()->RemoveOrphanAutofillTableRows();
2176 
2177   // Set the pref so that this fix is never run again.
2178   pref_service_->SetBoolean(prefs::kAutofillOrphanRowsRemoved, true);
2179 }
2180 
ApplyDedupingRoutine()2181 bool PersonalDataManager::ApplyDedupingRoutine() {
2182   if (!is_autofill_profile_cleanup_pending_)
2183     return false;
2184 
2185   is_autofill_profile_cleanup_pending_ = false;
2186 
2187   // No need to de-duplicate if there are less than two profiles.
2188   if (web_profiles_.size() < 2) {
2189     DVLOG(1) << "Autofill profile de-duplication not needed.";
2190     return false;
2191   }
2192 
2193   // Check if de-duplication has already been performed this major version.
2194   if (pref_service_->GetInteger(prefs::kAutofillLastVersionDeduped) >=
2195       CHROME_VERSION_MAJOR) {
2196     DVLOG(1)
2197         << "Autofill profile de-duplication already performed for this version";
2198     return false;
2199   }
2200 
2201   DVLOG(1) << "Starting autofill profile de-duplication.";
2202   std::unordered_set<std::string> profiles_to_delete;
2203   profiles_to_delete.reserve(web_profiles_.size());
2204 
2205   // Create the map used to update credit card's billing addresses after the
2206   // dedupe.
2207   std::unordered_map<std::string, std::string> guids_merge_map;
2208 
2209   // The changes can't happen directly on the web_profiles_, but need to be
2210   // updated in the database at first, and then updated on the web_profiles_.
2211   // Therefore, we need a copy of web_profiles_ to keep track of the changes.
2212   std::vector<std::unique_ptr<AutofillProfile>> new_profiles;
2213   for (const auto& it : web_profiles_) {
2214     new_profiles.push_back(std::make_unique<AutofillProfile>(*(it.get())));
2215   }
2216 
2217   DedupeProfiles(&new_profiles, &profiles_to_delete, &guids_merge_map);
2218 
2219   // Apply the profile changes to the database.
2220   for (const auto& profile : new_profiles) {
2221     // If the profile was set to be deleted, remove it from the database,
2222     // otherwise update it.
2223     if (profiles_to_delete.count(profile->guid())) {
2224       RemoveProfileFromDB(profile->guid());
2225     } else {
2226       UpdateProfileInDB(*(profile.get()));
2227     }
2228   }
2229 
2230   UpdateCardsBillingAddressReference(guids_merge_map);
2231 
2232   // Set the pref to the current major version.
2233   pref_service_->SetInteger(prefs::kAutofillLastVersionDeduped,
2234                             CHROME_VERSION_MAJOR);
2235   return true;
2236 }
2237 
DedupeProfiles(std::vector<std::unique_ptr<AutofillProfile>> * existing_profiles,std::unordered_set<std::string> * profiles_to_delete,std::unordered_map<std::string,std::string> * guids_merge_map) const2238 void PersonalDataManager::DedupeProfiles(
2239     std::vector<std::unique_ptr<AutofillProfile>>* existing_profiles,
2240     std::unordered_set<std::string>* profiles_to_delete,
2241     std::unordered_map<std::string, std::string>* guids_merge_map) const {
2242   AutofillMetrics::LogNumberOfProfilesConsideredForDedupe(
2243       existing_profiles->size());
2244 
2245   // Sort the profiles by frecency with all the verified profiles at the end.
2246   // That way the most relevant profiles will get merged into the less relevant
2247   // profiles, which keeps the syntax of the most relevant profiles data.
2248   // Verified profiles are put at the end because they do not merge into other
2249   // profiles, so the loop can be stopped when we reach those. However they need
2250   // to be in the vector because an unverified profile trying to merge into a
2251   // similar verified profile will be discarded.
2252   base::Time comparison_time = AutofillClock::Now();
2253   std::sort(existing_profiles->begin(), existing_profiles->end(),
2254             [comparison_time](const std::unique_ptr<AutofillProfile>& a,
2255                               const std::unique_ptr<AutofillProfile>& b) {
2256               if (a->IsVerified() != b->IsVerified())
2257                 return !a->IsVerified();
2258               return a->HasGreaterFrecencyThan(b.get(), comparison_time);
2259             });
2260 
2261   AutofillProfileComparator comparator(app_locale_);
2262 
2263   for (size_t i = 0; i < existing_profiles->size(); ++i) {
2264     AutofillProfile* profile_to_merge = (*existing_profiles)[i].get();
2265 
2266     // If the profile was set to be deleted, skip it. It has already been
2267     // merged into another profile.
2268     if (profiles_to_delete->count(profile_to_merge->guid()))
2269       continue;
2270 
2271     // If we have reached the verified profiles, stop trying to merge. Verified
2272     // profiles do not get merged.
2273     if (profile_to_merge->IsVerified())
2274       break;
2275 
2276     // If we have not reached the last profile, try to merge |profile_to_merge|
2277     // with all the less relevant |existing_profiles|.
2278     for (size_t j = i + 1; j < existing_profiles->size(); ++j) {
2279       AutofillProfile* existing_profile = (*existing_profiles)[j].get();
2280 
2281       // Don't try to merge a profile that was already set for deletion.
2282       if (profiles_to_delete->count(existing_profile->guid()))
2283         continue;
2284 
2285       // Move on if the profiles are not mergeable.
2286       if (!comparator.AreMergeable(*existing_profile, *profile_to_merge))
2287         continue;
2288 
2289       // The profiles are found to be mergeable. Attempt to update the existing
2290       // profile. This returns true if the merge was successful, or if the
2291       // merge would have been successful but the existing profile IsVerified()
2292       // and will not accept updates from profile_to_merge.
2293       if (existing_profile->SaveAdditionalInfo(*profile_to_merge,
2294                                                app_locale_)) {
2295         // Keep track that a credit card using |profile_to_merge|'s GUID as its
2296         // billing address id should replace it by |existing_profile|'s GUID.
2297         guids_merge_map->emplace(profile_to_merge->guid(),
2298                                  existing_profile->guid());
2299 
2300         // Since |profile_to_merge| was a duplicate of |existing_profile|
2301         // and was merged successfully, it can now be deleted.
2302         profiles_to_delete->insert(profile_to_merge->guid());
2303 
2304         // Now try to merge the new resulting profile with the rest of the
2305         // existing profiles.
2306         profile_to_merge = existing_profile;
2307 
2308         // Verified profiles do not get merged. Save some time by not
2309         // trying.
2310         if (profile_to_merge->IsVerified())
2311           break;
2312       }
2313     }
2314   }
2315   AutofillMetrics::LogNumberOfProfilesRemovedDuringDedupe(
2316       profiles_to_delete->size());
2317 }
2318 
UpdateCardsBillingAddressReference(const std::unordered_map<std::string,std::string> & guids_merge_map)2319 void PersonalDataManager::UpdateCardsBillingAddressReference(
2320     const std::unordered_map<std::string, std::string>& guids_merge_map) {
2321   /*  Here is an example of what the graph might look like.
2322 
2323       A -> B
2324              \
2325                -> E
2326              /
2327       C -> D
2328   */
2329 
2330   for (auto* credit_card : GetCreditCards()) {
2331     // If the credit card is not associated with a billing address, skip it.
2332     if (credit_card->billing_address_id().empty())
2333       break;
2334 
2335     // If the billing address profile associated with the card has been merged,
2336     // replace it by the id of the profile in which it was merged. Repeat the
2337     // process until the billing address has not been merged into another one.
2338     std::unordered_map<std::string, std::string>::size_type nb_guid_changes = 0;
2339     bool was_modified = false;
2340     auto it = guids_merge_map.find(credit_card->billing_address_id());
2341     while (it != guids_merge_map.end()) {
2342       was_modified = true;
2343       credit_card->set_billing_address_id(it->second);
2344       it = guids_merge_map.find(credit_card->billing_address_id());
2345 
2346       // Out of abundance of caution.
2347       if (nb_guid_changes > guids_merge_map.size()) {
2348         NOTREACHED();
2349         // Cancel the changes for that card.
2350         was_modified = false;
2351         break;
2352       }
2353     }
2354 
2355     // If the card was modified, apply the changes to the database.
2356     if (was_modified) {
2357       if (credit_card->record_type() == CreditCard::LOCAL_CARD)
2358         database_helper_->GetLocalDatabase()->UpdateCreditCard(*credit_card);
2359       else
2360         database_helper_->GetServerDatabase()->UpdateServerCardMetadata(
2361             *credit_card);
2362     }
2363   }
2364   Refresh();
2365 }
2366 
ConvertWalletAddressesAndUpdateWalletCards()2367 void PersonalDataManager::ConvertWalletAddressesAndUpdateWalletCards() {
2368   // If the full Sync feature isn't enabled, then do NOT convert any Wallet
2369   // addresses to local ones.
2370   if (!IsSyncFeatureEnabled()) {
2371     // PDM expects that each call to
2372     // ConvertWalletAddressesAndUpdateWalletCards() is followed by a
2373     // AutofillAddressConversionCompleted() notification, simulate the
2374     // notification here.
2375     AutofillAddressConversionCompleted();
2376     return;
2377   }
2378 
2379   database_helper_->GetServerDatabase()
2380       ->ConvertWalletAddressesAndUpdateWalletCards(
2381           app_locale_, GetAccountInfoForPaymentsServer().email);
2382 }
2383 
DeleteDisusedCreditCards()2384 bool PersonalDataManager::DeleteDisusedCreditCards() {
2385   // Only delete local cards, as server cards are managed by Payments.
2386   auto cards = GetLocalCreditCards();
2387 
2388   // Early exit when there is no local cards.
2389   if (cards.empty()) {
2390     return true;
2391   }
2392 
2393   std::vector<std::string> guid_to_delete;
2394   for (CreditCard* card : cards) {
2395     if (card->IsDeletable()) {
2396       guid_to_delete.push_back(card->guid());
2397     }
2398   }
2399 
2400   size_t num_deleted_cards = guid_to_delete.size();
2401 
2402   for (auto const& guid : guid_to_delete) {
2403     database_helper_->GetLocalDatabase()->RemoveCreditCard(guid);
2404   }
2405 
2406   if (num_deleted_cards > 0) {
2407     Refresh();
2408   }
2409 
2410   AutofillMetrics::LogNumberOfCreditCardsDeletedForDisuse(num_deleted_cards);
2411 
2412   return true;
2413 }
2414 
DeleteDisusedAddresses()2415 bool PersonalDataManager::DeleteDisusedAddresses() {
2416   const std::vector<AutofillProfile*>& profiles = GetProfiles();
2417 
2418   // Early exit when there are no profiles.
2419   if (profiles.empty()) {
2420     DVLOG(1) << "There are no profiles";
2421     return true;
2422   }
2423 
2424   std::unordered_set<std::string> used_billing_address_guids;
2425   for (CreditCard* card : GetCreditCards()) {
2426     if (!card->IsDeletable()) {
2427       used_billing_address_guids.insert(card->billing_address_id());
2428     }
2429   }
2430 
2431   std::vector<std::string> guids_to_delete;
2432   for (AutofillProfile* profile : profiles) {
2433     if (profile->IsDeletable() &&
2434         !used_billing_address_guids.count(profile->guid())) {
2435       guids_to_delete.push_back(profile->guid());
2436     }
2437   }
2438 
2439   size_t num_deleted_addresses = guids_to_delete.size();
2440 
2441   for (auto const& guid : guids_to_delete) {
2442     RemoveAutofillProfileByGUIDAndBlankCreditCardReference(guid);
2443   }
2444 
2445   if (num_deleted_addresses > 0) {
2446     Refresh();
2447   }
2448 
2449   AutofillMetrics::LogNumberOfAddressesDeletedForDisuse(num_deleted_addresses);
2450 
2451   return true;
2452 }
2453 
ApplyAddressFixesAndCleanups()2454 void PersonalDataManager::ApplyAddressFixesAndCleanups() {
2455   // Validate profiles once per major.
2456   UpdateClientValidityStates(GetProfiles());
2457 
2458   // One-time fix, otherwise NOP.
2459   RemoveOrphanAutofillTableRows();
2460 
2461   // Once per major version, otherwise NOP.
2462   ApplyDedupingRoutine();
2463 
2464   DeleteDisusedAddresses();
2465 
2466   // If feature AutofillCreateDataForTest is enabled, and once per user profile
2467   // startup.
2468   test_data_creator_.MaybeAddTestProfiles(base::BindRepeating(
2469       &PersonalDataManager::AddProfile, base::Unretained(this)));
2470 
2471   // Ran everytime it is called.
2472   ClearProfileNonSettingsOrigins();
2473 }
2474 
ApplyCardFixesAndCleanups()2475 void PersonalDataManager::ApplyCardFixesAndCleanups() {
2476   DeleteDisusedCreditCards();
2477 
2478   // If feature AutofillCreateDataForTest is enabled, and once per user profile
2479   // startup.
2480   test_data_creator_.MaybeAddTestCreditCards(base::BindRepeating(
2481       &PersonalDataManager::AddCreditCard, base::Unretained(this)));
2482 
2483   // Ran everytime it is called.
2484   ClearCreditCardNonSettingsOrigins();
2485 }
2486 
ResetProfileValidity()2487 void PersonalDataManager::ResetProfileValidity() {
2488   synced_profile_validity_.reset();
2489   profiles_server_validities_need_update_ = true;
2490 }
2491 
AddProfileToDB(const AutofillProfile & profile,bool enforced)2492 void PersonalDataManager::AddProfileToDB(const AutofillProfile& profile,
2493                                          bool enforced) {
2494   if (profile.IsEmpty(app_locale_)) {
2495     NotifyPersonalDataObserver();
2496     return;
2497   }
2498 
2499   if (!ProfileChangesAreOngoing(profile.guid())) {
2500     if (!enforced && (FindByGUID(web_profiles_, profile.guid()) ||
2501                       FindByContents(web_profiles_, profile))) {
2502       NotifyPersonalDataObserver();
2503       return;
2504     }
2505   }
2506   ongoing_profile_changes_[profile.guid()].push_back(
2507       AutofillProfileDeepChange(AutofillProfileChange::ADD, profile));
2508   if (enforced)
2509     ongoing_profile_changes_[profile.guid()].back().set_enforced();
2510   UpdateClientValidityStates(profile);
2511 }
2512 
UpdateProfileInDB(const AutofillProfile & profile,bool enforced)2513 void PersonalDataManager::UpdateProfileInDB(const AutofillProfile& profile,
2514                                             bool enforced) {
2515   // if the update is enforced, don't check if a similar profile already exists
2516   // or not. Otherwise, check if updating the profile makes sense.
2517   if (!enforced && !ProfileChangesAreOngoing(profile.guid())) {
2518     const auto* existing_profile = GetProfileByGUID(profile.guid());
2519     bool profile_exists = (existing_profile != nullptr);
2520     if (!profile_exists || existing_profile->EqualsForUpdatePurposes(profile)) {
2521       NotifyPersonalDataObserver();
2522       return;
2523     }
2524   }
2525 
2526   ongoing_profile_changes_[profile.guid()].push_back(
2527       AutofillProfileDeepChange(AutofillProfileChange::UPDATE, profile));
2528   if (enforced)
2529     ongoing_profile_changes_[profile.guid()].back().set_enforced();
2530   UpdateClientValidityStates(profile);
2531 }
2532 
RemoveProfileFromDB(const std::string & guid)2533 void PersonalDataManager::RemoveProfileFromDB(const std::string& guid) {
2534   auto profile_it = FindElementByGUID(web_profiles_, guid);
2535   bool profile_exists = profile_it != web_profiles_.end();
2536   if (!profile_exists && !ProfileChangesAreOngoing(guid)) {
2537     NotifyPersonalDataObserver();
2538     return;
2539   }
2540   const AutofillProfile* profile =
2541       profile_exists ? profile_it->get()
2542                      : ongoing_profile_changes_[guid].back().profile();
2543   AutofillProfileDeepChange change(AutofillProfileChange::REMOVE, *profile);
2544   if (!ProfileChangesAreOngoing(guid)) {
2545     database_helper_->GetLocalDatabase()->RemoveAutofillProfile(guid);
2546     change.set_is_ongoing_on_background();
2547   }
2548   ongoing_profile_changes_[guid].push_back(std::move(change));
2549 }
2550 
HandleNextProfileChange(const std::string & guid)2551 void PersonalDataManager::HandleNextProfileChange(const std::string& guid) {
2552   if (!ProfileChangesAreOngoing(guid))
2553     return;
2554 
2555   const auto& change = ongoing_profile_changes_[guid].front();
2556   if (change.is_ongoing_on_background())
2557     return;
2558 
2559   const auto& change_type = change.type();
2560   const auto* existing_profile = GetProfileByGUID(guid);
2561   const bool profile_exists = (existing_profile != nullptr);
2562   const auto& profile = *(ongoing_profile_changes_[guid].front().profile());
2563 
2564   DCHECK(guid == profile.guid());
2565 
2566   if (change_type == AutofillProfileChange::REMOVE) {
2567     if (!profile_exists) {
2568       OnProfileChangeDone(guid);
2569       return;
2570     }
2571     database_helper_->GetLocalDatabase()->RemoveAutofillProfile(guid);
2572     change.set_is_ongoing_on_background();
2573     return;
2574   }
2575 
2576   if (!change.has_validation_effort_made())
2577     return;
2578 
2579   if (change_type == AutofillProfileChange::ADD) {
2580     if (!change.enforced() &&
2581         (profile_exists || FindByContents(web_profiles_, profile))) {
2582       OnProfileChangeDone(guid);
2583       return;
2584     }
2585     database_helper_->GetLocalDatabase()->AddAutofillProfile(profile);
2586     change.set_is_ongoing_on_background();
2587     return;
2588   }
2589 
2590   if (profile_exists && (change.enforced() ||
2591                          !existing_profile->EqualsForUpdatePurposes(profile))) {
2592     database_helper_->GetLocalDatabase()->UpdateAutofillProfile(profile);
2593     change.set_is_ongoing_on_background();
2594   } else {
2595     OnProfileChangeDone(guid);
2596   }
2597 }
2598 
ProfileChangesAreOngoing(const std::string & guid)2599 bool PersonalDataManager::ProfileChangesAreOngoing(const std::string& guid) {
2600   return ongoing_profile_changes_.find(guid) !=
2601              ongoing_profile_changes_.end() &&
2602          !ongoing_profile_changes_[guid].empty();
2603 }
2604 
ProfileChangesAreOngoing()2605 bool PersonalDataManager::ProfileChangesAreOngoing() {
2606   for (const auto& task : ongoing_profile_changes_) {
2607     if (ProfileChangesAreOngoing(task.first)) {
2608       return true;
2609     }
2610   }
2611   return false;
2612 }
2613 
OnProfileChangeDone(const std::string & guid)2614 void PersonalDataManager::OnProfileChangeDone(const std::string& guid) {
2615   ongoing_profile_changes_[guid].pop_front();
2616 
2617   if (!ProfileChangesAreOngoing()) {
2618     Refresh();
2619   } else {
2620     NotifyPersonalDataObserver();
2621     HandleNextProfileChange(guid);
2622   }
2623 }
2624 
ClearOnGoingProfileChanges()2625 void PersonalDataManager::ClearOnGoingProfileChanges() {
2626   ongoing_profile_changes_.clear();
2627 }
2628 
HasPendingQueries()2629 bool PersonalDataManager::HasPendingQueries() {
2630   return pending_profiles_query_ != 0 || pending_creditcards_query_ != 0 ||
2631          pending_server_profiles_query_ != 0 ||
2632          pending_server_creditcards_query_ != 0 ||
2633          pending_server_creditcard_cloud_token_data_query_ != 0 ||
2634          pending_customer_data_query_ != 0 || pending_upi_ids_query_ != 0 ||
2635          pending_offer_data_query_ != 0;
2636 }
2637 
MigrateUserOptedInWalletSyncTransportIfNeeded()2638 void PersonalDataManager::MigrateUserOptedInWalletSyncTransportIfNeeded() {
2639   CoreAccountInfo primary_account =
2640       sync_service_->GetAuthenticatedAccountInfo();
2641   if (primary_account.IsEmpty())
2642     return;
2643 
2644   if (identity_manager_->GetAccountIdMigrationState() ==
2645       signin::IdentityManager::MIGRATION_NOT_STARTED) {
2646     return;
2647   }
2648 
2649   CoreAccountId primary_account_id = primary_account.account_id;
2650 
2651   // When migration is started or done, the primary account is created from a
2652   // Gaia ID.
2653   if (primary_account_id.IsEmail()) {
2654     DLOG(ERROR) << "Unexpected primary account id from an email ["
2655                 << primary_account_id << "].";
2656     base::UmaHistogramEnumeration(
2657         "Autofill.MigrateUserOptedInToWalletSync",
2658         MigrateUserOptedInWalletSyncType::
2659             kNotMigratedUnexpectedPrimaryAccountIdWithEmail);
2660     return;
2661   }
2662 
2663   CoreAccountId legacy_account_id_from_email =
2664       CoreAccountId::FromEmail(gaia::CanonicalizeEmail(primary_account.email));
2665 
2666   MigrateUserOptedInWalletSyncType migrate =
2667       prefs::IsUserOptedInWalletSyncTransport(pref_service_,
2668                                               legacy_account_id_from_email)
2669           ? MigrateUserOptedInWalletSyncType::kMigratedFromCanonicalEmail
2670           : MigrateUserOptedInWalletSyncType::kNotMigrated;
2671 
2672   if (migrate == MigrateUserOptedInWalletSyncType::kNotMigrated &&
2673       prefs::IsUserOptedInWalletSyncTransport(
2674           pref_service_, CoreAccountId::FromEmail(primary_account.email))) {
2675     // Only canonicalized emails should be used to create CoreAccountId objects
2676     // by the IdentityManager. Be overly caution and also check whether
2677     // the non-canonical email was used when the user opted in to wallet sync.
2678     legacy_account_id_from_email =
2679         CoreAccountId::FromEmail(primary_account.email);
2680     migrate = MigrateUserOptedInWalletSyncType::kMigratedFromNonCanonicalEmail;
2681   }
2682 
2683   base::UmaHistogramEnumeration("Autofill.MigrateUserOptedInToWalletSync",
2684                                 migrate);
2685 
2686   if (migrate == MigrateUserOptedInWalletSyncType::kNotMigrated)
2687     return;
2688 
2689   DCHECK(prefs::IsUserOptedInWalletSyncTransport(pref_service_,
2690                                                  legacy_account_id_from_email));
2691   prefs::SetUserOptedInWalletSyncTransport(pref_service_,
2692                                            legacy_account_id_from_email,
2693                                            /*opted_in=*/false);
2694   prefs::SetUserOptedInWalletSyncTransport(pref_service_, primary_account_id,
2695                                            /*opted_in=*/true);
2696 }
2697 
GetDisplayNicknameForCreditCard(const CreditCard & card) const2698 base::string16 PersonalDataManager::GetDisplayNicknameForCreditCard(
2699     const CreditCard& card) const {
2700   if (!base::FeatureList::IsEnabled(
2701           features::kAutofillEnableCardNicknameManagement)) {
2702     return base::string16();
2703   }
2704 
2705   // Always prefer a local nickname if available.
2706   if (card.HasNonEmptyValidNickname() &&
2707       card.record_type() == CreditCard::LOCAL_CARD)
2708     return card.nickname();
2709   // Either the card a) has no nickname or b) is a server card and we would
2710   // prefer to use the nickname of a local card.
2711   std::vector<CreditCard*> candidates = GetCreditCards();
2712   for (CreditCard* candidate : candidates) {
2713     if (candidate->guid() != card.guid() && candidate->HasSameNumberAs(card) &&
2714         candidate->HasNonEmptyValidNickname()) {
2715       return candidate->nickname();
2716     }
2717   }
2718   // Fall back to nickname of |card|, which may be empty.
2719   return card.nickname();
2720 }
2721 
2722 }  // namespace autofill
2723