Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / components / search_engines / template_url_service.cc
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/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/guid.h"
14 #include "base/i18n/case_conversion.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/metrics/histogram.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/profiler/scoped_tracker.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 "components/rappor/rappor_service.h"
26 #include "components/search_engines/search_engines_pref_names.h"
27 #include "components/search_engines/search_host_to_urls_map.h"
28 #include "components/search_engines/search_terms_data.h"
29 #include "components/search_engines/template_url.h"
30 #include "components/search_engines/template_url_prepopulate_data.h"
31 #include "components/search_engines/template_url_service_client.h"
32 #include "components/search_engines/template_url_service_observer.h"
33 #include "components/search_engines/util.h"
34 #include "components/url_fixer/url_fixer.h"
35 #include "net/base/net_util.h"
36 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
37 #include "sync/api/sync_change.h"
38 #include "sync/api/sync_error_factory.h"
39 #include "sync/protocol/search_engine_specifics.pb.h"
40 #include "sync/protocol/sync.pb.h"
41 #include "url/gurl.h"
42
43 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet;
44 typedef TemplateURLService::SyncDataMap SyncDataMap;
45
46 namespace {
47
48 bool IdenticalSyncGUIDs(const TemplateURLData* data, const TemplateURL* turl) {
49   if (!data || !turl)
50     return !data && !turl;
51
52   return data->sync_guid == turl->sync_guid();
53 }
54
55 const char kDeleteSyncedEngineHistogramName[] =
56     "Search.DeleteSyncedSearchEngine";
57
58 // Values for an enumerated histogram used to track whenever an ACTION_DELETE is
59 // sent to the server for search engines.
60 enum DeleteSyncedSearchEngineEvent {
61   DELETE_ENGINE_USER_ACTION,
62   DELETE_ENGINE_PRE_SYNC,
63   DELETE_ENGINE_EMPTY_FIELD,
64   DELETE_ENGINE_MAX,
65 };
66
67 // Returns true iff the change in |change_list| at index |i| should not be sent
68 // up to the server based on its GUIDs presence in |sync_data| or when compared
69 // to changes after it in |change_list|.
70 // The criteria is:
71 //  1) It is an ACTION_UPDATE or ACTION_DELETE and the sync_guid associated
72 //     with it is NOT found in |sync_data|. We can only update and remove
73 //     entries that were originally from the Sync server.
74 //  2) It is an ACTION_ADD and the sync_guid associated with it is found in
75 //     |sync_data|. We cannot re-add entries that Sync already knew about.
76 //  3) There is an update after an update for the same GUID. We prune earlier
77 //     ones just to save bandwidth (Sync would normally coalesce them).
78 bool ShouldRemoveSyncChange(size_t index,
79                             syncer::SyncChangeList* change_list,
80                             const SyncDataMap* sync_data) {
81   DCHECK(index < change_list->size());
82   const syncer::SyncChange& change_i = (*change_list)[index];
83   const std::string guid = change_i.sync_data().GetSpecifics()
84       .search_engine().sync_guid();
85   syncer::SyncChange::SyncChangeType type = change_i.change_type();
86   if ((type == syncer::SyncChange::ACTION_UPDATE ||
87        type == syncer::SyncChange::ACTION_DELETE) &&
88        sync_data->find(guid) == sync_data->end())
89     return true;
90   if (type == syncer::SyncChange::ACTION_ADD &&
91       sync_data->find(guid) != sync_data->end())
92     return true;
93   if (type == syncer::SyncChange::ACTION_UPDATE) {
94     for (size_t j = index + 1; j < change_list->size(); j++) {
95       const syncer::SyncChange& change_j = (*change_list)[j];
96       if ((syncer::SyncChange::ACTION_UPDATE == change_j.change_type()) &&
97           (change_j.sync_data().GetSpecifics().search_engine().sync_guid() ==
98               guid))
99         return true;
100     }
101   }
102   return false;
103 }
104
105 // Remove SyncChanges that should not be sent to the server from |change_list|.
106 // This is done to eliminate incorrect SyncChanges added by the merge and
107 // conflict resolution logic when it is unsure of whether or not an entry is new
108 // from Sync or originally from the local model. This also removes changes that
109 // would be otherwise be coalesced by Sync in order to save bandwidth.
110 void PruneSyncChanges(const SyncDataMap* sync_data,
111                       syncer::SyncChangeList* change_list) {
112   for (size_t i = 0; i < change_list->size(); ) {
113     if (ShouldRemoveSyncChange(i, change_list, sync_data))
114       change_list->erase(change_list->begin() + i);
115     else
116       ++i;
117   }
118 }
119
120 // Returns true if |turl|'s GUID is not found inside |sync_data|. This is to be
121 // used in MergeDataAndStartSyncing to differentiate between TemplateURLs from
122 // Sync and TemplateURLs that were initially local, assuming |sync_data| is the
123 // |initial_sync_data| parameter.
124 bool IsFromSync(const TemplateURL* turl, const SyncDataMap& sync_data) {
125   return !!sync_data.count(turl->sync_guid());
126 }
127
128 // Log the number of instances of a keyword that exist, with zero or more
129 // underscores, which could occur as the result of conflict resolution.
130 void LogDuplicatesHistogram(
131     const TemplateURLService::TemplateURLVector& template_urls) {
132   std::map<std::string, int> duplicates;
133   for (TemplateURLService::TemplateURLVector::const_iterator it =
134       template_urls.begin(); it != template_urls.end(); ++it) {
135     std::string keyword = base::UTF16ToASCII((*it)->keyword());
136     base::TrimString(keyword, "_", &keyword);
137     duplicates[keyword]++;
138   }
139
140   // Count the keywords with duplicates.
141   int num_dupes = 0;
142   for (std::map<std::string, int>::const_iterator it = duplicates.begin();
143       it != duplicates.end(); ++it) {
144     if (it->second > 1)
145       num_dupes++;
146   }
147
148   UMA_HISTOGRAM_COUNTS_100("Search.SearchEngineDuplicateCounts", num_dupes);
149 }
150
151 }  // namespace
152
153
154 // TemplateURLService::LessWithPrefix -----------------------------------------
155
156 class TemplateURLService::LessWithPrefix {
157  public:
158   // We want to find the set of keywords that begin with a prefix.  The STL
159   // algorithms will return the set of elements that are "equal to" the
160   // prefix, where "equal(x, y)" means "!(cmp(x, y) || cmp(y, x))".  When
161   // cmp() is the typical std::less<>, this results in lexicographic equality;
162   // we need to extend this to mark a prefix as "not less than" a keyword it
163   // begins, which will cause the desired elements to be considered "equal to"
164   // the prefix.  Note: this is still a strict weak ordering, as required by
165   // equal_range() (though I will not prove that here).
166   //
167   // Unfortunately the calling convention is not "prefix and element" but
168   // rather "two elements", so we pass the prefix as a fake "element" which has
169   // a NULL KeywordDataElement pointer.
170   bool operator()(const KeywordToTemplateMap::value_type& elem1,
171                   const KeywordToTemplateMap::value_type& elem2) const {
172     return (elem1.second == NULL) ?
173         (elem2.first.compare(0, elem1.first.length(), elem1.first) > 0) :
174         (elem1.first < elem2.first);
175   }
176 };
177
178
179 // TemplateURLService ---------------------------------------------------------
180
181 TemplateURLService::TemplateURLService(
182     PrefService* prefs,
183     scoped_ptr<SearchTermsData> search_terms_data,
184     const scoped_refptr<KeywordWebDataService>& web_data_service,
185     scoped_ptr<TemplateURLServiceClient> client,
186     GoogleURLTracker* google_url_tracker,
187     rappor::RapporService* rappor_service,
188     const base::Closure& dsp_change_callback)
189     : prefs_(prefs),
190       search_terms_data_(search_terms_data.Pass()),
191       web_data_service_(web_data_service),
192       client_(client.Pass()),
193       google_url_tracker_(google_url_tracker),
194       rappor_service_(rappor_service),
195       dsp_change_callback_(dsp_change_callback),
196       provider_map_(new SearchHostToURLsMap),
197       loaded_(false),
198       load_failed_(false),
199       load_handle_(0),
200       default_search_provider_(NULL),
201       next_id_(kInvalidTemplateURLID + 1),
202       time_provider_(&base::Time::Now),
203       models_associated_(false),
204       processing_syncer_changes_(false),
205       dsp_change_origin_(DSP_CHANGE_OTHER),
206       default_search_manager_(
207           prefs_,
208           base::Bind(&TemplateURLService::OnDefaultSearchChange,
209                      base::Unretained(this))) {
210   DCHECK(search_terms_data_);
211   Init(NULL, 0);
212 }
213
214 TemplateURLService::TemplateURLService(const Initializer* initializers,
215                                        const int count)
216     : prefs_(NULL),
217       search_terms_data_(new SearchTermsData),
218       web_data_service_(NULL),
219       google_url_tracker_(NULL),
220       rappor_service_(NULL),
221       provider_map_(new SearchHostToURLsMap),
222       loaded_(false),
223       load_failed_(false),
224       load_handle_(0),
225       default_search_provider_(NULL),
226       next_id_(kInvalidTemplateURLID + 1),
227       time_provider_(&base::Time::Now),
228       models_associated_(false),
229       processing_syncer_changes_(false),
230       dsp_change_origin_(DSP_CHANGE_OTHER),
231       default_search_manager_(
232           prefs_,
233           base::Bind(&TemplateURLService::OnDefaultSearchChange,
234                      base::Unretained(this))) {
235   Init(initializers, count);
236 }
237
238 TemplateURLService::~TemplateURLService() {
239   // |web_data_service_| should be deleted during Shutdown().
240   DCHECK(!web_data_service_.get());
241   STLDeleteElements(&template_urls_);
242 }
243
244 // static
245 bool TemplateURLService::LoadDefaultSearchProviderFromPrefs(
246     PrefService* prefs,
247     scoped_ptr<TemplateURLData>* default_provider_data,
248     bool* is_managed) {
249   if (!prefs || !prefs->HasPrefPath(prefs::kDefaultSearchProviderSearchURL) ||
250       !prefs->HasPrefPath(prefs::kDefaultSearchProviderKeyword))
251     return false;
252
253   const PrefService::Preference* pref =
254       prefs->FindPreference(prefs::kDefaultSearchProviderSearchURL);
255   *is_managed = pref && pref->IsManaged();
256
257   if (!prefs->GetBoolean(prefs::kDefaultSearchProviderEnabled)) {
258     // The user doesn't want a default search provider.
259     default_provider_data->reset(NULL);
260     return true;
261   }
262
263   base::string16 name =
264       base::UTF8ToUTF16(prefs->GetString(prefs::kDefaultSearchProviderName));
265   base::string16 keyword =
266       base::UTF8ToUTF16(prefs->GetString(prefs::kDefaultSearchProviderKeyword));
267   if (keyword.empty())
268     return false;
269   std::string search_url =
270       prefs->GetString(prefs::kDefaultSearchProviderSearchURL);
271   // Force URL to be non-empty.  We've never supported this case, but past bugs
272   // might have resulted in it slipping through; eventually this code can be
273   // replaced with a DCHECK(!search_url.empty());.
274   if (search_url.empty())
275     return false;
276   std::string suggest_url =
277       prefs->GetString(prefs::kDefaultSearchProviderSuggestURL);
278   std::string instant_url =
279       prefs->GetString(prefs::kDefaultSearchProviderInstantURL);
280   std::string image_url =
281       prefs->GetString(prefs::kDefaultSearchProviderImageURL);
282   std::string new_tab_url =
283       prefs->GetString(prefs::kDefaultSearchProviderNewTabURL);
284   std::string search_url_post_params =
285       prefs->GetString(prefs::kDefaultSearchProviderSearchURLPostParams);
286   std::string suggest_url_post_params =
287       prefs->GetString(prefs::kDefaultSearchProviderSuggestURLPostParams);
288   std::string instant_url_post_params =
289       prefs->GetString(prefs::kDefaultSearchProviderInstantURLPostParams);
290   std::string image_url_post_params =
291       prefs->GetString(prefs::kDefaultSearchProviderImageURLPostParams);
292   std::string icon_url =
293       prefs->GetString(prefs::kDefaultSearchProviderIconURL);
294   std::string encodings =
295       prefs->GetString(prefs::kDefaultSearchProviderEncodings);
296   std::string id_string = prefs->GetString(prefs::kDefaultSearchProviderID);
297   std::string prepopulate_id =
298       prefs->GetString(prefs::kDefaultSearchProviderPrepopulateID);
299   const base::ListValue* alternate_urls =
300       prefs->GetList(prefs::kDefaultSearchProviderAlternateURLs);
301   std::string search_terms_replacement_key = prefs->GetString(
302       prefs::kDefaultSearchProviderSearchTermsReplacementKey);
303
304   default_provider_data->reset(new TemplateURLData);
305   (*default_provider_data)->short_name = name;
306   (*default_provider_data)->SetKeyword(keyword);
307   (*default_provider_data)->SetURL(search_url);
308   (*default_provider_data)->suggestions_url = suggest_url;
309   (*default_provider_data)->instant_url = instant_url;
310   (*default_provider_data)->image_url = image_url;
311   (*default_provider_data)->new_tab_url = new_tab_url;
312   (*default_provider_data)->search_url_post_params = search_url_post_params;
313   (*default_provider_data)->suggestions_url_post_params =
314       suggest_url_post_params;
315   (*default_provider_data)->instant_url_post_params = instant_url_post_params;
316   (*default_provider_data)->image_url_post_params = image_url_post_params;
317   (*default_provider_data)->favicon_url = GURL(icon_url);
318   (*default_provider_data)->show_in_default_list = true;
319   (*default_provider_data)->alternate_urls.clear();
320   for (size_t i = 0; i < alternate_urls->GetSize(); ++i) {
321     std::string alternate_url;
322     if (alternate_urls->GetString(i, &alternate_url))
323       (*default_provider_data)->alternate_urls.push_back(alternate_url);
324   }
325   (*default_provider_data)->search_terms_replacement_key =
326       search_terms_replacement_key;
327   base::SplitString(encodings, ';', &(*default_provider_data)->input_encodings);
328   if (!id_string.empty() && !*is_managed) {
329     int64 value;
330     base::StringToInt64(id_string, &value);
331     (*default_provider_data)->id = value;
332   }
333   if (!prepopulate_id.empty() && !*is_managed) {
334     int value;
335     base::StringToInt(prepopulate_id, &value);
336     (*default_provider_data)->prepopulate_id = value;
337   }
338   return true;
339 }
340
341 // static
342 base::string16 TemplateURLService::CleanUserInputKeyword(
343     const base::string16& keyword) {
344   // Remove the scheme.
345   base::string16 result(base::i18n::ToLower(keyword));
346   base::TrimWhitespace(result, base::TRIM_ALL, &result);
347   url::Component scheme_component;
348   if (url::ExtractScheme(base::UTF16ToUTF8(keyword).c_str(),
349                          static_cast<int>(keyword.length()),
350                          &scheme_component)) {
351     // If the scheme isn't "http" or "https", bail.  The user isn't trying to
352     // type a web address, but rather an FTP, file:, or other scheme URL, or a
353     // search query with some sort of initial operator (e.g. "site:").
354     if (result.compare(0, scheme_component.end(),
355                        base::ASCIIToUTF16(url::kHttpScheme)) &&
356         result.compare(0, scheme_component.end(),
357                        base::ASCIIToUTF16(url::kHttpsScheme)))
358       return base::string16();
359
360     // Include trailing ':'.
361     result.erase(0, scheme_component.end() + 1);
362     // Many schemes usually have "//" after them, so strip it too.
363     const base::string16 after_scheme(base::ASCIIToUTF16("//"));
364     if (result.compare(0, after_scheme.length(), after_scheme) == 0)
365       result.erase(0, after_scheme.length());
366   }
367
368   // Remove leading "www.".
369   result = net::StripWWW(result);
370
371   // Remove trailing "/".
372   return (result.length() > 0 && result[result.length() - 1] == '/') ?
373       result.substr(0, result.length() - 1) : result;
374 }
375
376 // static
377 void TemplateURLService::SaveDefaultSearchProviderToPrefs(
378     const TemplateURL* t_url,
379     PrefService* prefs) {
380   if (!prefs)
381     return;
382
383   bool enabled = false;
384   std::string search_url;
385   std::string suggest_url;
386   std::string instant_url;
387   std::string image_url;
388   std::string new_tab_url;
389   std::string search_url_post_params;
390   std::string suggest_url_post_params;
391   std::string instant_url_post_params;
392   std::string image_url_post_params;
393   std::string icon_url;
394   std::string encodings;
395   std::string short_name;
396   std::string keyword;
397   std::string id_string;
398   std::string prepopulate_id;
399   base::ListValue alternate_urls;
400   std::string search_terms_replacement_key;
401   if (t_url) {
402     DCHECK_EQ(TemplateURL::NORMAL, t_url->GetType());
403     enabled = true;
404     search_url = t_url->url();
405     suggest_url = t_url->suggestions_url();
406     instant_url = t_url->instant_url();
407     image_url = t_url->image_url();
408     new_tab_url = t_url->new_tab_url();
409     search_url_post_params = t_url->search_url_post_params();
410     suggest_url_post_params = t_url->suggestions_url_post_params();
411     instant_url_post_params = t_url->instant_url_post_params();
412     image_url_post_params = t_url->image_url_post_params();
413     GURL icon_gurl = t_url->favicon_url();
414     if (!icon_gurl.is_empty())
415       icon_url = icon_gurl.spec();
416     encodings = JoinString(t_url->input_encodings(), ';');
417     short_name = base::UTF16ToUTF8(t_url->short_name());
418     keyword = base::UTF16ToUTF8(t_url->keyword());
419     id_string = base::Int64ToString(t_url->id());
420     prepopulate_id = base::Int64ToString(t_url->prepopulate_id());
421     for (size_t i = 0; i < t_url->alternate_urls().size(); ++i)
422       alternate_urls.AppendString(t_url->alternate_urls()[i]);
423     search_terms_replacement_key = t_url->search_terms_replacement_key();
424   }
425   prefs->SetBoolean(prefs::kDefaultSearchProviderEnabled, enabled);
426   prefs->SetString(prefs::kDefaultSearchProviderSearchURL, search_url);
427   prefs->SetString(prefs::kDefaultSearchProviderSuggestURL, suggest_url);
428   prefs->SetString(prefs::kDefaultSearchProviderInstantURL, instant_url);
429   prefs->SetString(prefs::kDefaultSearchProviderImageURL, image_url);
430   prefs->SetString(prefs::kDefaultSearchProviderNewTabURL, new_tab_url);
431   prefs->SetString(prefs::kDefaultSearchProviderSearchURLPostParams,
432                    search_url_post_params);
433   prefs->SetString(prefs::kDefaultSearchProviderSuggestURLPostParams,
434                    suggest_url_post_params);
435   prefs->SetString(prefs::kDefaultSearchProviderInstantURLPostParams,
436                    instant_url_post_params);
437   prefs->SetString(prefs::kDefaultSearchProviderImageURLPostParams,
438                    image_url_post_params);
439   prefs->SetString(prefs::kDefaultSearchProviderIconURL, icon_url);
440   prefs->SetString(prefs::kDefaultSearchProviderEncodings, encodings);
441   prefs->SetString(prefs::kDefaultSearchProviderName, short_name);
442   prefs->SetString(prefs::kDefaultSearchProviderKeyword, keyword);
443   prefs->SetString(prefs::kDefaultSearchProviderID, id_string);
444   prefs->SetString(prefs::kDefaultSearchProviderPrepopulateID, prepopulate_id);
445   prefs->Set(prefs::kDefaultSearchProviderAlternateURLs, alternate_urls);
446   prefs->SetString(prefs::kDefaultSearchProviderSearchTermsReplacementKey,
447       search_terms_replacement_key);
448 }
449
450 bool TemplateURLService::CanReplaceKeyword(
451     const base::string16& keyword,
452     const GURL& url,
453     TemplateURL** template_url_to_replace) {
454   DCHECK(!keyword.empty());  // This should only be called for non-empty
455                              // keywords. If we need to support empty kewords
456                              // the code needs to change slightly.
457   TemplateURL* existing_url = GetTemplateURLForKeyword(keyword);
458   if (template_url_to_replace)
459     *template_url_to_replace = existing_url;
460   if (existing_url) {
461     // We already have a TemplateURL for this keyword. Only allow it to be
462     // replaced if the TemplateURL can be replaced.
463     return CanReplace(existing_url);
464   }
465
466   // We don't have a TemplateURL with keyword. Only allow a new one if there
467   // isn't a TemplateURL for the specified host, or there is one but it can
468   // be replaced. We do this to ensure that if the user assigns a different
469   // keyword to a generated TemplateURL, we won't regenerate another keyword for
470   // the same host.
471   return !url.is_valid() || url.host().empty() ||
472       CanReplaceKeywordForHost(url.host(), template_url_to_replace);
473 }
474
475 void TemplateURLService::FindMatchingKeywords(
476     const base::string16& prefix,
477     bool support_replacement_only,
478     TemplateURLVector* matches) {
479   // Sanity check args.
480   if (prefix.empty())
481     return;
482   DCHECK(matches != NULL);
483   DCHECK(matches->empty());  // The code for exact matches assumes this.
484
485   // Required for VS2010: http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
486   TemplateURL* const kNullTemplateURL = NULL;
487
488   // Find matching keyword range.  Searches the element map for keywords
489   // beginning with |prefix| and stores the endpoints of the resulting set in
490   // |match_range|.
491   const std::pair<KeywordToTemplateMap::const_iterator,
492                   KeywordToTemplateMap::const_iterator> match_range(
493       std::equal_range(
494           keyword_to_template_map_.begin(), keyword_to_template_map_.end(),
495           KeywordToTemplateMap::value_type(prefix, kNullTemplateURL),
496           LessWithPrefix()));
497
498   // Return vector of matching keywords.
499   for (KeywordToTemplateMap::const_iterator i(match_range.first);
500        i != match_range.second; ++i) {
501     if (!support_replacement_only ||
502         i->second->url_ref().SupportsReplacement(search_terms_data()))
503       matches->push_back(i->second);
504   }
505 }
506
507 TemplateURL* TemplateURLService::GetTemplateURLForKeyword(
508     const base::string16& keyword) {
509   KeywordToTemplateMap::const_iterator elem(
510       keyword_to_template_map_.find(keyword));
511   if (elem != keyword_to_template_map_.end())
512     return elem->second;
513   return (!loaded_ &&
514       initial_default_search_provider_.get() &&
515       (initial_default_search_provider_->keyword() == keyword)) ?
516       initial_default_search_provider_.get() : NULL;
517 }
518
519 TemplateURL* TemplateURLService::GetTemplateURLForGUID(
520     const std::string& sync_guid) {
521   GUIDToTemplateMap::const_iterator elem(guid_to_template_map_.find(sync_guid));
522   if (elem != guid_to_template_map_.end())
523     return elem->second;
524   return (!loaded_ &&
525       initial_default_search_provider_.get() &&
526       (initial_default_search_provider_->sync_guid() == sync_guid)) ?
527       initial_default_search_provider_.get() : NULL;
528 }
529
530 TemplateURL* TemplateURLService::GetTemplateURLForHost(
531     const std::string& host) {
532   if (loaded_)
533     return provider_map_->GetTemplateURLForHost(host);
534   TemplateURL* initial_dsp = initial_default_search_provider_.get();
535   if (!initial_dsp)
536     return NULL;
537   return (initial_dsp->GenerateSearchURL(search_terms_data()).host() == host) ?
538       initial_dsp : NULL;
539 }
540
541 bool TemplateURLService::Add(TemplateURL* template_url) {
542   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
543   if (!AddNoNotify(template_url, true))
544     return false;
545   NotifyObservers();
546   return true;
547 }
548
549 void TemplateURLService::AddWithOverrides(TemplateURL* template_url,
550                                           const base::string16& short_name,
551                                           const base::string16& keyword,
552                                           const std::string& url) {
553   DCHECK(!keyword.empty());
554   DCHECK(!url.empty());
555   template_url->data_.short_name = short_name;
556   template_url->data_.SetKeyword(keyword);
557   template_url->SetURL(url);
558   Add(template_url);
559 }
560
561 void TemplateURLService::AddExtensionControlledTURL(
562     TemplateURL* template_url,
563     scoped_ptr<TemplateURL::AssociatedExtensionInfo> info) {
564   DCHECK(loaded_);
565   DCHECK(template_url);
566   DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
567   DCHECK(info);
568   DCHECK_NE(TemplateURL::NORMAL, info->type);
569   DCHECK_EQ(info->wants_to_be_default_engine,
570             template_url->show_in_default_list());
571   DCHECK(!FindTemplateURLForExtension(info->extension_id, info->type));
572   template_url->extension_info_.swap(info);
573
574   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
575   if (AddNoNotify(template_url, true)) {
576     if (template_url->extension_info_->wants_to_be_default_engine)
577       UpdateExtensionDefaultSearchEngine();
578     NotifyObservers();
579   }
580 }
581
582 void TemplateURLService::Remove(TemplateURL* template_url) {
583   RemoveNoNotify(template_url);
584   NotifyObservers();
585 }
586
587 void TemplateURLService::RemoveExtensionControlledTURL(
588     const std::string& extension_id,
589     TemplateURL::Type type) {
590   DCHECK(loaded_);
591   TemplateURL* url = FindTemplateURLForExtension(extension_id, type);
592   if (!url)
593     return;
594   // NULL this out so that we can call RemoveNoNotify.
595   // UpdateExtensionDefaultSearchEngine will cause it to be reset.
596   if (default_search_provider_ == url)
597     default_search_provider_ = NULL;
598   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
599   RemoveNoNotify(url);
600   UpdateExtensionDefaultSearchEngine();
601   NotifyObservers();
602 }
603
604 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after) {
605   RemoveAutoGeneratedBetween(created_after, base::Time());
606 }
607
608 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after,
609                                                     base::Time created_before) {
610   RemoveAutoGeneratedForOriginBetween(GURL(), created_after, created_before);
611 }
612
613 void TemplateURLService::RemoveAutoGeneratedForOriginBetween(
614     const GURL& origin,
615     base::Time created_after,
616     base::Time created_before) {
617   GURL o(origin.GetOrigin());
618   bool should_notify = false;
619   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
620   for (size_t i = 0; i < template_urls_.size();) {
621     if (template_urls_[i]->date_created() >= created_after &&
622         (created_before.is_null() ||
623          template_urls_[i]->date_created() < created_before) &&
624         CanReplace(template_urls_[i]) &&
625         (o.is_empty() ||
626          template_urls_[i]->GenerateSearchURL(
627              search_terms_data()).GetOrigin() == o)) {
628       RemoveNoNotify(template_urls_[i]);
629       should_notify = true;
630     } else {
631       ++i;
632     }
633   }
634   if (should_notify)
635     NotifyObservers();
636 }
637
638 void TemplateURLService::RegisterOmniboxKeyword(
639      const std::string& extension_id,
640      const std::string& extension_name,
641      const std::string& keyword,
642      const std::string& template_url_string) {
643   DCHECK(loaded_);
644
645   if (FindTemplateURLForExtension(extension_id,
646                                   TemplateURL::OMNIBOX_API_EXTENSION))
647     return;
648
649   TemplateURLData data;
650   data.short_name = base::UTF8ToUTF16(extension_name);
651   data.SetKeyword(base::UTF8ToUTF16(keyword));
652   data.SetURL(template_url_string);
653   TemplateURL* url = new TemplateURL(data);
654   scoped_ptr<TemplateURL::AssociatedExtensionInfo> info(
655       new TemplateURL::AssociatedExtensionInfo(
656           TemplateURL::OMNIBOX_API_EXTENSION, extension_id));
657   AddExtensionControlledTURL(url, info.Pass());
658 }
659
660 TemplateURLService::TemplateURLVector TemplateURLService::GetTemplateURLs() {
661   return template_urls_;
662 }
663
664 void TemplateURLService::IncrementUsageCount(TemplateURL* url) {
665   DCHECK(url);
666   // Extension-controlled search engines are not persisted.
667   if (url->GetType() != TemplateURL::NORMAL)
668     return;
669   if (std::find(template_urls_.begin(), template_urls_.end(), url) ==
670       template_urls_.end())
671     return;
672   ++url->data_.usage_count;
673
674   if (web_data_service_.get())
675     web_data_service_->UpdateKeyword(url->data());
676 }
677
678 void TemplateURLService::ResetTemplateURL(TemplateURL* url,
679                                           const base::string16& title,
680                                           const base::string16& keyword,
681                                           const std::string& search_url) {
682   if (ResetTemplateURLNoNotify(url, title, keyword, search_url))
683     NotifyObservers();
684 }
685
686 bool TemplateURLService::CanMakeDefault(const TemplateURL* url) {
687   return
688       ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
689        (default_search_provider_source_ ==
690         DefaultSearchManager::FROM_FALLBACK)) &&
691       (url != GetDefaultSearchProvider()) &&
692       url->url_ref().SupportsReplacement(search_terms_data()) &&
693       (url->GetType() == TemplateURL::NORMAL);
694 }
695
696 void TemplateURLService::SetUserSelectedDefaultSearchProvider(
697     TemplateURL* url) {
698   // Omnibox keywords cannot be made default. Extension-controlled search
699   // engines can be made default only by the extension itself because they
700   // aren't persisted.
701   DCHECK(!url || (url->GetType() == TemplateURL::NORMAL));
702   if (load_failed_) {
703     // Skip the DefaultSearchManager, which will persist to user preferences.
704     if ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
705         (default_search_provider_source_ ==
706          DefaultSearchManager::FROM_FALLBACK)) {
707       ApplyDefaultSearchChange(url ? &url->data() : NULL,
708                                DefaultSearchManager::FROM_USER);
709     }
710   } else {
711     // We rely on the DefaultSearchManager to call OnDefaultSearchChange if, in
712     // fact, the effective DSE changes.
713     if (url)
714       default_search_manager_.SetUserSelectedDefaultSearchEngine(url->data());
715     else
716       default_search_manager_.ClearUserSelectedDefaultSearchEngine();
717   }
718 }
719
720 TemplateURL* TemplateURLService::GetDefaultSearchProvider() {
721   return loaded_ ?
722     default_search_provider_ : initial_default_search_provider_.get();
723 }
724
725 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
726     const GURL& url) {
727   TemplateURL* default_provider = GetDefaultSearchProvider();
728   return default_provider &&
729       default_provider->IsSearchURL(url, search_terms_data());
730 }
731
732 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
733   return default_search_provider_source_ ==
734       DefaultSearchManager::FROM_EXTENSION;
735 }
736
737 void TemplateURLService::RepairPrepopulatedSearchEngines() {
738   // Can't clean DB if it hasn't been loaded.
739   DCHECK(loaded());
740
741   if ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
742       (default_search_provider_source_ ==
743           DefaultSearchManager::FROM_FALLBACK)) {
744     // Clear |default_search_provider_| in case we want to remove the engine it
745     // points to. This will get reset at the end of the function anyway.
746     default_search_provider_ = NULL;
747   }
748
749   size_t default_search_provider_index = 0;
750   ScopedVector<TemplateURLData> prepopulated_urls =
751       TemplateURLPrepopulateData::GetPrepopulatedEngines(
752           prefs_, &default_search_provider_index);
753   DCHECK(!prepopulated_urls.empty());
754   ActionsFromPrepopulateData actions(CreateActionsFromCurrentPrepopulateData(
755       &prepopulated_urls, template_urls_, default_search_provider_));
756
757   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
758
759   // Remove items.
760   for (std::vector<TemplateURL*>::iterator i = actions.removed_engines.begin();
761        i < actions.removed_engines.end(); ++i)
762     RemoveNoNotify(*i);
763
764   // Edit items.
765   for (EditedEngines::iterator i(actions.edited_engines.begin());
766        i < actions.edited_engines.end(); ++i) {
767     TemplateURL new_values(i->second);
768     UpdateNoNotify(i->first, new_values);
769   }
770
771   // Add items.
772   for (std::vector<TemplateURLData>::const_iterator i =
773            actions.added_engines.begin();
774        i < actions.added_engines.end();
775        ++i) {
776     AddNoNotify(new TemplateURL(*i), true);
777   }
778
779   base::AutoReset<DefaultSearchChangeOrigin> change_origin(
780       &dsp_change_origin_, DSP_CHANGE_PROFILE_RESET);
781
782   default_search_manager_.ClearUserSelectedDefaultSearchEngine();
783
784   if (!default_search_provider_) {
785     // If the default search provider came from a user pref we would have been
786     // notified of the new (fallback-provided) value in
787     // ClearUserSelectedDefaultSearchEngine() above. Since we are here, the
788     // value was presumably originally a fallback value (which may have been
789     // repaired).
790     DefaultSearchManager::Source source;
791     const TemplateURLData* new_dse =
792         default_search_manager_.GetDefaultSearchEngine(&source);
793     // ApplyDefaultSearchChange will notify observers once it is done.
794     ApplyDefaultSearchChange(new_dse, source);
795   } else {
796     NotifyObservers();
797   }
798 }
799
800 void TemplateURLService::AddObserver(TemplateURLServiceObserver* observer) {
801   model_observers_.AddObserver(observer);
802 }
803
804 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver* observer) {
805   model_observers_.RemoveObserver(observer);
806 }
807
808 void TemplateURLService::Load() {
809   if (loaded_ || load_handle_)
810     return;
811
812   if (web_data_service_.get())
813     load_handle_ = web_data_service_->GetKeywords(this);
814   else
815     ChangeToLoadedState();
816 }
817
818 scoped_ptr<TemplateURLService::Subscription>
819     TemplateURLService::RegisterOnLoadedCallback(
820         const base::Closure& callback) {
821   return loaded_ ?
822       scoped_ptr<TemplateURLService::Subscription>() :
823       on_loaded_callbacks_.Add(callback);
824 }
825
826 void TemplateURLService::OnWebDataServiceRequestDone(
827     KeywordWebDataService::Handle h,
828     const WDTypedResult* result) {
829   // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
830   tracked_objects::ScopedTracker tracking_profile(
831       FROM_HERE_WITH_EXPLICIT_FUNCTION(
832           "422460 TemplateURLService::OnWebDataServiceRequestDone"));
833
834   // Reset the load_handle so that we don't try and cancel the load in
835   // the destructor.
836   load_handle_ = 0;
837
838   if (!result) {
839     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
840     tracked_objects::ScopedTracker tracking_profile1(
841         FROM_HERE_WITH_EXPLICIT_FUNCTION(
842             "422460 TemplateURLService::OnWebDataServiceRequestDone 1"));
843
844     // Results are null if the database went away or (most likely) wasn't
845     // loaded.
846     load_failed_ = true;
847     web_data_service_ = NULL;
848     ChangeToLoadedState();
849     return;
850   }
851
852   TemplateURLVector template_urls;
853   int new_resource_keyword_version = 0;
854   {
855     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
856     tracked_objects::ScopedTracker tracking_profile2(
857         FROM_HERE_WITH_EXPLICIT_FUNCTION(
858             "422460 TemplateURLService::OnWebDataServiceRequestDone 2"));
859
860     GetSearchProvidersUsingKeywordResult(
861         *result,
862         web_data_service_.get(),
863         prefs_,
864         &template_urls,
865         (default_search_provider_source_ == DefaultSearchManager::FROM_USER)
866             ? initial_default_search_provider_.get()
867             : NULL,
868         search_terms_data(),
869         &new_resource_keyword_version,
870         &pre_sync_deletes_);
871   }
872
873   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
874
875   {
876     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
877     tracked_objects::ScopedTracker tracking_profile4(
878         FROM_HERE_WITH_EXPLICIT_FUNCTION(
879             "422460 TemplateURLService::OnWebDataServiceRequestDone 4"));
880
881     PatchMissingSyncGUIDs(&template_urls);
882
883     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
884     tracked_objects::ScopedTracker tracking_profile41(
885         FROM_HERE_WITH_EXPLICIT_FUNCTION(
886             "422460 TemplateURLService::OnWebDataServiceRequestDone 41"));
887
888     SetTemplateURLs(&template_urls);
889
890     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
891     tracked_objects::ScopedTracker tracking_profile42(
892         FROM_HERE_WITH_EXPLICIT_FUNCTION(
893             "422460 TemplateURLService::OnWebDataServiceRequestDone 42"));
894
895     // This initializes provider_map_ which should be done before
896     // calling UpdateKeywordSearchTermsForURL.
897     // This also calls NotifyObservers.
898     ChangeToLoadedState();
899
900     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
901     tracked_objects::ScopedTracker tracking_profile43(
902         FROM_HERE_WITH_EXPLICIT_FUNCTION(
903             "422460 TemplateURLService::OnWebDataServiceRequestDone 43"));
904
905     // Index any visits that occurred before we finished loading.
906     for (size_t i = 0; i < visits_to_add_.size(); ++i)
907       UpdateKeywordSearchTermsForURL(visits_to_add_[i]);
908     visits_to_add_.clear();
909
910     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
911     tracked_objects::ScopedTracker tracking_profile44(
912         FROM_HERE_WITH_EXPLICIT_FUNCTION(
913             "422460 TemplateURLService::OnWebDataServiceRequestDone 44"));
914
915     if (new_resource_keyword_version)
916       web_data_service_->SetBuiltinKeywordVersion(new_resource_keyword_version);
917   }
918
919   if (default_search_provider_) {
920     // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
921     tracked_objects::ScopedTracker tracking_profile5(
922         FROM_HERE_WITH_EXPLICIT_FUNCTION(
923             "422460 TemplateURLService::OnWebDataServiceRequestDone 5"));
924
925     UMA_HISTOGRAM_ENUMERATION(
926         "Search.DefaultSearchProviderType",
927         TemplateURLPrepopulateData::GetEngineType(
928             *default_search_provider_, search_terms_data()),
929         SEARCH_ENGINE_MAX);
930
931     if (rappor_service_) {
932       rappor_service_->RecordSample(
933           "Search.DefaultSearchProvider",
934           rappor::ETLD_PLUS_ONE_RAPPOR_TYPE,
935           net::registry_controlled_domains::GetDomainAndRegistry(
936               default_search_provider_->url_ref().GetHost(search_terms_data()),
937               net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES));
938     }
939   }
940 }
941
942 base::string16 TemplateURLService::GetKeywordShortName(
943     const base::string16& keyword,
944     bool* is_omnibox_api_extension_keyword) {
945   const TemplateURL* template_url = GetTemplateURLForKeyword(keyword);
946
947   // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
948   // to track changes to the model, this should become a DCHECK.
949   if (template_url) {
950     *is_omnibox_api_extension_keyword =
951         template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
952     return template_url->AdjustedShortNameForLocaleDirection();
953   }
954   *is_omnibox_api_extension_keyword = false;
955   return base::string16();
956 }
957
958 void TemplateURLService::OnHistoryURLVisited(const URLVisitedDetails& details) {
959   if (!loaded_)
960     visits_to_add_.push_back(details);
961   else
962     UpdateKeywordSearchTermsForURL(details);
963 }
964
965 void TemplateURLService::Shutdown() {
966   if (client_)
967     client_->Shutdown();
968   // This check has to be done at Shutdown() instead of in the dtor to ensure
969   // that no clients of KeywordWebDataService are holding ptrs to it after the
970   // first phase of the KeyedService Shutdown() process.
971   if (load_handle_) {
972     DCHECK(web_data_service_.get());
973     web_data_service_->CancelRequest(load_handle_);
974   }
975   web_data_service_ = NULL;
976 }
977
978 syncer::SyncDataList TemplateURLService::GetAllSyncData(
979     syncer::ModelType type) const {
980   DCHECK_EQ(syncer::SEARCH_ENGINES, type);
981
982   syncer::SyncDataList current_data;
983   for (TemplateURLVector::const_iterator iter = template_urls_.begin();
984       iter != template_urls_.end(); ++iter) {
985     // We don't sync keywords managed by policy.
986     if ((*iter)->created_by_policy())
987       continue;
988     // We don't sync extension-controlled search engines.
989     if ((*iter)->GetType() != TemplateURL::NORMAL)
990       continue;
991     current_data.push_back(CreateSyncDataFromTemplateURL(**iter));
992   }
993
994   return current_data;
995 }
996
997 syncer::SyncError TemplateURLService::ProcessSyncChanges(
998     const tracked_objects::Location& from_here,
999     const syncer::SyncChangeList& change_list) {
1000   if (!models_associated_) {
1001     syncer::SyncError error(FROM_HERE,
1002                             syncer::SyncError::DATATYPE_ERROR,
1003                             "Models not yet associated.",
1004                             syncer::SEARCH_ENGINES);
1005     return error;
1006   }
1007   DCHECK(loaded_);
1008
1009   base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
1010
1011   // We've started syncing, so set our origin member to the base Sync value.
1012   // As we move through Sync Code, we may set this to increasingly specific
1013   // origins so we can tell what exactly caused a DSP change.
1014   base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
1015       DSP_CHANGE_SYNC_UNINTENTIONAL);
1016
1017   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1018
1019   syncer::SyncChangeList new_changes;
1020   syncer::SyncError error;
1021   for (syncer::SyncChangeList::const_iterator iter = change_list.begin();
1022        iter != change_list.end(); ++iter) {
1023     DCHECK_EQ(syncer::SEARCH_ENGINES, iter->sync_data().GetDataType());
1024
1025     std::string guid =
1026         iter->sync_data().GetSpecifics().search_engine().sync_guid();
1027     TemplateURL* existing_turl = GetTemplateURLForGUID(guid);
1028     scoped_ptr<TemplateURL> turl(CreateTemplateURLFromTemplateURLAndSyncData(
1029         client_.get(), prefs_, search_terms_data(), existing_turl,
1030         iter->sync_data(), &new_changes));
1031     if (!turl.get())
1032       continue;
1033
1034     // Explicitly don't check for conflicts against extension keywords; in this
1035     // case the functions which modify the keyword map know how to handle the
1036     // conflicts.
1037     // TODO(mpcomplete): If we allow editing extension keywords, then those will
1038     // need to undergo conflict resolution.
1039     TemplateURL* existing_keyword_turl =
1040         FindNonExtensionTemplateURLForKeyword(turl->keyword());
1041     if (iter->change_type() == syncer::SyncChange::ACTION_DELETE) {
1042       if (!existing_turl) {
1043         error = sync_error_factory_->CreateAndUploadError(
1044             FROM_HERE,
1045             "ProcessSyncChanges failed on ChangeType ACTION_DELETE");
1046         continue;
1047       }
1048       if (existing_turl == GetDefaultSearchProvider()) {
1049         // The only way Sync can attempt to delete the default search provider
1050         // is if we had changed the kSyncedDefaultSearchProviderGUID
1051         // preference, but perhaps it has not yet been received. To avoid
1052         // situations where this has come in erroneously, we will un-delete
1053         // the current default search from the Sync data. If the pref really
1054         // does arrive later, then default search will change to the correct
1055         // entry, but we'll have this extra entry sitting around. The result is
1056         // not ideal, but it prevents a far more severe bug where the default is
1057         // unexpectedly swapped to something else. The user can safely delete
1058         // the extra entry again later, if they choose. Most users who do not
1059         // look at the search engines UI will not notice this.
1060         // Note that we append a special character to the end of the keyword in
1061         // an attempt to avoid a ping-poinging situation where receiving clients
1062         // may try to continually delete the resurrected entry.
1063         base::string16 updated_keyword = UniquifyKeyword(*existing_turl, true);
1064         TemplateURLData data(existing_turl->data());
1065         data.SetKeyword(updated_keyword);
1066         TemplateURL new_turl(data);
1067         if (UpdateNoNotify(existing_turl, new_turl))
1068           NotifyObservers();
1069
1070         syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(new_turl);
1071         new_changes.push_back(syncer::SyncChange(FROM_HERE,
1072                                                  syncer::SyncChange::ACTION_ADD,
1073                                                  sync_data));
1074         // Ignore the delete attempt. This means we never end up resetting the
1075         // default search provider due to an ACTION_DELETE from sync.
1076         continue;
1077       }
1078
1079       Remove(existing_turl);
1080     } else if (iter->change_type() == syncer::SyncChange::ACTION_ADD) {
1081       if (existing_turl) {
1082         error = sync_error_factory_->CreateAndUploadError(
1083             FROM_HERE,
1084             "ProcessSyncChanges failed on ChangeType ACTION_ADD");
1085         continue;
1086       }
1087       const std::string guid = turl->sync_guid();
1088       if (existing_keyword_turl) {
1089         // Resolve any conflicts so we can safely add the new entry.
1090         ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1091                                    &new_changes);
1092       }
1093       base::AutoReset<DefaultSearchChangeOrigin> change_origin(
1094           &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
1095       // Force the local ID to kInvalidTemplateURLID so we can add it.
1096       TemplateURLData data(turl->data());
1097       data.id = kInvalidTemplateURLID;
1098       TemplateURL* added = new TemplateURL(data);
1099       if (Add(added))
1100         MaybeUpdateDSEAfterSync(added);
1101     } else if (iter->change_type() == syncer::SyncChange::ACTION_UPDATE) {
1102       if (!existing_turl) {
1103         error = sync_error_factory_->CreateAndUploadError(
1104             FROM_HERE,
1105             "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
1106         continue;
1107       }
1108       if (existing_keyword_turl && (existing_keyword_turl != existing_turl)) {
1109         // Resolve any conflicts with other entries so we can safely update the
1110         // keyword.
1111         ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1112                                    &new_changes);
1113       }
1114       if (UpdateNoNotify(existing_turl, *turl)) {
1115         NotifyObservers();
1116         MaybeUpdateDSEAfterSync(existing_turl);
1117       }
1118     } else {
1119       // We've unexpectedly received an ACTION_INVALID.
1120       error = sync_error_factory_->CreateAndUploadError(
1121           FROM_HERE,
1122           "ProcessSyncChanges received an ACTION_INVALID");
1123     }
1124   }
1125
1126   // If something went wrong, we want to prematurely exit to avoid pushing
1127   // inconsistent data to Sync. We return the last error we received.
1128   if (error.IsSet())
1129     return error;
1130
1131   error = sync_processor_->ProcessSyncChanges(from_here, new_changes);
1132
1133   return error;
1134 }
1135
1136 syncer::SyncMergeResult TemplateURLService::MergeDataAndStartSyncing(
1137     syncer::ModelType type,
1138     const syncer::SyncDataList& initial_sync_data,
1139     scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
1140     scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) {
1141   DCHECK(loaded_);
1142   DCHECK_EQ(type, syncer::SEARCH_ENGINES);
1143   DCHECK(!sync_processor_.get());
1144   DCHECK(sync_processor.get());
1145   DCHECK(sync_error_factory.get());
1146   syncer::SyncMergeResult merge_result(type);
1147
1148   // Disable sync if we failed to load.
1149   if (load_failed_) {
1150     merge_result.set_error(syncer::SyncError(
1151         FROM_HERE, syncer::SyncError::DATATYPE_ERROR,
1152         "Local database load failed.", syncer::SEARCH_ENGINES));
1153     return merge_result;
1154   }
1155
1156   sync_processor_ = sync_processor.Pass();
1157   sync_error_factory_ = sync_error_factory.Pass();
1158
1159   // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
1160   // don't step on our own toes.
1161   base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
1162
1163   // We've started syncing, so set our origin member to the base Sync value.
1164   // As we move through Sync Code, we may set this to increasingly specific
1165   // origins so we can tell what exactly caused a DSP change.
1166   base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
1167       DSP_CHANGE_SYNC_UNINTENTIONAL);
1168
1169   syncer::SyncChangeList new_changes;
1170
1171   // Build maps of our sync GUIDs to syncer::SyncData.
1172   SyncDataMap local_data_map = CreateGUIDToSyncDataMap(
1173       GetAllSyncData(syncer::SEARCH_ENGINES));
1174   SyncDataMap sync_data_map = CreateGUIDToSyncDataMap(initial_sync_data);
1175
1176   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1177
1178   merge_result.set_num_items_before_association(local_data_map.size());
1179   for (SyncDataMap::const_iterator iter = sync_data_map.begin();
1180       iter != sync_data_map.end(); ++iter) {
1181     TemplateURL* local_turl = GetTemplateURLForGUID(iter->first);
1182     scoped_ptr<TemplateURL> sync_turl(
1183         CreateTemplateURLFromTemplateURLAndSyncData(
1184             client_.get(), prefs_, search_terms_data(), local_turl,
1185             iter->second, &new_changes));
1186     if (!sync_turl.get())
1187       continue;
1188
1189     if (pre_sync_deletes_.find(sync_turl->sync_guid()) !=
1190         pre_sync_deletes_.end()) {
1191       // This entry was deleted before the initial sync began (possibly through
1192       // preprocessing in TemplateURLService's loading code). Ignore it and send
1193       // an ACTION_DELETE up to the server.
1194       new_changes.push_back(
1195           syncer::SyncChange(FROM_HERE,
1196                              syncer::SyncChange::ACTION_DELETE,
1197                              iter->second));
1198       UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1199           DELETE_ENGINE_PRE_SYNC, DELETE_ENGINE_MAX);
1200       continue;
1201     }
1202
1203     if (local_turl) {
1204       DCHECK(IsFromSync(local_turl, sync_data_map));
1205       // This local search engine is already synced. If the timestamp differs
1206       // from Sync, we need to update locally or to the cloud. Note that if the
1207       // timestamps are equal, we touch neither.
1208       if (sync_turl->last_modified() > local_turl->last_modified()) {
1209         // We've received an update from Sync. We should replace all synced
1210         // fields in the local TemplateURL. Note that this includes the
1211         // TemplateURLID and the TemplateURL may have to be reparsed. This
1212         // also makes the local data's last_modified timestamp equal to Sync's,
1213         // avoiding an Update on the next MergeData call.
1214         if (UpdateNoNotify(local_turl, *sync_turl))
1215           NotifyObservers();
1216         merge_result.set_num_items_modified(
1217             merge_result.num_items_modified() + 1);
1218       } else if (sync_turl->last_modified() < local_turl->last_modified()) {
1219         // Otherwise, we know we have newer data, so update Sync with our
1220         // data fields.
1221         new_changes.push_back(
1222             syncer::SyncChange(FROM_HERE,
1223                                syncer::SyncChange::ACTION_UPDATE,
1224                                local_data_map[local_turl->sync_guid()]));
1225       }
1226       local_data_map.erase(iter->first);
1227     } else {
1228       // The search engine from the cloud has not been synced locally. Merge it
1229       // into our local model. This will handle any conflicts with local (and
1230       // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1231       // over not-yet-synced TemplateURLs.
1232       MergeInSyncTemplateURL(sync_turl.get(), sync_data_map, &new_changes,
1233                              &local_data_map, &merge_result);
1234     }
1235   }
1236
1237   // The remaining SyncData in local_data_map should be everything that needs to
1238   // be pushed as ADDs to sync.
1239   for (SyncDataMap::const_iterator iter = local_data_map.begin();
1240       iter != local_data_map.end(); ++iter) {
1241     new_changes.push_back(
1242         syncer::SyncChange(FROM_HERE,
1243                            syncer::SyncChange::ACTION_ADD,
1244                            iter->second));
1245   }
1246
1247   // Do some post-processing on the change list to ensure that we are sending
1248   // valid changes to sync_processor_.
1249   PruneSyncChanges(&sync_data_map, &new_changes);
1250
1251   LogDuplicatesHistogram(GetTemplateURLs());
1252   merge_result.set_num_items_after_association(
1253       GetAllSyncData(syncer::SEARCH_ENGINES).size());
1254   merge_result.set_error(
1255       sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
1256   if (merge_result.error().IsSet())
1257     return merge_result;
1258
1259   // The ACTION_DELETEs from this set are processed. Empty it so we don't try to
1260   // reuse them on the next call to MergeDataAndStartSyncing.
1261   pre_sync_deletes_.clear();
1262
1263   models_associated_ = true;
1264   return merge_result;
1265 }
1266
1267 void TemplateURLService::StopSyncing(syncer::ModelType type) {
1268   DCHECK_EQ(type, syncer::SEARCH_ENGINES);
1269   models_associated_ = false;
1270   sync_processor_.reset();
1271   sync_error_factory_.reset();
1272 }
1273
1274 void TemplateURLService::ProcessTemplateURLChange(
1275     const tracked_objects::Location& from_here,
1276     const TemplateURL* turl,
1277     syncer::SyncChange::SyncChangeType type) {
1278   DCHECK_NE(type, syncer::SyncChange::ACTION_INVALID);
1279   DCHECK(turl);
1280
1281   if (!models_associated_)
1282     return;  // Not syncing.
1283
1284   if (processing_syncer_changes_)
1285     return;  // These are changes originating from us. Ignore.
1286
1287   // Avoid syncing keywords managed by policy.
1288   if (turl->created_by_policy())
1289     return;
1290
1291   // Avoid syncing extension-controlled search engines.
1292   if (turl->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)
1293     return;
1294
1295   syncer::SyncChangeList changes;
1296
1297   syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1298   changes.push_back(syncer::SyncChange(from_here,
1299                                        type,
1300                                        sync_data));
1301
1302   sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
1303 }
1304
1305 // static
1306 syncer::SyncData TemplateURLService::CreateSyncDataFromTemplateURL(
1307     const TemplateURL& turl) {
1308   sync_pb::EntitySpecifics specifics;
1309   sync_pb::SearchEngineSpecifics* se_specifics =
1310       specifics.mutable_search_engine();
1311   se_specifics->set_short_name(base::UTF16ToUTF8(turl.short_name()));
1312   se_specifics->set_keyword(base::UTF16ToUTF8(turl.keyword()));
1313   se_specifics->set_favicon_url(turl.favicon_url().spec());
1314   se_specifics->set_url(turl.url());
1315   se_specifics->set_safe_for_autoreplace(turl.safe_for_autoreplace());
1316   se_specifics->set_originating_url(turl.originating_url().spec());
1317   se_specifics->set_date_created(turl.date_created().ToInternalValue());
1318   se_specifics->set_input_encodings(JoinString(turl.input_encodings(), ';'));
1319   se_specifics->set_show_in_default_list(turl.show_in_default_list());
1320   se_specifics->set_suggestions_url(turl.suggestions_url());
1321   se_specifics->set_prepopulate_id(turl.prepopulate_id());
1322   se_specifics->set_instant_url(turl.instant_url());
1323   if (!turl.image_url().empty())
1324     se_specifics->set_image_url(turl.image_url());
1325   se_specifics->set_new_tab_url(turl.new_tab_url());
1326   if (!turl.search_url_post_params().empty())
1327     se_specifics->set_search_url_post_params(turl.search_url_post_params());
1328   if (!turl.suggestions_url_post_params().empty()) {
1329     se_specifics->set_suggestions_url_post_params(
1330         turl.suggestions_url_post_params());
1331   }
1332   if (!turl.instant_url_post_params().empty())
1333     se_specifics->set_instant_url_post_params(turl.instant_url_post_params());
1334   if (!turl.image_url_post_params().empty())
1335     se_specifics->set_image_url_post_params(turl.image_url_post_params());
1336   se_specifics->set_last_modified(turl.last_modified().ToInternalValue());
1337   se_specifics->set_sync_guid(turl.sync_guid());
1338   for (size_t i = 0; i < turl.alternate_urls().size(); ++i)
1339     se_specifics->add_alternate_urls(turl.alternate_urls()[i]);
1340   se_specifics->set_search_terms_replacement_key(
1341       turl.search_terms_replacement_key());
1342
1343   return syncer::SyncData::CreateLocalData(se_specifics->sync_guid(),
1344                                            se_specifics->keyword(),
1345                                            specifics);
1346 }
1347
1348 // static
1349 scoped_ptr<TemplateURL>
1350 TemplateURLService::CreateTemplateURLFromTemplateURLAndSyncData(
1351     TemplateURLServiceClient* client,
1352     PrefService* prefs,
1353     const SearchTermsData& search_terms_data,
1354     TemplateURL* existing_turl,
1355     const syncer::SyncData& sync_data,
1356     syncer::SyncChangeList* change_list) {
1357   DCHECK(change_list);
1358
1359   sync_pb::SearchEngineSpecifics specifics =
1360       sync_data.GetSpecifics().search_engine();
1361
1362   // Past bugs might have caused either of these fields to be empty.  Just
1363   // delete this data off the server.
1364   if (specifics.url().empty() || specifics.sync_guid().empty()) {
1365     change_list->push_back(
1366         syncer::SyncChange(FROM_HERE,
1367                            syncer::SyncChange::ACTION_DELETE,
1368                            sync_data));
1369     UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
1370         DELETE_ENGINE_EMPTY_FIELD, DELETE_ENGINE_MAX);
1371     return NULL;
1372   }
1373
1374   TemplateURLData data(existing_turl ?
1375       existing_turl->data() : TemplateURLData());
1376   data.short_name = base::UTF8ToUTF16(specifics.short_name());
1377   data.originating_url = GURL(specifics.originating_url());
1378   base::string16 keyword(base::UTF8ToUTF16(specifics.keyword()));
1379   // NOTE: Once this code has shipped in a couple of stable releases, we can
1380   // probably remove the migration portion, comment out the
1381   // "autogenerate_keyword" field entirely in the .proto file, and fold the
1382   // empty keyword case into the "delete data" block above.
1383   bool reset_keyword =
1384       specifics.autogenerate_keyword() || specifics.keyword().empty();
1385   if (reset_keyword)
1386     keyword = base::ASCIIToUTF16("dummy");  // Will be replaced below.
1387   DCHECK(!keyword.empty());
1388   data.SetKeyword(keyword);
1389   data.SetURL(specifics.url());
1390   data.suggestions_url = specifics.suggestions_url();
1391   data.instant_url = specifics.instant_url();
1392   data.image_url = specifics.image_url();
1393   data.new_tab_url = specifics.new_tab_url();
1394   data.search_url_post_params = specifics.search_url_post_params();
1395   data.suggestions_url_post_params = specifics.suggestions_url_post_params();
1396   data.instant_url_post_params = specifics.instant_url_post_params();
1397   data.image_url_post_params = specifics.image_url_post_params();
1398   data.favicon_url = GURL(specifics.favicon_url());
1399   data.show_in_default_list = specifics.show_in_default_list();
1400   data.safe_for_autoreplace = specifics.safe_for_autoreplace();
1401   base::SplitString(specifics.input_encodings(), ';', &data.input_encodings);
1402   // If the server data has duplicate encodings, we'll want to push an update
1403   // below to correct it.  Note that we also fix this in
1404   // GetSearchProvidersUsingKeywordResult(), since otherwise we'd never correct
1405   // local problems for clients which have disabled search engine sync.
1406   bool deduped = DeDupeEncodings(&data.input_encodings);
1407   data.date_created = base::Time::FromInternalValue(specifics.date_created());
1408   data.last_modified = base::Time::FromInternalValue(specifics.last_modified());
1409   data.prepopulate_id = specifics.prepopulate_id();
1410   data.sync_guid = specifics.sync_guid();
1411   data.alternate_urls.clear();
1412   for (int i = 0; i < specifics.alternate_urls_size(); ++i)
1413     data.alternate_urls.push_back(specifics.alternate_urls(i));
1414   data.search_terms_replacement_key = specifics.search_terms_replacement_key();
1415
1416   scoped_ptr<TemplateURL> turl(new TemplateURL(data));
1417   // If this TemplateURL matches a built-in prepopulated template URL, it's
1418   // possible that sync is trying to modify fields that should not be touched.
1419   // Revert these fields to the built-in values.
1420   UpdateTemplateURLIfPrepopulated(turl.get(), prefs);
1421
1422   // We used to sync keywords associated with omnibox extensions, but no longer
1423   // want to.  However, if we delete these keywords from sync, we'll break any
1424   // synced old versions of Chrome which were relying on them.  Instead, for now
1425   // we simply ignore these.
1426   // TODO(vasilii): After a few Chrome versions, change this to go ahead and
1427   // delete these from sync.
1428   DCHECK(client);
1429   client->RestoreExtensionInfoIfNecessary(turl.get());
1430   if (turl->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)
1431     return NULL;
1432
1433   DCHECK_EQ(TemplateURL::NORMAL, turl->GetType());
1434   if (reset_keyword || deduped) {
1435     if (reset_keyword)
1436       turl->ResetKeywordIfNecessary(search_terms_data, true);
1437     syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*turl);
1438     change_list->push_back(syncer::SyncChange(FROM_HERE,
1439                                               syncer::SyncChange::ACTION_UPDATE,
1440                                               sync_data));
1441   } else if (turl->IsGoogleSearchURLWithReplaceableKeyword(search_terms_data)) {
1442     if (!existing_turl) {
1443       // We're adding a new TemplateURL that uses the Google base URL, so set
1444       // its keyword appropriately for the local environment.
1445       turl->ResetKeywordIfNecessary(search_terms_data, false);
1446     } else if (existing_turl->IsGoogleSearchURLWithReplaceableKeyword(
1447         search_terms_data)) {
1448       // Ignore keyword changes triggered by the Google base URL changing on
1449       // another client.  If the base URL changes in this client as well, we'll
1450       // pick that up separately at the appropriate time.  Otherwise, changing
1451       // the keyword here could result in having the wrong keyword for the local
1452       // environment.
1453       turl->data_.SetKeyword(existing_turl->keyword());
1454     }
1455   }
1456
1457   return turl.Pass();
1458 }
1459
1460 // static
1461 SyncDataMap TemplateURLService::CreateGUIDToSyncDataMap(
1462     const syncer::SyncDataList& sync_data) {
1463   SyncDataMap data_map;
1464   for (syncer::SyncDataList::const_iterator i(sync_data.begin());
1465        i != sync_data.end();
1466        ++i)
1467     data_map[i->GetSpecifics().search_engine().sync_guid()] = *i;
1468   return data_map;
1469 }
1470
1471 void TemplateURLService::Init(const Initializer* initializers,
1472                               int num_initializers) {
1473   if (client_)
1474     client_->SetOwner(this);
1475
1476   // GoogleURLTracker is not created in tests.
1477   if (google_url_tracker_) {
1478     google_url_updated_subscription_ =
1479         google_url_tracker_->RegisterCallback(base::Bind(
1480             &TemplateURLService::GoogleBaseURLChanged, base::Unretained(this)));
1481   }
1482
1483   if (prefs_) {
1484     pref_change_registrar_.Init(prefs_);
1485     pref_change_registrar_.Add(
1486         prefs::kSyncedDefaultSearchProviderGUID,
1487         base::Bind(
1488             &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged,
1489             base::Unretained(this)));
1490   }
1491
1492   DefaultSearchManager::Source source = DefaultSearchManager::FROM_USER;
1493   TemplateURLData* dse =
1494       default_search_manager_.GetDefaultSearchEngine(&source);
1495   ApplyDefaultSearchChange(dse, source);
1496
1497   if (num_initializers > 0) {
1498     // This path is only hit by test code and is used to simulate a loaded
1499     // TemplateURLService.
1500     ChangeToLoadedState();
1501
1502     // Add specific initializers, if any.
1503     KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1504     for (int i(0); i < num_initializers; ++i) {
1505       DCHECK(initializers[i].keyword);
1506       DCHECK(initializers[i].url);
1507       DCHECK(initializers[i].content);
1508
1509       // TemplateURLService ends up owning the TemplateURL, don't try and free
1510       // it.
1511       TemplateURLData data;
1512       data.short_name = base::UTF8ToUTF16(initializers[i].content);
1513       data.SetKeyword(base::UTF8ToUTF16(initializers[i].keyword));
1514       data.SetURL(initializers[i].url);
1515       TemplateURL* template_url = new TemplateURL(data);
1516       AddNoNotify(template_url, true);
1517
1518       // Set the first provided identifier to be the default.
1519       if (i == 0)
1520         default_search_manager_.SetUserSelectedDefaultSearchEngine(data);
1521     }
1522   }
1523
1524   // Request a server check for the correct Google URL if Google is the
1525   // default search engine.
1526   RequestGoogleURLTrackerServerCheckIfNecessary();
1527 }
1528
1529 void TemplateURLService::RemoveFromMaps(TemplateURL* template_url) {
1530   const base::string16& keyword = template_url->keyword();
1531   DCHECK_NE(0U, keyword_to_template_map_.count(keyword));
1532   if (keyword_to_template_map_[keyword] == template_url) {
1533     // We need to check whether the keyword can now be provided by another
1534     // TemplateURL.  See the comments in AddToMaps() for more information on
1535     // extension keywords and how they can coexist with non-extension keywords.
1536     // In the case of more than one extension, we use the most recently
1537     // installed (which will be the most recently added, which will have the
1538     // highest ID).
1539     TemplateURL* best_fallback = NULL;
1540     for (TemplateURLVector::const_iterator i(template_urls_.begin());
1541          i != template_urls_.end(); ++i) {
1542       TemplateURL* turl = *i;
1543       // This next statement relies on the fact that there can only be one
1544       // non-Omnibox API TemplateURL with a given keyword.
1545       if ((turl != template_url) && (turl->keyword() == keyword) &&
1546           (!best_fallback ||
1547            (best_fallback->GetType() != TemplateURL::OMNIBOX_API_EXTENSION) ||
1548            ((turl->GetType() == TemplateURL::OMNIBOX_API_EXTENSION) &&
1549             (turl->id() > best_fallback->id()))))
1550         best_fallback = turl;
1551     }
1552     if (best_fallback)
1553       keyword_to_template_map_[keyword] = best_fallback;
1554     else
1555       keyword_to_template_map_.erase(keyword);
1556   }
1557
1558   if (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)
1559     return;
1560
1561   if (!template_url->sync_guid().empty())
1562     guid_to_template_map_.erase(template_url->sync_guid());
1563   // |provider_map_| is only initialized after loading has completed.
1564   if (loaded_) {
1565     provider_map_->Remove(template_url);
1566   }
1567 }
1568
1569 void TemplateURLService::AddToMaps(TemplateURL* template_url) {
1570   bool template_url_is_omnibox_api =
1571       template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1572   const base::string16& keyword = template_url->keyword();
1573   KeywordToTemplateMap::const_iterator i =
1574       keyword_to_template_map_.find(keyword);
1575   if (i == keyword_to_template_map_.end()) {
1576     keyword_to_template_map_[keyword] = template_url;
1577   } else {
1578     const TemplateURL* existing_url = i->second;
1579     // We should only have overlapping keywords when at least one comes from
1580     // an extension.  In that case, the ranking order is:
1581     //   Manually-modified keywords > extension keywords > replaceable keywords
1582     // When there are multiple extensions, the last-added wins.
1583     bool existing_url_is_omnibox_api =
1584         existing_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1585     DCHECK(existing_url_is_omnibox_api || template_url_is_omnibox_api);
1586     if (existing_url_is_omnibox_api ?
1587         !CanReplace(template_url) : CanReplace(existing_url))
1588       keyword_to_template_map_[keyword] = template_url;
1589   }
1590
1591   if (template_url_is_omnibox_api)
1592     return;
1593
1594   if (!template_url->sync_guid().empty())
1595     guid_to_template_map_[template_url->sync_guid()] = template_url;
1596   // |provider_map_| is only initialized after loading has completed.
1597   if (loaded_)
1598     provider_map_->Add(template_url, search_terms_data());
1599 }
1600
1601 // Helper for partition() call in next function.
1602 bool HasValidID(TemplateURL* t_url) {
1603   return t_url->id() != kInvalidTemplateURLID;
1604 }
1605
1606 void TemplateURLService::SetTemplateURLs(TemplateURLVector* urls) {
1607   // Partition the URLs first, instead of implementing the loops below by simply
1608   // scanning the input twice.  While it's not supposed to happen normally, it's
1609   // possible for corrupt databases to return multiple entries with the same
1610   // keyword.  In this case, the first loop may delete the first entry when
1611   // adding the second.  If this happens, the second loop must not attempt to
1612   // access the deleted entry.  Partitioning ensures this constraint.
1613   TemplateURLVector::iterator first_invalid(
1614       std::partition(urls->begin(), urls->end(), HasValidID));
1615
1616   // First, add the items that already have id's, so that the next_id_ gets
1617   // properly set.
1618   for (TemplateURLVector::const_iterator i = urls->begin(); i != first_invalid;
1619        ++i) {
1620     next_id_ = std::max(next_id_, (*i)->id());
1621     AddNoNotify(*i, false);
1622   }
1623
1624   // Next add the new items that don't have id's.
1625   for (TemplateURLVector::const_iterator i = first_invalid; i != urls->end();
1626        ++i)
1627     AddNoNotify(*i, true);
1628
1629   // Clear the input vector to reduce the chance callers will try to use a
1630   // (possibly deleted) entry.
1631   urls->clear();
1632 }
1633
1634 void TemplateURLService::ChangeToLoadedState() {
1635   // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
1636   tracked_objects::ScopedTracker tracking_profile1(
1637       FROM_HERE_WITH_EXPLICIT_FUNCTION(
1638           "422460 TemplateURLService::ChangeToLoadedState 1"));
1639
1640   DCHECK(!loaded_);
1641
1642   provider_map_->Init(template_urls_, search_terms_data());
1643   loaded_ = true;
1644
1645   // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
1646   tracked_objects::ScopedTracker tracking_profile2(
1647       FROM_HERE_WITH_EXPLICIT_FUNCTION(
1648           "422460 TemplateURLService::ChangeToLoadedState 2"));
1649
1650   // This will cause a call to NotifyObservers().
1651   ApplyDefaultSearchChangeNoMetrics(
1652       initial_default_search_provider_ ?
1653           &initial_default_search_provider_->data() : NULL,
1654       default_search_provider_source_);
1655   initial_default_search_provider_.reset();
1656
1657   // TODO(vadimt): Remove ScopedTracker below once crbug.com/422460 is fixed.
1658   tracked_objects::ScopedTracker tracking_profile3(
1659       FROM_HERE_WITH_EXPLICIT_FUNCTION(
1660           "422460 TemplateURLService::ChangeToLoadedState 3"));
1661
1662   on_loaded_callbacks_.Notify();
1663 }
1664
1665 bool TemplateURLService::CanReplaceKeywordForHost(
1666     const std::string& host,
1667     TemplateURL** to_replace) {
1668   DCHECK(!to_replace || !*to_replace);
1669   const TemplateURLSet* urls = provider_map_->GetURLsForHost(host);
1670   if (!urls)
1671     return true;
1672   for (TemplateURLSet::const_iterator i(urls->begin()); i != urls->end(); ++i) {
1673     if (CanReplace(*i)) {
1674       if (to_replace)
1675         *to_replace = *i;
1676       return true;
1677     }
1678   }
1679   return false;
1680 }
1681
1682 bool TemplateURLService::CanReplace(const TemplateURL* t_url) {
1683   return (t_url != default_search_provider_ && !t_url->show_in_default_list() &&
1684           t_url->safe_for_autoreplace());
1685 }
1686
1687 TemplateURL* TemplateURLService::FindNonExtensionTemplateURLForKeyword(
1688     const base::string16& keyword) {
1689   TemplateURL* keyword_turl = GetTemplateURLForKeyword(keyword);
1690   if (!keyword_turl || (keyword_turl->GetType() == TemplateURL::NORMAL))
1691     return keyword_turl;
1692   // The extension keyword in the model may be hiding a replaceable
1693   // non-extension keyword.  Look for it.
1694   for (TemplateURLVector::const_iterator i(template_urls_.begin());
1695        i != template_urls_.end(); ++i) {
1696     if (((*i)->GetType() == TemplateURL::NORMAL) &&
1697         ((*i)->keyword() == keyword))
1698       return *i;
1699   }
1700   return NULL;
1701 }
1702
1703 bool TemplateURLService::UpdateNoNotify(TemplateURL* existing_turl,
1704                                         const TemplateURL& new_values) {
1705   DCHECK(existing_turl);
1706   if (std::find(template_urls_.begin(), template_urls_.end(), existing_turl) ==
1707       template_urls_.end())
1708     return false;
1709
1710   DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION, existing_turl->GetType());
1711
1712   base::string16 old_keyword(existing_turl->keyword());
1713   keyword_to_template_map_.erase(old_keyword);
1714   if (!existing_turl->sync_guid().empty())
1715     guid_to_template_map_.erase(existing_turl->sync_guid());
1716
1717   // |provider_map_| is only initialized after loading has completed.
1718   if (loaded_)
1719     provider_map_->Remove(existing_turl);
1720
1721   TemplateURLID previous_id = existing_turl->id();
1722   existing_turl->CopyFrom(new_values);
1723   existing_turl->data_.id = previous_id;
1724
1725   if (loaded_) {
1726     provider_map_->Add(existing_turl, search_terms_data());
1727   }
1728
1729   const base::string16& keyword = existing_turl->keyword();
1730   KeywordToTemplateMap::const_iterator i =
1731       keyword_to_template_map_.find(keyword);
1732   if (i == keyword_to_template_map_.end()) {
1733     keyword_to_template_map_[keyword] = existing_turl;
1734   } else {
1735     // We can theoretically reach here in two cases:
1736     //   * There is an existing extension keyword and sync brings in a rename of
1737     //     a non-extension keyword to match.  In this case we just need to pick
1738     //     which keyword has priority to update the keyword map.
1739     //   * Autogeneration of the keyword for a Google default search provider
1740     //     at load time causes it to conflict with an existing keyword.  In this
1741     //     case we delete the existing keyword if it's replaceable, or else undo
1742     //     the change in keyword for |existing_turl|.
1743     TemplateURL* existing_keyword_turl = i->second;
1744     if (existing_keyword_turl->GetType() != TemplateURL::NORMAL) {
1745       if (!CanReplace(existing_turl))
1746         keyword_to_template_map_[keyword] = existing_turl;
1747     } else {
1748       if (CanReplace(existing_keyword_turl)) {
1749         RemoveNoNotify(existing_keyword_turl);
1750       } else {
1751         existing_turl->data_.SetKeyword(old_keyword);
1752         keyword_to_template_map_[old_keyword] = existing_turl;
1753       }
1754     }
1755   }
1756   if (!existing_turl->sync_guid().empty())
1757     guid_to_template_map_[existing_turl->sync_guid()] = existing_turl;
1758
1759   if (web_data_service_.get())
1760     web_data_service_->UpdateKeyword(existing_turl->data());
1761
1762   // Inform sync of the update.
1763   ProcessTemplateURLChange(
1764       FROM_HERE, existing_turl, syncer::SyncChange::ACTION_UPDATE);
1765
1766   if (default_search_provider_ == existing_turl &&
1767       default_search_provider_source_ == DefaultSearchManager::FROM_USER) {
1768     default_search_manager_.SetUserSelectedDefaultSearchEngine(
1769         default_search_provider_->data());
1770   }
1771   return true;
1772 }
1773
1774 // static
1775 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1776     TemplateURL* template_url,
1777     PrefService* prefs) {
1778   int prepopulate_id = template_url->prepopulate_id();
1779   if (template_url->prepopulate_id() == 0)
1780     return;
1781
1782   size_t default_search_index;
1783   ScopedVector<TemplateURLData> prepopulated_urls =
1784       TemplateURLPrepopulateData::GetPrepopulatedEngines(
1785           prefs, &default_search_index);
1786
1787   for (size_t i = 0; i < prepopulated_urls.size(); ++i) {
1788     if (prepopulated_urls[i]->prepopulate_id == prepopulate_id) {
1789       MergeIntoPrepopulatedEngineData(template_url, prepopulated_urls[i]);
1790       template_url->CopyFrom(TemplateURL(*prepopulated_urls[i]));
1791     }
1792   }
1793 }
1794
1795 void TemplateURLService::MaybeUpdateDSEAfterSync(TemplateURL* synced_turl) {
1796   if (prefs_ &&
1797       (synced_turl->sync_guid() ==
1798           prefs_->GetString(prefs::kSyncedDefaultSearchProviderGUID))) {
1799     default_search_manager_.SetUserSelectedDefaultSearchEngine(
1800         synced_turl->data());
1801   }
1802 }
1803
1804 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1805     const URLVisitedDetails& details) {
1806   if (!details.url.is_valid())
1807     return;
1808
1809   const TemplateURLSet* urls_for_host =
1810       provider_map_->GetURLsForHost(details.url.host());
1811   if (!urls_for_host)
1812     return;
1813
1814   for (TemplateURLSet::const_iterator i = urls_for_host->begin();
1815        i != urls_for_host->end(); ++i) {
1816     base::string16 search_terms;
1817     if ((*i)->ExtractSearchTermsFromURL(details.url, search_terms_data(),
1818                                         &search_terms) &&
1819         !search_terms.empty()) {
1820       if (details.is_keyword_transition) {
1821         // The visit is the result of the user entering a keyword, generate a
1822         // KEYWORD_GENERATED visit for the KEYWORD so that the keyword typed
1823         // count is boosted.
1824         AddTabToSearchVisit(**i);
1825       }
1826       if (client_) {
1827         client_->SetKeywordSearchTermsForURL(
1828             details.url, (*i)->id(), search_terms);
1829       }
1830     }
1831   }
1832 }
1833
1834 void TemplateURLService::AddTabToSearchVisit(const TemplateURL& t_url) {
1835   // Only add visits for entries the user hasn't modified. If the user modified
1836   // the entry the keyword may no longer correspond to the host name. It may be
1837   // possible to do something more sophisticated here, but it's so rare as to
1838   // not be worth it.
1839   if (!t_url.safe_for_autoreplace())
1840     return;
1841
1842   if (!client_)
1843     return;
1844
1845   GURL url(
1846       url_fixer::FixupURL(base::UTF16ToUTF8(t_url.keyword()), std::string()));
1847   if (!url.is_valid())
1848     return;
1849
1850   // Synthesize a visit for the keyword. This ensures the url for the keyword is
1851   // autocompleted even if the user doesn't type the url in directly.
1852   client_->AddKeywordGeneratedVisit(url);
1853 }
1854
1855 void TemplateURLService::RequestGoogleURLTrackerServerCheckIfNecessary() {
1856   if (default_search_provider_ &&
1857       default_search_provider_->HasGoogleBaseURLs(search_terms_data()) &&
1858       google_url_tracker_)
1859     google_url_tracker_->RequestServerCheck(false);
1860 }
1861
1862 void TemplateURLService::GoogleBaseURLChanged() {
1863   if (!loaded_)
1864     return;
1865
1866   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1867   bool something_changed = false;
1868   for (TemplateURLVector::iterator i(template_urls_.begin());
1869        i != template_urls_.end(); ++i) {
1870     TemplateURL* t_url = *i;
1871     if (t_url->HasGoogleBaseURLs(search_terms_data())) {
1872       TemplateURL updated_turl(t_url->data());
1873       updated_turl.ResetKeywordIfNecessary(search_terms_data(), false);
1874       KeywordToTemplateMap::const_iterator existing_entry =
1875           keyword_to_template_map_.find(updated_turl.keyword());
1876       if ((existing_entry != keyword_to_template_map_.end()) &&
1877           (existing_entry->second != t_url)) {
1878         // The new autogenerated keyword conflicts with another TemplateURL.
1879         // Overwrite it if it's replaceable; otherwise, leave |t_url| using its
1880         // current keyword.  (This will not prevent |t_url| from auto-updating
1881         // the keyword in the future if the conflicting TemplateURL disappears.)
1882         // Note that we must still update |t_url| in this case, or the
1883         // |provider_map_| will not be updated correctly.
1884         if (CanReplace(existing_entry->second))
1885           RemoveNoNotify(existing_entry->second);
1886         else
1887           updated_turl.data_.SetKeyword(t_url->keyword());
1888       }
1889       something_changed = true;
1890       // This will send the keyword change to sync.  Note that other clients
1891       // need to reset the keyword to an appropriate local value when this
1892       // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
1893       UpdateNoNotify(t_url, updated_turl);
1894     }
1895   }
1896   if (something_changed)
1897     NotifyObservers();
1898 }
1899
1900 void TemplateURLService::OnDefaultSearchChange(
1901     const TemplateURLData* data,
1902     DefaultSearchManager::Source source) {
1903   if (prefs_ && (source == DefaultSearchManager::FROM_USER) &&
1904       ((source != default_search_provider_source_) ||
1905        !IdenticalSyncGUIDs(data, GetDefaultSearchProvider()))) {
1906     prefs_->SetString(prefs::kSyncedDefaultSearchProviderGUID, data->sync_guid);
1907   }
1908   ApplyDefaultSearchChange(data, source);
1909 }
1910
1911 void TemplateURLService::ApplyDefaultSearchChange(
1912     const TemplateURLData* data,
1913     DefaultSearchManager::Source source) {
1914   if (!ApplyDefaultSearchChangeNoMetrics(data, source))
1915     return;
1916
1917   UMA_HISTOGRAM_ENUMERATION(
1918       "Search.DefaultSearchChangeOrigin", dsp_change_origin_, DSP_CHANGE_MAX);
1919
1920   if (GetDefaultSearchProvider() &&
1921       GetDefaultSearchProvider()->HasGoogleBaseURLs(search_terms_data()) &&
1922       !dsp_change_callback_.is_null())
1923     dsp_change_callback_.Run();
1924 }
1925
1926 bool TemplateURLService::ApplyDefaultSearchChangeNoMetrics(
1927     const TemplateURLData* data,
1928     DefaultSearchManager::Source source) {
1929   if (!loaded_) {
1930     // Set |initial_default_search_provider_| from the preferences. This is
1931     // mainly so we can hold ownership until we get to the point where the list
1932     // of keywords from Web Data is the owner of everything including the
1933     // default.
1934     bool changed = TemplateURL::MatchesData(
1935         initial_default_search_provider_.get(), data, search_terms_data());
1936     initial_default_search_provider_.reset(
1937         data ? new TemplateURL(*data) : NULL);
1938     default_search_provider_source_ = source;
1939     return changed;
1940   }
1941
1942   // Prevent recursion if we update the value stored in default_search_manager_.
1943   // Note that we exclude the case of data == NULL because that could cause a
1944   // false positive for recursion when the initial_default_search_provider_ is
1945   // NULL due to policy. We'll never actually get recursion with data == NULL.
1946   if (source == default_search_provider_source_ && data != NULL &&
1947       TemplateURL::MatchesData(default_search_provider_, data,
1948                                search_terms_data()))
1949     return false;
1950
1951   // This may be deleted later. Use exclusively for pointer comparison to detect
1952   // a change.
1953   TemplateURL* previous_default_search_engine = default_search_provider_;
1954
1955   KeywordWebDataService::BatchModeScoper scoper(web_data_service_.get());
1956   if (default_search_provider_source_ == DefaultSearchManager::FROM_POLICY ||
1957       source == DefaultSearchManager::FROM_POLICY) {
1958     // We do this both to remove any no-longer-applicable policy-defined DSE as
1959     // well as to add the new one, if appropriate.
1960     UpdateProvidersCreatedByPolicy(
1961         &template_urls_,
1962         source == DefaultSearchManager::FROM_POLICY ? data : NULL);
1963   }
1964
1965   if (!data) {
1966     default_search_provider_ = NULL;
1967   } else if (source == DefaultSearchManager::FROM_EXTENSION) {
1968     default_search_provider_ = FindMatchingExtensionTemplateURL(
1969         *data, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
1970   } else if (source == DefaultSearchManager::FROM_FALLBACK) {
1971     default_search_provider_ =
1972         FindPrepopulatedTemplateURL(data->prepopulate_id);
1973     if (default_search_provider_) {
1974       TemplateURLData update_data(*data);
1975       update_data.sync_guid = default_search_provider_->sync_guid();
1976       if (!default_search_provider_->safe_for_autoreplace()) {
1977         update_data.safe_for_autoreplace = false;
1978         update_data.SetKeyword(default_search_provider_->keyword());
1979         update_data.short_name = default_search_provider_->short_name();
1980       }
1981       UpdateNoNotify(default_search_provider_, TemplateURL(update_data));
1982     } else {
1983       // Normally the prepopulated fallback should be present in
1984       // |template_urls_|, but in a few cases it might not be:
1985       // (1) Tests that initialize the TemplateURLService in peculiar ways.
1986       // (2) If the user deleted the pre-populated default and we subsequently
1987       // lost their user-selected value.
1988       TemplateURL* new_dse = new TemplateURL(*data);
1989       if (AddNoNotify(new_dse, true))
1990         default_search_provider_ = new_dse;
1991     }
1992   } else if (source == DefaultSearchManager::FROM_USER) {
1993     default_search_provider_ = GetTemplateURLForGUID(data->sync_guid);
1994     if (!default_search_provider_ && data->prepopulate_id) {
1995       default_search_provider_ =
1996           FindPrepopulatedTemplateURL(data->prepopulate_id);
1997     }
1998     TemplateURLData new_data(*data);
1999     new_data.show_in_default_list = true;
2000     if (default_search_provider_) {
2001       UpdateNoNotify(default_search_provider_, TemplateURL(new_data));
2002     } else {
2003       new_data.id = kInvalidTemplateURLID;
2004       TemplateURL* new_dse = new TemplateURL(new_data);
2005       if (AddNoNotify(new_dse, true))
2006         default_search_provider_ = new_dse;
2007     }
2008     if (default_search_provider_ && prefs_) {
2009       prefs_->SetString(prefs::kSyncedDefaultSearchProviderGUID,
2010                         default_search_provider_->sync_guid());
2011     }
2012
2013   }
2014
2015   default_search_provider_source_ = source;
2016
2017   bool changed = default_search_provider_ != previous_default_search_engine;
2018   if (changed)
2019     RequestGoogleURLTrackerServerCheckIfNecessary();
2020
2021   NotifyObservers();
2022
2023   return changed;
2024 }
2025
2026 bool TemplateURLService::AddNoNotify(TemplateURL* template_url,
2027                                      bool newly_adding) {
2028   DCHECK(template_url);
2029
2030   if (newly_adding) {
2031     DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
2032     DCHECK(std::find(template_urls_.begin(), template_urls_.end(),
2033                      template_url) == template_urls_.end());
2034     template_url->data_.id = ++next_id_;
2035   }
2036
2037   template_url->ResetKeywordIfNecessary(search_terms_data(), false);
2038   // Check whether |template_url|'s keyword conflicts with any already in the
2039   // model.
2040   TemplateURL* existing_keyword_turl =
2041       GetTemplateURLForKeyword(template_url->keyword());
2042
2043   // Check whether |template_url|'s keyword conflicts with any already in the
2044   // model.  Note that we can reach here during the loading phase while
2045   // processing the template URLs from the web data service.  In this case,
2046   // GetTemplateURLForKeyword() will look not only at what's already in the
2047   // model, but at the |initial_default_search_provider_|.  Since this engine
2048   // will presumably also be present in the web data, we need to double-check
2049   // that any "pre-existing" entries we find are actually coming from
2050   // |template_urls_|, lest we detect a "conflict" between the
2051   // |initial_default_search_provider_| and the web data version of itself.
2052   if (template_url->GetType() != TemplateURL::OMNIBOX_API_EXTENSION &&
2053       existing_keyword_turl &&
2054       existing_keyword_turl->GetType() != TemplateURL::OMNIBOX_API_EXTENSION &&
2055       (std::find(template_urls_.begin(), template_urls_.end(),
2056                  existing_keyword_turl) != template_urls_.end())) {
2057     DCHECK_NE(existing_keyword_turl, template_url);
2058     // Only replace one of the TemplateURLs if they are either both extensions,
2059     // or both not extensions.
2060     bool are_same_type = existing_keyword_turl->GetType() ==
2061         template_url->GetType();
2062     if (CanReplace(existing_keyword_turl) && are_same_type) {
2063       RemoveNoNotify(existing_keyword_turl);
2064     } else if (CanReplace(template_url) && are_same_type) {
2065       delete template_url;
2066       return false;
2067     } else {
2068       base::string16 new_keyword =
2069           UniquifyKeyword(*existing_keyword_turl, false);
2070       ResetTemplateURLNoNotify(existing_keyword_turl,
2071                                existing_keyword_turl->short_name(), new_keyword,
2072                                existing_keyword_turl->url());
2073     }
2074   }
2075   template_urls_.push_back(template_url);
2076   AddToMaps(template_url);
2077
2078   if (newly_adding &&
2079       (template_url->GetType() == TemplateURL::NORMAL)) {
2080     if (web_data_service_.get())
2081       web_data_service_->AddKeyword(template_url->data());
2082
2083     // Inform sync of the addition. Note that this will assign a GUID to
2084     // template_url and add it to the guid_to_template_map_.
2085     ProcessTemplateURLChange(FROM_HERE,
2086                              template_url,
2087                              syncer::SyncChange::ACTION_ADD);
2088   }
2089
2090   return true;
2091 }
2092
2093 void TemplateURLService::RemoveNoNotify(TemplateURL* template_url) {
2094   DCHECK(template_url != default_search_provider_);
2095
2096   TemplateURLVector::iterator i =
2097       std::find(template_urls_.begin(), template_urls_.end(), template_url);
2098   if (i == template_urls_.end())
2099     return;
2100
2101   RemoveFromMaps(template_url);
2102
2103   // Remove it from the vector containing all TemplateURLs.
2104   template_urls_.erase(i);
2105
2106   if (template_url->GetType() == TemplateURL::NORMAL) {
2107     if (web_data_service_.get())
2108       web_data_service_->RemoveKeyword(template_url->id());
2109
2110     // Inform sync of the deletion.
2111     ProcessTemplateURLChange(FROM_HERE,
2112                              template_url,
2113                              syncer::SyncChange::ACTION_DELETE);
2114
2115     UMA_HISTOGRAM_ENUMERATION(kDeleteSyncedEngineHistogramName,
2116                               DELETE_ENGINE_USER_ACTION, DELETE_ENGINE_MAX);
2117   }
2118
2119   if (loaded_ && client_)
2120     client_->DeleteAllSearchTermsForKeyword(template_url->id());
2121
2122   // We own the TemplateURL and need to delete it.
2123   delete template_url;
2124 }
2125
2126 bool TemplateURLService::ResetTemplateURLNoNotify(
2127     TemplateURL* url,
2128     const base::string16& title,
2129     const base::string16& keyword,
2130     const std::string& search_url) {
2131   DCHECK(!keyword.empty());
2132   DCHECK(!search_url.empty());
2133   TemplateURLData data(url->data());
2134   data.short_name = title;
2135   data.SetKeyword(keyword);
2136   if (search_url != data.url()) {
2137     data.SetURL(search_url);
2138     // The urls have changed, reset the favicon url.
2139     data.favicon_url = GURL();
2140   }
2141   data.safe_for_autoreplace = false;
2142   data.last_modified = time_provider_();
2143   return UpdateNoNotify(url, TemplateURL(data));
2144 }
2145
2146 void TemplateURLService::NotifyObservers() {
2147   if (!loaded_)
2148     return;
2149
2150   FOR_EACH_OBSERVER(TemplateURLServiceObserver, model_observers_,
2151                     OnTemplateURLServiceChanged());
2152 }
2153
2154 // |template_urls| are the TemplateURLs loaded from the database.
2155 // |default_from_prefs| is the default search provider from the preferences, or
2156 // NULL if the DSE is not policy-defined.
2157 //
2158 // This function removes from the vector and the database all the TemplateURLs
2159 // that were set by policy, unless it is the current default search provider, in
2160 // which case it is updated with the data from prefs.
2161 void TemplateURLService::UpdateProvidersCreatedByPolicy(
2162     TemplateURLVector* template_urls,
2163     const TemplateURLData* default_from_prefs) {
2164   DCHECK(template_urls);
2165
2166   for (TemplateURLVector::iterator i = template_urls->begin();
2167        i != template_urls->end(); ) {
2168     TemplateURL* template_url = *i;
2169     if (template_url->created_by_policy()) {
2170       if (default_from_prefs &&
2171           TemplateURL::MatchesData(template_url, default_from_prefs,
2172                                    search_terms_data())) {
2173         // If the database specified a default search provider that was set
2174         // by policy, and the default search provider from the preferences
2175         // is also set by policy and they are the same, keep the entry in the
2176         // database and the |default_search_provider|.
2177         default_search_provider_ = template_url;
2178         // Prevent us from saving any other entries, or creating a new one.
2179         default_from_prefs = NULL;
2180         ++i;
2181         continue;
2182       }
2183
2184       RemoveFromMaps(template_url);
2185       i = template_urls->erase(i);
2186       if (web_data_service_.get())
2187         web_data_service_->RemoveKeyword(template_url->id());
2188       delete template_url;
2189     } else {
2190       ++i;
2191     }
2192   }
2193
2194   if (default_from_prefs) {
2195     default_search_provider_ = NULL;
2196     default_search_provider_source_ = DefaultSearchManager::FROM_POLICY;
2197     TemplateURLData new_data(*default_from_prefs);
2198     if (new_data.sync_guid.empty())
2199       new_data.sync_guid = base::GenerateGUID();
2200     new_data.created_by_policy = true;
2201     TemplateURL* new_dse = new TemplateURL(new_data);
2202     if (AddNoNotify(new_dse, true))
2203       default_search_provider_ = new_dse;
2204   }
2205 }
2206
2207 void TemplateURLService::ResetTemplateURLGUID(TemplateURL* url,
2208                                               const std::string& guid) {
2209   DCHECK(loaded_);
2210   DCHECK(!guid.empty());
2211
2212   TemplateURLData data(url->data());
2213   data.sync_guid = guid;
2214   UpdateNoNotify(url, TemplateURL(data));
2215 }
2216
2217 base::string16 TemplateURLService::UniquifyKeyword(const TemplateURL& turl,
2218                                                    bool force) {
2219   if (!force) {
2220     // Already unique.
2221     if (!GetTemplateURLForKeyword(turl.keyword()))
2222       return turl.keyword();
2223
2224     // First, try to return the generated keyword for the TemplateURL (except
2225     // for extensions, as their keywords are not associated with their URLs).
2226     GURL gurl(turl.url());
2227     if (gurl.is_valid() &&
2228         (turl.GetType() != TemplateURL::OMNIBOX_API_EXTENSION)) {
2229       base::string16 keyword_candidate = TemplateURL::GenerateKeyword(gurl);
2230       if (!GetTemplateURLForKeyword(keyword_candidate))
2231         return keyword_candidate;
2232     }
2233   }
2234
2235   // We try to uniquify the keyword by appending a special character to the end.
2236   // This is a best-effort approach where we try to preserve the original
2237   // keyword and let the user do what they will after our attempt.
2238   base::string16 keyword_candidate(turl.keyword());
2239   do {
2240     keyword_candidate.append(base::ASCIIToUTF16("_"));
2241   } while (GetTemplateURLForKeyword(keyword_candidate));
2242
2243   return keyword_candidate;
2244 }
2245
2246 bool TemplateURLService::IsLocalTemplateURLBetter(
2247     const TemplateURL* local_turl,
2248     const TemplateURL* sync_turl) {
2249   DCHECK(GetTemplateURLForGUID(local_turl->sync_guid()));
2250   return local_turl->last_modified() > sync_turl->last_modified() ||
2251          local_turl->created_by_policy() ||
2252          local_turl== GetDefaultSearchProvider();
2253 }
2254
2255 void TemplateURLService::ResolveSyncKeywordConflict(
2256     TemplateURL* unapplied_sync_turl,
2257     TemplateURL* applied_sync_turl,
2258     syncer::SyncChangeList* change_list) {
2259   DCHECK(loaded_);
2260   DCHECK(unapplied_sync_turl);
2261   DCHECK(applied_sync_turl);
2262   DCHECK(change_list);
2263   DCHECK_EQ(applied_sync_turl->keyword(), unapplied_sync_turl->keyword());
2264   DCHECK_EQ(TemplateURL::NORMAL, applied_sync_turl->GetType());
2265
2266   // Both |unapplied_sync_turl| and |applied_sync_turl| are known to Sync, so
2267   // don't delete either of them. Instead, determine which is "better" and
2268   // uniquify the other one, sending an update to the server for the updated
2269   // entry.
2270   const bool applied_turl_is_better =
2271       IsLocalTemplateURLBetter(applied_sync_turl, unapplied_sync_turl);
2272   TemplateURL* loser = applied_turl_is_better ?
2273       unapplied_sync_turl : applied_sync_turl;
2274   base::string16 new_keyword = UniquifyKeyword(*loser, false);
2275   DCHECK(!GetTemplateURLForKeyword(new_keyword));
2276   if (applied_turl_is_better) {
2277     // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2278     // for adding or updating unapplied_sync_turl in the local model.
2279     unapplied_sync_turl->data_.SetKeyword(new_keyword);
2280   } else {
2281     // Update |applied_sync_turl| in the local model with the new keyword.
2282     TemplateURLData data(applied_sync_turl->data());
2283     data.SetKeyword(new_keyword);
2284     if (UpdateNoNotify(applied_sync_turl, TemplateURL(data)))
2285       NotifyObservers();
2286   }
2287   // The losing TemplateURL should have their keyword updated. Send a change to
2288   // the server to reflect this change.
2289   syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*loser);
2290   change_list->push_back(syncer::SyncChange(FROM_HERE,
2291       syncer::SyncChange::ACTION_UPDATE,
2292       sync_data));
2293 }
2294
2295 void TemplateURLService::MergeInSyncTemplateURL(
2296     TemplateURL* sync_turl,
2297     const SyncDataMap& sync_data,
2298     syncer::SyncChangeList* change_list,
2299     SyncDataMap* local_data,
2300     syncer::SyncMergeResult* merge_result) {
2301   DCHECK(sync_turl);
2302   DCHECK(!GetTemplateURLForGUID(sync_turl->sync_guid()));
2303   DCHECK(IsFromSync(sync_turl, sync_data));
2304
2305   TemplateURL* conflicting_turl =
2306       FindNonExtensionTemplateURLForKeyword(sync_turl->keyword());
2307   bool should_add_sync_turl = true;
2308
2309   // If there was no TemplateURL in the local model that conflicts with
2310   // |sync_turl|, skip the following preparation steps and just add |sync_turl|
2311   // directly. Otherwise, modify |conflicting_turl| to make room for
2312   // |sync_turl|.
2313   if (conflicting_turl) {
2314     if (IsFromSync(conflicting_turl, sync_data)) {
2315       // |conflicting_turl| is already known to Sync, so we're not allowed to
2316       // remove it. In this case, we want to uniquify the worse one and send an
2317       // update for the changed keyword to sync. We can reuse the logic from
2318       // ResolveSyncKeywordConflict for this.
2319       ResolveSyncKeywordConflict(sync_turl, conflicting_turl, change_list);
2320       merge_result->set_num_items_modified(
2321           merge_result->num_items_modified() + 1);
2322     } else {
2323       // |conflicting_turl| is not yet known to Sync. If it is better, then we
2324       // want to transfer its values up to sync. Otherwise, we remove it and
2325       // allow the entry from Sync to overtake it in the model.
2326       const std::string guid = conflicting_turl->sync_guid();
2327       if (IsLocalTemplateURLBetter(conflicting_turl, sync_turl)) {
2328         ResetTemplateURLGUID(conflicting_turl, sync_turl->sync_guid());
2329         syncer::SyncData sync_data =
2330             CreateSyncDataFromTemplateURL(*conflicting_turl);
2331         change_list->push_back(syncer::SyncChange(
2332             FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
2333         // Note that in this case we do not add the Sync TemplateURL to the
2334         // local model, since we've effectively "merged" it in by updating the
2335         // local conflicting entry with its sync_guid.
2336         should_add_sync_turl = false;
2337         merge_result->set_num_items_modified(
2338             merge_result->num_items_modified() + 1);
2339       } else {
2340         // We guarantee that this isn't the local search provider. Otherwise,
2341         // local would have won.
2342         DCHECK(conflicting_turl != GetDefaultSearchProvider());
2343         Remove(conflicting_turl);
2344         merge_result->set_num_items_deleted(
2345             merge_result->num_items_deleted() + 1);
2346       }
2347       // This TemplateURL was either removed or overwritten in the local model.
2348       // Remove the entry from the local data so it isn't pushed up to Sync.
2349       local_data->erase(guid);
2350     }
2351   }
2352
2353   if (should_add_sync_turl) {
2354     // Force the local ID to kInvalidTemplateURLID so we can add it.
2355     TemplateURLData data(sync_turl->data());
2356     data.id = kInvalidTemplateURLID;
2357     TemplateURL* added = new TemplateURL(data);
2358     base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2359         &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
2360     if (Add(added))
2361       MaybeUpdateDSEAfterSync(added);
2362     merge_result->set_num_items_added(
2363         merge_result->num_items_added() + 1);
2364   }
2365 }
2366
2367 void TemplateURLService::PatchMissingSyncGUIDs(
2368     TemplateURLVector* template_urls) {
2369   DCHECK(template_urls);
2370   for (TemplateURLVector::iterator i = template_urls->begin();
2371        i != template_urls->end(); ++i) {
2372     TemplateURL* template_url = *i;
2373     DCHECK(template_url);
2374     if (template_url->sync_guid().empty() &&
2375         (template_url->GetType() == TemplateURL::NORMAL)) {
2376       template_url->data_.sync_guid = base::GenerateGUID();
2377       if (web_data_service_.get())
2378         web_data_service_->UpdateKeyword(template_url->data());
2379     }
2380   }
2381 }
2382
2383 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
2384   base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2385       &dsp_change_origin_, DSP_CHANGE_SYNC_PREF);
2386
2387   std::string new_guid =
2388       prefs_->GetString(prefs::kSyncedDefaultSearchProviderGUID);
2389   if (new_guid.empty()) {
2390     default_search_manager_.ClearUserSelectedDefaultSearchEngine();
2391     return;
2392   }
2393
2394   TemplateURL* turl = GetTemplateURLForGUID(new_guid);
2395   if (turl)
2396     default_search_manager_.SetUserSelectedDefaultSearchEngine(turl->data());
2397 }
2398
2399 TemplateURL* TemplateURLService::FindPrepopulatedTemplateURL(
2400     int prepopulated_id) {
2401   for (TemplateURLVector::const_iterator i = template_urls_.begin();
2402        i != template_urls_.end(); ++i) {
2403     if ((*i)->prepopulate_id() == prepopulated_id)
2404       return *i;
2405   }
2406   return NULL;
2407 }
2408
2409 TemplateURL* TemplateURLService::FindTemplateURLForExtension(
2410     const std::string& extension_id,
2411     TemplateURL::Type type) {
2412   DCHECK_NE(TemplateURL::NORMAL, type);
2413   for (TemplateURLVector::const_iterator i = template_urls_.begin();
2414        i != template_urls_.end(); ++i) {
2415     if ((*i)->GetType() == type &&
2416         (*i)->GetExtensionId() == extension_id)
2417       return *i;
2418   }
2419   return NULL;
2420 }
2421
2422 TemplateURL* TemplateURLService::FindMatchingExtensionTemplateURL(
2423     const TemplateURLData& data,
2424     TemplateURL::Type type) {
2425   DCHECK_NE(TemplateURL::NORMAL, type);
2426   for (TemplateURLVector::const_iterator i = template_urls_.begin();
2427        i != template_urls_.end(); ++i) {
2428     if ((*i)->GetType() == type &&
2429         TemplateURL::MatchesData(*i, &data, search_terms_data()))
2430       return *i;
2431   }
2432   return NULL;
2433 }
2434
2435 void TemplateURLService::UpdateExtensionDefaultSearchEngine() {
2436   TemplateURL* most_recently_intalled_default = NULL;
2437   for (TemplateURLVector::const_iterator i = template_urls_.begin();
2438        i != template_urls_.end(); ++i) {
2439     if (((*i)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) &&
2440         (*i)->extension_info_->wants_to_be_default_engine &&
2441         (*i)->SupportsReplacement(search_terms_data()) &&
2442         (!most_recently_intalled_default ||
2443          (most_recently_intalled_default->extension_info_->install_time <
2444              (*i)->extension_info_->install_time)))
2445       most_recently_intalled_default = *i;
2446   }
2447
2448   if (most_recently_intalled_default) {
2449     base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2450         &dsp_change_origin_, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION);
2451     default_search_manager_.SetExtensionControlledDefaultSearchEngine(
2452         most_recently_intalled_default->data());
2453   } else {
2454     default_search_manager_.ClearExtensionControlledDefaultSearchEngine();
2455   }
2456 }