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