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