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