bfdfe1c857a64562524dccd8be6e2a59c008d4f7
[platform/framework/web/crosswalk.git] / src / chrome / browser / search_engines / template_url_service.cc
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.
4
5 #include "chrome/browser/search_engines/template_url_service.h"
6
7 #include <algorithm>
8 #include <utility>
9
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"
54
55 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet;
56 typedef TemplateURLService::SyncDataMap SyncDataMap;
57
58 namespace {
59
60 bool TemplateURLsHaveSamePrefs(const TemplateURL* url1,
61                                const TemplateURL* url2) {
62   if (url1 == url2)
63     return true;
64   return (url1 != NULL) && (url2 != NULL) &&
65       (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());
84 }
85
86 const char kFirstPotentialEngineHistogramName[] =
87     "Search.FirstPotentialEngineCalled";
88
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,
98 };
99
100 const char kDeleteSyncedEngineHistogramName[] =
101     "Search.DeleteSyncedSearchEngine";
102
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,
110 };
111
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;
119   }
120   return NULL;
121 }
122
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;
156     }
157   }
158   return false;
159 }
160
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;
173   }
174 }
175
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();
183
184   virtual std::string GoogleBaseURLValue() const OVERRIDE;
185
186  private:
187   std::string old_base_url;
188 };
189
190 OldBaseURLSearchTermsData::OldBaseURLSearchTermsData(
191     Profile* profile,
192     const std::string& old_base_url)
193     : UIThreadSearchTermsData(profile),
194       old_base_url(old_base_url) {
195 }
196
197 OldBaseURLSearchTermsData::~OldBaseURLSearchTermsData() {
198 }
199
200 std::string OldBaseURLSearchTermsData::GoogleBaseURLValue() const {
201   return old_base_url;
202 }
203
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());
210 }
211
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]++;
222   }
223
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++;
230   }
231
232   UMA_HISTOGRAM_COUNTS_100("Search.SearchEngineDuplicateCounts", num_dupes);
233 }
234
235 }  // namespace
236
237
238 // TemplateURLService::ExtensionKeyword ---------------------------------------
239
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) {
247 }
248
249 TemplateURLService::ExtensionKeyword::~ExtensionKeyword() {}
250
251
252 // TemplateURLService::LessWithPrefix -----------------------------------------
253
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).
264   //
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);
273   }
274 };
275
276
277 // TemplateURLService ---------------------------------------------------------
278
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   DCHECK(profile_);
294   Init(NULL, 0);
295 }
296
297 TemplateURLService::TemplateURLService(const Initializer* initializers,
298                                        const int count)
299     : provider_map_(new SearchHostToURLsMap),
300       profile_(NULL),
301       loaded_(false),
302       load_failed_(false),
303       load_handle_(0),
304       service_(NULL),
305       default_search_provider_(NULL),
306       is_default_search_managed_(false),
307       next_id_(kInvalidTemplateURLID + 1),
308       time_provider_(&base::Time::Now),
309       models_associated_(false),
310       processing_syncer_changes_(false),
311       pending_synced_default_search_(false),
312       dsp_change_origin_(DSP_CHANGE_OTHER) {
313   Init(initializers, count);
314 }
315
316 TemplateURLService::~TemplateURLService() {
317   // |service_| should be deleted during Shutdown().
318   DCHECK(!service_);
319   STLDeleteElements(&template_urls_);
320 }
321
322 // static
323 base::string16 TemplateURLService::GenerateKeyword(const GURL& url) {
324   DCHECK(url.is_valid());
325   // Strip "www." off the front of the keyword; otherwise the keyword won't work
326   // properly.  See http://code.google.com/p/chromium/issues/detail?id=6984 .
327   // Special case: if the host was exactly "www." (not sure this can happen but
328   // perhaps with some weird intranet and custom DNS server?), ensure we at
329   // least don't return the empty string.
330   base::string16 keyword(net::StripWWWFromHost(url));
331   return keyword.empty() ? base::ASCIIToUTF16("www") : keyword;
332 }
333
334 // static
335 base::string16 TemplateURLService::CleanUserInputKeyword(
336     const base::string16& keyword) {
337   // Remove the scheme.
338   base::string16 result(base::i18n::ToLower(keyword));
339   base::TrimWhitespace(result, base::TRIM_ALL, &result);
340   url_parse::Component scheme_component;
341   if (url_parse::ExtractScheme(base::UTF16ToUTF8(keyword).c_str(),
342                                static_cast<int>(keyword.length()),
343                                &scheme_component)) {
344     // If the scheme isn't "http" or "https", bail.  The user isn't trying to
345     // type a web address, but rather an FTP, file:, or other scheme URL, or a
346     // search query with some sort of initial operator (e.g. "site:").
347     if (result.compare(0, scheme_component.end(),
348                        base::ASCIIToUTF16(content::kHttpScheme)) &&
349         result.compare(0, scheme_component.end(),
350                        base::ASCIIToUTF16(content::kHttpsScheme)))
351       return base::string16();
352
353     // Include trailing ':'.
354     result.erase(0, scheme_component.end() + 1);
355     // Many schemes usually have "//" after them, so strip it too.
356     const base::string16 after_scheme(base::ASCIIToUTF16("//"));
357     if (result.compare(0, after_scheme.length(), after_scheme) == 0)
358       result.erase(0, after_scheme.length());
359   }
360
361   // Remove leading "www.".
362   result = net::StripWWW(result);
363
364   // Remove trailing "/".
365   return (result.length() > 0 && result[result.length() - 1] == '/') ?
366       result.substr(0, result.length() - 1) : result;
367 }
368
369 // static
370 GURL TemplateURLService::GenerateSearchURL(TemplateURL* t_url) {
371   DCHECK(t_url);
372   UIThreadSearchTermsData search_terms_data(t_url->profile());
373   return GenerateSearchURLUsingTermsData(t_url, search_terms_data);
374 }
375
376 // static
377 GURL TemplateURLService::GenerateSearchURLUsingTermsData(
378     const TemplateURL* t_url,
379     const SearchTermsData& search_terms_data) {
380   DCHECK(t_url);
381
382   const TemplateURLRef& search_ref = t_url->url_ref();
383   if (!search_ref.IsValidUsingTermsData(search_terms_data))
384     return GURL();
385
386   if (!search_ref.SupportsReplacementUsingTermsData(search_terms_data))
387     return GURL(t_url->url());
388
389   // Use something obscure for the search terms argument so that in the rare
390   // case the term replaces the URL it's unlikely another keyword would have the
391   // same url.
392   // TODO(jnd): Add additional parameters to get post data when the search URL
393   // has post parameters.
394   return GURL(search_ref.ReplaceSearchTermsUsingTermsData(
395       TemplateURLRef::SearchTermsArgs(
396           base::ASCIIToUTF16("blah.blah.blah.blah.blah")),
397       search_terms_data, NULL));
398 }
399
400 bool TemplateURLService::CanReplaceKeyword(
401     const base::string16& keyword,
402     const GURL& url,
403     TemplateURL** template_url_to_replace) {
404   DCHECK(!keyword.empty());  // This should only be called for non-empty
405                              // keywords. If we need to support empty kewords
406                              // the code needs to change slightly.
407   TemplateURL* existing_url = GetTemplateURLForKeyword(keyword);
408   if (template_url_to_replace)
409     *template_url_to_replace = existing_url;
410   if (existing_url) {
411     // We already have a TemplateURL for this keyword. Only allow it to be
412     // replaced if the TemplateURL can be replaced.
413     return CanReplace(existing_url);
414   }
415
416   // We don't have a TemplateURL with keyword. Only allow a new one if there
417   // isn't a TemplateURL for the specified host, or there is one but it can
418   // be replaced. We do this to ensure that if the user assigns a different
419   // keyword to a generated TemplateURL, we won't regenerate another keyword for
420   // the same host.
421   return !url.is_valid() || url.host().empty() ||
422       CanReplaceKeywordForHost(url.host(), template_url_to_replace);
423 }
424
425 void TemplateURLService::FindMatchingKeywords(
426     const base::string16& prefix,
427     bool support_replacement_only,
428     TemplateURLVector* matches) const {
429   // Sanity check args.
430   if (prefix.empty())
431     return;
432   DCHECK(matches != NULL);
433   DCHECK(matches->empty());  // The code for exact matches assumes this.
434
435   // Required for VS2010: http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
436   TemplateURL* const kNullTemplateURL = NULL;
437
438   // Find matching keyword range.  Searches the element map for keywords
439   // beginning with |prefix| and stores the endpoints of the resulting set in
440   // |match_range|.
441   const std::pair<KeywordToTemplateMap::const_iterator,
442                   KeywordToTemplateMap::const_iterator> match_range(
443       std::equal_range(
444           keyword_to_template_map_.begin(), keyword_to_template_map_.end(),
445           KeywordToTemplateMap::value_type(prefix, kNullTemplateURL),
446           LessWithPrefix()));
447
448   // Return vector of matching keywords.
449   for (KeywordToTemplateMap::const_iterator i(match_range.first);
450        i != match_range.second; ++i) {
451     if (!support_replacement_only || i->second->url_ref().SupportsReplacement())
452       matches->push_back(i->second);
453   }
454 }
455
456 TemplateURL* TemplateURLService::GetTemplateURLForKeyword(
457     const base::string16& keyword) {
458   KeywordToTemplateMap::const_iterator elem(
459       keyword_to_template_map_.find(keyword));
460   if (elem != keyword_to_template_map_.end())
461     return elem->second;
462   return ((!loaded_ || load_failed_) &&
463       initial_default_search_provider_.get() &&
464       (initial_default_search_provider_->keyword() == keyword)) ?
465       initial_default_search_provider_.get() : NULL;
466 }
467
468 TemplateURL* TemplateURLService::GetTemplateURLForGUID(
469     const std::string& sync_guid) {
470   GUIDToTemplateMap::const_iterator elem(guid_to_template_map_.find(sync_guid));
471   if (elem != guid_to_template_map_.end())
472     return elem->second;
473   return ((!loaded_ || load_failed_) &&
474       initial_default_search_provider_.get() &&
475       (initial_default_search_provider_->sync_guid() == sync_guid)) ?
476       initial_default_search_provider_.get() : NULL;
477 }
478
479 TemplateURL* TemplateURLService::GetTemplateURLForHost(
480     const std::string& host) {
481   if (loaded_) {
482     TemplateURL* t_url = provider_map_->GetTemplateURLForHost(host);
483     if (t_url)
484       return t_url;
485   }
486   return ((!loaded_ || load_failed_) &&
487       initial_default_search_provider_.get() &&
488       (GenerateSearchURL(initial_default_search_provider_.get()).host() ==
489           host)) ? initial_default_search_provider_.get() : NULL;
490 }
491
492 void TemplateURLService::Add(TemplateURL* template_url) {
493   if (AddNoNotify(template_url, true))
494     NotifyObservers();
495 }
496
497 void TemplateURLService::AddAndSetProfile(TemplateURL* template_url,
498                                           Profile* profile) {
499   template_url->profile_ = profile;
500   Add(template_url);
501 }
502
503 void TemplateURLService::AddWithOverrides(TemplateURL* template_url,
504                                           const base::string16& short_name,
505                                           const base::string16& keyword,
506                                           const std::string& url) {
507   DCHECK(!keyword.empty());
508   DCHECK(!url.empty());
509   template_url->data_.short_name = short_name;
510   template_url->data_.SetKeyword(keyword);
511   template_url->SetURL(url);
512   Add(template_url);
513 }
514
515 void TemplateURLService::AddExtensionControlledTURL(
516     TemplateURL* template_url,
517     scoped_ptr<AssociatedExtensionInfo> info) {
518   DCHECK(loaded_);
519   DCHECK(template_url);
520   DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
521   DCHECK(info);
522   template_url->extension_info_.swap(info);
523   DCHECK(!FindTemplateURLForExtension(
524       template_url->GetExtensionId(),
525       TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION));
526
527   if (AddNoNotify(template_url, true)) {
528     // Note that we can't call CanMakeDefault() here, since it would return
529     // false when another extension is already controlling the default search
530     // engine, and we want to allow new extensions to take over.
531     if (template_url->extension_info_->wants_to_be_default_engine &&
532         !is_default_search_managed()) {
533       TemplateURL* default_candidate = FindExtensionDefaultSearchEngine();
534       if (default_candidate == template_url) {
535         base::AutoReset<DefaultSearchChangeOrigin> change_origin(
536             &dsp_change_origin_, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION);
537         SetDefaultSearchProviderNoNotify(template_url);
538       }
539     }
540     NotifyObservers();
541   }
542 }
543
544 void TemplateURLService::Remove(TemplateURL* template_url) {
545   RemoveNoNotify(template_url);
546   NotifyObservers();
547 }
548
549 void TemplateURLService::RemoveExtensionControlledTURL(
550     const std::string& extension_id) {
551   DCHECK(loaded_);
552   TemplateURL* url = FindTemplateURLForExtension(
553       extension_id, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
554   if (!url)
555     return;
556   bool restore_dse = (url == GetDefaultSearchProvider());
557   if (restore_dse) {
558     DCHECK(!is_default_search_managed());
559     default_search_provider_ = NULL;
560   }
561   RemoveNoNotify(url);
562   if (restore_dse)
563     SetDefaultSearchProviderAfterRemovingDefaultExtension();
564   NotifyObservers();
565 }
566
567 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after) {
568   RemoveAutoGeneratedBetween(created_after, base::Time());
569 }
570
571 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after,
572                                                     base::Time created_before) {
573   RemoveAutoGeneratedForOriginBetween(GURL(), created_after, created_before);
574 }
575
576 void TemplateURLService::RemoveAutoGeneratedForOriginBetween(
577     const GURL& origin,
578     base::Time created_after,
579     base::Time created_before) {
580   GURL o(origin.GetOrigin());
581   bool should_notify = false;
582   for (size_t i = 0; i < template_urls_.size();) {
583     if (template_urls_[i]->date_created() >= created_after &&
584         (created_before.is_null() ||
585          template_urls_[i]->date_created() < created_before) &&
586         CanReplace(template_urls_[i]) &&
587         (o.is_empty() ||
588          GenerateSearchURL(template_urls_[i]).GetOrigin() == o)) {
589       RemoveNoNotify(template_urls_[i]);
590       should_notify = true;
591     } else {
592       ++i;
593     }
594   }
595   if (should_notify)
596     NotifyObservers();
597 }
598
599
600 void TemplateURLService::RegisterOmniboxKeyword(
601     const std::string& extension_id,
602     const std::string& extension_name,
603     const std::string& keyword) {
604   DCHECK(loaded_);
605
606   if (!FindTemplateURLForExtension(extension_id,
607                                    TemplateURL::OMNIBOX_API_EXTENSION)) {
608     ExtensionKeyword extension_url(extension_id, extension_name, keyword);
609     Add(CreateTemplateURLForExtension(extension_url));
610   }
611 }
612
613 void TemplateURLService::UnregisterOmniboxKeyword(
614     const std::string& extension_id) {
615   DCHECK(loaded_);
616   TemplateURL* url = FindTemplateURLForExtension(
617       extension_id, TemplateURL::OMNIBOX_API_EXTENSION);
618   if (url)
619     Remove(url);
620 }
621
622 TemplateURLService::TemplateURLVector TemplateURLService::GetTemplateURLs() {
623   return template_urls_;
624 }
625
626 void TemplateURLService::IncrementUsageCount(TemplateURL* url) {
627   DCHECK(url);
628   // Extension-controlled search engines are not persisted.
629   if (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
630     return;
631   if (std::find(template_urls_.begin(), template_urls_.end(), url) ==
632       template_urls_.end())
633     return;
634   ++url->data_.usage_count;
635
636   if (service_.get())
637     service_.get()->UpdateKeyword(url->data());
638 }
639
640 void TemplateURLService::ResetTemplateURL(TemplateURL* url,
641                                           const base::string16& title,
642                                           const base::string16& keyword,
643                                           const std::string& search_url) {
644   if (!loaded_)
645     return;
646   DCHECK(!keyword.empty());
647   DCHECK(!search_url.empty());
648   TemplateURLData data(url->data());
649   data.short_name = title;
650   data.SetKeyword(keyword);
651   if (search_url != data.url()) {
652     data.SetURL(search_url);
653     // The urls have changed, reset the favicon url.
654     data.favicon_url = GURL();
655   }
656   data.safe_for_autoreplace = false;
657   data.last_modified = time_provider_();
658   TemplateURL new_url(url->profile(), data);
659   UIThreadSearchTermsData search_terms_data(url->profile());
660   if (UpdateNoNotify(url, new_url, search_terms_data))
661     NotifyObservers();
662 }
663
664 bool TemplateURLService::CanMakeDefault(const TemplateURL* url) {
665   return  !is_default_search_managed() &&
666       !IsExtensionControlledDefaultSearch() &&
667       (url != GetDefaultSearchProvider()) &&
668       url->url_ref().SupportsReplacement() &&
669       (url->GetType() == TemplateURL::NORMAL);
670 }
671
672 void TemplateURLService::SetDefaultSearchProvider(TemplateURL* url) {
673   DCHECK(!is_default_search_managed_);
674   // Omnibox keywords cannot be made default. Extension-controlled search
675   // engines can be made default only by the extension itself because they
676   // aren't persisted.
677   DCHECK(!url || (url->GetType() == TemplateURL::NORMAL));
678
679   // Always persist the setting in the database, that way if the backup
680   // signature has changed out from under us it gets reset correctly.
681   if (SetDefaultSearchProviderNoNotify(url))
682     NotifyObservers();
683 }
684
685 TemplateURL* TemplateURLService::GetDefaultSearchProvider() {
686   if (loaded_ && !load_failed_)
687     return default_search_provider_;
688   // We're not loaded, rely on the default search provider stored in prefs.
689   return initial_default_search_provider_.get();
690 }
691
692 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
693     const GURL& url) {
694   TemplateURL* default_provider = GetDefaultSearchProvider();
695   return default_provider && default_provider->IsSearchURL(url);
696 }
697
698 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
699   const TemplateURL* default_provider = GetDefaultSearchProvider();
700   return default_provider && (default_provider->GetType() ==
701       TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
702 }
703
704 TemplateURL* TemplateURLService::FindNewDefaultSearchProvider() {
705   // See if the prepopulated default still exists.
706   scoped_ptr<TemplateURL> prepopulated_default(
707       TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(profile_));
708   for (TemplateURLVector::iterator i = template_urls_.begin();
709        i != template_urls_.end(); ++i) {
710     if ((*i)->prepopulate_id() == prepopulated_default->prepopulate_id())
711       return *i;
712   }
713   // If not, use the first non-extension keyword of the templates that supports
714   // search term replacement.
715   if (processing_syncer_changes_) {
716     UMA_HISTOGRAM_ENUMERATION(
717         kFirstPotentialEngineHistogramName,
718         FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_PROCESSING_SYNC_CHANGES,
719         FIRST_POTENTIAL_CALLSITE_MAX);
720   } else {
721     if (sync_processor_.get()) {
722       // We're not currently in a sync cycle, but we're syncing.
723       UMA_HISTOGRAM_ENUMERATION(kFirstPotentialEngineHistogramName,
724                                 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_SYNCING,
725                                 FIRST_POTENTIAL_CALLSITE_MAX);
726     } else {
727       // We're not syncing at all.
728       UMA_HISTOGRAM_ENUMERATION(
729           kFirstPotentialEngineHistogramName,
730           FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_NOT_SYNCING,
731           FIRST_POTENTIAL_CALLSITE_MAX);
732     }
733   }
734   return FirstPotentialDefaultEngine(template_urls_);
735 }
736
737 void TemplateURLService::RepairPrepopulatedSearchEngines() {
738   // Can't clean DB if it hasn't been loaded.
739   DCHECK(loaded());
740
741   size_t default_search_provider_index = 0;
742   ScopedVector<TemplateURL> prepopulated_urls =
743       TemplateURLPrepopulateData::GetPrepopulatedEngines(
744           profile_, &default_search_provider_index);
745   DCHECK(!prepopulated_urls.empty());
746   int default_search_engine_id =
747       prepopulated_urls[default_search_provider_index]->prepopulate_id();
748   TemplateURL* current_dse = default_search_provider_;
749   ActionsFromPrepopulateData actions(CreateActionsFromCurrentPrepopulateData(
750       &prepopulated_urls, template_urls_, current_dse));
751   // Remove items.
752   for (std::vector<TemplateURL*>::iterator i = actions.removed_engines.begin();
753        i < actions.removed_engines.end(); ++i)
754     RemoveNoNotify(*i);
755
756   // Edit items.
757   for (EditedEngines::iterator i(actions.edited_engines.begin());
758        i < actions.edited_engines.end(); ++i) {
759     UIThreadSearchTermsData search_terms_data(profile());
760     TemplateURL new_values(profile(), i->second);
761     UpdateNoNotify(i->first, new_values, search_terms_data);
762   }
763
764   // Add items.
765   for (std::vector<TemplateURL*>::iterator i = actions.added_engines.begin();
766        i < actions.added_engines.end(); ++i)
767     AddNoNotify(*i, true);
768
769   // Change the DSE.
770   TemplateURL* new_dse = FindURLByPrepopulateID(template_urls_,
771                                                 default_search_engine_id);
772   DCHECK(new_dse);
773   if (CanMakeDefault(new_dse)) {
774     base::AutoReset<DefaultSearchChangeOrigin> change_origin(
775         &dsp_change_origin_, DSP_CHANGE_PROFILE_RESET);
776     SetDefaultSearchProviderNoNotify(new_dse);
777   }
778   NotifyObservers();
779 }
780
781 void TemplateURLService::AddObserver(TemplateURLServiceObserver* observer) {
782   model_observers_.AddObserver(observer);
783 }
784
785 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver* observer) {
786   model_observers_.RemoveObserver(observer);
787 }
788
789 void TemplateURLService::Load() {
790   if (loaded_ || load_handle_)
791     return;
792
793   if (!service_.get()) {
794     service_ = WebDataService::FromBrowserContext(profile_);
795   }
796
797   if (service_.get()) {
798     load_handle_ = service_->GetKeywords(this);
799   } else {
800     ChangeToLoadedState();
801     on_loaded_callbacks_.Notify();
802   }
803 }
804
805 scoped_ptr<TemplateURLService::Subscription>
806     TemplateURLService::RegisterOnLoadedCallback(
807         const base::Closure& callback) {
808   return loaded_ ?
809       scoped_ptr<TemplateURLService::Subscription>() :
810       on_loaded_callbacks_.Add(callback);
811 }
812
813 void TemplateURLService::OnWebDataServiceRequestDone(
814     WebDataService::Handle h,
815     const WDTypedResult* result) {
816   // Reset the load_handle so that we don't try and cancel the load in
817   // the destructor.
818   load_handle_ = 0;
819
820   if (!result) {
821     // Results are null if the database went away or (most likely) wasn't
822     // loaded.
823     load_failed_ = true;
824     ChangeToLoadedState();
825     on_loaded_callbacks_.Notify();
826     return;
827   }
828
829   // initial_default_search_provider_ is only needed before we've finished
830   // loading. Now that we've loaded we can nuke it.
831   initial_default_search_provider_.reset();
832
833   TemplateURLVector template_urls;
834   TemplateURL* default_search_provider = NULL;
835   int new_resource_keyword_version = 0;
836   GetSearchProvidersUsingKeywordResult(*result, service_.get(), profile_,
837       &template_urls, &default_search_provider, &new_resource_keyword_version,
838       &pre_sync_deletes_);
839
840   AddTemplateURLsAndSetupDefaultEngine(&template_urls, default_search_provider);
841
842   // This initializes provider_map_ which should be done before
843   // calling UpdateKeywordSearchTermsForURL.
844   ChangeToLoadedState();
845
846   // Index any visits that occurred before we finished loading.
847   for (size_t i = 0; i < visits_to_add_.size(); ++i)
848     UpdateKeywordSearchTermsForURL(visits_to_add_[i]);
849   visits_to_add_.clear();
850
851   if (new_resource_keyword_version)
852     service_->SetBuiltinKeywordVersion(new_resource_keyword_version);
853
854   EnsureDefaultSearchProviderExists();
855
856   NotifyObservers();
857   on_loaded_callbacks_.Notify();
858 }
859
860 base::string16 TemplateURLService::GetKeywordShortName(
861     const base::string16& keyword,
862     bool* is_omnibox_api_extension_keyword) {
863   const TemplateURL* template_url = GetTemplateURLForKeyword(keyword);
864
865   // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
866   // to track changes to the model, this should become a DCHECK.
867   if (template_url) {
868     *is_omnibox_api_extension_keyword =
869         template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
870     return template_url->AdjustedShortNameForLocaleDirection();
871   }
872   *is_omnibox_api_extension_keyword = false;
873   return base::string16();
874 }
875
876 void TemplateURLService::Observe(int type,
877                                  const content::NotificationSource& source,
878                                  const content::NotificationDetails& details) {
879   if (type == chrome::NOTIFICATION_HISTORY_URL_VISITED) {
880     content::Details<history::URLVisitedDetails> visit_details(details);
881     if (!loaded_)
882       visits_to_add_.push_back(*visit_details.ptr());
883     else
884       UpdateKeywordSearchTermsForURL(*visit_details.ptr());
885   } else if (type == chrome::NOTIFICATION_DEFAULT_SEARCH_POLICY_CHANGED) {
886     // Policy has been updated, so the default search prefs may be different.
887     // Reload the default search provider from them.
888     // TODO(pkasting): Rather than communicating via prefs, we should eventually
889     // observe policy changes directly.
890     UpdateDefaultSearch();
891   } else if (type == chrome::NOTIFICATION_GOOGLE_URL_UPDATED) {
892     if (loaded_) {
893       GoogleBaseURLChanged(
894           content::Details<GoogleURLTracker::UpdatedDetails>(details)->first);
895     }
896   } else {
897     NOTREACHED();
898   }
899 }
900
901 void TemplateURLService::Shutdown() {
902   // This check has to be done at Shutdown() instead of in the dtor to ensure
903   // that no clients of WebDataService are holding ptrs to it after the first
904   // phase of the KeyedService Shutdown() process.
905   if (load_handle_) {
906     DCHECK(service_.get());
907     service_->CancelRequest(load_handle_);
908   }
909   service_ = NULL;
910 }
911
912 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
913   // Listen for changes to the default search from Sync.
914   PrefService* prefs = GetPrefs();
915   TemplateURL* new_default_search = GetTemplateURLForGUID(
916       prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID));
917   if (new_default_search && !is_default_search_managed_) {
918     if (new_default_search != GetDefaultSearchProvider()) {
919       base::AutoReset<DefaultSearchChangeOrigin> change_origin(
920           &dsp_change_origin_, DSP_CHANGE_SYNC_PREF);
921       SetDefaultSearchProvider(new_default_search);
922       pending_synced_default_search_ = false;
923     }
924   } else {
925     // If it's not there, or if default search is currently managed, set a
926     // flag to indicate that we waiting on the search engine entry to come
927     // in through Sync.
928     pending_synced_default_search_ = true;
929   }
930   UpdateDefaultSearch();
931 }
932
933 syncer::SyncDataList TemplateURLService::GetAllSyncData(
934     syncer::ModelType type) const {
935   DCHECK_EQ(syncer::SEARCH_ENGINES, type);
936
937   syncer::SyncDataList current_data;
938   for (TemplateURLVector::const_iterator iter = template_urls_.begin();
939       iter != template_urls_.end(); ++iter) {
940     // We don't sync keywords managed by policy.
941     if ((*iter)->created_by_policy())
942       continue;
943     // We don't sync extension-controlled search engines.
944     if ((*iter)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
945       continue;
946     current_data.push_back(CreateSyncDataFromTemplateURL(**iter));
947   }
948
949   return current_data;
950 }
951
952 syncer::SyncError TemplateURLService::ProcessSyncChanges(
953     const tracked_objects::Location& from_here,
954     const syncer::SyncChangeList& change_list) {
955   if (!models_associated_) {
956     syncer::SyncError error(FROM_HERE,
957                             syncer::SyncError::DATATYPE_ERROR,
958                             "Models not yet associated.",
959                             syncer::SEARCH_ENGINES);
960     return error;
961   }
962   DCHECK(loaded_);
963
964   base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
965
966   // We've started syncing, so set our origin member to the base Sync value.
967   // As we move through Sync Code, we may set this to increasingly specific
968   // origins so we can tell what exactly caused a DSP change.
969   base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
970       DSP_CHANGE_SYNC_UNINTENTIONAL);
971
972   syncer::SyncChangeList new_changes;
973   syncer::SyncError error;
974   for (syncer::SyncChangeList::const_iterator iter = change_list.begin();
975       iter != change_list.end(); ++iter) {
976     DCHECK_EQ(syncer::SEARCH_ENGINES, iter->sync_data().GetDataType());
977
978     std::string guid =
979         iter->sync_data().GetSpecifics().search_engine().sync_guid();
980     TemplateURL* existing_turl = GetTemplateURLForGUID(guid);
981     scoped_ptr<TemplateURL> turl(CreateTemplateURLFromTemplateURLAndSyncData(
982         profile_, existing_turl, iter->sync_data(), &new_changes));
983     if (!turl.get())
984       continue;
985
986     // Explicitly don't check for conflicts against extension keywords; in this
987     // case the functions which modify the keyword map know how to handle the
988     // conflicts.
989     // TODO(mpcomplete): If we allow editing extension keywords, then those will
990     // need to undergo conflict resolution.
991     TemplateURL* existing_keyword_turl =
992         FindNonExtensionTemplateURLForKeyword(turl->keyword());
993     if (iter->change_type() == syncer::SyncChange::ACTION_DELETE) {
994       if (!existing_turl) {
995         NOTREACHED() << "Unexpected sync change state.";
996         error = sync_error_factory_->CreateAndUploadError(
997             FROM_HERE,
998             "ProcessSyncChanges failed on ChangeType ACTION_DELETE");
999         LOG(ERROR) << "Trying to delete a non-existent TemplateURL.";
1000         continue;
1001       }
1002       if (existing_turl == GetDefaultSearchProvider()) {
1003         // The only way Sync can attempt to delete the default search provider
1004         // is if we had changed the kSyncedDefaultSearchProviderGUID
1005         // preference, but perhaps it has not yet been received. To avoid
1006         // situations where this has come in erroneously, we will un-delete
1007         // the current default search from the Sync data. If the pref really
1008         // does arrive later, then default search will change to the correct
1009         // entry, but we'll have this extra entry sitting around. The result is
1010         // not ideal, but it prevents a far more severe bug where the default is
1011         // unexpectedly swapped to something else. The user can safely delete
1012         // the extra entry again later, if they choose. Most users who do not
1013         // look at the search engines UI will not notice this.
1014         // Note that we append a special character to the end of the keyword in
1015         // an attempt to avoid a ping-poinging situation where receiving clients
1016         // may try to continually delete the resurrected entry.
1017         base::string16 updated_keyword = UniquifyKeyword(*existing_turl, true);
1018         TemplateURLData data(existing_turl->data());
1019         data.SetKeyword(updated_keyword);
1020         TemplateURL new_turl(existing_turl->profile(), data);
1021         UIThreadSearchTermsData search_terms_data(existing_turl->profile());
1022         if (UpdateNoNotify(existing_turl, new_turl, search_terms_data))
1023           NotifyObservers();
1024
1025         syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(new_turl);
1026         new_changes.push_back(syncer::SyncChange(FROM_HERE,
1027                                                  syncer::SyncChange::ACTION_ADD,
1028                                                  sync_data));
1029         // Ignore the delete attempt. This means we never end up reseting the
1030         // default search provider due to an ACTION_DELETE from sync.
1031         continue;
1032       }
1033
1034       Remove(existing_turl);
1035     } else if (iter->change_type() == syncer::SyncChange::ACTION_ADD) {
1036       if (existing_turl) {
1037         NOTREACHED() << "Unexpected sync change state.";
1038         error = sync_error_factory_->CreateAndUploadError(
1039             FROM_HERE,
1040             "ProcessSyncChanges failed on ChangeType ACTION_ADD");
1041         LOG(ERROR) << "Trying to add an existing TemplateURL.";
1042         continue;
1043       }
1044       const std::string guid = turl->sync_guid();
1045       if (existing_keyword_turl) {
1046         // Resolve any conflicts so we can safely add the new entry.
1047         ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1048                                    &new_changes);
1049       }
1050       // Force the local ID to kInvalidTemplateURLID so we can add it.
1051       TemplateURLData data(turl->data());
1052       data.id = kInvalidTemplateURLID;
1053       Add(new TemplateURL(profile_, data));
1054
1055       // Possibly set the newly added |turl| as the default search provider.
1056       SetDefaultSearchProviderIfNewlySynced(guid);
1057     } else if (iter->change_type() == syncer::SyncChange::ACTION_UPDATE) {
1058       if (!existing_turl) {
1059         NOTREACHED() << "Unexpected sync change state.";
1060         error = sync_error_factory_->CreateAndUploadError(
1061             FROM_HERE,
1062             "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
1063         LOG(ERROR) << "Trying to update a non-existent TemplateURL.";
1064         continue;
1065       }
1066       if (existing_keyword_turl && (existing_keyword_turl != existing_turl)) {
1067         // Resolve any conflicts with other entries so we can safely update the
1068         // keyword.
1069         ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1070                                    &new_changes);
1071       }
1072       UIThreadSearchTermsData search_terms_data(existing_turl->profile());
1073       if (UpdateNoNotify(existing_turl, *turl, search_terms_data))
1074         NotifyObservers();
1075     } else {
1076       // We've unexpectedly received an ACTION_INVALID.
1077       NOTREACHED() << "Unexpected sync change state.";
1078       error = sync_error_factory_->CreateAndUploadError(
1079           FROM_HERE,
1080           "ProcessSyncChanges received an ACTION_INVALID");
1081     }
1082   }
1083
1084   // If something went wrong, we want to prematurely exit to avoid pushing
1085   // inconsistent data to Sync. We return the last error we received.
1086   if (error.IsSet())
1087     return error;
1088
1089   error = sync_processor_->ProcessSyncChanges(from_here, new_changes);
1090
1091   return error;
1092 }
1093
1094 syncer::SyncMergeResult TemplateURLService::MergeDataAndStartSyncing(
1095     syncer::ModelType type,
1096     const syncer::SyncDataList& initial_sync_data,
1097     scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
1098     scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) {
1099   DCHECK(loaded_);
1100   DCHECK_EQ(type, syncer::SEARCH_ENGINES);
1101   DCHECK(!sync_processor_.get());
1102   DCHECK(sync_processor.get());
1103   DCHECK(sync_error_factory.get());
1104   syncer::SyncMergeResult merge_result(type);
1105   sync_processor_ = sync_processor.Pass();
1106   sync_error_factory_ = sync_error_factory.Pass();
1107
1108   // We just started syncing, so set our wait-for-default flag if we are
1109   // expecting a default from Sync.
1110   if (GetPrefs()) {
1111     std::string default_guid = GetPrefs()->GetString(
1112         prefs::kSyncedDefaultSearchProviderGUID);
1113     const TemplateURL* current_default = GetDefaultSearchProvider();
1114
1115     if (!default_guid.empty() &&
1116         (!current_default || current_default->sync_guid() != default_guid))
1117       pending_synced_default_search_ = true;
1118   }
1119
1120   // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
1121   // don't step on our own toes.
1122   base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
1123
1124   // We've started syncing, so set our origin member to the base Sync value.
1125   // As we move through Sync Code, we may set this to increasingly specific
1126   // origins so we can tell what exactly caused a DSP change.
1127   base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
1128       DSP_CHANGE_SYNC_UNINTENTIONAL);
1129
1130   syncer::SyncChangeList new_changes;
1131
1132   // Build maps of our sync GUIDs to syncer::SyncData.
1133   SyncDataMap local_data_map = CreateGUIDToSyncDataMap(
1134       GetAllSyncData(syncer::SEARCH_ENGINES));
1135   SyncDataMap sync_data_map = CreateGUIDToSyncDataMap(initial_sync_data);
1136
1137   merge_result.set_num_items_before_association(local_data_map.size());
1138   for (SyncDataMap::const_iterator iter = sync_data_map.begin();
1139       iter != sync_data_map.end(); ++iter) {
1140     TemplateURL* local_turl = GetTemplateURLForGUID(iter->first);
1141     scoped_ptr<TemplateURL> sync_turl(
1142         CreateTemplateURLFromTemplateURLAndSyncData(profile_, local_turl,
1143             iter->second, &new_changes));
1144     if (!sync_turl.get())
1145       continue;
1146
1147     if (pre_sync_deletes_.find(sync_turl->sync_guid()) !=
1148         pre_sync_deletes_.end()) {
1149       // This entry was deleted before the initial sync began (possibly through
1150       // preprocessing in TemplateURLService's loading code). Ignore it and send
1151       // an ACTION_DELETE up to the server.
1152       new_changes.push_back(
1153           syncer::SyncChange(FROM_HERE,
1154                              syncer::SyncChange::ACTION_DELETE,
1155                              iter->second));
1156       UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1157           DELETE_ENGINE_PRE_SYNC, DELETE_ENGINE_MAX);
1158       continue;
1159     }
1160
1161     if (local_turl) {
1162       DCHECK(IsFromSync(local_turl, sync_data_map));
1163       // This local search engine is already synced. If the timestamp differs
1164       // from Sync, we need to update locally or to the cloud. Note that if the
1165       // timestamps are equal, we touch neither.
1166       if (sync_turl->last_modified() > local_turl->last_modified()) {
1167         // We've received an update from Sync. We should replace all synced
1168         // fields in the local TemplateURL. Note that this includes the
1169         // TemplateURLID and the TemplateURL may have to be reparsed. This
1170         // also makes the local data's last_modified timestamp equal to Sync's,
1171         // avoiding an Update on the next MergeData call.
1172         UIThreadSearchTermsData search_terms_data(local_turl->profile());
1173         if (UpdateNoNotify(local_turl, *sync_turl, search_terms_data))
1174           NotifyObservers();
1175         merge_result.set_num_items_modified(
1176             merge_result.num_items_modified() + 1);
1177       } else if (sync_turl->last_modified() < local_turl->last_modified()) {
1178         // Otherwise, we know we have newer data, so update Sync with our
1179         // data fields.
1180         new_changes.push_back(
1181             syncer::SyncChange(FROM_HERE,
1182                                syncer::SyncChange::ACTION_UPDATE,
1183                                local_data_map[local_turl->sync_guid()]));
1184       }
1185       local_data_map.erase(iter->first);
1186     } else {
1187       // The search engine from the cloud has not been synced locally. Merge it
1188       // into our local model. This will handle any conflicts with local (and
1189       // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1190       // over not-yet-synced TemplateURLs.
1191       MergeInSyncTemplateURL(sync_turl.get(), sync_data_map, &new_changes,
1192                              &local_data_map, &merge_result);
1193     }
1194   }
1195
1196   // If there is a pending synced default search provider that was processed
1197   // above, set it now.
1198   TemplateURL* pending_default = GetPendingSyncedDefaultSearchProvider();
1199   if (pending_default) {
1200     base::AutoReset<DefaultSearchChangeOrigin> change_origin(
1201         &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
1202     SetDefaultSearchProvider(pending_default);
1203   }
1204
1205   // The remaining SyncData in local_data_map should be everything that needs to
1206   // be pushed as ADDs to sync.
1207   for (SyncDataMap::const_iterator iter = local_data_map.begin();
1208       iter != local_data_map.end(); ++iter) {
1209     new_changes.push_back(
1210         syncer::SyncChange(FROM_HERE,
1211                            syncer::SyncChange::ACTION_ADD,
1212                            iter->second));
1213   }
1214
1215   // Do some post-processing on the change list to ensure that we are sending
1216   // valid changes to sync_processor_.
1217   PruneSyncChanges(&sync_data_map, &new_changes);
1218
1219   LogDuplicatesHistogram(GetTemplateURLs());
1220   merge_result.set_num_items_after_association(
1221       GetAllSyncData(syncer::SEARCH_ENGINES).size());
1222   merge_result.set_error(
1223       sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
1224   if (merge_result.error().IsSet())
1225     return merge_result;
1226
1227   // The ACTION_DELETEs from this set are processed. Empty it so we don't try to
1228   // reuse them on the next call to MergeDataAndStartSyncing.
1229   pre_sync_deletes_.clear();
1230
1231   models_associated_ = true;
1232   return merge_result;
1233 }
1234
1235 void TemplateURLService::StopSyncing(syncer::ModelType type) {
1236   DCHECK_EQ(type, syncer::SEARCH_ENGINES);
1237   models_associated_ = false;
1238   sync_processor_.reset();
1239   sync_error_factory_.reset();
1240 }
1241
1242 void TemplateURLService::ProcessTemplateURLChange(
1243     const tracked_objects::Location& from_here,
1244     const TemplateURL* turl,
1245     syncer::SyncChange::SyncChangeType type) {
1246   DCHECK_NE(type, syncer::SyncChange::ACTION_INVALID);
1247   DCHECK(turl);
1248
1249   if (!models_associated_)
1250     return;  // Not syncing.
1251
1252   if (processing_syncer_changes_)
1253     return;  // These are changes originating from us. Ignore.
1254
1255   // Avoid syncing keywords managed by policy.
1256   if (turl->created_by_policy())
1257     return;
1258
1259   // Avoid syncing extension-controlled search engines.
1260   if (turl->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
1261     return;
1262
1263   syncer::SyncChangeList changes;
1264
1265   syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1266   changes.push_back(syncer::SyncChange(from_here,
1267                                        type,
1268                                        sync_data));
1269
1270   sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
1271 }
1272
1273 // static
1274 syncer::SyncData TemplateURLService::CreateSyncDataFromTemplateURL(
1275     const TemplateURL& turl) {
1276   sync_pb::EntitySpecifics specifics;
1277   sync_pb::SearchEngineSpecifics* se_specifics =
1278       specifics.mutable_search_engine();
1279   se_specifics->set_short_name(base::UTF16ToUTF8(turl.short_name()));
1280   se_specifics->set_keyword(base::UTF16ToUTF8(turl.keyword()));
1281   se_specifics->set_favicon_url(turl.favicon_url().spec());
1282   se_specifics->set_url(turl.url());
1283   se_specifics->set_safe_for_autoreplace(turl.safe_for_autoreplace());
1284   se_specifics->set_originating_url(turl.originating_url().spec());
1285   se_specifics->set_date_created(turl.date_created().ToInternalValue());
1286   se_specifics->set_input_encodings(JoinString(turl.input_encodings(), ';'));
1287   se_specifics->set_show_in_default_list(turl.show_in_default_list());
1288   se_specifics->set_suggestions_url(turl.suggestions_url());
1289   se_specifics->set_prepopulate_id(turl.prepopulate_id());
1290   se_specifics->set_instant_url(turl.instant_url());
1291   if (!turl.image_url().empty())
1292     se_specifics->set_image_url(turl.image_url());
1293   se_specifics->set_new_tab_url(turl.new_tab_url());
1294   if (!turl.search_url_post_params().empty())
1295     se_specifics->set_search_url_post_params(turl.search_url_post_params());
1296   if (!turl.suggestions_url_post_params().empty()) {
1297     se_specifics->set_suggestions_url_post_params(
1298         turl.suggestions_url_post_params());
1299   }
1300   if (!turl.instant_url_post_params().empty())
1301     se_specifics->set_instant_url_post_params(turl.instant_url_post_params());
1302   if (!turl.image_url_post_params().empty())
1303     se_specifics->set_image_url_post_params(turl.image_url_post_params());
1304   se_specifics->set_last_modified(turl.last_modified().ToInternalValue());
1305   se_specifics->set_sync_guid(turl.sync_guid());
1306   for (size_t i = 0; i < turl.alternate_urls().size(); ++i)
1307     se_specifics->add_alternate_urls(turl.alternate_urls()[i]);
1308   se_specifics->set_search_terms_replacement_key(
1309       turl.search_terms_replacement_key());
1310
1311   return syncer::SyncData::CreateLocalData(se_specifics->sync_guid(),
1312                                            se_specifics->keyword(),
1313                                            specifics);
1314 }
1315
1316 // static
1317 TemplateURL* TemplateURLService::CreateTemplateURLFromTemplateURLAndSyncData(
1318     Profile* profile,
1319     TemplateURL* existing_turl,
1320     const syncer::SyncData& sync_data,
1321     syncer::SyncChangeList* change_list) {
1322   DCHECK(change_list);
1323
1324   sync_pb::SearchEngineSpecifics specifics =
1325       sync_data.GetSpecifics().search_engine();
1326
1327   // Past bugs might have caused either of these fields to be empty.  Just
1328   // delete this data off the server.
1329   if (specifics.url().empty() || specifics.sync_guid().empty()) {
1330     change_list->push_back(
1331         syncer::SyncChange(FROM_HERE,
1332                            syncer::SyncChange::ACTION_DELETE,
1333                            sync_data));
1334     UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1335         DELETE_ENGINE_EMPTY_FIELD, DELETE_ENGINE_MAX);
1336     return NULL;
1337   }
1338
1339   TemplateURLData data(existing_turl ?
1340       existing_turl->data() : TemplateURLData());
1341   data.short_name = base::UTF8ToUTF16(specifics.short_name());
1342   data.originating_url = GURL(specifics.originating_url());
1343   base::string16 keyword(base::UTF8ToUTF16(specifics.keyword()));
1344   // NOTE: Once this code has shipped in a couple of stable releases, we can
1345   // probably remove the migration portion, comment out the
1346   // "autogenerate_keyword" field entirely in the .proto file, and fold the
1347   // empty keyword case into the "delete data" block above.
1348   bool reset_keyword =
1349       specifics.autogenerate_keyword() || specifics.keyword().empty();
1350   if (reset_keyword)
1351     keyword = base::ASCIIToUTF16("dummy");  // Will be replaced below.
1352   DCHECK(!keyword.empty());
1353   data.SetKeyword(keyword);
1354   data.SetURL(specifics.url());
1355   data.suggestions_url = specifics.suggestions_url();
1356   data.instant_url = specifics.instant_url();
1357   data.image_url = specifics.image_url();
1358   data.new_tab_url = specifics.new_tab_url();
1359   data.search_url_post_params = specifics.search_url_post_params();
1360   data.suggestions_url_post_params = specifics.suggestions_url_post_params();
1361   data.instant_url_post_params = specifics.instant_url_post_params();
1362   data.image_url_post_params = specifics.image_url_post_params();
1363   data.favicon_url = GURL(specifics.favicon_url());
1364   data.show_in_default_list = specifics.show_in_default_list();
1365   data.safe_for_autoreplace = specifics.safe_for_autoreplace();
1366   base::SplitString(specifics.input_encodings(), ';', &data.input_encodings);
1367   // If the server data has duplicate encodings, we'll want to push an update
1368   // below to correct it.  Note that we also fix this in
1369   // GetSearchProvidersUsingKeywordResult(), since otherwise we'd never correct
1370   // local problems for clients which have disabled search engine sync.
1371   bool deduped = DeDupeEncodings(&data.input_encodings);
1372   data.date_created = base::Time::FromInternalValue(specifics.date_created());
1373   data.last_modified = base::Time::FromInternalValue(specifics.last_modified());
1374   data.prepopulate_id = specifics.prepopulate_id();
1375   data.sync_guid = specifics.sync_guid();
1376   data.alternate_urls.clear();
1377   for (int i = 0; i < specifics.alternate_urls_size(); ++i)
1378     data.alternate_urls.push_back(specifics.alternate_urls(i));
1379   data.search_terms_replacement_key = specifics.search_terms_replacement_key();
1380
1381   TemplateURL* turl = new TemplateURL(profile, data);
1382   // If this TemplateURL matches a built-in prepopulated template URL, it's
1383   // possible that sync is trying to modify fields that should not be touched.
1384   // Revert these fields to the built-in values.
1385   UpdateTemplateURLIfPrepopulated(turl, profile);
1386   DCHECK_NE(TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION, turl->GetType());
1387   if (reset_keyword || deduped) {
1388     if (reset_keyword)
1389       turl->ResetKeywordIfNecessary(true);
1390     syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1391     change_list->push_back(syncer::SyncChange(FROM_HERE,
1392                                               syncer::SyncChange::ACTION_UPDATE,
1393                                               sync_data));
1394   } else if (turl->IsGoogleSearchURLWithReplaceableKeyword()) {
1395     if (!existing_turl) {
1396       // We're adding a new TemplateURL that uses the Google base URL, so set
1397       // its keyword appropriately for the local environment.
1398       turl->ResetKeywordIfNecessary(false);
1399     } else if (existing_turl->IsGoogleSearchURLWithReplaceableKeyword()) {
1400       // Ignore keyword changes triggered by the Google base URL changing on
1401       // another client.  If the base URL changes in this client as well, we'll
1402       // pick that up separately at the appropriate time.  Otherwise, changing
1403       // the keyword here could result in having the wrong keyword for the local
1404       // environment.
1405       turl->data_.SetKeyword(existing_turl->keyword());
1406     }
1407   }
1408
1409   return turl;
1410 }
1411
1412 // static
1413 SyncDataMap TemplateURLService::CreateGUIDToSyncDataMap(
1414     const syncer::SyncDataList& sync_data) {
1415   SyncDataMap data_map;
1416   for (syncer::SyncDataList::const_iterator i(sync_data.begin());
1417        i != sync_data.end();
1418        ++i)
1419     data_map[i->GetSpecifics().search_engine().sync_guid()] = *i;
1420   return data_map;
1421 }
1422
1423 void TemplateURLService::SetKeywordSearchTermsForURL(
1424     const TemplateURL* t_url,
1425     const GURL& url,
1426     const base::string16& term) {
1427   HistoryService* history = profile_  ?
1428       HistoryServiceFactory::GetForProfile(profile_,
1429                                            Profile::EXPLICIT_ACCESS) :
1430       NULL;
1431   if (!history)
1432     return;
1433   history->SetKeywordSearchTermsForURL(url, t_url->id(), term);
1434 }
1435
1436 void TemplateURLService::Init(const Initializer* initializers,
1437                               int num_initializers) {
1438   // Register for notifications.
1439   if (profile_) {
1440     // TODO(sky): bug 1166191. The keywords should be moved into the history
1441     // db, which will mean we no longer need this notification and the history
1442     // backend can handle automatically adding the search terms as the user
1443     // navigates.
1444     content::Source<Profile> profile_source(profile_->GetOriginalProfile());
1445     notification_registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URL_VISITED,
1446                                 profile_source);
1447     notification_registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_URL_UPDATED,
1448                                 profile_source);
1449     pref_change_registrar_.Init(GetPrefs());
1450     pref_change_registrar_.Add(
1451         prefs::kSyncedDefaultSearchProviderGUID,
1452         base::Bind(
1453             &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged,
1454             base::Unretained(this)));
1455   }
1456   notification_registrar_.Add(this,
1457       chrome::NOTIFICATION_DEFAULT_SEARCH_POLICY_CHANGED,
1458       content::NotificationService::AllSources());
1459
1460   if (num_initializers > 0) {
1461     // This path is only hit by test code and is used to simulate a loaded
1462     // TemplateURLService.
1463     ChangeToLoadedState();
1464
1465     // Add specific initializers, if any.
1466     for (int i(0); i < num_initializers; ++i) {
1467       DCHECK(initializers[i].keyword);
1468       DCHECK(initializers[i].url);
1469       DCHECK(initializers[i].content);
1470
1471       // TemplateURLService ends up owning the TemplateURL, don't try and free
1472       // it.
1473       TemplateURLData data;
1474       data.short_name = base::UTF8ToUTF16(initializers[i].content);
1475       data.SetKeyword(base::UTF8ToUTF16(initializers[i].keyword));
1476       data.SetURL(initializers[i].url);
1477       TemplateURL* template_url = new TemplateURL(profile_, data);
1478       AddNoNotify(template_url, true);
1479
1480       // Set the first provided identifier to be the default.
1481       if (i == 0)
1482         SetDefaultSearchProviderNoNotify(template_url);
1483     }
1484   }
1485
1486   // Initialize default search.
1487   UpdateDefaultSearch();
1488
1489   // Request a server check for the correct Google URL if Google is the
1490   // default search engine and not in headless mode.
1491   if (profile_ && initial_default_search_provider_.get() &&
1492       initial_default_search_provider_->url_ref().HasGoogleBaseURLs()) {
1493     scoped_ptr<base::Environment> env(base::Environment::Create());
1494     if (!env->HasVar(env_vars::kHeadless))
1495       GoogleURLTracker::RequestServerCheck(profile_, false);
1496   }
1497 }
1498
1499 void TemplateURLService::RemoveFromMaps(TemplateURL* template_url) {
1500   const base::string16& keyword = template_url->keyword();
1501   DCHECK_NE(0U, keyword_to_template_map_.count(keyword));
1502   if (keyword_to_template_map_[keyword] == template_url) {
1503     // We need to check whether the keyword can now be provided by another
1504     // TemplateURL.  See the comments in AddToMaps() for more information on
1505     // extension keywords and how they can coexist with non-extension keywords.
1506     // In the case of more than one extension, we use the most recently
1507     // installed (which will be the most recently added, which will have the
1508     // highest ID).
1509     TemplateURL* best_fallback = NULL;
1510     for (TemplateURLVector::const_iterator i(template_urls_.begin());
1511          i != template_urls_.end(); ++i) {
1512       TemplateURL* turl = *i;
1513       // This next statement relies on the fact that there can only be one
1514       // non-Omnibox API TemplateURL with a given keyword.
1515       if ((turl != template_url) && (turl->keyword() == keyword) &&
1516           (!best_fallback ||
1517            (best_fallback->GetType() != TemplateURL::OMNIBOX_API_EXTENSION) ||
1518            ((turl->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) &&
1519             (turl->id() > best_fallback->id()))))
1520         best_fallback = turl;
1521     }
1522     if (best_fallback)
1523       keyword_to_template_map_[keyword] = best_fallback;
1524     else
1525       keyword_to_template_map_.erase(keyword);
1526   }
1527
1528   if (!template_url->sync_guid().empty())
1529     guid_to_template_map_.erase(template_url->sync_guid());
1530   if (loaded_) {
1531     UIThreadSearchTermsData search_terms_data(template_url->profile());
1532     provider_map_->Remove(template_url, search_terms_data);
1533   }
1534 }
1535
1536 void TemplateURLService::AddToMaps(TemplateURL* template_url) {
1537   bool template_url_is_omnibox_api =
1538       template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1539   const base::string16& keyword = template_url->keyword();
1540   KeywordToTemplateMap::const_iterator i =
1541       keyword_to_template_map_.find(keyword);
1542   if (i == keyword_to_template_map_.end()) {
1543     keyword_to_template_map_[keyword] = template_url;
1544   } else {
1545     const TemplateURL* existing_url = i->second;
1546     // We should only have overlapping keywords when at least one comes from
1547     // an extension.  In that case, the ranking order is:
1548     //   Manually-modified keywords > extension keywords > replaceable keywords
1549     // When there are multiple extensions, the last-added wins.
1550     bool existing_url_is_omnibox_api =
1551         existing_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1552     DCHECK(existing_url_is_omnibox_api || template_url_is_omnibox_api);
1553     if (existing_url_is_omnibox_api ?
1554         !CanReplace(template_url) : CanReplace(existing_url))
1555       keyword_to_template_map_[keyword] = template_url;
1556   }
1557
1558   if (!template_url->sync_guid().empty())
1559     guid_to_template_map_[template_url->sync_guid()] = template_url;
1560   if (loaded_) {
1561     UIThreadSearchTermsData search_terms_data(profile_);
1562     provider_map_->Add(template_url, search_terms_data);
1563   }
1564 }
1565
1566 // Helper for partition() call in next function.
1567 bool HasValidID(TemplateURL* t_url) {
1568   return t_url->id() != kInvalidTemplateURLID;
1569 }
1570
1571 void TemplateURLService::SetTemplateURLs(TemplateURLVector* urls) {
1572   // Partition the URLs first, instead of implementing the loops below by simply
1573   // scanning the input twice.  While it's not supposed to happen normally, it's
1574   // possible for corrupt databases to return multiple entries with the same
1575   // keyword.  In this case, the first loop may delete the first entry when
1576   // adding the second.  If this happens, the second loop must not attempt to
1577   // access the deleted entry.  Partitioning ensures this constraint.
1578   TemplateURLVector::iterator first_invalid(
1579       std::partition(urls->begin(), urls->end(), HasValidID));
1580
1581   // First, add the items that already have id's, so that the next_id_ gets
1582   // properly set.
1583   for (TemplateURLVector::const_iterator i = urls->begin(); i != first_invalid;
1584        ++i) {
1585     next_id_ = std::max(next_id_, (*i)->id());
1586     AddNoNotify(*i, false);
1587   }
1588
1589   // Next add the new items that don't have id's.
1590   for (TemplateURLVector::const_iterator i = first_invalid; i != urls->end();
1591        ++i)
1592     AddNoNotify(*i, true);
1593
1594   // Clear the input vector to reduce the chance callers will try to use a
1595   // (possibly deleted) entry.
1596   urls->clear();
1597 }
1598
1599 void TemplateURLService::ChangeToLoadedState() {
1600   DCHECK(!loaded_);
1601
1602   UIThreadSearchTermsData search_terms_data(profile_);
1603   provider_map_->Init(template_urls_, search_terms_data);
1604   loaded_ = true;
1605 }
1606
1607 void TemplateURLService::SaveDefaultSearchProviderToPrefs(
1608     const TemplateURL* t_url) {
1609   PrefService* prefs = GetPrefs();
1610   if (!prefs)
1611     return;
1612
1613   bool enabled = false;
1614   std::string search_url;
1615   std::string suggest_url;
1616   std::string instant_url;
1617   std::string image_url;
1618   std::string new_tab_url;
1619   std::string search_url_post_params;
1620   std::string suggest_url_post_params;
1621   std::string instant_url_post_params;
1622   std::string image_url_post_params;
1623   std::string icon_url;
1624   std::string encodings;
1625   std::string short_name;
1626   std::string keyword;
1627   std::string id_string;
1628   std::string prepopulate_id;
1629   base::ListValue alternate_urls;
1630   std::string search_terms_replacement_key;
1631   if (t_url) {
1632     DCHECK_EQ(TemplateURL::NORMAL, t_url->GetType());
1633     enabled = true;
1634     search_url = t_url->url();
1635     suggest_url = t_url->suggestions_url();
1636     instant_url = t_url->instant_url();
1637     image_url = t_url->image_url();
1638     new_tab_url = t_url->new_tab_url();
1639     search_url_post_params = t_url->search_url_post_params();
1640     suggest_url_post_params = t_url->suggestions_url_post_params();
1641     instant_url_post_params = t_url->instant_url_post_params();
1642     image_url_post_params = t_url->image_url_post_params();
1643     GURL icon_gurl = t_url->favicon_url();
1644     if (!icon_gurl.is_empty())
1645       icon_url = icon_gurl.spec();
1646     encodings = JoinString(t_url->input_encodings(), ';');
1647     short_name = base::UTF16ToUTF8(t_url->short_name());
1648     keyword = base::UTF16ToUTF8(t_url->keyword());
1649     id_string = base::Int64ToString(t_url->id());
1650     prepopulate_id = base::Int64ToString(t_url->prepopulate_id());
1651     for (size_t i = 0; i < t_url->alternate_urls().size(); ++i)
1652       alternate_urls.AppendString(t_url->alternate_urls()[i]);
1653     search_terms_replacement_key = t_url->search_terms_replacement_key();
1654   }
1655   prefs->SetBoolean(prefs::kDefaultSearchProviderEnabled, enabled);
1656   prefs->SetString(prefs::kDefaultSearchProviderSearchURL, search_url);
1657   prefs->SetString(prefs::kDefaultSearchProviderSuggestURL, suggest_url);
1658   prefs->SetString(prefs::kDefaultSearchProviderInstantURL, instant_url);
1659   prefs->SetString(prefs::kDefaultSearchProviderImageURL, image_url);
1660   prefs->SetString(prefs::kDefaultSearchProviderNewTabURL, new_tab_url);
1661   prefs->SetString(prefs::kDefaultSearchProviderSearchURLPostParams,
1662                    search_url_post_params);
1663   prefs->SetString(prefs::kDefaultSearchProviderSuggestURLPostParams,
1664                    suggest_url_post_params);
1665   prefs->SetString(prefs::kDefaultSearchProviderInstantURLPostParams,
1666                    instant_url_post_params);
1667   prefs->SetString(prefs::kDefaultSearchProviderImageURLPostParams,
1668                    image_url_post_params);
1669   prefs->SetString(prefs::kDefaultSearchProviderIconURL, icon_url);
1670   prefs->SetString(prefs::kDefaultSearchProviderEncodings, encodings);
1671   prefs->SetString(prefs::kDefaultSearchProviderName, short_name);
1672   prefs->SetString(prefs::kDefaultSearchProviderKeyword, keyword);
1673   prefs->SetString(prefs::kDefaultSearchProviderID, id_string);
1674   prefs->SetString(prefs::kDefaultSearchProviderPrepopulateID, prepopulate_id);
1675   prefs->Set(prefs::kDefaultSearchProviderAlternateURLs, alternate_urls);
1676   prefs->SetString(prefs::kDefaultSearchProviderSearchTermsReplacementKey,
1677       search_terms_replacement_key);
1678 }
1679
1680 bool TemplateURLService::LoadDefaultSearchProviderFromPrefs(
1681     scoped_ptr<TemplateURL>* default_provider,
1682     bool* is_managed) {
1683   PrefService* prefs = GetPrefs();
1684   if (!prefs || !prefs->HasPrefPath(prefs::kDefaultSearchProviderSearchURL))
1685     return false;
1686
1687   const PrefService::Preference* pref =
1688       prefs->FindPreference(prefs::kDefaultSearchProviderSearchURL);
1689   *is_managed = pref && pref->IsManaged();
1690
1691   if (!prefs->GetBoolean(prefs::kDefaultSearchProviderEnabled)) {
1692     // The user doesn't want a default search provider.
1693     default_provider->reset(NULL);
1694     return true;
1695   }
1696
1697   base::string16 name =
1698       base::UTF8ToUTF16(prefs->GetString(prefs::kDefaultSearchProviderName));
1699   base::string16 keyword =
1700       base::UTF8ToUTF16(prefs->GetString(prefs::kDefaultSearchProviderKeyword));
1701   // Force keyword to be non-empty.
1702   // TODO(pkasting): This is only necessary as long as we're potentially loading
1703   // older prefs where empty keywords are theoretically possible.  Eventually
1704   // this code can be replaced with a DCHECK(!keyword.empty());.
1705   bool update_keyword = keyword.empty();
1706   if (update_keyword)
1707     keyword = base::ASCIIToUTF16("dummy");
1708   std::string search_url =
1709       prefs->GetString(prefs::kDefaultSearchProviderSearchURL);
1710   // Force URL to be non-empty.  We've never supported this case, but past bugs
1711   // might have resulted in it slipping through; eventually this code can be
1712   // replaced with a DCHECK(!search_url.empty());.
1713   if (search_url.empty())
1714     return false;
1715   std::string suggest_url =
1716       prefs->GetString(prefs::kDefaultSearchProviderSuggestURL);
1717   std::string instant_url =
1718       prefs->GetString(prefs::kDefaultSearchProviderInstantURL);
1719   std::string image_url =
1720       prefs->GetString(prefs::kDefaultSearchProviderImageURL);
1721   std::string new_tab_url =
1722       prefs->GetString(prefs::kDefaultSearchProviderNewTabURL);
1723   std::string search_url_post_params =
1724       prefs->GetString(prefs::kDefaultSearchProviderSearchURLPostParams);
1725   std::string suggest_url_post_params =
1726       prefs->GetString(prefs::kDefaultSearchProviderSuggestURLPostParams);
1727   std::string instant_url_post_params =
1728       prefs->GetString(prefs::kDefaultSearchProviderInstantURLPostParams);
1729   std::string image_url_post_params =
1730       prefs->GetString(prefs::kDefaultSearchProviderImageURLPostParams);
1731   std::string icon_url =
1732       prefs->GetString(prefs::kDefaultSearchProviderIconURL);
1733   std::string encodings =
1734       prefs->GetString(prefs::kDefaultSearchProviderEncodings);
1735   std::string id_string = prefs->GetString(prefs::kDefaultSearchProviderID);
1736   std::string prepopulate_id =
1737       prefs->GetString(prefs::kDefaultSearchProviderPrepopulateID);
1738   const base::ListValue* alternate_urls =
1739       prefs->GetList(prefs::kDefaultSearchProviderAlternateURLs);
1740   std::string search_terms_replacement_key = prefs->GetString(
1741       prefs::kDefaultSearchProviderSearchTermsReplacementKey);
1742
1743   TemplateURLData data;
1744   data.short_name = name;
1745   data.SetKeyword(keyword);
1746   data.SetURL(search_url);
1747   data.suggestions_url = suggest_url;
1748   data.instant_url = instant_url;
1749   data.image_url = image_url;
1750   data.new_tab_url = new_tab_url;
1751   data.search_url_post_params = search_url_post_params;
1752   data.suggestions_url_post_params = suggest_url_post_params;
1753   data.instant_url_post_params = instant_url_post_params;
1754   data.image_url_post_params = image_url_post_params;
1755   data.favicon_url = GURL(icon_url);
1756   data.show_in_default_list = true;
1757   data.alternate_urls.clear();
1758   for (size_t i = 0; i < alternate_urls->GetSize(); ++i) {
1759     std::string alternate_url;
1760     if (alternate_urls->GetString(i, &alternate_url))
1761       data.alternate_urls.push_back(alternate_url);
1762   }
1763   data.search_terms_replacement_key = search_terms_replacement_key;
1764   base::SplitString(encodings, ';', &data.input_encodings);
1765   if (!id_string.empty() && !*is_managed) {
1766     int64 value;
1767     base::StringToInt64(id_string, &value);
1768     data.id = value;
1769   }
1770   if (!prepopulate_id.empty() && !*is_managed) {
1771     int value;
1772     base::StringToInt(prepopulate_id, &value);
1773     data.prepopulate_id = value;
1774   }
1775   default_provider->reset(new TemplateURL(profile_, data));
1776   DCHECK_EQ(TemplateURL::NORMAL, (*default_provider)->GetType());
1777   if (update_keyword)
1778     (*default_provider)->ResetKeywordIfNecessary(true);
1779   return true;
1780 }
1781
1782 void TemplateURLService::ClearDefaultProviderFromPrefs() {
1783   // We overwrite user preferences. If the default search engine is managed,
1784   // there is no effect.
1785   SaveDefaultSearchProviderToPrefs(NULL);
1786   // Default value for kDefaultSearchProviderEnabled is true.
1787   PrefService* prefs = GetPrefs();
1788   if (prefs)
1789     prefs->SetBoolean(prefs::kDefaultSearchProviderEnabled, true);
1790 }
1791
1792 bool TemplateURLService::CanReplaceKeywordForHost(
1793     const std::string& host,
1794     TemplateURL** to_replace) {
1795   DCHECK(!to_replace || !*to_replace);
1796   const TemplateURLSet* urls = provider_map_->GetURLsForHost(host);
1797   if (!urls)
1798     return true;
1799   for (TemplateURLSet::const_iterator i(urls->begin()); i != urls->end(); ++i) {
1800     if (CanReplace(*i)) {
1801       if (to_replace)
1802         *to_replace = *i;
1803       return true;
1804     }
1805   }
1806   return false;
1807 }
1808
1809 bool TemplateURLService::CanReplace(const TemplateURL* t_url) {
1810   return (t_url != default_search_provider_ && !t_url->show_in_default_list() &&
1811           t_url->safe_for_autoreplace());
1812 }
1813
1814 TemplateURL* TemplateURLService::FindNonExtensionTemplateURLForKeyword(
1815     const base::string16& keyword) {
1816   TemplateURL* keyword_turl = GetTemplateURLForKeyword(keyword);
1817   if (!keyword_turl || (keyword_turl->GetType() == TemplateURL::NORMAL))
1818     return keyword_turl;
1819   // The extension keyword in the model may be hiding a replaceable
1820   // non-extension keyword.  Look for it.
1821   for (TemplateURLVector::const_iterator i(template_urls_.begin());
1822        i != template_urls_.end(); ++i) {
1823     if (((*i)->GetType() == TemplateURL::NORMAL) &&
1824         ((*i)->keyword() == keyword))
1825       return *i;
1826   }
1827   return NULL;
1828 }
1829
1830 bool TemplateURLService::UpdateNoNotify(
1831     TemplateURL* existing_turl,
1832     const TemplateURL& new_values,
1833     const SearchTermsData& old_search_terms_data) {
1834   DCHECK(loaded_);
1835   DCHECK(existing_turl);
1836   if (std::find(template_urls_.begin(), template_urls_.end(), existing_turl) ==
1837       template_urls_.end())
1838     return false;
1839
1840   base::string16 old_keyword(existing_turl->keyword());
1841   keyword_to_template_map_.erase(old_keyword);
1842   if (!existing_turl->sync_guid().empty())
1843     guid_to_template_map_.erase(existing_turl->sync_guid());
1844
1845   provider_map_->Remove(existing_turl, old_search_terms_data);
1846   TemplateURLID previous_id = existing_turl->id();
1847   existing_turl->CopyFrom(new_values);
1848   existing_turl->data_.id = previous_id;
1849   UIThreadSearchTermsData new_search_terms_data(profile_);
1850   provider_map_->Add(existing_turl, new_search_terms_data);
1851
1852   const base::string16& keyword = existing_turl->keyword();
1853   KeywordToTemplateMap::const_iterator i =
1854       keyword_to_template_map_.find(keyword);
1855   if (i == keyword_to_template_map_.end()) {
1856     keyword_to_template_map_[keyword] = existing_turl;
1857   } else {
1858     // We can theoretically reach here in two cases:
1859     //   * There is an existing extension keyword and sync brings in a rename of
1860     //     a non-extension keyword to match.  In this case we just need to pick
1861     //     which keyword has priority to update the keyword map.
1862     //   * Autogeneration of the keyword for a Google default search provider
1863     //     at load time causes it to conflict with an existing keyword.  In this
1864     //     case we delete the existing keyword if it's replaceable, or else undo
1865     //     the change in keyword for |existing_turl|.
1866     TemplateURL* existing_keyword_turl = i->second;
1867     if (existing_keyword_turl->GetType() != TemplateURL::NORMAL) {
1868       if (!CanReplace(existing_turl))
1869         keyword_to_template_map_[keyword] = existing_turl;
1870     } else {
1871       if (CanReplace(existing_keyword_turl)) {
1872         RemoveNoNotify(existing_keyword_turl);
1873       } else {
1874         existing_turl->data_.SetKeyword(old_keyword);
1875         keyword_to_template_map_[old_keyword] = existing_turl;
1876       }
1877     }
1878   }
1879   if (!existing_turl->sync_guid().empty())
1880     guid_to_template_map_[existing_turl->sync_guid()] = existing_turl;
1881
1882   if (service_.get())
1883     service_->UpdateKeyword(existing_turl->data());
1884
1885   // Inform sync of the update.
1886   ProcessTemplateURLChange(FROM_HERE,
1887                            existing_turl,
1888                            syncer::SyncChange::ACTION_UPDATE);
1889
1890   if (default_search_provider_ == existing_turl) {
1891     bool success = SetDefaultSearchProviderNoNotify(existing_turl);
1892     DCHECK(success);
1893   }
1894   return true;
1895 }
1896
1897 // static
1898 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1899     TemplateURL* template_url,
1900     Profile* profile) {
1901   int prepopulate_id = template_url->prepopulate_id();
1902   if (template_url->prepopulate_id() == 0)
1903     return;
1904
1905   size_t default_search_index;
1906   ScopedVector<TemplateURL> prepopulated_urls =
1907       TemplateURLPrepopulateData::GetPrepopulatedEngines(profile,
1908                                                          &default_search_index);
1909
1910   for (size_t i = 0; i < prepopulated_urls.size(); ++i) {
1911     if (prepopulated_urls[i]->prepopulate_id() == prepopulate_id) {
1912       MergeIntoPrepopulatedEngineData(&prepopulated_urls[i]->data_,
1913                                       template_url);
1914       template_url->CopyFrom(*prepopulated_urls[i]);
1915     }
1916   }
1917 }
1918
1919 PrefService* TemplateURLService::GetPrefs() {
1920   return profile_ ? profile_->GetPrefs() : NULL;
1921 }
1922
1923 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1924     const history::URLVisitedDetails& details) {
1925   const history::URLRow& row = details.row;
1926   if (!row.url().is_valid())
1927     return;
1928
1929   const TemplateURLSet* urls_for_host =
1930       provider_map_->GetURLsForHost(row.url().host());
1931   if (!urls_for_host)
1932     return;
1933
1934   for (TemplateURLSet::const_iterator i = urls_for_host->begin();
1935        i != urls_for_host->end(); ++i) {
1936     base::string16 search_terms;
1937     if ((*i)->ExtractSearchTermsFromURL(row.url(), &search_terms) &&
1938         !search_terms.empty()) {
1939       if (content::PageTransitionStripQualifier(details.transition) ==
1940           content::PAGE_TRANSITION_KEYWORD) {
1941         // The visit is the result of the user entering a keyword, generate a
1942         // KEYWORD_GENERATED visit for the KEYWORD so that the keyword typed
1943         // count is boosted.
1944         AddTabToSearchVisit(**i);
1945       }
1946       SetKeywordSearchTermsForURL(*i, row.url(), search_terms);
1947     }
1948   }
1949 }
1950
1951 void TemplateURLService::AddTabToSearchVisit(const TemplateURL& t_url) {
1952   // Only add visits for entries the user hasn't modified. If the user modified
1953   // the entry the keyword may no longer correspond to the host name. It may be
1954   // possible to do something more sophisticated here, but it's so rare as to
1955   // not be worth it.
1956   if (!t_url.safe_for_autoreplace())
1957     return;
1958
1959   if (!profile_)
1960     return;
1961
1962   HistoryService* history =
1963       HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
1964   if (!history)
1965     return;
1966
1967   GURL url(URLFixerUpper::FixupURL(base::UTF16ToUTF8(t_url.keyword()),
1968                                    std::string()));
1969   if (!url.is_valid())
1970     return;
1971
1972   // Synthesize a visit for the keyword. This ensures the url for the keyword is
1973   // autocompleted even if the user doesn't type the url in directly.
1974   history->AddPage(url, base::Time::Now(), NULL, 0, GURL(),
1975                    history::RedirectList(),
1976                    content::PAGE_TRANSITION_KEYWORD_GENERATED,
1977                    history::SOURCE_BROWSED, false);
1978 }
1979
1980 void TemplateURLService::GoogleBaseURLChanged(const GURL& old_base_url) {
1981   bool something_changed = false;
1982   for (TemplateURLVector::iterator i(template_urls_.begin());
1983        i != template_urls_.end(); ++i) {
1984     TemplateURL* t_url = *i;
1985     if (t_url->url_ref().HasGoogleBaseURLs() ||
1986         t_url->suggestions_url_ref().HasGoogleBaseURLs()) {
1987       TemplateURL updated_turl(t_url->profile(), t_url->data());
1988       updated_turl.ResetKeywordIfNecessary(false);
1989       KeywordToTemplateMap::const_iterator existing_entry =
1990           keyword_to_template_map_.find(updated_turl.keyword());
1991       if ((existing_entry != keyword_to_template_map_.end()) &&
1992           (existing_entry->second != t_url)) {
1993         // The new autogenerated keyword conflicts with another TemplateURL.
1994         // Overwrite it if it's replaceable; otherwise, leave |t_url| using its
1995         // current keyword.  (This will not prevent |t_url| from auto-updating
1996         // the keyword in the future if the conflicting TemplateURL disappears.)
1997         // Note that we must still update |t_url| in this case, or the
1998         // |provider_map_| will not be updated correctly.
1999         if (CanReplace(existing_entry->second))
2000           RemoveNoNotify(existing_entry->second);
2001         else
2002           updated_turl.data_.SetKeyword(t_url->keyword());
2003       }
2004       something_changed = true;
2005       // This will send the keyword change to sync.  Note that other clients
2006       // need to reset the keyword to an appropriate local value when this
2007       // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
2008       UpdateNoNotify(t_url, updated_turl,
2009           OldBaseURLSearchTermsData(t_url->profile(), old_base_url.spec()));
2010     }
2011   }
2012   if (something_changed)
2013     NotifyObservers();
2014 }
2015
2016 void TemplateURLService::UpdateDefaultSearch() {
2017   if (!loaded_) {
2018     // Set |initial_default_search_provider_| from the preferences.  We use this
2019     // value for default search provider until the database has been loaded.
2020     if (!LoadDefaultSearchProviderFromPrefs(&initial_default_search_provider_,
2021                                             &is_default_search_managed_)) {
2022       // Prefs does not specify, so rely on the prepopulated engines.  This
2023       // should happen only the first time Chrome is started.
2024       initial_default_search_provider_.reset(
2025           TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(profile_));
2026       is_default_search_managed_ = false;
2027     }
2028     return;
2029   }
2030   // Load the default search specified in prefs.
2031   scoped_ptr<TemplateURL> new_default_from_prefs;
2032   bool new_is_default_managed = false;
2033   // Load the default from prefs.  It's possible that it won't succeed
2034   // because we are in the middle of doing SaveDefaultSearchProviderToPrefs()
2035   // and all the preference items have not been saved.  In that case, we
2036   // don't have yet a default.  It would be much better if we could save
2037   // preferences in batches and trigger notifications at the end.
2038   LoadDefaultSearchProviderFromPrefs(&new_default_from_prefs,
2039                                      &new_is_default_managed);
2040   if (!is_default_search_managed_ && !new_is_default_managed) {
2041     // We're not interested in cases where the default was and remains
2042     // unmanaged.  In that case, preferences have no impact on the default.
2043     return;
2044   }
2045   if (is_default_search_managed_ && new_is_default_managed) {
2046     // The default was managed and remains managed.  Update the default only
2047     // if it has changed; we don't want to respond to changes triggered by
2048     // SaveDefaultSearchProviderToPrefs.
2049     if (TemplateURLsHaveSamePrefs(default_search_provider_,
2050                                   new_default_from_prefs.get()))
2051       return;
2052     if (new_default_from_prefs.get() == NULL) {
2053       // default_search_provider_ can't be NULL otherwise
2054       // TemplateURLsHaveSamePrefs would have returned true.  Remove this now
2055       // invalid value.
2056       TemplateURL* old_default = default_search_provider_;
2057       bool success = SetDefaultSearchProviderNoNotify(NULL);
2058       DCHECK(success);
2059       RemoveNoNotify(old_default);
2060     } else if (default_search_provider_) {
2061       TemplateURLData data(new_default_from_prefs->data());
2062       data.created_by_policy = true;
2063       TemplateURL new_values(new_default_from_prefs->profile(), data);
2064       UIThreadSearchTermsData search_terms_data(
2065           default_search_provider_->profile());
2066       UpdateNoNotify(default_search_provider_, new_values, search_terms_data);
2067     } else {
2068       TemplateURL* new_template = NULL;
2069       if (new_default_from_prefs.get()) {
2070         TemplateURLData data(new_default_from_prefs->data());
2071         data.created_by_policy = true;
2072         new_template = new TemplateURL(profile_, data);
2073         if (!AddNoNotify(new_template, true))
2074           return;
2075       }
2076       bool success = SetDefaultSearchProviderNoNotify(new_template);
2077       DCHECK(success);
2078     }
2079   } else if (!is_default_search_managed_ && new_is_default_managed) {
2080     // The default used to be unmanaged and is now managed.  Add the new
2081     // managed default to the list of URLs and set it as default.
2082     is_default_search_managed_ = new_is_default_managed;
2083     TemplateURL* new_template = NULL;
2084     if (new_default_from_prefs.get()) {
2085       TemplateURLData data(new_default_from_prefs->data());
2086       data.created_by_policy = true;
2087       new_template = new TemplateURL(profile_, data);
2088       if (!AddNoNotify(new_template, true))
2089         return;
2090     }
2091     bool success = SetDefaultSearchProviderNoNotify(new_template);
2092     DCHECK(success);
2093   } else {
2094     // The default was managed and is no longer.
2095     DCHECK(is_default_search_managed_ && !new_is_default_managed);
2096     is_default_search_managed_ = new_is_default_managed;
2097     // If we had a default, delete the previous default if created by policy
2098     // and set a likely default.
2099     if ((default_search_provider_ != NULL) &&
2100         default_search_provider_->created_by_policy()) {
2101       TemplateURL* old_default = default_search_provider_;
2102       default_search_provider_ = NULL;
2103       RemoveNoNotify(old_default);
2104     }
2105
2106     // The likely default should be from Sync if we were waiting on Sync.
2107     // Otherwise, it should be FindNewDefaultSearchProvider.
2108     TemplateURL* synced_default = GetPendingSyncedDefaultSearchProvider();
2109     if (synced_default) {
2110       pending_synced_default_search_ = false;
2111
2112       base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2113           &dsp_change_origin_, DSP_CHANGE_SYNC_NOT_MANAGED);
2114       SetDefaultSearchProviderNoNotify(synced_default);
2115     } else {
2116       SetDefaultSearchProviderNoNotify(FindNewDefaultSearchProvider());
2117     }
2118   }
2119   NotifyObservers();
2120 }
2121
2122 bool TemplateURLService::SetDefaultSearchProviderNoNotify(TemplateURL* url) {
2123   if (url) {
2124     if (std::find(template_urls_.begin(), template_urls_.end(), url) ==
2125         template_urls_.end())
2126       return false;
2127     // Omnibox keywords cannot be made default.
2128     DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION, url->GetType());
2129   }
2130
2131   // Only bother reassigning |url| if it has changed. Notice that we don't just
2132   // early exit if they are equal, because |url| may have had its fields
2133   // changed, and needs to be persisted below (for example, when this is called
2134   // from UpdateNoNotify).
2135   if (default_search_provider_ != url) {
2136     // Engines set by policy override extension-controlled engines, which
2137     // override other engines.
2138     DCHECK(!is_default_search_managed() || !url ||
2139            (url->GetType() == TemplateURL::NORMAL));
2140     if (is_default_search_managed() || !default_search_provider_ ||
2141         (default_search_provider_->GetType() == TemplateURL::NORMAL) ||
2142         (url &&
2143          (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION))){
2144       UMA_HISTOGRAM_ENUMERATION("Search.DefaultSearchChangeOrigin",
2145                                 dsp_change_origin_, DSP_CHANGE_MAX);
2146       default_search_provider_ = url;
2147     }
2148   }
2149
2150   if (url) {
2151     // Don't mark the url as edited, otherwise we won't be able to rev the
2152     // template urls we ship with.
2153     url->data_.show_in_default_list = true;
2154     if (service_.get() && (url->GetType() == TemplateURL::NORMAL))
2155       service_->UpdateKeyword(url->data());
2156
2157     if (url->url_ref().HasGoogleBaseURLs()) {
2158       GoogleURLTracker::RequestServerCheck(profile_, false);
2159 #if defined(ENABLE_RLZ)
2160       RLZTracker::RecordProductEvent(rlz_lib::CHROME,
2161                                      RLZTracker::CHROME_OMNIBOX,
2162                                      rlz_lib::SET_TO_GOOGLE);
2163 #endif
2164     }
2165   }
2166
2167   // Extension-controlled search engines shouldn't be persisted anywhere.
2168   if (url && (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION))
2169     return true;
2170
2171   if (!is_default_search_managed_) {
2172     SaveDefaultSearchProviderToPrefs(url);
2173
2174     // If we are syncing, we want to set the synced pref that will notify other
2175     // instances to change their default to this new search provider.
2176     // Note: we don't update the pref if we're currently in the middle of
2177     // handling a sync operation. Sync operations from other clients are not
2178     // guaranteed to arrive together, and any client that deletes the default
2179     // needs to set a new default as well. If we update the default here, we're
2180     // likely to race with the update from the other client, resulting in
2181     // a possibly random default search provider.
2182     if (sync_processor_.get() && url && !url->sync_guid().empty() &&
2183         GetPrefs() && !processing_syncer_changes_) {
2184       GetPrefs()->SetString(prefs::kSyncedDefaultSearchProviderGUID,
2185                             url->sync_guid());
2186     }
2187   }
2188
2189   if (service_.get())
2190     service_->SetDefaultSearchProvider(url);
2191
2192   // Inform sync the change to the show_in_default_list flag.
2193   if (url)
2194     ProcessTemplateURLChange(FROM_HERE,
2195                              url,
2196                              syncer::SyncChange::ACTION_UPDATE);
2197   return true;
2198 }
2199
2200 bool TemplateURLService::AddNoNotify(TemplateURL* template_url,
2201                                      bool newly_adding) {
2202   DCHECK(template_url);
2203
2204   if (newly_adding) {
2205     DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
2206     DCHECK(std::find(template_urls_.begin(), template_urls_.end(),
2207                      template_url) == template_urls_.end());
2208     template_url->data_.id = ++next_id_;
2209   }
2210
2211   template_url->ResetKeywordIfNecessary(false);
2212   // Check whether |template_url|'s keyword conflicts with any already in the
2213   // model.
2214   TemplateURL* existing_keyword_turl =
2215       GetTemplateURLForKeyword(template_url->keyword());
2216   if (existing_keyword_turl != NULL) {
2217     DCHECK_NE(existing_keyword_turl, template_url);
2218     // Only replace one of the TemplateURLs if they are either both extensions,
2219     // or both not extensions.
2220     bool are_same_type = existing_keyword_turl->GetType() ==
2221         template_url->GetType();
2222     if (CanReplace(existing_keyword_turl) && are_same_type) {
2223       RemoveNoNotify(existing_keyword_turl);
2224     } else if (CanReplace(template_url) && are_same_type) {
2225       delete template_url;
2226       return false;
2227     } else {
2228       base::string16 new_keyword =
2229           UniquifyKeyword(*existing_keyword_turl, false);
2230       ResetTemplateURL(existing_keyword_turl,
2231                        existing_keyword_turl->short_name(), new_keyword,
2232                        existing_keyword_turl->url());
2233     }
2234   }
2235   template_urls_.push_back(template_url);
2236   AddToMaps(template_url);
2237
2238   if (newly_adding &&
2239       (template_url->GetType() !=
2240           TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)) {
2241     if (service_.get())
2242       service_->AddKeyword(template_url->data());
2243
2244     // Inform sync of the addition. Note that this will assign a GUID to
2245     // template_url and add it to the guid_to_template_map_.
2246     ProcessTemplateURLChange(FROM_HERE,
2247                              template_url,
2248                              syncer::SyncChange::ACTION_ADD);
2249   }
2250
2251   return true;
2252 }
2253
2254 void TemplateURLService::RemoveNoNotify(TemplateURL* template_url) {
2255   TemplateURLVector::iterator i =
2256       std::find(template_urls_.begin(), template_urls_.end(), template_url);
2257   if (i == template_urls_.end())
2258     return;
2259
2260   if (template_url == default_search_provider_) {
2261     // Should never delete the default search provider.
2262     NOTREACHED();
2263     return;
2264   }
2265
2266   RemoveFromMaps(template_url);
2267
2268   // Remove it from the vector containing all TemplateURLs.
2269   template_urls_.erase(i);
2270
2271   if (template_url->GetType() != TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) {
2272     if (service_.get())
2273       service_->RemoveKeyword(template_url->id());
2274
2275     // Inform sync of the deletion.
2276     ProcessTemplateURLChange(FROM_HERE,
2277                              template_url,
2278                              syncer::SyncChange::ACTION_DELETE);
2279
2280     UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
2281                               DELETE_ENGINE_USER_ACTION, DELETE_ENGINE_MAX);
2282   }
2283
2284   if (profile_) {
2285     content::Source<Profile> source(profile_);
2286     TemplateURLID id = template_url->id();
2287     content::NotificationService::current()->Notify(
2288         chrome::NOTIFICATION_TEMPLATE_URL_REMOVED,
2289         source,
2290         content::Details<TemplateURLID>(&id));
2291   }
2292
2293   // We own the TemplateURL and need to delete it.
2294   delete template_url;
2295 }
2296
2297 void TemplateURLService::NotifyObservers() {
2298   if (!loaded_)
2299     return;
2300
2301   FOR_EACH_OBSERVER(TemplateURLServiceObserver, model_observers_,
2302                     OnTemplateURLServiceChanged());
2303 }
2304
2305 // |template_urls| are the TemplateURLs loaded from the database.
2306 // |default_search_provider| points to one of them, if it was set in the db.
2307 // |default_from_prefs| is the default search provider from the preferences.
2308 // Check |is_default_search_managed_| to determine if it was set by policy.
2309 //
2310 // This function removes from the vector and the database all the TemplateURLs
2311 // that were set by policy, unless it is the current default search provider
2312 // and matches what is set by a managed preference.
2313 void TemplateURLService::RemoveProvidersCreatedByPolicy(
2314     TemplateURLVector* template_urls,
2315     TemplateURL** default_search_provider,
2316     TemplateURL* default_from_prefs) {
2317   DCHECK(template_urls);
2318   DCHECK(default_search_provider);
2319   for (TemplateURLVector::iterator i = template_urls->begin();
2320        i != template_urls->end(); ) {
2321     TemplateURL* template_url = *i;
2322     if (template_url->created_by_policy()) {
2323       if (template_url == *default_search_provider &&
2324           is_default_search_managed_ &&
2325           TemplateURLsHaveSamePrefs(template_url,
2326                                     default_from_prefs)) {
2327         // If the database specified a default search provider that was set
2328         // by policy, and the default search provider from the preferences
2329         // is also set by policy and they are the same, keep the entry in the
2330         // database and the |default_search_provider|.
2331         ++i;
2332         continue;
2333       }
2334
2335       // The database loaded a managed |default_search_provider|, but it has
2336       // been updated in the prefs. Remove it from the database, and update the
2337       // |default_search_provider| pointer here.
2338       if (*default_search_provider &&
2339           (*default_search_provider)->id() == template_url->id())
2340         *default_search_provider = NULL;
2341
2342       i = template_urls->erase(i);
2343       if (service_.get())
2344         service_->RemoveKeyword(template_url->id());
2345       delete template_url;
2346     } else {
2347       ++i;
2348     }
2349   }
2350 }
2351
2352 void TemplateURLService::ResetTemplateURLGUID(TemplateURL* url,
2353                                               const std::string& guid) {
2354   DCHECK(loaded_);
2355   DCHECK(!guid.empty());
2356
2357   TemplateURLData data(url->data());
2358   data.sync_guid = guid;
2359   TemplateURL new_url(url->profile(), data);
2360   UIThreadSearchTermsData search_terms_data(url->profile());
2361   UpdateNoNotify(url, new_url, search_terms_data);
2362 }
2363
2364 base::string16 TemplateURLService::UniquifyKeyword(const TemplateURL& turl,
2365                                                    bool force) {
2366   if (!force) {
2367     // Already unique.
2368     if (!GetTemplateURLForKeyword(turl.keyword()))
2369       return turl.keyword();
2370
2371     // First, try to return the generated keyword for the TemplateURL (except
2372     // for extensions, as their keywords are not associated with their URLs).
2373     GURL gurl(turl.url());
2374     if (gurl.is_valid() &&
2375         (turl.GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
2376       base::string16 keyword_candidate = GenerateKeyword(gurl);
2377       if (!GetTemplateURLForKeyword(keyword_candidate))
2378         return keyword_candidate;
2379     }
2380   }
2381
2382   // We try to uniquify the keyword by appending a special character to the end.
2383   // This is a best-effort approach where we try to preserve the original
2384   // keyword and let the user do what they will after our attempt.
2385   base::string16 keyword_candidate(turl.keyword());
2386   do {
2387     keyword_candidate.append(base::ASCIIToUTF16("_"));
2388   } while (GetTemplateURLForKeyword(keyword_candidate));
2389
2390   return keyword_candidate;
2391 }
2392
2393 bool TemplateURLService::IsLocalTemplateURLBetter(
2394     const TemplateURL* local_turl,
2395     const TemplateURL* sync_turl) {
2396   DCHECK(GetTemplateURLForGUID(local_turl->sync_guid()));
2397   return local_turl->last_modified() > sync_turl->last_modified() ||
2398          local_turl->created_by_policy() ||
2399          local_turl== GetDefaultSearchProvider();
2400 }
2401
2402 void TemplateURLService::ResolveSyncKeywordConflict(
2403     TemplateURL* unapplied_sync_turl,
2404     TemplateURL* applied_sync_turl,
2405     syncer::SyncChangeList* change_list) {
2406   DCHECK(loaded_);
2407   DCHECK(unapplied_sync_turl);
2408   DCHECK(applied_sync_turl);
2409   DCHECK(change_list);
2410   DCHECK_EQ(applied_sync_turl->keyword(), unapplied_sync_turl->keyword());
2411   DCHECK_NE(TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION,
2412             applied_sync_turl->GetType());
2413
2414   // Both |unapplied_sync_turl| and |applied_sync_turl| are known to Sync, so
2415   // don't delete either of them. Instead, determine which is "better" and
2416   // uniquify the other one, sending an update to the server for the updated
2417   // entry.
2418   const bool applied_turl_is_better =
2419       IsLocalTemplateURLBetter(applied_sync_turl, unapplied_sync_turl);
2420   TemplateURL* loser = applied_turl_is_better ?
2421       unapplied_sync_turl : applied_sync_turl;
2422   base::string16 new_keyword = UniquifyKeyword(*loser, false);
2423   DCHECK(!GetTemplateURLForKeyword(new_keyword));
2424   if (applied_turl_is_better) {
2425     // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2426     // for adding or updating unapplied_sync_turl in the local model.
2427     unapplied_sync_turl->data_.SetKeyword(new_keyword);
2428   } else {
2429     // Update |applied_sync_turl| in the local model with the new keyword.
2430     TemplateURLData data(applied_sync_turl->data());
2431     data.SetKeyword(new_keyword);
2432     TemplateURL new_turl(applied_sync_turl->profile(), data);
2433     UIThreadSearchTermsData search_terms_data(applied_sync_turl->profile());
2434     if (UpdateNoNotify(applied_sync_turl, new_turl, search_terms_data))
2435       NotifyObservers();
2436   }
2437   // The losing TemplateURL should have their keyword updated. Send a change to
2438   // the server to reflect this change.
2439   syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*loser);
2440   change_list->push_back(syncer::SyncChange(FROM_HERE,
2441       syncer::SyncChange::ACTION_UPDATE,
2442       sync_data));
2443 }
2444
2445 void TemplateURLService::MergeInSyncTemplateURL(
2446     TemplateURL* sync_turl,
2447     const SyncDataMap& sync_data,
2448     syncer::SyncChangeList* change_list,
2449     SyncDataMap* local_data,
2450     syncer::SyncMergeResult* merge_result) {
2451   DCHECK(sync_turl);
2452   DCHECK(!GetTemplateURLForGUID(sync_turl->sync_guid()));
2453   DCHECK(IsFromSync(sync_turl, sync_data));
2454
2455   TemplateURL* conflicting_turl =
2456       FindNonExtensionTemplateURLForKeyword(sync_turl->keyword());
2457   bool should_add_sync_turl = true;
2458
2459   // If there was no TemplateURL in the local model that conflicts with
2460   // |sync_turl|, skip the following preparation steps and just add |sync_turl|
2461   // directly. Otherwise, modify |conflicting_turl| to make room for
2462   // |sync_turl|.
2463   if (conflicting_turl) {
2464     if (IsFromSync(conflicting_turl, sync_data)) {
2465       // |conflicting_turl| is already known to Sync, so we're not allowed to
2466       // remove it. In this case, we want to uniquify the worse one and send an
2467       // update for the changed keyword to sync. We can reuse the logic from
2468       // ResolveSyncKeywordConflict for this.
2469       ResolveSyncKeywordConflict(sync_turl, conflicting_turl, change_list);
2470       merge_result->set_num_items_modified(
2471           merge_result->num_items_modified() + 1);
2472     } else {
2473       // |conflicting_turl| is not yet known to Sync. If it is better, then we
2474       // want to transfer its values up to sync. Otherwise, we remove it and
2475       // allow the entry from Sync to overtake it in the model.
2476       const std::string guid = conflicting_turl->sync_guid();
2477       if (IsLocalTemplateURLBetter(conflicting_turl, sync_turl)) {
2478         ResetTemplateURLGUID(conflicting_turl, sync_turl->sync_guid());
2479         syncer::SyncData sync_data =
2480             CreateSyncDataFromTemplateURL(*conflicting_turl);
2481         change_list->push_back(syncer::SyncChange(
2482             FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
2483         if (conflicting_turl == GetDefaultSearchProvider() &&
2484             !pending_synced_default_search_) {
2485           // If we're not waiting for the Synced default to come in, we should
2486           // override the pref with our new GUID. If we are waiting for the
2487           // arrival of a synced default, setting the pref here would cause us
2488           // to lose the GUID we are waiting on.
2489           PrefService* prefs = GetPrefs();
2490           if (prefs) {
2491             prefs->SetString(prefs::kSyncedDefaultSearchProviderGUID,
2492                              conflicting_turl->sync_guid());
2493           }
2494         }
2495         // Note that in this case we do not add the Sync TemplateURL to the
2496         // local model, since we've effectively "merged" it in by updating the
2497         // local conflicting entry with its sync_guid.
2498         should_add_sync_turl = false;
2499         merge_result->set_num_items_modified(
2500             merge_result->num_items_modified() + 1);
2501       } else {
2502         // We guarantee that this isn't the local search provider. Otherwise,
2503         // local would have won.
2504         DCHECK(conflicting_turl != GetDefaultSearchProvider());
2505         Remove(conflicting_turl);
2506         merge_result->set_num_items_deleted(
2507             merge_result->num_items_deleted() + 1);
2508       }
2509       // This TemplateURL was either removed or overwritten in the local model.
2510       // Remove the entry from the local data so it isn't pushed up to Sync.
2511       local_data->erase(guid);
2512     }
2513   }
2514
2515   if (should_add_sync_turl) {
2516     // Force the local ID to kInvalidTemplateURLID so we can add it.
2517     TemplateURLData data(sync_turl->data());
2518     data.id = kInvalidTemplateURLID;
2519     Add(new TemplateURL(profile_, data));
2520     merge_result->set_num_items_added(
2521         merge_result->num_items_added() + 1);
2522   }
2523 }
2524
2525 void TemplateURLService::SetDefaultSearchProviderIfNewlySynced(
2526     const std::string& guid) {
2527   // If we're not syncing or if default search is managed by policy, ignore.
2528   if (!sync_processor_.get() || is_default_search_managed_)
2529     return;
2530
2531   PrefService* prefs = GetPrefs();
2532   if (prefs && pending_synced_default_search_ &&
2533       prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID) == guid) {
2534     // Make sure this actually exists. We should not be calling this unless we
2535     // really just added this TemplateURL.
2536     TemplateURL* turl_from_sync = GetTemplateURLForGUID(guid);
2537     if (turl_from_sync && turl_from_sync->SupportsReplacement()) {
2538       base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2539           &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
2540       SetDefaultSearchProvider(turl_from_sync);
2541     }
2542     pending_synced_default_search_ = false;
2543   }
2544 }
2545
2546 TemplateURL* TemplateURLService::GetPendingSyncedDefaultSearchProvider() {
2547   PrefService* prefs = GetPrefs();
2548   if (!prefs || !pending_synced_default_search_)
2549     return NULL;
2550
2551   // Could be NULL if no such thing exists.
2552   return GetTemplateURLForGUID(
2553       prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID));
2554 }
2555
2556 void TemplateURLService::PatchMissingSyncGUIDs(
2557     TemplateURLVector* template_urls) {
2558   DCHECK(template_urls);
2559   for (TemplateURLVector::iterator i = template_urls->begin();
2560        i != template_urls->end(); ++i) {
2561     TemplateURL* template_url = *i;
2562     DCHECK(template_url);
2563     if (template_url->sync_guid().empty() &&
2564         (template_url->GetType() !=
2565             TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)) {
2566       template_url->data_.sync_guid = base::GenerateGUID();
2567       if (service_.get())
2568         service_->UpdateKeyword(template_url->data());
2569     }
2570   }
2571 }
2572
2573 void TemplateURLService::AddTemplateURLsAndSetupDefaultEngine(
2574     TemplateURLVector* template_urls,
2575     TemplateURL* default_search_provider) {
2576   DCHECK(template_urls);
2577   is_default_search_managed_ = false;
2578   bool database_specified_a_default = (default_search_provider != NULL);
2579
2580   // Check if default search provider is now managed.
2581   scoped_ptr<TemplateURL> default_from_prefs;
2582   LoadDefaultSearchProviderFromPrefs(&default_from_prefs,
2583                                      &is_default_search_managed_);
2584
2585   // Remove entries that were created because of policy as they may have
2586   // changed since the database was saved.
2587   RemoveProvidersCreatedByPolicy(template_urls,
2588                                  &default_search_provider,
2589                                  default_from_prefs.get());
2590
2591   PatchMissingSyncGUIDs(template_urls);
2592
2593   if (is_default_search_managed_) {
2594     SetTemplateURLs(template_urls);
2595
2596     if (TemplateURLsHaveSamePrefs(default_search_provider,
2597                                   default_from_prefs.get())) {
2598       // The value from the preferences was previously stored in the database.
2599       // Reuse it.
2600     } else {
2601       // The value from the preferences takes over.
2602       default_search_provider = NULL;
2603       if (default_from_prefs) {
2604         TemplateURLData data(default_from_prefs->data());
2605         data.created_by_policy = true;
2606         data.id = kInvalidTemplateURLID;
2607         default_search_provider = new TemplateURL(profile_, data);
2608         if (!AddNoNotify(default_search_provider, true))
2609           default_search_provider = NULL;
2610       }
2611     }
2612     // Note that this saves the default search provider to prefs.
2613     if (!default_search_provider ||
2614         ((default_search_provider->GetType() !=
2615             TemplateURL::OMNIBOX_API_EXTENSION) &&
2616          default_search_provider->SupportsReplacement())) {
2617       bool success = SetDefaultSearchProviderNoNotify(default_search_provider);
2618       DCHECK(success);
2619     }
2620   } else {
2621     // If we had a managed default, replace it with the synced default if
2622     // applicable, or the first provider of the list.
2623     TemplateURL* synced_default = GetPendingSyncedDefaultSearchProvider();
2624     if (synced_default) {
2625       default_search_provider = synced_default;
2626       pending_synced_default_search_ = false;
2627     } else if (database_specified_a_default &&
2628         default_search_provider == NULL) {
2629       UMA_HISTOGRAM_ENUMERATION(kFirstPotentialEngineHistogramName,
2630                                 FIRST_POTENTIAL_CALLSITE_ON_LOAD,
2631                                 FIRST_POTENTIAL_CALLSITE_MAX);
2632       default_search_provider = FirstPotentialDefaultEngine(*template_urls);
2633     }
2634
2635     // If the default search provider existed previously, then just
2636     // set the member variable. Otherwise, we'll set it using the method
2637     // to ensure that it is saved properly after its id is set.
2638     if (default_search_provider &&
2639         (default_search_provider->id() != kInvalidTemplateURLID)) {
2640       default_search_provider_ = default_search_provider;
2641       default_search_provider = NULL;
2642     }
2643     SetTemplateURLs(template_urls);
2644
2645     if (default_search_provider) {
2646       base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2647           &dsp_change_origin_, default_from_prefs ?
2648               dsp_change_origin_ : DSP_CHANGE_NEW_ENGINE_NO_PREFS);
2649       // Note that this saves the default search provider to prefs.
2650       SetDefaultSearchProvider(default_search_provider);
2651     } else {
2652       // Always save the default search provider to prefs. That way we don't
2653       // have to worry about it being out of sync.
2654       if (default_search_provider_)
2655         SaveDefaultSearchProviderToPrefs(default_search_provider_);
2656     }
2657   }
2658 }
2659
2660 void TemplateURLService::EnsureDefaultSearchProviderExists() {
2661   if (!is_default_search_managed()) {
2662     bool has_default_search_provider = default_search_provider_ &&
2663         default_search_provider_->SupportsReplacement();
2664     UMA_HISTOGRAM_BOOLEAN("Search.HasDefaultSearchProvider",
2665                           has_default_search_provider);
2666     // Ensure that default search provider exists. See http://crbug.com/116952.
2667     if (!has_default_search_provider) {
2668       bool success =
2669           SetDefaultSearchProviderNoNotify(FindNewDefaultSearchProvider());
2670       DCHECK(success);
2671     }
2672     // Don't log anything if the user has a NULL default search provider.
2673     if (default_search_provider_) {
2674       UMA_HISTOGRAM_ENUMERATION("Search.DefaultSearchProviderType",
2675           TemplateURLPrepopulateData::GetEngineType(*default_search_provider_),
2676           SEARCH_ENGINE_MAX);
2677     }
2678   }
2679 }
2680
2681 TemplateURL* TemplateURLService::CreateTemplateURLForExtension(
2682     const ExtensionKeyword& extension_keyword) const {
2683   TemplateURLData data;
2684   data.short_name = base::UTF8ToUTF16(extension_keyword.extension_name);
2685   data.SetKeyword(base::UTF8ToUTF16(extension_keyword.extension_keyword));
2686   // This URL is not actually used for navigation. It holds the extension's
2687   // ID, as well as forcing the TemplateURL to be treated as a search keyword.
2688   data.SetURL(std::string(extensions::kExtensionScheme) + "://" +
2689       extension_keyword.extension_id + "/?q={searchTerms}");
2690   return new TemplateURL(profile_, data);
2691 }
2692
2693 TemplateURL* TemplateURLService::FindTemplateURLForExtension(
2694     const std::string& extension_id,
2695     TemplateURL::Type type) const {
2696   DCHECK_NE(TemplateURL::NORMAL, type);
2697   for (TemplateURLVector::const_iterator i = template_urls_.begin();
2698        i != template_urls_.end(); ++i) {
2699     if ((*i)->GetType() == type &&
2700         (*i)->GetExtensionId() == extension_id)
2701       return *i;
2702   }
2703
2704   return NULL;
2705 }
2706
2707 TemplateURL* TemplateURLService::FindExtensionDefaultSearchEngine() const {
2708   TemplateURL* most_recently_intalled_default = NULL;
2709   for (TemplateURLVector::const_iterator i = template_urls_.begin();
2710        i != template_urls_.end(); ++i) {
2711     if (((*i)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) &&
2712         (*i)->extension_info_->wants_to_be_default_engine &&
2713         (*i)->SupportsReplacement() &&
2714         (!most_recently_intalled_default ||
2715          (most_recently_intalled_default->extension_info_->install_time <
2716              (*i)->extension_info_->install_time)))
2717       most_recently_intalled_default = *i;
2718   }
2719
2720   return most_recently_intalled_default;
2721 }
2722
2723 void TemplateURLService::
2724     SetDefaultSearchProviderAfterRemovingDefaultExtension() {
2725   DCHECK(!is_default_search_managed());
2726   TemplateURL* new_dse = FindExtensionDefaultSearchEngine();
2727   if (!new_dse) {
2728     scoped_ptr<TemplateURL> default_provider;
2729     bool is_managed;
2730     if (LoadDefaultSearchProviderFromPrefs(&default_provider, &is_managed) &&
2731         default_provider) {
2732       for (TemplateURLVector::const_iterator i = template_urls_.begin();
2733            i != template_urls_.end(); ++i) {
2734         if ((*i)->id() == default_provider->id()) {
2735           new_dse = *i;
2736           break;
2737         }
2738       }
2739     }
2740   }
2741   if (!new_dse)
2742     new_dse = FindNewDefaultSearchProvider();
2743   SetDefaultSearchProviderNoNotify(new_dse);
2744 }