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.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/rappor/rappor_service.h"
26 #include "components/search_engines/search_engines_pref_names.h"
27 #include "components/search_engines/search_host_to_urls_map.h"
28 #include "components/search_engines/search_terms_data.h"
29 #include "components/search_engines/template_url.h"
30 #include "components/search_engines/template_url_prepopulate_data.h"
31 #include "components/search_engines/template_url_service_client.h"
32 #include "components/search_engines/template_url_service_observer.h"
33 #include "components/search_engines/util.h"
34 #include "components/url_fixer/url_fixer.h"
35 #include "net/base/net_util.h"
36 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
37 #include "sync/api/sync_change.h"
38 #include "sync/api/sync_error_factory.h"
39 #include "sync/protocol/search_engine_specifics.pb.h"
40 #include "sync/protocol/sync.pb.h"
43 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet
;
44 typedef TemplateURLService::SyncDataMap SyncDataMap
;
48 bool IdenticalSyncGUIDs(const TemplateURLData
* data
, const TemplateURL
* turl
) {
50 return !data
&& !turl
;
52 return data
->sync_guid
== turl
->sync_guid();
55 const char kDeleteSyncedEngineHistogramName
[] =
56 "Search.DeleteSyncedSearchEngine";
58 // Values for an enumerated histogram used to track whenever an ACTION_DELETE is
59 // sent to the server for search engines.
60 enum DeleteSyncedSearchEngineEvent
{
61 DELETE_ENGINE_USER_ACTION
,
62 DELETE_ENGINE_PRE_SYNC
,
63 DELETE_ENGINE_EMPTY_FIELD
,
67 // Returns true iff the change in |change_list| at index |i| should not be sent
68 // up to the server based on its GUIDs presence in |sync_data| or when compared
69 // to changes after it in |change_list|.
71 // 1) It is an ACTION_UPDATE or ACTION_DELETE and the sync_guid associated
72 // with it is NOT found in |sync_data|. We can only update and remove
73 // entries that were originally from the Sync server.
74 // 2) It is an ACTION_ADD and the sync_guid associated with it is found in
75 // |sync_data|. We cannot re-add entries that Sync already knew about.
76 // 3) There is an update after an update for the same GUID. We prune earlier
77 // ones just to save bandwidth (Sync would normally coalesce them).
78 bool ShouldRemoveSyncChange(size_t index
,
79 syncer::SyncChangeList
* change_list
,
80 const SyncDataMap
* sync_data
) {
81 DCHECK(index
< change_list
->size());
82 const syncer::SyncChange
& change_i
= (*change_list
)[index
];
83 const std::string guid
= change_i
.sync_data().GetSpecifics()
84 .search_engine().sync_guid();
85 syncer::SyncChange::SyncChangeType type
= change_i
.change_type();
86 if ((type
== syncer::SyncChange::ACTION_UPDATE
||
87 type
== syncer::SyncChange::ACTION_DELETE
) &&
88 sync_data
->find(guid
) == sync_data
->end())
90 if (type
== syncer::SyncChange::ACTION_ADD
&&
91 sync_data
->find(guid
) != sync_data
->end())
93 if (type
== syncer::SyncChange::ACTION_UPDATE
) {
94 for (size_t j
= index
+ 1; j
< change_list
->size(); j
++) {
95 const syncer::SyncChange
& change_j
= (*change_list
)[j
];
96 if ((syncer::SyncChange::ACTION_UPDATE
== change_j
.change_type()) &&
97 (change_j
.sync_data().GetSpecifics().search_engine().sync_guid() ==
105 // Remove SyncChanges that should not be sent to the server from |change_list|.
106 // This is done to eliminate incorrect SyncChanges added by the merge and
107 // conflict resolution logic when it is unsure of whether or not an entry is new
108 // from Sync or originally from the local model. This also removes changes that
109 // would be otherwise be coalesced by Sync in order to save bandwidth.
110 void PruneSyncChanges(const SyncDataMap
* sync_data
,
111 syncer::SyncChangeList
* change_list
) {
112 for (size_t i
= 0; i
< change_list
->size(); ) {
113 if (ShouldRemoveSyncChange(i
, change_list
, sync_data
))
114 change_list
->erase(change_list
->begin() + i
);
120 // Returns true if |turl|'s GUID is not found inside |sync_data|. This is to be
121 // used in MergeDataAndStartSyncing to differentiate between TemplateURLs from
122 // Sync and TemplateURLs that were initially local, assuming |sync_data| is the
123 // |initial_sync_data| parameter.
124 bool IsFromSync(const TemplateURL
* turl
, const SyncDataMap
& sync_data
) {
125 return !!sync_data
.count(turl
->sync_guid());
128 // Log the number of instances of a keyword that exist, with zero or more
129 // underscores, which could occur as the result of conflict resolution.
130 void LogDuplicatesHistogram(
131 const TemplateURLService::TemplateURLVector
& template_urls
) {
132 std::map
<std::string
, int> duplicates
;
133 for (TemplateURLService::TemplateURLVector::const_iterator it
=
134 template_urls
.begin(); it
!= template_urls
.end(); ++it
) {
135 std::string keyword
= base::UTF16ToASCII((*it
)->keyword());
136 base::TrimString(keyword
, "_", &keyword
);
137 duplicates
[keyword
]++;
140 // Count the keywords with duplicates.
142 for (std::map
<std::string
, int>::const_iterator it
= duplicates
.begin();
143 it
!= duplicates
.end(); ++it
) {
148 UMA_HISTOGRAM_COUNTS_100("Search.SearchEngineDuplicateCounts", num_dupes
);
154 // TemplateURLService::LessWithPrefix -----------------------------------------
156 class TemplateURLService::LessWithPrefix
{
158 // We want to find the set of keywords that begin with a prefix. The STL
159 // algorithms will return the set of elements that are "equal to" the
160 // prefix, where "equal(x, y)" means "!(cmp(x, y) || cmp(y, x))". When
161 // cmp() is the typical std::less<>, this results in lexicographic equality;
162 // we need to extend this to mark a prefix as "not less than" a keyword it
163 // begins, which will cause the desired elements to be considered "equal to"
164 // the prefix. Note: this is still a strict weak ordering, as required by
165 // equal_range() (though I will not prove that here).
167 // Unfortunately the calling convention is not "prefix and element" but
168 // rather "two elements", so we pass the prefix as a fake "element" which has
169 // a NULL KeywordDataElement pointer.
170 bool operator()(const KeywordToTemplateMap::value_type
& elem1
,
171 const KeywordToTemplateMap::value_type
& elem2
) const {
172 return (elem1
.second
== NULL
) ?
173 (elem2
.first
.compare(0, elem1
.first
.length(), elem1
.first
) > 0) :
174 (elem1
.first
< elem2
.first
);
179 // TemplateURLService ---------------------------------------------------------
181 TemplateURLService::TemplateURLService(
183 scoped_ptr
<SearchTermsData
> search_terms_data
,
184 const scoped_refptr
<KeywordWebDataService
>& web_data_service
,
185 scoped_ptr
<TemplateURLServiceClient
> client
,
186 GoogleURLTracker
* google_url_tracker
,
187 rappor::RapporService
* rappor_service
,
188 const base::Closure
& dsp_change_callback
)
190 search_terms_data_(search_terms_data
.Pass()),
191 web_data_service_(web_data_service
),
192 client_(client
.Pass()),
193 google_url_tracker_(google_url_tracker
),
194 rappor_service_(rappor_service
),
195 dsp_change_callback_(dsp_change_callback
),
196 provider_map_(new SearchHostToURLsMap
),
200 default_search_provider_(NULL
),
201 next_id_(kInvalidTemplateURLID
+ 1),
202 clock_(new base::DefaultClock
),
203 models_associated_(false),
204 processing_syncer_changes_(false),
205 dsp_change_origin_(DSP_CHANGE_OTHER
),
206 default_search_manager_(
208 base::Bind(&TemplateURLService::OnDefaultSearchChange
,
209 base::Unretained(this))) {
210 DCHECK(search_terms_data_
);
214 TemplateURLService::TemplateURLService(const Initializer
* initializers
,
217 search_terms_data_(new SearchTermsData
),
218 web_data_service_(NULL
),
219 google_url_tracker_(NULL
),
220 rappor_service_(NULL
),
221 provider_map_(new SearchHostToURLsMap
),
225 default_search_provider_(NULL
),
226 next_id_(kInvalidTemplateURLID
+ 1),
227 clock_(new base::DefaultClock
),
228 models_associated_(false),
229 processing_syncer_changes_(false),
230 dsp_change_origin_(DSP_CHANGE_OTHER
),
231 default_search_manager_(
233 base::Bind(&TemplateURLService::OnDefaultSearchChange
,
234 base::Unretained(this))) {
235 Init(initializers
, count
);
238 TemplateURLService::~TemplateURLService() {
239 // |web_data_service_| should be deleted during Shutdown().
240 DCHECK(!web_data_service_
.get());
241 STLDeleteElements(&template_urls_
);
245 base::string16
TemplateURLService::CleanUserInputKeyword(
246 const base::string16
& keyword
) {
247 // Remove the scheme.
248 base::string16
result(base::i18n::ToLower(keyword
));
249 base::TrimWhitespace(result
, base::TRIM_ALL
, &result
);
250 url::Component scheme_component
;
251 if (url::ExtractScheme(base::UTF16ToUTF8(keyword
).c_str(),
252 static_cast<int>(keyword
.length()),
253 &scheme_component
)) {
254 // If the scheme isn't "http" or "https", bail. The user isn't trying to
255 // type a web address, but rather an FTP, file:, or other scheme URL, or a
256 // search query with some sort of initial operator (e.g. "site:").
257 if (result
.compare(0, scheme_component
.end(),
258 base::ASCIIToUTF16(url::kHttpScheme
)) &&
259 result
.compare(0, scheme_component
.end(),
260 base::ASCIIToUTF16(url::kHttpsScheme
)))
261 return base::string16();
263 // Include trailing ':'.
264 result
.erase(0, scheme_component
.end() + 1);
265 // Many schemes usually have "//" after them, so strip it too.
266 const base::string16
after_scheme(base::ASCIIToUTF16("//"));
267 if (result
.compare(0, after_scheme
.length(), after_scheme
) == 0)
268 result
.erase(0, after_scheme
.length());
271 // Remove leading "www.".
272 result
= net::StripWWW(result
);
274 // Remove trailing "/".
275 return (result
.length() > 0 && result
[result
.length() - 1] == '/') ?
276 result
.substr(0, result
.length() - 1) : result
;
279 bool TemplateURLService::CanReplaceKeyword(
280 const base::string16
& keyword
,
282 TemplateURL
** template_url_to_replace
) {
283 DCHECK(!keyword
.empty()); // This should only be called for non-empty
284 // keywords. If we need to support empty kewords
285 // the code needs to change slightly.
286 TemplateURL
* existing_url
= GetTemplateURLForKeyword(keyword
);
287 if (template_url_to_replace
)
288 *template_url_to_replace
= existing_url
;
290 // We already have a TemplateURL for this keyword. Only allow it to be
291 // replaced if the TemplateURL can be replaced.
292 return CanReplace(existing_url
);
295 // We don't have a TemplateURL with keyword. Only allow a new one if there
296 // isn't a TemplateURL for the specified host, or there is one but it can
297 // be replaced. We do this to ensure that if the user assigns a different
298 // keyword to a generated TemplateURL, we won't regenerate another keyword for
300 return !url
.is_valid() || url
.host().empty() ||
301 CanReplaceKeywordForHost(url
.host(), template_url_to_replace
);
304 void TemplateURLService::FindMatchingKeywords(
305 const base::string16
& prefix
,
306 bool support_replacement_only
,
307 TemplateURLVector
* matches
) {
308 // Sanity check args.
311 DCHECK(matches
!= NULL
);
312 DCHECK(matches
->empty()); // The code for exact matches assumes this.
314 // Required for VS2010: http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
315 TemplateURL
* const kNullTemplateURL
= NULL
;
317 // Find matching keyword range. Searches the element map for keywords
318 // beginning with |prefix| and stores the endpoints of the resulting set in
320 const std::pair
<KeywordToTemplateMap::const_iterator
,
321 KeywordToTemplateMap::const_iterator
> match_range(
323 keyword_to_template_map_
.begin(), keyword_to_template_map_
.end(),
324 KeywordToTemplateMap::value_type(prefix
, kNullTemplateURL
),
327 // Return vector of matching keywords.
328 for (KeywordToTemplateMap::const_iterator
i(match_range
.first
);
329 i
!= match_range
.second
; ++i
) {
330 if (!support_replacement_only
||
331 i
->second
->url_ref().SupportsReplacement(search_terms_data()))
332 matches
->push_back(i
->second
);
336 TemplateURL
* TemplateURLService::GetTemplateURLForKeyword(
337 const base::string16
& keyword
) {
338 KeywordToTemplateMap::const_iterator
elem(
339 keyword_to_template_map_
.find(keyword
));
340 if (elem
!= keyword_to_template_map_
.end())
343 initial_default_search_provider_
.get() &&
344 (initial_default_search_provider_
->keyword() == keyword
)) ?
345 initial_default_search_provider_
.get() : NULL
;
348 TemplateURL
* TemplateURLService::GetTemplateURLForGUID(
349 const std::string
& sync_guid
) {
350 GUIDToTemplateMap::const_iterator
elem(guid_to_template_map_
.find(sync_guid
));
351 if (elem
!= guid_to_template_map_
.end())
354 initial_default_search_provider_
.get() &&
355 (initial_default_search_provider_
->sync_guid() == sync_guid
)) ?
356 initial_default_search_provider_
.get() : NULL
;
359 TemplateURL
* TemplateURLService::GetTemplateURLForHost(
360 const std::string
& host
) {
362 return provider_map_
->GetTemplateURLForHost(host
);
363 TemplateURL
* initial_dsp
= initial_default_search_provider_
.get();
366 return (initial_dsp
->GenerateSearchURL(search_terms_data()).host() == host
) ?
370 bool TemplateURLService::Add(TemplateURL
* template_url
) {
371 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
372 if (!AddNoNotify(template_url
, true))
378 void TemplateURLService::AddWithOverrides(TemplateURL
* template_url
,
379 const base::string16
& short_name
,
380 const base::string16
& keyword
,
381 const std::string
& url
) {
382 DCHECK(!keyword
.empty());
383 DCHECK(!url
.empty());
384 template_url
->data_
.short_name
= short_name
;
385 template_url
->data_
.SetKeyword(keyword
);
386 template_url
->SetURL(url
);
390 void TemplateURLService::AddExtensionControlledTURL(
391 TemplateURL
* template_url
,
392 scoped_ptr
<TemplateURL::AssociatedExtensionInfo
> info
) {
394 DCHECK(template_url
);
395 DCHECK_EQ(kInvalidTemplateURLID
, template_url
->id());
397 DCHECK_NE(TemplateURL::NORMAL
, info
->type
);
398 DCHECK_EQ(info
->wants_to_be_default_engine
,
399 template_url
->show_in_default_list());
400 DCHECK(!FindTemplateURLForExtension(info
->extension_id
, info
->type
));
401 template_url
->extension_info_
.swap(info
);
403 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
404 if (AddNoNotify(template_url
, true)) {
405 if (template_url
->extension_info_
->wants_to_be_default_engine
)
406 UpdateExtensionDefaultSearchEngine();
411 void TemplateURLService::Remove(TemplateURL
* template_url
) {
412 RemoveNoNotify(template_url
);
416 void TemplateURLService::RemoveExtensionControlledTURL(
417 const std::string
& extension_id
,
418 TemplateURL::Type type
) {
420 TemplateURL
* url
= FindTemplateURLForExtension(extension_id
, type
);
423 // NULL this out so that we can call RemoveNoNotify.
424 // UpdateExtensionDefaultSearchEngine will cause it to be reset.
425 if (default_search_provider_
== url
)
426 default_search_provider_
= NULL
;
427 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
429 UpdateExtensionDefaultSearchEngine();
433 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after
) {
434 RemoveAutoGeneratedBetween(created_after
, base::Time());
437 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after
,
438 base::Time created_before
) {
439 RemoveAutoGeneratedForOriginBetween(GURL(), created_after
, created_before
);
442 void TemplateURLService::RemoveAutoGeneratedForOriginBetween(
444 base::Time created_after
,
445 base::Time created_before
) {
446 GURL
o(origin
.GetOrigin());
447 bool should_notify
= false;
448 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
449 for (size_t i
= 0; i
< template_urls_
.size();) {
450 if (template_urls_
[i
]->date_created() >= created_after
&&
451 (created_before
.is_null() ||
452 template_urls_
[i
]->date_created() < created_before
) &&
453 CanReplace(template_urls_
[i
]) &&
455 template_urls_
[i
]->GenerateSearchURL(
456 search_terms_data()).GetOrigin() == o
)) {
457 RemoveNoNotify(template_urls_
[i
]);
458 should_notify
= true;
467 void TemplateURLService::RegisterOmniboxKeyword(
468 const std::string
& extension_id
,
469 const std::string
& extension_name
,
470 const std::string
& keyword
,
471 const std::string
& template_url_string
) {
474 if (FindTemplateURLForExtension(extension_id
,
475 TemplateURL::OMNIBOX_API_EXTENSION
))
478 TemplateURLData data
;
479 data
.short_name
= base::UTF8ToUTF16(extension_name
);
480 data
.SetKeyword(base::UTF8ToUTF16(keyword
));
481 data
.SetURL(template_url_string
);
482 TemplateURL
* url
= new TemplateURL(data
);
483 scoped_ptr
<TemplateURL::AssociatedExtensionInfo
> info(
484 new TemplateURL::AssociatedExtensionInfo(
485 TemplateURL::OMNIBOX_API_EXTENSION
, extension_id
));
486 AddExtensionControlledTURL(url
, info
.Pass());
489 TemplateURLService::TemplateURLVector
TemplateURLService::GetTemplateURLs() {
490 return template_urls_
;
493 void TemplateURLService::IncrementUsageCount(TemplateURL
* url
) {
495 // Extension-controlled search engines are not persisted.
496 if (url
->GetType() != TemplateURL::NORMAL
)
498 if (std::find(template_urls_
.begin(), template_urls_
.end(), url
) ==
499 template_urls_
.end())
501 ++url
->data_
.usage_count
;
503 if (web_data_service_
.get())
504 web_data_service_
->UpdateKeyword(url
->data());
507 void TemplateURLService::ResetTemplateURL(TemplateURL
* url
,
508 const base::string16
& title
,
509 const base::string16
& keyword
,
510 const std::string
& search_url
) {
511 if (ResetTemplateURLNoNotify(url
, title
, keyword
, search_url
))
515 bool TemplateURLService::CanMakeDefault(const TemplateURL
* url
) {
517 ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
518 (default_search_provider_source_
==
519 DefaultSearchManager::FROM_FALLBACK
)) &&
520 (url
!= GetDefaultSearchProvider()) &&
521 url
->url_ref().SupportsReplacement(search_terms_data()) &&
522 (url
->GetType() == TemplateURL::NORMAL
);
525 void TemplateURLService::SetUserSelectedDefaultSearchProvider(
527 // Omnibox keywords cannot be made default. Extension-controlled search
528 // engines can be made default only by the extension itself because they
530 DCHECK(!url
|| (url
->GetType() == TemplateURL::NORMAL
));
532 // Skip the DefaultSearchManager, which will persist to user preferences.
533 if ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
534 (default_search_provider_source_
==
535 DefaultSearchManager::FROM_FALLBACK
)) {
536 ApplyDefaultSearchChange(url
? &url
->data() : NULL
,
537 DefaultSearchManager::FROM_USER
);
540 // We rely on the DefaultSearchManager to call OnDefaultSearchChange if, in
541 // fact, the effective DSE changes.
543 default_search_manager_
.SetUserSelectedDefaultSearchEngine(url
->data());
545 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
549 TemplateURL
* TemplateURLService::GetDefaultSearchProvider() {
551 default_search_provider_
: initial_default_search_provider_
.get();
554 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
556 TemplateURL
* default_provider
= GetDefaultSearchProvider();
557 return default_provider
&&
558 default_provider
->IsSearchURL(url
, search_terms_data());
561 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
562 return default_search_provider_source_
==
563 DefaultSearchManager::FROM_EXTENSION
;
566 void TemplateURLService::RepairPrepopulatedSearchEngines() {
567 // Can't clean DB if it hasn't been loaded.
570 if ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
571 (default_search_provider_source_
==
572 DefaultSearchManager::FROM_FALLBACK
)) {
573 // Clear |default_search_provider_| in case we want to remove the engine it
574 // points to. This will get reset at the end of the function anyway.
575 default_search_provider_
= NULL
;
578 size_t default_search_provider_index
= 0;
579 ScopedVector
<TemplateURLData
> prepopulated_urls
=
580 TemplateURLPrepopulateData::GetPrepopulatedEngines(
581 prefs_
, &default_search_provider_index
);
582 DCHECK(!prepopulated_urls
.empty());
583 ActionsFromPrepopulateData
actions(CreateActionsFromCurrentPrepopulateData(
584 &prepopulated_urls
, template_urls_
, default_search_provider_
));
586 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
589 for (std::vector
<TemplateURL
*>::iterator i
= actions
.removed_engines
.begin();
590 i
< actions
.removed_engines
.end(); ++i
)
594 for (EditedEngines::iterator
i(actions
.edited_engines
.begin());
595 i
< actions
.edited_engines
.end(); ++i
) {
596 TemplateURL
new_values(i
->second
);
597 UpdateNoNotify(i
->first
, new_values
);
601 for (std::vector
<TemplateURLData
>::const_iterator i
=
602 actions
.added_engines
.begin();
603 i
< actions
.added_engines
.end();
605 AddNoNotify(new TemplateURL(*i
), true);
608 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
609 &dsp_change_origin_
, DSP_CHANGE_PROFILE_RESET
);
611 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
613 if (!default_search_provider_
) {
614 // If the default search provider came from a user pref we would have been
615 // notified of the new (fallback-provided) value in
616 // ClearUserSelectedDefaultSearchEngine() above. Since we are here, the
617 // value was presumably originally a fallback value (which may have been
619 DefaultSearchManager::Source source
;
620 const TemplateURLData
* new_dse
=
621 default_search_manager_
.GetDefaultSearchEngine(&source
);
622 // ApplyDefaultSearchChange will notify observers once it is done.
623 ApplyDefaultSearchChange(new_dse
, source
);
629 void TemplateURLService::AddObserver(TemplateURLServiceObserver
* observer
) {
630 model_observers_
.AddObserver(observer
);
633 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver
* observer
) {
634 model_observers_
.RemoveObserver(observer
);
637 void TemplateURLService::Load() {
638 if (loaded_
|| load_handle_
)
641 if (web_data_service_
.get())
642 load_handle_
= web_data_service_
->GetKeywords(this);
644 ChangeToLoadedState();
647 scoped_ptr
<TemplateURLService::Subscription
>
648 TemplateURLService::RegisterOnLoadedCallback(
649 const base::Closure
& callback
) {
651 scoped_ptr
<TemplateURLService::Subscription
>() :
652 on_loaded_callbacks_
.Add(callback
);
655 void TemplateURLService::OnWebDataServiceRequestDone(
656 KeywordWebDataService::Handle h
,
657 const WDTypedResult
* result
) {
658 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
660 tracked_objects::ScopedTracker
tracking_profile(
661 FROM_HERE_WITH_EXPLICIT_FUNCTION(
662 "422460 TemplateURLService::OnWebDataServiceRequestDone"));
664 // Reset the load_handle so that we don't try and cancel the load in
669 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
671 tracked_objects::ScopedTracker
tracking_profile1(
672 FROM_HERE_WITH_EXPLICIT_FUNCTION(
673 "422460 TemplateURLService::OnWebDataServiceRequestDone 1"));
675 // Results are null if the database went away or (most likely) wasn't
678 web_data_service_
= NULL
;
679 ChangeToLoadedState();
683 TemplateURLVector template_urls
;
684 int new_resource_keyword_version
= 0;
686 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
688 tracked_objects::ScopedTracker
tracking_profile2(
689 FROM_HERE_WITH_EXPLICIT_FUNCTION(
690 "422460 TemplateURLService::OnWebDataServiceRequestDone 2"));
692 GetSearchProvidersUsingKeywordResult(
693 *result
, web_data_service_
.get(), prefs_
, &template_urls
,
694 (default_search_provider_source_
== DefaultSearchManager::FROM_USER
)
695 ? initial_default_search_provider_
.get()
697 search_terms_data(), &new_resource_keyword_version
, &pre_sync_deletes_
);
700 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
703 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
705 tracked_objects::ScopedTracker
tracking_profile4(
706 FROM_HERE_WITH_EXPLICIT_FUNCTION(
707 "422460 TemplateURLService::OnWebDataServiceRequestDone 4"));
709 PatchMissingSyncGUIDs(&template_urls
);
711 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
713 tracked_objects::ScopedTracker
tracking_profile41(
714 FROM_HERE_WITH_EXPLICIT_FUNCTION(
715 "422460 TemplateURLService::OnWebDataServiceRequestDone 41"));
717 SetTemplateURLs(&template_urls
);
719 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
721 tracked_objects::ScopedTracker
tracking_profile42(
722 FROM_HERE_WITH_EXPLICIT_FUNCTION(
723 "422460 TemplateURLService::OnWebDataServiceRequestDone 42"));
725 // This initializes provider_map_ which should be done before
726 // calling UpdateKeywordSearchTermsForURL.
727 // This also calls NotifyObservers.
728 ChangeToLoadedState();
730 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
732 tracked_objects::ScopedTracker
tracking_profile43(
733 FROM_HERE_WITH_EXPLICIT_FUNCTION(
734 "422460 TemplateURLService::OnWebDataServiceRequestDone 43"));
736 // Index any visits that occurred before we finished loading.
737 for (size_t i
= 0; i
< visits_to_add_
.size(); ++i
)
738 UpdateKeywordSearchTermsForURL(visits_to_add_
[i
]);
739 visits_to_add_
.clear();
741 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
743 tracked_objects::ScopedTracker
tracking_profile44(
744 FROM_HERE_WITH_EXPLICIT_FUNCTION(
745 "422460 TemplateURLService::OnWebDataServiceRequestDone 44"));
747 if (new_resource_keyword_version
)
748 web_data_service_
->SetBuiltinKeywordVersion(new_resource_keyword_version
);
751 if (default_search_provider_
) {
752 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
754 tracked_objects::ScopedTracker
tracking_profile5(
755 FROM_HERE_WITH_EXPLICIT_FUNCTION(
756 "422460 TemplateURLService::OnWebDataServiceRequestDone 5"));
758 UMA_HISTOGRAM_ENUMERATION(
759 "Search.DefaultSearchProviderType",
760 TemplateURLPrepopulateData::GetEngineType(
761 *default_search_provider_
, search_terms_data()),
764 if (rappor_service_
) {
765 rappor_service_
->RecordSample(
766 "Search.DefaultSearchProvider",
767 rappor::ETLD_PLUS_ONE_RAPPOR_TYPE
,
768 net::registry_controlled_domains::GetDomainAndRegistry(
769 default_search_provider_
->url_ref().GetHost(search_terms_data()),
770 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
));
775 base::string16
TemplateURLService::GetKeywordShortName(
776 const base::string16
& keyword
,
777 bool* is_omnibox_api_extension_keyword
) {
778 const TemplateURL
* template_url
= GetTemplateURLForKeyword(keyword
);
780 // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
781 // to track changes to the model, this should become a DCHECK.
783 *is_omnibox_api_extension_keyword
=
784 template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
785 return template_url
->AdjustedShortNameForLocaleDirection();
787 *is_omnibox_api_extension_keyword
= false;
788 return base::string16();
791 void TemplateURLService::OnHistoryURLVisited(const URLVisitedDetails
& details
) {
793 visits_to_add_
.push_back(details
);
795 UpdateKeywordSearchTermsForURL(details
);
798 void TemplateURLService::Shutdown() {
801 // This check has to be done at Shutdown() instead of in the dtor to ensure
802 // that no clients of KeywordWebDataService are holding ptrs to it after the
803 // first phase of the KeyedService Shutdown() process.
805 DCHECK(web_data_service_
.get());
806 web_data_service_
->CancelRequest(load_handle_
);
808 web_data_service_
= NULL
;
811 syncer::SyncDataList
TemplateURLService::GetAllSyncData(
812 syncer::ModelType type
) const {
813 DCHECK_EQ(syncer::SEARCH_ENGINES
, type
);
815 syncer::SyncDataList current_data
;
816 for (TemplateURLVector::const_iterator iter
= template_urls_
.begin();
817 iter
!= template_urls_
.end(); ++iter
) {
818 // We don't sync keywords managed by policy.
819 if ((*iter
)->created_by_policy())
821 // We don't sync extension-controlled search engines.
822 if ((*iter
)->GetType() != TemplateURL::NORMAL
)
824 current_data
.push_back(CreateSyncDataFromTemplateURL(**iter
));
830 syncer::SyncError
TemplateURLService::ProcessSyncChanges(
831 const tracked_objects::Location
& from_here
,
832 const syncer::SyncChangeList
& change_list
) {
833 if (!models_associated_
) {
834 syncer::SyncError
error(FROM_HERE
,
835 syncer::SyncError::DATATYPE_ERROR
,
836 "Models not yet associated.",
837 syncer::SEARCH_ENGINES
);
842 base::AutoReset
<bool> processing_changes(&processing_syncer_changes_
, true);
844 // We've started syncing, so set our origin member to the base Sync value.
845 // As we move through Sync Code, we may set this to increasingly specific
846 // origins so we can tell what exactly caused a DSP change.
847 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(&dsp_change_origin_
,
848 DSP_CHANGE_SYNC_UNINTENTIONAL
);
850 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
852 syncer::SyncChangeList new_changes
;
853 syncer::SyncError error
;
854 for (syncer::SyncChangeList::const_iterator iter
= change_list
.begin();
855 iter
!= change_list
.end(); ++iter
) {
856 DCHECK_EQ(syncer::SEARCH_ENGINES
, iter
->sync_data().GetDataType());
859 iter
->sync_data().GetSpecifics().search_engine().sync_guid();
860 TemplateURL
* existing_turl
= GetTemplateURLForGUID(guid
);
861 scoped_ptr
<TemplateURL
> turl(CreateTemplateURLFromTemplateURLAndSyncData(
862 client_
.get(), prefs_
, search_terms_data(), existing_turl
,
863 iter
->sync_data(), &new_changes
));
867 // Explicitly don't check for conflicts against extension keywords; in this
868 // case the functions which modify the keyword map know how to handle the
870 // TODO(mpcomplete): If we allow editing extension keywords, then those will
871 // need to undergo conflict resolution.
872 TemplateURL
* existing_keyword_turl
=
873 FindNonExtensionTemplateURLForKeyword(turl
->keyword());
874 if (iter
->change_type() == syncer::SyncChange::ACTION_DELETE
) {
875 if (!existing_turl
) {
876 error
= sync_error_factory_
->CreateAndUploadError(
878 "ProcessSyncChanges failed on ChangeType ACTION_DELETE");
881 if (existing_turl
== GetDefaultSearchProvider()) {
882 // The only way Sync can attempt to delete the default search provider
883 // is if we had changed the kSyncedDefaultSearchProviderGUID
884 // preference, but perhaps it has not yet been received. To avoid
885 // situations where this has come in erroneously, we will un-delete
886 // the current default search from the Sync data. If the pref really
887 // does arrive later, then default search will change to the correct
888 // entry, but we'll have this extra entry sitting around. The result is
889 // not ideal, but it prevents a far more severe bug where the default is
890 // unexpectedly swapped to something else. The user can safely delete
891 // the extra entry again later, if they choose. Most users who do not
892 // look at the search engines UI will not notice this.
893 // Note that we append a special character to the end of the keyword in
894 // an attempt to avoid a ping-poinging situation where receiving clients
895 // may try to continually delete the resurrected entry.
896 base::string16 updated_keyword
= UniquifyKeyword(*existing_turl
, true);
897 TemplateURLData
data(existing_turl
->data());
898 data
.SetKeyword(updated_keyword
);
899 TemplateURL
new_turl(data
);
900 if (UpdateNoNotify(existing_turl
, new_turl
))
903 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(new_turl
);
904 new_changes
.push_back(syncer::SyncChange(FROM_HERE
,
905 syncer::SyncChange::ACTION_ADD
,
907 // Ignore the delete attempt. This means we never end up resetting the
908 // default search provider due to an ACTION_DELETE from sync.
912 Remove(existing_turl
);
913 } else if (iter
->change_type() == syncer::SyncChange::ACTION_ADD
) {
915 error
= sync_error_factory_
->CreateAndUploadError(
917 "ProcessSyncChanges failed on ChangeType ACTION_ADD");
920 const std::string guid
= turl
->sync_guid();
921 if (existing_keyword_turl
) {
922 // Resolve any conflicts so we can safely add the new entry.
923 ResolveSyncKeywordConflict(turl
.get(), existing_keyword_turl
,
926 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
927 &dsp_change_origin_
, DSP_CHANGE_SYNC_ADD
);
928 // Force the local ID to kInvalidTemplateURLID so we can add it.
929 TemplateURLData
data(turl
->data());
930 data
.id
= kInvalidTemplateURLID
;
931 TemplateURL
* added
= new TemplateURL(data
);
933 MaybeUpdateDSEAfterSync(added
);
934 } else if (iter
->change_type() == syncer::SyncChange::ACTION_UPDATE
) {
935 if (!existing_turl
) {
936 error
= sync_error_factory_
->CreateAndUploadError(
938 "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
941 if (existing_keyword_turl
&& (existing_keyword_turl
!= existing_turl
)) {
942 // Resolve any conflicts with other entries so we can safely update the
944 ResolveSyncKeywordConflict(turl
.get(), existing_keyword_turl
,
947 if (UpdateNoNotify(existing_turl
, *turl
)) {
949 MaybeUpdateDSEAfterSync(existing_turl
);
952 // We've unexpectedly received an ACTION_INVALID.
953 error
= sync_error_factory_
->CreateAndUploadError(
955 "ProcessSyncChanges received an ACTION_INVALID");
959 // If something went wrong, we want to prematurely exit to avoid pushing
960 // inconsistent data to Sync. We return the last error we received.
964 error
= sync_processor_
->ProcessSyncChanges(from_here
, new_changes
);
969 syncer::SyncMergeResult
TemplateURLService::MergeDataAndStartSyncing(
970 syncer::ModelType type
,
971 const syncer::SyncDataList
& initial_sync_data
,
972 scoped_ptr
<syncer::SyncChangeProcessor
> sync_processor
,
973 scoped_ptr
<syncer::SyncErrorFactory
> sync_error_factory
) {
975 DCHECK_EQ(type
, syncer::SEARCH_ENGINES
);
976 DCHECK(!sync_processor_
.get());
977 DCHECK(sync_processor
.get());
978 DCHECK(sync_error_factory
.get());
979 syncer::SyncMergeResult
merge_result(type
);
981 // Disable sync if we failed to load.
983 merge_result
.set_error(syncer::SyncError(
984 FROM_HERE
, syncer::SyncError::DATATYPE_ERROR
,
985 "Local database load failed.", syncer::SEARCH_ENGINES
));
989 sync_processor_
= sync_processor
.Pass();
990 sync_error_factory_
= sync_error_factory
.Pass();
992 // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
993 // don't step on our own toes.
994 base::AutoReset
<bool> processing_changes(&processing_syncer_changes_
, true);
996 // We've started syncing, so set our origin member to the base Sync value.
997 // As we move through Sync Code, we may set this to increasingly specific
998 // origins so we can tell what exactly caused a DSP change.
999 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(&dsp_change_origin_
,
1000 DSP_CHANGE_SYNC_UNINTENTIONAL
);
1002 syncer::SyncChangeList new_changes
;
1004 // Build maps of our sync GUIDs to syncer::SyncData.
1005 SyncDataMap local_data_map
= CreateGUIDToSyncDataMap(
1006 GetAllSyncData(syncer::SEARCH_ENGINES
));
1007 SyncDataMap sync_data_map
= CreateGUIDToSyncDataMap(initial_sync_data
);
1009 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1011 merge_result
.set_num_items_before_association(local_data_map
.size());
1012 for (SyncDataMap::const_iterator iter
= sync_data_map
.begin();
1013 iter
!= sync_data_map
.end(); ++iter
) {
1014 TemplateURL
* local_turl
= GetTemplateURLForGUID(iter
->first
);
1015 scoped_ptr
<TemplateURL
> sync_turl(
1016 CreateTemplateURLFromTemplateURLAndSyncData(
1017 client_
.get(), prefs_
, search_terms_data(), local_turl
,
1018 iter
->second
, &new_changes
));
1019 if (!sync_turl
.get())
1022 if (pre_sync_deletes_
.find(sync_turl
->sync_guid()) !=
1023 pre_sync_deletes_
.end()) {
1024 // This entry was deleted before the initial sync began (possibly through
1025 // preprocessing in TemplateURLService's loading code). Ignore it and send
1026 // an ACTION_DELETE up to the server.
1027 new_changes
.push_back(
1028 syncer::SyncChange(FROM_HERE
,
1029 syncer::SyncChange::ACTION_DELETE
,
1031 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1032 DELETE_ENGINE_PRE_SYNC
, DELETE_ENGINE_MAX
);
1037 DCHECK(IsFromSync(local_turl
, sync_data_map
));
1038 // This local search engine is already synced. If the timestamp differs
1039 // from Sync, we need to update locally or to the cloud. Note that if the
1040 // timestamps are equal, we touch neither.
1041 if (sync_turl
->last_modified() > local_turl
->last_modified()) {
1042 // We've received an update from Sync. We should replace all synced
1043 // fields in the local TemplateURL. Note that this includes the
1044 // TemplateURLID and the TemplateURL may have to be reparsed. This
1045 // also makes the local data's last_modified timestamp equal to Sync's,
1046 // avoiding an Update on the next MergeData call.
1047 if (UpdateNoNotify(local_turl
, *sync_turl
))
1049 merge_result
.set_num_items_modified(
1050 merge_result
.num_items_modified() + 1);
1051 } else if (sync_turl
->last_modified() < local_turl
->last_modified()) {
1052 // Otherwise, we know we have newer data, so update Sync with our
1054 new_changes
.push_back(
1055 syncer::SyncChange(FROM_HERE
,
1056 syncer::SyncChange::ACTION_UPDATE
,
1057 local_data_map
[local_turl
->sync_guid()]));
1059 local_data_map
.erase(iter
->first
);
1061 // The search engine from the cloud has not been synced locally. Merge it
1062 // into our local model. This will handle any conflicts with local (and
1063 // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1064 // over not-yet-synced TemplateURLs.
1065 MergeInSyncTemplateURL(sync_turl
.get(), sync_data_map
, &new_changes
,
1066 &local_data_map
, &merge_result
);
1070 // The remaining SyncData in local_data_map should be everything that needs to
1071 // be pushed as ADDs to sync.
1072 for (SyncDataMap::const_iterator iter
= local_data_map
.begin();
1073 iter
!= local_data_map
.end(); ++iter
) {
1074 new_changes
.push_back(
1075 syncer::SyncChange(FROM_HERE
,
1076 syncer::SyncChange::ACTION_ADD
,
1080 // Do some post-processing on the change list to ensure that we are sending
1081 // valid changes to sync_processor_.
1082 PruneSyncChanges(&sync_data_map
, &new_changes
);
1084 LogDuplicatesHistogram(GetTemplateURLs());
1085 merge_result
.set_num_items_after_association(
1086 GetAllSyncData(syncer::SEARCH_ENGINES
).size());
1087 merge_result
.set_error(
1088 sync_processor_
->ProcessSyncChanges(FROM_HERE
, new_changes
));
1089 if (merge_result
.error().IsSet())
1090 return merge_result
;
1092 // The ACTION_DELETEs from this set are processed. Empty it so we don't try to
1093 // reuse them on the next call to MergeDataAndStartSyncing.
1094 pre_sync_deletes_
.clear();
1096 models_associated_
= true;
1097 return merge_result
;
1100 void TemplateURLService::StopSyncing(syncer::ModelType type
) {
1101 DCHECK_EQ(type
, syncer::SEARCH_ENGINES
);
1102 models_associated_
= false;
1103 sync_processor_
.reset();
1104 sync_error_factory_
.reset();
1107 void TemplateURLService::ProcessTemplateURLChange(
1108 const tracked_objects::Location
& from_here
,
1109 const TemplateURL
* turl
,
1110 syncer::SyncChange::SyncChangeType type
) {
1111 DCHECK_NE(type
, syncer::SyncChange::ACTION_INVALID
);
1114 if (!models_associated_
)
1115 return; // Not syncing.
1117 if (processing_syncer_changes_
)
1118 return; // These are changes originating from us. Ignore.
1120 // Avoid syncing keywords managed by policy.
1121 if (turl
->created_by_policy())
1124 // Avoid syncing extension-controlled search engines.
1125 if (turl
->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
)
1128 syncer::SyncChangeList changes
;
1130 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*turl
);
1131 changes
.push_back(syncer::SyncChange(from_here
,
1135 sync_processor_
->ProcessSyncChanges(FROM_HERE
, changes
);
1139 syncer::SyncData
TemplateURLService::CreateSyncDataFromTemplateURL(
1140 const TemplateURL
& turl
) {
1141 sync_pb::EntitySpecifics specifics
;
1142 sync_pb::SearchEngineSpecifics
* se_specifics
=
1143 specifics
.mutable_search_engine();
1144 se_specifics
->set_short_name(base::UTF16ToUTF8(turl
.short_name()));
1145 se_specifics
->set_keyword(base::UTF16ToUTF8(turl
.keyword()));
1146 se_specifics
->set_favicon_url(turl
.favicon_url().spec());
1147 se_specifics
->set_url(turl
.url());
1148 se_specifics
->set_safe_for_autoreplace(turl
.safe_for_autoreplace());
1149 se_specifics
->set_originating_url(turl
.originating_url().spec());
1150 se_specifics
->set_date_created(turl
.date_created().ToInternalValue());
1151 se_specifics
->set_input_encodings(JoinString(turl
.input_encodings(), ';'));
1152 se_specifics
->set_show_in_default_list(turl
.show_in_default_list());
1153 se_specifics
->set_suggestions_url(turl
.suggestions_url());
1154 se_specifics
->set_prepopulate_id(turl
.prepopulate_id());
1155 se_specifics
->set_instant_url(turl
.instant_url());
1156 if (!turl
.image_url().empty())
1157 se_specifics
->set_image_url(turl
.image_url());
1158 se_specifics
->set_new_tab_url(turl
.new_tab_url());
1159 if (!turl
.search_url_post_params().empty())
1160 se_specifics
->set_search_url_post_params(turl
.search_url_post_params());
1161 if (!turl
.suggestions_url_post_params().empty()) {
1162 se_specifics
->set_suggestions_url_post_params(
1163 turl
.suggestions_url_post_params());
1165 if (!turl
.instant_url_post_params().empty())
1166 se_specifics
->set_instant_url_post_params(turl
.instant_url_post_params());
1167 if (!turl
.image_url_post_params().empty())
1168 se_specifics
->set_image_url_post_params(turl
.image_url_post_params());
1169 se_specifics
->set_last_modified(turl
.last_modified().ToInternalValue());
1170 se_specifics
->set_sync_guid(turl
.sync_guid());
1171 for (size_t i
= 0; i
< turl
.alternate_urls().size(); ++i
)
1172 se_specifics
->add_alternate_urls(turl
.alternate_urls()[i
]);
1173 se_specifics
->set_search_terms_replacement_key(
1174 turl
.search_terms_replacement_key());
1176 return syncer::SyncData::CreateLocalData(se_specifics
->sync_guid(),
1177 se_specifics
->keyword(),
1182 scoped_ptr
<TemplateURL
>
1183 TemplateURLService::CreateTemplateURLFromTemplateURLAndSyncData(
1184 TemplateURLServiceClient
* client
,
1186 const SearchTermsData
& search_terms_data
,
1187 TemplateURL
* existing_turl
,
1188 const syncer::SyncData
& sync_data
,
1189 syncer::SyncChangeList
* change_list
) {
1190 DCHECK(change_list
);
1192 sync_pb::SearchEngineSpecifics specifics
=
1193 sync_data
.GetSpecifics().search_engine();
1195 // Past bugs might have caused either of these fields to be empty. Just
1196 // delete this data off the server.
1197 if (specifics
.url().empty() || specifics
.sync_guid().empty()) {
1198 change_list
->push_back(
1199 syncer::SyncChange(FROM_HERE
,
1200 syncer::SyncChange::ACTION_DELETE
,
1202 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1203 DELETE_ENGINE_EMPTY_FIELD
, DELETE_ENGINE_MAX
);
1207 TemplateURLData
data(existing_turl
?
1208 existing_turl
->data() : TemplateURLData());
1209 data
.short_name
= base::UTF8ToUTF16(specifics
.short_name());
1210 data
.originating_url
= GURL(specifics
.originating_url());
1211 base::string16
keyword(base::UTF8ToUTF16(specifics
.keyword()));
1212 // NOTE: Once this code has shipped in a couple of stable releases, we can
1213 // probably remove the migration portion, comment out the
1214 // "autogenerate_keyword" field entirely in the .proto file, and fold the
1215 // empty keyword case into the "delete data" block above.
1216 bool reset_keyword
=
1217 specifics
.autogenerate_keyword() || specifics
.keyword().empty();
1219 keyword
= base::ASCIIToUTF16("dummy"); // Will be replaced below.
1220 DCHECK(!keyword
.empty());
1221 data
.SetKeyword(keyword
);
1222 data
.SetURL(specifics
.url());
1223 data
.suggestions_url
= specifics
.suggestions_url();
1224 data
.instant_url
= specifics
.instant_url();
1225 data
.image_url
= specifics
.image_url();
1226 data
.new_tab_url
= specifics
.new_tab_url();
1227 data
.search_url_post_params
= specifics
.search_url_post_params();
1228 data
.suggestions_url_post_params
= specifics
.suggestions_url_post_params();
1229 data
.instant_url_post_params
= specifics
.instant_url_post_params();
1230 data
.image_url_post_params
= specifics
.image_url_post_params();
1231 data
.favicon_url
= GURL(specifics
.favicon_url());
1232 data
.show_in_default_list
= specifics
.show_in_default_list();
1233 data
.safe_for_autoreplace
= specifics
.safe_for_autoreplace();
1234 base::SplitString(specifics
.input_encodings(), ';', &data
.input_encodings
);
1235 // If the server data has duplicate encodings, we'll want to push an update
1236 // below to correct it. Note that we also fix this in
1237 // GetSearchProvidersUsingKeywordResult(), since otherwise we'd never correct
1238 // local problems for clients which have disabled search engine sync.
1239 bool deduped
= DeDupeEncodings(&data
.input_encodings
);
1240 data
.date_created
= base::Time::FromInternalValue(specifics
.date_created());
1241 data
.last_modified
= base::Time::FromInternalValue(specifics
.last_modified());
1242 data
.prepopulate_id
= specifics
.prepopulate_id();
1243 data
.sync_guid
= specifics
.sync_guid();
1244 data
.alternate_urls
.clear();
1245 for (int i
= 0; i
< specifics
.alternate_urls_size(); ++i
)
1246 data
.alternate_urls
.push_back(specifics
.alternate_urls(i
));
1247 data
.search_terms_replacement_key
= specifics
.search_terms_replacement_key();
1249 scoped_ptr
<TemplateURL
> turl(new TemplateURL(data
));
1250 // If this TemplateURL matches a built-in prepopulated template URL, it's
1251 // possible that sync is trying to modify fields that should not be touched.
1252 // Revert these fields to the built-in values.
1253 UpdateTemplateURLIfPrepopulated(turl
.get(), prefs
);
1255 // We used to sync keywords associated with omnibox extensions, but no longer
1256 // want to. However, if we delete these keywords from sync, we'll break any
1257 // synced old versions of Chrome which were relying on them. Instead, for now
1258 // we simply ignore these.
1259 // TODO(vasilii): After a few Chrome versions, change this to go ahead and
1260 // delete these from sync.
1262 client
->RestoreExtensionInfoIfNecessary(turl
.get());
1263 if (turl
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
)
1266 DCHECK_EQ(TemplateURL::NORMAL
, turl
->GetType());
1267 if (reset_keyword
|| deduped
) {
1269 turl
->ResetKeywordIfNecessary(search_terms_data
, true);
1270 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*turl
);
1271 change_list
->push_back(syncer::SyncChange(FROM_HERE
,
1272 syncer::SyncChange::ACTION_UPDATE
,
1274 } else if (turl
->IsGoogleSearchURLWithReplaceableKeyword(search_terms_data
)) {
1275 if (!existing_turl
) {
1276 // We're adding a new TemplateURL that uses the Google base URL, so set
1277 // its keyword appropriately for the local environment.
1278 turl
->ResetKeywordIfNecessary(search_terms_data
, false);
1279 } else if (existing_turl
->IsGoogleSearchURLWithReplaceableKeyword(
1280 search_terms_data
)) {
1281 // Ignore keyword changes triggered by the Google base URL changing on
1282 // another client. If the base URL changes in this client as well, we'll
1283 // pick that up separately at the appropriate time. Otherwise, changing
1284 // the keyword here could result in having the wrong keyword for the local
1286 turl
->data_
.SetKeyword(existing_turl
->keyword());
1294 SyncDataMap
TemplateURLService::CreateGUIDToSyncDataMap(
1295 const syncer::SyncDataList
& sync_data
) {
1296 SyncDataMap data_map
;
1297 for (syncer::SyncDataList::const_iterator
i(sync_data
.begin());
1298 i
!= sync_data
.end();
1300 data_map
[i
->GetSpecifics().search_engine().sync_guid()] = *i
;
1304 void TemplateURLService::Init(const Initializer
* initializers
,
1305 int num_initializers
) {
1307 client_
->SetOwner(this);
1309 // GoogleURLTracker is not created in tests.
1310 if (google_url_tracker_
) {
1311 google_url_updated_subscription_
=
1312 google_url_tracker_
->RegisterCallback(base::Bind(
1313 &TemplateURLService::GoogleBaseURLChanged
, base::Unretained(this)));
1317 pref_change_registrar_
.Init(prefs_
);
1318 pref_change_registrar_
.Add(
1319 prefs::kSyncedDefaultSearchProviderGUID
,
1321 &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged
,
1322 base::Unretained(this)));
1325 DefaultSearchManager::Source source
= DefaultSearchManager::FROM_USER
;
1326 TemplateURLData
* dse
=
1327 default_search_manager_
.GetDefaultSearchEngine(&source
);
1328 ApplyDefaultSearchChange(dse
, source
);
1330 if (num_initializers
> 0) {
1331 // This path is only hit by test code and is used to simulate a loaded
1332 // TemplateURLService.
1333 ChangeToLoadedState();
1335 // Add specific initializers, if any.
1336 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1337 for (int i(0); i
< num_initializers
; ++i
) {
1338 DCHECK(initializers
[i
].keyword
);
1339 DCHECK(initializers
[i
].url
);
1340 DCHECK(initializers
[i
].content
);
1342 // TemplateURLService ends up owning the TemplateURL, don't try and free
1344 TemplateURLData data
;
1345 data
.short_name
= base::UTF8ToUTF16(initializers
[i
].content
);
1346 data
.SetKeyword(base::UTF8ToUTF16(initializers
[i
].keyword
));
1347 data
.SetURL(initializers
[i
].url
);
1348 TemplateURL
* template_url
= new TemplateURL(data
);
1349 AddNoNotify(template_url
, true);
1351 // Set the first provided identifier to be the default.
1353 default_search_manager_
.SetUserSelectedDefaultSearchEngine(data
);
1357 // Request a server check for the correct Google URL if Google is the
1358 // default search engine.
1359 RequestGoogleURLTrackerServerCheckIfNecessary();
1362 void TemplateURLService::RemoveFromMaps(TemplateURL
* template_url
) {
1363 const base::string16
& keyword
= template_url
->keyword();
1364 DCHECK_NE(0U, keyword_to_template_map_
.count(keyword
));
1365 if (keyword_to_template_map_
[keyword
] == template_url
) {
1366 // We need to check whether the keyword can now be provided by another
1367 // TemplateURL. See the comments in AddToMaps() for more information on
1368 // extension keywords and how they can coexist with non-extension keywords.
1369 // In the case of more than one extension, we use the most recently
1370 // installed (which will be the most recently added, which will have the
1372 TemplateURL
* best_fallback
= NULL
;
1373 for (TemplateURLVector::const_iterator
i(template_urls_
.begin());
1374 i
!= template_urls_
.end(); ++i
) {
1375 TemplateURL
* turl
= *i
;
1376 // This next statement relies on the fact that there can only be one
1377 // non-Omnibox API TemplateURL with a given keyword.
1378 if ((turl
!= template_url
) && (turl
->keyword() == keyword
) &&
1380 (best_fallback
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
) ||
1381 ((turl
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
) &&
1382 (turl
->id() > best_fallback
->id()))))
1383 best_fallback
= turl
;
1386 keyword_to_template_map_
[keyword
] = best_fallback
;
1388 keyword_to_template_map_
.erase(keyword
);
1391 if (template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
)
1394 if (!template_url
->sync_guid().empty())
1395 guid_to_template_map_
.erase(template_url
->sync_guid());
1396 // |provider_map_| is only initialized after loading has completed.
1398 provider_map_
->Remove(template_url
);
1402 void TemplateURLService::AddToMaps(TemplateURL
* template_url
) {
1403 bool template_url_is_omnibox_api
=
1404 template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
1405 const base::string16
& keyword
= template_url
->keyword();
1406 KeywordToTemplateMap::const_iterator i
=
1407 keyword_to_template_map_
.find(keyword
);
1408 if (i
== keyword_to_template_map_
.end()) {
1409 keyword_to_template_map_
[keyword
] = template_url
;
1411 const TemplateURL
* existing_url
= i
->second
;
1412 // We should only have overlapping keywords when at least one comes from
1413 // an extension. In that case, the ranking order is:
1414 // Manually-modified keywords > extension keywords > replaceable keywords
1415 // When there are multiple extensions, the last-added wins.
1416 bool existing_url_is_omnibox_api
=
1417 existing_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
1418 DCHECK(existing_url_is_omnibox_api
|| template_url_is_omnibox_api
);
1419 if (existing_url_is_omnibox_api
?
1420 !CanReplace(template_url
) : CanReplace(existing_url
))
1421 keyword_to_template_map_
[keyword
] = template_url
;
1424 if (template_url_is_omnibox_api
)
1427 if (!template_url
->sync_guid().empty())
1428 guid_to_template_map_
[template_url
->sync_guid()] = template_url
;
1429 // |provider_map_| is only initialized after loading has completed.
1431 provider_map_
->Add(template_url
, search_terms_data());
1434 // Helper for partition() call in next function.
1435 bool HasValidID(TemplateURL
* t_url
) {
1436 return t_url
->id() != kInvalidTemplateURLID
;
1439 void TemplateURLService::SetTemplateURLs(TemplateURLVector
* urls
) {
1440 // Partition the URLs first, instead of implementing the loops below by simply
1441 // scanning the input twice. While it's not supposed to happen normally, it's
1442 // possible for corrupt databases to return multiple entries with the same
1443 // keyword. In this case, the first loop may delete the first entry when
1444 // adding the second. If this happens, the second loop must not attempt to
1445 // access the deleted entry. Partitioning ensures this constraint.
1446 TemplateURLVector::iterator
first_invalid(
1447 std::partition(urls
->begin(), urls
->end(), HasValidID
));
1449 // First, add the items that already have id's, so that the next_id_ gets
1451 for (TemplateURLVector::const_iterator i
= urls
->begin(); i
!= first_invalid
;
1453 next_id_
= std::max(next_id_
, (*i
)->id());
1454 AddNoNotify(*i
, false);
1457 // Next add the new items that don't have id's.
1458 for (TemplateURLVector::const_iterator i
= first_invalid
; i
!= urls
->end();
1460 AddNoNotify(*i
, true);
1462 // Clear the input vector to reduce the chance callers will try to use a
1463 // (possibly deleted) entry.
1467 void TemplateURLService::ChangeToLoadedState() {
1468 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1470 tracked_objects::ScopedTracker
tracking_profile1(
1471 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1472 "422460 TemplateURLService::ChangeToLoadedState 1"));
1476 provider_map_
->Init(template_urls_
, search_terms_data());
1479 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1481 tracked_objects::ScopedTracker
tracking_profile2(
1482 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1483 "422460 TemplateURLService::ChangeToLoadedState 2"));
1485 // This will cause a call to NotifyObservers().
1486 ApplyDefaultSearchChangeNoMetrics(
1487 initial_default_search_provider_
?
1488 &initial_default_search_provider_
->data() : NULL
,
1489 default_search_provider_source_
);
1490 initial_default_search_provider_
.reset();
1492 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1494 tracked_objects::ScopedTracker
tracking_profile3(
1495 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1496 "422460 TemplateURLService::ChangeToLoadedState 3"));
1498 on_loaded_callbacks_
.Notify();
1501 bool TemplateURLService::CanReplaceKeywordForHost(
1502 const std::string
& host
,
1503 TemplateURL
** to_replace
) {
1504 DCHECK(!to_replace
|| !*to_replace
);
1505 const TemplateURLSet
* urls
= provider_map_
->GetURLsForHost(host
);
1508 for (TemplateURLSet::const_iterator
i(urls
->begin()); i
!= urls
->end(); ++i
) {
1509 if (CanReplace(*i
)) {
1518 bool TemplateURLService::CanReplace(const TemplateURL
* t_url
) {
1519 return (t_url
!= default_search_provider_
&& !t_url
->show_in_default_list() &&
1520 t_url
->safe_for_autoreplace());
1523 TemplateURL
* TemplateURLService::FindNonExtensionTemplateURLForKeyword(
1524 const base::string16
& keyword
) {
1525 TemplateURL
* keyword_turl
= GetTemplateURLForKeyword(keyword
);
1526 if (!keyword_turl
|| (keyword_turl
->GetType() == TemplateURL::NORMAL
))
1527 return keyword_turl
;
1528 // The extension keyword in the model may be hiding a replaceable
1529 // non-extension keyword. Look for it.
1530 for (TemplateURLVector::const_iterator
i(template_urls_
.begin());
1531 i
!= template_urls_
.end(); ++i
) {
1532 if (((*i
)->GetType() == TemplateURL::NORMAL
) &&
1533 ((*i
)->keyword() == keyword
))
1539 bool TemplateURLService::UpdateNoNotify(TemplateURL
* existing_turl
,
1540 const TemplateURL
& new_values
) {
1541 DCHECK(existing_turl
);
1542 if (std::find(template_urls_
.begin(), template_urls_
.end(), existing_turl
) ==
1543 template_urls_
.end())
1546 DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION
, existing_turl
->GetType());
1548 base::string16
old_keyword(existing_turl
->keyword());
1549 keyword_to_template_map_
.erase(old_keyword
);
1550 if (!existing_turl
->sync_guid().empty())
1551 guid_to_template_map_
.erase(existing_turl
->sync_guid());
1553 // |provider_map_| is only initialized after loading has completed.
1555 provider_map_
->Remove(existing_turl
);
1557 TemplateURLID previous_id
= existing_turl
->id();
1558 existing_turl
->CopyFrom(new_values
);
1559 existing_turl
->data_
.id
= previous_id
;
1562 provider_map_
->Add(existing_turl
, search_terms_data());
1565 const base::string16
& keyword
= existing_turl
->keyword();
1566 KeywordToTemplateMap::const_iterator i
=
1567 keyword_to_template_map_
.find(keyword
);
1568 if (i
== keyword_to_template_map_
.end()) {
1569 keyword_to_template_map_
[keyword
] = existing_turl
;
1571 // We can theoretically reach here in two cases:
1572 // * There is an existing extension keyword and sync brings in a rename of
1573 // a non-extension keyword to match. In this case we just need to pick
1574 // which keyword has priority to update the keyword map.
1575 // * Autogeneration of the keyword for a Google default search provider
1576 // at load time causes it to conflict with an existing keyword. In this
1577 // case we delete the existing keyword if it's replaceable, or else undo
1578 // the change in keyword for |existing_turl|.
1579 TemplateURL
* existing_keyword_turl
= i
->second
;
1580 if (existing_keyword_turl
->GetType() != TemplateURL::NORMAL
) {
1581 if (!CanReplace(existing_turl
))
1582 keyword_to_template_map_
[keyword
] = existing_turl
;
1584 if (CanReplace(existing_keyword_turl
)) {
1585 RemoveNoNotify(existing_keyword_turl
);
1587 existing_turl
->data_
.SetKeyword(old_keyword
);
1588 keyword_to_template_map_
[old_keyword
] = existing_turl
;
1592 if (!existing_turl
->sync_guid().empty())
1593 guid_to_template_map_
[existing_turl
->sync_guid()] = existing_turl
;
1595 if (web_data_service_
.get())
1596 web_data_service_
->UpdateKeyword(existing_turl
->data());
1598 // Inform sync of the update.
1599 ProcessTemplateURLChange(
1600 FROM_HERE
, existing_turl
, syncer::SyncChange::ACTION_UPDATE
);
1602 if (default_search_provider_
== existing_turl
&&
1603 default_search_provider_source_
== DefaultSearchManager::FROM_USER
) {
1604 default_search_manager_
.SetUserSelectedDefaultSearchEngine(
1605 default_search_provider_
->data());
1611 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1612 TemplateURL
* template_url
,
1613 PrefService
* prefs
) {
1614 int prepopulate_id
= template_url
->prepopulate_id();
1615 if (template_url
->prepopulate_id() == 0)
1618 size_t default_search_index
;
1619 ScopedVector
<TemplateURLData
> prepopulated_urls
=
1620 TemplateURLPrepopulateData::GetPrepopulatedEngines(
1621 prefs
, &default_search_index
);
1623 for (size_t i
= 0; i
< prepopulated_urls
.size(); ++i
) {
1624 if (prepopulated_urls
[i
]->prepopulate_id
== prepopulate_id
) {
1625 MergeIntoPrepopulatedEngineData(template_url
, prepopulated_urls
[i
]);
1626 template_url
->CopyFrom(TemplateURL(*prepopulated_urls
[i
]));
1631 void TemplateURLService::MaybeUpdateDSEAfterSync(TemplateURL
* synced_turl
) {
1633 (synced_turl
->sync_guid() ==
1634 prefs_
->GetString(prefs::kSyncedDefaultSearchProviderGUID
))) {
1635 default_search_manager_
.SetUserSelectedDefaultSearchEngine(
1636 synced_turl
->data());
1640 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1641 const URLVisitedDetails
& details
) {
1642 if (!details
.url
.is_valid())
1645 const TemplateURLSet
* urls_for_host
=
1646 provider_map_
->GetURLsForHost(details
.url
.host());
1650 for (TemplateURLSet::const_iterator i
= urls_for_host
->begin();
1651 i
!= urls_for_host
->end(); ++i
) {
1652 base::string16 search_terms
;
1653 if ((*i
)->ExtractSearchTermsFromURL(details
.url
, search_terms_data(),
1655 !search_terms
.empty()) {
1656 if (details
.is_keyword_transition
) {
1657 // The visit is the result of the user entering a keyword, generate a
1658 // KEYWORD_GENERATED visit for the KEYWORD so that the keyword typed
1659 // count is boosted.
1660 AddTabToSearchVisit(**i
);
1663 client_
->SetKeywordSearchTermsForURL(
1664 details
.url
, (*i
)->id(), search_terms
);
1670 void TemplateURLService::AddTabToSearchVisit(const TemplateURL
& t_url
) {
1671 // Only add visits for entries the user hasn't modified. If the user modified
1672 // the entry the keyword may no longer correspond to the host name. It may be
1673 // possible to do something more sophisticated here, but it's so rare as to
1675 if (!t_url
.safe_for_autoreplace())
1682 url_fixer::FixupURL(base::UTF16ToUTF8(t_url
.keyword()), std::string()));
1683 if (!url
.is_valid())
1686 // Synthesize a visit for the keyword. This ensures the url for the keyword is
1687 // autocompleted even if the user doesn't type the url in directly.
1688 client_
->AddKeywordGeneratedVisit(url
);
1691 void TemplateURLService::RequestGoogleURLTrackerServerCheckIfNecessary() {
1692 if (default_search_provider_
&&
1693 default_search_provider_
->HasGoogleBaseURLs(search_terms_data()) &&
1694 google_url_tracker_
)
1695 google_url_tracker_
->RequestServerCheck(false);
1698 void TemplateURLService::GoogleBaseURLChanged() {
1702 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1703 bool something_changed
= false;
1704 for (TemplateURLVector::iterator
i(template_urls_
.begin());
1705 i
!= template_urls_
.end(); ++i
) {
1706 TemplateURL
* t_url
= *i
;
1707 if (t_url
->HasGoogleBaseURLs(search_terms_data())) {
1708 TemplateURL
updated_turl(t_url
->data());
1709 updated_turl
.ResetKeywordIfNecessary(search_terms_data(), false);
1710 KeywordToTemplateMap::const_iterator existing_entry
=
1711 keyword_to_template_map_
.find(updated_turl
.keyword());
1712 if ((existing_entry
!= keyword_to_template_map_
.end()) &&
1713 (existing_entry
->second
!= t_url
)) {
1714 // The new autogenerated keyword conflicts with another TemplateURL.
1715 // Overwrite it if it's replaceable; otherwise, leave |t_url| using its
1716 // current keyword. (This will not prevent |t_url| from auto-updating
1717 // the keyword in the future if the conflicting TemplateURL disappears.)
1718 // Note that we must still update |t_url| in this case, or the
1719 // |provider_map_| will not be updated correctly.
1720 if (CanReplace(existing_entry
->second
))
1721 RemoveNoNotify(existing_entry
->second
);
1723 updated_turl
.data_
.SetKeyword(t_url
->keyword());
1725 something_changed
= true;
1726 // This will send the keyword change to sync. Note that other clients
1727 // need to reset the keyword to an appropriate local value when this
1728 // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
1729 UpdateNoNotify(t_url
, updated_turl
);
1732 if (something_changed
)
1736 void TemplateURLService::OnDefaultSearchChange(
1737 const TemplateURLData
* data
,
1738 DefaultSearchManager::Source source
) {
1739 if (prefs_
&& (source
== DefaultSearchManager::FROM_USER
) &&
1740 ((source
!= default_search_provider_source_
) ||
1741 !IdenticalSyncGUIDs(data
, GetDefaultSearchProvider()))) {
1742 prefs_
->SetString(prefs::kSyncedDefaultSearchProviderGUID
, data
->sync_guid
);
1744 ApplyDefaultSearchChange(data
, source
);
1747 void TemplateURLService::ApplyDefaultSearchChange(
1748 const TemplateURLData
* data
,
1749 DefaultSearchManager::Source source
) {
1750 if (!ApplyDefaultSearchChangeNoMetrics(data
, source
))
1753 UMA_HISTOGRAM_ENUMERATION(
1754 "Search.DefaultSearchChangeOrigin", dsp_change_origin_
, DSP_CHANGE_MAX
);
1756 if (GetDefaultSearchProvider() &&
1757 GetDefaultSearchProvider()->HasGoogleBaseURLs(search_terms_data()) &&
1758 !dsp_change_callback_
.is_null())
1759 dsp_change_callback_
.Run();
1762 bool TemplateURLService::ApplyDefaultSearchChangeNoMetrics(
1763 const TemplateURLData
* data
,
1764 DefaultSearchManager::Source source
) {
1766 // Set |initial_default_search_provider_| from the preferences. This is
1767 // mainly so we can hold ownership until we get to the point where the list
1768 // of keywords from Web Data is the owner of everything including the
1770 bool changed
= TemplateURL::MatchesData(
1771 initial_default_search_provider_
.get(), data
, search_terms_data());
1772 initial_default_search_provider_
.reset(
1773 data
? new TemplateURL(*data
) : NULL
);
1774 default_search_provider_source_
= source
;
1778 // Prevent recursion if we update the value stored in default_search_manager_.
1779 // Note that we exclude the case of data == NULL because that could cause a
1780 // false positive for recursion when the initial_default_search_provider_ is
1781 // NULL due to policy. We'll never actually get recursion with data == NULL.
1782 if (source
== default_search_provider_source_
&& data
!= NULL
&&
1783 TemplateURL::MatchesData(default_search_provider_
, data
,
1784 search_terms_data()))
1787 // This may be deleted later. Use exclusively for pointer comparison to detect
1789 TemplateURL
* previous_default_search_engine
= default_search_provider_
;
1791 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1792 if (default_search_provider_source_
== DefaultSearchManager::FROM_POLICY
||
1793 source
== DefaultSearchManager::FROM_POLICY
) {
1794 // We do this both to remove any no-longer-applicable policy-defined DSE as
1795 // well as to add the new one, if appropriate.
1796 UpdateProvidersCreatedByPolicy(
1798 source
== DefaultSearchManager::FROM_POLICY
? data
: NULL
);
1802 default_search_provider_
= NULL
;
1803 } else if (source
== DefaultSearchManager::FROM_EXTENSION
) {
1804 default_search_provider_
= FindMatchingExtensionTemplateURL(
1805 *data
, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
);
1806 } else if (source
== DefaultSearchManager::FROM_FALLBACK
) {
1807 default_search_provider_
=
1808 FindPrepopulatedTemplateURL(data
->prepopulate_id
);
1809 if (default_search_provider_
) {
1810 TemplateURLData
update_data(*data
);
1811 update_data
.sync_guid
= default_search_provider_
->sync_guid();
1812 if (!default_search_provider_
->safe_for_autoreplace()) {
1813 update_data
.safe_for_autoreplace
= false;
1814 update_data
.SetKeyword(default_search_provider_
->keyword());
1815 update_data
.short_name
= default_search_provider_
->short_name();
1817 UpdateNoNotify(default_search_provider_
, TemplateURL(update_data
));
1819 // Normally the prepopulated fallback should be present in
1820 // |template_urls_|, but in a few cases it might not be:
1821 // (1) Tests that initialize the TemplateURLService in peculiar ways.
1822 // (2) If the user deleted the pre-populated default and we subsequently
1823 // lost their user-selected value.
1824 TemplateURL
* new_dse
= new TemplateURL(*data
);
1825 if (AddNoNotify(new_dse
, true))
1826 default_search_provider_
= new_dse
;
1828 } else if (source
== DefaultSearchManager::FROM_USER
) {
1829 default_search_provider_
= GetTemplateURLForGUID(data
->sync_guid
);
1830 if (!default_search_provider_
&& data
->prepopulate_id
) {
1831 default_search_provider_
=
1832 FindPrepopulatedTemplateURL(data
->prepopulate_id
);
1834 TemplateURLData
new_data(*data
);
1835 new_data
.show_in_default_list
= true;
1836 if (default_search_provider_
) {
1837 UpdateNoNotify(default_search_provider_
, TemplateURL(new_data
));
1839 new_data
.id
= kInvalidTemplateURLID
;
1840 TemplateURL
* new_dse
= new TemplateURL(new_data
);
1841 if (AddNoNotify(new_dse
, true))
1842 default_search_provider_
= new_dse
;
1844 if (default_search_provider_
&& prefs_
) {
1845 prefs_
->SetString(prefs::kSyncedDefaultSearchProviderGUID
,
1846 default_search_provider_
->sync_guid());
1851 default_search_provider_source_
= source
;
1853 bool changed
= default_search_provider_
!= previous_default_search_engine
;
1855 RequestGoogleURLTrackerServerCheckIfNecessary();
1862 bool TemplateURLService::AddNoNotify(TemplateURL
* template_url
,
1863 bool newly_adding
) {
1864 DCHECK(template_url
);
1867 DCHECK_EQ(kInvalidTemplateURLID
, template_url
->id());
1868 DCHECK(std::find(template_urls_
.begin(), template_urls_
.end(),
1869 template_url
) == template_urls_
.end());
1870 template_url
->data_
.id
= ++next_id_
;
1873 template_url
->ResetKeywordIfNecessary(search_terms_data(), false);
1874 // Check whether |template_url|'s keyword conflicts with any already in the
1876 TemplateURL
* existing_keyword_turl
=
1877 GetTemplateURLForKeyword(template_url
->keyword());
1879 // Check whether |template_url|'s keyword conflicts with any already in the
1880 // model. Note that we can reach here during the loading phase while
1881 // processing the template URLs from the web data service. In this case,
1882 // GetTemplateURLForKeyword() will look not only at what's already in the
1883 // model, but at the |initial_default_search_provider_|. Since this engine
1884 // will presumably also be present in the web data, we need to double-check
1885 // that any "pre-existing" entries we find are actually coming from
1886 // |template_urls_|, lest we detect a "conflict" between the
1887 // |initial_default_search_provider_| and the web data version of itself.
1888 if (template_url
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
&&
1889 existing_keyword_turl
&&
1890 existing_keyword_turl
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
&&
1891 (std::find(template_urls_
.begin(), template_urls_
.end(),
1892 existing_keyword_turl
) != template_urls_
.end())) {
1893 DCHECK_NE(existing_keyword_turl
, template_url
);
1894 // Only replace one of the TemplateURLs if they are either both extensions,
1895 // or both not extensions.
1896 bool are_same_type
= existing_keyword_turl
->GetType() ==
1897 template_url
->GetType();
1898 if (CanReplace(existing_keyword_turl
) && are_same_type
) {
1899 RemoveNoNotify(existing_keyword_turl
);
1900 } else if (CanReplace(template_url
) && are_same_type
) {
1901 delete template_url
;
1904 base::string16 new_keyword
=
1905 UniquifyKeyword(*existing_keyword_turl
, false);
1906 ResetTemplateURLNoNotify(existing_keyword_turl
,
1907 existing_keyword_turl
->short_name(), new_keyword
,
1908 existing_keyword_turl
->url());
1911 template_urls_
.push_back(template_url
);
1912 AddToMaps(template_url
);
1915 (template_url
->GetType() == TemplateURL::NORMAL
)) {
1916 if (web_data_service_
.get())
1917 web_data_service_
->AddKeyword(template_url
->data());
1919 // Inform sync of the addition. Note that this will assign a GUID to
1920 // template_url and add it to the guid_to_template_map_.
1921 ProcessTemplateURLChange(FROM_HERE
,
1923 syncer::SyncChange::ACTION_ADD
);
1929 void TemplateURLService::RemoveNoNotify(TemplateURL
* template_url
) {
1930 DCHECK(template_url
!= default_search_provider_
);
1932 TemplateURLVector::iterator i
=
1933 std::find(template_urls_
.begin(), template_urls_
.end(), template_url
);
1934 if (i
== template_urls_
.end())
1937 RemoveFromMaps(template_url
);
1939 // Remove it from the vector containing all TemplateURLs.
1940 template_urls_
.erase(i
);
1942 if (template_url
->GetType() == TemplateURL::NORMAL
) {
1943 if (web_data_service_
.get())
1944 web_data_service_
->RemoveKeyword(template_url
->id());
1946 // Inform sync of the deletion.
1947 ProcessTemplateURLChange(FROM_HERE
,
1949 syncer::SyncChange::ACTION_DELETE
);
1951 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1952 DELETE_ENGINE_USER_ACTION
, DELETE_ENGINE_MAX
);
1955 if (loaded_
&& client_
)
1956 client_
->DeleteAllSearchTermsForKeyword(template_url
->id());
1958 // We own the TemplateURL and need to delete it.
1959 delete template_url
;
1962 bool TemplateURLService::ResetTemplateURLNoNotify(
1964 const base::string16
& title
,
1965 const base::string16
& keyword
,
1966 const std::string
& search_url
) {
1967 DCHECK(!keyword
.empty());
1968 DCHECK(!search_url
.empty());
1969 TemplateURLData
data(url
->data());
1970 data
.short_name
= title
;
1971 data
.SetKeyword(keyword
);
1972 if (search_url
!= data
.url()) {
1973 data
.SetURL(search_url
);
1974 // The urls have changed, reset the favicon url.
1975 data
.favicon_url
= GURL();
1977 data
.safe_for_autoreplace
= false;
1978 data
.last_modified
= clock_
->Now();
1979 return UpdateNoNotify(url
, TemplateURL(data
));
1982 void TemplateURLService::NotifyObservers() {
1986 FOR_EACH_OBSERVER(TemplateURLServiceObserver
, model_observers_
,
1987 OnTemplateURLServiceChanged());
1990 // |template_urls| are the TemplateURLs loaded from the database.
1991 // |default_from_prefs| is the default search provider from the preferences, or
1992 // NULL if the DSE is not policy-defined.
1994 // This function removes from the vector and the database all the TemplateURLs
1995 // that were set by policy, unless it is the current default search provider, in
1996 // which case it is updated with the data from prefs.
1997 void TemplateURLService::UpdateProvidersCreatedByPolicy(
1998 TemplateURLVector
* template_urls
,
1999 const TemplateURLData
* default_from_prefs
) {
2000 DCHECK(template_urls
);
2002 for (TemplateURLVector::iterator i
= template_urls
->begin();
2003 i
!= template_urls
->end(); ) {
2004 TemplateURL
* template_url
= *i
;
2005 if (template_url
->created_by_policy()) {
2006 if (default_from_prefs
&&
2007 TemplateURL::MatchesData(template_url
, default_from_prefs
,
2008 search_terms_data())) {
2009 // If the database specified a default search provider that was set
2010 // by policy, and the default search provider from the preferences
2011 // is also set by policy and they are the same, keep the entry in the
2012 // database and the |default_search_provider|.
2013 default_search_provider_
= template_url
;
2014 // Prevent us from saving any other entries, or creating a new one.
2015 default_from_prefs
= NULL
;
2020 RemoveFromMaps(template_url
);
2021 i
= template_urls
->erase(i
);
2022 if (web_data_service_
.get())
2023 web_data_service_
->RemoveKeyword(template_url
->id());
2024 delete template_url
;
2030 if (default_from_prefs
) {
2031 default_search_provider_
= NULL
;
2032 default_search_provider_source_
= DefaultSearchManager::FROM_POLICY
;
2033 TemplateURLData
new_data(*default_from_prefs
);
2034 if (new_data
.sync_guid
.empty())
2035 new_data
.sync_guid
= base::GenerateGUID();
2036 new_data
.created_by_policy
= true;
2037 TemplateURL
* new_dse
= new TemplateURL(new_data
);
2038 if (AddNoNotify(new_dse
, true))
2039 default_search_provider_
= new_dse
;
2043 void TemplateURLService::ResetTemplateURLGUID(TemplateURL
* url
,
2044 const std::string
& guid
) {
2046 DCHECK(!guid
.empty());
2048 TemplateURLData
data(url
->data());
2049 data
.sync_guid
= guid
;
2050 UpdateNoNotify(url
, TemplateURL(data
));
2053 base::string16
TemplateURLService::UniquifyKeyword(const TemplateURL
& turl
,
2057 if (!GetTemplateURLForKeyword(turl
.keyword()))
2058 return turl
.keyword();
2060 // First, try to return the generated keyword for the TemplateURL (except
2061 // for extensions, as their keywords are not associated with their URLs).
2062 GURL
gurl(turl
.url());
2063 if (gurl
.is_valid() &&
2064 (turl
.GetType() != TemplateURL::OMNIBOX_API_EXTENSION
)) {
2065 base::string16 keyword_candidate
= TemplateURL::GenerateKeyword(gurl
);
2066 if (!GetTemplateURLForKeyword(keyword_candidate
))
2067 return keyword_candidate
;
2071 // We try to uniquify the keyword by appending a special character to the end.
2072 // This is a best-effort approach where we try to preserve the original
2073 // keyword and let the user do what they will after our attempt.
2074 base::string16
keyword_candidate(turl
.keyword());
2076 keyword_candidate
.append(base::ASCIIToUTF16("_"));
2077 } while (GetTemplateURLForKeyword(keyword_candidate
));
2079 return keyword_candidate
;
2082 bool TemplateURLService::IsLocalTemplateURLBetter(
2083 const TemplateURL
* local_turl
,
2084 const TemplateURL
* sync_turl
) {
2085 DCHECK(GetTemplateURLForGUID(local_turl
->sync_guid()));
2086 return local_turl
->last_modified() > sync_turl
->last_modified() ||
2087 local_turl
->created_by_policy() ||
2088 local_turl
== GetDefaultSearchProvider();
2091 void TemplateURLService::ResolveSyncKeywordConflict(
2092 TemplateURL
* unapplied_sync_turl
,
2093 TemplateURL
* applied_sync_turl
,
2094 syncer::SyncChangeList
* change_list
) {
2096 DCHECK(unapplied_sync_turl
);
2097 DCHECK(applied_sync_turl
);
2098 DCHECK(change_list
);
2099 DCHECK_EQ(applied_sync_turl
->keyword(), unapplied_sync_turl
->keyword());
2100 DCHECK_EQ(TemplateURL::NORMAL
, applied_sync_turl
->GetType());
2102 // Both |unapplied_sync_turl| and |applied_sync_turl| are known to Sync, so
2103 // don't delete either of them. Instead, determine which is "better" and
2104 // uniquify the other one, sending an update to the server for the updated
2106 const bool applied_turl_is_better
=
2107 IsLocalTemplateURLBetter(applied_sync_turl
, unapplied_sync_turl
);
2108 TemplateURL
* loser
= applied_turl_is_better
?
2109 unapplied_sync_turl
: applied_sync_turl
;
2110 base::string16 new_keyword
= UniquifyKeyword(*loser
, false);
2111 DCHECK(!GetTemplateURLForKeyword(new_keyword
));
2112 if (applied_turl_is_better
) {
2113 // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2114 // for adding or updating unapplied_sync_turl in the local model.
2115 unapplied_sync_turl
->data_
.SetKeyword(new_keyword
);
2117 // Update |applied_sync_turl| in the local model with the new keyword.
2118 TemplateURLData
data(applied_sync_turl
->data());
2119 data
.SetKeyword(new_keyword
);
2120 if (UpdateNoNotify(applied_sync_turl
, TemplateURL(data
)))
2123 // The losing TemplateURL should have their keyword updated. Send a change to
2124 // the server to reflect this change.
2125 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*loser
);
2126 change_list
->push_back(syncer::SyncChange(FROM_HERE
,
2127 syncer::SyncChange::ACTION_UPDATE
,
2131 void TemplateURLService::MergeInSyncTemplateURL(
2132 TemplateURL
* sync_turl
,
2133 const SyncDataMap
& sync_data
,
2134 syncer::SyncChangeList
* change_list
,
2135 SyncDataMap
* local_data
,
2136 syncer::SyncMergeResult
* merge_result
) {
2138 DCHECK(!GetTemplateURLForGUID(sync_turl
->sync_guid()));
2139 DCHECK(IsFromSync(sync_turl
, sync_data
));
2141 TemplateURL
* conflicting_turl
=
2142 FindNonExtensionTemplateURLForKeyword(sync_turl
->keyword());
2143 bool should_add_sync_turl
= true;
2145 // If there was no TemplateURL in the local model that conflicts with
2146 // |sync_turl|, skip the following preparation steps and just add |sync_turl|
2147 // directly. Otherwise, modify |conflicting_turl| to make room for
2149 if (conflicting_turl
) {
2150 if (IsFromSync(conflicting_turl
, sync_data
)) {
2151 // |conflicting_turl| is already known to Sync, so we're not allowed to
2152 // remove it. In this case, we want to uniquify the worse one and send an
2153 // update for the changed keyword to sync. We can reuse the logic from
2154 // ResolveSyncKeywordConflict for this.
2155 ResolveSyncKeywordConflict(sync_turl
, conflicting_turl
, change_list
);
2156 merge_result
->set_num_items_modified(
2157 merge_result
->num_items_modified() + 1);
2159 // |conflicting_turl| is not yet known to Sync. If it is better, then we
2160 // want to transfer its values up to sync. Otherwise, we remove it and
2161 // allow the entry from Sync to overtake it in the model.
2162 const std::string guid
= conflicting_turl
->sync_guid();
2163 if (IsLocalTemplateURLBetter(conflicting_turl
, sync_turl
)) {
2164 ResetTemplateURLGUID(conflicting_turl
, sync_turl
->sync_guid());
2165 syncer::SyncData sync_data
=
2166 CreateSyncDataFromTemplateURL(*conflicting_turl
);
2167 change_list
->push_back(syncer::SyncChange(
2168 FROM_HERE
, syncer::SyncChange::ACTION_UPDATE
, sync_data
));
2169 // Note that in this case we do not add the Sync TemplateURL to the
2170 // local model, since we've effectively "merged" it in by updating the
2171 // local conflicting entry with its sync_guid.
2172 should_add_sync_turl
= false;
2173 merge_result
->set_num_items_modified(
2174 merge_result
->num_items_modified() + 1);
2176 // We guarantee that this isn't the local search provider. Otherwise,
2177 // local would have won.
2178 DCHECK(conflicting_turl
!= GetDefaultSearchProvider());
2179 Remove(conflicting_turl
);
2180 merge_result
->set_num_items_deleted(
2181 merge_result
->num_items_deleted() + 1);
2183 // This TemplateURL was either removed or overwritten in the local model.
2184 // Remove the entry from the local data so it isn't pushed up to Sync.
2185 local_data
->erase(guid
);
2189 if (should_add_sync_turl
) {
2190 // Force the local ID to kInvalidTemplateURLID so we can add it.
2191 TemplateURLData
data(sync_turl
->data());
2192 data
.id
= kInvalidTemplateURLID
;
2193 TemplateURL
* added
= new TemplateURL(data
);
2194 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2195 &dsp_change_origin_
, DSP_CHANGE_SYNC_ADD
);
2197 MaybeUpdateDSEAfterSync(added
);
2198 merge_result
->set_num_items_added(
2199 merge_result
->num_items_added() + 1);
2203 void TemplateURLService::PatchMissingSyncGUIDs(
2204 TemplateURLVector
* template_urls
) {
2205 DCHECK(template_urls
);
2206 for (TemplateURLVector::iterator i
= template_urls
->begin();
2207 i
!= template_urls
->end(); ++i
) {
2208 TemplateURL
* template_url
= *i
;
2209 DCHECK(template_url
);
2210 if (template_url
->sync_guid().empty() &&
2211 (template_url
->GetType() == TemplateURL::NORMAL
)) {
2212 template_url
->data_
.sync_guid
= base::GenerateGUID();
2213 if (web_data_service_
.get())
2214 web_data_service_
->UpdateKeyword(template_url
->data());
2219 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
2220 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2221 &dsp_change_origin_
, DSP_CHANGE_SYNC_PREF
);
2223 std::string new_guid
=
2224 prefs_
->GetString(prefs::kSyncedDefaultSearchProviderGUID
);
2225 if (new_guid
.empty()) {
2226 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
2230 TemplateURL
* turl
= GetTemplateURLForGUID(new_guid
);
2232 default_search_manager_
.SetUserSelectedDefaultSearchEngine(turl
->data());
2235 TemplateURL
* TemplateURLService::FindPrepopulatedTemplateURL(
2236 int prepopulated_id
) {
2237 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2238 i
!= template_urls_
.end(); ++i
) {
2239 if ((*i
)->prepopulate_id() == prepopulated_id
)
2245 TemplateURL
* TemplateURLService::FindTemplateURLForExtension(
2246 const std::string
& extension_id
,
2247 TemplateURL::Type type
) {
2248 DCHECK_NE(TemplateURL::NORMAL
, type
);
2249 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2250 i
!= template_urls_
.end(); ++i
) {
2251 if ((*i
)->GetType() == type
&&
2252 (*i
)->GetExtensionId() == extension_id
)
2258 TemplateURL
* TemplateURLService::FindMatchingExtensionTemplateURL(
2259 const TemplateURLData
& data
,
2260 TemplateURL::Type type
) {
2261 DCHECK_NE(TemplateURL::NORMAL
, type
);
2262 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2263 i
!= template_urls_
.end(); ++i
) {
2264 if ((*i
)->GetType() == type
&&
2265 TemplateURL::MatchesData(*i
, &data
, search_terms_data()))
2271 void TemplateURLService::UpdateExtensionDefaultSearchEngine() {
2272 TemplateURL
* most_recently_intalled_default
= NULL
;
2273 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2274 i
!= template_urls_
.end(); ++i
) {
2275 if (((*i
)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
) &&
2276 (*i
)->extension_info_
->wants_to_be_default_engine
&&
2277 (*i
)->SupportsReplacement(search_terms_data()) &&
2278 (!most_recently_intalled_default
||
2279 (most_recently_intalled_default
->extension_info_
->install_time
<
2280 (*i
)->extension_info_
->install_time
)))
2281 most_recently_intalled_default
= *i
;
2284 if (most_recently_intalled_default
) {
2285 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2286 &dsp_change_origin_
, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION
);
2287 default_search_manager_
.SetExtensionControlledDefaultSearchEngine(
2288 most_recently_intalled_default
->data());
2290 default_search_manager_
.ClearExtensionControlledDefaultSearchEngine();