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