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/stl_util.h"
19 #include "base/strings/string_number_conversions.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/time.h"
24 #include "components/rappor/rappor_service.h"
25 #include "components/search_engines/search_engines_pref_names.h"
26 #include "components/search_engines/search_host_to_urls_map.h"
27 #include "components/search_engines/search_terms_data.h"
28 #include "components/search_engines/template_url.h"
29 #include "components/search_engines/template_url_prepopulate_data.h"
30 #include "components/search_engines/template_url_service_client.h"
31 #include "components/search_engines/template_url_service_observer.h"
32 #include "components/search_engines/util.h"
33 #include "components/url_fixer/url_fixer.h"
34 #include "net/base/net_util.h"
35 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
36 #include "sync/api/sync_change.h"
37 #include "sync/api/sync_error_factory.h"
38 #include "sync/protocol/search_engine_specifics.pb.h"
39 #include "sync/protocol/sync.pb.h"
42 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet
;
43 typedef TemplateURLService::SyncDataMap SyncDataMap
;
47 bool IdenticalSyncGUIDs(const TemplateURLData
* data
, const TemplateURL
* turl
) {
49 return !data
&& !turl
;
51 return data
->sync_guid
== turl
->sync_guid();
54 const char kDeleteSyncedEngineHistogramName
[] =
55 "Search.DeleteSyncedSearchEngine";
57 // Values for an enumerated histogram used to track whenever an ACTION_DELETE is
58 // sent to the server for search engines.
59 enum DeleteSyncedSearchEngineEvent
{
60 DELETE_ENGINE_USER_ACTION
,
61 DELETE_ENGINE_PRE_SYNC
,
62 DELETE_ENGINE_EMPTY_FIELD
,
66 // Returns true iff the change in |change_list| at index |i| should not be sent
67 // up to the server based on its GUIDs presence in |sync_data| or when compared
68 // to changes after it in |change_list|.
70 // 1) It is an ACTION_UPDATE or ACTION_DELETE and the sync_guid associated
71 // with it is NOT found in |sync_data|. We can only update and remove
72 // entries that were originally from the Sync server.
73 // 2) It is an ACTION_ADD and the sync_guid associated with it is found in
74 // |sync_data|. We cannot re-add entries that Sync already knew about.
75 // 3) There is an update after an update for the same GUID. We prune earlier
76 // ones just to save bandwidth (Sync would normally coalesce them).
77 bool ShouldRemoveSyncChange(size_t index
,
78 syncer::SyncChangeList
* change_list
,
79 const SyncDataMap
* sync_data
) {
80 DCHECK(index
< change_list
->size());
81 const syncer::SyncChange
& change_i
= (*change_list
)[index
];
82 const std::string guid
= change_i
.sync_data().GetSpecifics()
83 .search_engine().sync_guid();
84 syncer::SyncChange::SyncChangeType type
= change_i
.change_type();
85 if ((type
== syncer::SyncChange::ACTION_UPDATE
||
86 type
== syncer::SyncChange::ACTION_DELETE
) &&
87 sync_data
->find(guid
) == sync_data
->end())
89 if (type
== syncer::SyncChange::ACTION_ADD
&&
90 sync_data
->find(guid
) != sync_data
->end())
92 if (type
== syncer::SyncChange::ACTION_UPDATE
) {
93 for (size_t j
= index
+ 1; j
< change_list
->size(); j
++) {
94 const syncer::SyncChange
& change_j
= (*change_list
)[j
];
95 if ((syncer::SyncChange::ACTION_UPDATE
== change_j
.change_type()) &&
96 (change_j
.sync_data().GetSpecifics().search_engine().sync_guid() ==
104 // Remove SyncChanges that should not be sent to the server from |change_list|.
105 // This is done to eliminate incorrect SyncChanges added by the merge and
106 // conflict resolution logic when it is unsure of whether or not an entry is new
107 // from Sync or originally from the local model. This also removes changes that
108 // would be otherwise be coalesced by Sync in order to save bandwidth.
109 void PruneSyncChanges(const SyncDataMap
* sync_data
,
110 syncer::SyncChangeList
* change_list
) {
111 for (size_t i
= 0; i
< change_list
->size(); ) {
112 if (ShouldRemoveSyncChange(i
, change_list
, sync_data
))
113 change_list
->erase(change_list
->begin() + i
);
119 // Returns true if |turl|'s GUID is not found inside |sync_data|. This is to be
120 // used in MergeDataAndStartSyncing to differentiate between TemplateURLs from
121 // Sync and TemplateURLs that were initially local, assuming |sync_data| is the
122 // |initial_sync_data| parameter.
123 bool IsFromSync(const TemplateURL
* turl
, const SyncDataMap
& sync_data
) {
124 return !!sync_data
.count(turl
->sync_guid());
127 // Log the number of instances of a keyword that exist, with zero or more
128 // underscores, which could occur as the result of conflict resolution.
129 void LogDuplicatesHistogram(
130 const TemplateURLService::TemplateURLVector
& template_urls
) {
131 std::map
<std::string
, int> duplicates
;
132 for (TemplateURLService::TemplateURLVector::const_iterator it
=
133 template_urls
.begin(); it
!= template_urls
.end(); ++it
) {
134 std::string keyword
= base::UTF16ToASCII((*it
)->keyword());
135 base::TrimString(keyword
, "_", &keyword
);
136 duplicates
[keyword
]++;
139 // Count the keywords with duplicates.
141 for (std::map
<std::string
, int>::const_iterator it
= duplicates
.begin();
142 it
!= duplicates
.end(); ++it
) {
147 UMA_HISTOGRAM_COUNTS_100("Search.SearchEngineDuplicateCounts", num_dupes
);
153 // TemplateURLService::LessWithPrefix -----------------------------------------
155 class TemplateURLService::LessWithPrefix
{
157 // We want to find the set of keywords that begin with a prefix. The STL
158 // algorithms will return the set of elements that are "equal to" the
159 // prefix, where "equal(x, y)" means "!(cmp(x, y) || cmp(y, x))". When
160 // cmp() is the typical std::less<>, this results in lexicographic equality;
161 // we need to extend this to mark a prefix as "not less than" a keyword it
162 // begins, which will cause the desired elements to be considered "equal to"
163 // the prefix. Note: this is still a strict weak ordering, as required by
164 // equal_range() (though I will not prove that here).
166 // Unfortunately the calling convention is not "prefix and element" but
167 // rather "two elements", so we pass the prefix as a fake "element" which has
168 // a NULL KeywordDataElement pointer.
169 bool operator()(const KeywordToTemplateMap::value_type
& elem1
,
170 const KeywordToTemplateMap::value_type
& elem2
) const {
171 return (elem1
.second
== NULL
) ?
172 (elem2
.first
.compare(0, elem1
.first
.length(), elem1
.first
) > 0) :
173 (elem1
.first
< elem2
.first
);
178 // TemplateURLService ---------------------------------------------------------
180 TemplateURLService::TemplateURLService(
182 scoped_ptr
<SearchTermsData
> search_terms_data
,
183 KeywordWebDataService
* web_data_service
,
184 scoped_ptr
<TemplateURLServiceClient
> client
,
185 GoogleURLTracker
* google_url_tracker
,
186 rappor::RapporService
* rappor_service
,
187 const base::Closure
& dsp_change_callback
)
189 search_terms_data_(search_terms_data
.Pass()),
190 web_data_service_(web_data_service
),
191 client_(client
.Pass()),
192 google_url_tracker_(google_url_tracker
),
193 rappor_service_(rappor_service
),
194 dsp_change_callback_(dsp_change_callback
),
195 provider_map_(new SearchHostToURLsMap
),
199 default_search_provider_(NULL
),
200 next_id_(kInvalidTemplateURLID
+ 1),
201 time_provider_(&base::Time::Now
),
202 models_associated_(false),
203 processing_syncer_changes_(false),
204 dsp_change_origin_(DSP_CHANGE_OTHER
),
205 default_search_manager_(
207 base::Bind(&TemplateURLService::OnDefaultSearchChange
,
208 base::Unretained(this))) {
209 DCHECK(search_terms_data_
);
213 TemplateURLService::TemplateURLService(const Initializer
* initializers
,
216 search_terms_data_(new SearchTermsData
),
217 web_data_service_(NULL
),
218 google_url_tracker_(NULL
),
219 rappor_service_(NULL
),
220 provider_map_(new SearchHostToURLsMap
),
224 default_search_provider_(NULL
),
225 next_id_(kInvalidTemplateURLID
+ 1),
226 time_provider_(&base::Time::Now
),
227 models_associated_(false),
228 processing_syncer_changes_(false),
229 dsp_change_origin_(DSP_CHANGE_OTHER
),
230 default_search_manager_(
232 base::Bind(&TemplateURLService::OnDefaultSearchChange
,
233 base::Unretained(this))) {
234 Init(initializers
, count
);
237 TemplateURLService::~TemplateURLService() {
238 // |web_data_service_| should be deleted during Shutdown().
239 DCHECK(!web_data_service_
.get());
240 STLDeleteElements(&template_urls_
);
244 bool TemplateURLService::LoadDefaultSearchProviderFromPrefs(
246 scoped_ptr
<TemplateURLData
>* default_provider_data
,
248 if (!prefs
|| !prefs
->HasPrefPath(prefs::kDefaultSearchProviderSearchURL
) ||
249 !prefs
->HasPrefPath(prefs::kDefaultSearchProviderKeyword
))
252 const PrefService::Preference
* pref
=
253 prefs
->FindPreference(prefs::kDefaultSearchProviderSearchURL
);
254 *is_managed
= pref
&& pref
->IsManaged();
256 if (!prefs
->GetBoolean(prefs::kDefaultSearchProviderEnabled
)) {
257 // The user doesn't want a default search provider.
258 default_provider_data
->reset(NULL
);
262 base::string16 name
=
263 base::UTF8ToUTF16(prefs
->GetString(prefs::kDefaultSearchProviderName
));
264 base::string16 keyword
=
265 base::UTF8ToUTF16(prefs
->GetString(prefs::kDefaultSearchProviderKeyword
));
268 std::string search_url
=
269 prefs
->GetString(prefs::kDefaultSearchProviderSearchURL
);
270 // Force URL to be non-empty. We've never supported this case, but past bugs
271 // might have resulted in it slipping through; eventually this code can be
272 // replaced with a DCHECK(!search_url.empty());.
273 if (search_url
.empty())
275 std::string suggest_url
=
276 prefs
->GetString(prefs::kDefaultSearchProviderSuggestURL
);
277 std::string instant_url
=
278 prefs
->GetString(prefs::kDefaultSearchProviderInstantURL
);
279 std::string image_url
=
280 prefs
->GetString(prefs::kDefaultSearchProviderImageURL
);
281 std::string new_tab_url
=
282 prefs
->GetString(prefs::kDefaultSearchProviderNewTabURL
);
283 std::string search_url_post_params
=
284 prefs
->GetString(prefs::kDefaultSearchProviderSearchURLPostParams
);
285 std::string suggest_url_post_params
=
286 prefs
->GetString(prefs::kDefaultSearchProviderSuggestURLPostParams
);
287 std::string instant_url_post_params
=
288 prefs
->GetString(prefs::kDefaultSearchProviderInstantURLPostParams
);
289 std::string image_url_post_params
=
290 prefs
->GetString(prefs::kDefaultSearchProviderImageURLPostParams
);
291 std::string icon_url
=
292 prefs
->GetString(prefs::kDefaultSearchProviderIconURL
);
293 std::string encodings
=
294 prefs
->GetString(prefs::kDefaultSearchProviderEncodings
);
295 std::string id_string
= prefs
->GetString(prefs::kDefaultSearchProviderID
);
296 std::string prepopulate_id
=
297 prefs
->GetString(prefs::kDefaultSearchProviderPrepopulateID
);
298 const base::ListValue
* alternate_urls
=
299 prefs
->GetList(prefs::kDefaultSearchProviderAlternateURLs
);
300 std::string search_terms_replacement_key
= prefs
->GetString(
301 prefs::kDefaultSearchProviderSearchTermsReplacementKey
);
303 default_provider_data
->reset(new TemplateURLData
);
304 (*default_provider_data
)->short_name
= name
;
305 (*default_provider_data
)->SetKeyword(keyword
);
306 (*default_provider_data
)->SetURL(search_url
);
307 (*default_provider_data
)->suggestions_url
= suggest_url
;
308 (*default_provider_data
)->instant_url
= instant_url
;
309 (*default_provider_data
)->image_url
= image_url
;
310 (*default_provider_data
)->new_tab_url
= new_tab_url
;
311 (*default_provider_data
)->search_url_post_params
= search_url_post_params
;
312 (*default_provider_data
)->suggestions_url_post_params
=
313 suggest_url_post_params
;
314 (*default_provider_data
)->instant_url_post_params
= instant_url_post_params
;
315 (*default_provider_data
)->image_url_post_params
= image_url_post_params
;
316 (*default_provider_data
)->favicon_url
= GURL(icon_url
);
317 (*default_provider_data
)->show_in_default_list
= true;
318 (*default_provider_data
)->alternate_urls
.clear();
319 for (size_t i
= 0; i
< alternate_urls
->GetSize(); ++i
) {
320 std::string alternate_url
;
321 if (alternate_urls
->GetString(i
, &alternate_url
))
322 (*default_provider_data
)->alternate_urls
.push_back(alternate_url
);
324 (*default_provider_data
)->search_terms_replacement_key
=
325 search_terms_replacement_key
;
326 base::SplitString(encodings
, ';', &(*default_provider_data
)->input_encodings
);
327 if (!id_string
.empty() && !*is_managed
) {
329 base::StringToInt64(id_string
, &value
);
330 (*default_provider_data
)->id
= value
;
332 if (!prepopulate_id
.empty() && !*is_managed
) {
334 base::StringToInt(prepopulate_id
, &value
);
335 (*default_provider_data
)->prepopulate_id
= value
;
341 base::string16
TemplateURLService::CleanUserInputKeyword(
342 const base::string16
& keyword
) {
343 // Remove the scheme.
344 base::string16
result(base::i18n::ToLower(keyword
));
345 base::TrimWhitespace(result
, base::TRIM_ALL
, &result
);
346 url::Component scheme_component
;
347 if (url::ExtractScheme(base::UTF16ToUTF8(keyword
).c_str(),
348 static_cast<int>(keyword
.length()),
349 &scheme_component
)) {
350 // If the scheme isn't "http" or "https", bail. The user isn't trying to
351 // type a web address, but rather an FTP, file:, or other scheme URL, or a
352 // search query with some sort of initial operator (e.g. "site:").
353 if (result
.compare(0, scheme_component
.end(),
354 base::ASCIIToUTF16(url::kHttpScheme
)) &&
355 result
.compare(0, scheme_component
.end(),
356 base::ASCIIToUTF16(url::kHttpsScheme
)))
357 return base::string16();
359 // Include trailing ':'.
360 result
.erase(0, scheme_component
.end() + 1);
361 // Many schemes usually have "//" after them, so strip it too.
362 const base::string16
after_scheme(base::ASCIIToUTF16("//"));
363 if (result
.compare(0, after_scheme
.length(), after_scheme
) == 0)
364 result
.erase(0, after_scheme
.length());
367 // Remove leading "www.".
368 result
= net::StripWWW(result
);
370 // Remove trailing "/".
371 return (result
.length() > 0 && result
[result
.length() - 1] == '/') ?
372 result
.substr(0, result
.length() - 1) : result
;
376 void TemplateURLService::SaveDefaultSearchProviderToPrefs(
377 const TemplateURL
* t_url
,
378 PrefService
* prefs
) {
382 bool enabled
= false;
383 std::string search_url
;
384 std::string suggest_url
;
385 std::string instant_url
;
386 std::string image_url
;
387 std::string new_tab_url
;
388 std::string search_url_post_params
;
389 std::string suggest_url_post_params
;
390 std::string instant_url_post_params
;
391 std::string image_url_post_params
;
392 std::string icon_url
;
393 std::string encodings
;
394 std::string short_name
;
396 std::string id_string
;
397 std::string prepopulate_id
;
398 base::ListValue alternate_urls
;
399 std::string search_terms_replacement_key
;
401 DCHECK_EQ(TemplateURL::NORMAL
, t_url
->GetType());
403 search_url
= t_url
->url();
404 suggest_url
= t_url
->suggestions_url();
405 instant_url
= t_url
->instant_url();
406 image_url
= t_url
->image_url();
407 new_tab_url
= t_url
->new_tab_url();
408 search_url_post_params
= t_url
->search_url_post_params();
409 suggest_url_post_params
= t_url
->suggestions_url_post_params();
410 instant_url_post_params
= t_url
->instant_url_post_params();
411 image_url_post_params
= t_url
->image_url_post_params();
412 GURL icon_gurl
= t_url
->favicon_url();
413 if (!icon_gurl
.is_empty())
414 icon_url
= icon_gurl
.spec();
415 encodings
= JoinString(t_url
->input_encodings(), ';');
416 short_name
= base::UTF16ToUTF8(t_url
->short_name());
417 keyword
= base::UTF16ToUTF8(t_url
->keyword());
418 id_string
= base::Int64ToString(t_url
->id());
419 prepopulate_id
= base::Int64ToString(t_url
->prepopulate_id());
420 for (size_t i
= 0; i
< t_url
->alternate_urls().size(); ++i
)
421 alternate_urls
.AppendString(t_url
->alternate_urls()[i
]);
422 search_terms_replacement_key
= t_url
->search_terms_replacement_key();
424 prefs
->SetBoolean(prefs::kDefaultSearchProviderEnabled
, enabled
);
425 prefs
->SetString(prefs::kDefaultSearchProviderSearchURL
, search_url
);
426 prefs
->SetString(prefs::kDefaultSearchProviderSuggestURL
, suggest_url
);
427 prefs
->SetString(prefs::kDefaultSearchProviderInstantURL
, instant_url
);
428 prefs
->SetString(prefs::kDefaultSearchProviderImageURL
, image_url
);
429 prefs
->SetString(prefs::kDefaultSearchProviderNewTabURL
, new_tab_url
);
430 prefs
->SetString(prefs::kDefaultSearchProviderSearchURLPostParams
,
431 search_url_post_params
);
432 prefs
->SetString(prefs::kDefaultSearchProviderSuggestURLPostParams
,
433 suggest_url_post_params
);
434 prefs
->SetString(prefs::kDefaultSearchProviderInstantURLPostParams
,
435 instant_url_post_params
);
436 prefs
->SetString(prefs::kDefaultSearchProviderImageURLPostParams
,
437 image_url_post_params
);
438 prefs
->SetString(prefs::kDefaultSearchProviderIconURL
, icon_url
);
439 prefs
->SetString(prefs::kDefaultSearchProviderEncodings
, encodings
);
440 prefs
->SetString(prefs::kDefaultSearchProviderName
, short_name
);
441 prefs
->SetString(prefs::kDefaultSearchProviderKeyword
, keyword
);
442 prefs
->SetString(prefs::kDefaultSearchProviderID
, id_string
);
443 prefs
->SetString(prefs::kDefaultSearchProviderPrepopulateID
, prepopulate_id
);
444 prefs
->Set(prefs::kDefaultSearchProviderAlternateURLs
, alternate_urls
);
445 prefs
->SetString(prefs::kDefaultSearchProviderSearchTermsReplacementKey
,
446 search_terms_replacement_key
);
449 bool TemplateURLService::CanReplaceKeyword(
450 const base::string16
& keyword
,
452 TemplateURL
** template_url_to_replace
) {
453 DCHECK(!keyword
.empty()); // This should only be called for non-empty
454 // keywords. If we need to support empty kewords
455 // the code needs to change slightly.
456 TemplateURL
* existing_url
= GetTemplateURLForKeyword(keyword
);
457 if (template_url_to_replace
)
458 *template_url_to_replace
= existing_url
;
460 // We already have a TemplateURL for this keyword. Only allow it to be
461 // replaced if the TemplateURL can be replaced.
462 return CanReplace(existing_url
);
465 // We don't have a TemplateURL with keyword. Only allow a new one if there
466 // isn't a TemplateURL for the specified host, or there is one but it can
467 // be replaced. We do this to ensure that if the user assigns a different
468 // keyword to a generated TemplateURL, we won't regenerate another keyword for
470 return !url
.is_valid() || url
.host().empty() ||
471 CanReplaceKeywordForHost(url
.host(), template_url_to_replace
);
474 void TemplateURLService::FindMatchingKeywords(
475 const base::string16
& prefix
,
476 bool support_replacement_only
,
477 TemplateURLVector
* matches
) {
478 // Sanity check args.
481 DCHECK(matches
!= NULL
);
482 DCHECK(matches
->empty()); // The code for exact matches assumes this.
484 // Required for VS2010: http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
485 TemplateURL
* const kNullTemplateURL
= NULL
;
487 // Find matching keyword range. Searches the element map for keywords
488 // beginning with |prefix| and stores the endpoints of the resulting set in
490 const std::pair
<KeywordToTemplateMap::const_iterator
,
491 KeywordToTemplateMap::const_iterator
> match_range(
493 keyword_to_template_map_
.begin(), keyword_to_template_map_
.end(),
494 KeywordToTemplateMap::value_type(prefix
, kNullTemplateURL
),
497 // Return vector of matching keywords.
498 for (KeywordToTemplateMap::const_iterator
i(match_range
.first
);
499 i
!= match_range
.second
; ++i
) {
500 if (!support_replacement_only
||
501 i
->second
->url_ref().SupportsReplacement(search_terms_data()))
502 matches
->push_back(i
->second
);
506 TemplateURL
* TemplateURLService::GetTemplateURLForKeyword(
507 const base::string16
& keyword
) {
508 KeywordToTemplateMap::const_iterator
elem(
509 keyword_to_template_map_
.find(keyword
));
510 if (elem
!= keyword_to_template_map_
.end())
513 initial_default_search_provider_
.get() &&
514 (initial_default_search_provider_
->keyword() == keyword
)) ?
515 initial_default_search_provider_
.get() : NULL
;
518 TemplateURL
* TemplateURLService::GetTemplateURLForGUID(
519 const std::string
& sync_guid
) {
520 GUIDToTemplateMap::const_iterator
elem(guid_to_template_map_
.find(sync_guid
));
521 if (elem
!= guid_to_template_map_
.end())
524 initial_default_search_provider_
.get() &&
525 (initial_default_search_provider_
->sync_guid() == sync_guid
)) ?
526 initial_default_search_provider_
.get() : NULL
;
529 TemplateURL
* TemplateURLService::GetTemplateURLForHost(
530 const std::string
& host
) {
532 return provider_map_
->GetTemplateURLForHost(host
);
533 TemplateURL
* initial_dsp
= initial_default_search_provider_
.get();
536 return (initial_dsp
->GenerateSearchURL(search_terms_data()).host() == host
) ?
540 bool TemplateURLService::Add(TemplateURL
* template_url
) {
541 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
542 if (!AddNoNotify(template_url
, true))
548 void TemplateURLService::AddWithOverrides(TemplateURL
* template_url
,
549 const base::string16
& short_name
,
550 const base::string16
& keyword
,
551 const std::string
& url
) {
552 DCHECK(!keyword
.empty());
553 DCHECK(!url
.empty());
554 template_url
->data_
.short_name
= short_name
;
555 template_url
->data_
.SetKeyword(keyword
);
556 template_url
->SetURL(url
);
560 void TemplateURLService::AddExtensionControlledTURL(
561 TemplateURL
* template_url
,
562 scoped_ptr
<TemplateURL::AssociatedExtensionInfo
> info
) {
564 DCHECK(template_url
);
565 DCHECK_EQ(kInvalidTemplateURLID
, template_url
->id());
567 DCHECK_NE(TemplateURL::NORMAL
, info
->type
);
568 DCHECK_EQ(info
->wants_to_be_default_engine
,
569 template_url
->show_in_default_list());
570 DCHECK(!FindTemplateURLForExtension(info
->extension_id
, info
->type
));
571 template_url
->extension_info_
.swap(info
);
573 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
574 if (AddNoNotify(template_url
, true)) {
575 if (template_url
->extension_info_
->wants_to_be_default_engine
)
576 UpdateExtensionDefaultSearchEngine();
581 void TemplateURLService::Remove(TemplateURL
* template_url
) {
582 RemoveNoNotify(template_url
);
586 void TemplateURLService::RemoveExtensionControlledTURL(
587 const std::string
& extension_id
,
588 TemplateURL::Type type
) {
590 TemplateURL
* url
= FindTemplateURLForExtension(extension_id
, type
);
593 // NULL this out so that we can call RemoveNoNotify.
594 // UpdateExtensionDefaultSearchEngine will cause it to be reset.
595 if (default_search_provider_
== url
)
596 default_search_provider_
= NULL
;
597 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
599 UpdateExtensionDefaultSearchEngine();
603 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after
) {
604 RemoveAutoGeneratedBetween(created_after
, base::Time());
607 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after
,
608 base::Time created_before
) {
609 RemoveAutoGeneratedForOriginBetween(GURL(), created_after
, created_before
);
612 void TemplateURLService::RemoveAutoGeneratedForOriginBetween(
614 base::Time created_after
,
615 base::Time created_before
) {
616 GURL
o(origin
.GetOrigin());
617 bool should_notify
= false;
618 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
619 for (size_t i
= 0; i
< template_urls_
.size();) {
620 if (template_urls_
[i
]->date_created() >= created_after
&&
621 (created_before
.is_null() ||
622 template_urls_
[i
]->date_created() < created_before
) &&
623 CanReplace(template_urls_
[i
]) &&
625 template_urls_
[i
]->GenerateSearchURL(
626 search_terms_data()).GetOrigin() == o
)) {
627 RemoveNoNotify(template_urls_
[i
]);
628 should_notify
= true;
637 void TemplateURLService::RegisterOmniboxKeyword(
638 const std::string
& extension_id
,
639 const std::string
& extension_name
,
640 const std::string
& keyword
,
641 const std::string
& template_url_string
) {
644 if (FindTemplateURLForExtension(extension_id
,
645 TemplateURL::OMNIBOX_API_EXTENSION
))
648 TemplateURLData data
;
649 data
.short_name
= base::UTF8ToUTF16(extension_name
);
650 data
.SetKeyword(base::UTF8ToUTF16(keyword
));
651 data
.SetURL(template_url_string
);
652 TemplateURL
* url
= new TemplateURL(data
);
653 scoped_ptr
<TemplateURL::AssociatedExtensionInfo
> info(
654 new TemplateURL::AssociatedExtensionInfo(
655 TemplateURL::OMNIBOX_API_EXTENSION
, extension_id
));
656 AddExtensionControlledTURL(url
, info
.Pass());
659 TemplateURLService::TemplateURLVector
TemplateURLService::GetTemplateURLs() {
660 return template_urls_
;
663 void TemplateURLService::IncrementUsageCount(TemplateURL
* url
) {
665 // Extension-controlled search engines are not persisted.
666 if (url
->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
)
668 if (std::find(template_urls_
.begin(), template_urls_
.end(), url
) ==
669 template_urls_
.end())
671 ++url
->data_
.usage_count
;
673 if (web_data_service_
.get())
674 web_data_service_
->UpdateKeyword(url
->data());
677 void TemplateURLService::ResetTemplateURL(TemplateURL
* url
,
678 const base::string16
& title
,
679 const base::string16
& keyword
,
680 const std::string
& search_url
) {
681 if (ResetTemplateURLNoNotify(url
, title
, keyword
, search_url
))
685 bool TemplateURLService::CanMakeDefault(const TemplateURL
* url
) {
687 ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
688 (default_search_provider_source_
==
689 DefaultSearchManager::FROM_FALLBACK
)) &&
690 (url
!= GetDefaultSearchProvider()) &&
691 url
->url_ref().SupportsReplacement(search_terms_data()) &&
692 (url
->GetType() == TemplateURL::NORMAL
);
695 void TemplateURLService::SetUserSelectedDefaultSearchProvider(
697 // Omnibox keywords cannot be made default. Extension-controlled search
698 // engines can be made default only by the extension itself because they
700 DCHECK(!url
|| (url
->GetType() == TemplateURL::NORMAL
));
702 // Skip the DefaultSearchManager, which will persist to user preferences.
703 if ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
704 (default_search_provider_source_
==
705 DefaultSearchManager::FROM_FALLBACK
)) {
706 ApplyDefaultSearchChange(url
? &url
->data() : NULL
,
707 DefaultSearchManager::FROM_USER
);
710 // We rely on the DefaultSearchManager to call OnDefaultSearchChange if, in
711 // fact, the effective DSE changes.
713 default_search_manager_
.SetUserSelectedDefaultSearchEngine(url
->data());
715 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
719 TemplateURL
* TemplateURLService::GetDefaultSearchProvider() {
721 default_search_provider_
: initial_default_search_provider_
.get();
724 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
726 TemplateURL
* default_provider
= GetDefaultSearchProvider();
727 return default_provider
&&
728 default_provider
->IsSearchURL(url
, search_terms_data());
731 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
732 return default_search_provider_source_
==
733 DefaultSearchManager::FROM_EXTENSION
;
736 void TemplateURLService::RepairPrepopulatedSearchEngines() {
737 // Can't clean DB if it hasn't been loaded.
740 if ((default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ||
741 (default_search_provider_source_
==
742 DefaultSearchManager::FROM_FALLBACK
)) {
743 // Clear |default_search_provider_| in case we want to remove the engine it
744 // points to. This will get reset at the end of the function anyway.
745 default_search_provider_
= NULL
;
748 size_t default_search_provider_index
= 0;
749 ScopedVector
<TemplateURLData
> prepopulated_urls
=
750 TemplateURLPrepopulateData::GetPrepopulatedEngines(
751 prefs_
, &default_search_provider_index
);
752 DCHECK(!prepopulated_urls
.empty());
753 ActionsFromPrepopulateData
actions(CreateActionsFromCurrentPrepopulateData(
754 &prepopulated_urls
, template_urls_
, default_search_provider_
));
756 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
759 for (std::vector
<TemplateURL
*>::iterator i
= actions
.removed_engines
.begin();
760 i
< actions
.removed_engines
.end(); ++i
)
764 for (EditedEngines::iterator
i(actions
.edited_engines
.begin());
765 i
< actions
.edited_engines
.end(); ++i
) {
766 TemplateURL
new_values(i
->second
);
767 UpdateNoNotify(i
->first
, new_values
);
771 for (std::vector
<TemplateURLData
>::const_iterator i
=
772 actions
.added_engines
.begin();
773 i
< actions
.added_engines
.end();
775 AddNoNotify(new TemplateURL(*i
), true);
778 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
779 &dsp_change_origin_
, DSP_CHANGE_PROFILE_RESET
);
781 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
783 if (!default_search_provider_
) {
784 // If the default search provider came from a user pref we would have been
785 // notified of the new (fallback-provided) value in
786 // ClearUserSelectedDefaultSearchEngine() above. Since we are here, the
787 // value was presumably originally a fallback value (which may have been
789 DefaultSearchManager::Source source
;
790 const TemplateURLData
* new_dse
=
791 default_search_manager_
.GetDefaultSearchEngine(&source
);
792 // ApplyDefaultSearchChange will notify observers once it is done.
793 ApplyDefaultSearchChange(new_dse
, source
);
799 void TemplateURLService::AddObserver(TemplateURLServiceObserver
* observer
) {
800 model_observers_
.AddObserver(observer
);
803 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver
* observer
) {
804 model_observers_
.RemoveObserver(observer
);
807 void TemplateURLService::Load() {
808 if (loaded_
|| load_handle_
)
811 if (web_data_service_
.get())
812 load_handle_
= web_data_service_
->GetKeywords(this);
814 ChangeToLoadedState();
817 scoped_ptr
<TemplateURLService::Subscription
>
818 TemplateURLService::RegisterOnLoadedCallback(
819 const base::Closure
& callback
) {
821 scoped_ptr
<TemplateURLService::Subscription
>() :
822 on_loaded_callbacks_
.Add(callback
);
825 void TemplateURLService::OnWebDataServiceRequestDone(
826 KeywordWebDataService::Handle h
,
827 const WDTypedResult
* result
) {
828 // Reset the load_handle so that we don't try and cancel the load in
833 // Results are null if the database went away or (most likely) wasn't
836 web_data_service_
= NULL
;
837 ChangeToLoadedState();
841 TemplateURLVector template_urls
;
842 int new_resource_keyword_version
= 0;
843 GetSearchProvidersUsingKeywordResult(
845 web_data_service_
.get(),
848 (default_search_provider_source_
== DefaultSearchManager::FROM_USER
) ?
849 initial_default_search_provider_
.get() : NULL
,
851 &new_resource_keyword_version
,
855 // Restore extension info of loaded TemplateURLs.
856 for (size_t i
= 0; i
< template_urls
.size(); ++i
) {
857 DCHECK(!template_urls
[i
]->extension_info_
);
858 client_
->RestoreExtensionInfoIfNecessary(template_urls
[i
]);
862 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
864 PatchMissingSyncGUIDs(&template_urls
);
865 SetTemplateURLs(&template_urls
);
867 // This initializes provider_map_ which should be done before
868 // calling UpdateKeywordSearchTermsForURL.
869 // This also calls NotifyObservers.
870 ChangeToLoadedState();
872 // Index any visits that occurred before we finished loading.
873 for (size_t i
= 0; i
< visits_to_add_
.size(); ++i
)
874 UpdateKeywordSearchTermsForURL(visits_to_add_
[i
]);
875 visits_to_add_
.clear();
877 if (new_resource_keyword_version
)
878 web_data_service_
->SetBuiltinKeywordVersion(new_resource_keyword_version
);
880 if (default_search_provider_
) {
881 UMA_HISTOGRAM_ENUMERATION(
882 "Search.DefaultSearchProviderType",
883 TemplateURLPrepopulateData::GetEngineType(
884 *default_search_provider_
, search_terms_data()),
887 if (rappor_service_
) {
888 rappor_service_
->RecordSample(
889 "Search.DefaultSearchProvider",
890 rappor::ETLD_PLUS_ONE_RAPPOR_TYPE
,
891 net::registry_controlled_domains::GetDomainAndRegistry(
892 default_search_provider_
->url_ref().GetHost(search_terms_data()),
893 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
));
898 base::string16
TemplateURLService::GetKeywordShortName(
899 const base::string16
& keyword
,
900 bool* is_omnibox_api_extension_keyword
) {
901 const TemplateURL
* template_url
= GetTemplateURLForKeyword(keyword
);
903 // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
904 // to track changes to the model, this should become a DCHECK.
906 *is_omnibox_api_extension_keyword
=
907 template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
908 return template_url
->AdjustedShortNameForLocaleDirection();
910 *is_omnibox_api_extension_keyword
= false;
911 return base::string16();
914 void TemplateURLService::OnHistoryURLVisited(const URLVisitedDetails
& details
) {
916 visits_to_add_
.push_back(details
);
918 UpdateKeywordSearchTermsForURL(details
);
921 void TemplateURLService::Shutdown() {
922 // This check has to be done at Shutdown() instead of in the dtor to ensure
923 // that no clients of KeywordWebDataService are holding ptrs to it after the
924 // first phase of the KeyedService Shutdown() process.
926 DCHECK(web_data_service_
.get());
927 web_data_service_
->CancelRequest(load_handle_
);
929 web_data_service_
= NULL
;
932 syncer::SyncDataList
TemplateURLService::GetAllSyncData(
933 syncer::ModelType type
) const {
934 DCHECK_EQ(syncer::SEARCH_ENGINES
, type
);
936 syncer::SyncDataList current_data
;
937 for (TemplateURLVector::const_iterator iter
= template_urls_
.begin();
938 iter
!= template_urls_
.end(); ++iter
) {
939 // We don't sync keywords managed by policy.
940 if ((*iter
)->created_by_policy())
942 // We don't sync extension-controlled search engines.
943 if ((*iter
)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
)
945 current_data
.push_back(CreateSyncDataFromTemplateURL(**iter
));
951 syncer::SyncError
TemplateURLService::ProcessSyncChanges(
952 const tracked_objects::Location
& from_here
,
953 const syncer::SyncChangeList
& change_list
) {
954 if (!models_associated_
) {
955 syncer::SyncError
error(FROM_HERE
,
956 syncer::SyncError::DATATYPE_ERROR
,
957 "Models not yet associated.",
958 syncer::SEARCH_ENGINES
);
963 base::AutoReset
<bool> processing_changes(&processing_syncer_changes_
, true);
965 // We've started syncing, so set our origin member to the base Sync value.
966 // As we move through Sync Code, we may set this to increasingly specific
967 // origins so we can tell what exactly caused a DSP change.
968 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(&dsp_change_origin_
,
969 DSP_CHANGE_SYNC_UNINTENTIONAL
);
971 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
973 syncer::SyncChangeList new_changes
;
974 syncer::SyncError error
;
975 for (syncer::SyncChangeList::const_iterator iter
= change_list
.begin();
976 iter
!= change_list
.end(); ++iter
) {
977 DCHECK_EQ(syncer::SEARCH_ENGINES
, iter
->sync_data().GetDataType());
980 iter
->sync_data().GetSpecifics().search_engine().sync_guid();
981 TemplateURL
* existing_turl
= GetTemplateURLForGUID(guid
);
982 scoped_ptr
<TemplateURL
> turl(CreateTemplateURLFromTemplateURLAndSyncData(
983 prefs_
, search_terms_data(), existing_turl
, iter
->sync_data(),
988 // Explicitly don't check for conflicts against extension keywords; in this
989 // case the functions which modify the keyword map know how to handle the
991 // TODO(mpcomplete): If we allow editing extension keywords, then those will
992 // need to undergo conflict resolution.
993 TemplateURL
* existing_keyword_turl
=
994 FindNonExtensionTemplateURLForKeyword(turl
->keyword());
995 if (iter
->change_type() == syncer::SyncChange::ACTION_DELETE
) {
996 if (!existing_turl
) {
997 error
= sync_error_factory_
->CreateAndUploadError(
999 "ProcessSyncChanges failed on ChangeType ACTION_DELETE");
1002 if (existing_turl
== GetDefaultSearchProvider()) {
1003 // The only way Sync can attempt to delete the default search provider
1004 // is if we had changed the kSyncedDefaultSearchProviderGUID
1005 // preference, but perhaps it has not yet been received. To avoid
1006 // situations where this has come in erroneously, we will un-delete
1007 // the current default search from the Sync data. If the pref really
1008 // does arrive later, then default search will change to the correct
1009 // entry, but we'll have this extra entry sitting around. The result is
1010 // not ideal, but it prevents a far more severe bug where the default is
1011 // unexpectedly swapped to something else. The user can safely delete
1012 // the extra entry again later, if they choose. Most users who do not
1013 // look at the search engines UI will not notice this.
1014 // Note that we append a special character to the end of the keyword in
1015 // an attempt to avoid a ping-poinging situation where receiving clients
1016 // may try to continually delete the resurrected entry.
1017 base::string16 updated_keyword
= UniquifyKeyword(*existing_turl
, true);
1018 TemplateURLData
data(existing_turl
->data());
1019 data
.SetKeyword(updated_keyword
);
1020 TemplateURL
new_turl(data
);
1021 if (UpdateNoNotify(existing_turl
, new_turl
))
1024 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(new_turl
);
1025 new_changes
.push_back(syncer::SyncChange(FROM_HERE
,
1026 syncer::SyncChange::ACTION_ADD
,
1028 // Ignore the delete attempt. This means we never end up resetting the
1029 // default search provider due to an ACTION_DELETE from sync.
1033 Remove(existing_turl
);
1034 } else if (iter
->change_type() == syncer::SyncChange::ACTION_ADD
) {
1035 if (existing_turl
) {
1036 error
= sync_error_factory_
->CreateAndUploadError(
1038 "ProcessSyncChanges failed on ChangeType ACTION_ADD");
1041 const std::string guid
= turl
->sync_guid();
1042 if (existing_keyword_turl
) {
1043 // Resolve any conflicts so we can safely add the new entry.
1044 ResolveSyncKeywordConflict(turl
.get(), existing_keyword_turl
,
1047 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
1048 &dsp_change_origin_
, DSP_CHANGE_SYNC_ADD
);
1049 // Force the local ID to kInvalidTemplateURLID so we can add it.
1050 TemplateURLData
data(turl
->data());
1051 data
.id
= kInvalidTemplateURLID
;
1052 TemplateURL
* added
= new TemplateURL(data
);
1054 MaybeUpdateDSEAfterSync(added
);
1055 } else if (iter
->change_type() == syncer::SyncChange::ACTION_UPDATE
) {
1056 if (!existing_turl
) {
1057 error
= sync_error_factory_
->CreateAndUploadError(
1059 "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
1062 if (existing_keyword_turl
&& (existing_keyword_turl
!= existing_turl
)) {
1063 // Resolve any conflicts with other entries so we can safely update the
1065 ResolveSyncKeywordConflict(turl
.get(), existing_keyword_turl
,
1068 if (UpdateNoNotify(existing_turl
, *turl
)) {
1070 MaybeUpdateDSEAfterSync(existing_turl
);
1073 // We've unexpectedly received an ACTION_INVALID.
1074 error
= sync_error_factory_
->CreateAndUploadError(
1076 "ProcessSyncChanges received an ACTION_INVALID");
1080 // If something went wrong, we want to prematurely exit to avoid pushing
1081 // inconsistent data to Sync. We return the last error we received.
1085 error
= sync_processor_
->ProcessSyncChanges(from_here
, new_changes
);
1090 syncer::SyncMergeResult
TemplateURLService::MergeDataAndStartSyncing(
1091 syncer::ModelType type
,
1092 const syncer::SyncDataList
& initial_sync_data
,
1093 scoped_ptr
<syncer::SyncChangeProcessor
> sync_processor
,
1094 scoped_ptr
<syncer::SyncErrorFactory
> sync_error_factory
) {
1096 DCHECK_EQ(type
, syncer::SEARCH_ENGINES
);
1097 DCHECK(!sync_processor_
.get());
1098 DCHECK(sync_processor
.get());
1099 DCHECK(sync_error_factory
.get());
1100 syncer::SyncMergeResult
merge_result(type
);
1102 // Disable sync if we failed to load.
1104 merge_result
.set_error(syncer::SyncError(
1105 FROM_HERE
, syncer::SyncError::DATATYPE_ERROR
,
1106 "Local database load failed.", syncer::SEARCH_ENGINES
));
1107 return merge_result
;
1110 sync_processor_
= sync_processor
.Pass();
1111 sync_error_factory_
= sync_error_factory
.Pass();
1113 // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
1114 // don't step on our own toes.
1115 base::AutoReset
<bool> processing_changes(&processing_syncer_changes_
, true);
1117 // We've started syncing, so set our origin member to the base Sync value.
1118 // As we move through Sync Code, we may set this to increasingly specific
1119 // origins so we can tell what exactly caused a DSP change.
1120 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(&dsp_change_origin_
,
1121 DSP_CHANGE_SYNC_UNINTENTIONAL
);
1123 syncer::SyncChangeList new_changes
;
1125 // Build maps of our sync GUIDs to syncer::SyncData.
1126 SyncDataMap local_data_map
= CreateGUIDToSyncDataMap(
1127 GetAllSyncData(syncer::SEARCH_ENGINES
));
1128 SyncDataMap sync_data_map
= CreateGUIDToSyncDataMap(initial_sync_data
);
1130 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1132 merge_result
.set_num_items_before_association(local_data_map
.size());
1133 for (SyncDataMap::const_iterator iter
= sync_data_map
.begin();
1134 iter
!= sync_data_map
.end(); ++iter
) {
1135 TemplateURL
* local_turl
= GetTemplateURLForGUID(iter
->first
);
1136 scoped_ptr
<TemplateURL
> sync_turl(
1137 CreateTemplateURLFromTemplateURLAndSyncData(
1138 prefs_
, search_terms_data(), local_turl
, iter
->second
,
1140 if (!sync_turl
.get())
1143 if (pre_sync_deletes_
.find(sync_turl
->sync_guid()) !=
1144 pre_sync_deletes_
.end()) {
1145 // This entry was deleted before the initial sync began (possibly through
1146 // preprocessing in TemplateURLService's loading code). Ignore it and send
1147 // an ACTION_DELETE up to the server.
1148 new_changes
.push_back(
1149 syncer::SyncChange(FROM_HERE
,
1150 syncer::SyncChange::ACTION_DELETE
,
1152 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1153 DELETE_ENGINE_PRE_SYNC
, DELETE_ENGINE_MAX
);
1158 DCHECK(IsFromSync(local_turl
, sync_data_map
));
1159 // This local search engine is already synced. If the timestamp differs
1160 // from Sync, we need to update locally or to the cloud. Note that if the
1161 // timestamps are equal, we touch neither.
1162 if (sync_turl
->last_modified() > local_turl
->last_modified()) {
1163 // We've received an update from Sync. We should replace all synced
1164 // fields in the local TemplateURL. Note that this includes the
1165 // TemplateURLID and the TemplateURL may have to be reparsed. This
1166 // also makes the local data's last_modified timestamp equal to Sync's,
1167 // avoiding an Update on the next MergeData call.
1168 if (UpdateNoNotify(local_turl
, *sync_turl
))
1170 merge_result
.set_num_items_modified(
1171 merge_result
.num_items_modified() + 1);
1172 } else if (sync_turl
->last_modified() < local_turl
->last_modified()) {
1173 // Otherwise, we know we have newer data, so update Sync with our
1175 new_changes
.push_back(
1176 syncer::SyncChange(FROM_HERE
,
1177 syncer::SyncChange::ACTION_UPDATE
,
1178 local_data_map
[local_turl
->sync_guid()]));
1180 local_data_map
.erase(iter
->first
);
1182 // The search engine from the cloud has not been synced locally. Merge it
1183 // into our local model. This will handle any conflicts with local (and
1184 // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1185 // over not-yet-synced TemplateURLs.
1186 MergeInSyncTemplateURL(sync_turl
.get(), sync_data_map
, &new_changes
,
1187 &local_data_map
, &merge_result
);
1191 // The remaining SyncData in local_data_map should be everything that needs to
1192 // be pushed as ADDs to sync.
1193 for (SyncDataMap::const_iterator iter
= local_data_map
.begin();
1194 iter
!= local_data_map
.end(); ++iter
) {
1195 new_changes
.push_back(
1196 syncer::SyncChange(FROM_HERE
,
1197 syncer::SyncChange::ACTION_ADD
,
1201 // Do some post-processing on the change list to ensure that we are sending
1202 // valid changes to sync_processor_.
1203 PruneSyncChanges(&sync_data_map
, &new_changes
);
1205 LogDuplicatesHistogram(GetTemplateURLs());
1206 merge_result
.set_num_items_after_association(
1207 GetAllSyncData(syncer::SEARCH_ENGINES
).size());
1208 merge_result
.set_error(
1209 sync_processor_
->ProcessSyncChanges(FROM_HERE
, new_changes
));
1210 if (merge_result
.error().IsSet())
1211 return merge_result
;
1213 // The ACTION_DELETEs from this set are processed. Empty it so we don't try to
1214 // reuse them on the next call to MergeDataAndStartSyncing.
1215 pre_sync_deletes_
.clear();
1217 models_associated_
= true;
1218 return merge_result
;
1221 void TemplateURLService::StopSyncing(syncer::ModelType type
) {
1222 DCHECK_EQ(type
, syncer::SEARCH_ENGINES
);
1223 models_associated_
= false;
1224 sync_processor_
.reset();
1225 sync_error_factory_
.reset();
1228 void TemplateURLService::ProcessTemplateURLChange(
1229 const tracked_objects::Location
& from_here
,
1230 const TemplateURL
* turl
,
1231 syncer::SyncChange::SyncChangeType type
) {
1232 DCHECK_NE(type
, syncer::SyncChange::ACTION_INVALID
);
1235 if (!models_associated_
)
1236 return; // Not syncing.
1238 if (processing_syncer_changes_
)
1239 return; // These are changes originating from us. Ignore.
1241 // Avoid syncing keywords managed by policy.
1242 if (turl
->created_by_policy())
1245 // Avoid syncing extension-controlled search engines.
1246 if (turl
->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
)
1249 syncer::SyncChangeList changes
;
1251 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*turl
);
1252 changes
.push_back(syncer::SyncChange(from_here
,
1256 sync_processor_
->ProcessSyncChanges(FROM_HERE
, changes
);
1260 syncer::SyncData
TemplateURLService::CreateSyncDataFromTemplateURL(
1261 const TemplateURL
& turl
) {
1262 sync_pb::EntitySpecifics specifics
;
1263 sync_pb::SearchEngineSpecifics
* se_specifics
=
1264 specifics
.mutable_search_engine();
1265 se_specifics
->set_short_name(base::UTF16ToUTF8(turl
.short_name()));
1266 se_specifics
->set_keyword(base::UTF16ToUTF8(turl
.keyword()));
1267 se_specifics
->set_favicon_url(turl
.favicon_url().spec());
1268 se_specifics
->set_url(turl
.url());
1269 se_specifics
->set_safe_for_autoreplace(turl
.safe_for_autoreplace());
1270 se_specifics
->set_originating_url(turl
.originating_url().spec());
1271 se_specifics
->set_date_created(turl
.date_created().ToInternalValue());
1272 se_specifics
->set_input_encodings(JoinString(turl
.input_encodings(), ';'));
1273 se_specifics
->set_show_in_default_list(turl
.show_in_default_list());
1274 se_specifics
->set_suggestions_url(turl
.suggestions_url());
1275 se_specifics
->set_prepopulate_id(turl
.prepopulate_id());
1276 se_specifics
->set_instant_url(turl
.instant_url());
1277 if (!turl
.image_url().empty())
1278 se_specifics
->set_image_url(turl
.image_url());
1279 se_specifics
->set_new_tab_url(turl
.new_tab_url());
1280 if (!turl
.search_url_post_params().empty())
1281 se_specifics
->set_search_url_post_params(turl
.search_url_post_params());
1282 if (!turl
.suggestions_url_post_params().empty()) {
1283 se_specifics
->set_suggestions_url_post_params(
1284 turl
.suggestions_url_post_params());
1286 if (!turl
.instant_url_post_params().empty())
1287 se_specifics
->set_instant_url_post_params(turl
.instant_url_post_params());
1288 if (!turl
.image_url_post_params().empty())
1289 se_specifics
->set_image_url_post_params(turl
.image_url_post_params());
1290 se_specifics
->set_last_modified(turl
.last_modified().ToInternalValue());
1291 se_specifics
->set_sync_guid(turl
.sync_guid());
1292 for (size_t i
= 0; i
< turl
.alternate_urls().size(); ++i
)
1293 se_specifics
->add_alternate_urls(turl
.alternate_urls()[i
]);
1294 se_specifics
->set_search_terms_replacement_key(
1295 turl
.search_terms_replacement_key());
1297 return syncer::SyncData::CreateLocalData(se_specifics
->sync_guid(),
1298 se_specifics
->keyword(),
1303 TemplateURL
* TemplateURLService::CreateTemplateURLFromTemplateURLAndSyncData(
1305 const SearchTermsData
& search_terms_data
,
1306 TemplateURL
* existing_turl
,
1307 const syncer::SyncData
& sync_data
,
1308 syncer::SyncChangeList
* change_list
) {
1309 DCHECK(change_list
);
1311 sync_pb::SearchEngineSpecifics specifics
=
1312 sync_data
.GetSpecifics().search_engine();
1314 // Past bugs might have caused either of these fields to be empty. Just
1315 // delete this data off the server.
1316 if (specifics
.url().empty() || specifics
.sync_guid().empty()) {
1317 change_list
->push_back(
1318 syncer::SyncChange(FROM_HERE
,
1319 syncer::SyncChange::ACTION_DELETE
,
1321 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
1322 DELETE_ENGINE_EMPTY_FIELD
, DELETE_ENGINE_MAX
);
1326 TemplateURLData
data(existing_turl
?
1327 existing_turl
->data() : TemplateURLData());
1328 data
.short_name
= base::UTF8ToUTF16(specifics
.short_name());
1329 data
.originating_url
= GURL(specifics
.originating_url());
1330 base::string16
keyword(base::UTF8ToUTF16(specifics
.keyword()));
1331 // NOTE: Once this code has shipped in a couple of stable releases, we can
1332 // probably remove the migration portion, comment out the
1333 // "autogenerate_keyword" field entirely in the .proto file, and fold the
1334 // empty keyword case into the "delete data" block above.
1335 bool reset_keyword
=
1336 specifics
.autogenerate_keyword() || specifics
.keyword().empty();
1338 keyword
= base::ASCIIToUTF16("dummy"); // Will be replaced below.
1339 DCHECK(!keyword
.empty());
1340 data
.SetKeyword(keyword
);
1341 data
.SetURL(specifics
.url());
1342 data
.suggestions_url
= specifics
.suggestions_url();
1343 data
.instant_url
= specifics
.instant_url();
1344 data
.image_url
= specifics
.image_url();
1345 data
.new_tab_url
= specifics
.new_tab_url();
1346 data
.search_url_post_params
= specifics
.search_url_post_params();
1347 data
.suggestions_url_post_params
= specifics
.suggestions_url_post_params();
1348 data
.instant_url_post_params
= specifics
.instant_url_post_params();
1349 data
.image_url_post_params
= specifics
.image_url_post_params();
1350 data
.favicon_url
= GURL(specifics
.favicon_url());
1351 data
.show_in_default_list
= specifics
.show_in_default_list();
1352 data
.safe_for_autoreplace
= specifics
.safe_for_autoreplace();
1353 base::SplitString(specifics
.input_encodings(), ';', &data
.input_encodings
);
1354 // If the server data has duplicate encodings, we'll want to push an update
1355 // below to correct it. Note that we also fix this in
1356 // GetSearchProvidersUsingKeywordResult(), since otherwise we'd never correct
1357 // local problems for clients which have disabled search engine sync.
1358 bool deduped
= DeDupeEncodings(&data
.input_encodings
);
1359 data
.date_created
= base::Time::FromInternalValue(specifics
.date_created());
1360 data
.last_modified
= base::Time::FromInternalValue(specifics
.last_modified());
1361 data
.prepopulate_id
= specifics
.prepopulate_id();
1362 data
.sync_guid
= specifics
.sync_guid();
1363 data
.alternate_urls
.clear();
1364 for (int i
= 0; i
< specifics
.alternate_urls_size(); ++i
)
1365 data
.alternate_urls
.push_back(specifics
.alternate_urls(i
));
1366 data
.search_terms_replacement_key
= specifics
.search_terms_replacement_key();
1368 TemplateURL
* turl
= new TemplateURL(data
);
1369 // If this TemplateURL matches a built-in prepopulated template URL, it's
1370 // possible that sync is trying to modify fields that should not be touched.
1371 // Revert these fields to the built-in values.
1372 UpdateTemplateURLIfPrepopulated(turl
, prefs
);
1373 DCHECK_NE(TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
, turl
->GetType());
1374 if (reset_keyword
|| deduped
) {
1376 turl
->ResetKeywordIfNecessary(search_terms_data
, true);
1377 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*turl
);
1378 change_list
->push_back(syncer::SyncChange(FROM_HERE
,
1379 syncer::SyncChange::ACTION_UPDATE
,
1381 } else if (turl
->IsGoogleSearchURLWithReplaceableKeyword(search_terms_data
)) {
1382 if (!existing_turl
) {
1383 // We're adding a new TemplateURL that uses the Google base URL, so set
1384 // its keyword appropriately for the local environment.
1385 turl
->ResetKeywordIfNecessary(search_terms_data
, false);
1386 } else if (existing_turl
->IsGoogleSearchURLWithReplaceableKeyword(
1387 search_terms_data
)) {
1388 // Ignore keyword changes triggered by the Google base URL changing on
1389 // another client. If the base URL changes in this client as well, we'll
1390 // pick that up separately at the appropriate time. Otherwise, changing
1391 // the keyword here could result in having the wrong keyword for the local
1393 turl
->data_
.SetKeyword(existing_turl
->keyword());
1401 SyncDataMap
TemplateURLService::CreateGUIDToSyncDataMap(
1402 const syncer::SyncDataList
& sync_data
) {
1403 SyncDataMap data_map
;
1404 for (syncer::SyncDataList::const_iterator
i(sync_data
.begin());
1405 i
!= sync_data
.end();
1407 data_map
[i
->GetSpecifics().search_engine().sync_guid()] = *i
;
1411 void TemplateURLService::SetKeywordSearchTermsForURL(
1412 const TemplateURL
* t_url
,
1414 const base::string16
& term
) {
1416 client_
->SetKeywordSearchTermsForURL(url
, t_url
->id(), term
);
1419 void TemplateURLService::Init(const Initializer
* initializers
,
1420 int num_initializers
) {
1422 client_
->SetOwner(this);
1424 // GoogleURLTracker is not created in tests.
1425 if (google_url_tracker_
) {
1426 google_url_updated_subscription_
=
1427 google_url_tracker_
->RegisterCallback(base::Bind(
1428 &TemplateURLService::GoogleBaseURLChanged
, base::Unretained(this)));
1432 pref_change_registrar_
.Init(prefs_
);
1433 pref_change_registrar_
.Add(
1434 prefs::kSyncedDefaultSearchProviderGUID
,
1436 &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged
,
1437 base::Unretained(this)));
1440 DefaultSearchManager::Source source
= DefaultSearchManager::FROM_USER
;
1441 TemplateURLData
* dse
=
1442 default_search_manager_
.GetDefaultSearchEngine(&source
);
1443 ApplyDefaultSearchChange(dse
, source
);
1445 if (num_initializers
> 0) {
1446 // This path is only hit by test code and is used to simulate a loaded
1447 // TemplateURLService.
1448 ChangeToLoadedState();
1450 // Add specific initializers, if any.
1451 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1452 for (int i(0); i
< num_initializers
; ++i
) {
1453 DCHECK(initializers
[i
].keyword
);
1454 DCHECK(initializers
[i
].url
);
1455 DCHECK(initializers
[i
].content
);
1457 // TemplateURLService ends up owning the TemplateURL, don't try and free
1459 TemplateURLData data
;
1460 data
.short_name
= base::UTF8ToUTF16(initializers
[i
].content
);
1461 data
.SetKeyword(base::UTF8ToUTF16(initializers
[i
].keyword
));
1462 data
.SetURL(initializers
[i
].url
);
1463 TemplateURL
* template_url
= new TemplateURL(data
);
1464 AddNoNotify(template_url
, true);
1466 // Set the first provided identifier to be the default.
1468 default_search_manager_
.SetUserSelectedDefaultSearchEngine(data
);
1472 // Request a server check for the correct Google URL if Google is the
1473 // default search engine.
1474 RequestGoogleURLTrackerServerCheckIfNecessary();
1477 void TemplateURLService::RemoveFromMaps(TemplateURL
* template_url
) {
1478 const base::string16
& keyword
= template_url
->keyword();
1479 DCHECK_NE(0U, keyword_to_template_map_
.count(keyword
));
1480 if (keyword_to_template_map_
[keyword
] == template_url
) {
1481 // We need to check whether the keyword can now be provided by another
1482 // TemplateURL. See the comments in AddToMaps() for more information on
1483 // extension keywords and how they can coexist with non-extension keywords.
1484 // In the case of more than one extension, we use the most recently
1485 // installed (which will be the most recently added, which will have the
1487 TemplateURL
* best_fallback
= NULL
;
1488 for (TemplateURLVector::const_iterator
i(template_urls_
.begin());
1489 i
!= template_urls_
.end(); ++i
) {
1490 TemplateURL
* turl
= *i
;
1491 // This next statement relies on the fact that there can only be one
1492 // non-Omnibox API TemplateURL with a given keyword.
1493 if ((turl
!= template_url
) && (turl
->keyword() == keyword
) &&
1495 (best_fallback
->GetType() != TemplateURL::OMNIBOX_API_EXTENSION
) ||
1496 ((turl
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
) &&
1497 (turl
->id() > best_fallback
->id()))))
1498 best_fallback
= turl
;
1501 keyword_to_template_map_
[keyword
] = best_fallback
;
1503 keyword_to_template_map_
.erase(keyword
);
1506 if (!template_url
->sync_guid().empty())
1507 guid_to_template_map_
.erase(template_url
->sync_guid());
1508 // |provider_map_| is only initialized after loading has completed.
1510 provider_map_
->Remove(template_url
);
1514 void TemplateURLService::AddToMaps(TemplateURL
* template_url
) {
1515 bool template_url_is_omnibox_api
=
1516 template_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
1517 const base::string16
& keyword
= template_url
->keyword();
1518 KeywordToTemplateMap::const_iterator i
=
1519 keyword_to_template_map_
.find(keyword
);
1520 if (i
== keyword_to_template_map_
.end()) {
1521 keyword_to_template_map_
[keyword
] = template_url
;
1523 const TemplateURL
* existing_url
= i
->second
;
1524 // We should only have overlapping keywords when at least one comes from
1525 // an extension. In that case, the ranking order is:
1526 // Manually-modified keywords > extension keywords > replaceable keywords
1527 // When there are multiple extensions, the last-added wins.
1528 bool existing_url_is_omnibox_api
=
1529 existing_url
->GetType() == TemplateURL::OMNIBOX_API_EXTENSION
;
1530 DCHECK(existing_url_is_omnibox_api
|| template_url_is_omnibox_api
);
1531 if (existing_url_is_omnibox_api
?
1532 !CanReplace(template_url
) : CanReplace(existing_url
))
1533 keyword_to_template_map_
[keyword
] = template_url
;
1536 if (!template_url
->sync_guid().empty())
1537 guid_to_template_map_
[template_url
->sync_guid()] = template_url
;
1538 // |provider_map_| is only initialized after loading has completed.
1540 provider_map_
->Add(template_url
, search_terms_data());
1543 // Helper for partition() call in next function.
1544 bool HasValidID(TemplateURL
* t_url
) {
1545 return t_url
->id() != kInvalidTemplateURLID
;
1548 void TemplateURLService::SetTemplateURLs(TemplateURLVector
* urls
) {
1549 // Partition the URLs first, instead of implementing the loops below by simply
1550 // scanning the input twice. While it's not supposed to happen normally, it's
1551 // possible for corrupt databases to return multiple entries with the same
1552 // keyword. In this case, the first loop may delete the first entry when
1553 // adding the second. If this happens, the second loop must not attempt to
1554 // access the deleted entry. Partitioning ensures this constraint.
1555 TemplateURLVector::iterator
first_invalid(
1556 std::partition(urls
->begin(), urls
->end(), HasValidID
));
1558 // First, add the items that already have id's, so that the next_id_ gets
1560 for (TemplateURLVector::const_iterator i
= urls
->begin(); i
!= first_invalid
;
1562 next_id_
= std::max(next_id_
, (*i
)->id());
1563 AddNoNotify(*i
, false);
1566 // Next add the new items that don't have id's.
1567 for (TemplateURLVector::const_iterator i
= first_invalid
; i
!= urls
->end();
1569 AddNoNotify(*i
, true);
1571 // Clear the input vector to reduce the chance callers will try to use a
1572 // (possibly deleted) entry.
1576 void TemplateURLService::ChangeToLoadedState() {
1579 provider_map_
->Init(template_urls_
, search_terms_data());
1582 // This will cause a call to NotifyObservers().
1583 ApplyDefaultSearchChangeNoMetrics(
1584 initial_default_search_provider_
?
1585 &initial_default_search_provider_
->data() : NULL
,
1586 default_search_provider_source_
);
1587 initial_default_search_provider_
.reset();
1588 on_loaded_callbacks_
.Notify();
1591 bool TemplateURLService::CanReplaceKeywordForHost(
1592 const std::string
& host
,
1593 TemplateURL
** to_replace
) {
1594 DCHECK(!to_replace
|| !*to_replace
);
1595 const TemplateURLSet
* urls
= provider_map_
->GetURLsForHost(host
);
1598 for (TemplateURLSet::const_iterator
i(urls
->begin()); i
!= urls
->end(); ++i
) {
1599 if (CanReplace(*i
)) {
1608 bool TemplateURLService::CanReplace(const TemplateURL
* t_url
) {
1609 return (t_url
!= default_search_provider_
&& !t_url
->show_in_default_list() &&
1610 t_url
->safe_for_autoreplace());
1613 TemplateURL
* TemplateURLService::FindNonExtensionTemplateURLForKeyword(
1614 const base::string16
& keyword
) {
1615 TemplateURL
* keyword_turl
= GetTemplateURLForKeyword(keyword
);
1616 if (!keyword_turl
|| (keyword_turl
->GetType() == TemplateURL::NORMAL
))
1617 return keyword_turl
;
1618 // The extension keyword in the model may be hiding a replaceable
1619 // non-extension keyword. Look for it.
1620 for (TemplateURLVector::const_iterator
i(template_urls_
.begin());
1621 i
!= template_urls_
.end(); ++i
) {
1622 if (((*i
)->GetType() == TemplateURL::NORMAL
) &&
1623 ((*i
)->keyword() == keyword
))
1629 bool TemplateURLService::UpdateNoNotify(TemplateURL
* existing_turl
,
1630 const TemplateURL
& new_values
) {
1631 DCHECK(existing_turl
);
1632 if (std::find(template_urls_
.begin(), template_urls_
.end(), existing_turl
) ==
1633 template_urls_
.end())
1636 base::string16
old_keyword(existing_turl
->keyword());
1637 keyword_to_template_map_
.erase(old_keyword
);
1638 if (!existing_turl
->sync_guid().empty())
1639 guid_to_template_map_
.erase(existing_turl
->sync_guid());
1641 // |provider_map_| is only initialized after loading has completed.
1643 provider_map_
->Remove(existing_turl
);
1645 TemplateURLID previous_id
= existing_turl
->id();
1646 existing_turl
->CopyFrom(new_values
);
1647 existing_turl
->data_
.id
= previous_id
;
1650 provider_map_
->Add(existing_turl
, search_terms_data());
1653 const base::string16
& keyword
= existing_turl
->keyword();
1654 KeywordToTemplateMap::const_iterator i
=
1655 keyword_to_template_map_
.find(keyword
);
1656 if (i
== keyword_to_template_map_
.end()) {
1657 keyword_to_template_map_
[keyword
] = existing_turl
;
1659 // We can theoretically reach here in two cases:
1660 // * There is an existing extension keyword and sync brings in a rename of
1661 // a non-extension keyword to match. In this case we just need to pick
1662 // which keyword has priority to update the keyword map.
1663 // * Autogeneration of the keyword for a Google default search provider
1664 // at load time causes it to conflict with an existing keyword. In this
1665 // case we delete the existing keyword if it's replaceable, or else undo
1666 // the change in keyword for |existing_turl|.
1667 TemplateURL
* existing_keyword_turl
= i
->second
;
1668 if (existing_keyword_turl
->GetType() != TemplateURL::NORMAL
) {
1669 if (!CanReplace(existing_turl
))
1670 keyword_to_template_map_
[keyword
] = existing_turl
;
1672 if (CanReplace(existing_keyword_turl
)) {
1673 RemoveNoNotify(existing_keyword_turl
);
1675 existing_turl
->data_
.SetKeyword(old_keyword
);
1676 keyword_to_template_map_
[old_keyword
] = existing_turl
;
1680 if (!existing_turl
->sync_guid().empty())
1681 guid_to_template_map_
[existing_turl
->sync_guid()] = existing_turl
;
1683 if (web_data_service_
.get())
1684 web_data_service_
->UpdateKeyword(existing_turl
->data());
1686 // Inform sync of the update.
1687 ProcessTemplateURLChange(
1688 FROM_HERE
, existing_turl
, syncer::SyncChange::ACTION_UPDATE
);
1690 if (default_search_provider_
== existing_turl
&&
1691 default_search_provider_source_
== DefaultSearchManager::FROM_USER
) {
1692 default_search_manager_
.SetUserSelectedDefaultSearchEngine(
1693 default_search_provider_
->data());
1699 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1700 TemplateURL
* template_url
,
1701 PrefService
* prefs
) {
1702 int prepopulate_id
= template_url
->prepopulate_id();
1703 if (template_url
->prepopulate_id() == 0)
1706 size_t default_search_index
;
1707 ScopedVector
<TemplateURLData
> prepopulated_urls
=
1708 TemplateURLPrepopulateData::GetPrepopulatedEngines(
1709 prefs
, &default_search_index
);
1711 for (size_t i
= 0; i
< prepopulated_urls
.size(); ++i
) {
1712 if (prepopulated_urls
[i
]->prepopulate_id
== prepopulate_id
) {
1713 MergeIntoPrepopulatedEngineData(template_url
, prepopulated_urls
[i
]);
1714 template_url
->CopyFrom(TemplateURL(*prepopulated_urls
[i
]));
1719 void TemplateURLService::MaybeUpdateDSEAfterSync(TemplateURL
* synced_turl
) {
1721 (synced_turl
->sync_guid() ==
1722 prefs_
->GetString(prefs::kSyncedDefaultSearchProviderGUID
))) {
1723 default_search_manager_
.SetUserSelectedDefaultSearchEngine(
1724 synced_turl
->data());
1728 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1729 const URLVisitedDetails
& details
) {
1730 if (!details
.url
.is_valid())
1733 const TemplateURLSet
* urls_for_host
=
1734 provider_map_
->GetURLsForHost(details
.url
.host());
1738 for (TemplateURLSet::const_iterator i
= urls_for_host
->begin();
1739 i
!= urls_for_host
->end(); ++i
) {
1740 base::string16 search_terms
;
1741 if ((*i
)->ExtractSearchTermsFromURL(details
.url
, search_terms_data(),
1743 !search_terms
.empty()) {
1744 if (details
.is_keyword_transition
) {
1745 // The visit is the result of the user entering a keyword, generate a
1746 // KEYWORD_GENERATED visit for the KEYWORD so that the keyword typed
1747 // count is boosted.
1748 AddTabToSearchVisit(**i
);
1750 SetKeywordSearchTermsForURL(*i
, details
.url
, search_terms
);
1755 void TemplateURLService::AddTabToSearchVisit(const TemplateURL
& t_url
) {
1756 // Only add visits for entries the user hasn't modified. If the user modified
1757 // the entry the keyword may no longer correspond to the host name. It may be
1758 // possible to do something more sophisticated here, but it's so rare as to
1760 if (!t_url
.safe_for_autoreplace())
1767 url_fixer::FixupURL(base::UTF16ToUTF8(t_url
.keyword()), std::string()));
1768 if (!url
.is_valid())
1771 // Synthesize a visit for the keyword. This ensures the url for the keyword is
1772 // autocompleted even if the user doesn't type the url in directly.
1773 client_
->AddKeywordGeneratedVisit(url
);
1776 void TemplateURLService::RequestGoogleURLTrackerServerCheckIfNecessary() {
1777 if (default_search_provider_
&&
1778 default_search_provider_
->HasGoogleBaseURLs(search_terms_data()) &&
1779 google_url_tracker_
)
1780 google_url_tracker_
->RequestServerCheck(false);
1783 void TemplateURLService::GoogleBaseURLChanged() {
1787 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1788 bool something_changed
= false;
1789 for (TemplateURLVector::iterator
i(template_urls_
.begin());
1790 i
!= template_urls_
.end(); ++i
) {
1791 TemplateURL
* t_url
= *i
;
1792 if (t_url
->HasGoogleBaseURLs(search_terms_data())) {
1793 TemplateURL
updated_turl(t_url
->data());
1794 updated_turl
.ResetKeywordIfNecessary(search_terms_data(), false);
1795 KeywordToTemplateMap::const_iterator existing_entry
=
1796 keyword_to_template_map_
.find(updated_turl
.keyword());
1797 if ((existing_entry
!= keyword_to_template_map_
.end()) &&
1798 (existing_entry
->second
!= t_url
)) {
1799 // The new autogenerated keyword conflicts with another TemplateURL.
1800 // Overwrite it if it's replaceable; otherwise, leave |t_url| using its
1801 // current keyword. (This will not prevent |t_url| from auto-updating
1802 // the keyword in the future if the conflicting TemplateURL disappears.)
1803 // Note that we must still update |t_url| in this case, or the
1804 // |provider_map_| will not be updated correctly.
1805 if (CanReplace(existing_entry
->second
))
1806 RemoveNoNotify(existing_entry
->second
);
1808 updated_turl
.data_
.SetKeyword(t_url
->keyword());
1810 something_changed
= true;
1811 // This will send the keyword change to sync. Note that other clients
1812 // need to reset the keyword to an appropriate local value when this
1813 // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
1814 UpdateNoNotify(t_url
, updated_turl
);
1817 if (something_changed
)
1821 void TemplateURLService::OnDefaultSearchChange(
1822 const TemplateURLData
* data
,
1823 DefaultSearchManager::Source source
) {
1824 if (prefs_
&& (source
== DefaultSearchManager::FROM_USER
) &&
1825 ((source
!= default_search_provider_source_
) ||
1826 !IdenticalSyncGUIDs(data
, GetDefaultSearchProvider()))) {
1827 prefs_
->SetString(prefs::kSyncedDefaultSearchProviderGUID
, data
->sync_guid
);
1829 ApplyDefaultSearchChange(data
, source
);
1832 void TemplateURLService::ApplyDefaultSearchChange(
1833 const TemplateURLData
* data
,
1834 DefaultSearchManager::Source source
) {
1835 if (!ApplyDefaultSearchChangeNoMetrics(data
, source
))
1838 UMA_HISTOGRAM_ENUMERATION(
1839 "Search.DefaultSearchChangeOrigin", dsp_change_origin_
, DSP_CHANGE_MAX
);
1841 if (GetDefaultSearchProvider() &&
1842 GetDefaultSearchProvider()->HasGoogleBaseURLs(search_terms_data()) &&
1843 !dsp_change_callback_
.is_null())
1844 dsp_change_callback_
.Run();
1847 bool TemplateURLService::ApplyDefaultSearchChangeNoMetrics(
1848 const TemplateURLData
* data
,
1849 DefaultSearchManager::Source source
) {
1851 // Set |initial_default_search_provider_| from the preferences. This is
1852 // mainly so we can hold ownership until we get to the point where the list
1853 // of keywords from Web Data is the owner of everything including the
1855 bool changed
= TemplateURL::MatchesData(
1856 initial_default_search_provider_
.get(), data
, search_terms_data());
1857 initial_default_search_provider_
.reset(
1858 data
? new TemplateURL(*data
) : NULL
);
1859 default_search_provider_source_
= source
;
1863 // Prevent recursion if we update the value stored in default_search_manager_.
1864 // Note that we exclude the case of data == NULL because that could cause a
1865 // false positive for recursion when the initial_default_search_provider_ is
1866 // NULL due to policy. We'll never actually get recursion with data == NULL.
1867 if (source
== default_search_provider_source_
&& data
!= NULL
&&
1868 TemplateURL::MatchesData(default_search_provider_
, data
,
1869 search_terms_data()))
1872 // This may be deleted later. Use exclusively for pointer comparison to detect
1874 TemplateURL
* previous_default_search_engine
= default_search_provider_
;
1876 KeywordWebDataService::BatchModeScoper
scoper(web_data_service_
.get());
1877 if (default_search_provider_source_
== DefaultSearchManager::FROM_POLICY
||
1878 source
== DefaultSearchManager::FROM_POLICY
) {
1879 // We do this both to remove any no-longer-applicable policy-defined DSE as
1880 // well as to add the new one, if appropriate.
1881 UpdateProvidersCreatedByPolicy(
1883 source
== DefaultSearchManager::FROM_POLICY
? data
: NULL
);
1887 default_search_provider_
= NULL
;
1888 } else if (source
== DefaultSearchManager::FROM_EXTENSION
) {
1889 default_search_provider_
= FindMatchingExtensionTemplateURL(
1890 *data
, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
);
1891 } else if (source
== DefaultSearchManager::FROM_FALLBACK
) {
1892 default_search_provider_
=
1893 FindPrepopulatedTemplateURL(data
->prepopulate_id
);
1894 if (default_search_provider_
) {
1895 TemplateURLData
update_data(*data
);
1896 update_data
.sync_guid
= default_search_provider_
->sync_guid();
1897 if (!default_search_provider_
->safe_for_autoreplace()) {
1898 update_data
.safe_for_autoreplace
= false;
1899 update_data
.SetKeyword(default_search_provider_
->keyword());
1900 update_data
.short_name
= default_search_provider_
->short_name();
1902 UpdateNoNotify(default_search_provider_
, TemplateURL(update_data
));
1904 // Normally the prepopulated fallback should be present in
1905 // |template_urls_|, but in a few cases it might not be:
1906 // (1) Tests that initialize the TemplateURLService in peculiar ways.
1907 // (2) If the user deleted the pre-populated default and we subsequently
1908 // lost their user-selected value.
1909 TemplateURL
* new_dse
= new TemplateURL(*data
);
1910 if (AddNoNotify(new_dse
, true))
1911 default_search_provider_
= new_dse
;
1913 } else if (source
== DefaultSearchManager::FROM_USER
) {
1914 default_search_provider_
= GetTemplateURLForGUID(data
->sync_guid
);
1915 if (!default_search_provider_
&& data
->prepopulate_id
) {
1916 default_search_provider_
=
1917 FindPrepopulatedTemplateURL(data
->prepopulate_id
);
1919 TemplateURLData
new_data(*data
);
1920 new_data
.show_in_default_list
= true;
1921 if (default_search_provider_
) {
1922 UpdateNoNotify(default_search_provider_
, TemplateURL(new_data
));
1924 new_data
.id
= kInvalidTemplateURLID
;
1925 TemplateURL
* new_dse
= new TemplateURL(new_data
);
1926 if (AddNoNotify(new_dse
, true))
1927 default_search_provider_
= new_dse
;
1929 if (default_search_provider_
&& prefs_
) {
1930 prefs_
->SetString(prefs::kSyncedDefaultSearchProviderGUID
,
1931 default_search_provider_
->sync_guid());
1936 default_search_provider_source_
= source
;
1938 bool changed
= default_search_provider_
!= previous_default_search_engine
;
1940 RequestGoogleURLTrackerServerCheckIfNecessary();
1947 bool TemplateURLService::AddNoNotify(TemplateURL
* template_url
,
1948 bool newly_adding
) {
1949 DCHECK(template_url
);
1952 DCHECK_EQ(kInvalidTemplateURLID
, template_url
->id());
1953 DCHECK(std::find(template_urls_
.begin(), template_urls_
.end(),
1954 template_url
) == template_urls_
.end());
1955 template_url
->data_
.id
= ++next_id_
;
1958 template_url
->ResetKeywordIfNecessary(search_terms_data(), false);
1959 // Check whether |template_url|'s keyword conflicts with any already in the
1961 TemplateURL
* existing_keyword_turl
=
1962 GetTemplateURLForKeyword(template_url
->keyword());
1964 // Check whether |template_url|'s keyword conflicts with any already in the
1965 // model. Note that we can reach here during the loading phase while
1966 // processing the template URLs from the web data service. In this case,
1967 // GetTemplateURLForKeyword() will look not only at what's already in the
1968 // model, but at the |initial_default_search_provider_|. Since this engine
1969 // will presumably also be present in the web data, we need to double-check
1970 // that any "pre-existing" entries we find are actually coming from
1971 // |template_urls_|, lest we detect a "conflict" between the
1972 // |initial_default_search_provider_| and the web data version of itself.
1973 if (existing_keyword_turl
&&
1974 (std::find(template_urls_
.begin(), template_urls_
.end(),
1975 existing_keyword_turl
) != template_urls_
.end())) {
1976 DCHECK_NE(existing_keyword_turl
, template_url
);
1977 // Only replace one of the TemplateURLs if they are either both extensions,
1978 // or both not extensions.
1979 bool are_same_type
= existing_keyword_turl
->GetType() ==
1980 template_url
->GetType();
1981 if (CanReplace(existing_keyword_turl
) && are_same_type
) {
1982 RemoveNoNotify(existing_keyword_turl
);
1983 } else if (CanReplace(template_url
) && are_same_type
) {
1984 delete template_url
;
1987 base::string16 new_keyword
=
1988 UniquifyKeyword(*existing_keyword_turl
, false);
1989 ResetTemplateURLNoNotify(existing_keyword_turl
,
1990 existing_keyword_turl
->short_name(), new_keyword
,
1991 existing_keyword_turl
->url());
1994 template_urls_
.push_back(template_url
);
1995 AddToMaps(template_url
);
1998 (template_url
->GetType() !=
1999 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
)) {
2000 if (web_data_service_
.get())
2001 web_data_service_
->AddKeyword(template_url
->data());
2003 // Inform sync of the addition. Note that this will assign a GUID to
2004 // template_url and add it to the guid_to_template_map_.
2005 ProcessTemplateURLChange(FROM_HERE
,
2007 syncer::SyncChange::ACTION_ADD
);
2013 void TemplateURLService::RemoveNoNotify(TemplateURL
* template_url
) {
2014 DCHECK(template_url
!= default_search_provider_
);
2016 TemplateURLVector::iterator i
=
2017 std::find(template_urls_
.begin(), template_urls_
.end(), template_url
);
2018 if (i
== template_urls_
.end())
2021 RemoveFromMaps(template_url
);
2023 // Remove it from the vector containing all TemplateURLs.
2024 template_urls_
.erase(i
);
2026 if (template_url
->GetType() != TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
) {
2027 if (web_data_service_
.get())
2028 web_data_service_
->RemoveKeyword(template_url
->id());
2030 // Inform sync of the deletion.
2031 ProcessTemplateURLChange(FROM_HERE
,
2033 syncer::SyncChange::ACTION_DELETE
);
2035 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName
,
2036 DELETE_ENGINE_USER_ACTION
, DELETE_ENGINE_MAX
);
2039 if (loaded_
&& client_
)
2040 client_
->DeleteAllSearchTermsForKeyword(template_url
->id());
2042 // We own the TemplateURL and need to delete it.
2043 delete template_url
;
2046 bool TemplateURLService::ResetTemplateURLNoNotify(
2048 const base::string16
& title
,
2049 const base::string16
& keyword
,
2050 const std::string
& search_url
) {
2051 DCHECK(!keyword
.empty());
2052 DCHECK(!search_url
.empty());
2053 TemplateURLData
data(url
->data());
2054 data
.short_name
= title
;
2055 data
.SetKeyword(keyword
);
2056 if (search_url
!= data
.url()) {
2057 data
.SetURL(search_url
);
2058 // The urls have changed, reset the favicon url.
2059 data
.favicon_url
= GURL();
2061 data
.safe_for_autoreplace
= false;
2062 data
.last_modified
= time_provider_();
2063 return UpdateNoNotify(url
, TemplateURL(data
));
2066 void TemplateURLService::NotifyObservers() {
2070 FOR_EACH_OBSERVER(TemplateURLServiceObserver
, model_observers_
,
2071 OnTemplateURLServiceChanged());
2074 // |template_urls| are the TemplateURLs loaded from the database.
2075 // |default_from_prefs| is the default search provider from the preferences, or
2076 // NULL if the DSE is not policy-defined.
2078 // This function removes from the vector and the database all the TemplateURLs
2079 // that were set by policy, unless it is the current default search provider, in
2080 // which case it is updated with the data from prefs.
2081 void TemplateURLService::UpdateProvidersCreatedByPolicy(
2082 TemplateURLVector
* template_urls
,
2083 const TemplateURLData
* default_from_prefs
) {
2084 DCHECK(template_urls
);
2086 for (TemplateURLVector::iterator i
= template_urls
->begin();
2087 i
!= template_urls
->end(); ) {
2088 TemplateURL
* template_url
= *i
;
2089 if (template_url
->created_by_policy()) {
2090 if (default_from_prefs
&&
2091 TemplateURL::MatchesData(template_url
, default_from_prefs
,
2092 search_terms_data())) {
2093 // If the database specified a default search provider that was set
2094 // by policy, and the default search provider from the preferences
2095 // is also set by policy and they are the same, keep the entry in the
2096 // database and the |default_search_provider|.
2097 default_search_provider_
= template_url
;
2098 // Prevent us from saving any other entries, or creating a new one.
2099 default_from_prefs
= NULL
;
2104 RemoveFromMaps(template_url
);
2105 i
= template_urls
->erase(i
);
2106 if (web_data_service_
.get())
2107 web_data_service_
->RemoveKeyword(template_url
->id());
2108 delete template_url
;
2114 if (default_from_prefs
) {
2115 default_search_provider_
= NULL
;
2116 default_search_provider_source_
= DefaultSearchManager::FROM_POLICY
;
2117 TemplateURLData
new_data(*default_from_prefs
);
2118 if (new_data
.sync_guid
.empty())
2119 new_data
.sync_guid
= base::GenerateGUID();
2120 new_data
.created_by_policy
= true;
2121 TemplateURL
* new_dse
= new TemplateURL(new_data
);
2122 if (AddNoNotify(new_dse
, true))
2123 default_search_provider_
= new_dse
;
2127 void TemplateURLService::ResetTemplateURLGUID(TemplateURL
* url
,
2128 const std::string
& guid
) {
2130 DCHECK(!guid
.empty());
2132 TemplateURLData
data(url
->data());
2133 data
.sync_guid
= guid
;
2134 UpdateNoNotify(url
, TemplateURL(data
));
2137 base::string16
TemplateURLService::UniquifyKeyword(const TemplateURL
& turl
,
2141 if (!GetTemplateURLForKeyword(turl
.keyword()))
2142 return turl
.keyword();
2144 // First, try to return the generated keyword for the TemplateURL (except
2145 // for extensions, as their keywords are not associated with their URLs).
2146 GURL
gurl(turl
.url());
2147 if (gurl
.is_valid() &&
2148 (turl
.GetType() != TemplateURL::OMNIBOX_API_EXTENSION
)) {
2149 base::string16 keyword_candidate
= TemplateURL::GenerateKeyword(gurl
);
2150 if (!GetTemplateURLForKeyword(keyword_candidate
))
2151 return keyword_candidate
;
2155 // We try to uniquify the keyword by appending a special character to the end.
2156 // This is a best-effort approach where we try to preserve the original
2157 // keyword and let the user do what they will after our attempt.
2158 base::string16
keyword_candidate(turl
.keyword());
2160 keyword_candidate
.append(base::ASCIIToUTF16("_"));
2161 } while (GetTemplateURLForKeyword(keyword_candidate
));
2163 return keyword_candidate
;
2166 bool TemplateURLService::IsLocalTemplateURLBetter(
2167 const TemplateURL
* local_turl
,
2168 const TemplateURL
* sync_turl
) {
2169 DCHECK(GetTemplateURLForGUID(local_turl
->sync_guid()));
2170 return local_turl
->last_modified() > sync_turl
->last_modified() ||
2171 local_turl
->created_by_policy() ||
2172 local_turl
== GetDefaultSearchProvider();
2175 void TemplateURLService::ResolveSyncKeywordConflict(
2176 TemplateURL
* unapplied_sync_turl
,
2177 TemplateURL
* applied_sync_turl
,
2178 syncer::SyncChangeList
* change_list
) {
2180 DCHECK(unapplied_sync_turl
);
2181 DCHECK(applied_sync_turl
);
2182 DCHECK(change_list
);
2183 DCHECK_EQ(applied_sync_turl
->keyword(), unapplied_sync_turl
->keyword());
2184 DCHECK_NE(TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
,
2185 applied_sync_turl
->GetType());
2187 // Both |unapplied_sync_turl| and |applied_sync_turl| are known to Sync, so
2188 // don't delete either of them. Instead, determine which is "better" and
2189 // uniquify the other one, sending an update to the server for the updated
2191 const bool applied_turl_is_better
=
2192 IsLocalTemplateURLBetter(applied_sync_turl
, unapplied_sync_turl
);
2193 TemplateURL
* loser
= applied_turl_is_better
?
2194 unapplied_sync_turl
: applied_sync_turl
;
2195 base::string16 new_keyword
= UniquifyKeyword(*loser
, false);
2196 DCHECK(!GetTemplateURLForKeyword(new_keyword
));
2197 if (applied_turl_is_better
) {
2198 // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2199 // for adding or updating unapplied_sync_turl in the local model.
2200 unapplied_sync_turl
->data_
.SetKeyword(new_keyword
);
2202 // Update |applied_sync_turl| in the local model with the new keyword.
2203 TemplateURLData
data(applied_sync_turl
->data());
2204 data
.SetKeyword(new_keyword
);
2205 if (UpdateNoNotify(applied_sync_turl
, TemplateURL(data
)))
2208 // The losing TemplateURL should have their keyword updated. Send a change to
2209 // the server to reflect this change.
2210 syncer::SyncData sync_data
= CreateSyncDataFromTemplateURL(*loser
);
2211 change_list
->push_back(syncer::SyncChange(FROM_HERE
,
2212 syncer::SyncChange::ACTION_UPDATE
,
2216 void TemplateURLService::MergeInSyncTemplateURL(
2217 TemplateURL
* sync_turl
,
2218 const SyncDataMap
& sync_data
,
2219 syncer::SyncChangeList
* change_list
,
2220 SyncDataMap
* local_data
,
2221 syncer::SyncMergeResult
* merge_result
) {
2223 DCHECK(!GetTemplateURLForGUID(sync_turl
->sync_guid()));
2224 DCHECK(IsFromSync(sync_turl
, sync_data
));
2226 TemplateURL
* conflicting_turl
=
2227 FindNonExtensionTemplateURLForKeyword(sync_turl
->keyword());
2228 bool should_add_sync_turl
= true;
2230 // If there was no TemplateURL in the local model that conflicts with
2231 // |sync_turl|, skip the following preparation steps and just add |sync_turl|
2232 // directly. Otherwise, modify |conflicting_turl| to make room for
2234 if (conflicting_turl
) {
2235 if (IsFromSync(conflicting_turl
, sync_data
)) {
2236 // |conflicting_turl| is already known to Sync, so we're not allowed to
2237 // remove it. In this case, we want to uniquify the worse one and send an
2238 // update for the changed keyword to sync. We can reuse the logic from
2239 // ResolveSyncKeywordConflict for this.
2240 ResolveSyncKeywordConflict(sync_turl
, conflicting_turl
, change_list
);
2241 merge_result
->set_num_items_modified(
2242 merge_result
->num_items_modified() + 1);
2244 // |conflicting_turl| is not yet known to Sync. If it is better, then we
2245 // want to transfer its values up to sync. Otherwise, we remove it and
2246 // allow the entry from Sync to overtake it in the model.
2247 const std::string guid
= conflicting_turl
->sync_guid();
2248 if (IsLocalTemplateURLBetter(conflicting_turl
, sync_turl
)) {
2249 ResetTemplateURLGUID(conflicting_turl
, sync_turl
->sync_guid());
2250 syncer::SyncData sync_data
=
2251 CreateSyncDataFromTemplateURL(*conflicting_turl
);
2252 change_list
->push_back(syncer::SyncChange(
2253 FROM_HERE
, syncer::SyncChange::ACTION_UPDATE
, sync_data
));
2254 // Note that in this case we do not add the Sync TemplateURL to the
2255 // local model, since we've effectively "merged" it in by updating the
2256 // local conflicting entry with its sync_guid.
2257 should_add_sync_turl
= false;
2258 merge_result
->set_num_items_modified(
2259 merge_result
->num_items_modified() + 1);
2261 // We guarantee that this isn't the local search provider. Otherwise,
2262 // local would have won.
2263 DCHECK(conflicting_turl
!= GetDefaultSearchProvider());
2264 Remove(conflicting_turl
);
2265 merge_result
->set_num_items_deleted(
2266 merge_result
->num_items_deleted() + 1);
2268 // This TemplateURL was either removed or overwritten in the local model.
2269 // Remove the entry from the local data so it isn't pushed up to Sync.
2270 local_data
->erase(guid
);
2274 if (should_add_sync_turl
) {
2275 // Force the local ID to kInvalidTemplateURLID so we can add it.
2276 TemplateURLData
data(sync_turl
->data());
2277 data
.id
= kInvalidTemplateURLID
;
2278 TemplateURL
* added
= new TemplateURL(data
);
2279 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2280 &dsp_change_origin_
, DSP_CHANGE_SYNC_ADD
);
2282 MaybeUpdateDSEAfterSync(added
);
2283 merge_result
->set_num_items_added(
2284 merge_result
->num_items_added() + 1);
2288 void TemplateURLService::PatchMissingSyncGUIDs(
2289 TemplateURLVector
* template_urls
) {
2290 DCHECK(template_urls
);
2291 for (TemplateURLVector::iterator i
= template_urls
->begin();
2292 i
!= template_urls
->end(); ++i
) {
2293 TemplateURL
* template_url
= *i
;
2294 DCHECK(template_url
);
2295 if (template_url
->sync_guid().empty() &&
2296 (template_url
->GetType() !=
2297 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
)) {
2298 template_url
->data_
.sync_guid
= base::GenerateGUID();
2299 if (web_data_service_
.get())
2300 web_data_service_
->UpdateKeyword(template_url
->data());
2305 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
2306 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2307 &dsp_change_origin_
, DSP_CHANGE_SYNC_PREF
);
2309 std::string new_guid
=
2310 prefs_
->GetString(prefs::kSyncedDefaultSearchProviderGUID
);
2311 if (new_guid
.empty()) {
2312 default_search_manager_
.ClearUserSelectedDefaultSearchEngine();
2316 TemplateURL
* turl
= GetTemplateURLForGUID(new_guid
);
2318 default_search_manager_
.SetUserSelectedDefaultSearchEngine(turl
->data());
2321 TemplateURL
* TemplateURLService::FindPrepopulatedTemplateURL(
2322 int prepopulated_id
) {
2323 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2324 i
!= template_urls_
.end(); ++i
) {
2325 if ((*i
)->prepopulate_id() == prepopulated_id
)
2331 TemplateURL
* TemplateURLService::FindTemplateURLForExtension(
2332 const std::string
& extension_id
,
2333 TemplateURL::Type type
) {
2334 DCHECK_NE(TemplateURL::NORMAL
, type
);
2335 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2336 i
!= template_urls_
.end(); ++i
) {
2337 if ((*i
)->GetType() == type
&&
2338 (*i
)->GetExtensionId() == extension_id
)
2344 TemplateURL
* TemplateURLService::FindMatchingExtensionTemplateURL(
2345 const TemplateURLData
& data
,
2346 TemplateURL::Type type
) {
2347 DCHECK_NE(TemplateURL::NORMAL
, type
);
2348 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2349 i
!= template_urls_
.end(); ++i
) {
2350 if ((*i
)->GetType() == type
&&
2351 TemplateURL::MatchesData(*i
, &data
, search_terms_data()))
2357 void TemplateURLService::UpdateExtensionDefaultSearchEngine() {
2358 TemplateURL
* most_recently_intalled_default
= NULL
;
2359 for (TemplateURLVector::const_iterator i
= template_urls_
.begin();
2360 i
!= template_urls_
.end(); ++i
) {
2361 if (((*i
)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION
) &&
2362 (*i
)->extension_info_
->wants_to_be_default_engine
&&
2363 (*i
)->SupportsReplacement(search_terms_data()) &&
2364 (!most_recently_intalled_default
||
2365 (most_recently_intalled_default
->extension_info_
->install_time
<
2366 (*i
)->extension_info_
->install_time
)))
2367 most_recently_intalled_default
= *i
;
2370 if (most_recently_intalled_default
) {
2371 base::AutoReset
<DefaultSearchChangeOrigin
> change_origin(
2372 &dsp_change_origin_
, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION
);
2373 default_search_manager_
.SetExtensionControlledDefaultSearchEngine(
2374 most_recently_intalled_default
->data());
2376 default_search_manager_
.ClearExtensionControlledDefaultSearchEngine();