[safe-browsing] Database full hash matches like prefix match.
[chromium-blink-merge.git] / chrome / browser / search_engines / template_url_service.cc
blob345786874e08a3ac15f7723b16ddcd43fe7f6c70
1 // Copyright (c) 2012 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 "chrome/browser/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/environment.h"
14 #include "base/guid.h"
15 #include "base/i18n/case_conversion.h"
16 #include "base/memory/scoped_vector.h"
17 #include "base/metrics/histogram.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_split.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/time/time.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/extensions/extension_service.h"
27 #include "chrome/browser/google/google_url_tracker.h"
28 #include "chrome/browser/history/history_notifications.h"
29 #include "chrome/browser/history/history_service.h"
30 #include "chrome/browser/history/history_service_factory.h"
31 #include "chrome/browser/profiles/profile.h"
32 #include "chrome/browser/rlz/rlz.h"
33 #include "chrome/browser/search_engines/search_host_to_urls_map.h"
34 #include "chrome/browser/search_engines/search_terms_data.h"
35 #include "chrome/browser/search_engines/template_url.h"
36 #include "chrome/browser/search_engines/template_url_prepopulate_data.h"
37 #include "chrome/browser/search_engines/template_url_service_observer.h"
38 #include "chrome/browser/search_engines/util.h"
39 #include "chrome/browser/webdata/web_data_service.h"
40 #include "chrome/common/chrome_switches.h"
41 #include "chrome/common/env_vars.h"
42 #include "chrome/common/extensions/api/omnibox/omnibox_handler.h"
43 #include "chrome/common/net/url_fixer_upper.h"
44 #include "chrome/common/pref_names.h"
45 #include "chrome/common/url_constants.h"
46 #include "content/public/browser/notification_service.h"
47 #include "extensions/common/constants.h"
48 #include "net/base/net_util.h"
49 #include "sync/api/sync_change.h"
50 #include "sync/api/sync_error_factory.h"
51 #include "sync/protocol/search_engine_specifics.pb.h"
52 #include "sync/protocol/sync.pb.h"
53 #include "ui/base/l10n/l10n_util.h"
55 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet;
56 typedef TemplateURLService::SyncDataMap SyncDataMap;
58 namespace {
60 bool TemplateURLMatchesData(const TemplateURL* url1,
61 const TemplateURLData* url2) {
62 if (!url1 || !url2)
63 return !url1 && !url2;
65 return (url1->short_name() == url2->short_name) &&
66 url1->HasSameKeywordAs(*url2) &&
67 (url1->url() == url2->url()) &&
68 (url1->suggestions_url() == url2->suggestions_url) &&
69 (url1->instant_url() == url2->instant_url) &&
70 (url1->image_url() == url2->image_url) &&
71 (url1->new_tab_url() == url2->new_tab_url) &&
72 (url1->search_url_post_params() == url2->search_url_post_params) &&
73 (url1->suggestions_url_post_params() ==
74 url2->suggestions_url_post_params) &&
75 (url1->instant_url_post_params() == url2->instant_url_post_params) &&
76 (url1->image_url_post_params() == url2->image_url_post_params) &&
77 (url1->favicon_url() == url2->favicon_url) &&
78 (url1->safe_for_autoreplace() == url2->safe_for_autoreplace) &&
79 (url1->show_in_default_list() == url2->show_in_default_list) &&
80 (url1->input_encodings() == url2->input_encodings) &&
81 (url1->alternate_urls() == url2->alternate_urls) &&
82 (url1->search_terms_replacement_key() ==
83 url2->search_terms_replacement_key);
86 const char kFirstPotentialEngineHistogramName[] =
87 "Search.FirstPotentialEngineCalled";
89 // Values for an enumerated histogram used to track whenever
90 // FirstPotentialDefaultEngine is called, and from where.
91 enum FirstPotentialEngineCaller {
92 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP,
93 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_PROCESSING_SYNC_CHANGES,
94 FIRST_POTENTIAL_CALLSITE_ON_LOAD,
95 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_SYNCING,
96 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_NOT_SYNCING,
97 FIRST_POTENTIAL_CALLSITE_MAX,
100 const char kDeleteSyncedEngineHistogramName[] =
101 "Search.DeleteSyncedSearchEngine";
103 // Values for an enumerated histogram used to track whenever an ACTION_DELETE is
104 // sent to the server for search engines.
105 enum DeleteSyncedSearchEngineEvent {
106 DELETE_ENGINE_USER_ACTION,
107 DELETE_ENGINE_PRE_SYNC,
108 DELETE_ENGINE_EMPTY_FIELD,
109 DELETE_ENGINE_MAX,
112 TemplateURL* FirstPotentialDefaultEngine(
113 const TemplateURLService::TemplateURLVector& template_urls) {
114 for (TemplateURLService::TemplateURLVector::const_iterator i(
115 template_urls.begin()); i != template_urls.end(); ++i) {
116 if ((*i)->ShowInDefaultList() &&
117 ((*i)->GetType() == TemplateURL::NORMAL))
118 return *i;
120 return NULL;
123 // Returns true iff the change in |change_list| at index |i| should not be sent
124 // up to the server based on its GUIDs presence in |sync_data| or when compared
125 // to changes after it in |change_list|.
126 // The criteria is:
127 // 1) It is an ACTION_UPDATE or ACTION_DELETE and the sync_guid associated
128 // with it is NOT found in |sync_data|. We can only update and remove
129 // entries that were originally from the Sync server.
130 // 2) It is an ACTION_ADD and the sync_guid associated with it is found in
131 // |sync_data|. We cannot re-add entries that Sync already knew about.
132 // 3) There is an update after an update for the same GUID. We prune earlier
133 // ones just to save bandwidth (Sync would normally coalesce them).
134 bool ShouldRemoveSyncChange(size_t index,
135 syncer::SyncChangeList* change_list,
136 const SyncDataMap* sync_data) {
137 DCHECK(index < change_list->size());
138 const syncer::SyncChange& change_i = (*change_list)[index];
139 const std::string guid = change_i.sync_data().GetSpecifics()
140 .search_engine().sync_guid();
141 syncer::SyncChange::SyncChangeType type = change_i.change_type();
142 if ((type == syncer::SyncChange::ACTION_UPDATE ||
143 type == syncer::SyncChange::ACTION_DELETE) &&
144 sync_data->find(guid) == sync_data->end())
145 return true;
146 if (type == syncer::SyncChange::ACTION_ADD &&
147 sync_data->find(guid) != sync_data->end())
148 return true;
149 if (type == syncer::SyncChange::ACTION_UPDATE) {
150 for (size_t j = index + 1; j < change_list->size(); j++) {
151 const syncer::SyncChange& change_j = (*change_list)[j];
152 if ((syncer::SyncChange::ACTION_UPDATE == change_j.change_type()) &&
153 (change_j.sync_data().GetSpecifics().search_engine().sync_guid() ==
154 guid))
155 return true;
158 return false;
161 // Remove SyncChanges that should not be sent to the server from |change_list|.
162 // This is done to eliminate incorrect SyncChanges added by the merge and
163 // conflict resolution logic when it is unsure of whether or not an entry is new
164 // from Sync or originally from the local model. This also removes changes that
165 // would be otherwise be coalesced by Sync in order to save bandwidth.
166 void PruneSyncChanges(const SyncDataMap* sync_data,
167 syncer::SyncChangeList* change_list) {
168 for (size_t i = 0; i < change_list->size(); ) {
169 if (ShouldRemoveSyncChange(i, change_list, sync_data))
170 change_list->erase(change_list->begin() + i);
171 else
172 ++i;
176 // Helper class that reports a specific string as the Google base URL. We use
177 // this so that code can calculate a TemplateURL's previous search URL after a
178 // change to the global base URL.
179 class OldBaseURLSearchTermsData : public UIThreadSearchTermsData {
180 public:
181 OldBaseURLSearchTermsData(Profile* profile, const std::string& old_base_url);
182 virtual ~OldBaseURLSearchTermsData();
184 virtual std::string GoogleBaseURLValue() const OVERRIDE;
186 private:
187 std::string old_base_url;
190 OldBaseURLSearchTermsData::OldBaseURLSearchTermsData(
191 Profile* profile,
192 const std::string& old_base_url)
193 : UIThreadSearchTermsData(profile),
194 old_base_url(old_base_url) {
197 OldBaseURLSearchTermsData::~OldBaseURLSearchTermsData() {
200 std::string OldBaseURLSearchTermsData::GoogleBaseURLValue() const {
201 return old_base_url;
204 // Returns true if |turl|'s GUID is not found inside |sync_data|. This is to be
205 // used in MergeDataAndStartSyncing to differentiate between TemplateURLs from
206 // Sync and TemplateURLs that were initially local, assuming |sync_data| is the
207 // |initial_sync_data| parameter.
208 bool IsFromSync(const TemplateURL* turl, const SyncDataMap& sync_data) {
209 return !!sync_data.count(turl->sync_guid());
212 // Log the number of instances of a keyword that exist, with zero or more
213 // underscores, which could occur as the result of conflict resolution.
214 void LogDuplicatesHistogram(
215 const TemplateURLService::TemplateURLVector& template_urls) {
216 std::map<std::string, int> duplicates;
217 for (TemplateURLService::TemplateURLVector::const_iterator it =
218 template_urls.begin(); it != template_urls.end(); ++it) {
219 std::string keyword = base::UTF16ToASCII((*it)->keyword());
220 base::TrimString(keyword, "_", &keyword);
221 duplicates[keyword]++;
224 // Count the keywords with duplicates.
225 int num_dupes = 0;
226 for (std::map<std::string, int>::const_iterator it = duplicates.begin();
227 it != duplicates.end(); ++it) {
228 if (it->second > 1)
229 num_dupes++;
232 UMA_HISTOGRAM_COUNTS_100("Search.SearchEngineDuplicateCounts", num_dupes);
235 } // namespace
238 // TemplateURLService::ExtensionKeyword ---------------------------------------
240 TemplateURLService::ExtensionKeyword::ExtensionKeyword(
241 const std::string& id,
242 const std::string& name,
243 const std::string& keyword)
244 : extension_id(id),
245 extension_name(name),
246 extension_keyword(keyword) {
249 TemplateURLService::ExtensionKeyword::~ExtensionKeyword() {}
252 // TemplateURLService::LessWithPrefix -----------------------------------------
254 class TemplateURLService::LessWithPrefix {
255 public:
256 // We want to find the set of keywords that begin with a prefix. The STL
257 // algorithms will return the set of elements that are "equal to" the
258 // prefix, where "equal(x, y)" means "!(cmp(x, y) || cmp(y, x))". When
259 // cmp() is the typical std::less<>, this results in lexicographic equality;
260 // we need to extend this to mark a prefix as "not less than" a keyword it
261 // begins, which will cause the desired elements to be considered "equal to"
262 // the prefix. Note: this is still a strict weak ordering, as required by
263 // equal_range() (though I will not prove that here).
265 // Unfortunately the calling convention is not "prefix and element" but
266 // rather "two elements", so we pass the prefix as a fake "element" which has
267 // a NULL KeywordDataElement pointer.
268 bool operator()(const KeywordToTemplateMap::value_type& elem1,
269 const KeywordToTemplateMap::value_type& elem2) const {
270 return (elem1.second == NULL) ?
271 (elem2.first.compare(0, elem1.first.length(), elem1.first) > 0) :
272 (elem1.first < elem2.first);
277 // TemplateURLService ---------------------------------------------------------
279 TemplateURLService::TemplateURLService(Profile* profile)
280 : provider_map_(new SearchHostToURLsMap),
281 profile_(profile),
282 loaded_(false),
283 load_failed_(false),
284 load_handle_(0),
285 default_search_provider_(NULL),
286 is_default_search_managed_(false),
287 next_id_(kInvalidTemplateURLID + 1),
288 time_provider_(&base::Time::Now),
289 models_associated_(false),
290 processing_syncer_changes_(false),
291 pending_synced_default_search_(false),
292 dsp_change_origin_(DSP_CHANGE_OTHER),
293 default_search_manager_(new DefaultSearchManager(GetPrefs())) {
294 DCHECK(profile_);
295 Init(NULL, 0);
298 TemplateURLService::TemplateURLService(const Initializer* initializers,
299 const int count)
300 : provider_map_(new SearchHostToURLsMap),
301 profile_(NULL),
302 loaded_(false),
303 load_failed_(false),
304 load_handle_(0),
305 service_(NULL),
306 default_search_provider_(NULL),
307 is_default_search_managed_(false),
308 next_id_(kInvalidTemplateURLID + 1),
309 time_provider_(&base::Time::Now),
310 models_associated_(false),
311 processing_syncer_changes_(false),
312 pending_synced_default_search_(false),
313 dsp_change_origin_(DSP_CHANGE_OTHER) {
314 Init(initializers, count);
317 TemplateURLService::~TemplateURLService() {
318 // |service_| should be deleted during Shutdown().
319 DCHECK(!service_);
320 STLDeleteElements(&template_urls_);
323 // static
324 base::string16 TemplateURLService::GenerateKeyword(const GURL& url) {
325 DCHECK(url.is_valid());
326 // Strip "www." off the front of the keyword; otherwise the keyword won't work
327 // properly. See http://code.google.com/p/chromium/issues/detail?id=6984 .
328 // Special case: if the host was exactly "www." (not sure this can happen but
329 // perhaps with some weird intranet and custom DNS server?), ensure we at
330 // least don't return the empty string.
331 base::string16 keyword(net::StripWWWFromHost(url));
332 return keyword.empty() ? base::ASCIIToUTF16("www") : keyword;
335 // static
336 base::string16 TemplateURLService::CleanUserInputKeyword(
337 const base::string16& keyword) {
338 // Remove the scheme.
339 base::string16 result(base::i18n::ToLower(keyword));
340 base::TrimWhitespace(result, base::TRIM_ALL, &result);
341 url::Component scheme_component;
342 if (url::ExtractScheme(base::UTF16ToUTF8(keyword).c_str(),
343 static_cast<int>(keyword.length()),
344 &scheme_component)) {
345 // If the scheme isn't "http" or "https", bail. The user isn't trying to
346 // type a web address, but rather an FTP, file:, or other scheme URL, or a
347 // search query with some sort of initial operator (e.g. "site:").
348 if (result.compare(0, scheme_component.end(),
349 base::ASCIIToUTF16(content::kHttpScheme)) &&
350 result.compare(0, scheme_component.end(),
351 base::ASCIIToUTF16(content::kHttpsScheme)))
352 return base::string16();
354 // Include trailing ':'.
355 result.erase(0, scheme_component.end() + 1);
356 // Many schemes usually have "//" after them, so strip it too.
357 const base::string16 after_scheme(base::ASCIIToUTF16("//"));
358 if (result.compare(0, after_scheme.length(), after_scheme) == 0)
359 result.erase(0, after_scheme.length());
362 // Remove leading "www.".
363 result = net::StripWWW(result);
365 // Remove trailing "/".
366 return (result.length() > 0 && result[result.length() - 1] == '/') ?
367 result.substr(0, result.length() - 1) : result;
370 // static
371 GURL TemplateURLService::GenerateSearchURL(TemplateURL* t_url) {
372 DCHECK(t_url);
373 UIThreadSearchTermsData search_terms_data(t_url->profile());
374 return GenerateSearchURLUsingTermsData(t_url, search_terms_data);
377 // static
378 GURL TemplateURLService::GenerateSearchURLUsingTermsData(
379 const TemplateURL* t_url,
380 const SearchTermsData& search_terms_data) {
381 DCHECK(t_url);
383 const TemplateURLRef& search_ref = t_url->url_ref();
384 if (!search_ref.IsValidUsingTermsData(search_terms_data))
385 return GURL();
387 if (!search_ref.SupportsReplacementUsingTermsData(search_terms_data))
388 return GURL(t_url->url());
390 // Use something obscure for the search terms argument so that in the rare
391 // case the term replaces the URL it's unlikely another keyword would have the
392 // same url.
393 // TODO(jnd): Add additional parameters to get post data when the search URL
394 // has post parameters.
395 return GURL(search_ref.ReplaceSearchTermsUsingTermsData(
396 TemplateURLRef::SearchTermsArgs(
397 base::ASCIIToUTF16("blah.blah.blah.blah.blah")),
398 search_terms_data, NULL));
401 bool TemplateURLService::CanReplaceKeyword(
402 const base::string16& keyword,
403 const GURL& url,
404 TemplateURL** template_url_to_replace) {
405 DCHECK(!keyword.empty()); // This should only be called for non-empty
406 // keywords. If we need to support empty kewords
407 // the code needs to change slightly.
408 TemplateURL* existing_url = GetTemplateURLForKeyword(keyword);
409 if (template_url_to_replace)
410 *template_url_to_replace = existing_url;
411 if (existing_url) {
412 // We already have a TemplateURL for this keyword. Only allow it to be
413 // replaced if the TemplateURL can be replaced.
414 return CanReplace(existing_url);
417 // We don't have a TemplateURL with keyword. Only allow a new one if there
418 // isn't a TemplateURL for the specified host, or there is one but it can
419 // be replaced. We do this to ensure that if the user assigns a different
420 // keyword to a generated TemplateURL, we won't regenerate another keyword for
421 // the same host.
422 return !url.is_valid() || url.host().empty() ||
423 CanReplaceKeywordForHost(url.host(), template_url_to_replace);
426 void TemplateURLService::FindMatchingKeywords(
427 const base::string16& prefix,
428 bool support_replacement_only,
429 TemplateURLVector* matches) const {
430 // Sanity check args.
431 if (prefix.empty())
432 return;
433 DCHECK(matches != NULL);
434 DCHECK(matches->empty()); // The code for exact matches assumes this.
436 // Required for VS2010: http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
437 TemplateURL* const kNullTemplateURL = NULL;
439 // Find matching keyword range. Searches the element map for keywords
440 // beginning with |prefix| and stores the endpoints of the resulting set in
441 // |match_range|.
442 const std::pair<KeywordToTemplateMap::const_iterator,
443 KeywordToTemplateMap::const_iterator> match_range(
444 std::equal_range(
445 keyword_to_template_map_.begin(), keyword_to_template_map_.end(),
446 KeywordToTemplateMap::value_type(prefix, kNullTemplateURL),
447 LessWithPrefix()));
449 // Return vector of matching keywords.
450 for (KeywordToTemplateMap::const_iterator i(match_range.first);
451 i != match_range.second; ++i) {
452 if (!support_replacement_only || i->second->url_ref().SupportsReplacement())
453 matches->push_back(i->second);
457 TemplateURL* TemplateURLService::GetTemplateURLForKeyword(
458 const base::string16& keyword) {
459 KeywordToTemplateMap::const_iterator elem(
460 keyword_to_template_map_.find(keyword));
461 if (elem != keyword_to_template_map_.end())
462 return elem->second;
463 return ((!loaded_ || load_failed_) &&
464 initial_default_search_provider_.get() &&
465 (initial_default_search_provider_->keyword() == keyword)) ?
466 initial_default_search_provider_.get() : NULL;
469 TemplateURL* TemplateURLService::GetTemplateURLForGUID(
470 const std::string& sync_guid) {
471 GUIDToTemplateMap::const_iterator elem(guid_to_template_map_.find(sync_guid));
472 if (elem != guid_to_template_map_.end())
473 return elem->second;
474 return ((!loaded_ || load_failed_) &&
475 initial_default_search_provider_.get() &&
476 (initial_default_search_provider_->sync_guid() == sync_guid)) ?
477 initial_default_search_provider_.get() : NULL;
480 TemplateURL* TemplateURLService::GetTemplateURLForHost(
481 const std::string& host) {
482 if (loaded_) {
483 TemplateURL* t_url = provider_map_->GetTemplateURLForHost(host);
484 if (t_url)
485 return t_url;
487 return ((!loaded_ || load_failed_) &&
488 initial_default_search_provider_.get() &&
489 (GenerateSearchURL(initial_default_search_provider_.get()).host() ==
490 host)) ? initial_default_search_provider_.get() : NULL;
493 void TemplateURLService::Add(TemplateURL* template_url) {
494 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
495 if (AddNoNotify(template_url, true))
496 NotifyObservers();
499 void TemplateURLService::AddAndSetProfile(TemplateURL* template_url,
500 Profile* profile) {
501 template_url->profile_ = profile;
502 Add(template_url);
505 void TemplateURLService::AddWithOverrides(TemplateURL* template_url,
506 const base::string16& short_name,
507 const base::string16& keyword,
508 const std::string& url) {
509 DCHECK(!keyword.empty());
510 DCHECK(!url.empty());
511 template_url->data_.short_name = short_name;
512 template_url->data_.SetKeyword(keyword);
513 template_url->SetURL(url);
514 Add(template_url);
517 void TemplateURLService::AddExtensionControlledTURL(
518 TemplateURL* template_url,
519 scoped_ptr<AssociatedExtensionInfo> info) {
520 DCHECK(loaded_);
521 DCHECK(template_url);
522 DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
523 DCHECK(info);
524 DCHECK_EQ(info->wants_to_be_default_engine,
525 template_url->show_in_default_list());
526 template_url->extension_info_.swap(info);
527 DCHECK(!FindTemplateURLForExtension(
528 template_url->GetExtensionId(),
529 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION));
531 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
532 if (AddNoNotify(template_url, true)) {
533 // Note that we can't call CanMakeDefault() here, since it would return
534 // false when another extension is already controlling the default search
535 // engine, and we want to allow new extensions to take over.
536 if (template_url->extension_info_->wants_to_be_default_engine &&
537 !is_default_search_managed()) {
538 TemplateURL* default_candidate = FindExtensionDefaultSearchEngine();
539 if (default_candidate == template_url) {
540 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
541 &dsp_change_origin_, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION);
542 SetDefaultSearchProviderNoNotify(template_url);
545 NotifyObservers();
549 void TemplateURLService::Remove(TemplateURL* template_url) {
550 RemoveNoNotify(template_url);
551 NotifyObservers();
554 void TemplateURLService::RemoveExtensionControlledTURL(
555 const std::string& extension_id) {
556 DCHECK(loaded_);
557 TemplateURL* url = FindTemplateURLForExtension(
558 extension_id, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
559 if (!url)
560 return;
561 bool restore_dse = (url == GetDefaultSearchProvider());
562 if (restore_dse) {
563 DCHECK(!is_default_search_managed());
564 default_search_provider_ = NULL;
566 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
567 RemoveNoNotify(url);
568 if (restore_dse)
569 SetDefaultSearchProviderAfterRemovingDefaultExtension();
570 NotifyObservers();
573 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after) {
574 RemoveAutoGeneratedBetween(created_after, base::Time());
577 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after,
578 base::Time created_before) {
579 RemoveAutoGeneratedForOriginBetween(GURL(), created_after, created_before);
582 void TemplateURLService::RemoveAutoGeneratedForOriginBetween(
583 const GURL& origin,
584 base::Time created_after,
585 base::Time created_before) {
586 GURL o(origin.GetOrigin());
587 bool should_notify = false;
588 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
589 for (size_t i = 0; i < template_urls_.size();) {
590 if (template_urls_[i]->date_created() >= created_after &&
591 (created_before.is_null() ||
592 template_urls_[i]->date_created() < created_before) &&
593 CanReplace(template_urls_[i]) &&
594 (o.is_empty() ||
595 GenerateSearchURL(template_urls_[i]).GetOrigin() == o)) {
596 RemoveNoNotify(template_urls_[i]);
597 should_notify = true;
598 } else {
599 ++i;
602 if (should_notify)
603 NotifyObservers();
607 void TemplateURLService::RegisterOmniboxKeyword(
608 const std::string& extension_id,
609 const std::string& extension_name,
610 const std::string& keyword) {
611 DCHECK(loaded_);
613 if (!FindTemplateURLForExtension(extension_id,
614 TemplateURL::OMNIBOX_API_EXTENSION)) {
615 ExtensionKeyword extension_url(extension_id, extension_name, keyword);
616 Add(CreateTemplateURLForExtension(extension_url));
620 void TemplateURLService::UnregisterOmniboxKeyword(
621 const std::string& extension_id) {
622 DCHECK(loaded_);
623 TemplateURL* url = FindTemplateURLForExtension(
624 extension_id, TemplateURL::OMNIBOX_API_EXTENSION);
625 if (url)
626 Remove(url);
629 TemplateURLService::TemplateURLVector TemplateURLService::GetTemplateURLs() {
630 return template_urls_;
633 void TemplateURLService::IncrementUsageCount(TemplateURL* url) {
634 DCHECK(url);
635 // Extension-controlled search engines are not persisted.
636 if (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
637 return;
638 if (std::find(template_urls_.begin(), template_urls_.end(), url) ==
639 template_urls_.end())
640 return;
641 ++url->data_.usage_count;
643 if (service_.get())
644 service_.get()->UpdateKeyword(url->data());
647 void TemplateURLService::ResetTemplateURL(TemplateURL* url,
648 const base::string16& title,
649 const base::string16& keyword,
650 const std::string& search_url) {
651 if (!loaded_)
652 return;
653 DCHECK(!keyword.empty());
654 DCHECK(!search_url.empty());
655 TemplateURLData data(url->data());
656 data.short_name = title;
657 data.SetKeyword(keyword);
658 if (search_url != data.url()) {
659 data.SetURL(search_url);
660 // The urls have changed, reset the favicon url.
661 data.favicon_url = GURL();
663 data.safe_for_autoreplace = false;
664 data.last_modified = time_provider_();
665 TemplateURL new_url(url->profile(), data);
666 UIThreadSearchTermsData search_terms_data(url->profile());
667 if (UpdateNoNotify(url, new_url, search_terms_data))
668 NotifyObservers();
671 bool TemplateURLService::CanMakeDefault(const TemplateURL* url) {
672 return !is_default_search_managed() &&
673 !IsExtensionControlledDefaultSearch() &&
674 (url != GetDefaultSearchProvider()) &&
675 url->url_ref().SupportsReplacement() &&
676 (url->GetType() == TemplateURL::NORMAL);
679 void TemplateURLService::SetUserSelectedDefaultSearchProvider(
680 TemplateURL* url) {
681 SetDefaultSearchProvider(url);
682 if (default_search_manager_) {
683 if (url)
684 default_search_manager_->SetUserSelectedDefaultSearchEngine(url->data());
685 else
686 default_search_manager_->ClearUserSelectedDefaultSearchEngine();
690 TemplateURL* TemplateURLService::GetDefaultSearchProvider() {
691 if (loaded_ && !load_failed_)
692 return default_search_provider_;
693 // We're not loaded, rely on the default search provider stored in prefs.
694 return initial_default_search_provider_.get();
697 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
698 const GURL& url) {
699 TemplateURL* default_provider = GetDefaultSearchProvider();
700 return default_provider && default_provider->IsSearchURL(url);
703 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
704 const TemplateURL* default_provider = GetDefaultSearchProvider();
705 return default_provider && (default_provider->GetType() ==
706 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
709 TemplateURL* TemplateURLService::FindNewDefaultSearchProvider() {
710 // See if the prepopulated default still exists.
711 scoped_ptr<TemplateURLData> prepopulated_default =
712 TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(GetPrefs());
714 for (TemplateURLVector::iterator i = template_urls_.begin();
715 i != template_urls_.end(); ++i) {
716 if ((*i)->prepopulate_id() == prepopulated_default->prepopulate_id)
717 return *i;
719 // If not, use the first non-extension keyword of the templates that supports
720 // search term replacement.
721 if (processing_syncer_changes_) {
722 UMA_HISTOGRAM_ENUMERATION(
723 kFirstPotentialEngineHistogramName,
724 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_PROCESSING_SYNC_CHANGES,
725 FIRST_POTENTIAL_CALLSITE_MAX);
726 } else {
727 if (sync_processor_.get()) {
728 // We're not currently in a sync cycle, but we're syncing.
729 UMA_HISTOGRAM_ENUMERATION(kFirstPotentialEngineHistogramName,
730 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_SYNCING,
731 FIRST_POTENTIAL_CALLSITE_MAX);
732 } else {
733 // We're not syncing at all.
734 UMA_HISTOGRAM_ENUMERATION(
735 kFirstPotentialEngineHistogramName,
736 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_NOT_SYNCING,
737 FIRST_POTENTIAL_CALLSITE_MAX);
740 return FirstPotentialDefaultEngine(template_urls_);
743 void TemplateURLService::RepairPrepopulatedSearchEngines() {
744 // Can't clean DB if it hasn't been loaded.
745 DCHECK(loaded());
747 size_t default_search_provider_index = 0;
748 ScopedVector<TemplateURLData> prepopulated_urls =
749 TemplateURLPrepopulateData::GetPrepopulatedEngines(
750 GetPrefs(), &default_search_provider_index);
751 DCHECK(!prepopulated_urls.empty());
752 int default_search_engine_id =
753 prepopulated_urls[default_search_provider_index]->prepopulate_id;
754 TemplateURL* current_dse = default_search_provider_;
755 ActionsFromPrepopulateData actions(CreateActionsFromCurrentPrepopulateData(
756 &prepopulated_urls, template_urls_, current_dse));
758 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
760 // Remove items.
761 for (std::vector<TemplateURL*>::iterator i = actions.removed_engines.begin();
762 i < actions.removed_engines.end(); ++i)
763 RemoveNoNotify(*i);
765 // Edit items.
766 for (EditedEngines::iterator i(actions.edited_engines.begin());
767 i < actions.edited_engines.end(); ++i) {
768 UIThreadSearchTermsData search_terms_data(profile());
769 TemplateURL new_values(profile(), i->second);
770 UpdateNoNotify(i->first, new_values, search_terms_data);
773 // Add items.
774 for (std::vector<TemplateURLData>::const_iterator i =
775 actions.added_engines.begin();
776 i < actions.added_engines.end();
777 ++i) {
778 AddNoNotify(new TemplateURL(profile_, *i), true);
781 // Change the DSE.
782 TemplateURL* new_dse = FindURLByPrepopulateID(template_urls_,
783 default_search_engine_id);
784 DCHECK(new_dse);
785 if (CanMakeDefault(new_dse)) {
786 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
787 &dsp_change_origin_, DSP_CHANGE_PROFILE_RESET);
788 SetDefaultSearchProviderNoNotify(new_dse);
790 NotifyObservers();
793 void TemplateURLService::AddObserver(TemplateURLServiceObserver* observer) {
794 model_observers_.AddObserver(observer);
797 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver* observer) {
798 model_observers_.RemoveObserver(observer);
801 void TemplateURLService::Load() {
802 if (loaded_ || load_handle_)
803 return;
805 if (!service_.get()) {
806 service_ = WebDataService::FromBrowserContext(profile_);
809 if (service_.get()) {
810 load_handle_ = service_->GetKeywords(this);
811 } else {
812 ChangeToLoadedState();
813 on_loaded_callbacks_.Notify();
817 scoped_ptr<TemplateURLService::Subscription>
818 TemplateURLService::RegisterOnLoadedCallback(
819 const base::Closure& callback) {
820 return loaded_ ?
821 scoped_ptr<TemplateURLService::Subscription>() :
822 on_loaded_callbacks_.Add(callback);
825 void TemplateURLService::OnWebDataServiceRequestDone(
826 WebDataService::Handle h,
827 const WDTypedResult* result) {
828 // Reset the load_handle so that we don't try and cancel the load in
829 // the destructor.
830 load_handle_ = 0;
832 if (!result) {
833 // Results are null if the database went away or (most likely) wasn't
834 // loaded.
835 load_failed_ = true;
836 ChangeToLoadedState();
837 on_loaded_callbacks_.Notify();
838 return;
841 // initial_default_search_provider_ is only needed before we've finished
842 // loading. Now that we've loaded we can nuke it.
843 initial_default_search_provider_.reset();
845 TemplateURLVector template_urls;
846 TemplateURL* default_search_provider = NULL;
847 int new_resource_keyword_version = 0;
848 GetSearchProvidersUsingKeywordResult(*result, service_.get(), profile_,
849 &template_urls, &default_search_provider, &new_resource_keyword_version,
850 &pre_sync_deletes_);
852 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
854 AddTemplateURLsAndSetupDefaultEngine(&template_urls, default_search_provider);
856 // This initializes provider_map_ which should be done before
857 // calling UpdateKeywordSearchTermsForURL.
858 ChangeToLoadedState();
860 // Index any visits that occurred before we finished loading.
861 for (size_t i = 0; i < visits_to_add_.size(); ++i)
862 UpdateKeywordSearchTermsForURL(visits_to_add_[i]);
863 visits_to_add_.clear();
865 if (new_resource_keyword_version)
866 service_->SetBuiltinKeywordVersion(new_resource_keyword_version);
868 EnsureDefaultSearchProviderExists();
870 NotifyObservers();
871 on_loaded_callbacks_.Notify();
874 base::string16 TemplateURLService::GetKeywordShortName(
875 const base::string16& keyword,
876 bool* is_omnibox_api_extension_keyword) {
877 const TemplateURL* template_url = GetTemplateURLForKeyword(keyword);
879 // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
880 // to track changes to the model, this should become a DCHECK.
881 if (template_url) {
882 *is_omnibox_api_extension_keyword =
883 template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
884 return template_url->AdjustedShortNameForLocaleDirection();
886 *is_omnibox_api_extension_keyword = false;
887 return base::string16();
890 void TemplateURLService::Observe(int type,
891 const content::NotificationSource& source,
892 const content::NotificationDetails& details) {
893 if (type == chrome::NOTIFICATION_HISTORY_URL_VISITED) {
894 content::Details<history::URLVisitedDetails> visit_details(details);
895 if (!loaded_)
896 visits_to_add_.push_back(*visit_details.ptr());
897 else
898 UpdateKeywordSearchTermsForURL(*visit_details.ptr());
899 } else if (type == chrome::NOTIFICATION_DEFAULT_SEARCH_POLICY_CHANGED) {
900 // Policy has been updated, so the default search prefs may be different.
901 // Reload the default search provider from them.
902 // TODO(pkasting): Rather than communicating via prefs, we should eventually
903 // observe policy changes directly.
904 UpdateDefaultSearch();
905 } else {
906 DCHECK_EQ(chrome::NOTIFICATION_GOOGLE_URL_UPDATED, type);
907 if (loaded_) {
908 GoogleBaseURLChanged(
909 content::Details<GoogleURLTracker::UpdatedDetails>(details)->first);
914 void TemplateURLService::Shutdown() {
915 // This check has to be done at Shutdown() instead of in the dtor to ensure
916 // that no clients of WebDataService are holding ptrs to it after the first
917 // phase of the KeyedService Shutdown() process.
918 if (load_handle_) {
919 DCHECK(service_.get());
920 service_->CancelRequest(load_handle_);
922 service_ = NULL;
925 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
926 // Listen for changes to the default search from Sync.
927 PrefService* prefs = GetPrefs();
928 TemplateURL* new_default_search = GetTemplateURLForGUID(
929 prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID));
930 if (new_default_search && !is_default_search_managed_) {
931 if (new_default_search != GetDefaultSearchProvider()) {
932 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
933 &dsp_change_origin_, DSP_CHANGE_SYNC_PREF);
934 SetUserSelectedDefaultSearchProvider(new_default_search);
935 pending_synced_default_search_ = false;
937 } else {
938 // If it's not there, or if default search is currently managed, set a
939 // flag to indicate that we waiting on the search engine entry to come
940 // in through Sync.
941 pending_synced_default_search_ = true;
943 UpdateDefaultSearch();
946 syncer::SyncDataList TemplateURLService::GetAllSyncData(
947 syncer::ModelType type) const {
948 DCHECK_EQ(syncer::SEARCH_ENGINES, type);
950 syncer::SyncDataList current_data;
951 for (TemplateURLVector::const_iterator iter = template_urls_.begin();
952 iter != template_urls_.end(); ++iter) {
953 // We don't sync keywords managed by policy.
954 if ((*iter)->created_by_policy())
955 continue;
956 // We don't sync extension-controlled search engines.
957 if ((*iter)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
958 continue;
959 current_data.push_back(CreateSyncDataFromTemplateURL(**iter));
962 return current_data;
965 syncer::SyncError TemplateURLService::ProcessSyncChanges(
966 const tracked_objects::Location& from_here,
967 const syncer::SyncChangeList& change_list) {
968 if (!models_associated_) {
969 syncer::SyncError error(FROM_HERE,
970 syncer::SyncError::DATATYPE_ERROR,
971 "Models not yet associated.",
972 syncer::SEARCH_ENGINES);
973 return error;
975 DCHECK(loaded_);
977 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
979 // We've started syncing, so set our origin member to the base Sync value.
980 // As we move through Sync Code, we may set this to increasingly specific
981 // origins so we can tell what exactly caused a DSP change.
982 base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
983 DSP_CHANGE_SYNC_UNINTENTIONAL);
985 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
987 syncer::SyncChangeList new_changes;
988 syncer::SyncError error;
989 for (syncer::SyncChangeList::const_iterator iter = change_list.begin();
990 iter != change_list.end(); ++iter) {
991 DCHECK_EQ(syncer::SEARCH_ENGINES, iter->sync_data().GetDataType());
993 std::string guid =
994 iter->sync_data().GetSpecifics().search_engine().sync_guid();
995 TemplateURL* existing_turl = GetTemplateURLForGUID(guid);
996 scoped_ptr<TemplateURL> turl(CreateTemplateURLFromTemplateURLAndSyncData(
997 profile_, existing_turl, iter->sync_data(), &new_changes));
998 if (!turl.get())
999 continue;
1001 // Explicitly don't check for conflicts against extension keywords; in this
1002 // case the functions which modify the keyword map know how to handle the
1003 // conflicts.
1004 // TODO(mpcomplete): If we allow editing extension keywords, then those will
1005 // need to undergo conflict resolution.
1006 TemplateURL* existing_keyword_turl =
1007 FindNonExtensionTemplateURLForKeyword(turl->keyword());
1008 if (iter->change_type() == syncer::SyncChange::ACTION_DELETE) {
1009 if (!existing_turl) {
1010 error = sync_error_factory_->CreateAndUploadError(
1011 FROM_HERE,
1012 "ProcessSyncChanges failed on ChangeType ACTION_DELETE");
1013 continue;
1015 if (existing_turl == GetDefaultSearchProvider()) {
1016 // The only way Sync can attempt to delete the default search provider
1017 // is if we had changed the kSyncedDefaultSearchProviderGUID
1018 // preference, but perhaps it has not yet been received. To avoid
1019 // situations where this has come in erroneously, we will un-delete
1020 // the current default search from the Sync data. If the pref really
1021 // does arrive later, then default search will change to the correct
1022 // entry, but we'll have this extra entry sitting around. The result is
1023 // not ideal, but it prevents a far more severe bug where the default is
1024 // unexpectedly swapped to something else. The user can safely delete
1025 // the extra entry again later, if they choose. Most users who do not
1026 // look at the search engines UI will not notice this.
1027 // Note that we append a special character to the end of the keyword in
1028 // an attempt to avoid a ping-poinging situation where receiving clients
1029 // may try to continually delete the resurrected entry.
1030 base::string16 updated_keyword = UniquifyKeyword(*existing_turl, true);
1031 TemplateURLData data(existing_turl->data());
1032 data.SetKeyword(updated_keyword);
1033 TemplateURL new_turl(existing_turl->profile(), data);
1034 UIThreadSearchTermsData search_terms_data(existing_turl->profile());
1035 if (UpdateNoNotify(existing_turl, new_turl, search_terms_data))
1036 NotifyObservers();
1038 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(new_turl);
1039 new_changes.push_back(syncer::SyncChange(FROM_HERE,
1040 syncer::SyncChange::ACTION_ADD,
1041 sync_data));
1042 // Ignore the delete attempt. This means we never end up reseting the
1043 // default search provider due to an ACTION_DELETE from sync.
1044 continue;
1047 Remove(existing_turl);
1048 } else if (iter->change_type() == syncer::SyncChange::ACTION_ADD) {
1049 if (existing_turl) {
1050 error = sync_error_factory_->CreateAndUploadError(
1051 FROM_HERE,
1052 "ProcessSyncChanges failed on ChangeType ACTION_ADD");
1053 continue;
1055 const std::string guid = turl->sync_guid();
1056 if (existing_keyword_turl) {
1057 // Resolve any conflicts so we can safely add the new entry.
1058 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1059 &new_changes);
1061 // Force the local ID to kInvalidTemplateURLID so we can add it.
1062 TemplateURLData data(turl->data());
1063 data.id = kInvalidTemplateURLID;
1064 Add(new TemplateURL(profile_, data));
1066 // Possibly set the newly added |turl| as the default search provider.
1067 SetDefaultSearchProviderIfNewlySynced(guid);
1068 } else if (iter->change_type() == syncer::SyncChange::ACTION_UPDATE) {
1069 if (!existing_turl) {
1070 error = sync_error_factory_->CreateAndUploadError(
1071 FROM_HERE,
1072 "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
1073 continue;
1075 if (existing_keyword_turl && (existing_keyword_turl != existing_turl)) {
1076 // Resolve any conflicts with other entries so we can safely update the
1077 // keyword.
1078 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1079 &new_changes);
1081 UIThreadSearchTermsData search_terms_data(existing_turl->profile());
1082 if (UpdateNoNotify(existing_turl, *turl, search_terms_data))
1083 NotifyObservers();
1084 } else {
1085 // We've unexpectedly received an ACTION_INVALID.
1086 error = sync_error_factory_->CreateAndUploadError(
1087 FROM_HERE,
1088 "ProcessSyncChanges received an ACTION_INVALID");
1092 // If something went wrong, we want to prematurely exit to avoid pushing
1093 // inconsistent data to Sync. We return the last error we received.
1094 if (error.IsSet())
1095 return error;
1097 error = sync_processor_->ProcessSyncChanges(from_here, new_changes);
1099 return error;
1102 syncer::SyncMergeResult TemplateURLService::MergeDataAndStartSyncing(
1103 syncer::ModelType type,
1104 const syncer::SyncDataList& initial_sync_data,
1105 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
1106 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) {
1107 DCHECK(loaded_);
1108 DCHECK_EQ(type, syncer::SEARCH_ENGINES);
1109 DCHECK(!sync_processor_.get());
1110 DCHECK(sync_processor.get());
1111 DCHECK(sync_error_factory.get());
1112 syncer::SyncMergeResult merge_result(type);
1113 sync_processor_ = sync_processor.Pass();
1114 sync_error_factory_ = sync_error_factory.Pass();
1116 // We just started syncing, so set our wait-for-default flag if we are
1117 // expecting a default from Sync.
1118 if (GetPrefs()) {
1119 std::string default_guid = GetPrefs()->GetString(
1120 prefs::kSyncedDefaultSearchProviderGUID);
1121 const TemplateURL* current_default = GetDefaultSearchProvider();
1123 if (!default_guid.empty() &&
1124 (!current_default || current_default->sync_guid() != default_guid))
1125 pending_synced_default_search_ = true;
1128 // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
1129 // don't step on our own toes.
1130 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
1132 // We've started syncing, so set our origin member to the base Sync value.
1133 // As we move through Sync Code, we may set this to increasingly specific
1134 // origins so we can tell what exactly caused a DSP change.
1135 base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
1136 DSP_CHANGE_SYNC_UNINTENTIONAL);
1138 syncer::SyncChangeList new_changes;
1140 // Build maps of our sync GUIDs to syncer::SyncData.
1141 SyncDataMap local_data_map = CreateGUIDToSyncDataMap(
1142 GetAllSyncData(syncer::SEARCH_ENGINES));
1143 SyncDataMap sync_data_map = CreateGUIDToSyncDataMap(initial_sync_data);
1145 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
1147 merge_result.set_num_items_before_association(local_data_map.size());
1148 for (SyncDataMap::const_iterator iter = sync_data_map.begin();
1149 iter != sync_data_map.end(); ++iter) {
1150 TemplateURL* local_turl = GetTemplateURLForGUID(iter->first);
1151 scoped_ptr<TemplateURL> sync_turl(
1152 CreateTemplateURLFromTemplateURLAndSyncData(profile_, local_turl,
1153 iter->second, &new_changes));
1154 if (!sync_turl.get())
1155 continue;
1157 if (pre_sync_deletes_.find(sync_turl->sync_guid()) !=
1158 pre_sync_deletes_.end()) {
1159 // This entry was deleted before the initial sync began (possibly through
1160 // preprocessing in TemplateURLService's loading code). Ignore it and send
1161 // an ACTION_DELETE up to the server.
1162 new_changes.push_back(
1163 syncer::SyncChange(FROM_HERE,
1164 syncer::SyncChange::ACTION_DELETE,
1165 iter->second));
1166 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1167 DELETE_ENGINE_PRE_SYNC, DELETE_ENGINE_MAX);
1168 continue;
1171 if (local_turl) {
1172 DCHECK(IsFromSync(local_turl, sync_data_map));
1173 // This local search engine is already synced. If the timestamp differs
1174 // from Sync, we need to update locally or to the cloud. Note that if the
1175 // timestamps are equal, we touch neither.
1176 if (sync_turl->last_modified() > local_turl->last_modified()) {
1177 // We've received an update from Sync. We should replace all synced
1178 // fields in the local TemplateURL. Note that this includes the
1179 // TemplateURLID and the TemplateURL may have to be reparsed. This
1180 // also makes the local data's last_modified timestamp equal to Sync's,
1181 // avoiding an Update on the next MergeData call.
1182 UIThreadSearchTermsData search_terms_data(local_turl->profile());
1183 if (UpdateNoNotify(local_turl, *sync_turl, search_terms_data))
1184 NotifyObservers();
1185 merge_result.set_num_items_modified(
1186 merge_result.num_items_modified() + 1);
1187 } else if (sync_turl->last_modified() < local_turl->last_modified()) {
1188 // Otherwise, we know we have newer data, so update Sync with our
1189 // data fields.
1190 new_changes.push_back(
1191 syncer::SyncChange(FROM_HERE,
1192 syncer::SyncChange::ACTION_UPDATE,
1193 local_data_map[local_turl->sync_guid()]));
1195 local_data_map.erase(iter->first);
1196 } else {
1197 // The search engine from the cloud has not been synced locally. Merge it
1198 // into our local model. This will handle any conflicts with local (and
1199 // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1200 // over not-yet-synced TemplateURLs.
1201 MergeInSyncTemplateURL(sync_turl.get(), sync_data_map, &new_changes,
1202 &local_data_map, &merge_result);
1206 // If there is a pending synced default search provider that was processed
1207 // above, set it now.
1208 TemplateURL* pending_default = GetPendingSyncedDefaultSearchProvider();
1209 if (pending_default) {
1210 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
1211 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
1212 SetUserSelectedDefaultSearchProvider(pending_default);
1215 // The remaining SyncData in local_data_map should be everything that needs to
1216 // be pushed as ADDs to sync.
1217 for (SyncDataMap::const_iterator iter = local_data_map.begin();
1218 iter != local_data_map.end(); ++iter) {
1219 new_changes.push_back(
1220 syncer::SyncChange(FROM_HERE,
1221 syncer::SyncChange::ACTION_ADD,
1222 iter->second));
1225 // Do some post-processing on the change list to ensure that we are sending
1226 // valid changes to sync_processor_.
1227 PruneSyncChanges(&sync_data_map, &new_changes);
1229 LogDuplicatesHistogram(GetTemplateURLs());
1230 merge_result.set_num_items_after_association(
1231 GetAllSyncData(syncer::SEARCH_ENGINES).size());
1232 merge_result.set_error(
1233 sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
1234 if (merge_result.error().IsSet())
1235 return merge_result;
1237 // The ACTION_DELETEs from this set are processed. Empty it so we don't try to
1238 // reuse them on the next call to MergeDataAndStartSyncing.
1239 pre_sync_deletes_.clear();
1241 models_associated_ = true;
1242 return merge_result;
1245 void TemplateURLService::StopSyncing(syncer::ModelType type) {
1246 DCHECK_EQ(type, syncer::SEARCH_ENGINES);
1247 models_associated_ = false;
1248 sync_processor_.reset();
1249 sync_error_factory_.reset();
1252 void TemplateURLService::ProcessTemplateURLChange(
1253 const tracked_objects::Location& from_here,
1254 const TemplateURL* turl,
1255 syncer::SyncChange::SyncChangeType type) {
1256 DCHECK_NE(type, syncer::SyncChange::ACTION_INVALID);
1257 DCHECK(turl);
1259 if (!models_associated_)
1260 return; // Not syncing.
1262 if (processing_syncer_changes_)
1263 return; // These are changes originating from us. Ignore.
1265 // Avoid syncing keywords managed by policy.
1266 if (turl->created_by_policy())
1267 return;
1269 // Avoid syncing extension-controlled search engines.
1270 if (turl->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
1271 return;
1273 syncer::SyncChangeList changes;
1275 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1276 changes.push_back(syncer::SyncChange(from_here,
1277 type,
1278 sync_data));
1280 sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
1283 // static
1284 syncer::SyncData TemplateURLService::CreateSyncDataFromTemplateURL(
1285 const TemplateURL& turl) {
1286 sync_pb::EntitySpecifics specifics;
1287 sync_pb::SearchEngineSpecifics* se_specifics =
1288 specifics.mutable_search_engine();
1289 se_specifics->set_short_name(base::UTF16ToUTF8(turl.short_name()));
1290 se_specifics->set_keyword(base::UTF16ToUTF8(turl.keyword()));
1291 se_specifics->set_favicon_url(turl.favicon_url().spec());
1292 se_specifics->set_url(turl.url());
1293 se_specifics->set_safe_for_autoreplace(turl.safe_for_autoreplace());
1294 se_specifics->set_originating_url(turl.originating_url().spec());
1295 se_specifics->set_date_created(turl.date_created().ToInternalValue());
1296 se_specifics->set_input_encodings(JoinString(turl.input_encodings(), ';'));
1297 se_specifics->set_show_in_default_list(turl.show_in_default_list());
1298 se_specifics->set_suggestions_url(turl.suggestions_url());
1299 se_specifics->set_prepopulate_id(turl.prepopulate_id());
1300 se_specifics->set_instant_url(turl.instant_url());
1301 if (!turl.image_url().empty())
1302 se_specifics->set_image_url(turl.image_url());
1303 se_specifics->set_new_tab_url(turl.new_tab_url());
1304 if (!turl.search_url_post_params().empty())
1305 se_specifics->set_search_url_post_params(turl.search_url_post_params());
1306 if (!turl.suggestions_url_post_params().empty()) {
1307 se_specifics->set_suggestions_url_post_params(
1308 turl.suggestions_url_post_params());
1310 if (!turl.instant_url_post_params().empty())
1311 se_specifics->set_instant_url_post_params(turl.instant_url_post_params());
1312 if (!turl.image_url_post_params().empty())
1313 se_specifics->set_image_url_post_params(turl.image_url_post_params());
1314 se_specifics->set_last_modified(turl.last_modified().ToInternalValue());
1315 se_specifics->set_sync_guid(turl.sync_guid());
1316 for (size_t i = 0; i < turl.alternate_urls().size(); ++i)
1317 se_specifics->add_alternate_urls(turl.alternate_urls()[i]);
1318 se_specifics->set_search_terms_replacement_key(
1319 turl.search_terms_replacement_key());
1321 return syncer::SyncData::CreateLocalData(se_specifics->sync_guid(),
1322 se_specifics->keyword(),
1323 specifics);
1326 // static
1327 TemplateURL* TemplateURLService::CreateTemplateURLFromTemplateURLAndSyncData(
1328 Profile* profile,
1329 TemplateURL* existing_turl,
1330 const syncer::SyncData& sync_data,
1331 syncer::SyncChangeList* change_list) {
1332 DCHECK(change_list);
1334 sync_pb::SearchEngineSpecifics specifics =
1335 sync_data.GetSpecifics().search_engine();
1337 // Past bugs might have caused either of these fields to be empty. Just
1338 // delete this data off the server.
1339 if (specifics.url().empty() || specifics.sync_guid().empty()) {
1340 change_list->push_back(
1341 syncer::SyncChange(FROM_HERE,
1342 syncer::SyncChange::ACTION_DELETE,
1343 sync_data));
1344 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1345 DELETE_ENGINE_EMPTY_FIELD, DELETE_ENGINE_MAX);
1346 return NULL;
1349 TemplateURLData data(existing_turl ?
1350 existing_turl->data() : TemplateURLData());
1351 data.short_name = base::UTF8ToUTF16(specifics.short_name());
1352 data.originating_url = GURL(specifics.originating_url());
1353 base::string16 keyword(base::UTF8ToUTF16(specifics.keyword()));
1354 // NOTE: Once this code has shipped in a couple of stable releases, we can
1355 // probably remove the migration portion, comment out the
1356 // "autogenerate_keyword" field entirely in the .proto file, and fold the
1357 // empty keyword case into the "delete data" block above.
1358 bool reset_keyword =
1359 specifics.autogenerate_keyword() || specifics.keyword().empty();
1360 if (reset_keyword)
1361 keyword = base::ASCIIToUTF16("dummy"); // Will be replaced below.
1362 DCHECK(!keyword.empty());
1363 data.SetKeyword(keyword);
1364 data.SetURL(specifics.url());
1365 data.suggestions_url = specifics.suggestions_url();
1366 data.instant_url = specifics.instant_url();
1367 data.image_url = specifics.image_url();
1368 data.new_tab_url = specifics.new_tab_url();
1369 data.search_url_post_params = specifics.search_url_post_params();
1370 data.suggestions_url_post_params = specifics.suggestions_url_post_params();
1371 data.instant_url_post_params = specifics.instant_url_post_params();
1372 data.image_url_post_params = specifics.image_url_post_params();
1373 data.favicon_url = GURL(specifics.favicon_url());
1374 data.show_in_default_list = specifics.show_in_default_list();
1375 data.safe_for_autoreplace = specifics.safe_for_autoreplace();
1376 base::SplitString(specifics.input_encodings(), ';', &data.input_encodings);
1377 // If the server data has duplicate encodings, we'll want to push an update
1378 // below to correct it. Note that we also fix this in
1379 // GetSearchProvidersUsingKeywordResult(), since otherwise we'd never correct
1380 // local problems for clients which have disabled search engine sync.
1381 bool deduped = DeDupeEncodings(&data.input_encodings);
1382 data.date_created = base::Time::FromInternalValue(specifics.date_created());
1383 data.last_modified = base::Time::FromInternalValue(specifics.last_modified());
1384 data.prepopulate_id = specifics.prepopulate_id();
1385 data.sync_guid = specifics.sync_guid();
1386 data.alternate_urls.clear();
1387 for (int i = 0; i < specifics.alternate_urls_size(); ++i)
1388 data.alternate_urls.push_back(specifics.alternate_urls(i));
1389 data.search_terms_replacement_key = specifics.search_terms_replacement_key();
1391 TemplateURL* turl = new TemplateURL(profile, data);
1392 // If this TemplateURL matches a built-in prepopulated template URL, it's
1393 // possible that sync is trying to modify fields that should not be touched.
1394 // Revert these fields to the built-in values.
1395 UpdateTemplateURLIfPrepopulated(turl, profile);
1396 DCHECK_NE(TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION, turl->GetType());
1397 if (reset_keyword || deduped) {
1398 if (reset_keyword)
1399 turl->ResetKeywordIfNecessary(true);
1400 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1401 change_list->push_back(syncer::SyncChange(FROM_HERE,
1402 syncer::SyncChange::ACTION_UPDATE,
1403 sync_data));
1404 } else if (turl->IsGoogleSearchURLWithReplaceableKeyword()) {
1405 if (!existing_turl) {
1406 // We're adding a new TemplateURL that uses the Google base URL, so set
1407 // its keyword appropriately for the local environment.
1408 turl->ResetKeywordIfNecessary(false);
1409 } else if (existing_turl->IsGoogleSearchURLWithReplaceableKeyword()) {
1410 // Ignore keyword changes triggered by the Google base URL changing on
1411 // another client. If the base URL changes in this client as well, we'll
1412 // pick that up separately at the appropriate time. Otherwise, changing
1413 // the keyword here could result in having the wrong keyword for the local
1414 // environment.
1415 turl->data_.SetKeyword(existing_turl->keyword());
1419 return turl;
1422 // static
1423 SyncDataMap TemplateURLService::CreateGUIDToSyncDataMap(
1424 const syncer::SyncDataList& sync_data) {
1425 SyncDataMap data_map;
1426 for (syncer::SyncDataList::const_iterator i(sync_data.begin());
1427 i != sync_data.end();
1428 ++i)
1429 data_map[i->GetSpecifics().search_engine().sync_guid()] = *i;
1430 return data_map;
1433 void TemplateURLService::SetKeywordSearchTermsForURL(
1434 const TemplateURL* t_url,
1435 const GURL& url,
1436 const base::string16& term) {
1437 HistoryService* history = profile_ ?
1438 HistoryServiceFactory::GetForProfile(profile_,
1439 Profile::EXPLICIT_ACCESS) :
1440 NULL;
1441 if (!history)
1442 return;
1443 history->SetKeywordSearchTermsForURL(url, t_url->id(), term);
1446 void TemplateURLService::Init(const Initializer* initializers,
1447 int num_initializers) {
1448 // Register for notifications.
1449 if (profile_) {
1450 // TODO(sky): bug 1166191. The keywords should be moved into the history
1451 // db, which will mean we no longer need this notification and the history
1452 // backend can handle automatically adding the search terms as the user
1453 // navigates.
1454 content::Source<Profile> profile_source(profile_->GetOriginalProfile());
1455 notification_registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URL_VISITED,
1456 profile_source);
1457 notification_registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_URL_UPDATED,
1458 profile_source);
1459 pref_change_registrar_.Init(GetPrefs());
1460 pref_change_registrar_.Add(
1461 prefs::kSyncedDefaultSearchProviderGUID,
1462 base::Bind(
1463 &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged,
1464 base::Unretained(this)));
1466 notification_registrar_.Add(
1467 this, chrome::NOTIFICATION_DEFAULT_SEARCH_POLICY_CHANGED,
1468 content::NotificationService::AllSources());
1470 if (num_initializers > 0) {
1471 // This path is only hit by test code and is used to simulate a loaded
1472 // TemplateURLService.
1473 ChangeToLoadedState();
1475 // Add specific initializers, if any.
1476 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
1477 for (int i(0); i < num_initializers; ++i) {
1478 DCHECK(initializers[i].keyword);
1479 DCHECK(initializers[i].url);
1480 DCHECK(initializers[i].content);
1482 // TemplateURLService ends up owning the TemplateURL, don't try and free
1483 // it.
1484 TemplateURLData data;
1485 data.short_name = base::UTF8ToUTF16(initializers[i].content);
1486 data.SetKeyword(base::UTF8ToUTF16(initializers[i].keyword));
1487 data.SetURL(initializers[i].url);
1488 TemplateURL* template_url = new TemplateURL(profile_, data);
1489 AddNoNotify(template_url, true);
1491 // Set the first provided identifier to be the default.
1492 if (i == 0)
1493 SetDefaultSearchProviderNoNotify(template_url);
1497 // Initialize default search.
1498 UpdateDefaultSearch();
1500 // Request a server check for the correct Google URL if Google is the
1501 // default search engine and not in headless mode.
1502 if (profile_ && initial_default_search_provider_.get() &&
1503 initial_default_search_provider_->url_ref().HasGoogleBaseURLs()) {
1504 scoped_ptr<base::Environment> env(base::Environment::Create());
1505 if (!env->HasVar(env_vars::kHeadless))
1506 GoogleURLTracker::RequestServerCheck(profile_, false);
1510 void TemplateURLService::RemoveFromMaps(TemplateURL* template_url) {
1511 const base::string16& keyword = template_url->keyword();
1512 DCHECK_NE(0U, keyword_to_template_map_.count(keyword));
1513 if (keyword_to_template_map_[keyword] == template_url) {
1514 // We need to check whether the keyword can now be provided by another
1515 // TemplateURL. See the comments in AddToMaps() for more information on
1516 // extension keywords and how they can coexist with non-extension keywords.
1517 // In the case of more than one extension, we use the most recently
1518 // installed (which will be the most recently added, which will have the
1519 // highest ID).
1520 TemplateURL* best_fallback = NULL;
1521 for (TemplateURLVector::const_iterator i(template_urls_.begin());
1522 i != template_urls_.end(); ++i) {
1523 TemplateURL* turl = *i;
1524 // This next statement relies on the fact that there can only be one
1525 // non-Omnibox API TemplateURL with a given keyword.
1526 if ((turl != template_url) && (turl->keyword() == keyword) &&
1527 (!best_fallback ||
1528 (best_fallback->GetType() != TemplateURL::OMNIBOX_API_EXTENSION) ||
1529 ((turl->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) &&
1530 (turl->id() > best_fallback->id()))))
1531 best_fallback = turl;
1533 if (best_fallback)
1534 keyword_to_template_map_[keyword] = best_fallback;
1535 else
1536 keyword_to_template_map_.erase(keyword);
1539 if (!template_url->sync_guid().empty())
1540 guid_to_template_map_.erase(template_url->sync_guid());
1541 if (loaded_) {
1542 UIThreadSearchTermsData search_terms_data(template_url->profile());
1543 provider_map_->Remove(template_url, search_terms_data);
1547 void TemplateURLService::AddToMaps(TemplateURL* template_url) {
1548 bool template_url_is_omnibox_api =
1549 template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1550 const base::string16& keyword = template_url->keyword();
1551 KeywordToTemplateMap::const_iterator i =
1552 keyword_to_template_map_.find(keyword);
1553 if (i == keyword_to_template_map_.end()) {
1554 keyword_to_template_map_[keyword] = template_url;
1555 } else {
1556 const TemplateURL* existing_url = i->second;
1557 // We should only have overlapping keywords when at least one comes from
1558 // an extension. In that case, the ranking order is:
1559 // Manually-modified keywords > extension keywords > replaceable keywords
1560 // When there are multiple extensions, the last-added wins.
1561 bool existing_url_is_omnibox_api =
1562 existing_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1563 DCHECK(existing_url_is_omnibox_api || template_url_is_omnibox_api);
1564 if (existing_url_is_omnibox_api ?
1565 !CanReplace(template_url) : CanReplace(existing_url))
1566 keyword_to_template_map_[keyword] = template_url;
1569 if (!template_url->sync_guid().empty())
1570 guid_to_template_map_[template_url->sync_guid()] = template_url;
1571 if (loaded_) {
1572 UIThreadSearchTermsData search_terms_data(profile_);
1573 provider_map_->Add(template_url, search_terms_data);
1577 // Helper for partition() call in next function.
1578 bool HasValidID(TemplateURL* t_url) {
1579 return t_url->id() != kInvalidTemplateURLID;
1582 void TemplateURLService::SetTemplateURLs(TemplateURLVector* urls) {
1583 // Partition the URLs first, instead of implementing the loops below by simply
1584 // scanning the input twice. While it's not supposed to happen normally, it's
1585 // possible for corrupt databases to return multiple entries with the same
1586 // keyword. In this case, the first loop may delete the first entry when
1587 // adding the second. If this happens, the second loop must not attempt to
1588 // access the deleted entry. Partitioning ensures this constraint.
1589 TemplateURLVector::iterator first_invalid(
1590 std::partition(urls->begin(), urls->end(), HasValidID));
1592 // First, add the items that already have id's, so that the next_id_ gets
1593 // properly set.
1594 for (TemplateURLVector::const_iterator i = urls->begin(); i != first_invalid;
1595 ++i) {
1596 next_id_ = std::max(next_id_, (*i)->id());
1597 AddNoNotify(*i, false);
1600 // Next add the new items that don't have id's.
1601 for (TemplateURLVector::const_iterator i = first_invalid; i != urls->end();
1602 ++i)
1603 AddNoNotify(*i, true);
1605 // Clear the input vector to reduce the chance callers will try to use a
1606 // (possibly deleted) entry.
1607 urls->clear();
1610 void TemplateURLService::ChangeToLoadedState() {
1611 DCHECK(!loaded_);
1613 UIThreadSearchTermsData search_terms_data(profile_);
1614 provider_map_->Init(template_urls_, search_terms_data);
1615 loaded_ = true;
1618 void TemplateURLService::SaveDefaultSearchProviderToPrefs(
1619 const TemplateURL* t_url) {
1620 PrefService* prefs = GetPrefs();
1621 if (!prefs)
1622 return;
1624 bool enabled = false;
1625 std::string search_url;
1626 std::string suggest_url;
1627 std::string instant_url;
1628 std::string image_url;
1629 std::string new_tab_url;
1630 std::string search_url_post_params;
1631 std::string suggest_url_post_params;
1632 std::string instant_url_post_params;
1633 std::string image_url_post_params;
1634 std::string icon_url;
1635 std::string encodings;
1636 std::string short_name;
1637 std::string keyword;
1638 std::string id_string;
1639 std::string prepopulate_id;
1640 base::ListValue alternate_urls;
1641 std::string search_terms_replacement_key;
1642 if (t_url) {
1643 DCHECK_EQ(TemplateURL::NORMAL, t_url->GetType());
1644 enabled = true;
1645 search_url = t_url->url();
1646 suggest_url = t_url->suggestions_url();
1647 instant_url = t_url->instant_url();
1648 image_url = t_url->image_url();
1649 new_tab_url = t_url->new_tab_url();
1650 search_url_post_params = t_url->search_url_post_params();
1651 suggest_url_post_params = t_url->suggestions_url_post_params();
1652 instant_url_post_params = t_url->instant_url_post_params();
1653 image_url_post_params = t_url->image_url_post_params();
1654 GURL icon_gurl = t_url->favicon_url();
1655 if (!icon_gurl.is_empty())
1656 icon_url = icon_gurl.spec();
1657 encodings = JoinString(t_url->input_encodings(), ';');
1658 short_name = base::UTF16ToUTF8(t_url->short_name());
1659 keyword = base::UTF16ToUTF8(t_url->keyword());
1660 id_string = base::Int64ToString(t_url->id());
1661 prepopulate_id = base::Int64ToString(t_url->prepopulate_id());
1662 for (size_t i = 0; i < t_url->alternate_urls().size(); ++i)
1663 alternate_urls.AppendString(t_url->alternate_urls()[i]);
1664 search_terms_replacement_key = t_url->search_terms_replacement_key();
1666 prefs->SetBoolean(prefs::kDefaultSearchProviderEnabled, enabled);
1667 prefs->SetString(prefs::kDefaultSearchProviderSearchURL, search_url);
1668 prefs->SetString(prefs::kDefaultSearchProviderSuggestURL, suggest_url);
1669 prefs->SetString(prefs::kDefaultSearchProviderInstantURL, instant_url);
1670 prefs->SetString(prefs::kDefaultSearchProviderImageURL, image_url);
1671 prefs->SetString(prefs::kDefaultSearchProviderNewTabURL, new_tab_url);
1672 prefs->SetString(prefs::kDefaultSearchProviderSearchURLPostParams,
1673 search_url_post_params);
1674 prefs->SetString(prefs::kDefaultSearchProviderSuggestURLPostParams,
1675 suggest_url_post_params);
1676 prefs->SetString(prefs::kDefaultSearchProviderInstantURLPostParams,
1677 instant_url_post_params);
1678 prefs->SetString(prefs::kDefaultSearchProviderImageURLPostParams,
1679 image_url_post_params);
1680 prefs->SetString(prefs::kDefaultSearchProviderIconURL, icon_url);
1681 prefs->SetString(prefs::kDefaultSearchProviderEncodings, encodings);
1682 prefs->SetString(prefs::kDefaultSearchProviderName, short_name);
1683 prefs->SetString(prefs::kDefaultSearchProviderKeyword, keyword);
1684 prefs->SetString(prefs::kDefaultSearchProviderID, id_string);
1685 prefs->SetString(prefs::kDefaultSearchProviderPrepopulateID, prepopulate_id);
1686 prefs->Set(prefs::kDefaultSearchProviderAlternateURLs, alternate_urls);
1687 prefs->SetString(prefs::kDefaultSearchProviderSearchTermsReplacementKey,
1688 search_terms_replacement_key);
1691 bool TemplateURLService::LoadDefaultSearchProviderFromPrefs(
1692 scoped_ptr<TemplateURLData>* default_provider_data,
1693 bool* is_managed) {
1694 PrefService* prefs = GetPrefs();
1695 if (!prefs || !prefs->HasPrefPath(prefs::kDefaultSearchProviderSearchURL) ||
1696 !prefs->HasPrefPath(prefs::kDefaultSearchProviderKeyword))
1697 return false;
1699 const PrefService::Preference* pref =
1700 prefs->FindPreference(prefs::kDefaultSearchProviderSearchURL);
1701 *is_managed = pref && pref->IsManaged();
1703 if (!prefs->GetBoolean(prefs::kDefaultSearchProviderEnabled)) {
1704 // The user doesn't want a default search provider.
1705 default_provider_data->reset(NULL);
1706 return true;
1709 base::string16 name =
1710 base::UTF8ToUTF16(prefs->GetString(prefs::kDefaultSearchProviderName));
1711 base::string16 keyword =
1712 base::UTF8ToUTF16(prefs->GetString(prefs::kDefaultSearchProviderKeyword));
1713 if (keyword.empty())
1714 return false;
1715 std::string search_url =
1716 prefs->GetString(prefs::kDefaultSearchProviderSearchURL);
1717 // Force URL to be non-empty. We've never supported this case, but past bugs
1718 // might have resulted in it slipping through; eventually this code can be
1719 // replaced with a DCHECK(!search_url.empty());.
1720 if (search_url.empty())
1721 return false;
1722 std::string suggest_url =
1723 prefs->GetString(prefs::kDefaultSearchProviderSuggestURL);
1724 std::string instant_url =
1725 prefs->GetString(prefs::kDefaultSearchProviderInstantURL);
1726 std::string image_url =
1727 prefs->GetString(prefs::kDefaultSearchProviderImageURL);
1728 std::string new_tab_url =
1729 prefs->GetString(prefs::kDefaultSearchProviderNewTabURL);
1730 std::string search_url_post_params =
1731 prefs->GetString(prefs::kDefaultSearchProviderSearchURLPostParams);
1732 std::string suggest_url_post_params =
1733 prefs->GetString(prefs::kDefaultSearchProviderSuggestURLPostParams);
1734 std::string instant_url_post_params =
1735 prefs->GetString(prefs::kDefaultSearchProviderInstantURLPostParams);
1736 std::string image_url_post_params =
1737 prefs->GetString(prefs::kDefaultSearchProviderImageURLPostParams);
1738 std::string icon_url =
1739 prefs->GetString(prefs::kDefaultSearchProviderIconURL);
1740 std::string encodings =
1741 prefs->GetString(prefs::kDefaultSearchProviderEncodings);
1742 std::string id_string = prefs->GetString(prefs::kDefaultSearchProviderID);
1743 std::string prepopulate_id =
1744 prefs->GetString(prefs::kDefaultSearchProviderPrepopulateID);
1745 const base::ListValue* alternate_urls =
1746 prefs->GetList(prefs::kDefaultSearchProviderAlternateURLs);
1747 std::string search_terms_replacement_key = prefs->GetString(
1748 prefs::kDefaultSearchProviderSearchTermsReplacementKey);
1750 default_provider_data->reset(new TemplateURLData);
1751 (*default_provider_data)->short_name = name;
1752 (*default_provider_data)->SetKeyword(keyword);
1753 (*default_provider_data)->SetURL(search_url);
1754 (*default_provider_data)->suggestions_url = suggest_url;
1755 (*default_provider_data)->instant_url = instant_url;
1756 (*default_provider_data)->image_url = image_url;
1757 (*default_provider_data)->new_tab_url = new_tab_url;
1758 (*default_provider_data)->search_url_post_params = search_url_post_params;
1759 (*default_provider_data)->suggestions_url_post_params =
1760 suggest_url_post_params;
1761 (*default_provider_data)->instant_url_post_params = instant_url_post_params;
1762 (*default_provider_data)->image_url_post_params = image_url_post_params;
1763 (*default_provider_data)->favicon_url = GURL(icon_url);
1764 (*default_provider_data)->show_in_default_list = true;
1765 (*default_provider_data)->alternate_urls.clear();
1766 for (size_t i = 0; i < alternate_urls->GetSize(); ++i) {
1767 std::string alternate_url;
1768 if (alternate_urls->GetString(i, &alternate_url))
1769 (*default_provider_data)->alternate_urls.push_back(alternate_url);
1771 (*default_provider_data)->search_terms_replacement_key =
1772 search_terms_replacement_key;
1773 base::SplitString(encodings, ';', &(*default_provider_data)->input_encodings);
1774 if (!id_string.empty() && !*is_managed) {
1775 int64 value;
1776 base::StringToInt64(id_string, &value);
1777 (*default_provider_data)->id = value;
1779 if (!prepopulate_id.empty() && !*is_managed) {
1780 int value;
1781 base::StringToInt(prepopulate_id, &value);
1782 (*default_provider_data)->prepopulate_id = value;
1784 return true;
1787 void TemplateURLService::ClearDefaultProviderFromPrefs() {
1788 // We overwrite user preferences. If the default search engine is managed,
1789 // there is no effect.
1790 SaveDefaultSearchProviderToPrefs(NULL);
1791 // Default value for kDefaultSearchProviderEnabled is true.
1792 PrefService* prefs = GetPrefs();
1793 if (prefs)
1794 prefs->SetBoolean(prefs::kDefaultSearchProviderEnabled, true);
1797 bool TemplateURLService::CanReplaceKeywordForHost(
1798 const std::string& host,
1799 TemplateURL** to_replace) {
1800 DCHECK(!to_replace || !*to_replace);
1801 const TemplateURLSet* urls = provider_map_->GetURLsForHost(host);
1802 if (!urls)
1803 return true;
1804 for (TemplateURLSet::const_iterator i(urls->begin()); i != urls->end(); ++i) {
1805 if (CanReplace(*i)) {
1806 if (to_replace)
1807 *to_replace = *i;
1808 return true;
1811 return false;
1814 bool TemplateURLService::CanReplace(const TemplateURL* t_url) {
1815 return (t_url != default_search_provider_ && !t_url->show_in_default_list() &&
1816 t_url->safe_for_autoreplace());
1819 TemplateURL* TemplateURLService::FindNonExtensionTemplateURLForKeyword(
1820 const base::string16& keyword) {
1821 TemplateURL* keyword_turl = GetTemplateURLForKeyword(keyword);
1822 if (!keyword_turl || (keyword_turl->GetType() == TemplateURL::NORMAL))
1823 return keyword_turl;
1824 // The extension keyword in the model may be hiding a replaceable
1825 // non-extension keyword. Look for it.
1826 for (TemplateURLVector::const_iterator i(template_urls_.begin());
1827 i != template_urls_.end(); ++i) {
1828 if (((*i)->GetType() == TemplateURL::NORMAL) &&
1829 ((*i)->keyword() == keyword))
1830 return *i;
1832 return NULL;
1835 bool TemplateURLService::UpdateNoNotify(
1836 TemplateURL* existing_turl,
1837 const TemplateURL& new_values,
1838 const SearchTermsData& old_search_terms_data) {
1839 DCHECK(loaded_);
1840 DCHECK(existing_turl);
1841 if (std::find(template_urls_.begin(), template_urls_.end(), existing_turl) ==
1842 template_urls_.end())
1843 return false;
1845 base::string16 old_keyword(existing_turl->keyword());
1846 keyword_to_template_map_.erase(old_keyword);
1847 if (!existing_turl->sync_guid().empty())
1848 guid_to_template_map_.erase(existing_turl->sync_guid());
1850 provider_map_->Remove(existing_turl, old_search_terms_data);
1851 TemplateURLID previous_id = existing_turl->id();
1852 existing_turl->CopyFrom(new_values);
1853 existing_turl->data_.id = previous_id;
1854 UIThreadSearchTermsData new_search_terms_data(profile_);
1855 provider_map_->Add(existing_turl, new_search_terms_data);
1857 const base::string16& keyword = existing_turl->keyword();
1858 KeywordToTemplateMap::const_iterator i =
1859 keyword_to_template_map_.find(keyword);
1860 if (i == keyword_to_template_map_.end()) {
1861 keyword_to_template_map_[keyword] = existing_turl;
1862 } else {
1863 // We can theoretically reach here in two cases:
1864 // * There is an existing extension keyword and sync brings in a rename of
1865 // a non-extension keyword to match. In this case we just need to pick
1866 // which keyword has priority to update the keyword map.
1867 // * Autogeneration of the keyword for a Google default search provider
1868 // at load time causes it to conflict with an existing keyword. In this
1869 // case we delete the existing keyword if it's replaceable, or else undo
1870 // the change in keyword for |existing_turl|.
1871 TemplateURL* existing_keyword_turl = i->second;
1872 if (existing_keyword_turl->GetType() != TemplateURL::NORMAL) {
1873 if (!CanReplace(existing_turl))
1874 keyword_to_template_map_[keyword] = existing_turl;
1875 } else {
1876 if (CanReplace(existing_keyword_turl)) {
1877 RemoveNoNotify(existing_keyword_turl);
1878 } else {
1879 existing_turl->data_.SetKeyword(old_keyword);
1880 keyword_to_template_map_[old_keyword] = existing_turl;
1884 if (!existing_turl->sync_guid().empty())
1885 guid_to_template_map_[existing_turl->sync_guid()] = existing_turl;
1887 if (service_.get())
1888 service_->UpdateKeyword(existing_turl->data());
1890 // Inform sync of the update.
1891 ProcessTemplateURLChange(FROM_HERE,
1892 existing_turl,
1893 syncer::SyncChange::ACTION_UPDATE);
1895 if (default_search_provider_ == existing_turl) {
1896 bool success = SetDefaultSearchProviderNoNotify(existing_turl);
1897 DCHECK(success);
1899 return true;
1902 // static
1903 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1904 TemplateURL* template_url,
1905 Profile* profile) {
1906 int prepopulate_id = template_url->prepopulate_id();
1907 if (template_url->prepopulate_id() == 0)
1908 return;
1910 size_t default_search_index;
1911 ScopedVector<TemplateURLData> prepopulated_urls =
1912 TemplateURLPrepopulateData::GetPrepopulatedEngines(
1913 profile ? profile->GetPrefs() : NULL, &default_search_index);
1915 for (size_t i = 0; i < prepopulated_urls.size(); ++i) {
1916 if (prepopulated_urls[i]->prepopulate_id == prepopulate_id) {
1917 MergeIntoPrepopulatedEngineData(template_url, prepopulated_urls[i]);
1918 template_url->CopyFrom(TemplateURL(profile, *prepopulated_urls[i]));
1923 PrefService* TemplateURLService::GetPrefs() {
1924 return profile_ ? profile_->GetPrefs() : NULL;
1927 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1928 const history::URLVisitedDetails& details) {
1929 const history::URLRow& row = details.row;
1930 if (!row.url().is_valid())
1931 return;
1933 const TemplateURLSet* urls_for_host =
1934 provider_map_->GetURLsForHost(row.url().host());
1935 if (!urls_for_host)
1936 return;
1938 for (TemplateURLSet::const_iterator i = urls_for_host->begin();
1939 i != urls_for_host->end(); ++i) {
1940 base::string16 search_terms;
1941 if ((*i)->ExtractSearchTermsFromURL(row.url(), &search_terms) &&
1942 !search_terms.empty()) {
1943 if (content::PageTransitionStripQualifier(details.transition) ==
1944 content::PAGE_TRANSITION_KEYWORD) {
1945 // The visit is the result of the user entering a keyword, generate a
1946 // KEYWORD_GENERATED visit for the KEYWORD so that the keyword typed
1947 // count is boosted.
1948 AddTabToSearchVisit(**i);
1950 SetKeywordSearchTermsForURL(*i, row.url(), search_terms);
1955 void TemplateURLService::AddTabToSearchVisit(const TemplateURL& t_url) {
1956 // Only add visits for entries the user hasn't modified. If the user modified
1957 // the entry the keyword may no longer correspond to the host name. It may be
1958 // possible to do something more sophisticated here, but it's so rare as to
1959 // not be worth it.
1960 if (!t_url.safe_for_autoreplace())
1961 return;
1963 if (!profile_)
1964 return;
1966 HistoryService* history =
1967 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
1968 if (!history)
1969 return;
1971 GURL url(URLFixerUpper::FixupURL(base::UTF16ToUTF8(t_url.keyword()),
1972 std::string()));
1973 if (!url.is_valid())
1974 return;
1976 // Synthesize a visit for the keyword. This ensures the url for the keyword is
1977 // autocompleted even if the user doesn't type the url in directly.
1978 history->AddPage(url, base::Time::Now(), NULL, 0, GURL(),
1979 history::RedirectList(),
1980 content::PAGE_TRANSITION_KEYWORD_GENERATED,
1981 history::SOURCE_BROWSED, false);
1984 void TemplateURLService::GoogleBaseURLChanged(const GURL& old_base_url) {
1985 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
1986 bool something_changed = false;
1987 for (TemplateURLVector::iterator i(template_urls_.begin());
1988 i != template_urls_.end(); ++i) {
1989 TemplateURL* t_url = *i;
1990 if (t_url->url_ref().HasGoogleBaseURLs() ||
1991 t_url->suggestions_url_ref().HasGoogleBaseURLs()) {
1992 TemplateURL updated_turl(t_url->profile(), t_url->data());
1993 updated_turl.ResetKeywordIfNecessary(false);
1994 KeywordToTemplateMap::const_iterator existing_entry =
1995 keyword_to_template_map_.find(updated_turl.keyword());
1996 if ((existing_entry != keyword_to_template_map_.end()) &&
1997 (existing_entry->second != t_url)) {
1998 // The new autogenerated keyword conflicts with another TemplateURL.
1999 // Overwrite it if it's replaceable; otherwise, leave |t_url| using its
2000 // current keyword. (This will not prevent |t_url| from auto-updating
2001 // the keyword in the future if the conflicting TemplateURL disappears.)
2002 // Note that we must still update |t_url| in this case, or the
2003 // |provider_map_| will not be updated correctly.
2004 if (CanReplace(existing_entry->second))
2005 RemoveNoNotify(existing_entry->second);
2006 else
2007 updated_turl.data_.SetKeyword(t_url->keyword());
2009 something_changed = true;
2010 // This will send the keyword change to sync. Note that other clients
2011 // need to reset the keyword to an appropriate local value when this
2012 // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
2013 UpdateNoNotify(t_url, updated_turl,
2014 OldBaseURLSearchTermsData(t_url->profile(), old_base_url.spec()));
2017 if (something_changed)
2018 NotifyObservers();
2021 void TemplateURLService::UpdateDefaultSearch() {
2022 if (!loaded_) {
2023 // Set |initial_default_search_provider_| from the preferences. We use this
2024 // value for default search provider until the database has been loaded.
2025 scoped_ptr<TemplateURLData> data;
2026 if (!LoadDefaultSearchProviderFromPrefs(&data,
2027 &is_default_search_managed_)) {
2028 // Prefs does not specify, so rely on the prepopulated engines. This
2029 // should happen only the first time Chrome is started.
2030 data =
2031 TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(GetPrefs());
2032 is_default_search_managed_ = false;
2035 initial_default_search_provider_.reset(
2036 data ? new TemplateURL(profile_, *data) : NULL);
2038 return;
2040 // Load the default search specified in prefs.
2041 scoped_ptr<TemplateURLData> new_default_from_prefs;
2042 bool new_is_default_managed = false;
2043 // Load the default from prefs. It's possible that it won't succeed
2044 // because we are in the middle of doing SaveDefaultSearchProviderToPrefs()
2045 // and all the preference items have not been saved. In that case, we
2046 // don't have yet a default. It would be much better if we could save
2047 // preferences in batches and trigger notifications at the end.
2048 LoadDefaultSearchProviderFromPrefs(&new_default_from_prefs,
2049 &new_is_default_managed);
2050 if (!is_default_search_managed_ && !new_is_default_managed) {
2051 // We're not interested in cases where the default was and remains
2052 // unmanaged. In that case, preferences have no impact on the default.
2053 return;
2055 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
2056 if (is_default_search_managed_ && new_is_default_managed) {
2057 // The default was managed and remains managed. Update the default only
2058 // if it has changed; we don't want to respond to changes triggered by
2059 // SaveDefaultSearchProviderToPrefs.
2060 if (TemplateURLMatchesData(default_search_provider_,
2061 new_default_from_prefs.get()))
2062 return;
2063 if (!new_default_from_prefs) {
2064 // default_search_provider_ can't be NULL otherwise
2065 // TemplateURLMatchesData would have returned true. Remove this now
2066 // invalid value.
2067 TemplateURL* old_default = default_search_provider_;
2068 bool success = SetDefaultSearchProviderNoNotify(NULL);
2069 DCHECK(success);
2070 RemoveNoNotify(old_default);
2071 } else if (default_search_provider_) {
2072 new_default_from_prefs->created_by_policy = true;
2073 TemplateURL new_values(profile_, *new_default_from_prefs);
2074 UIThreadSearchTermsData search_terms_data(
2075 default_search_provider_->profile());
2076 UpdateNoNotify(default_search_provider_, new_values, search_terms_data);
2077 } else {
2078 TemplateURL* new_template = NULL;
2079 if (new_default_from_prefs) {
2080 new_default_from_prefs->created_by_policy = true;
2081 new_template = new TemplateURL(profile_, *new_default_from_prefs);
2082 if (!AddNoNotify(new_template, true))
2083 return;
2085 bool success = SetDefaultSearchProviderNoNotify(new_template);
2086 DCHECK(success);
2088 } else if (!is_default_search_managed_ && new_is_default_managed) {
2089 // The default used to be unmanaged and is now managed. Add the new
2090 // managed default to the list of URLs and set it as default.
2091 is_default_search_managed_ = new_is_default_managed;
2092 TemplateURL* new_template = NULL;
2093 if (new_default_from_prefs) {
2094 new_default_from_prefs->created_by_policy = true;
2095 new_template = new TemplateURL(profile_, *new_default_from_prefs);
2096 if (!AddNoNotify(new_template, true))
2097 return;
2099 bool success = SetDefaultSearchProviderNoNotify(new_template);
2100 DCHECK(success);
2101 } else {
2102 // The default was managed and is no longer.
2103 DCHECK(is_default_search_managed_ && !new_is_default_managed);
2104 is_default_search_managed_ = new_is_default_managed;
2105 // If we had a default, delete the previous default if created by policy
2106 // and set a likely default.
2107 if ((default_search_provider_ != NULL) &&
2108 default_search_provider_->created_by_policy()) {
2109 TemplateURL* old_default = default_search_provider_;
2110 default_search_provider_ = NULL;
2111 RemoveNoNotify(old_default);
2114 // The likely default should be from Sync if we were waiting on Sync.
2115 // Otherwise, it should be FindNewDefaultSearchProvider.
2116 TemplateURL* synced_default = GetPendingSyncedDefaultSearchProvider();
2117 if (synced_default) {
2118 pending_synced_default_search_ = false;
2120 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2121 &dsp_change_origin_, DSP_CHANGE_SYNC_NOT_MANAGED);
2122 SetDefaultSearchProviderNoNotify(synced_default);
2123 } else {
2124 SetDefaultSearchProviderNoNotify(FindNewDefaultSearchProvider());
2127 NotifyObservers();
2130 void TemplateURLService::SetDefaultSearchProvider(
2131 TemplateURL* url) {
2132 DCHECK(!is_default_search_managed_);
2133 // Omnibox keywords cannot be made default. Extension-controlled search
2134 // engines can be made default only by the extension itself because they
2135 // aren't persisted.
2136 DCHECK(!url || (url->GetType() == TemplateURL::NORMAL));
2138 // Always persist the setting in the database, that way if the backup
2139 // signature has changed out from under us it gets reset correctly.
2140 if (SetDefaultSearchProviderNoNotify(url))
2141 NotifyObservers();
2144 bool TemplateURLService::SetDefaultSearchProviderNoNotify(TemplateURL* url) {
2145 if (url) {
2146 if (std::find(template_urls_.begin(), template_urls_.end(), url) ==
2147 template_urls_.end())
2148 return false;
2149 // Omnibox keywords cannot be made default.
2150 DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION, url->GetType());
2153 // Only bother reassigning |url| if it has changed. Notice that we don't just
2154 // early exit if they are equal, because |url| may have had its fields
2155 // changed, and needs to be persisted below (for example, when this is called
2156 // from UpdateNoNotify).
2157 if (default_search_provider_ != url) {
2158 // Engines set by policy override extension-controlled engines, which
2159 // override other engines.
2160 DCHECK(!is_default_search_managed() || !url ||
2161 (url->GetType() == TemplateURL::NORMAL));
2162 if (is_default_search_managed() || !default_search_provider_ ||
2163 (default_search_provider_->GetType() == TemplateURL::NORMAL) ||
2164 (url &&
2165 (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION))){
2166 UMA_HISTOGRAM_ENUMERATION("Search.DefaultSearchChangeOrigin",
2167 dsp_change_origin_, DSP_CHANGE_MAX);
2168 default_search_provider_ = url;
2172 if (url) {
2173 // Don't mark the url as edited, otherwise we won't be able to rev the
2174 // template urls we ship with.
2175 url->data_.show_in_default_list = true;
2176 if (service_.get() && (url->GetType() == TemplateURL::NORMAL))
2177 service_->UpdateKeyword(url->data());
2179 if (url->url_ref().HasGoogleBaseURLs()) {
2180 GoogleURLTracker::RequestServerCheck(profile_, false);
2181 #if defined(ENABLE_RLZ)
2182 RLZTracker::RecordProductEvent(rlz_lib::CHROME,
2183 RLZTracker::CHROME_OMNIBOX,
2184 rlz_lib::SET_TO_GOOGLE);
2185 #endif
2189 // Extension-controlled search engines shouldn't be persisted anywhere.
2190 if (url && (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION))
2191 return true;
2193 if (!is_default_search_managed_) {
2194 SaveDefaultSearchProviderToPrefs(url);
2196 // If we are syncing, we want to set the synced pref that will notify other
2197 // instances to change their default to this new search provider.
2198 // Note: we don't update the pref if we're currently in the middle of
2199 // handling a sync operation. Sync operations from other clients are not
2200 // guaranteed to arrive together, and any client that deletes the default
2201 // needs to set a new default as well. If we update the default here, we're
2202 // likely to race with the update from the other client, resulting in
2203 // a possibly random default search provider.
2204 if (sync_processor_.get() && url && !url->sync_guid().empty() &&
2205 GetPrefs() && !processing_syncer_changes_) {
2206 GetPrefs()->SetString(prefs::kSyncedDefaultSearchProviderGUID,
2207 url->sync_guid());
2211 if (service_.get())
2212 service_->SetDefaultSearchProviderID(url ? url->id() : 0);
2214 // Inform sync the change to the show_in_default_list flag.
2215 if (url)
2216 ProcessTemplateURLChange(FROM_HERE,
2217 url,
2218 syncer::SyncChange::ACTION_UPDATE);
2219 return true;
2222 bool TemplateURLService::AddNoNotify(TemplateURL* template_url,
2223 bool newly_adding) {
2224 DCHECK(template_url);
2226 if (newly_adding) {
2227 DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
2228 DCHECK(std::find(template_urls_.begin(), template_urls_.end(),
2229 template_url) == template_urls_.end());
2230 template_url->data_.id = ++next_id_;
2233 template_url->ResetKeywordIfNecessary(false);
2234 // Check whether |template_url|'s keyword conflicts with any already in the
2235 // model.
2236 TemplateURL* existing_keyword_turl =
2237 GetTemplateURLForKeyword(template_url->keyword());
2238 if (existing_keyword_turl != NULL) {
2239 DCHECK_NE(existing_keyword_turl, template_url);
2240 // Only replace one of the TemplateURLs if they are either both extensions,
2241 // or both not extensions.
2242 bool are_same_type = existing_keyword_turl->GetType() ==
2243 template_url->GetType();
2244 if (CanReplace(existing_keyword_turl) && are_same_type) {
2245 RemoveNoNotify(existing_keyword_turl);
2246 } else if (CanReplace(template_url) && are_same_type) {
2247 delete template_url;
2248 return false;
2249 } else {
2250 base::string16 new_keyword =
2251 UniquifyKeyword(*existing_keyword_turl, false);
2252 ResetTemplateURL(existing_keyword_turl,
2253 existing_keyword_turl->short_name(), new_keyword,
2254 existing_keyword_turl->url());
2257 template_urls_.push_back(template_url);
2258 AddToMaps(template_url);
2260 if (newly_adding &&
2261 (template_url->GetType() !=
2262 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)) {
2263 if (service_.get())
2264 service_->AddKeyword(template_url->data());
2266 // Inform sync of the addition. Note that this will assign a GUID to
2267 // template_url and add it to the guid_to_template_map_.
2268 ProcessTemplateURLChange(FROM_HERE,
2269 template_url,
2270 syncer::SyncChange::ACTION_ADD);
2273 return true;
2276 void TemplateURLService::RemoveNoNotify(TemplateURL* template_url) {
2277 DCHECK(template_url != default_search_provider_);
2279 TemplateURLVector::iterator i =
2280 std::find(template_urls_.begin(), template_urls_.end(), template_url);
2281 if (i == template_urls_.end())
2282 return;
2284 RemoveFromMaps(template_url);
2286 // Remove it from the vector containing all TemplateURLs.
2287 template_urls_.erase(i);
2289 if (template_url->GetType() != TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) {
2290 if (service_.get())
2291 service_->RemoveKeyword(template_url->id());
2293 // Inform sync of the deletion.
2294 ProcessTemplateURLChange(FROM_HERE,
2295 template_url,
2296 syncer::SyncChange::ACTION_DELETE);
2298 UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
2299 DELETE_ENGINE_USER_ACTION, DELETE_ENGINE_MAX);
2302 if (profile_) {
2303 content::Source<Profile> source(profile_);
2304 TemplateURLID id = template_url->id();
2305 content::NotificationService::current()->Notify(
2306 chrome::NOTIFICATION_TEMPLATE_URL_REMOVED,
2307 source,
2308 content::Details<TemplateURLID>(&id));
2311 // We own the TemplateURL and need to delete it.
2312 delete template_url;
2315 void TemplateURLService::NotifyObservers() {
2316 if (!loaded_)
2317 return;
2319 FOR_EACH_OBSERVER(TemplateURLServiceObserver, model_observers_,
2320 OnTemplateURLServiceChanged());
2323 // |template_urls| are the TemplateURLs loaded from the database.
2324 // |default_search_provider| points to one of them, if it was set in the db.
2325 // |default_from_prefs| is the default search provider from the preferences.
2326 // Check |is_default_search_managed_| to determine if it was set by policy.
2328 // This function removes from the vector and the database all the TemplateURLs
2329 // that were set by policy, unless it is the current default search provider
2330 // and matches what is set by a managed preference.
2331 void TemplateURLService::RemoveProvidersCreatedByPolicy(
2332 TemplateURLVector* template_urls,
2333 TemplateURL** default_search_provider,
2334 TemplateURLData* default_from_prefs) {
2335 DCHECK(template_urls);
2336 DCHECK(default_search_provider);
2337 for (TemplateURLVector::iterator i = template_urls->begin();
2338 i != template_urls->end(); ) {
2339 TemplateURL* template_url = *i;
2340 if (template_url->created_by_policy()) {
2341 if (template_url == *default_search_provider &&
2342 is_default_search_managed_ &&
2343 TemplateURLMatchesData(template_url, default_from_prefs)) {
2344 // If the database specified a default search provider that was set
2345 // by policy, and the default search provider from the preferences
2346 // is also set by policy and they are the same, keep the entry in the
2347 // database and the |default_search_provider|.
2348 ++i;
2349 continue;
2352 // The database loaded a managed |default_search_provider|, but it has
2353 // been updated in the prefs. Remove it from the database, and update the
2354 // |default_search_provider| pointer here.
2355 if (*default_search_provider &&
2356 (*default_search_provider)->id() == template_url->id())
2357 *default_search_provider = NULL;
2359 i = template_urls->erase(i);
2360 if (service_.get())
2361 service_->RemoveKeyword(template_url->id());
2362 delete template_url;
2363 } else {
2364 ++i;
2369 void TemplateURLService::ResetTemplateURLGUID(TemplateURL* url,
2370 const std::string& guid) {
2371 DCHECK(loaded_);
2372 DCHECK(!guid.empty());
2374 TemplateURLData data(url->data());
2375 data.sync_guid = guid;
2376 TemplateURL new_url(url->profile(), data);
2377 UIThreadSearchTermsData search_terms_data(url->profile());
2378 UpdateNoNotify(url, new_url, search_terms_data);
2381 base::string16 TemplateURLService::UniquifyKeyword(const TemplateURL& turl,
2382 bool force) {
2383 if (!force) {
2384 // Already unique.
2385 if (!GetTemplateURLForKeyword(turl.keyword()))
2386 return turl.keyword();
2388 // First, try to return the generated keyword for the TemplateURL (except
2389 // for extensions, as their keywords are not associated with their URLs).
2390 GURL gurl(turl.url());
2391 if (gurl.is_valid() &&
2392 (turl.GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
2393 base::string16 keyword_candidate = GenerateKeyword(gurl);
2394 if (!GetTemplateURLForKeyword(keyword_candidate))
2395 return keyword_candidate;
2399 // We try to uniquify the keyword by appending a special character to the end.
2400 // This is a best-effort approach where we try to preserve the original
2401 // keyword and let the user do what they will after our attempt.
2402 base::string16 keyword_candidate(turl.keyword());
2403 do {
2404 keyword_candidate.append(base::ASCIIToUTF16("_"));
2405 } while (GetTemplateURLForKeyword(keyword_candidate));
2407 return keyword_candidate;
2410 bool TemplateURLService::IsLocalTemplateURLBetter(
2411 const TemplateURL* local_turl,
2412 const TemplateURL* sync_turl) {
2413 DCHECK(GetTemplateURLForGUID(local_turl->sync_guid()));
2414 return local_turl->last_modified() > sync_turl->last_modified() ||
2415 local_turl->created_by_policy() ||
2416 local_turl== GetDefaultSearchProvider();
2419 void TemplateURLService::ResolveSyncKeywordConflict(
2420 TemplateURL* unapplied_sync_turl,
2421 TemplateURL* applied_sync_turl,
2422 syncer::SyncChangeList* change_list) {
2423 DCHECK(loaded_);
2424 DCHECK(unapplied_sync_turl);
2425 DCHECK(applied_sync_turl);
2426 DCHECK(change_list);
2427 DCHECK_EQ(applied_sync_turl->keyword(), unapplied_sync_turl->keyword());
2428 DCHECK_NE(TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION,
2429 applied_sync_turl->GetType());
2431 // Both |unapplied_sync_turl| and |applied_sync_turl| are known to Sync, so
2432 // don't delete either of them. Instead, determine which is "better" and
2433 // uniquify the other one, sending an update to the server for the updated
2434 // entry.
2435 const bool applied_turl_is_better =
2436 IsLocalTemplateURLBetter(applied_sync_turl, unapplied_sync_turl);
2437 TemplateURL* loser = applied_turl_is_better ?
2438 unapplied_sync_turl : applied_sync_turl;
2439 base::string16 new_keyword = UniquifyKeyword(*loser, false);
2440 DCHECK(!GetTemplateURLForKeyword(new_keyword));
2441 if (applied_turl_is_better) {
2442 // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2443 // for adding or updating unapplied_sync_turl in the local model.
2444 unapplied_sync_turl->data_.SetKeyword(new_keyword);
2445 } else {
2446 // Update |applied_sync_turl| in the local model with the new keyword.
2447 TemplateURLData data(applied_sync_turl->data());
2448 data.SetKeyword(new_keyword);
2449 TemplateURL new_turl(applied_sync_turl->profile(), data);
2450 UIThreadSearchTermsData search_terms_data(applied_sync_turl->profile());
2451 if (UpdateNoNotify(applied_sync_turl, new_turl, search_terms_data))
2452 NotifyObservers();
2454 // The losing TemplateURL should have their keyword updated. Send a change to
2455 // the server to reflect this change.
2456 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*loser);
2457 change_list->push_back(syncer::SyncChange(FROM_HERE,
2458 syncer::SyncChange::ACTION_UPDATE,
2459 sync_data));
2462 void TemplateURLService::MergeInSyncTemplateURL(
2463 TemplateURL* sync_turl,
2464 const SyncDataMap& sync_data,
2465 syncer::SyncChangeList* change_list,
2466 SyncDataMap* local_data,
2467 syncer::SyncMergeResult* merge_result) {
2468 DCHECK(sync_turl);
2469 DCHECK(!GetTemplateURLForGUID(sync_turl->sync_guid()));
2470 DCHECK(IsFromSync(sync_turl, sync_data));
2472 TemplateURL* conflicting_turl =
2473 FindNonExtensionTemplateURLForKeyword(sync_turl->keyword());
2474 bool should_add_sync_turl = true;
2476 // If there was no TemplateURL in the local model that conflicts with
2477 // |sync_turl|, skip the following preparation steps and just add |sync_turl|
2478 // directly. Otherwise, modify |conflicting_turl| to make room for
2479 // |sync_turl|.
2480 if (conflicting_turl) {
2481 if (IsFromSync(conflicting_turl, sync_data)) {
2482 // |conflicting_turl| is already known to Sync, so we're not allowed to
2483 // remove it. In this case, we want to uniquify the worse one and send an
2484 // update for the changed keyword to sync. We can reuse the logic from
2485 // ResolveSyncKeywordConflict for this.
2486 ResolveSyncKeywordConflict(sync_turl, conflicting_turl, change_list);
2487 merge_result->set_num_items_modified(
2488 merge_result->num_items_modified() + 1);
2489 } else {
2490 // |conflicting_turl| is not yet known to Sync. If it is better, then we
2491 // want to transfer its values up to sync. Otherwise, we remove it and
2492 // allow the entry from Sync to overtake it in the model.
2493 const std::string guid = conflicting_turl->sync_guid();
2494 if (IsLocalTemplateURLBetter(conflicting_turl, sync_turl)) {
2495 ResetTemplateURLGUID(conflicting_turl, sync_turl->sync_guid());
2496 syncer::SyncData sync_data =
2497 CreateSyncDataFromTemplateURL(*conflicting_turl);
2498 change_list->push_back(syncer::SyncChange(
2499 FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
2500 if (conflicting_turl == GetDefaultSearchProvider() &&
2501 !pending_synced_default_search_) {
2502 // If we're not waiting for the Synced default to come in, we should
2503 // override the pref with our new GUID. If we are waiting for the
2504 // arrival of a synced default, setting the pref here would cause us
2505 // to lose the GUID we are waiting on.
2506 PrefService* prefs = GetPrefs();
2507 if (prefs) {
2508 prefs->SetString(prefs::kSyncedDefaultSearchProviderGUID,
2509 conflicting_turl->sync_guid());
2512 // Note that in this case we do not add the Sync TemplateURL to the
2513 // local model, since we've effectively "merged" it in by updating the
2514 // local conflicting entry with its sync_guid.
2515 should_add_sync_turl = false;
2516 merge_result->set_num_items_modified(
2517 merge_result->num_items_modified() + 1);
2518 } else {
2519 // We guarantee that this isn't the local search provider. Otherwise,
2520 // local would have won.
2521 DCHECK(conflicting_turl != GetDefaultSearchProvider());
2522 Remove(conflicting_turl);
2523 merge_result->set_num_items_deleted(
2524 merge_result->num_items_deleted() + 1);
2526 // This TemplateURL was either removed or overwritten in the local model.
2527 // Remove the entry from the local data so it isn't pushed up to Sync.
2528 local_data->erase(guid);
2532 if (should_add_sync_turl) {
2533 // Force the local ID to kInvalidTemplateURLID so we can add it.
2534 TemplateURLData data(sync_turl->data());
2535 data.id = kInvalidTemplateURLID;
2536 Add(new TemplateURL(profile_, data));
2537 merge_result->set_num_items_added(
2538 merge_result->num_items_added() + 1);
2542 void TemplateURLService::SetDefaultSearchProviderIfNewlySynced(
2543 const std::string& guid) {
2544 // If we're not syncing or if default search is managed by policy, ignore.
2545 if (!sync_processor_.get() || is_default_search_managed_)
2546 return;
2548 PrefService* prefs = GetPrefs();
2549 if (prefs && pending_synced_default_search_ &&
2550 prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID) == guid) {
2551 // Make sure this actually exists. We should not be calling this unless we
2552 // really just added this TemplateURL.
2553 TemplateURL* turl_from_sync = GetTemplateURLForGUID(guid);
2554 if (turl_from_sync && turl_from_sync->SupportsReplacement()) {
2555 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2556 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
2557 SetDefaultSearchProvider(turl_from_sync);
2559 pending_synced_default_search_ = false;
2563 TemplateURL* TemplateURLService::GetPendingSyncedDefaultSearchProvider() {
2564 PrefService* prefs = GetPrefs();
2565 if (!prefs || !pending_synced_default_search_)
2566 return NULL;
2568 // Could be NULL if no such thing exists.
2569 return GetTemplateURLForGUID(
2570 prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID));
2573 void TemplateURLService::PatchMissingSyncGUIDs(
2574 TemplateURLVector* template_urls) {
2575 DCHECK(template_urls);
2576 for (TemplateURLVector::iterator i = template_urls->begin();
2577 i != template_urls->end(); ++i) {
2578 TemplateURL* template_url = *i;
2579 DCHECK(template_url);
2580 if (template_url->sync_guid().empty() &&
2581 (template_url->GetType() !=
2582 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)) {
2583 template_url->data_.sync_guid = base::GenerateGUID();
2584 if (service_.get())
2585 service_->UpdateKeyword(template_url->data());
2590 void TemplateURLService::AddTemplateURLsAndSetupDefaultEngine(
2591 TemplateURLVector* template_urls,
2592 TemplateURL* default_search_provider) {
2593 DCHECK(template_urls);
2594 is_default_search_managed_ = false;
2595 bool database_specified_a_default = (default_search_provider != NULL);
2597 // Check if default search provider is now managed.
2598 scoped_ptr<TemplateURLData> default_from_prefs;
2599 LoadDefaultSearchProviderFromPrefs(&default_from_prefs,
2600 &is_default_search_managed_);
2602 // Remove entries that were created because of policy as they may have
2603 // changed since the database was saved.
2604 RemoveProvidersCreatedByPolicy(template_urls,
2605 &default_search_provider,
2606 default_from_prefs.get());
2608 PatchMissingSyncGUIDs(template_urls);
2610 if (is_default_search_managed_) {
2611 SetTemplateURLs(template_urls);
2613 if (TemplateURLMatchesData(default_search_provider,
2614 default_from_prefs.get())) {
2615 // The value from the preferences was previously stored in the database.
2616 // Reuse it.
2617 } else {
2618 // The value from the preferences takes over.
2619 default_search_provider = NULL;
2620 if (default_from_prefs) {
2621 default_from_prefs->created_by_policy = true;
2622 default_from_prefs->id = kInvalidTemplateURLID;
2623 default_search_provider =
2624 new TemplateURL(profile_, *default_from_prefs);
2625 if (!AddNoNotify(default_search_provider, true))
2626 default_search_provider = NULL;
2629 // Note that this saves the default search provider to prefs.
2630 if (!default_search_provider ||
2631 ((default_search_provider->GetType() !=
2632 TemplateURL::OMNIBOX_API_EXTENSION) &&
2633 default_search_provider->SupportsReplacement())) {
2634 bool success = SetDefaultSearchProviderNoNotify(default_search_provider);
2635 DCHECK(success);
2637 } else {
2638 // If we had a managed default, replace it with the synced default if
2639 // applicable, or the first provider of the list.
2640 TemplateURL* synced_default = GetPendingSyncedDefaultSearchProvider();
2641 if (synced_default) {
2642 default_search_provider = synced_default;
2643 pending_synced_default_search_ = false;
2644 } else if (database_specified_a_default &&
2645 default_search_provider == NULL) {
2646 UMA_HISTOGRAM_ENUMERATION(kFirstPotentialEngineHistogramName,
2647 FIRST_POTENTIAL_CALLSITE_ON_LOAD,
2648 FIRST_POTENTIAL_CALLSITE_MAX);
2649 default_search_provider = FirstPotentialDefaultEngine(*template_urls);
2652 // If the default search provider existed previously, then just
2653 // set the member variable. Otherwise, we'll set it using the method
2654 // to ensure that it is saved properly after its id is set.
2655 if (default_search_provider &&
2656 (default_search_provider->id() != kInvalidTemplateURLID)) {
2657 default_search_provider_ = default_search_provider;
2658 default_search_provider = NULL;
2660 SetTemplateURLs(template_urls);
2662 if (default_search_provider) {
2663 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2664 &dsp_change_origin_, default_from_prefs ?
2665 dsp_change_origin_ : DSP_CHANGE_NEW_ENGINE_NO_PREFS);
2666 // Note that this saves the default search provider to prefs.
2667 SetDefaultSearchProvider(default_search_provider);
2668 } else {
2669 // Always save the default search provider to prefs. That way we don't
2670 // have to worry about it being out of sync.
2671 if (default_search_provider_)
2672 SaveDefaultSearchProviderToPrefs(default_search_provider_);
2677 void TemplateURLService::EnsureDefaultSearchProviderExists() {
2678 if (!is_default_search_managed()) {
2679 bool has_default_search_provider = default_search_provider_ &&
2680 default_search_provider_->SupportsReplacement();
2681 UMA_HISTOGRAM_BOOLEAN("Search.HasDefaultSearchProvider",
2682 has_default_search_provider);
2683 // Ensure that default search provider exists. See http://crbug.com/116952.
2684 if (!has_default_search_provider) {
2685 bool success =
2686 SetDefaultSearchProviderNoNotify(FindNewDefaultSearchProvider());
2687 DCHECK(success);
2689 // Don't log anything if the user has a NULL default search provider.
2690 if (default_search_provider_) {
2691 UMA_HISTOGRAM_ENUMERATION("Search.DefaultSearchProviderType",
2692 TemplateURLPrepopulateData::GetEngineType(*default_search_provider_),
2693 SEARCH_ENGINE_MAX);
2698 TemplateURL* TemplateURLService::CreateTemplateURLForExtension(
2699 const ExtensionKeyword& extension_keyword) const {
2700 TemplateURLData data;
2701 data.short_name = base::UTF8ToUTF16(extension_keyword.extension_name);
2702 data.SetKeyword(base::UTF8ToUTF16(extension_keyword.extension_keyword));
2703 // This URL is not actually used for navigation. It holds the extension's
2704 // ID, as well as forcing the TemplateURL to be treated as a search keyword.
2705 data.SetURL(std::string(extensions::kExtensionScheme) + "://" +
2706 extension_keyword.extension_id + "/?q={searchTerms}");
2707 return new TemplateURL(profile_, data);
2710 TemplateURL* TemplateURLService::FindTemplateURLForExtension(
2711 const std::string& extension_id,
2712 TemplateURL::Type type) const {
2713 DCHECK_NE(TemplateURL::NORMAL, type);
2714 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2715 i != template_urls_.end(); ++i) {
2716 if ((*i)->GetType() == type &&
2717 (*i)->GetExtensionId() == extension_id)
2718 return *i;
2721 return NULL;
2724 TemplateURL* TemplateURLService::FindExtensionDefaultSearchEngine() const {
2725 TemplateURL* most_recently_intalled_default = NULL;
2726 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2727 i != template_urls_.end(); ++i) {
2728 if (((*i)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) &&
2729 (*i)->extension_info_->wants_to_be_default_engine &&
2730 (*i)->SupportsReplacement() &&
2731 (!most_recently_intalled_default ||
2732 (most_recently_intalled_default->extension_info_->install_time <
2733 (*i)->extension_info_->install_time)))
2734 most_recently_intalled_default = *i;
2737 return most_recently_intalled_default;
2740 void TemplateURLService::
2741 SetDefaultSearchProviderAfterRemovingDefaultExtension() {
2742 DCHECK(!is_default_search_managed());
2743 TemplateURL* new_dse = FindExtensionDefaultSearchEngine();
2744 if (!new_dse) {
2745 scoped_ptr<TemplateURLData> default_provider;
2746 bool is_managed;
2747 if (LoadDefaultSearchProviderFromPrefs(&default_provider, &is_managed) &&
2748 default_provider) {
2749 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2750 i != template_urls_.end(); ++i) {
2751 if ((*i)->id() == default_provider->id) {
2752 new_dse = *i;
2753 break;
2758 if (!new_dse)
2759 new_dse = FindNewDefaultSearchProvider();
2760 SetDefaultSearchProviderNoNotify(new_dse);