1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/search_engines/template_url_service.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/guid.h"
14 #include "base/i18n/case_conversion.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/metrics/histogram_macros.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/profiler/scoped_tracker.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/time/default_clock.h"
24 #include "base/time/time.h"
25 #include "components/pref_registry/pref_registry_syncable.h"
26 #include "components/rappor/rappor_service.h"
27 #include "components/search_engines/search_engines_pref_names.h"
28 #include "components/search_engines/search_host_to_urls_map.h"
29 #include "components/search_engines/search_terms_data.h"
30 #include "components/search_engines/template_url.h"
31 #include "components/search_engines/template_url_prepopulate_data.h"
32 #include "components/search_engines/template_url_service_client.h"
33 #include "components/search_engines/template_url_service_observer.h"
34 #include "components/search_engines/util.h"
35 #include "components/url_fixer/url_fixer.h"
36 #include "net/base/net_util.h"
37 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
38 #include "sync/api/sync_change.h"
39 #include "sync/api/sync_error_factory.h"
40 #include "sync/protocol/search_engine_specifics.pb.h"
41 #include "sync/protocol/sync.pb.h"
44 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet
;
45 typedef TemplateURLService::SyncDataMap SyncDataMap
;
49 bool IdenticalSyncGUIDs(const TemplateURLData
* data
, const TemplateURL
* turl
) {
51 return !data
&& !turl
;
53 return data
->sync_guid
== turl
->sync_guid();
56 const char kDeleteSyncedEngineHistogramName
[] =
57 "Search.DeleteSyncedSearchEngine";
59 // Values for an enumerated histogram used to track whenever an ACTION_DELETE is
60 // sent to the server for search engines.
61 enum DeleteSyncedSearchEngineEvent
{
62 DELETE_ENGINE_USER_ACTION
,
63 DELETE_ENGINE_PRE_SYNC
,
64 DELETE_ENGINE_EMPTY_FIELD
,
68 // Returns true iff the change in |change_list| at index |i| should not be sent
69 // up to the server based on its GUIDs presence in |sync_data| or when compared
70 // to changes after it in |change_list|.
72 // 1) It is an ACTION_UPDATE or ACTION_DELETE and the sync_guid associated
73 // with it is NOT found in |sync_data|. We can only update and remove
74 // entries that were originally from the Sync server.
75 // 2) It is an ACTION_ADD and the sync_guid associated with it is found in
76 // |sync_data|. We cannot re-add entries that Sync already knew about.
77 // 3) There is an update after an update for the same GUID. We prune earlier
78 // ones just to save bandwidth (Sync would normally coalesce them).
79 bool ShouldRemoveSyncChange(size_t index
,
80 syncer::SyncChangeList
* change_list
,
81 const SyncDataMap
* sync_data
) {
82 DCHECK(index
< change_list
->size());
83 const syncer::SyncChange
& change_i
= (*change_list
)[index
];
84 const std::string guid
= change_i
.sync_data().GetSpecifics()
85 .search_engine().sync_guid();
86 syncer::SyncChange::SyncChangeType type
= change_i
.change_type();
87 if ((type
== syncer::SyncChange::ACTION_UPDATE
||
88 type
== syncer::SyncChange::ACTION_DELETE
) &&
89 sync_data
->find(guid
) == sync_data
->end())
91 if (type
== syncer::SyncChange::ACTION_ADD
&&
92 sync_data
->find(guid
) != sync_data
->end())
94 if (type
== syncer::SyncChange::ACTION_UPDATE
) {
95 for (size_t j
= index
+ 1; j
< change_list
->size(); j
++) {
96 const syncer::SyncChange
& change_j
= (*change_list
)[j
];
97 if ((syncer::SyncChange::ACTION_UPDATE
== change_j
.change_type()) &&
98 (change_j
.sync_data().GetSpecifics().search_engine().sync_guid() ==
106 // Remove SyncChanges that should not be sent to the server from |change_list|.
107 // This is done to eliminate incorrect SyncChanges added by the merge and
108 // conflict resolution logic when it is unsure of whether or not an entry is new
109 // from Sync or originally from the local model. This also removes changes that
110 // would be otherwise be coalesced by Sync in order to save bandwidth.
111 void PruneSyncChanges(const SyncDataMap
* sync_data
,
112 syncer::SyncChangeList
* change_list
) {
113 for (size_t i
= 0; i
< change_list
->size(); ) {
114 if (ShouldRemoveSyncChange(i
, change_list
, sync_data
))
115 change_list
->erase(change_list
->begin() + i
);
121 // Returns true if |turl|'s GUID is not found inside |sync_data|. This is to be
122 // used in MergeDataAndStartSyncing to differentiate between TemplateURLs from
123 // Sync and TemplateURLs that were initially local, assuming |sync_data| is the
124 // |initial_sync_data| parameter.
125 bool IsFromSync(const TemplateURL
* turl
, const SyncDataMap
& sync_data
) {
126 return !!sync_data
.count(turl
->sync_guid());
129 // Log the number of instances of a keyword that exist, with zero or more
130 // underscores, which could occur as the result of conflict resolution.
131 void LogDuplicatesHistogram(
132 const TemplateURLService::TemplateURLVector
& template_urls
) {
133 std::map
<std::string
, int> duplicates
;
134 for (TemplateURLService::TemplateURLVector::const_iterator it
=
135 template_urls
.begin(); it
!= template_urls
.end(); ++it
) {
136 std::string keyword
= base::UTF16ToASCII((*it
)->keyword());
137 base::TrimString(keyword
, "_", &keyword
);
138 duplicates
[keyword
]++;
141 // Count the keywords with duplicates.
143 for (std::map
<std::string
, int>::const_iterator it
= duplicates
.begin();
144 it
!= duplicates
.end(); ++it
) {
149 UMA_HISTOGRAM_COUNTS_100("Search.SearchEngineDuplicateCounts", num_dupes
);
155 // TemplateURLService::LessWithPrefix -----------------------------------------
157 class TemplateURLService::LessWithPrefix
{
159 // We want to find the set of keywords that begin with a prefix. The STL
160 // algorithms will return the set of elements that are "equal to" the
161 // prefix, where "equal(x, y)" means "!(cmp(x, y) || cmp(y, x))". When
162 // cmp() is the typical std::less<>, this results in lexicographic equality;
163 // we need to extend this to mark a prefix as "not less than" a keyword it
164 // begins, which will cause the desired elements to be considered "equal to"
165 // the prefix. Note: this is still a strict weak ordering, as required by
166 // equal_range() (though I will not prove that here).
168 // Unfortunately the calling convention is not "prefix and element" but
169 // rather "two elements", so we pass the prefix as a fake "element" which has
170 // a NULL KeywordDataElement pointer.
171 bool operator()(const KeywordToTemplateMap::value_type
& elem1
,
172 const KeywordToTemplateMap::value_type
& elem2
) const {
173 return (elem1
.second
== NULL
) ?
174 (elem2
.first
.compare(0, elem1
.first
.length(), elem1
.first
) > 0) :
175 (elem1
.first
< elem2
.first
);
180 // TemplateURLService ---------------------------------------------------------
182 TemplateURLService::TemplateURLService(
184 scoped_ptr
<SearchTermsData
> search_terms_data
,
185 const scoped_refptr
<KeywordWebDataService
>& web_data_service
,
186 scoped_ptr
<TemplateURLServiceClient
> client
,
187 GoogleURLTracker
* google_url_tracker
,
188 rappor::RapporService
* rappor_service
,
189 const base::Closure
& dsp_change_callback
)
191 search_terms_data_(search_terms_data
.Pass()),
192 web_data_service_(web_data_service
),
193 client_(client
.Pass()),
194 google_url_tracker_(google_url_tracker
),
195 rappor_service_(rappor_service
),
196 dsp_change_callback_(dsp_change_callback
),
197 provider_map_(new SearchHostToURLsMap
),
201 default_search_provider_(NULL
),
202 next_id_(kInvalidTemplateURLID
+ 1),
203 clock_(new base::DefaultClock
),
204 models_associated_(false),
205 processing_syncer_changes_(false),
206 dsp_change_origin_(DSP_CHANGE_OTHER
),
207 default_search_manager_(
209 base::Bind(&TemplateURLService::OnDefaultSearchChange
,
210 base::Unretained(this))) {
211 DCHECK(search_terms_data_
);
215 TemplateURLService::TemplateURLService(const Initializer
* initializers
,
218 search_terms_data_(new SearchTermsData
),
219 web_data_service_(NULL
),
220 google_url_tracker_(NULL
),
221 rappor_service_(NULL
),
222 provider_map_(new SearchHostToURLsMap
),
226 default_search_provider_(NULL
),
227 next_id_(kInvalidTemplateURLID
+ 1),
228 clock_(new base::DefaultClock
),
229 models_associated_(false),
230 processing_syncer_changes_(false),
231 dsp_change_origin_(DSP_CHANGE_OTHER
),
232 default_search_manager_(
234 base::Bind(&TemplateURLService::OnDefaultSearchChange
,
235 base::Unretained(this))) {
236 Init(initializers
, count
);
239 TemplateURLService::~TemplateURLService() {
240 // |web_data_service_| should be deleted during Shutdown().
241 DCHECK(!web_data_service_
.get());
242 STLDeleteElements(&template_urls_
);
246 void TemplateURLService::RegisterProfilePrefs(
247 user_prefs::PrefRegistrySyncable
* registry
) {
248 registry
->RegisterStringPref(prefs::kSyncedDefaultSearchProviderGUID
,
250 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
251 registry
->RegisterBooleanPref(prefs::kDefaultSearchProviderEnabled
, true);
252 registry
->RegisterStringPref(prefs::kDefaultSearchProviderName
,
254 registry
->RegisterStringPref(prefs::kDefaultSearchProviderID
, std::string());
255 registry
->RegisterStringPref(prefs::kDefaultSearchProviderPrepopulateID
,
257 registry
->RegisterStringPref(prefs::kDefaultSearchProviderSuggestURL
,
259 registry
->RegisterStringPref(prefs::kDefaultSearchProviderSearchURL
,
261 registry
->RegisterStringPref(prefs::kDefaultSearchProviderInstantURL
,
263 registry
->RegisterStringPref(prefs::kDefaultSearchProviderImageURL
,
265 registry
->RegisterStringPref(prefs::kDefaultSearchProviderNewTabURL
,
267 registry
->RegisterStringPref(prefs::kDefaultSearchProviderSearchURLPostParams
,
269 registry
->RegisterStringPref(
270 prefs::kDefaultSearchProviderSuggestURLPostParams
, std::string());
271 registry
->RegisterStringPref(
272 prefs::kDefaultSearchProviderInstantURLPostParams
, std::string());
273 registry
->RegisterStringPref(prefs::kDefaultSearchProviderImageURLPostParams
,
275 registry
->RegisterStringPref(prefs::kDefaultSearchProviderKeyword
,
277 registry
->RegisterStringPref(prefs::kDefaultSearchProviderIconURL
,
279 registry
->RegisterStringPref(prefs::kDefaultSearchProviderEncodings
,
281 registry
->RegisterListPref(prefs::kDefaultSearchProviderAlternateURLs
);
282 registry
->RegisterStringPref(
283 prefs::kDefaultSearchProviderSearchTermsReplacementKey
, std::string());
287 base::string16
TemplateURLService::CleanUserInputKeyword(
288 const base::string16
& keyword
) {
289 // Remove the scheme.
290 base::string16
result(base::i18n::ToLower(keyword
));
291 base::TrimWhitespace(result
, base::TRIM_ALL
, &result
);
292 url::Component scheme_component
;
293 if (url::ExtractScheme(base::UTF16ToUTF8(keyword
).c_str(),
294 static_cast<int>(keyword
.length()),
295 &scheme_component
)) {
296 // If the scheme isn't "http" or "https", bail. The user isn't trying to
297 // type a web address, but rather an FTP, file:, or other scheme URL, or a
298 // search query with some sort of initial operator (e.g. "site:").
299 if (result
.compare(0, scheme_component
.end(),
300 base::ASCIIToUTF16(url::kHttpScheme
)) &&
301 result
.compare(0, scheme_component
.end(),
302 base::ASCIIToUTF16(url::kHttpsScheme
)))
303 return base::string16();
305 // Include trailing ':'.
306 result
.erase(0, scheme_component
.end() + 1);
307 // Many schemes usually have "//" after them, so strip it too.
308 const base::string16
after_scheme(base::ASCIIToUTF16("//"));
309 if (result
.compare(0, after_scheme
.length(), after_scheme
) == 0)
310 result
.erase(0, after_scheme
.length());
313 // Remove leading "www.".
314 result
= net::StripWWW(result
);
316 // Remove trailing "/".
317 return (result
.length() > 0 && result
[result
.length() - 1] == '/') ?
318 result
.substr(0, result
.length() - 1) : result
;
321 bool TemplateURLService::CanAddAutogeneratedKeyword(
322 const base::string16
& keyword
,
324 TemplateURL
** template_url_to_replace
) {
325 DCHECK(!keyword
.empty()); // This should only be called for non-empty
326 // keywords. If we need to support empty kewords
327 // the code needs to change slightly.
328 TemplateURL
* existing_url
= GetTemplateURLForKeyword(keyword
);
329 if (template_url_to_replace
)
330 *template_url_to_replace
= existing_url
;
332 // We already have a TemplateURL for this keyword. Only allow it to be
333 // replaced if the TemplateURL can be replaced.
334 return CanReplace(existing_url
);
337 // We don't have a TemplateURL with keyword. We still may not allow this
338 // keyword if there's evidence we may have created this keyword before and
339 // the user renamed it (because, for instance, the keyword is a common word
340 // that may interfere with search queries). An easy heuristic for this is
341 // whether the user has a TemplateURL that has been manually modified (e.g.,
342 // renamed) connected to the same host.
343 return !url
.is_valid() || url
.host().empty() ||
344 CanAddAutogeneratedKeywordForHost(url
.host());
347 void TemplateURLService::FindMatchingKeywords(
348 const base::string16
& prefix
,
349 bool support_replacement_only
,
350 TemplateURLVector
* matches
) {
351 // Sanity check args.
354 DCHECK(matches
!= NULL
);
355 DCHECK(matches
->empty()); // The code for exact matches assumes this.
357 // Required for VS2010: http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
358 TemplateURL
* const kNullTemplateURL
= NULL
;
360 // Find matching keyword range. Searches the element map for keywords
361 // beginning with |prefix| and stores the endpoints of the resulting set in
363 const std::pair
<KeywordToTemplateMap::const_iterator
,
364 KeywordToTemplateMap::const_iterator
> match_range(
366 keyword_to_template_map_
.begin(), keyword_to_template_map_
.end(),
367 KeywordToTemplateMap::value_type(prefix
, kNullTemplateURL
),
370 // Return vector of matching keywords.
371 for (KeywordToTemplateMap::const_iterator
i(match_range
.first
);
372 i
!= match_range
.second
; ++i
) {
373 if (!support_replacement_only
||
374 i
->second
->url_ref().SupportsReplacement(search_terms_data()))
375 matches
->push_back(i
->second
);
379 TemplateURL
* TemplateURLService::GetTemplateURLForKeyword(
380 const base::string16
& keyword
) {
381 KeywordToTemplateMap::const_iterator
elem(
382 keyword_to_template_map_
.find(keyword
));
383 if (elem
!= keyword_to_template_map_
.end())
386 initial_default_search_provider_
.get() &&
387 (initial_default_search_provider_
->keyword() == keyword
)) ?
388 initial_default_search_provider_
.get() : NULL
;
391 TemplateURL
* TemplateURLService::GetTemplateURLForGUID(
392 const std::string
& sync_guid
) {
393 GUIDToTemplateMap::const_iterator
elem(guid_to_template_map_
.find(sync_guid
));
394 if (elem
!= guid_to_template_map_
.end())
397 initial_default_search_provider_
.get() &&
398 (initial_default_search_provider_
->sync_guid() == sync_guid
)) ?
399 initial_default_search_provider_
.get() : NULL
;
402 TemplateURL
* TemplateURLService::GetTemplateURLForHost(
403 const std::string
& host
) {
405 return provider_map_
->GetTemplateURLForHost(host
);
406 TemplateURL
* initial_dsp
= initial_default_search_provider_
.get();
409 return (initial_dsp
->GenerateSearchURL(search_terms_data()).host() == host
) ?
413 bool TemplateURLService::Add(TemplateURL
* template_url
) {
414 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
415 if (!AddNoNotify(template_url
, true))
421 void TemplateURLService::AddWithOverrides(TemplateURL
* template_url
,
422 const base::string16
& short_name
,
423 const base::string16
& keyword
,
424 const std::string
& url
) {
425 DCHECK(!short_name
.empty());
426 DCHECK(!keyword
.empty());
427 DCHECK(!url
.empty());
428 template_url
->data_
.SetShortName(short_name
);
429 template_url
->data_
.SetKeyword(keyword
);
430 template_url
->SetURL(url
);
434 void TemplateURLService::AddExtensionControlledTURL(
435 TemplateURL
* template_url
,
436 scoped_ptr
<TemplateURL::AssociatedExtensionInfo
> info
) {
438 DCHECK(template_url
);
439 DCHECK_EQ(kInvalidTemplateURLID
, template_url
->id());
441 DCHECK_NE(TemplateURL::NORMAL
, info
->type
);
442 DCHECK_EQ(info
->wants_to_be_default_engine
,
443 template_url
->show_in_default_list());
444 DCHECK(!FindTemplateURLForExtension(info
->extension_id
, info
->type
));
445 template_url
->extension_info_
.swap(info
);
447 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
448 if (AddNoNotify(template_url
, true)) {
449 if (template_url
->extension_info_
->wants_to_be_default_engine
)
450 UpdateExtensionDefaultSearchEngine();
455 void TemplateURLService::Remove(TemplateURL
* template_url
) {
456 RemoveNoNotify(template_url
);
460 void TemplateURLService::RemoveExtensionControlledTURL(
461 const std::string
& extension_id
,
462 TemplateURL::Type type
) {
464 TemplateURL
* url
= FindTemplateURLForExtension(extension_id
, type
);
467 // NULL this out so that we can call RemoveNoNotify.
468 // UpdateExtensionDefaultSearchEngine will cause it to be reset.
469 if (default_search_provider_
== url
)
470 default_search_provider_
= NULL
;
471 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
473 UpdateExtensionDefaultSearchEngine();
477 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after
) {
478 RemoveAutoGeneratedBetween(created_after
, base::Time());
481 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after
,
482 base::Time created_before
) {
483 RemoveAutoGeneratedForOriginBetween(GURL(), created_after
, created_before
);
486 void TemplateURLService::RemoveAutoGeneratedForOriginBetween(
488 base::Time created_after
,
489 base::Time created_before
) {
490 GURL
o(origin
.GetOrigin());
491 bool should_notify
= false;
492 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
493 for (size_t i
= 0; i
< template_urls_
.size();) {
494 if (template_urls_
[i
]->date_created() >= created_after
&&
495 (created_before
.is_null() ||
496 template_urls_
[i
]->date_created() < created_before
) &&
497 CanReplace(template_urls_
[i
]) &&
499 template_urls_
[i
]->GenerateSearchURL(
500 search_terms_data()).GetOrigin() == o
)) {
501 RemoveNoNotify(template_urls_
[i
]);
502 should_notify
= true;
511 void TemplateURLService::RegisterOmniboxKeyword(
512 const std::string
& extension_id
,
513 const std::string
& extension_name
,
514 const std::string
& keyword
,
515 const std::string
& template_url_string
) {
518 if (FindTemplateURLForExtension(extension_id
,
519 TemplateURL::OMNIBOX_API_EXTENSION
))
522 TemplateURLData data
;
523 data
.SetShortName(base::UTF8ToUTF16(extension_name
));
524 data
.SetKeyword(base::UTF8ToUTF16(keyword
));
525 data
.SetURL(template_url_string
);
526 TemplateURL
* url
= new TemplateURL(data
);
527 scoped_ptr
<TemplateURL::AssociatedExtensionInfo
> info(
528 new TemplateURL::AssociatedExtensionInfo(
529 TemplateURL::OMNIBOX_API_EXTENSION
, extension_id
));
530 AddExtensionControlledTURL(url
, info
.Pass());
533 TemplateURLService::TemplateURLVector
TemplateURLService::GetTemplateURLs() {
534 return template_urls_
;
537 void TemplateURLService::IncrementUsageCount(TemplateURL
* url
) {
539 // Extension-controlled search engines are not persisted.
540 if (url
->GetType() != TemplateURL::NORMAL
)
542 if (std::find(template_urls_
.begin(), template_urls_
.end(), url
) ==
543 template_urls_
.end())
545 ++url
->data_
.usage_count
;
547 if (web_data_service_
.get())
548 web_data_service_
->UpdateKeyword(url
->data());
551 void TemplateURLService::ResetTemplateURL(TemplateURL
* url
,
552 const base::string16
& title
,
553 const base::string16
& keyword
,
554 const std::string
& search_url
) {
555 if (ResetTemplateURLNoNotify(url
, title
, keyword
, search_url
))
559 bool TemplateURLService::CanMakeDefault(const TemplateURL
* url
) {
561 ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
562 (default_search_provider_source_
==
563 DefaultSearchManager::FROM_FALLBACK
)) &&
564 (url
!= GetDefaultSearchProvider()) &&
565 url
->url_ref().SupportsReplacement(search_terms_data()) &&
566 (url
->GetType() == TemplateURL::NORMAL
);
569 void TemplateURLService::SetUserSelectedDefaultSearchProvider(
571 // Omnibox keywords cannot be made default. Extension-controlled search
572 // engines can be made default only by the extension itself because they
574 DCHECK(!url
|| (url
->GetType() == TemplateURL::NORMAL
));
576 // Skip the DefaultSearchManager, which will persist to user preferences.
577 if ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
578 (default_search_provider_source_
==
579 DefaultSearchManager::FROM_FALLBACK
)) {
580 ApplyDefaultSearchChange(url
? &url
->data() : NULL
,
581 DefaultSearchManager::FROM_USER
);
584 // We rely on the DefaultSearchManager to call OnDefaultSearchChange if, in
585 // fact, the effective DSE changes.
587 default_search_manager_
.SetUserSelectedDefaultSearchEngine(url
->data());
589 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
593 TemplateURL
* TemplateURLService::GetDefaultSearchProvider() {
594 return const_cast<TemplateURL
*>(
595 static_cast<const TemplateURLService
*>(this)->GetDefaultSearchProvider());
598 const TemplateURL
* TemplateURLService::GetDefaultSearchProvider() const {
599 return loaded_
? default_search_provider_
600 : initial_default_search_provider_
.get();
603 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
604 const GURL
& url
) const {
605 const TemplateURL
* default_provider
= GetDefaultSearchProvider();
606 return default_provider
&&
607 default_provider
->IsSearchURL(url
, search_terms_data());
610 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
611 return default_search_provider_source_
==
612 DefaultSearchManager::FROM_EXTENSION
;
615 void TemplateURLService::RepairPrepopulatedSearchEngines() {
616 // Can't clean DB if it hasn't been loaded.
619 if ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
620 (default_search_provider_source_
==
621 DefaultSearchManager::FROM_FALLBACK
)) {
622 // Clear |default_search_provider_| in case we want to remove the engine it
623 // points to. This will get reset at the end of the function anyway.
624 default_search_provider_
= NULL
;
627 size_t default_search_provider_index
= 0;
628 ScopedVector
<TemplateURLData
> prepopulated_urls
=
629 TemplateURLPrepopulateData::GetPrepopulatedEngines(
630 prefs_
, &default_search_provider_index
);
631 DCHECK(!prepopulated_urls
.empty());
632 ActionsFromPrepopulateData
actions(CreateActionsFromCurrentPrepopulateData(
633 &prepopulated_urls
, template_urls_
, default_search_provider_
));
635 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
638 for (std::vector
<TemplateURL
*>::iterator i
= actions
.removed_engines
.begin();
639 i
< actions
.removed_engines
.end(); ++i
)
643 for (EditedEngines::iterator
i(actions
.edited_engines
.begin());
644 i
< actions
.edited_engines
.end(); ++i
) {
645 TemplateURL
new_values(i
->second
);
646 UpdateNoNotify(i
->first
, new_values
);
650 for (std::vector
<TemplateURLData
>::const_iterator i
=
651 actions
.added_engines
.begin();
652 i
< actions
.added_engines
.end();
654 AddNoNotify(new TemplateURL(*i
), true);
657 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
658 &dsp_change_origin_
, DSP_CHANGE_PROFILE_RESET
);
660 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
662 if (!default_search_provider_
) {
663 // If the default search provider came from a user pref we would have been
664 // notified of the new (fallback-provided) value in
665 // ClearUserSelectedDefaultSearchEngine() above. Since we are here, the
666 // value was presumably originally a fallback value (which may have been
668 DefaultSearchManager::Source source
;
669 const TemplateURLData
* new_dse
=
670 default_search_manager_
.GetDefaultSearchEngine(&source
);
671 // ApplyDefaultSearchChange will notify observers once it is done.
672 ApplyDefaultSearchChange(new_dse
, source
);
678 void TemplateURLService::AddObserver(TemplateURLServiceObserver
* observer
) {
679 model_observers_
.AddObserver(observer
);
682 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver
* observer
) {
683 model_observers_
.RemoveObserver(observer
);
686 void TemplateURLService::Load() {
687 if (loaded_
|| load_handle_
)
690 if (web_data_service_
.get())
691 load_handle_
= web_data_service_
->GetKeywords(this);
693 ChangeToLoadedState();
696 scoped_ptr
<TemplateURLService::Subscription
>
697 TemplateURLService::RegisterOnLoadedCallback(
698 const base::Closure
& callback
) {
700 scoped_ptr
<TemplateURLService::Subscription
>() :
701 on_loaded_callbacks_
.Add(callback
);
704 void TemplateURLService::OnWebDataServiceRequestDone(
705 KeywordWebDataService::Handle h
,
706 const WDTypedResult
* result
) {
707 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
709 tracked_objects::ScopedTracker
tracking_profile(
710 FROM_HERE_WITH_EXPLICIT_FUNCTION(
711 "422460 TemplateURLService::OnWebDataServiceRequestDone"));
713 // Reset the load_handle so that we don't try and cancel the load in
718 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
720 tracked_objects::ScopedTracker
tracking_profile1(
721 FROM_HERE_WITH_EXPLICIT_FUNCTION(
722 "422460 TemplateURLService::OnWebDataServiceRequestDone 1"));
724 // Results are null if the database went away or (most likely) wasn't
727 web_data_service_
= NULL
;
728 ChangeToLoadedState();
732 TemplateURLVector template_urls
;
733 int new_resource_keyword_version
= 0;
735 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
737 tracked_objects::ScopedTracker
tracking_profile2(
738 FROM_HERE_WITH_EXPLICIT_FUNCTION(
739 "422460 TemplateURLService::OnWebDataServiceRequestDone 2"));
741 GetSearchProvidersUsingKeywordResult(
742 *result
, web_data_service_
.get(), prefs_
, &template_urls
,
743 (default_search_provider_source_
== DefaultSearchManager::FROM_USER
)
744 ? initial_default_search_provider_
.get()
746 search_terms_data(), &new_resource_keyword_version
, &pre_sync_deletes_
);
749 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
752 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
754 tracked_objects::ScopedTracker
tracking_profile4(
755 FROM_HERE_WITH_EXPLICIT_FUNCTION(
756 "422460 TemplateURLService::OnWebDataServiceRequestDone 4"));
758 PatchMissingSyncGUIDs(&template_urls
);
760 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
762 tracked_objects::ScopedTracker
tracking_profile41(
763 FROM_HERE_WITH_EXPLICIT_FUNCTION(
764 "422460 TemplateURLService::OnWebDataServiceRequestDone 41"));
766 SetTemplateURLs(&template_urls
);
768 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
770 tracked_objects::ScopedTracker
tracking_profile42(
771 FROM_HERE_WITH_EXPLICIT_FUNCTION(
772 "422460 TemplateURLService::OnWebDataServiceRequestDone 42"));
774 // This initializes provider_map_ which should be done before
775 // calling UpdateKeywordSearchTermsForURL.
776 // This also calls NotifyObservers.
777 ChangeToLoadedState();
779 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
781 tracked_objects::ScopedTracker
tracking_profile43(
782 FROM_HERE_WITH_EXPLICIT_FUNCTION(
783 "422460 TemplateURLService::OnWebDataServiceRequestDone 43"));
785 // Index any visits that occurred before we finished loading.
786 for (size_t i
= 0; i
< visits_to_add_
.size(); ++i
)
787 UpdateKeywordSearchTermsForURL(visits_to_add_
[i
]);
788 visits_to_add_
.clear();
790 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
792 tracked_objects::ScopedTracker
tracking_profile44(
793 FROM_HERE_WITH_EXPLICIT_FUNCTION(
794 "422460 TemplateURLService::OnWebDataServiceRequestDone 44"));
796 if (new_resource_keyword_version
)
797 web_data_service_
->SetBuiltinKeywordVersion(new_resource_keyword_version
);
800 if (default_search_provider_
) {
801 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
803 tracked_objects::ScopedTracker
tracking_profile5(
804 FROM_HERE_WITH_EXPLICIT_FUNCTION(
805 "422460 TemplateURLService::OnWebDataServiceRequestDone 5"));
807 UMA_HISTOGRAM_ENUMERATION(
808 "Search.DefaultSearchProviderType",
809 TemplateURLPrepopulateData::GetEngineType(
810 *default_search_provider_
, search_terms_data()),
813 if (rappor_service_
) {
814 rappor_service_
->RecordSample(
815 "Search.DefaultSearchProvider",
816 rappor::ETLD_PLUS_ONE_RAPPOR_TYPE
,
817 net::registry_controlled_domains::GetDomainAndRegistry(
818 default_search_provider_
->url_ref().GetHost(search_terms_data()),
819 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
));
824 base::string16
TemplateURLService::GetKeywordShortName(
825 const base::string16
& keyword
,
826 bool* is_omnibox_api_extension_keyword
) {
827 const TemplateURL
* template_url
= GetTemplateURLForKeyword(keyword
);
829 // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
830 // to track changes to the model, this should become a DCHECK.
832 *is_omnibox_api_extension_keyword
=
833 template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
834 return template_url
->AdjustedShortNameForLocaleDirection();
836 *is_omnibox_api_extension_keyword
= false;
837 return base::string16();
840 void TemplateURLService::OnHistoryURLVisited(const URLVisitedDetails
& details
) {
842 visits_to_add_
.push_back(details
);
844 UpdateKeywordSearchTermsForURL(details
);
847 void TemplateURLService::Shutdown() {
850 // This check has to be done at Shutdown() instead of in the dtor to ensure
851 // that no clients of KeywordWebDataService are holding ptrs to it after the
852 // first phase of the KeyedService Shutdown() process.
854 DCHECK(web_data_service_
.get());
855 web_data_service_
->CancelRequest(load_handle_
);
857 web_data_service_
= NULL
;
860 syncer::SyncDataList
TemplateURLService::GetAllSyncData(
861 syncer::ModelType type
) const {
862 DCHECK_EQ(syncer::SEARCH_ENGINES
, type
);
864 syncer::SyncDataList current_data
;
865 for (TemplateURLVector::const_iterator iter
= template_urls_
.begin();
866 iter
!= template_urls_
.end(); ++iter
) {
867 // We don't sync keywords managed by policy.
868 if ((*iter
)->created_by_policy())
870 // We don't sync extension-controlled search engines.
871 if ((*iter
)->GetType() != TemplateURL::NORMAL
)
873 current_data
.push_back(CreateSyncDataFromTemplateURL(**iter
));
879 syncer::SyncError
TemplateURLService::ProcessSyncChanges(
880 const tracked_objects::Location
& from_here
,
881 const syncer::SyncChangeList
& change_list
) {
882 if (!models_associated_
) {
883 syncer::SyncError
error(FROM_HERE
,
884 syncer::SyncError::DATATYPE_ERROR
,
885 "Models not yet associated.",
886 syncer::SEARCH_ENGINES
);
891 base::AutoReset
<bool> processing_changes(&processing_syncer_changes_
, true);
893 // We've started syncing, so set our origin member to the base Sync value.
894 // As we move through Sync Code, we may set this to increasingly specific
895 // origins so we can tell what exactly caused a DSP change.
896 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(&dsp_change_origin_
,
897 DSP_CHANGE_SYNC_UNINTENTIONAL
);
899 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
901 syncer::SyncChangeList new_changes
;
902 syncer::SyncError error
;
903 for (syncer::SyncChangeList::const_iterator iter
= change_list
.begin();
904 iter
!= change_list
.end(); ++iter
) {
905 DCHECK_EQ(syncer::SEARCH_ENGINES
, iter
->sync_data().GetDataType());
908 iter
->sync_data().GetSpecifics().search_engine().sync_guid();
909 TemplateURL
* existing_turl
= GetTemplateURLForGUID(guid
);
910 scoped_ptr
<TemplateURL
> turl(CreateTemplateURLFromTemplateURLAndSyncData(
911 client_
.get(), prefs_
, search_terms_data(), existing_turl
,
912 iter
->sync_data(), &new_changes
));
916 // Explicitly don't check for conflicts against extension keywords; in this
917 // case the functions which modify the keyword map know how to handle the
919 // TODO(mpcomplete): If we allow editing extension keywords, then those will
920 // need to undergo conflict resolution.
921 TemplateURL
* existing_keyword_turl
=
922 FindNonExtensionTemplateURLForKeyword(turl
->keyword());
923 if (iter
->change_type() == syncer::SyncChange::ACTION_DELETE
) {
924 if (!existing_turl
) {
925 error
= sync_error_factory_
->CreateAndUploadError(
927 "ProcessSyncChanges failed on ChangeType ACTION_DELETE");
930 if (existing_turl
== GetDefaultSearchProvider()) {
931 // The only way Sync can attempt to delete the default search provider
932 // is if we had changed the kSyncedDefaultSearchProviderGUID
933 // preference, but perhaps it has not yet been received. To avoid
934 // situations where this has come in erroneously, we will un-delete
935 // the current default search from the Sync data. If the pref really
936 // does arrive later, then default search will change to the correct
937 // entry, but we'll have this extra entry sitting around. The result is
938 // not ideal, but it prevents a far more severe bug where the default is
939 // unexpectedly swapped to something else. The user can safely delete
940 // the extra entry again later, if they choose. Most users who do not
941 // look at the search engines UI will not notice this.
942 // Note that we append a special character to the end of the keyword in
943 // an attempt to avoid a ping-poinging situation where receiving clients
944 // may try to continually delete the resurrected entry.
945 base::string16 updated_keyword
= UniquifyKeyword(*existing_turl
, true);
946 TemplateURLData
data(existing_turl
->data());
947 data
.SetKeyword(updated_keyword
);
948 TemplateURL
new_turl(data
);
949 if (UpdateNoNotify(existing_turl
, new_turl
))
952 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(new_turl
);
953 new_changes
.push_back(syncer::SyncChange(FROM_HERE
,
954 syncer::SyncChange::ACTION_ADD
,
956 // Ignore the delete attempt. This means we never end up resetting the
957 // default search provider due to an ACTION_DELETE from sync.
961 Remove(existing_turl
);
962 } else if (iter
->change_type() == syncer::SyncChange::ACTION_ADD
) {
964 error
= sync_error_factory_
->CreateAndUploadError(
966 "ProcessSyncChanges failed on ChangeType ACTION_ADD");
969 const std::string guid
= turl
->sync_guid();
970 if (existing_keyword_turl
) {
971 // Resolve any conflicts so we can safely add the new entry.
972 ResolveSyncKeywordConflict(turl
.get(), existing_keyword_turl
,
975 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
976 &dsp_change_origin_
, DSP_CHANGE_SYNC_ADD
);
977 // Force the local ID to kInvalidTemplateURLID so we can add it.
978 TemplateURLData
data(turl
->data());
979 data
.id
= kInvalidTemplateURLID
;
980 TemplateURL
* added
= new TemplateURL(data
);
982 MaybeUpdateDSEAfterSync(added
);
983 } else if (iter
->change_type() == syncer::SyncChange::ACTION_UPDATE
) {
984 if (!existing_turl
) {
985 error
= sync_error_factory_
->CreateAndUploadError(
987 "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
990 if (existing_keyword_turl
&& (existing_keyword_turl
!= existing_turl
)) {
991 // Resolve any conflicts with other entries so we can safely update the
993 ResolveSyncKeywordConflict(turl
.get(), existing_keyword_turl
,
996 if (UpdateNoNotify(existing_turl
, *turl
)) {
998 MaybeUpdateDSEAfterSync(existing_turl
);
1001 // We've unexpectedly received an ACTION_INVALID.
1002 error
= sync_error_factory_
->CreateAndUploadError(
1004 "ProcessSyncChanges received an ACTION_INVALID");
1008 // If something went wrong, we want to prematurely exit to avoid pushing
1009 // inconsistent data to Sync. We return the last error we received.
1013 error
= sync_processor_
->ProcessSyncChanges(from_here
, new_changes
);
1018 syncer::SyncMergeResult
TemplateURLService::MergeDataAndStartSyncing(
1019 syncer::ModelType type
,
1020 const syncer::SyncDataList
& initial_sync_data
,
1021 scoped_ptr
<syncer::SyncChangeProcessor
> sync_processor
,
1022 scoped_ptr
<syncer::SyncErrorFactory
> sync_error_factory
) {
1024 DCHECK_EQ(type
, syncer::SEARCH_ENGINES
);
1025 DCHECK(!sync_processor_
.get());
1026 DCHECK(sync_processor
.get());
1027 DCHECK(sync_error_factory
.get());
1028 syncer::SyncMergeResult
merge_result(type
);
1030 // Disable sync if we failed to load.
1032 merge_result
.set_error(syncer::SyncError(
1033 FROM_HERE
, syncer::SyncError::DATATYPE_ERROR
,
1034 "Local database load failed.", syncer::SEARCH_ENGINES
));
1035 return merge_result
;
1038 sync_processor_
= sync_processor
.Pass();
1039 sync_error_factory_
= sync_error_factory
.Pass();
1041 // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
1042 // don't step on our own toes.
1043 base::AutoReset
<bool> processing_changes(&processing_syncer_changes_
, true);
1045 // We've started syncing, so set our origin member to the base Sync value.
1046 // As we move through Sync Code, we may set this to increasingly specific
1047 // origins so we can tell what exactly caused a DSP change.
1048 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(&dsp_change_origin_
,
1049 DSP_CHANGE_SYNC_UNINTENTIONAL
);
1051 syncer::SyncChangeList new_changes
;
1053 // Build maps of our sync GUIDs to syncer::SyncData.
1054 SyncDataMap local_data_map
= CreateGUIDToSyncDataMap(
1055 GetAllSyncData(syncer::SEARCH_ENGINES
));
1056 SyncDataMap sync_data_map
= CreateGUIDToSyncDataMap(initial_sync_data
);
1058 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1060 merge_result
.set_num_items_before_association(local_data_map
.size());
1061 for (SyncDataMap::const_iterator iter
= sync_data_map
.begin();
1062 iter
!= sync_data_map
.end(); ++iter
) {
1063 TemplateURL
* local_turl
= GetTemplateURLForGUID(iter
->first
);
1064 scoped_ptr
<TemplateURL
> sync_turl(
1065 CreateTemplateURLFromTemplateURLAndSyncData(
1066 client_
.get(), prefs_
, search_terms_data(), local_turl
,
1067 iter
->second
, &new_changes
));
1068 if (!sync_turl
.get())
1071 if (pre_sync_deletes_
.find(sync_turl
->sync_guid()) !=
1072 pre_sync_deletes_
.end()) {
1073 // This entry was deleted before the initial sync began (possibly through
1074 // preprocessing in TemplateURLService's loading code). Ignore it and send
1075 // an ACTION_DELETE up to the server.
1076 new_changes
.push_back(
1077 syncer::SyncChange(FROM_HERE
,
1078 syncer::SyncChange::ACTION_DELETE
,
1080 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1081 DELETE_ENGINE_PRE_SYNC
, DELETE_ENGINE_MAX
);
1086 DCHECK(IsFromSync(local_turl
, sync_data_map
));
1087 // This local search engine is already synced. If the timestamp differs
1088 // from Sync, we need to update locally or to the cloud. Note that if the
1089 // timestamps are equal, we touch neither.
1090 if (sync_turl
->last_modified() > local_turl
->last_modified()) {
1091 // We've received an update from Sync. We should replace all synced
1092 // fields in the local TemplateURL. Note that this includes the
1093 // TemplateURLID and the TemplateURL may have to be reparsed. This
1094 // also makes the local data's last_modified timestamp equal to Sync's,
1095 // avoiding an Update on the next MergeData call.
1096 if (UpdateNoNotify(local_turl
, *sync_turl
))
1098 merge_result
.set_num_items_modified(
1099 merge_result
.num_items_modified() + 1);
1100 } else if (sync_turl
->last_modified() < local_turl
->last_modified()) {
1101 // Otherwise, we know we have newer data, so update Sync with our
1103 new_changes
.push_back(
1104 syncer::SyncChange(FROM_HERE
,
1105 syncer::SyncChange::ACTION_UPDATE
,
1106 local_data_map
[local_turl
->sync_guid()]));
1108 local_data_map
.erase(iter
->first
);
1110 // The search engine from the cloud has not been synced locally. Merge it
1111 // into our local model. This will handle any conflicts with local (and
1112 // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1113 // over not-yet-synced TemplateURLs.
1114 MergeInSyncTemplateURL(sync_turl
.get(), sync_data_map
, &new_changes
,
1115 &local_data_map
, &merge_result
);
1119 // The remaining SyncData in local_data_map should be everything that needs to
1120 // be pushed as ADDs to sync.
1121 for (SyncDataMap::const_iterator iter
= local_data_map
.begin();
1122 iter
!= local_data_map
.end(); ++iter
) {
1123 new_changes
.push_back(
1124 syncer::SyncChange(FROM_HERE
,
1125 syncer::SyncChange::ACTION_ADD
,
1129 // Do some post-processing on the change list to ensure that we are sending
1130 // valid changes to sync_processor_.
1131 PruneSyncChanges(&sync_data_map
, &new_changes
);
1133 LogDuplicatesHistogram(GetTemplateURLs());
1134 merge_result
.set_num_items_after_association(
1135 GetAllSyncData(syncer::SEARCH_ENGINES
).size());
1136 merge_result
.set_error(
1137 sync_processor_
->ProcessSyncChanges(FROM_HERE
, new_changes
));
1138 if (merge_result
.error().IsSet())
1139 return merge_result
;
1141 // The ACTION_DELETEs from this set are processed. Empty it so we don't try to
1142 // reuse them on the next call to MergeDataAndStartSyncing.
1143 pre_sync_deletes_
.clear();
1145 models_associated_
= true;
1146 return merge_result
;
1149 void TemplateURLService::StopSyncing(syncer::ModelType type
) {
1150 DCHECK_EQ(type
, syncer::SEARCH_ENGINES
);
1151 models_associated_
= false;
1152 sync_processor_
.reset();
1153 sync_error_factory_
.reset();
1156 void TemplateURLService::ProcessTemplateURLChange(
1157 const tracked_objects::Location
& from_here
,
1158 const TemplateURL
* turl
,
1159 syncer::SyncChange::SyncChangeType type
) {
1160 DCHECK_NE(type
, syncer::SyncChange::ACTION_INVALID
);
1163 if (!models_associated_
)
1164 return; // Not syncing.
1166 if (processing_syncer_changes_
)
1167 return; // These are changes originating from us. Ignore.
1169 // Avoid syncing keywords managed by policy.
1170 if (turl
->created_by_policy())
1173 // Avoid syncing extension-controlled search engines.
1174 if (turl
->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
)
1177 syncer::SyncChangeList changes
;
1179 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*turl
);
1180 changes
.push_back(syncer::SyncChange(from_here
,
1184 sync_processor_
->ProcessSyncChanges(FROM_HERE
, changes
);
1188 syncer::SyncData
TemplateURLService::CreateSyncDataFromTemplateURL(
1189 const TemplateURL
& turl
) {
1190 sync_pb::EntitySpecifics specifics
;
1191 sync_pb::SearchEngineSpecifics
* se_specifics
=
1192 specifics
.mutable_search_engine();
1193 se_specifics
->set_short_name(base::UTF16ToUTF8(turl
.short_name()));
1194 se_specifics
->set_keyword(base::UTF16ToUTF8(turl
.keyword()));
1195 se_specifics
->set_favicon_url(turl
.favicon_url().spec());
1196 se_specifics
->set_url(turl
.url());
1197 se_specifics
->set_safe_for_autoreplace(turl
.safe_for_autoreplace());
1198 se_specifics
->set_originating_url(turl
.originating_url().spec());
1199 se_specifics
->set_date_created(turl
.date_created().ToInternalValue());
1200 se_specifics
->set_input_encodings(
1201 base::JoinString(turl
.input_encodings(), ";"));
1202 se_specifics
->set_show_in_default_list(turl
.show_in_default_list());
1203 se_specifics
->set_suggestions_url(turl
.suggestions_url());
1204 se_specifics
->set_prepopulate_id(turl
.prepopulate_id());
1205 se_specifics
->set_instant_url(turl
.instant_url());
1206 if (!turl
.image_url().empty())
1207 se_specifics
->set_image_url(turl
.image_url());
1208 se_specifics
->set_new_tab_url(turl
.new_tab_url());
1209 if (!turl
.search_url_post_params().empty())
1210 se_specifics
->set_search_url_post_params(turl
.search_url_post_params());
1211 if (!turl
.suggestions_url_post_params().empty()) {
1212 se_specifics
->set_suggestions_url_post_params(
1213 turl
.suggestions_url_post_params());
1215 if (!turl
.instant_url_post_params().empty())
1216 se_specifics
->set_instant_url_post_params(turl
.instant_url_post_params());
1217 if (!turl
.image_url_post_params().empty())
1218 se_specifics
->set_image_url_post_params(turl
.image_url_post_params());
1219 se_specifics
->set_last_modified(turl
.last_modified().ToInternalValue());
1220 se_specifics
->set_sync_guid(turl
.sync_guid());
1221 for (size_t i
= 0; i
< turl
.alternate_urls().size(); ++i
)
1222 se_specifics
->add_alternate_urls(turl
.alternate_urls()[i
]);
1223 se_specifics
->set_search_terms_replacement_key(
1224 turl
.search_terms_replacement_key());
1226 return syncer::SyncData::CreateLocalData(se_specifics
->sync_guid(),
1227 se_specifics
->keyword(),
1232 scoped_ptr
<TemplateURL
>
1233 TemplateURLService::CreateTemplateURLFromTemplateURLAndSyncData(
1234 TemplateURLServiceClient
* client
,
1236 const SearchTermsData
& search_terms_data
,
1237 TemplateURL
* existing_turl
,
1238 const syncer::SyncData
& sync_data
,
1239 syncer::SyncChangeList
* change_list
) {
1240 DCHECK(change_list
);
1242 sync_pb::SearchEngineSpecifics specifics
=
1243 sync_data
.GetSpecifics().search_engine();
1245 // Past bugs might have caused either of these fields to be empty. Just
1246 // delete this data off the server.
1247 if (specifics
.url().empty() || specifics
.sync_guid().empty()) {
1248 change_list
->push_back(
1249 syncer::SyncChange(FROM_HERE
,
1250 syncer::SyncChange::ACTION_DELETE
,
1252 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1253 DELETE_ENGINE_EMPTY_FIELD
, DELETE_ENGINE_MAX
);
1257 TemplateURLData
data(existing_turl
?
1258 existing_turl
->data() : TemplateURLData());
1259 data
.SetShortName(base::UTF8ToUTF16(specifics
.short_name()));
1260 data
.originating_url
= GURL(specifics
.originating_url());
1261 base::string16
keyword(base::UTF8ToUTF16(specifics
.keyword()));
1262 // NOTE: Once this code has shipped in a couple of stable releases, we can
1263 // probably remove the migration portion, comment out the
1264 // "autogenerate_keyword" field entirely in the .proto file, and fold the
1265 // empty keyword case into the "delete data" block above.
1266 bool reset_keyword
=
1267 specifics
.autogenerate_keyword() || specifics
.keyword().empty();
1269 keyword
= base::ASCIIToUTF16("dummy"); // Will be replaced below.
1270 DCHECK(!keyword
.empty());
1271 data
.SetKeyword(keyword
);
1272 data
.SetURL(specifics
.url());
1273 data
.suggestions_url
= specifics
.suggestions_url();
1274 data
.instant_url
= specifics
.instant_url();
1275 data
.image_url
= specifics
.image_url();
1276 data
.new_tab_url
= specifics
.new_tab_url();
1277 data
.search_url_post_params
= specifics
.search_url_post_params();
1278 data
.suggestions_url_post_params
= specifics
.suggestions_url_post_params();
1279 data
.instant_url_post_params
= specifics
.instant_url_post_params();
1280 data
.image_url_post_params
= specifics
.image_url_post_params();
1281 data
.favicon_url
= GURL(specifics
.favicon_url());
1282 data
.show_in_default_list
= specifics
.show_in_default_list();
1283 data
.safe_for_autoreplace
= specifics
.safe_for_autoreplace();
1284 base::SplitString(specifics
.input_encodings(), ';', &data
.input_encodings
);
1285 // If the server data has duplicate encodings, we'll want to push an update
1286 // below to correct it. Note that we also fix this in
1287 // GetSearchProvidersUsingKeywordResult(), since otherwise we'd never correct
1288 // local problems for clients which have disabled search engine sync.
1289 bool deduped
= DeDupeEncodings(&data
.input_encodings
);
1290 data
.date_created
= base::Time::FromInternalValue(specifics
.date_created());
1291 data
.last_modified
= base::Time::FromInternalValue(specifics
.last_modified());
1292 data
.prepopulate_id
= specifics
.prepopulate_id();
1293 data
.sync_guid
= specifics
.sync_guid();
1294 data
.alternate_urls
.clear();
1295 for (int i
= 0; i
< specifics
.alternate_urls_size(); ++i
)
1296 data
.alternate_urls
.push_back(specifics
.alternate_urls(i
));
1297 data
.search_terms_replacement_key
= specifics
.search_terms_replacement_key();
1299 scoped_ptr
<TemplateURL
> turl(new TemplateURL(data
));
1300 // If this TemplateURL matches a built-in prepopulated template URL, it's
1301 // possible that sync is trying to modify fields that should not be touched.
1302 // Revert these fields to the built-in values.
1303 UpdateTemplateURLIfPrepopulated(turl
.get(), prefs
);
1305 // We used to sync keywords associated with omnibox extensions, but no longer
1306 // want to. However, if we delete these keywords from sync, we'll break any
1307 // synced old versions of Chrome which were relying on them. Instead, for now
1308 // we simply ignore these.
1309 // TODO(vasilii): After a few Chrome versions, change this to go ahead and
1310 // delete these from sync.
1312 client
->RestoreExtensionInfoIfNecessary(turl
.get());
1313 if (turl
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
)
1316 DCHECK_EQ(TemplateURL::NORMAL
, turl
->GetType());
1317 if (reset_keyword
|| deduped
) {
1319 turl
->ResetKeywordIfNecessary(search_terms_data
, true);
1320 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*turl
);
1321 change_list
->push_back(syncer::SyncChange(FROM_HERE
,
1322 syncer::SyncChange::ACTION_UPDATE
,
1324 } else if (turl
->IsGoogleSearchURLWithReplaceableKeyword(search_terms_data
)) {
1325 if (!existing_turl
) {
1326 // We're adding a new TemplateURL that uses the Google base URL, so set
1327 // its keyword appropriately for the local environment.
1328 turl
->ResetKeywordIfNecessary(search_terms_data
, false);
1329 } else if (existing_turl
->IsGoogleSearchURLWithReplaceableKeyword(
1330 search_terms_data
)) {
1331 // Ignore keyword changes triggered by the Google base URL changing on
1332 // another client. If the base URL changes in this client as well, we'll
1333 // pick that up separately at the appropriate time. Otherwise, changing
1334 // the keyword here could result in having the wrong keyword for the local
1336 turl
->data_
.SetKeyword(existing_turl
->keyword());
1344 SyncDataMap
TemplateURLService::CreateGUIDToSyncDataMap(
1345 const syncer::SyncDataList
& sync_data
) {
1346 SyncDataMap data_map
;
1347 for (syncer::SyncDataList::const_iterator
i(sync_data
.begin());
1348 i
!= sync_data
.end();
1350 data_map
[i
->GetSpecifics().search_engine().sync_guid()] = *i
;
1354 void TemplateURLService::Init(const Initializer
* initializers
,
1355 int num_initializers
) {
1357 client_
->SetOwner(this);
1359 // GoogleURLTracker is not created in tests.
1360 if (google_url_tracker_
) {
1361 google_url_updated_subscription_
=
1362 google_url_tracker_
->RegisterCallback(base::Bind(
1363 &TemplateURLService::GoogleBaseURLChanged
, base::Unretained(this)));
1367 pref_change_registrar_
.Init(prefs_
);
1368 pref_change_registrar_
.Add(
1369 prefs::kSyncedDefaultSearchProviderGUID
,
1371 &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged
,
1372 base::Unretained(this)));
1375 DefaultSearchManager::Source source
= DefaultSearchManager::FROM_USER
;
1376 TemplateURLData
* dse
=
1377 default_search_manager_
.GetDefaultSearchEngine(&source
);
1378 ApplyDefaultSearchChange(dse
, source
);
1380 if (num_initializers
> 0) {
1381 // This path is only hit by test code and is used to simulate a loaded
1382 // TemplateURLService.
1383 ChangeToLoadedState();
1385 // Add specific initializers, if any.
1386 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1387 for (int i(0); i
< num_initializers
; ++i
) {
1388 DCHECK(initializers
[i
].keyword
);
1389 DCHECK(initializers
[i
].url
);
1390 DCHECK(initializers
[i
].content
);
1392 // TemplateURLService ends up owning the TemplateURL, don't try and free
1394 TemplateURLData data
;
1395 data
.SetShortName(base::UTF8ToUTF16(initializers
[i
].content
));
1396 data
.SetKeyword(base::UTF8ToUTF16(initializers
[i
].keyword
));
1397 data
.SetURL(initializers
[i
].url
);
1398 TemplateURL
* template_url
= new TemplateURL(data
);
1399 AddNoNotify(template_url
, true);
1401 // Set the first provided identifier to be the default.
1403 default_search_manager_
.SetUserSelectedDefaultSearchEngine(data
);
1407 // Request a server check for the correct Google URL if Google is the
1408 // default search engine.
1409 RequestGoogleURLTrackerServerCheckIfNecessary();
1412 void TemplateURLService::RemoveFromMaps(TemplateURL
* template_url
) {
1413 const base::string16
& keyword
= template_url
->keyword();
1414 DCHECK_NE(0U, keyword_to_template_map_
.count(keyword
));
1415 if (keyword_to_template_map_
[keyword
] == template_url
) {
1416 // We need to check whether the keyword can now be provided by another
1417 // TemplateURL. See the comments in AddToMaps() for more information on
1418 // extension keywords and how they can coexist with non-extension keywords.
1419 // In the case of more than one extension, we use the most recently
1420 // installed (which will be the most recently added, which will have the
1422 TemplateURL
* best_fallback
= NULL
;
1423 for (TemplateURLVector::const_iterator
i(template_urls_
.begin());
1424 i
!= template_urls_
.end(); ++i
) {
1425 TemplateURL
* turl
= *i
;
1426 // This next statement relies on the fact that there can only be one
1427 // non-Omnibox API TemplateURL with a given keyword.
1428 if ((turl
!= template_url
) && (turl
->keyword() == keyword
) &&
1430 (best_fallback
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
) ||
1431 ((turl
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
) &&
1432 (turl
->id() > best_fallback
->id()))))
1433 best_fallback
= turl
;
1436 keyword_to_template_map_
[keyword
] = best_fallback
;
1438 keyword_to_template_map_
.erase(keyword
);
1441 if (template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
)
1444 if (!template_url
->sync_guid().empty())
1445 guid_to_template_map_
.erase(template_url
->sync_guid());
1446 // |provider_map_| is only initialized after loading has completed.
1448 provider_map_
->Remove(template_url
);
1452 void TemplateURLService::AddToMaps(TemplateURL
* template_url
) {
1453 bool template_url_is_omnibox_api
=
1454 template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
1455 const base::string16
& keyword
= template_url
->keyword();
1456 KeywordToTemplateMap::const_iterator i
=
1457 keyword_to_template_map_
.find(keyword
);
1458 if (i
== keyword_to_template_map_
.end()) {
1459 keyword_to_template_map_
[keyword
] = template_url
;
1461 const TemplateURL
* existing_url
= i
->second
;
1462 // We should only have overlapping keywords when at least one comes from
1463 // an extension. In that case, the ranking order is:
1464 // Manually-modified keywords > extension keywords > replaceable keywords
1465 // When there are multiple extensions, the last-added wins.
1466 bool existing_url_is_omnibox_api
=
1467 existing_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
1468 DCHECK(existing_url_is_omnibox_api
|| template_url_is_omnibox_api
);
1469 if (existing_url_is_omnibox_api
?
1470 !CanReplace(template_url
) : CanReplace(existing_url
))
1471 keyword_to_template_map_
[keyword
] = template_url
;
1474 if (template_url_is_omnibox_api
)
1477 if (!template_url
->sync_guid().empty())
1478 guid_to_template_map_
[template_url
->sync_guid()] = template_url
;
1479 // |provider_map_| is only initialized after loading has completed.
1481 provider_map_
->Add(template_url
, search_terms_data());
1484 // Helper for partition() call in next function.
1485 bool HasValidID(TemplateURL
* t_url
) {
1486 return t_url
->id() != kInvalidTemplateURLID
;
1489 void TemplateURLService::SetTemplateURLs(TemplateURLVector
* urls
) {
1490 // Partition the URLs first, instead of implementing the loops below by simply
1491 // scanning the input twice. While it's not supposed to happen normally, it's
1492 // possible for corrupt databases to return multiple entries with the same
1493 // keyword. In this case, the first loop may delete the first entry when
1494 // adding the second. If this happens, the second loop must not attempt to
1495 // access the deleted entry. Partitioning ensures this constraint.
1496 TemplateURLVector::iterator
first_invalid(
1497 std::partition(urls
->begin(), urls
->end(), HasValidID
));
1499 // First, add the items that already have id's, so that the next_id_ gets
1501 for (TemplateURLVector::const_iterator i
= urls
->begin(); i
!= first_invalid
;
1503 next_id_
= std::max(next_id_
, (*i
)->id());
1504 AddNoNotify(*i
, false);
1507 // Next add the new items that don't have id's.
1508 for (TemplateURLVector::const_iterator i
= first_invalid
; i
!= urls
->end();
1510 AddNoNotify(*i
, true);
1512 // Clear the input vector to reduce the chance callers will try to use a
1513 // (possibly deleted) entry.
1517 void TemplateURLService::ChangeToLoadedState() {
1518 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1520 tracked_objects::ScopedTracker
tracking_profile1(
1521 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1522 "422460 TemplateURLService::ChangeToLoadedState 1"));
1526 provider_map_
->Init(template_urls_
, search_terms_data());
1529 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1531 tracked_objects::ScopedTracker
tracking_profile2(
1532 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1533 "422460 TemplateURLService::ChangeToLoadedState 2"));
1535 // This will cause a call to NotifyObservers().
1536 ApplyDefaultSearchChangeNoMetrics(
1537 initial_default_search_provider_
?
1538 &initial_default_search_provider_
->data() : NULL
,
1539 default_search_provider_source_
);
1540 initial_default_search_provider_
.reset();
1542 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1544 tracked_objects::ScopedTracker
tracking_profile3(
1545 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1546 "422460 TemplateURLService::ChangeToLoadedState 3"));
1548 on_loaded_callbacks_
.Notify();
1551 bool TemplateURLService::CanAddAutogeneratedKeywordForHost(
1552 const std::string
& host
) {
1553 const TemplateURLSet
* urls
= provider_map_
->GetURLsForHost(host
);
1556 for (TemplateURLSet::const_iterator
i(urls
->begin()); i
!= urls
->end(); ++i
) {
1557 if (!(*i
)->safe_for_autoreplace())
1563 bool TemplateURLService::CanReplace(const TemplateURL
* t_url
) {
1564 return (t_url
!= default_search_provider_
&& !t_url
->show_in_default_list() &&
1565 t_url
->safe_for_autoreplace());
1568 TemplateURL
* TemplateURLService::FindNonExtensionTemplateURLForKeyword(
1569 const base::string16
& keyword
) {
1570 TemplateURL
* keyword_turl
= GetTemplateURLForKeyword(keyword
);
1571 if (!keyword_turl
|| (keyword_turl
->GetType() == TemplateURL::NORMAL
))
1572 return keyword_turl
;
1573 // The extension keyword in the model may be hiding a replaceable
1574 // non-extension keyword. Look for it.
1575 for (TemplateURLVector::const_iterator
i(template_urls_
.begin());
1576 i
!= template_urls_
.end(); ++i
) {
1577 if (((*i
)->GetType() == TemplateURL::NORMAL
) &&
1578 ((*i
)->keyword() == keyword
))
1584 bool TemplateURLService::UpdateNoNotify(TemplateURL
* existing_turl
,
1585 const TemplateURL
& new_values
) {
1586 DCHECK(existing_turl
);
1587 if (std::find(template_urls_
.begin(), template_urls_
.end(), existing_turl
) ==
1588 template_urls_
.end())
1591 DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION
, existing_turl
->GetType());
1593 base::string16
old_keyword(existing_turl
->keyword());
1594 keyword_to_template_map_
.erase(old_keyword
);
1595 if (!existing_turl
->sync_guid().empty())
1596 guid_to_template_map_
.erase(existing_turl
->sync_guid());
1598 // |provider_map_| is only initialized after loading has completed.
1600 provider_map_
->Remove(existing_turl
);
1602 TemplateURLID previous_id
= existing_turl
->id();
1603 existing_turl
->CopyFrom(new_values
);
1604 existing_turl
->data_
.id
= previous_id
;
1607 provider_map_
->Add(existing_turl
, search_terms_data());
1610 const base::string16
& keyword
= existing_turl
->keyword();
1611 KeywordToTemplateMap::const_iterator i
=
1612 keyword_to_template_map_
.find(keyword
);
1613 if (i
== keyword_to_template_map_
.end()) {
1614 keyword_to_template_map_
[keyword
] = existing_turl
;
1616 // We can theoretically reach here in two cases:
1617 // * There is an existing extension keyword and sync brings in a rename of
1618 // a non-extension keyword to match. In this case we just need to pick
1619 // which keyword has priority to update the keyword map.
1620 // * Autogeneration of the keyword for a Google default search provider
1621 // at load time causes it to conflict with an existing keyword. In this
1622 // case we delete the existing keyword if it's replaceable, or else undo
1623 // the change in keyword for |existing_turl|.
1624 TemplateURL
* existing_keyword_turl
= i
->second
;
1625 if (existing_keyword_turl
->GetType() != TemplateURL::NORMAL
) {
1626 if (!CanReplace(existing_turl
))
1627 keyword_to_template_map_
[keyword
] = existing_turl
;
1629 if (CanReplace(existing_keyword_turl
)) {
1630 RemoveNoNotify(existing_keyword_turl
);
1632 existing_turl
->data_
.SetKeyword(old_keyword
);
1633 keyword_to_template_map_
[old_keyword
] = existing_turl
;
1637 if (!existing_turl
->sync_guid().empty())
1638 guid_to_template_map_
[existing_turl
->sync_guid()] = existing_turl
;
1640 if (web_data_service_
.get())
1641 web_data_service_
->UpdateKeyword(existing_turl
->data());
1643 // Inform sync of the update.
1644 ProcessTemplateURLChange(
1645 FROM_HERE
, existing_turl
, syncer::SyncChange::ACTION_UPDATE
);
1647 if (default_search_provider_
== existing_turl
&&
1648 default_search_provider_source_
== DefaultSearchManager::FROM_USER
) {
1649 default_search_manager_
.SetUserSelectedDefaultSearchEngine(
1650 default_search_provider_
->data());
1656 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1657 TemplateURL
* template_url
,
1658 PrefService
* prefs
) {
1659 int prepopulate_id
= template_url
->prepopulate_id();
1660 if (template_url
->prepopulate_id() == 0)
1663 size_t default_search_index
;
1664 ScopedVector
<TemplateURLData
> prepopulated_urls
=
1665 TemplateURLPrepopulateData::GetPrepopulatedEngines(
1666 prefs
, &default_search_index
);
1668 for (size_t i
= 0; i
< prepopulated_urls
.size(); ++i
) {
1669 if (prepopulated_urls
[i
]->prepopulate_id
== prepopulate_id
) {
1670 MergeIntoPrepopulatedEngineData(template_url
, prepopulated_urls
[i
]);
1671 template_url
->CopyFrom(TemplateURL(*prepopulated_urls
[i
]));
1676 void TemplateURLService::MaybeUpdateDSEAfterSync(TemplateURL
* synced_turl
) {
1678 (synced_turl
->sync_guid() ==
1679 prefs_
->GetString(prefs::kSyncedDefaultSearchProviderGUID
))) {
1680 default_search_manager_
.SetUserSelectedDefaultSearchEngine(
1681 synced_turl
->data());
1685 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1686 const URLVisitedDetails
& details
) {
1687 if (!details
.url
.is_valid())
1690 const TemplateURLSet
* urls_for_host
=
1691 provider_map_
->GetURLsForHost(details
.url
.host());
1695 for (TemplateURLSet::const_iterator i
= urls_for_host
->begin();
1696 i
!= urls_for_host
->end(); ++i
) {
1697 base::string16 search_terms
;
1698 if ((*i
)->ExtractSearchTermsFromURL(details
.url
, search_terms_data(),
1700 !search_terms
.empty()) {
1701 if (details
.is_keyword_transition
) {
1702 // The visit is the result of the user entering a keyword, generate a
1703 // KEYWORD_GENERATED visit for the KEYWORD so that the keyword typed
1704 // count is boosted.
1705 AddTabToSearchVisit(**i
);
1708 client_
->SetKeywordSearchTermsForURL(
1709 details
.url
, (*i
)->id(), search_terms
);
1715 void TemplateURLService::AddTabToSearchVisit(const TemplateURL
& t_url
) {
1716 // Only add visits for entries the user hasn't modified. If the user modified
1717 // the entry the keyword may no longer correspond to the host name. It may be
1718 // possible to do something more sophisticated here, but it's so rare as to
1720 if (!t_url
.safe_for_autoreplace())
1727 url_fixer::FixupURL(base::UTF16ToUTF8(t_url
.keyword()), std::string()));
1728 if (!url
.is_valid())
1731 // Synthesize a visit for the keyword. This ensures the url for the keyword is
1732 // autocompleted even if the user doesn't type the url in directly.
1733 client_
->AddKeywordGeneratedVisit(url
);
1736 void TemplateURLService::RequestGoogleURLTrackerServerCheckIfNecessary() {
1737 if (default_search_provider_
&&
1738 default_search_provider_
->HasGoogleBaseURLs(search_terms_data()) &&
1739 google_url_tracker_
)
1740 google_url_tracker_
->RequestServerCheck(false);
1743 void TemplateURLService::GoogleBaseURLChanged() {
1747 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1748 bool something_changed
= false;
1749 for (TemplateURLVector::iterator
i(template_urls_
.begin());
1750 i
!= template_urls_
.end(); ++i
) {
1751 TemplateURL
* t_url
= *i
;
1752 if (t_url
->HasGoogleBaseURLs(search_terms_data())) {
1753 TemplateURL
updated_turl(t_url
->data());
1754 updated_turl
.ResetKeywordIfNecessary(search_terms_data(), false);
1755 KeywordToTemplateMap::const_iterator existing_entry
=
1756 keyword_to_template_map_
.find(updated_turl
.keyword());
1757 if ((existing_entry
!= keyword_to_template_map_
.end()) &&
1758 (existing_entry
->second
!= t_url
)) {
1759 // The new autogenerated keyword conflicts with another TemplateURL.
1760 // Overwrite it if it's replaceable; otherwise, leave |t_url| using its
1761 // current keyword. (This will not prevent |t_url| from auto-updating
1762 // the keyword in the future if the conflicting TemplateURL disappears.)
1763 // Note that we must still update |t_url| in this case, or the
1764 // |provider_map_| will not be updated correctly.
1765 if (CanReplace(existing_entry
->second
))
1766 RemoveNoNotify(existing_entry
->second
);
1768 updated_turl
.data_
.SetKeyword(t_url
->keyword());
1770 something_changed
= true;
1771 // This will send the keyword change to sync. Note that other clients
1772 // need to reset the keyword to an appropriate local value when this
1773 // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
1774 UpdateNoNotify(t_url
, updated_turl
);
1777 if (something_changed
)
1781 void TemplateURLService::OnDefaultSearchChange(
1782 const TemplateURLData
* data
,
1783 DefaultSearchManager::Source source
) {
1784 if (prefs_
&& (source
== DefaultSearchManager::FROM_USER
) &&
1785 ((source
!= default_search_provider_source_
) ||
1786 !IdenticalSyncGUIDs(data
, GetDefaultSearchProvider()))) {
1787 prefs_
->SetString(prefs::kSyncedDefaultSearchProviderGUID
, data
->sync_guid
);
1789 ApplyDefaultSearchChange(data
, source
);
1792 void TemplateURLService::ApplyDefaultSearchChange(
1793 const TemplateURLData
* data
,
1794 DefaultSearchManager::Source source
) {
1795 if (!ApplyDefaultSearchChangeNoMetrics(data
, source
))
1798 UMA_HISTOGRAM_ENUMERATION(
1799 "Search.DefaultSearchChangeOrigin", dsp_change_origin_
, DSP_CHANGE_MAX
);
1801 if (GetDefaultSearchProvider() &&
1802 GetDefaultSearchProvider()->HasGoogleBaseURLs(search_terms_data()) &&
1803 !dsp_change_callback_
.is_null())
1804 dsp_change_callback_
.Run();
1807 bool TemplateURLService::ApplyDefaultSearchChangeNoMetrics(
1808 const TemplateURLData
* data
,
1809 DefaultSearchManager::Source source
) {
1811 // Set |initial_default_search_provider_| from the preferences. This is
1812 // mainly so we can hold ownership until we get to the point where the list
1813 // of keywords from Web Data is the owner of everything including the
1815 bool changed
= TemplateURL::MatchesData(
1816 initial_default_search_provider_
.get(), data
, search_terms_data());
1817 initial_default_search_provider_
.reset(
1818 data
? new TemplateURL(*data
) : NULL
);
1819 default_search_provider_source_
= source
;
1823 // Prevent recursion if we update the value stored in default_search_manager_.
1824 // Note that we exclude the case of data == NULL because that could cause a
1825 // false positive for recursion when the initial_default_search_provider_ is
1826 // NULL due to policy. We'll never actually get recursion with data == NULL.
1827 if (source
== default_search_provider_source_
&& data
!= NULL
&&
1828 TemplateURL::MatchesData(default_search_provider_
, data
,
1829 search_terms_data()))
1832 // This may be deleted later. Use exclusively for pointer comparison to detect
1834 TemplateURL
* previous_default_search_engine
= default_search_provider_
;
1836 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1837 if (default_search_provider_source_
== DefaultSearchManager::FROM_POLICY
||
1838 source
== DefaultSearchManager::FROM_POLICY
) {
1839 // We do this both to remove any no-longer-applicable policy-defined DSE as
1840 // well as to add the new one, if appropriate.
1841 UpdateProvidersCreatedByPolicy(
1843 source
== DefaultSearchManager::FROM_POLICY
? data
: NULL
);
1847 default_search_provider_
= NULL
;
1848 } else if (source
== DefaultSearchManager::FROM_EXTENSION
) {
1849 default_search_provider_
= FindMatchingExtensionTemplateURL(
1850 *data
, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
);
1851 } else if (source
== DefaultSearchManager::FROM_FALLBACK
) {
1852 default_search_provider_
=
1853 FindPrepopulatedTemplateURL(data
->prepopulate_id
);
1854 if (default_search_provider_
) {
1855 TemplateURLData
update_data(*data
);
1856 update_data
.sync_guid
= default_search_provider_
->sync_guid();
1857 if (!default_search_provider_
->safe_for_autoreplace()) {
1858 update_data
.safe_for_autoreplace
= false;
1859 update_data
.SetKeyword(default_search_provider_
->keyword());
1860 update_data
.SetShortName(default_search_provider_
->short_name());
1862 UpdateNoNotify(default_search_provider_
, TemplateURL(update_data
));
1864 // Normally the prepopulated fallback should be present in
1865 // |template_urls_|, but in a few cases it might not be:
1866 // (1) Tests that initialize the TemplateURLService in peculiar ways.
1867 // (2) If the user deleted the pre-populated default and we subsequently
1868 // lost their user-selected value.
1869 TemplateURL
* new_dse
= new TemplateURL(*data
);
1870 if (AddNoNotify(new_dse
, true))
1871 default_search_provider_
= new_dse
;
1873 } else if (source
== DefaultSearchManager::FROM_USER
) {
1874 default_search_provider_
= GetTemplateURLForGUID(data
->sync_guid
);
1875 if (!default_search_provider_
&& data
->prepopulate_id
) {
1876 default_search_provider_
=
1877 FindPrepopulatedTemplateURL(data
->prepopulate_id
);
1879 TemplateURLData
new_data(*data
);
1880 new_data
.show_in_default_list
= true;
1881 if (default_search_provider_
) {
1882 UpdateNoNotify(default_search_provider_
, TemplateURL(new_data
));
1884 new_data
.id
= kInvalidTemplateURLID
;
1885 TemplateURL
* new_dse
= new TemplateURL(new_data
);
1886 if (AddNoNotify(new_dse
, true))
1887 default_search_provider_
= new_dse
;
1889 if (default_search_provider_
&& prefs_
) {
1890 prefs_
->SetString(prefs::kSyncedDefaultSearchProviderGUID
,
1891 default_search_provider_
->sync_guid());
1896 default_search_provider_source_
= source
;
1898 bool changed
= default_search_provider_
!= previous_default_search_engine
;
1900 RequestGoogleURLTrackerServerCheckIfNecessary();
1907 bool TemplateURLService::AddNoNotify(TemplateURL
* template_url
,
1908 bool newly_adding
) {
1909 DCHECK(template_url
);
1912 DCHECK_EQ(kInvalidTemplateURLID
, template_url
->id());
1913 DCHECK(std::find(template_urls_
.begin(), template_urls_
.end(),
1914 template_url
) == template_urls_
.end());
1915 template_url
->data_
.id
= ++next_id_
;
1918 template_url
->ResetKeywordIfNecessary(search_terms_data(), false);
1919 // Check whether |template_url|'s keyword conflicts with any already in the
1921 TemplateURL
* existing_keyword_turl
=
1922 GetTemplateURLForKeyword(template_url
->keyword());
1924 // Check whether |template_url|'s keyword conflicts with any already in the
1925 // model. Note that we can reach here during the loading phase while
1926 // processing the template URLs from the web data service. In this case,
1927 // GetTemplateURLForKeyword() will look not only at what's already in the
1928 // model, but at the |initial_default_search_provider_|. Since this engine
1929 // will presumably also be present in the web data, we need to double-check
1930 // that any "pre-existing" entries we find are actually coming from
1931 // |template_urls_|, lest we detect a "conflict" between the
1932 // |initial_default_search_provider_| and the web data version of itself.
1933 if (template_url
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
&&
1934 existing_keyword_turl
&&
1935 existing_keyword_turl
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
&&
1936 (std::find(template_urls_
.begin(), template_urls_
.end(),
1937 existing_keyword_turl
) != template_urls_
.end())) {
1938 DCHECK_NE(existing_keyword_turl
, template_url
);
1939 // Only replace one of the TemplateURLs if they are either both extensions,
1940 // or both not extensions.
1941 bool are_same_type
= existing_keyword_turl
->GetType() ==
1942 template_url
->GetType();
1943 if (CanReplace(existing_keyword_turl
) && are_same_type
) {
1944 RemoveNoNotify(existing_keyword_turl
);
1945 } else if (CanReplace(template_url
) && are_same_type
) {
1946 delete template_url
;
1949 base::string16 new_keyword
=
1950 UniquifyKeyword(*existing_keyword_turl
, false);
1951 ResetTemplateURLNoNotify(existing_keyword_turl
,
1952 existing_keyword_turl
->short_name(), new_keyword
,
1953 existing_keyword_turl
->url());
1956 template_urls_
.push_back(template_url
);
1957 AddToMaps(template_url
);
1960 (template_url
->GetType() == TemplateURL::NORMAL
)) {
1961 if (web_data_service_
.get())
1962 web_data_service_
->AddKeyword(template_url
->data());
1964 // Inform sync of the addition. Note that this will assign a GUID to
1965 // template_url and add it to the guid_to_template_map_.
1966 ProcessTemplateURLChange(FROM_HERE
,
1968 syncer::SyncChange::ACTION_ADD
);
1974 void TemplateURLService::RemoveNoNotify(TemplateURL
* template_url
) {
1975 DCHECK(template_url
!= default_search_provider_
);
1977 TemplateURLVector::iterator i
=
1978 std::find(template_urls_
.begin(), template_urls_
.end(), template_url
);
1979 if (i
== template_urls_
.end())
1982 RemoveFromMaps(template_url
);
1984 // Remove it from the vector containing all TemplateURLs.
1985 template_urls_
.erase(i
);
1987 if (template_url
->GetType() == TemplateURL::NORMAL
) {
1988 if (web_data_service_
.get())
1989 web_data_service_
->RemoveKeyword(template_url
->id());
1991 // Inform sync of the deletion.
1992 ProcessTemplateURLChange(FROM_HERE
,
1994 syncer::SyncChange::ACTION_DELETE
);
1996 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1997 DELETE_ENGINE_USER_ACTION
, DELETE_ENGINE_MAX
);
2000 if (loaded_
&& client_
)
2001 client_
->DeleteAllSearchTermsForKeyword(template_url
->id());
2003 // We own the TemplateURL and need to delete it.
2004 delete template_url
;
2007 bool TemplateURLService::ResetTemplateURLNoNotify(
2009 const base::string16
& title
,
2010 const base::string16
& keyword
,
2011 const std::string
& search_url
) {
2012 DCHECK(!keyword
.empty());
2013 DCHECK(!search_url
.empty());
2014 TemplateURLData
data(url
->data());
2015 data
.SetShortName(title
);
2016 data
.SetKeyword(keyword
);
2017 if (search_url
!= data
.url()) {
2018 data
.SetURL(search_url
);
2019 // The urls have changed, reset the favicon url.
2020 data
.favicon_url
= GURL();
2022 data
.safe_for_autoreplace
= false;
2023 data
.last_modified
= clock_
->Now();
2024 return UpdateNoNotify(url
, TemplateURL(data
));
2027 void TemplateURLService::NotifyObservers() {
2031 FOR_EACH_OBSERVER(TemplateURLServiceObserver
, model_observers_
,
2032 OnTemplateURLServiceChanged());
2035 // |template_urls| are the TemplateURLs loaded from the database.
2036 // |default_from_prefs| is the default search provider from the preferences, or
2037 // NULL if the DSE is not policy-defined.
2039 // This function removes from the vector and the database all the TemplateURLs
2040 // that were set by policy, unless it is the current default search provider, in
2041 // which case it is updated with the data from prefs.
2042 void TemplateURLService::UpdateProvidersCreatedByPolicy(
2043 TemplateURLVector
* template_urls
,
2044 const TemplateURLData
* default_from_prefs
) {
2045 DCHECK(template_urls
);
2047 for (TemplateURLVector::iterator i
= template_urls
->begin();
2048 i
!= template_urls
->end(); ) {
2049 TemplateURL
* template_url
= *i
;
2050 if (template_url
->created_by_policy()) {
2051 if (default_from_prefs
&&
2052 TemplateURL::MatchesData(template_url
, default_from_prefs
,
2053 search_terms_data())) {
2054 // If the database specified a default search provider that was set
2055 // by policy, and the default search provider from the preferences
2056 // is also set by policy and they are the same, keep the entry in the
2057 // database and the |default_search_provider|.
2058 default_search_provider_
= template_url
;
2059 // Prevent us from saving any other entries, or creating a new one.
2060 default_from_prefs
= NULL
;
2065 RemoveFromMaps(template_url
);
2066 i
= template_urls
->erase(i
);
2067 if (web_data_service_
.get())
2068 web_data_service_
->RemoveKeyword(template_url
->id());
2069 delete template_url
;
2075 if (default_from_prefs
) {
2076 default_search_provider_
= NULL
;
2077 default_search_provider_source_
= DefaultSearchManager::FROM_POLICY
;
2078 TemplateURLData
new_data(*default_from_prefs
);
2079 if (new_data
.sync_guid
.empty())
2080 new_data
.sync_guid
= base::GenerateGUID();
2081 new_data
.created_by_policy
= true;
2082 TemplateURL
* new_dse
= new TemplateURL(new_data
);
2083 if (AddNoNotify(new_dse
, true))
2084 default_search_provider_
= new_dse
;
2088 void TemplateURLService::ResetTemplateURLGUID(TemplateURL
* url
,
2089 const std::string
& guid
) {
2091 DCHECK(!guid
.empty());
2093 TemplateURLData
data(url
->data());
2094 data
.sync_guid
= guid
;
2095 UpdateNoNotify(url
, TemplateURL(data
));
2098 base::string16
TemplateURLService::UniquifyKeyword(const TemplateURL
& turl
,
2102 if (!GetTemplateURLForKeyword(turl
.keyword()))
2103 return turl
.keyword();
2105 // First, try to return the generated keyword for the TemplateURL (except
2106 // for extensions, as their keywords are not associated with their URLs).
2107 GURL
gurl(turl
.url());
2108 if (gurl
.is_valid() &&
2109 (turl
.GetType() != TemplateURL::OMNIBOX_API_EXTENSION
)) {
2110 base::string16 keyword_candidate
= TemplateURL::GenerateKeyword(gurl
);
2111 if (!GetTemplateURLForKeyword(keyword_candidate
))
2112 return keyword_candidate
;
2116 // We try to uniquify the keyword by appending a special character to the end.
2117 // This is a best-effort approach where we try to preserve the original
2118 // keyword and let the user do what they will after our attempt.
2119 base::string16
keyword_candidate(turl
.keyword());
2121 keyword_candidate
.append(base::ASCIIToUTF16("_"));
2122 } while (GetTemplateURLForKeyword(keyword_candidate
));
2124 return keyword_candidate
;
2127 bool TemplateURLService::IsLocalTemplateURLBetter(
2128 const TemplateURL
* local_turl
,
2129 const TemplateURL
* sync_turl
) {
2130 DCHECK(GetTemplateURLForGUID(local_turl
->sync_guid()));
2131 return local_turl
->last_modified() > sync_turl
->last_modified() ||
2132 local_turl
->created_by_policy() ||
2133 local_turl
== GetDefaultSearchProvider();
2136 void TemplateURLService::ResolveSyncKeywordConflict(
2137 TemplateURL
* unapplied_sync_turl
,
2138 TemplateURL
* applied_sync_turl
,
2139 syncer::SyncChangeList
* change_list
) {
2141 DCHECK(unapplied_sync_turl
);
2142 DCHECK(applied_sync_turl
);
2143 DCHECK(change_list
);
2144 DCHECK_EQ(applied_sync_turl
->keyword(), unapplied_sync_turl
->keyword());
2145 DCHECK_EQ(TemplateURL::NORMAL
, applied_sync_turl
->GetType());
2147 // Both |unapplied_sync_turl| and |applied_sync_turl| are known to Sync, so
2148 // don't delete either of them. Instead, determine which is "better" and
2149 // uniquify the other one, sending an update to the server for the updated
2151 const bool applied_turl_is_better
=
2152 IsLocalTemplateURLBetter(applied_sync_turl
, unapplied_sync_turl
);
2153 TemplateURL
* loser
= applied_turl_is_better
?
2154 unapplied_sync_turl
: applied_sync_turl
;
2155 base::string16 new_keyword
= UniquifyKeyword(*loser
, false);
2156 DCHECK(!GetTemplateURLForKeyword(new_keyword
));
2157 if (applied_turl_is_better
) {
2158 // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2159 // for adding or updating unapplied_sync_turl in the local model.
2160 unapplied_sync_turl
->data_
.SetKeyword(new_keyword
);
2162 // Update |applied_sync_turl| in the local model with the new keyword.
2163 TemplateURLData
data(applied_sync_turl
->data());
2164 data
.SetKeyword(new_keyword
);
2165 if (UpdateNoNotify(applied_sync_turl
, TemplateURL(data
)))
2168 // The losing TemplateURL should have their keyword updated. Send a change to
2169 // the server to reflect this change.
2170 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*loser
);
2171 change_list
->push_back(syncer::SyncChange(FROM_HERE
,
2172 syncer::SyncChange::ACTION_UPDATE
,
2176 void TemplateURLService::MergeInSyncTemplateURL(
2177 TemplateURL
* sync_turl
,
2178 const SyncDataMap
& sync_data
,
2179 syncer::SyncChangeList
* change_list
,
2180 SyncDataMap
* local_data
,
2181 syncer::SyncMergeResult
* merge_result
) {
2183 DCHECK(!GetTemplateURLForGUID(sync_turl
->sync_guid()));
2184 DCHECK(IsFromSync(sync_turl
, sync_data
));
2186 TemplateURL
* conflicting_turl
=
2187 FindNonExtensionTemplateURLForKeyword(sync_turl
->keyword());
2188 bool should_add_sync_turl
= true;
2190 // If there was no TemplateURL in the local model that conflicts with
2191 // |sync_turl|, skip the following preparation steps and just add |sync_turl|
2192 // directly. Otherwise, modify |conflicting_turl| to make room for
2194 if (conflicting_turl
) {
2195 if (IsFromSync(conflicting_turl
, sync_data
)) {
2196 // |conflicting_turl| is already known to Sync, so we're not allowed to
2197 // remove it. In this case, we want to uniquify the worse one and send an
2198 // update for the changed keyword to sync. We can reuse the logic from
2199 // ResolveSyncKeywordConflict for this.
2200 ResolveSyncKeywordConflict(sync_turl
, conflicting_turl
, change_list
);
2201 merge_result
->set_num_items_modified(
2202 merge_result
->num_items_modified() + 1);
2204 // |conflicting_turl| is not yet known to Sync. If it is better, then we
2205 // want to transfer its values up to sync. Otherwise, we remove it and
2206 // allow the entry from Sync to overtake it in the model.
2207 const std::string guid
= conflicting_turl
->sync_guid();
2208 if (IsLocalTemplateURLBetter(conflicting_turl
, sync_turl
)) {
2209 ResetTemplateURLGUID(conflicting_turl
, sync_turl
->sync_guid());
2210 syncer::SyncData sync_data
=
2211 CreateSyncDataFromTemplateURL(*conflicting_turl
);
2212 change_list
->push_back(syncer::SyncChange(
2213 FROM_HERE
, syncer::SyncChange::ACTION_UPDATE
, sync_data
));
2214 // Note that in this case we do not add the Sync TemplateURL to the
2215 // local model, since we've effectively "merged" it in by updating the
2216 // local conflicting entry with its sync_guid.
2217 should_add_sync_turl
= false;
2218 merge_result
->set_num_items_modified(
2219 merge_result
->num_items_modified() + 1);
2221 // We guarantee that this isn't the local search provider. Otherwise,
2222 // local would have won.
2223 DCHECK(conflicting_turl
!= GetDefaultSearchProvider());
2224 Remove(conflicting_turl
);
2225 merge_result
->set_num_items_deleted(
2226 merge_result
->num_items_deleted() + 1);
2228 // This TemplateURL was either removed or overwritten in the local model.
2229 // Remove the entry from the local data so it isn't pushed up to Sync.
2230 local_data
->erase(guid
);
2234 if (should_add_sync_turl
) {
2235 // Force the local ID to kInvalidTemplateURLID so we can add it.
2236 TemplateURLData
data(sync_turl
->data());
2237 data
.id
= kInvalidTemplateURLID
;
2238 TemplateURL
* added
= new TemplateURL(data
);
2239 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2240 &dsp_change_origin_
, DSP_CHANGE_SYNC_ADD
);
2242 MaybeUpdateDSEAfterSync(added
);
2243 merge_result
->set_num_items_added(
2244 merge_result
->num_items_added() + 1);
2248 void TemplateURLService::PatchMissingSyncGUIDs(
2249 TemplateURLVector
* template_urls
) {
2250 DCHECK(template_urls
);
2251 for (TemplateURLVector::iterator i
= template_urls
->begin();
2252 i
!= template_urls
->end(); ++i
) {
2253 TemplateURL
* template_url
= *i
;
2254 DCHECK(template_url
);
2255 if (template_url
->sync_guid().empty() &&
2256 (template_url
->GetType() == TemplateURL::NORMAL
)) {
2257 template_url
->data_
.sync_guid
= base::GenerateGUID();
2258 if (web_data_service_
.get())
2259 web_data_service_
->UpdateKeyword(template_url
->data());
2264 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
2265 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2266 &dsp_change_origin_
, DSP_CHANGE_SYNC_PREF
);
2268 std::string new_guid
=
2269 prefs_
->GetString(prefs::kSyncedDefaultSearchProviderGUID
);
2270 if (new_guid
.empty()) {
2271 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
2275 TemplateURL
* turl
= GetTemplateURLForGUID(new_guid
);
2277 default_search_manager_
.SetUserSelectedDefaultSearchEngine(turl
->data());
2280 TemplateURL
* TemplateURLService::FindPrepopulatedTemplateURL(
2281 int prepopulated_id
) {
2282 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2283 i
!= template_urls_
.end(); ++i
) {
2284 if ((*i
)->prepopulate_id() == prepopulated_id
)
2290 TemplateURL
* TemplateURLService::FindTemplateURLForExtension(
2291 const std::string
& extension_id
,
2292 TemplateURL::Type type
) {
2293 DCHECK_NE(TemplateURL::NORMAL
, type
);
2294 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2295 i
!= template_urls_
.end(); ++i
) {
2296 if ((*i
)->GetType() == type
&&
2297 (*i
)->GetExtensionId() == extension_id
)
2303 TemplateURL
* TemplateURLService::FindMatchingExtensionTemplateURL(
2304 const TemplateURLData
& data
,
2305 TemplateURL::Type type
) {
2306 DCHECK_NE(TemplateURL::NORMAL
, type
);
2307 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2308 i
!= template_urls_
.end(); ++i
) {
2309 if ((*i
)->GetType() == type
&&
2310 TemplateURL::MatchesData(*i
, &data
, search_terms_data()))
2316 void TemplateURLService::UpdateExtensionDefaultSearchEngine() {
2317 TemplateURL
* most_recently_intalled_default
= NULL
;
2318 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2319 i
!= template_urls_
.end(); ++i
) {
2320 if (((*i
)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
) &&
2321 (*i
)->extension_info_
->wants_to_be_default_engine
&&
2322 (*i
)->SupportsReplacement(search_terms_data()) &&
2323 (!most_recently_intalled_default
||
2324 (most_recently_intalled_default
->extension_info_
->install_time
<
2325 (*i
)->extension_info_
->install_time
)))
2326 most_recently_intalled_default
= *i
;
2329 if (most_recently_intalled_default
) {
2330 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2331 &dsp_change_origin_
, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION
);
2332 default_search_manager_
.SetExtensionControlledDefaultSearchEngine(
2333 most_recently_intalled_default
->data());
2335 default_search_manager_
.ClearExtensionControlledDefaultSearchEngine();