Add a stub __cxa_demangle to disable LLVM's demangler.
[chromium-blink-merge.git] / components / search_engines / template_url_service.cc
blobf0c4d8ea3d831723cf083ce620701fdb99083117
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"
7 #include <algorithm>
8 #include <utility>
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/guid.h"
14 #include "base/i18n/case_conversion.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/metrics/histogram_macros.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/profiler/scoped_tracker.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/time/default_clock.h"
24 #include "base/time/time.h"
25 #include "components/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"
41 #include "url/gurl.h"
43 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet;
44 typedef TemplateURLService::SyncDataMap SyncDataMap;
46 namespace {
48 bool IdenticalSyncGUIDs(const TemplateURLData* data, const TemplateURL* turl) {
49 if (!data || !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,
64 DELETE_ENGINE_MAX,
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|.
70 // The criteria is:
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())
89 return true;
90 if (type == syncer::SyncChange::ACTION_ADD &&
91 sync_data->find(guid) != sync_data->end())
92 return true;
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() ==
98 guid))
99 return true;
102 return false;
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);
115 else
116 ++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.
141 int num_dupes = 0;
142 for (std::map<std::string, int>::const_iterator it = duplicates.begin();
143 it != duplicates.end(); ++it) {
144 if (it->second > 1)
145 num_dupes++;
148 UMA_HISTOGRAM_COUNTS_100("Search.SearchEngineDuplicateCounts", num_dupes);
151 } // namespace
154 // TemplateURLService::LessWithPrefix -----------------------------------------
156 class TemplateURLService::LessWithPrefix {
157 public:
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(
182 PrefService* prefs,
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)
189 : prefs_(prefs),
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),
197 loaded_(false),
198 load_failed_(false),
199 load_handle_(0),
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_(
207 prefs_,
208 base::Bind(&TemplateURLService::OnDefaultSearchChange,
209 base::Unretained(this))) {
210 DCHECK(search_terms_data_);
211 Init(NULL, 0);
214 TemplateURLService::TemplateURLService(const Initializer* initializers,
215 const int count)
216 : prefs_(NULL),
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),
222 loaded_(false),
223 load_failed_(false),
224 load_handle_(0),
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_(
232 prefs_,
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_);
244 // static
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::CanAddAutogeneratedKeyword(
280 const base::string16& keyword,
281 const GURL& url,
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;
289 if (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. We still may not allow this
296 // keyword if there's evidence we may have created this keyword before and
297 // the user renamed it (because, for instance, the keyword is a common word
298 // that may interfere with search queries). An easy heuristic for this is
299 // whether the user has a TemplateURL that has been manually modified (e.g.,
300 // renamed) connected to the same host.
301 return !url.is_valid() || url.host().empty() ||
302 CanAddAutogeneratedKeywordForHost(url.host());
305 void TemplateURLService::FindMatchingKeywords(
306 const base::string16& prefix,
307 bool support_replacement_only,
308 TemplateURLVector* matches) {
309 // Sanity check args.
310 if (prefix.empty())
311 return;
312 DCHECK(matches != NULL);
313 DCHECK(matches->empty()); // The code for exact matches assumes this.
315 // Required for VS2010: http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
316 TemplateURL* const kNullTemplateURL = NULL;
318 // Find matching keyword range. Searches the element map for keywords
319 // beginning with |prefix| and stores the endpoints of the resulting set in
320 // |match_range|.
321 const std::pair<KeywordToTemplateMap::const_iterator,
322 KeywordToTemplateMap::const_iterator> match_range(
323 std::equal_range(
324 keyword_to_template_map_.begin(), keyword_to_template_map_.end(),
325 KeywordToTemplateMap::value_type(prefix, kNullTemplateURL),
326 LessWithPrefix()));
328 // Return vector of matching keywords.
329 for (KeywordToTemplateMap::const_iterator i(match_range.first);
330 i != match_range.second; ++i) {
331 if (!support_replacement_only ||
332 i->second->url_ref().SupportsReplacement(search_terms_data()))
333 matches->push_back(i->second);
337 TemplateURL* TemplateURLService::GetTemplateURLForKeyword(
338 const base::string16& keyword) {
339 KeywordToTemplateMap::const_iterator elem(
340 keyword_to_template_map_.find(keyword));
341 if (elem != keyword_to_template_map_.end())
342 return elem->second;
343 return (!loaded_ &&
344 initial_default_search_provider_.get() &&
345 (initial_default_search_provider_->keyword() == keyword)) ?
346 initial_default_search_provider_.get() : NULL;
349 TemplateURL* TemplateURLService::GetTemplateURLForGUID(
350 const std::string& sync_guid) {
351 GUIDToTemplateMap::const_iterator elem(guid_to_template_map_.find(sync_guid));
352 if (elem != guid_to_template_map_.end())
353 return elem->second;
354 return (!loaded_ &&
355 initial_default_search_provider_.get() &&
356 (initial_default_search_provider_->sync_guid() == sync_guid)) ?
357 initial_default_search_provider_.get() : NULL;
360 TemplateURL* TemplateURLService::GetTemplateURLForHost(
361 const std::string& host) {
362 if (loaded_)
363 return provider_map_->GetTemplateURLForHost(host);
364 TemplateURL* initial_dsp = initial_default_search_provider_.get();
365 if (!initial_dsp)
366 return NULL;
367 return (initial_dsp->GenerateSearchURL(search_terms_data()).host() == host) ?
368 initial_dsp : NULL;
371 bool TemplateURLService::Add(TemplateURL* template_url) {
372 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
373 if (!AddNoNotify(template_url, true))
374 return false;
375 NotifyObservers();
376 return true;
379 void TemplateURLService::AddWithOverrides(TemplateURL* template_url,
380 const base::string16& short_name,
381 const base::string16& keyword,
382 const std::string& url) {
383 DCHECK(!short_name.empty());
384 DCHECK(!keyword.empty());
385 DCHECK(!url.empty());
386 template_url->data_.SetShortName(short_name);
387 template_url->data_.SetKeyword(keyword);
388 template_url->SetURL(url);
389 Add(template_url);
392 void TemplateURLService::AddExtensionControlledTURL(
393 TemplateURL* template_url,
394 scoped_ptr<TemplateURL::AssociatedExtensionInfo> info) {
395 DCHECK(loaded_);
396 DCHECK(template_url);
397 DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
398 DCHECK(info);
399 DCHECK_NE(TemplateURL::NORMAL, info->type);
400 DCHECK_EQ(info->wants_to_be_default_engine,
401 template_url->show_in_default_list());
402 DCHECK(!FindTemplateURLForExtension(info->extension_id, info->type));
403 template_url->extension_info_.swap(info);
405 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
406 if (AddNoNotify(template_url, true)) {
407 if (template_url->extension_info_->wants_to_be_default_engine)
408 UpdateExtensionDefaultSearchEngine();
409 NotifyObservers();
413 void TemplateURLService::Remove(TemplateURL* template_url) {
414 RemoveNoNotify(template_url);
415 NotifyObservers();
418 void TemplateURLService::RemoveExtensionControlledTURL(
419 const std::string& extension_id,
420 TemplateURL::Type type) {
421 DCHECK(loaded_);
422 TemplateURL* url = FindTemplateURLForExtension(extension_id, type);
423 if (!url)
424 return;
425 // NULL this out so that we can call RemoveNoNotify.
426 // UpdateExtensionDefaultSearchEngine will cause it to be reset.
427 if (default_search_provider_ == url)
428 default_search_provider_ = NULL;
429 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
430 RemoveNoNotify(url);
431 UpdateExtensionDefaultSearchEngine();
432 NotifyObservers();
435 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after) {
436 RemoveAutoGeneratedBetween(created_after, base::Time());
439 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after,
440 base::Time created_before) {
441 RemoveAutoGeneratedForOriginBetween(GURL(), created_after, created_before);
444 void TemplateURLService::RemoveAutoGeneratedForOriginBetween(
445 const GURL& origin,
446 base::Time created_after,
447 base::Time created_before) {
448 GURL o(origin.GetOrigin());
449 bool should_notify = false;
450 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
451 for (size_t i = 0; i < template_urls_.size();) {
452 if (template_urls_[i]->date_created() >= created_after &&
453 (created_before.is_null() ||
454 template_urls_[i]->date_created() < created_before) &&
455 CanReplace(template_urls_[i]) &&
456 (o.is_empty() ||
457 template_urls_[i]->GenerateSearchURL(
458 search_terms_data()).GetOrigin() == o)) {
459 RemoveNoNotify(template_urls_[i]);
460 should_notify = true;
461 } else {
462 ++i;
465 if (should_notify)
466 NotifyObservers();
469 void TemplateURLService::RegisterOmniboxKeyword(
470 const std::string& extension_id,
471 const std::string& extension_name,
472 const std::string& keyword,
473 const std::string& template_url_string) {
474 DCHECK(loaded_);
476 if (FindTemplateURLForExtension(extension_id,
477 TemplateURL::OMNIBOX_API_EXTENSION))
478 return;
480 TemplateURLData data;
481 data.SetShortName(base::UTF8ToUTF16(extension_name));
482 data.SetKeyword(base::UTF8ToUTF16(keyword));
483 data.SetURL(template_url_string);
484 TemplateURL* url = new TemplateURL(data);
485 scoped_ptr<TemplateURL::AssociatedExtensionInfo> info(
486 new TemplateURL::AssociatedExtensionInfo(
487 TemplateURL::OMNIBOX_API_EXTENSION, extension_id));
488 AddExtensionControlledTURL(url, info.Pass());
491 TemplateURLService::TemplateURLVector TemplateURLService::GetTemplateURLs() {
492 return template_urls_;
495 void TemplateURLService::IncrementUsageCount(TemplateURL* url) {
496 DCHECK(url);
497 // Extension-controlled search engines are not persisted.
498 if (url->GetType() != TemplateURL::NORMAL)
499 return;
500 if (std::find(template_urls_.begin(), template_urls_.end(), url) ==
501 template_urls_.end())
502 return;
503 ++url->data_.usage_count;
505 if (web_data_service_.get())
506 web_data_service_->UpdateKeyword(url->data());
509 void TemplateURLService::ResetTemplateURL(TemplateURL* url,
510 const base::string16& title,
511 const base::string16& keyword,
512 const std::string& search_url) {
513 if (ResetTemplateURLNoNotify(url, title, keyword, search_url))
514 NotifyObservers();
517 bool TemplateURLService::CanMakeDefault(const TemplateURL* url) {
518 return
519 ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
520 (default_search_provider_source_ ==
521 DefaultSearchManager::FROM_FALLBACK)) &&
522 (url != GetDefaultSearchProvider()) &&
523 url->url_ref().SupportsReplacement(search_terms_data()) &&
524 (url->GetType() == TemplateURL::NORMAL);
527 void TemplateURLService::SetUserSelectedDefaultSearchProvider(
528 TemplateURL* url) {
529 // Omnibox keywords cannot be made default. Extension-controlled search
530 // engines can be made default only by the extension itself because they
531 // aren't persisted.
532 DCHECK(!url || (url->GetType() == TemplateURL::NORMAL));
533 if (load_failed_) {
534 // Skip the DefaultSearchManager, which will persist to user preferences.
535 if ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
536 (default_search_provider_source_ ==
537 DefaultSearchManager::FROM_FALLBACK)) {
538 ApplyDefaultSearchChange(url ? &url->data() : NULL,
539 DefaultSearchManager::FROM_USER);
541 } else {
542 // We rely on the DefaultSearchManager to call OnDefaultSearchChange if, in
543 // fact, the effective DSE changes.
544 if (url)
545 default_search_manager_.SetUserSelectedDefaultSearchEngine(url->data());
546 else
547 default_search_manager_.ClearUserSelectedDefaultSearchEngine();
551 TemplateURL* TemplateURLService::GetDefaultSearchProvider() {
552 return const_cast<TemplateURL*>(
553 static_cast<const TemplateURLService*>(this)->GetDefaultSearchProvider());
556 const TemplateURL* TemplateURLService::GetDefaultSearchProvider() const {
557 return loaded_ ? default_search_provider_
558 : initial_default_search_provider_.get();
561 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
562 const GURL& url) const {
563 const TemplateURL* default_provider = GetDefaultSearchProvider();
564 return default_provider &&
565 default_provider->IsSearchURL(url, search_terms_data());
568 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
569 return default_search_provider_source_ ==
570 DefaultSearchManager::FROM_EXTENSION;
573 void TemplateURLService::RepairPrepopulatedSearchEngines() {
574 // Can't clean DB if it hasn't been loaded.
575 DCHECK(loaded());
577 if ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
578 (default_search_provider_source_ ==
579 DefaultSearchManager::FROM_FALLBACK)) {
580 // Clear |default_search_provider_| in case we want to remove the engine it
581 // points to. This will get reset at the end of the function anyway.
582 default_search_provider_ = NULL;
585 size_t default_search_provider_index = 0;
586 ScopedVector<TemplateURLData> prepopulated_urls =
587 TemplateURLPrepopulateData::GetPrepopulatedEngines(
588 prefs_, &default_search_provider_index);
589 DCHECK(!prepopulated_urls.empty());
590 ActionsFromPrepopulateData actions(CreateActionsFromCurrentPrepopulateData(
591 &prepopulated_urls, template_urls_, default_search_provider_));
593 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
595 // Remove items.
596 for (std::vector<TemplateURL*>::iterator i = actions.removed_engines.begin();
597 i < actions.removed_engines.end(); ++i)
598 RemoveNoNotify(*i);
600 // Edit items.
601 for (EditedEngines::iterator i(actions.edited_engines.begin());
602 i < actions.edited_engines.end(); ++i) {
603 TemplateURL new_values(i->second);
604 UpdateNoNotify(i->first, new_values);
607 // Add items.
608 for (std::vector<TemplateURLData>::const_iterator i =
609 actions.added_engines.begin();
610 i < actions.added_engines.end();
611 ++i) {
612 AddNoNotify(new TemplateURL(*i), true);
615 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
616 &dsp_change_origin_, DSP_CHANGE_PROFILE_RESET);
618 default_search_manager_.ClearUserSelectedDefaultSearchEngine();
620 if (!default_search_provider_) {
621 // If the default search provider came from a user pref we would have been
622 // notified of the new (fallback-provided) value in
623 // ClearUserSelectedDefaultSearchEngine() above. Since we are here, the
624 // value was presumably originally a fallback value (which may have been
625 // repaired).
626 DefaultSearchManager::Source source;
627 const TemplateURLData* new_dse =
628 default_search_manager_.GetDefaultSearchEngine(&source);
629 // ApplyDefaultSearchChange will notify observers once it is done.
630 ApplyDefaultSearchChange(new_dse, source);
631 } else {
632 NotifyObservers();
636 void TemplateURLService::AddObserver(TemplateURLServiceObserver* observer) {
637 model_observers_.AddObserver(observer);
640 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver* observer) {
641 model_observers_.RemoveObserver(observer);
644 void TemplateURLService::Load() {
645 if (loaded_ || load_handle_)
646 return;
648 if (web_data_service_.get())
649 load_handle_ = web_data_service_->GetKeywords(this);
650 else
651 ChangeToLoadedState();
654 scoped_ptr<TemplateURLService::Subscription>
655 TemplateURLService::RegisterOnLoadedCallback(
656 const base::Closure& callback) {
657 return loaded_ ?
658 scoped_ptr<TemplateURLService::Subscription>() :
659 on_loaded_callbacks_.Add(callback);
662 void TemplateURLService::OnWebDataServiceRequestDone(
663 KeywordWebDataService::Handle h,
664 const WDTypedResult* result) {
665 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
666 // fixed.
667 tracked_objects::ScopedTracker tracking_profile(
668 FROM_HERE_WITH_EXPLICIT_FUNCTION(
669 "422460 TemplateURLService::OnWebDataServiceRequestDone"));
671 // Reset the load_handle so that we don't try and cancel the load in
672 // the destructor.
673 load_handle_ = 0;
675 if (!result) {
676 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
677 // is fixed.
678 tracked_objects::ScopedTracker tracking_profile1(
679 FROM_HERE_WITH_EXPLICIT_FUNCTION(
680 "422460 TemplateURLService::OnWebDataServiceRequestDone 1"));
682 // Results are null if the database went away or (most likely) wasn't
683 // loaded.
684 load_failed_ = true;
685 web_data_service_ = NULL;
686 ChangeToLoadedState();
687 return;
690 TemplateURLVector template_urls;
691 int new_resource_keyword_version = 0;
693 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
694 // is fixed.
695 tracked_objects::ScopedTracker tracking_profile2(
696 FROM_HERE_WITH_EXPLICIT_FUNCTION(
697 "422460 TemplateURLService::OnWebDataServiceRequestDone 2"));
699 GetSearchProvidersUsingKeywordResult(
700 *result, web_data_service_.get(), prefs_, &template_urls,
701 (default_search_provider_source_ == DefaultSearchManager::FROM_USER)
702 ? initial_default_search_provider_.get()
703 : NULL,
704 search_terms_data(), &new_resource_keyword_version, &pre_sync_deletes_);
707 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
710 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
711 // is fixed.
712 tracked_objects::ScopedTracker tracking_profile4(
713 FROM_HERE_WITH_EXPLICIT_FUNCTION(
714 "422460 TemplateURLService::OnWebDataServiceRequestDone 4"));
716 PatchMissingSyncGUIDs(&template_urls);
718 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
719 // is fixed.
720 tracked_objects::ScopedTracker tracking_profile41(
721 FROM_HERE_WITH_EXPLICIT_FUNCTION(
722 "422460 TemplateURLService::OnWebDataServiceRequestDone 41"));
724 SetTemplateURLs(&template_urls);
726 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
727 // is fixed.
728 tracked_objects::ScopedTracker tracking_profile42(
729 FROM_HERE_WITH_EXPLICIT_FUNCTION(
730 "422460 TemplateURLService::OnWebDataServiceRequestDone 42"));
732 // This initializes provider_map_ which should be done before
733 // calling UpdateKeywordSearchTermsForURL.
734 // This also calls NotifyObservers.
735 ChangeToLoadedState();
737 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
738 // is fixed.
739 tracked_objects::ScopedTracker tracking_profile43(
740 FROM_HERE_WITH_EXPLICIT_FUNCTION(
741 "422460 TemplateURLService::OnWebDataServiceRequestDone 43"));
743 // Index any visits that occurred before we finished loading.
744 for (size_t i = 0; i < visits_to_add_.size(); ++i)
745 UpdateKeywordSearchTermsForURL(visits_to_add_[i]);
746 visits_to_add_.clear();
748 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
749 // is fixed.
750 tracked_objects::ScopedTracker tracking_profile44(
751 FROM_HERE_WITH_EXPLICIT_FUNCTION(
752 "422460 TemplateURLService::OnWebDataServiceRequestDone 44"));
754 if (new_resource_keyword_version)
755 web_data_service_->SetBuiltinKeywordVersion(new_resource_keyword_version);
758 if (default_search_provider_) {
759 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460
760 // is fixed.
761 tracked_objects::ScopedTracker tracking_profile5(
762 FROM_HERE_WITH_EXPLICIT_FUNCTION(
763 "422460 TemplateURLService::OnWebDataServiceRequestDone 5"));
765 UMA_HISTOGRAM_ENUMERATION(
766 "Search.DefaultSearchProviderType",
767 TemplateURLPrepopulateData::GetEngineType(
768 *default_search_provider_, search_terms_data()),
769 SEARCH_ENGINE_MAX);
771 if (rappor_service_) {
772 rappor_service_->RecordSample(
773 "Search.DefaultSearchProvider",
774 rappor::ETLD_PLUS_ONE_RAPPOR_TYPE,
775 net::registry_controlled_domains::GetDomainAndRegistry(
776 default_search_provider_->url_ref().GetHost(search_terms_data()),
777 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
782 base::string16 TemplateURLService::GetKeywordShortName(
783 const base::string16& keyword,
784 bool* is_omnibox_api_extension_keyword) {
785 const TemplateURL* template_url = GetTemplateURLForKeyword(keyword);
787 // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
788 // to track changes to the model, this should become a DCHECK.
789 if (template_url) {
790 *is_omnibox_api_extension_keyword =
791 template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
792 return template_url->AdjustedShortNameForLocaleDirection();
794 *is_omnibox_api_extension_keyword = false;
795 return base::string16();
798 void TemplateURLService::OnHistoryURLVisited(const URLVisitedDetails& details) {
799 if (!loaded_)
800 visits_to_add_.push_back(details);
801 else
802 UpdateKeywordSearchTermsForURL(details);
805 void TemplateURLService::Shutdown() {
806 if (client_)
807 client_->Shutdown();
808 // This check has to be done at Shutdown() instead of in the dtor to ensure
809 // that no clients of KeywordWebDataService are holding ptrs to it after the
810 // first phase of the KeyedService Shutdown() process.
811 if (load_handle_) {
812 DCHECK(web_data_service_.get());
813 web_data_service_->CancelRequest(load_handle_);
815 web_data_service_ = NULL;
818 syncer::SyncDataList TemplateURLService::GetAllSyncData(
819 syncer::ModelType type) const {
820 DCHECK_EQ(syncer::SEARCH_ENGINES, type);
822 syncer::SyncDataList current_data;
823 for (TemplateURLVector::const_iterator iter = template_urls_.begin();
824 iter != template_urls_.end(); ++iter) {
825 // We don't sync keywords managed by policy.
826 if ((*iter)->created_by_policy())
827 continue;
828 // We don't sync extension-controlled search engines.
829 if ((*iter)->GetType() != TemplateURL::NORMAL)
830 continue;
831 current_data.push_back(CreateSyncDataFromTemplateURL(**iter));
834 return current_data;
837 syncer::SyncError TemplateURLService::ProcessSyncChanges(
838 const tracked_objects::Location& from_here,
839 const syncer::SyncChangeList& change_list) {
840 if (!models_associated_) {
841 syncer::SyncError error(FROM_HERE,
842 syncer::SyncError::DATATYPE_ERROR,
843 "Models not yet associated.",
844 syncer::SEARCH_ENGINES);
845 return error;
847 DCHECK(loaded_);
849 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
851 // We've started syncing, so set our origin member to the base Sync value.
852 // As we move through Sync Code, we may set this to increasingly specific
853 // origins so we can tell what exactly caused a DSP change.
854 base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
855 DSP_CHANGE_SYNC_UNINTENTIONAL);
857 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
859 syncer::SyncChangeList new_changes;
860 syncer::SyncError error;
861 for (syncer::SyncChangeList::const_iterator iter = change_list.begin();
862 iter != change_list.end(); ++iter) {
863 DCHECK_EQ(syncer::SEARCH_ENGINES, iter->sync_data().GetDataType());
865 std::string guid =
866 iter->sync_data().GetSpecifics().search_engine().sync_guid();
867 TemplateURL* existing_turl = GetTemplateURLForGUID(guid);
868 scoped_ptr<TemplateURL> turl(CreateTemplateURLFromTemplateURLAndSyncData(
869 client_.get(), prefs_, search_terms_data(), existing_turl,
870 iter->sync_data(), &new_changes));
871 if (!turl.get())
872 continue;
874 // Explicitly don't check for conflicts against extension keywords; in this
875 // case the functions which modify the keyword map know how to handle the
876 // conflicts.
877 // TODO(mpcomplete): If we allow editing extension keywords, then those will
878 // need to undergo conflict resolution.
879 TemplateURL* existing_keyword_turl =
880 FindNonExtensionTemplateURLForKeyword(turl->keyword());
881 if (iter->change_type() == syncer::SyncChange::ACTION_DELETE) {
882 if (!existing_turl) {
883 error = sync_error_factory_->CreateAndUploadError(
884 FROM_HERE,
885 "ProcessSyncChanges failed on ChangeType ACTION_DELETE");
886 continue;
888 if (existing_turl == GetDefaultSearchProvider()) {
889 // The only way Sync can attempt to delete the default search provider
890 // is if we had changed the kSyncedDefaultSearchProviderGUID
891 // preference, but perhaps it has not yet been received. To avoid
892 // situations where this has come in erroneously, we will un-delete
893 // the current default search from the Sync data. If the pref really
894 // does arrive later, then default search will change to the correct
895 // entry, but we'll have this extra entry sitting around. The result is
896 // not ideal, but it prevents a far more severe bug where the default is
897 // unexpectedly swapped to something else. The user can safely delete
898 // the extra entry again later, if they choose. Most users who do not
899 // look at the search engines UI will not notice this.
900 // Note that we append a special character to the end of the keyword in
901 // an attempt to avoid a ping-poinging situation where receiving clients
902 // may try to continually delete the resurrected entry.
903 base::string16 updated_keyword = UniquifyKeyword(*existing_turl, true);
904 TemplateURLData data(existing_turl->data());
905 data.SetKeyword(updated_keyword);
906 TemplateURL new_turl(data);
907 if (UpdateNoNotify(existing_turl, new_turl))
908 NotifyObservers();
910 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(new_turl);
911 new_changes.push_back(syncer::SyncChange(FROM_HERE,
912 syncer::SyncChange::ACTION_ADD,
913 sync_data));
914 // Ignore the delete attempt. This means we never end up resetting the
915 // default search provider due to an ACTION_DELETE from sync.
916 continue;
919 Remove(existing_turl);
920 } else if (iter->change_type() == syncer::SyncChange::ACTION_ADD) {
921 if (existing_turl) {
922 error = sync_error_factory_->CreateAndUploadError(
923 FROM_HERE,
924 "ProcessSyncChanges failed on ChangeType ACTION_ADD");
925 continue;
927 const std::string guid = turl->sync_guid();
928 if (existing_keyword_turl) {
929 // Resolve any conflicts so we can safely add the new entry.
930 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
931 &new_changes);
933 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
934 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
935 // Force the local ID to kInvalidTemplateURLID so we can add it.
936 TemplateURLData data(turl->data());
937 data.id = kInvalidTemplateURLID;
938 TemplateURL* added = new TemplateURL(data);
939 if (Add(added))
940 MaybeUpdateDSEAfterSync(added);
941 } else if (iter->change_type() == syncer::SyncChange::ACTION_UPDATE) {
942 if (!existing_turl) {
943 error = sync_error_factory_->CreateAndUploadError(
944 FROM_HERE,
945 "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
946 continue;
948 if (existing_keyword_turl && (existing_keyword_turl != existing_turl)) {
949 // Resolve any conflicts with other entries so we can safely update the
950 // keyword.
951 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
952 &new_changes);
954 if (UpdateNoNotify(existing_turl, *turl)) {
955 NotifyObservers();
956 MaybeUpdateDSEAfterSync(existing_turl);
958 } else {
959 // We've unexpectedly received an ACTION_INVALID.
960 error = sync_error_factory_->CreateAndUploadError(
961 FROM_HERE,
962 "ProcessSyncChanges received an ACTION_INVALID");
966 // If something went wrong, we want to prematurely exit to avoid pushing
967 // inconsistent data to Sync. We return the last error we received.
968 if (error.IsSet())
969 return error;
971 error = sync_processor_->ProcessSyncChanges(from_here, new_changes);
973 return error;
976 syncer::SyncMergeResult TemplateURLService::MergeDataAndStartSyncing(
977 syncer::ModelType type,
978 const syncer::SyncDataList& initial_sync_data,
979 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
980 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) {
981 DCHECK(loaded_);
982 DCHECK_EQ(type, syncer::SEARCH_ENGINES);
983 DCHECK(!sync_processor_.get());
984 DCHECK(sync_processor.get());
985 DCHECK(sync_error_factory.get());
986 syncer::SyncMergeResult merge_result(type);
988 // Disable sync if we failed to load.
989 if (load_failed_) {
990 merge_result.set_error(syncer::SyncError(
991 FROM_HERE, syncer::SyncError::DATATYPE_ERROR,
992 "Local database load failed.", syncer::SEARCH_ENGINES));
993 return merge_result;
996 sync_processor_ = sync_processor.Pass();
997 sync_error_factory_ = sync_error_factory.Pass();
999 // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
1000 // don't step on our own toes.
1001 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
1003 // We've started syncing, so set our origin member to the base Sync value.
1004 // As we move through Sync Code, we may set this to increasingly specific
1005 // origins so we can tell what exactly caused a DSP change.
1006 base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
1007 DSP_CHANGE_SYNC_UNINTENTIONAL);
1009 syncer::SyncChangeList new_changes;
1011 // Build maps of our sync GUIDs to syncer::SyncData.
1012 SyncDataMap local_data_map = CreateGUIDToSyncDataMap(
1013 GetAllSyncData(syncer::SEARCH_ENGINES));
1014 SyncDataMap sync_data_map = CreateGUIDToSyncDataMap(initial_sync_data);
1016 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1018 merge_result.set_num_items_before_association(local_data_map.size());
1019 for (SyncDataMap::const_iterator iter = sync_data_map.begin();
1020 iter != sync_data_map.end(); ++iter) {
1021 TemplateURL* local_turl = GetTemplateURLForGUID(iter->first);
1022 scoped_ptr<TemplateURL> sync_turl(
1023 CreateTemplateURLFromTemplateURLAndSyncData(
1024 client_.get(), prefs_, search_terms_data(), local_turl,
1025 iter->second, &new_changes));
1026 if (!sync_turl.get())
1027 continue;
1029 if (pre_sync_deletes_.find(sync_turl->sync_guid()) !=
1030 pre_sync_deletes_.end()) {
1031 // This entry was deleted before the initial sync began (possibly through
1032 // preprocessing in TemplateURLService's loading code). Ignore it and send
1033 // an ACTION_DELETE up to the server.
1034 new_changes.push_back(
1035 syncer::SyncChange(FROM_HERE,
1036 syncer::SyncChange::ACTION_DELETE,
1037 iter->second));
1038 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1039 DELETE_ENGINE_PRE_SYNC, DELETE_ENGINE_MAX);
1040 continue;
1043 if (local_turl) {
1044 DCHECK(IsFromSync(local_turl, sync_data_map));
1045 // This local search engine is already synced. If the timestamp differs
1046 // from Sync, we need to update locally or to the cloud. Note that if the
1047 // timestamps are equal, we touch neither.
1048 if (sync_turl->last_modified() > local_turl->last_modified()) {
1049 // We've received an update from Sync. We should replace all synced
1050 // fields in the local TemplateURL. Note that this includes the
1051 // TemplateURLID and the TemplateURL may have to be reparsed. This
1052 // also makes the local data's last_modified timestamp equal to Sync's,
1053 // avoiding an Update on the next MergeData call.
1054 if (UpdateNoNotify(local_turl, *sync_turl))
1055 NotifyObservers();
1056 merge_result.set_num_items_modified(
1057 merge_result.num_items_modified() + 1);
1058 } else if (sync_turl->last_modified() < local_turl->last_modified()) {
1059 // Otherwise, we know we have newer data, so update Sync with our
1060 // data fields.
1061 new_changes.push_back(
1062 syncer::SyncChange(FROM_HERE,
1063 syncer::SyncChange::ACTION_UPDATE,
1064 local_data_map[local_turl->sync_guid()]));
1066 local_data_map.erase(iter->first);
1067 } else {
1068 // The search engine from the cloud has not been synced locally. Merge it
1069 // into our local model. This will handle any conflicts with local (and
1070 // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1071 // over not-yet-synced TemplateURLs.
1072 MergeInSyncTemplateURL(sync_turl.get(), sync_data_map, &new_changes,
1073 &local_data_map, &merge_result);
1077 // The remaining SyncData in local_data_map should be everything that needs to
1078 // be pushed as ADDs to sync.
1079 for (SyncDataMap::const_iterator iter = local_data_map.begin();
1080 iter != local_data_map.end(); ++iter) {
1081 new_changes.push_back(
1082 syncer::SyncChange(FROM_HERE,
1083 syncer::SyncChange::ACTION_ADD,
1084 iter->second));
1087 // Do some post-processing on the change list to ensure that we are sending
1088 // valid changes to sync_processor_.
1089 PruneSyncChanges(&sync_data_map, &new_changes);
1091 LogDuplicatesHistogram(GetTemplateURLs());
1092 merge_result.set_num_items_after_association(
1093 GetAllSyncData(syncer::SEARCH_ENGINES).size());
1094 merge_result.set_error(
1095 sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
1096 if (merge_result.error().IsSet())
1097 return merge_result;
1099 // The ACTION_DELETEs from this set are processed. Empty it so we don't try to
1100 // reuse them on the next call to MergeDataAndStartSyncing.
1101 pre_sync_deletes_.clear();
1103 models_associated_ = true;
1104 return merge_result;
1107 void TemplateURLService::StopSyncing(syncer::ModelType type) {
1108 DCHECK_EQ(type, syncer::SEARCH_ENGINES);
1109 models_associated_ = false;
1110 sync_processor_.reset();
1111 sync_error_factory_.reset();
1114 void TemplateURLService::ProcessTemplateURLChange(
1115 const tracked_objects::Location& from_here,
1116 const TemplateURL* turl,
1117 syncer::SyncChange::SyncChangeType type) {
1118 DCHECK_NE(type, syncer::SyncChange::ACTION_INVALID);
1119 DCHECK(turl);
1121 if (!models_associated_)
1122 return; // Not syncing.
1124 if (processing_syncer_changes_)
1125 return; // These are changes originating from us. Ignore.
1127 // Avoid syncing keywords managed by policy.
1128 if (turl->created_by_policy())
1129 return;
1131 // Avoid syncing extension-controlled search engines.
1132 if (turl->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
1133 return;
1135 syncer::SyncChangeList changes;
1137 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1138 changes.push_back(syncer::SyncChange(from_here,
1139 type,
1140 sync_data));
1142 sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
1145 // static
1146 syncer::SyncData TemplateURLService::CreateSyncDataFromTemplateURL(
1147 const TemplateURL& turl) {
1148 sync_pb::EntitySpecifics specifics;
1149 sync_pb::SearchEngineSpecifics* se_specifics =
1150 specifics.mutable_search_engine();
1151 se_specifics->set_short_name(base::UTF16ToUTF8(turl.short_name()));
1152 se_specifics->set_keyword(base::UTF16ToUTF8(turl.keyword()));
1153 se_specifics->set_favicon_url(turl.favicon_url().spec());
1154 se_specifics->set_url(turl.url());
1155 se_specifics->set_safe_for_autoreplace(turl.safe_for_autoreplace());
1156 se_specifics->set_originating_url(turl.originating_url().spec());
1157 se_specifics->set_date_created(turl.date_created().ToInternalValue());
1158 se_specifics->set_input_encodings(JoinString(turl.input_encodings(), ';'));
1159 se_specifics->set_show_in_default_list(turl.show_in_default_list());
1160 se_specifics->set_suggestions_url(turl.suggestions_url());
1161 se_specifics->set_prepopulate_id(turl.prepopulate_id());
1162 se_specifics->set_instant_url(turl.instant_url());
1163 if (!turl.image_url().empty())
1164 se_specifics->set_image_url(turl.image_url());
1165 se_specifics->set_new_tab_url(turl.new_tab_url());
1166 if (!turl.search_url_post_params().empty())
1167 se_specifics->set_search_url_post_params(turl.search_url_post_params());
1168 if (!turl.suggestions_url_post_params().empty()) {
1169 se_specifics->set_suggestions_url_post_params(
1170 turl.suggestions_url_post_params());
1172 if (!turl.instant_url_post_params().empty())
1173 se_specifics->set_instant_url_post_params(turl.instant_url_post_params());
1174 if (!turl.image_url_post_params().empty())
1175 se_specifics->set_image_url_post_params(turl.image_url_post_params());
1176 se_specifics->set_last_modified(turl.last_modified().ToInternalValue());
1177 se_specifics->set_sync_guid(turl.sync_guid());
1178 for (size_t i = 0; i < turl.alternate_urls().size(); ++i)
1179 se_specifics->add_alternate_urls(turl.alternate_urls()[i]);
1180 se_specifics->set_search_terms_replacement_key(
1181 turl.search_terms_replacement_key());
1183 return syncer::SyncData::CreateLocalData(se_specifics->sync_guid(),
1184 se_specifics->keyword(),
1185 specifics);
1188 // static
1189 scoped_ptr<TemplateURL>
1190 TemplateURLService::CreateTemplateURLFromTemplateURLAndSyncData(
1191 TemplateURLServiceClient* client,
1192 PrefService* prefs,
1193 const SearchTermsData& search_terms_data,
1194 TemplateURL* existing_turl,
1195 const syncer::SyncData& sync_data,
1196 syncer::SyncChangeList* change_list) {
1197 DCHECK(change_list);
1199 sync_pb::SearchEngineSpecifics specifics =
1200 sync_data.GetSpecifics().search_engine();
1202 // Past bugs might have caused either of these fields to be empty. Just
1203 // delete this data off the server.
1204 if (specifics.url().empty() || specifics.sync_guid().empty()) {
1205 change_list->push_back(
1206 syncer::SyncChange(FROM_HERE,
1207 syncer::SyncChange::ACTION_DELETE,
1208 sync_data));
1209 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1210 DELETE_ENGINE_EMPTY_FIELD, DELETE_ENGINE_MAX);
1211 return NULL;
1214 TemplateURLData data(existing_turl ?
1215 existing_turl->data() : TemplateURLData());
1216 data.SetShortName(base::UTF8ToUTF16(specifics.short_name()));
1217 data.originating_url = GURL(specifics.originating_url());
1218 base::string16 keyword(base::UTF8ToUTF16(specifics.keyword()));
1219 // NOTE: Once this code has shipped in a couple of stable releases, we can
1220 // probably remove the migration portion, comment out the
1221 // "autogenerate_keyword" field entirely in the .proto file, and fold the
1222 // empty keyword case into the "delete data" block above.
1223 bool reset_keyword =
1224 specifics.autogenerate_keyword() || specifics.keyword().empty();
1225 if (reset_keyword)
1226 keyword = base::ASCIIToUTF16("dummy"); // Will be replaced below.
1227 DCHECK(!keyword.empty());
1228 data.SetKeyword(keyword);
1229 data.SetURL(specifics.url());
1230 data.suggestions_url = specifics.suggestions_url();
1231 data.instant_url = specifics.instant_url();
1232 data.image_url = specifics.image_url();
1233 data.new_tab_url = specifics.new_tab_url();
1234 data.search_url_post_params = specifics.search_url_post_params();
1235 data.suggestions_url_post_params = specifics.suggestions_url_post_params();
1236 data.instant_url_post_params = specifics.instant_url_post_params();
1237 data.image_url_post_params = specifics.image_url_post_params();
1238 data.favicon_url = GURL(specifics.favicon_url());
1239 data.show_in_default_list = specifics.show_in_default_list();
1240 data.safe_for_autoreplace = specifics.safe_for_autoreplace();
1241 base::SplitString(specifics.input_encodings(), ';', &data.input_encodings);
1242 // If the server data has duplicate encodings, we'll want to push an update
1243 // below to correct it. Note that we also fix this in
1244 // GetSearchProvidersUsingKeywordResult(), since otherwise we'd never correct
1245 // local problems for clients which have disabled search engine sync.
1246 bool deduped = DeDupeEncodings(&data.input_encodings);
1247 data.date_created = base::Time::FromInternalValue(specifics.date_created());
1248 data.last_modified = base::Time::FromInternalValue(specifics.last_modified());
1249 data.prepopulate_id = specifics.prepopulate_id();
1250 data.sync_guid = specifics.sync_guid();
1251 data.alternate_urls.clear();
1252 for (int i = 0; i < specifics.alternate_urls_size(); ++i)
1253 data.alternate_urls.push_back(specifics.alternate_urls(i));
1254 data.search_terms_replacement_key = specifics.search_terms_replacement_key();
1256 scoped_ptr<TemplateURL> turl(new TemplateURL(data));
1257 // If this TemplateURL matches a built-in prepopulated template URL, it's
1258 // possible that sync is trying to modify fields that should not be touched.
1259 // Revert these fields to the built-in values.
1260 UpdateTemplateURLIfPrepopulated(turl.get(), prefs);
1262 // We used to sync keywords associated with omnibox extensions, but no longer
1263 // want to. However, if we delete these keywords from sync, we'll break any
1264 // synced old versions of Chrome which were relying on them. Instead, for now
1265 // we simply ignore these.
1266 // TODO(vasilii): After a few Chrome versions, change this to go ahead and
1267 // delete these from sync.
1268 DCHECK(client);
1269 client->RestoreExtensionInfoIfNecessary(turl.get());
1270 if (turl->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)
1271 return NULL;
1273 DCHECK_EQ(TemplateURL::NORMAL, turl->GetType());
1274 if (reset_keyword || deduped) {
1275 if (reset_keyword)
1276 turl->ResetKeywordIfNecessary(search_terms_data, true);
1277 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1278 change_list->push_back(syncer::SyncChange(FROM_HERE,
1279 syncer::SyncChange::ACTION_UPDATE,
1280 sync_data));
1281 } else if (turl->IsGoogleSearchURLWithReplaceableKeyword(search_terms_data)) {
1282 if (!existing_turl) {
1283 // We're adding a new TemplateURL that uses the Google base URL, so set
1284 // its keyword appropriately for the local environment.
1285 turl->ResetKeywordIfNecessary(search_terms_data, false);
1286 } else if (existing_turl->IsGoogleSearchURLWithReplaceableKeyword(
1287 search_terms_data)) {
1288 // Ignore keyword changes triggered by the Google base URL changing on
1289 // another client. If the base URL changes in this client as well, we'll
1290 // pick that up separately at the appropriate time. Otherwise, changing
1291 // the keyword here could result in having the wrong keyword for the local
1292 // environment.
1293 turl->data_.SetKeyword(existing_turl->keyword());
1297 return turl.Pass();
1300 // static
1301 SyncDataMap TemplateURLService::CreateGUIDToSyncDataMap(
1302 const syncer::SyncDataList& sync_data) {
1303 SyncDataMap data_map;
1304 for (syncer::SyncDataList::const_iterator i(sync_data.begin());
1305 i != sync_data.end();
1306 ++i)
1307 data_map[i->GetSpecifics().search_engine().sync_guid()] = *i;
1308 return data_map;
1311 void TemplateURLService::Init(const Initializer* initializers,
1312 int num_initializers) {
1313 if (client_)
1314 client_->SetOwner(this);
1316 // GoogleURLTracker is not created in tests.
1317 if (google_url_tracker_) {
1318 google_url_updated_subscription_ =
1319 google_url_tracker_->RegisterCallback(base::Bind(
1320 &TemplateURLService::GoogleBaseURLChanged, base::Unretained(this)));
1323 if (prefs_) {
1324 pref_change_registrar_.Init(prefs_);
1325 pref_change_registrar_.Add(
1326 prefs::kSyncedDefaultSearchProviderGUID,
1327 base::Bind(
1328 &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged,
1329 base::Unretained(this)));
1332 DefaultSearchManager::Source source = DefaultSearchManager::FROM_USER;
1333 TemplateURLData* dse =
1334 default_search_manager_.GetDefaultSearchEngine(&source);
1335 ApplyDefaultSearchChange(dse, source);
1337 if (num_initializers > 0) {
1338 // This path is only hit by test code and is used to simulate a loaded
1339 // TemplateURLService.
1340 ChangeToLoadedState();
1342 // Add specific initializers, if any.
1343 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1344 for (int i(0); i < num_initializers; ++i) {
1345 DCHECK(initializers[i].keyword);
1346 DCHECK(initializers[i].url);
1347 DCHECK(initializers[i].content);
1349 // TemplateURLService ends up owning the TemplateURL, don't try and free
1350 // it.
1351 TemplateURLData data;
1352 data.SetShortName(base::UTF8ToUTF16(initializers[i].content));
1353 data.SetKeyword(base::UTF8ToUTF16(initializers[i].keyword));
1354 data.SetURL(initializers[i].url);
1355 TemplateURL* template_url = new TemplateURL(data);
1356 AddNoNotify(template_url, true);
1358 // Set the first provided identifier to be the default.
1359 if (i == 0)
1360 default_search_manager_.SetUserSelectedDefaultSearchEngine(data);
1364 // Request a server check for the correct Google URL if Google is the
1365 // default search engine.
1366 RequestGoogleURLTrackerServerCheckIfNecessary();
1369 void TemplateURLService::RemoveFromMaps(TemplateURL* template_url) {
1370 const base::string16& keyword = template_url->keyword();
1371 DCHECK_NE(0U, keyword_to_template_map_.count(keyword));
1372 if (keyword_to_template_map_[keyword] == template_url) {
1373 // We need to check whether the keyword can now be provided by another
1374 // TemplateURL. See the comments in AddToMaps() for more information on
1375 // extension keywords and how they can coexist with non-extension keywords.
1376 // In the case of more than one extension, we use the most recently
1377 // installed (which will be the most recently added, which will have the
1378 // highest ID).
1379 TemplateURL* best_fallback = NULL;
1380 for (TemplateURLVector::const_iterator i(template_urls_.begin());
1381 i != template_urls_.end(); ++i) {
1382 TemplateURL* turl = *i;
1383 // This next statement relies on the fact that there can only be one
1384 // non-Omnibox API TemplateURL with a given keyword.
1385 if ((turl != template_url) && (turl->keyword() == keyword) &&
1386 (!best_fallback ||
1387 (best_fallback->GetType() != TemplateURL::OMNIBOX_API_EXTENSION) ||
1388 ((turl->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) &&
1389 (turl->id() > best_fallback->id()))))
1390 best_fallback = turl;
1392 if (best_fallback)
1393 keyword_to_template_map_[keyword] = best_fallback;
1394 else
1395 keyword_to_template_map_.erase(keyword);
1398 if (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)
1399 return;
1401 if (!template_url->sync_guid().empty())
1402 guid_to_template_map_.erase(template_url->sync_guid());
1403 // |provider_map_| is only initialized after loading has completed.
1404 if (loaded_) {
1405 provider_map_->Remove(template_url);
1409 void TemplateURLService::AddToMaps(TemplateURL* template_url) {
1410 bool template_url_is_omnibox_api =
1411 template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1412 const base::string16& keyword = template_url->keyword();
1413 KeywordToTemplateMap::const_iterator i =
1414 keyword_to_template_map_.find(keyword);
1415 if (i == keyword_to_template_map_.end()) {
1416 keyword_to_template_map_[keyword] = template_url;
1417 } else {
1418 const TemplateURL* existing_url = i->second;
1419 // We should only have overlapping keywords when at least one comes from
1420 // an extension. In that case, the ranking order is:
1421 // Manually-modified keywords > extension keywords > replaceable keywords
1422 // When there are multiple extensions, the last-added wins.
1423 bool existing_url_is_omnibox_api =
1424 existing_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1425 DCHECK(existing_url_is_omnibox_api || template_url_is_omnibox_api);
1426 if (existing_url_is_omnibox_api ?
1427 !CanReplace(template_url) : CanReplace(existing_url))
1428 keyword_to_template_map_[keyword] = template_url;
1431 if (template_url_is_omnibox_api)
1432 return;
1434 if (!template_url->sync_guid().empty())
1435 guid_to_template_map_[template_url->sync_guid()] = template_url;
1436 // |provider_map_| is only initialized after loading has completed.
1437 if (loaded_)
1438 provider_map_->Add(template_url, search_terms_data());
1441 // Helper for partition() call in next function.
1442 bool HasValidID(TemplateURL* t_url) {
1443 return t_url->id() != kInvalidTemplateURLID;
1446 void TemplateURLService::SetTemplateURLs(TemplateURLVector* urls) {
1447 // Partition the URLs first, instead of implementing the loops below by simply
1448 // scanning the input twice. While it's not supposed to happen normally, it's
1449 // possible for corrupt databases to return multiple entries with the same
1450 // keyword. In this case, the first loop may delete the first entry when
1451 // adding the second. If this happens, the second loop must not attempt to
1452 // access the deleted entry. Partitioning ensures this constraint.
1453 TemplateURLVector::iterator first_invalid(
1454 std::partition(urls->begin(), urls->end(), HasValidID));
1456 // First, add the items that already have id's, so that the next_id_ gets
1457 // properly set.
1458 for (TemplateURLVector::const_iterator i = urls->begin(); i != first_invalid;
1459 ++i) {
1460 next_id_ = std::max(next_id_, (*i)->id());
1461 AddNoNotify(*i, false);
1464 // Next add the new items that don't have id's.
1465 for (TemplateURLVector::const_iterator i = first_invalid; i != urls->end();
1466 ++i)
1467 AddNoNotify(*i, true);
1469 // Clear the input vector to reduce the chance callers will try to use a
1470 // (possibly deleted) entry.
1471 urls->clear();
1474 void TemplateURLService::ChangeToLoadedState() {
1475 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1476 // fixed.
1477 tracked_objects::ScopedTracker tracking_profile1(
1478 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1479 "422460 TemplateURLService::ChangeToLoadedState 1"));
1481 DCHECK(!loaded_);
1483 provider_map_->Init(template_urls_, search_terms_data());
1484 loaded_ = true;
1486 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1487 // fixed.
1488 tracked_objects::ScopedTracker tracking_profile2(
1489 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1490 "422460 TemplateURLService::ChangeToLoadedState 2"));
1492 // This will cause a call to NotifyObservers().
1493 ApplyDefaultSearchChangeNoMetrics(
1494 initial_default_search_provider_ ?
1495 &initial_default_search_provider_->data() : NULL,
1496 default_search_provider_source_);
1497 initial_default_search_provider_.reset();
1499 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
1500 // fixed.
1501 tracked_objects::ScopedTracker tracking_profile3(
1502 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1503 "422460 TemplateURLService::ChangeToLoadedState 3"));
1505 on_loaded_callbacks_.Notify();
1508 bool TemplateURLService::CanAddAutogeneratedKeywordForHost(
1509 const std::string& host) {
1510 const TemplateURLSet* urls = provider_map_->GetURLsForHost(host);
1511 if (!urls)
1512 return true;
1513 for (TemplateURLSet::const_iterator i(urls->begin()); i != urls->end(); ++i) {
1514 if (!(*i)->safe_for_autoreplace())
1515 return false;
1517 return true;
1520 bool TemplateURLService::CanReplace(const TemplateURL* t_url) {
1521 return (t_url != default_search_provider_ && !t_url->show_in_default_list() &&
1522 t_url->safe_for_autoreplace());
1525 TemplateURL* TemplateURLService::FindNonExtensionTemplateURLForKeyword(
1526 const base::string16& keyword) {
1527 TemplateURL* keyword_turl = GetTemplateURLForKeyword(keyword);
1528 if (!keyword_turl || (keyword_turl->GetType() == TemplateURL::NORMAL))
1529 return keyword_turl;
1530 // The extension keyword in the model may be hiding a replaceable
1531 // non-extension keyword. Look for it.
1532 for (TemplateURLVector::const_iterator i(template_urls_.begin());
1533 i != template_urls_.end(); ++i) {
1534 if (((*i)->GetType() == TemplateURL::NORMAL) &&
1535 ((*i)->keyword() == keyword))
1536 return *i;
1538 return NULL;
1541 bool TemplateURLService::UpdateNoNotify(TemplateURL* existing_turl,
1542 const TemplateURL& new_values) {
1543 DCHECK(existing_turl);
1544 if (std::find(template_urls_.begin(), template_urls_.end(), existing_turl) ==
1545 template_urls_.end())
1546 return false;
1548 DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION, existing_turl->GetType());
1550 base::string16 old_keyword(existing_turl->keyword());
1551 keyword_to_template_map_.erase(old_keyword);
1552 if (!existing_turl->sync_guid().empty())
1553 guid_to_template_map_.erase(existing_turl->sync_guid());
1555 // |provider_map_| is only initialized after loading has completed.
1556 if (loaded_)
1557 provider_map_->Remove(existing_turl);
1559 TemplateURLID previous_id = existing_turl->id();
1560 existing_turl->CopyFrom(new_values);
1561 existing_turl->data_.id = previous_id;
1563 if (loaded_) {
1564 provider_map_->Add(existing_turl, search_terms_data());
1567 const base::string16& keyword = existing_turl->keyword();
1568 KeywordToTemplateMap::const_iterator i =
1569 keyword_to_template_map_.find(keyword);
1570 if (i == keyword_to_template_map_.end()) {
1571 keyword_to_template_map_[keyword] = existing_turl;
1572 } else {
1573 // We can theoretically reach here in two cases:
1574 // * There is an existing extension keyword and sync brings in a rename of
1575 // a non-extension keyword to match. In this case we just need to pick
1576 // which keyword has priority to update the keyword map.
1577 // * Autogeneration of the keyword for a Google default search provider
1578 // at load time causes it to conflict with an existing keyword. In this
1579 // case we delete the existing keyword if it's replaceable, or else undo
1580 // the change in keyword for |existing_turl|.
1581 TemplateURL* existing_keyword_turl = i->second;
1582 if (existing_keyword_turl->GetType() != TemplateURL::NORMAL) {
1583 if (!CanReplace(existing_turl))
1584 keyword_to_template_map_[keyword] = existing_turl;
1585 } else {
1586 if (CanReplace(existing_keyword_turl)) {
1587 RemoveNoNotify(existing_keyword_turl);
1588 } else {
1589 existing_turl->data_.SetKeyword(old_keyword);
1590 keyword_to_template_map_[old_keyword] = existing_turl;
1594 if (!existing_turl->sync_guid().empty())
1595 guid_to_template_map_[existing_turl->sync_guid()] = existing_turl;
1597 if (web_data_service_.get())
1598 web_data_service_->UpdateKeyword(existing_turl->data());
1600 // Inform sync of the update.
1601 ProcessTemplateURLChange(
1602 FROM_HERE, existing_turl, syncer::SyncChange::ACTION_UPDATE);
1604 if (default_search_provider_ == existing_turl &&
1605 default_search_provider_source_ == DefaultSearchManager::FROM_USER) {
1606 default_search_manager_.SetUserSelectedDefaultSearchEngine(
1607 default_search_provider_->data());
1609 return true;
1612 // static
1613 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1614 TemplateURL* template_url,
1615 PrefService* prefs) {
1616 int prepopulate_id = template_url->prepopulate_id();
1617 if (template_url->prepopulate_id() == 0)
1618 return;
1620 size_t default_search_index;
1621 ScopedVector<TemplateURLData> prepopulated_urls =
1622 TemplateURLPrepopulateData::GetPrepopulatedEngines(
1623 prefs, &default_search_index);
1625 for (size_t i = 0; i < prepopulated_urls.size(); ++i) {
1626 if (prepopulated_urls[i]->prepopulate_id == prepopulate_id) {
1627 MergeIntoPrepopulatedEngineData(template_url, prepopulated_urls[i]);
1628 template_url->CopyFrom(TemplateURL(*prepopulated_urls[i]));
1633 void TemplateURLService::MaybeUpdateDSEAfterSync(TemplateURL* synced_turl) {
1634 if (prefs_ &&
1635 (synced_turl->sync_guid() ==
1636 prefs_->GetString(prefs::kSyncedDefaultSearchProviderGUID))) {
1637 default_search_manager_.SetUserSelectedDefaultSearchEngine(
1638 synced_turl->data());
1642 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1643 const URLVisitedDetails& details) {
1644 if (!details.url.is_valid())
1645 return;
1647 const TemplateURLSet* urls_for_host =
1648 provider_map_->GetURLsForHost(details.url.host());
1649 if (!urls_for_host)
1650 return;
1652 for (TemplateURLSet::const_iterator i = urls_for_host->begin();
1653 i != urls_for_host->end(); ++i) {
1654 base::string16 search_terms;
1655 if ((*i)->ExtractSearchTermsFromURL(details.url, search_terms_data(),
1656 &search_terms) &&
1657 !search_terms.empty()) {
1658 if (details.is_keyword_transition) {
1659 // The visit is the result of the user entering a keyword, generate a
1660 // KEYWORD_GENERATED visit for the KEYWORD so that the keyword typed
1661 // count is boosted.
1662 AddTabToSearchVisit(**i);
1664 if (client_) {
1665 client_->SetKeywordSearchTermsForURL(
1666 details.url, (*i)->id(), search_terms);
1672 void TemplateURLService::AddTabToSearchVisit(const TemplateURL& t_url) {
1673 // Only add visits for entries the user hasn't modified. If the user modified
1674 // the entry the keyword may no longer correspond to the host name. It may be
1675 // possible to do something more sophisticated here, but it's so rare as to
1676 // not be worth it.
1677 if (!t_url.safe_for_autoreplace())
1678 return;
1680 if (!client_)
1681 return;
1683 GURL url(
1684 url_fixer::FixupURL(base::UTF16ToUTF8(t_url.keyword()), std::string()));
1685 if (!url.is_valid())
1686 return;
1688 // Synthesize a visit for the keyword. This ensures the url for the keyword is
1689 // autocompleted even if the user doesn't type the url in directly.
1690 client_->AddKeywordGeneratedVisit(url);
1693 void TemplateURLService::RequestGoogleURLTrackerServerCheckIfNecessary() {
1694 if (default_search_provider_ &&
1695 default_search_provider_->HasGoogleBaseURLs(search_terms_data()) &&
1696 google_url_tracker_)
1697 google_url_tracker_->RequestServerCheck(false);
1700 void TemplateURLService::GoogleBaseURLChanged() {
1701 if (!loaded_)
1702 return;
1704 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1705 bool something_changed = false;
1706 for (TemplateURLVector::iterator i(template_urls_.begin());
1707 i != template_urls_.end(); ++i) {
1708 TemplateURL* t_url = *i;
1709 if (t_url->HasGoogleBaseURLs(search_terms_data())) {
1710 TemplateURL updated_turl(t_url->data());
1711 updated_turl.ResetKeywordIfNecessary(search_terms_data(), false);
1712 KeywordToTemplateMap::const_iterator existing_entry =
1713 keyword_to_template_map_.find(updated_turl.keyword());
1714 if ((existing_entry != keyword_to_template_map_.end()) &&
1715 (existing_entry->second != t_url)) {
1716 // The new autogenerated keyword conflicts with another TemplateURL.
1717 // Overwrite it if it's replaceable; otherwise, leave |t_url| using its
1718 // current keyword. (This will not prevent |t_url| from auto-updating
1719 // the keyword in the future if the conflicting TemplateURL disappears.)
1720 // Note that we must still update |t_url| in this case, or the
1721 // |provider_map_| will not be updated correctly.
1722 if (CanReplace(existing_entry->second))
1723 RemoveNoNotify(existing_entry->second);
1724 else
1725 updated_turl.data_.SetKeyword(t_url->keyword());
1727 something_changed = true;
1728 // This will send the keyword change to sync. Note that other clients
1729 // need to reset the keyword to an appropriate local value when this
1730 // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
1731 UpdateNoNotify(t_url, updated_turl);
1734 if (something_changed)
1735 NotifyObservers();
1738 void TemplateURLService::OnDefaultSearchChange(
1739 const TemplateURLData* data,
1740 DefaultSearchManager::Source source) {
1741 if (prefs_ && (source == DefaultSearchManager::FROM_USER) &&
1742 ((source != default_search_provider_source_) ||
1743 !IdenticalSyncGUIDs(data, GetDefaultSearchProvider()))) {
1744 prefs_->SetString(prefs::kSyncedDefaultSearchProviderGUID, data->sync_guid);
1746 ApplyDefaultSearchChange(data, source);
1749 void TemplateURLService::ApplyDefaultSearchChange(
1750 const TemplateURLData* data,
1751 DefaultSearchManager::Source source) {
1752 if (!ApplyDefaultSearchChangeNoMetrics(data, source))
1753 return;
1755 UMA_HISTOGRAM_ENUMERATION(
1756 "Search.DefaultSearchChangeOrigin", dsp_change_origin_, DSP_CHANGE_MAX);
1758 if (GetDefaultSearchProvider() &&
1759 GetDefaultSearchProvider()->HasGoogleBaseURLs(search_terms_data()) &&
1760 !dsp_change_callback_.is_null())
1761 dsp_change_callback_.Run();
1764 bool TemplateURLService::ApplyDefaultSearchChangeNoMetrics(
1765 const TemplateURLData* data,
1766 DefaultSearchManager::Source source) {
1767 if (!loaded_) {
1768 // Set |initial_default_search_provider_| from the preferences. This is
1769 // mainly so we can hold ownership until we get to the point where the list
1770 // of keywords from Web Data is the owner of everything including the
1771 // default.
1772 bool changed = TemplateURL::MatchesData(
1773 initial_default_search_provider_.get(), data, search_terms_data());
1774 initial_default_search_provider_.reset(
1775 data ? new TemplateURL(*data) : NULL);
1776 default_search_provider_source_ = source;
1777 return changed;
1780 // Prevent recursion if we update the value stored in default_search_manager_.
1781 // Note that we exclude the case of data == NULL because that could cause a
1782 // false positive for recursion when the initial_default_search_provider_ is
1783 // NULL due to policy. We'll never actually get recursion with data == NULL.
1784 if (source == default_search_provider_source_ && data != NULL &&
1785 TemplateURL::MatchesData(default_search_provider_, data,
1786 search_terms_data()))
1787 return false;
1789 // This may be deleted later. Use exclusively for pointer comparison to detect
1790 // a change.
1791 TemplateURL* previous_default_search_engine = default_search_provider_;
1793 KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1794 if (default_search_provider_source_ == DefaultSearchManager::FROM_POLICY ||
1795 source == DefaultSearchManager::FROM_POLICY) {
1796 // We do this both to remove any no-longer-applicable policy-defined DSE as
1797 // well as to add the new one, if appropriate.
1798 UpdateProvidersCreatedByPolicy(
1799 &template_urls_,
1800 source == DefaultSearchManager::FROM_POLICY ? data : NULL);
1803 if (!data) {
1804 default_search_provider_ = NULL;
1805 } else if (source == DefaultSearchManager::FROM_EXTENSION) {
1806 default_search_provider_ = FindMatchingExtensionTemplateURL(
1807 *data, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
1808 } else if (source == DefaultSearchManager::FROM_FALLBACK) {
1809 default_search_provider_ =
1810 FindPrepopulatedTemplateURL(data->prepopulate_id);
1811 if (default_search_provider_) {
1812 TemplateURLData update_data(*data);
1813 update_data.sync_guid = default_search_provider_->sync_guid();
1814 if (!default_search_provider_->safe_for_autoreplace()) {
1815 update_data.safe_for_autoreplace = false;
1816 update_data.SetKeyword(default_search_provider_->keyword());
1817 update_data.SetShortName(default_search_provider_->short_name());
1819 UpdateNoNotify(default_search_provider_, TemplateURL(update_data));
1820 } else {
1821 // Normally the prepopulated fallback should be present in
1822 // |template_urls_|, but in a few cases it might not be:
1823 // (1) Tests that initialize the TemplateURLService in peculiar ways.
1824 // (2) If the user deleted the pre-populated default and we subsequently
1825 // lost their user-selected value.
1826 TemplateURL* new_dse = new TemplateURL(*data);
1827 if (AddNoNotify(new_dse, true))
1828 default_search_provider_ = new_dse;
1830 } else if (source == DefaultSearchManager::FROM_USER) {
1831 default_search_provider_ = GetTemplateURLForGUID(data->sync_guid);
1832 if (!default_search_provider_ && data->prepopulate_id) {
1833 default_search_provider_ =
1834 FindPrepopulatedTemplateURL(data->prepopulate_id);
1836 TemplateURLData new_data(*data);
1837 new_data.show_in_default_list = true;
1838 if (default_search_provider_) {
1839 UpdateNoNotify(default_search_provider_, TemplateURL(new_data));
1840 } else {
1841 new_data.id = kInvalidTemplateURLID;
1842 TemplateURL* new_dse = new TemplateURL(new_data);
1843 if (AddNoNotify(new_dse, true))
1844 default_search_provider_ = new_dse;
1846 if (default_search_provider_ && prefs_) {
1847 prefs_->SetString(prefs::kSyncedDefaultSearchProviderGUID,
1848 default_search_provider_->sync_guid());
1853 default_search_provider_source_ = source;
1855 bool changed = default_search_provider_ != previous_default_search_engine;
1856 if (changed)
1857 RequestGoogleURLTrackerServerCheckIfNecessary();
1859 NotifyObservers();
1861 return changed;
1864 bool TemplateURLService::AddNoNotify(TemplateURL* template_url,
1865 bool newly_adding) {
1866 DCHECK(template_url);
1868 if (newly_adding) {
1869 DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
1870 DCHECK(std::find(template_urls_.begin(), template_urls_.end(),
1871 template_url) == template_urls_.end());
1872 template_url->data_.id = ++next_id_;
1875 template_url->ResetKeywordIfNecessary(search_terms_data(), false);
1876 // Check whether |template_url|'s keyword conflicts with any already in the
1877 // model.
1878 TemplateURL* existing_keyword_turl =
1879 GetTemplateURLForKeyword(template_url->keyword());
1881 // Check whether |template_url|'s keyword conflicts with any already in the
1882 // model. Note that we can reach here during the loading phase while
1883 // processing the template URLs from the web data service. In this case,
1884 // GetTemplateURLForKeyword() will look not only at what's already in the
1885 // model, but at the |initial_default_search_provider_|. Since this engine
1886 // will presumably also be present in the web data, we need to double-check
1887 // that any "pre-existing" entries we find are actually coming from
1888 // |template_urls_|, lest we detect a "conflict" between the
1889 // |initial_default_search_provider_| and the web data version of itself.
1890 if (template_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION &&
1891 existing_keyword_turl &&
1892 existing_keyword_turl->GetType() != TemplateURL::OMNIBOX_API_EXTENSION &&
1893 (std::find(template_urls_.begin(), template_urls_.end(),
1894 existing_keyword_turl) != template_urls_.end())) {
1895 DCHECK_NE(existing_keyword_turl, template_url);
1896 // Only replace one of the TemplateURLs if they are either both extensions,
1897 // or both not extensions.
1898 bool are_same_type = existing_keyword_turl->GetType() ==
1899 template_url->GetType();
1900 if (CanReplace(existing_keyword_turl) && are_same_type) {
1901 RemoveNoNotify(existing_keyword_turl);
1902 } else if (CanReplace(template_url) && are_same_type) {
1903 delete template_url;
1904 return false;
1905 } else {
1906 base::string16 new_keyword =
1907 UniquifyKeyword(*existing_keyword_turl, false);
1908 ResetTemplateURLNoNotify(existing_keyword_turl,
1909 existing_keyword_turl->short_name(), new_keyword,
1910 existing_keyword_turl->url());
1913 template_urls_.push_back(template_url);
1914 AddToMaps(template_url);
1916 if (newly_adding &&
1917 (template_url->GetType() == TemplateURL::NORMAL)) {
1918 if (web_data_service_.get())
1919 web_data_service_->AddKeyword(template_url->data());
1921 // Inform sync of the addition. Note that this will assign a GUID to
1922 // template_url and add it to the guid_to_template_map_.
1923 ProcessTemplateURLChange(FROM_HERE,
1924 template_url,
1925 syncer::SyncChange::ACTION_ADD);
1928 return true;
1931 void TemplateURLService::RemoveNoNotify(TemplateURL* template_url) {
1932 DCHECK(template_url != default_search_provider_);
1934 TemplateURLVector::iterator i =
1935 std::find(template_urls_.begin(), template_urls_.end(), template_url);
1936 if (i == template_urls_.end())
1937 return;
1939 RemoveFromMaps(template_url);
1941 // Remove it from the vector containing all TemplateURLs.
1942 template_urls_.erase(i);
1944 if (template_url->GetType() == TemplateURL::NORMAL) {
1945 if (web_data_service_.get())
1946 web_data_service_->RemoveKeyword(template_url->id());
1948 // Inform sync of the deletion.
1949 ProcessTemplateURLChange(FROM_HERE,
1950 template_url,
1951 syncer::SyncChange::ACTION_DELETE);
1953 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1954 DELETE_ENGINE_USER_ACTION, DELETE_ENGINE_MAX);
1957 if (loaded_ && client_)
1958 client_->DeleteAllSearchTermsForKeyword(template_url->id());
1960 // We own the TemplateURL and need to delete it.
1961 delete template_url;
1964 bool TemplateURLService::ResetTemplateURLNoNotify(
1965 TemplateURL* url,
1966 const base::string16& title,
1967 const base::string16& keyword,
1968 const std::string& search_url) {
1969 DCHECK(!keyword.empty());
1970 DCHECK(!search_url.empty());
1971 TemplateURLData data(url->data());
1972 data.SetShortName(title);
1973 data.SetKeyword(keyword);
1974 if (search_url != data.url()) {
1975 data.SetURL(search_url);
1976 // The urls have changed, reset the favicon url.
1977 data.favicon_url = GURL();
1979 data.safe_for_autoreplace = false;
1980 data.last_modified = clock_->Now();
1981 return UpdateNoNotify(url, TemplateURL(data));
1984 void TemplateURLService::NotifyObservers() {
1985 if (!loaded_)
1986 return;
1988 FOR_EACH_OBSERVER(TemplateURLServiceObserver, model_observers_,
1989 OnTemplateURLServiceChanged());
1992 // |template_urls| are the TemplateURLs loaded from the database.
1993 // |default_from_prefs| is the default search provider from the preferences, or
1994 // NULL if the DSE is not policy-defined.
1996 // This function removes from the vector and the database all the TemplateURLs
1997 // that were set by policy, unless it is the current default search provider, in
1998 // which case it is updated with the data from prefs.
1999 void TemplateURLService::UpdateProvidersCreatedByPolicy(
2000 TemplateURLVector* template_urls,
2001 const TemplateURLData* default_from_prefs) {
2002 DCHECK(template_urls);
2004 for (TemplateURLVector::iterator i = template_urls->begin();
2005 i != template_urls->end(); ) {
2006 TemplateURL* template_url = *i;
2007 if (template_url->created_by_policy()) {
2008 if (default_from_prefs &&
2009 TemplateURL::MatchesData(template_url, default_from_prefs,
2010 search_terms_data())) {
2011 // If the database specified a default search provider that was set
2012 // by policy, and the default search provider from the preferences
2013 // is also set by policy and they are the same, keep the entry in the
2014 // database and the |default_search_provider|.
2015 default_search_provider_ = template_url;
2016 // Prevent us from saving any other entries, or creating a new one.
2017 default_from_prefs = NULL;
2018 ++i;
2019 continue;
2022 RemoveFromMaps(template_url);
2023 i = template_urls->erase(i);
2024 if (web_data_service_.get())
2025 web_data_service_->RemoveKeyword(template_url->id());
2026 delete template_url;
2027 } else {
2028 ++i;
2032 if (default_from_prefs) {
2033 default_search_provider_ = NULL;
2034 default_search_provider_source_ = DefaultSearchManager::FROM_POLICY;
2035 TemplateURLData new_data(*default_from_prefs);
2036 if (new_data.sync_guid.empty())
2037 new_data.sync_guid = base::GenerateGUID();
2038 new_data.created_by_policy = true;
2039 TemplateURL* new_dse = new TemplateURL(new_data);
2040 if (AddNoNotify(new_dse, true))
2041 default_search_provider_ = new_dse;
2045 void TemplateURLService::ResetTemplateURLGUID(TemplateURL* url,
2046 const std::string& guid) {
2047 DCHECK(loaded_);
2048 DCHECK(!guid.empty());
2050 TemplateURLData data(url->data());
2051 data.sync_guid = guid;
2052 UpdateNoNotify(url, TemplateURL(data));
2055 base::string16 TemplateURLService::UniquifyKeyword(const TemplateURL& turl,
2056 bool force) {
2057 if (!force) {
2058 // Already unique.
2059 if (!GetTemplateURLForKeyword(turl.keyword()))
2060 return turl.keyword();
2062 // First, try to return the generated keyword for the TemplateURL (except
2063 // for extensions, as their keywords are not associated with their URLs).
2064 GURL gurl(turl.url());
2065 if (gurl.is_valid() &&
2066 (turl.GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
2067 base::string16 keyword_candidate = TemplateURL::GenerateKeyword(gurl);
2068 if (!GetTemplateURLForKeyword(keyword_candidate))
2069 return keyword_candidate;
2073 // We try to uniquify the keyword by appending a special character to the end.
2074 // This is a best-effort approach where we try to preserve the original
2075 // keyword and let the user do what they will after our attempt.
2076 base::string16 keyword_candidate(turl.keyword());
2077 do {
2078 keyword_candidate.append(base::ASCIIToUTF16("_"));
2079 } while (GetTemplateURLForKeyword(keyword_candidate));
2081 return keyword_candidate;
2084 bool TemplateURLService::IsLocalTemplateURLBetter(
2085 const TemplateURL* local_turl,
2086 const TemplateURL* sync_turl) {
2087 DCHECK(GetTemplateURLForGUID(local_turl->sync_guid()));
2088 return local_turl->last_modified() > sync_turl->last_modified() ||
2089 local_turl->created_by_policy() ||
2090 local_turl== GetDefaultSearchProvider();
2093 void TemplateURLService::ResolveSyncKeywordConflict(
2094 TemplateURL* unapplied_sync_turl,
2095 TemplateURL* applied_sync_turl,
2096 syncer::SyncChangeList* change_list) {
2097 DCHECK(loaded_);
2098 DCHECK(unapplied_sync_turl);
2099 DCHECK(applied_sync_turl);
2100 DCHECK(change_list);
2101 DCHECK_EQ(applied_sync_turl->keyword(), unapplied_sync_turl->keyword());
2102 DCHECK_EQ(TemplateURL::NORMAL, applied_sync_turl->GetType());
2104 // Both |unapplied_sync_turl| and |applied_sync_turl| are known to Sync, so
2105 // don't delete either of them. Instead, determine which is "better" and
2106 // uniquify the other one, sending an update to the server for the updated
2107 // entry.
2108 const bool applied_turl_is_better =
2109 IsLocalTemplateURLBetter(applied_sync_turl, unapplied_sync_turl);
2110 TemplateURL* loser = applied_turl_is_better ?
2111 unapplied_sync_turl : applied_sync_turl;
2112 base::string16 new_keyword = UniquifyKeyword(*loser, false);
2113 DCHECK(!GetTemplateURLForKeyword(new_keyword));
2114 if (applied_turl_is_better) {
2115 // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2116 // for adding or updating unapplied_sync_turl in the local model.
2117 unapplied_sync_turl->data_.SetKeyword(new_keyword);
2118 } else {
2119 // Update |applied_sync_turl| in the local model with the new keyword.
2120 TemplateURLData data(applied_sync_turl->data());
2121 data.SetKeyword(new_keyword);
2122 if (UpdateNoNotify(applied_sync_turl, TemplateURL(data)))
2123 NotifyObservers();
2125 // The losing TemplateURL should have their keyword updated. Send a change to
2126 // the server to reflect this change.
2127 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*loser);
2128 change_list->push_back(syncer::SyncChange(FROM_HERE,
2129 syncer::SyncChange::ACTION_UPDATE,
2130 sync_data));
2133 void TemplateURLService::MergeInSyncTemplateURL(
2134 TemplateURL* sync_turl,
2135 const SyncDataMap& sync_data,
2136 syncer::SyncChangeList* change_list,
2137 SyncDataMap* local_data,
2138 syncer::SyncMergeResult* merge_result) {
2139 DCHECK(sync_turl);
2140 DCHECK(!GetTemplateURLForGUID(sync_turl->sync_guid()));
2141 DCHECK(IsFromSync(sync_turl, sync_data));
2143 TemplateURL* conflicting_turl =
2144 FindNonExtensionTemplateURLForKeyword(sync_turl->keyword());
2145 bool should_add_sync_turl = true;
2147 // If there was no TemplateURL in the local model that conflicts with
2148 // |sync_turl|, skip the following preparation steps and just add |sync_turl|
2149 // directly. Otherwise, modify |conflicting_turl| to make room for
2150 // |sync_turl|.
2151 if (conflicting_turl) {
2152 if (IsFromSync(conflicting_turl, sync_data)) {
2153 // |conflicting_turl| is already known to Sync, so we're not allowed to
2154 // remove it. In this case, we want to uniquify the worse one and send an
2155 // update for the changed keyword to sync. We can reuse the logic from
2156 // ResolveSyncKeywordConflict for this.
2157 ResolveSyncKeywordConflict(sync_turl, conflicting_turl, change_list);
2158 merge_result->set_num_items_modified(
2159 merge_result->num_items_modified() + 1);
2160 } else {
2161 // |conflicting_turl| is not yet known to Sync. If it is better, then we
2162 // want to transfer its values up to sync. Otherwise, we remove it and
2163 // allow the entry from Sync to overtake it in the model.
2164 const std::string guid = conflicting_turl->sync_guid();
2165 if (IsLocalTemplateURLBetter(conflicting_turl, sync_turl)) {
2166 ResetTemplateURLGUID(conflicting_turl, sync_turl->sync_guid());
2167 syncer::SyncData sync_data =
2168 CreateSyncDataFromTemplateURL(*conflicting_turl);
2169 change_list->push_back(syncer::SyncChange(
2170 FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
2171 // Note that in this case we do not add the Sync TemplateURL to the
2172 // local model, since we've effectively "merged" it in by updating the
2173 // local conflicting entry with its sync_guid.
2174 should_add_sync_turl = false;
2175 merge_result->set_num_items_modified(
2176 merge_result->num_items_modified() + 1);
2177 } else {
2178 // We guarantee that this isn't the local search provider. Otherwise,
2179 // local would have won.
2180 DCHECK(conflicting_turl != GetDefaultSearchProvider());
2181 Remove(conflicting_turl);
2182 merge_result->set_num_items_deleted(
2183 merge_result->num_items_deleted() + 1);
2185 // This TemplateURL was either removed or overwritten in the local model.
2186 // Remove the entry from the local data so it isn't pushed up to Sync.
2187 local_data->erase(guid);
2191 if (should_add_sync_turl) {
2192 // Force the local ID to kInvalidTemplateURLID so we can add it.
2193 TemplateURLData data(sync_turl->data());
2194 data.id = kInvalidTemplateURLID;
2195 TemplateURL* added = new TemplateURL(data);
2196 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2197 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
2198 if (Add(added))
2199 MaybeUpdateDSEAfterSync(added);
2200 merge_result->set_num_items_added(
2201 merge_result->num_items_added() + 1);
2205 void TemplateURLService::PatchMissingSyncGUIDs(
2206 TemplateURLVector* template_urls) {
2207 DCHECK(template_urls);
2208 for (TemplateURLVector::iterator i = template_urls->begin();
2209 i != template_urls->end(); ++i) {
2210 TemplateURL* template_url = *i;
2211 DCHECK(template_url);
2212 if (template_url->sync_guid().empty() &&
2213 (template_url->GetType() == TemplateURL::NORMAL)) {
2214 template_url->data_.sync_guid = base::GenerateGUID();
2215 if (web_data_service_.get())
2216 web_data_service_->UpdateKeyword(template_url->data());
2221 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
2222 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2223 &dsp_change_origin_, DSP_CHANGE_SYNC_PREF);
2225 std::string new_guid =
2226 prefs_->GetString(prefs::kSyncedDefaultSearchProviderGUID);
2227 if (new_guid.empty()) {
2228 default_search_manager_.ClearUserSelectedDefaultSearchEngine();
2229 return;
2232 TemplateURL* turl = GetTemplateURLForGUID(new_guid);
2233 if (turl)
2234 default_search_manager_.SetUserSelectedDefaultSearchEngine(turl->data());
2237 TemplateURL* TemplateURLService::FindPrepopulatedTemplateURL(
2238 int prepopulated_id) {
2239 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2240 i != template_urls_.end(); ++i) {
2241 if ((*i)->prepopulate_id() == prepopulated_id)
2242 return *i;
2244 return NULL;
2247 TemplateURL* TemplateURLService::FindTemplateURLForExtension(
2248 const std::string& extension_id,
2249 TemplateURL::Type type) {
2250 DCHECK_NE(TemplateURL::NORMAL, type);
2251 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2252 i != template_urls_.end(); ++i) {
2253 if ((*i)->GetType() == type &&
2254 (*i)->GetExtensionId() == extension_id)
2255 return *i;
2257 return NULL;
2260 TemplateURL* TemplateURLService::FindMatchingExtensionTemplateURL(
2261 const TemplateURLData& data,
2262 TemplateURL::Type type) {
2263 DCHECK_NE(TemplateURL::NORMAL, type);
2264 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2265 i != template_urls_.end(); ++i) {
2266 if ((*i)->GetType() == type &&
2267 TemplateURL::MatchesData(*i, &data, search_terms_data()))
2268 return *i;
2270 return NULL;
2273 void TemplateURLService::UpdateExtensionDefaultSearchEngine() {
2274 TemplateURL* most_recently_intalled_default = NULL;
2275 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2276 i != template_urls_.end(); ++i) {
2277 if (((*i)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) &&
2278 (*i)->extension_info_->wants_to_be_default_engine &&
2279 (*i)->SupportsReplacement(search_terms_data()) &&
2280 (!most_recently_intalled_default ||
2281 (most_recently_intalled_default->extension_info_->install_time <
2282 (*i)->extension_info_->install_time)))
2283 most_recently_intalled_default = *i;
2286 if (most_recently_intalled_default) {
2287 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2288 &dsp_change_origin_, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION);
2289 default_search_manager_.SetExtensionControlledDefaultSearchEngine(
2290 most_recently_intalled_default->data());
2291 } else {
2292 default_search_manager_.ClearExtensionControlledDefaultSearchEngine();