Upload upstream chromium 67.0.3396
[platform/framework/web/chromium-efl.git] / components / search_engines / template_url.h
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_H_
6 #define COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_H_
7
8 #include <cstddef>
9 #include <memory>
10 #include <string>
11 #include <utility>
12 #include <vector>
13
14 #include "base/gtest_prod_util.h"
15 #include "base/macros.h"
16 #include "base/time/time.h"
17 #include "components/search_engines/search_engine_type.h"
18 #include "components/search_engines/template_url_data.h"
19 #include "components/search_engines/template_url_id.h"
20 #include "third_party/metrics_proto/omnibox_event.pb.h"
21 #include "third_party/metrics_proto/omnibox_input_type.pb.h"
22 #include "ui/gfx/geometry/size.h"
23 #include "url/gurl.h"
24 #include "url/third_party/mozilla/url_parse.h"
25
26 class SearchTermsData;
27 class TemplateURL;
28
29
30 // TemplateURLRef -------------------------------------------------------------
31
32 // A TemplateURLRef represents a single URL within the larger TemplateURL class
33 // (which represents an entire "search engine", see below).  If
34 // SupportsReplacement() is true, this URL has placeholders in it, for which
35 // callers can substitute values to get a "real" URL using ReplaceSearchTerms().
36 //
37 // TemplateURLRefs always have a non-NULL |owner_| TemplateURL, which they
38 // access in order to get at important data like the underlying URL string or
39 // the associated Profile.
40 class TemplateURLRef {
41  public:
42   // Magic numbers to pass to ReplaceSearchTerms() for the |accepted_suggestion|
43   // parameter.  Most callers aren't using Suggest capabilities and should just
44   // pass NO_SUGGESTIONS_AVAILABLE.
45   // NOTE: Because positive values are meaningful, make sure these are negative!
46   enum AcceptedSuggestion {
47     NO_SUGGESTION_CHOSEN = -1,
48     NO_SUGGESTIONS_AVAILABLE = -2,
49   };
50
51   // Which kind of URL within our owner we are.  This allows us to get at the
52   // correct string field. Use |INDEXED| to indicate that the numerical
53   // |index_in_owner_| should be used instead.
54   enum Type {
55     SEARCH,
56     SUGGEST,
57     IMAGE,
58     NEW_TAB,
59     CONTEXTUAL_SEARCH,
60     INDEXED
61   };
62
63   // Type to store <content_type, post_data> pair for POST URLs.
64   // The |content_type|(first part of the pair) is the content-type of
65   // the |post_data|(second part of the pair) which is encoded in
66   // "multipart/form-data" format, it also contains the MIME boundary used in
67   // the |post_data|. See http://tools.ietf.org/html/rfc2046 for the details.
68   typedef std::pair<std::string, std::string> PostContent;
69
70   // This struct encapsulates arguments passed to
71   // TemplateURLRef::ReplaceSearchTerms methods.  By default, only search_terms
72   // is required and is passed in the constructor.
73   struct SearchTermsArgs {
74     explicit SearchTermsArgs(const base::string16& search_terms);
75     SearchTermsArgs(const SearchTermsArgs& other);
76     ~SearchTermsArgs();
77
78     struct ContextualSearchParams {
79       ContextualSearchParams();
80       // Modern constructor, used when the content is sent in the HTTP header
81       // instead of as CGI parameters.
82       // The |home_country| is an ISO country code for the country that the user
83       // considers their permanent home (which may be different from the country
84       // they are currently visiting).  Pass an empty string if none available.
85       ContextualSearchParams(int version,
86                              int contextual_cards_version,
87                              const std::string& home_country);
88       ContextualSearchParams(const ContextualSearchParams& other);
89       ~ContextualSearchParams();
90
91       // Estimates dynamic memory usage.
92       // See base/trace_event/memory_usage_estimator.h for more info.
93       size_t EstimateMemoryUsage() const;
94
95       // The version of contextual search.
96       int version;
97
98       // The version of Contextual Cards data to request.
99       // A value of 0 indicates no data needed.
100       int contextual_cards_version;
101
102       // The locale of the user's home country in an ISO country code format,
103       // or an empty string if not available.  This indicates where the user
104       // resides, not where they currently are.
105       std::string home_country;
106     };
107
108     // Estimates dynamic memory usage.
109     // See base/trace_event/memory_usage_estimator.h for more info.
110     size_t EstimateMemoryUsage() const;
111
112     // The search terms (query).
113     base::string16 search_terms;
114
115     // The original (input) query.
116     base::string16 original_query;
117
118     // The type the original input query was identified as.
119     metrics::OmniboxInputType input_type;
120
121     // The optional assisted query stats, aka AQS, used for logging purposes.
122     // This string contains impressions of all autocomplete matches shown
123     // at the query submission time.  For privacy reasons, we require the
124     // search provider to support HTTPS protocol in order to receive the AQS
125     // param.
126     // For more details, see http://goto.google.com/binary-clients-logging .
127     std::string assisted_query_stats;
128
129     // TODO: Remove along with "aq" CGI param.
130     int accepted_suggestion;
131
132     // The 0-based position of the cursor within the query string at the time
133     // the request was issued.  Set to base::string16::npos if not used.
134     size_t cursor_position;
135
136     // The URL of the current webpage to be used for experimental zero-prefix
137     // suggestions.
138     std::string current_page_url;
139
140     // Which omnibox the user used to type the prefix.
141     metrics::OmniboxEventProto::PageClassification page_classification;
142
143     // Optional session token.
144     std::string session_token;
145
146     // Prefetch query and type.
147     std::string prefetch_query;
148     std::string prefetch_query_type;
149
150     // Additional query params provided by the suggest server.
151     std::string suggest_query_params;
152
153     // If set, ReplaceSearchTerms() will automatically append any extra query
154     // params specified via the --extra-search-query-params command-line
155     // argument.  Generally, this should be set when dealing with the search
156     // TemplateURLRefs of the default search engine and the caller cares
157     // about the query portion of the URL.  Since neither TemplateURLRef nor
158     // indeed TemplateURL know whether a TemplateURL is the default search
159     // engine, callers instead must set this manually.
160     bool append_extra_query_params;
161
162     // The raw content of an image thumbnail that will be used as a query for
163     // search-by-image frontend.
164     std::string image_thumbnail_content;
165
166     // When searching for an image, the URL of the original image. Callers
167     // should leave this empty for images specified via data: URLs.
168     GURL image_url;
169
170     // When searching for an image, the original size of the image.
171     gfx::Size image_original_size;
172
173     // True if the search was made using the app list search box. Otherwise, the
174     // search was made using the omnibox.
175     bool from_app_list;
176
177     ContextualSearchParams contextual_search_params;
178   };
179
180   TemplateURLRef(const TemplateURL* owner, Type type);
181   TemplateURLRef(const TemplateURL* owner, size_t index_in_owner);
182   ~TemplateURLRef();
183
184   TemplateURLRef(const TemplateURLRef& source);
185   TemplateURLRef& operator=(const TemplateURLRef& source);
186
187   // Returns the raw URL. None of the parameters will have been replaced.
188   std::string GetURL() const;
189
190   // Returns the raw string of the post params. Please see comments in
191   // prepopulated_engines_schema.json for the format.
192   std::string GetPostParamsString() const;
193
194   // Returns true if this URL supports search term replacement.
195   bool SupportsReplacement(const SearchTermsData& search_terms_data) const;
196
197   // Returns a string that is the result of replacing the search terms in
198   // the url with the specified arguments.  We use our owner's input encoding.
199   //
200   // If this TemplateURLRef does not support replacement (SupportsReplacement
201   // returns false), an empty string is returned.
202   // If this TemplateURLRef uses POST, and |post_content| is not NULL, the
203   // |post_params_| will be replaced, encoded in "multipart/form-data" format
204   // and stored into |post_content|.
205   std::string ReplaceSearchTerms(const SearchTermsArgs& search_terms_args,
206                                  const SearchTermsData& search_terms_data,
207                                  PostContent* post_content) const;
208
209   // TODO(jnd): remove the following ReplaceSearchTerms definition which does
210   // not have |post_content| parameter once all reference callers pass
211   // |post_content| parameter.
212   std::string ReplaceSearchTerms(
213       const SearchTermsArgs& search_terms_args,
214       const SearchTermsData& search_terms_data) const {
215     return ReplaceSearchTerms(search_terms_args, search_terms_data, NULL);
216   }
217
218   // Returns true if the TemplateURLRef is valid. An invalid TemplateURLRef is
219   // one that contains unknown terms, or invalid characters.
220   bool IsValid(const SearchTermsData& search_terms_data) const;
221
222   // Returns a string representation of this TemplateURLRef suitable for
223   // display. The display format is the same as the format used by Firefox.
224   base::string16 DisplayURL(const SearchTermsData& search_terms_data) const;
225
226   // Converts a string as returned by DisplayURL back into a string as
227   // understood by TemplateURLRef.
228   static std::string DisplayURLToURLRef(const base::string16& display_url);
229
230   // If this TemplateURLRef is valid and contains one search term, this returns
231   // the host/path of the URL, otherwise this returns an empty string.
232   const std::string& GetHost(const SearchTermsData& search_terms_data) const;
233   const std::string& GetPath(const SearchTermsData& search_terms_data) const;
234
235   // If this TemplateURLRef is valid and contains one search term
236   // in its query or ref, this returns the key of the search term,
237   // otherwise this returns an empty string.
238   const std::string& GetSearchTermKey(
239       const SearchTermsData& search_terms_data) const;
240
241   // If this TemplateURLRef is valid and contains one search term,
242   // this returns the location of the search term,
243   // otherwise this returns url::Parsed::QUERY.
244   url::Parsed::ComponentType GetSearchTermKeyLocation(
245       const SearchTermsData& search_terms_data) const;
246
247   // If this TemplateURLRef is valid and contains one search term,
248   // this returns the fixed prefix before the search term,
249   // otherwise this returns an empty string.
250   const std::string& GetSearchTermValuePrefix(
251       const SearchTermsData& search_terms_data) const;
252
253   // If this TemplateURLRef is valid and contains one search term,
254   // this returns the fixed suffix after the search term,
255   // otherwise this returns an empty string.
256   const std::string& GetSearchTermValueSuffix(
257       const SearchTermsData& search_terms_data) const;
258
259   // Converts the specified term in our owner's encoding to a base::string16.
260   base::string16 SearchTermToString16(const base::StringPiece& term) const;
261
262   // Returns true if this TemplateURLRef has a replacement term of
263   // {google:baseURL} or {google:baseSuggestURL}.
264   bool HasGoogleBaseURLs(const SearchTermsData& search_terms_data) const;
265
266   // Use the pattern referred to by this TemplateURLRef to match the provided
267   // |url| and extract |search_terms| from it. Returns true if the pattern
268   // matches, even if |search_terms| is empty. In this case
269   // |search_term_component|, if not NULL, indicates whether the search terms
270   // were found in the query or the ref parameters; and |search_terms_position|,
271   // if not NULL, contains the position of the search terms in the query or the
272   // ref parameters. Returns false and an empty |search_terms| if the pattern
273   // does not match.
274   bool ExtractSearchTermsFromURL(
275       const GURL& url,
276       base::string16* search_terms,
277       const SearchTermsData& search_terms_data,
278       url::Parsed::ComponentType* search_term_component,
279       url::Component* search_terms_position) const;
280
281   // Whether the URL uses POST (as opposed to GET).
282   bool UsesPOSTMethod(const SearchTermsData& search_terms_data) const;
283
284   // Estimates dynamic memory usage.
285   // See base/trace_event/memory_usage_estimator.h for more info.
286   size_t EstimateMemoryUsage() const;
287
288  private:
289   friend class TemplateURL;
290   friend class TemplateURLTest;
291   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, SetPrepopulatedAndParse);
292   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseParameterKnown);
293   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseParameterUnknown);
294   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLEmpty);
295   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLNoTemplateEnd);
296   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLNoKnownParameters);
297   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLTwoParameters);
298   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLNestedParameter);
299   FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, URLRefTestImageURLWithPOST);
300
301   // Enumeration of the known types.
302   enum ReplacementType {
303     ENCODING,
304     GOOGLE_ASSISTED_QUERY_STATS,
305     GOOGLE_BASE_URL,
306     GOOGLE_BASE_SUGGEST_URL,
307     GOOGLE_CURRENT_PAGE_URL,
308     GOOGLE_CURSOR_POSITION,
309     GOOGLE_IMAGE_ORIGINAL_HEIGHT,
310     GOOGLE_IMAGE_ORIGINAL_WIDTH,
311     GOOGLE_IMAGE_SEARCH_SOURCE,
312     GOOGLE_IMAGE_THUMBNAIL,
313     GOOGLE_IMAGE_URL,
314     GOOGLE_INPUT_TYPE,
315     GOOGLE_IOS_SEARCH_LANGUAGE,
316     GOOGLE_NTP_IS_THEMED,
317     GOOGLE_CONTEXTUAL_SEARCH_VERSION,
318     GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA,
319     GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION,
320     GOOGLE_PAGE_CLASSIFICATION,
321     GOOGLE_PREFETCH_QUERY,
322     GOOGLE_RLZ,
323     GOOGLE_SEARCH_CLIENT,
324     GOOGLE_SEARCH_FIELDTRIAL_GROUP,
325     GOOGLE_SEARCH_VERSION,
326     GOOGLE_SESSION_TOKEN,
327     GOOGLE_SUGGEST_CLIENT,
328     GOOGLE_SUGGEST_REQUEST_ID,
329     GOOGLE_UNESCAPED_SEARCH_TERMS,
330     LANGUAGE,
331     MAIL_RU_REFERRAL_ID,
332     SEARCH_TERMS,
333     YANDEX_REFERRAL_ID,
334   };
335
336   // Used to identify an element of the raw url that can be replaced.
337   struct Replacement {
338     Replacement(ReplacementType type, size_t index)
339         : type(type), index(index), is_post_param(false) {}
340     ReplacementType type;
341     size_t index;
342     // Indicates the location in where the replacement is replaced. If
343     // |is_post_param| is false, |index| indicates the byte position in
344     // |parsed_url_|. Otherwise, |index| is the index of |post_params_|.
345     bool is_post_param;
346   };
347
348   // Stores a single parameter for a POST.
349   struct PostParam {
350     std::string name;
351     std::string value;
352     std::string content_type;
353
354     // Estimates dynamic memory usage.
355     // See base/trace_event/memory_usage_estimator.h for more info.
356     size_t EstimateMemoryUsage() const;
357   };
358
359   // The list of elements to replace.
360   typedef std::vector<struct Replacement> Replacements;
361   typedef std::vector<PostParam> PostParams;
362
363   // TemplateURLRef internally caches values to make replacement quick. This
364   // method invalidates any cached values.
365   void InvalidateCachedValues() const;
366
367   // Parses the parameter in url at the specified offset. start/end specify the
368   // range of the parameter in the url, including the braces. If the parameter
369   // is valid, url is updated to reflect the appropriate parameter. If
370   // the parameter is one of the known parameters an element is added to
371   // replacements indicating the type and range of the element. The original
372   // parameter is erased from the url.
373   //
374   // If the parameter is not a known parameter, false is returned. If this is a
375   // prepopulated URL, the parameter is erased, otherwise it is left alone.
376   bool ParseParameter(size_t start,
377                       size_t end,
378                       std::string* url,
379                       Replacements* replacements) const;
380
381   // Parses the specified url, replacing parameters as necessary. If
382   // successful, valid is set to true, and the parsed url is returned. For all
383   // known parameters that are encountered an entry is added to replacements.
384   // If there is an error parsing the url, valid is set to false, and an empty
385   // string is returned.  If the URL has the POST parameters, they will be
386   // parsed into |post_params| which will be further replaced with real search
387   // terms data and encoded in "multipart/form-data" format to generate the
388   // POST data.
389   std::string ParseURL(const std::string& url,
390                        Replacements* replacements,
391                        PostParams* post_params,
392                        bool* valid) const;
393
394   // If the url has not yet been parsed, ParseURL is invoked.
395   // NOTE: While this is const, it modifies parsed_, valid_, parsed_url_ and
396   // search_offset_.
397   void ParseIfNecessary(const SearchTermsData& search_terms_data) const;
398
399   // Extracts the query key and host from the url.
400   void ParseHostAndSearchTermKey(
401       const SearchTermsData& search_terms_data) const;
402
403   // Encode post parameters in "multipart/form-data" format and store it
404   // inside |post_content|. Returns false if errors are encountered during
405   // encoding. This method is called each time ReplaceSearchTerms gets called.
406   bool EncodeFormData(const PostParams& post_params,
407                       PostContent* post_content) const;
408
409   // Handles a replacement by using real term data. If the replacement
410   // belongs to a PostParam, the PostParam will be replaced by the term data.
411   // Otherwise, the term data will be inserted at the place that the
412   // replacement points to.
413   void HandleReplacement(const std::string& name,
414                          const std::string& value,
415                          const Replacement& replacement,
416                          std::string* url) const;
417
418   // Replaces all replacements in |parsed_url_| with their actual values and
419   // returns the result.  This is the main functionality of
420   // ReplaceSearchTerms().
421   std::string HandleReplacements(
422       const SearchTermsArgs& search_terms_args,
423       const SearchTermsData& search_terms_data,
424       PostContent* post_content) const;
425
426   // The TemplateURL that contains us.  This should outlive us.
427   const TemplateURL* owner_;
428
429   // What kind of URL we are.
430   Type type_;
431
432   // If |type_| is |INDEXED|, this |index_in_owner_| is used instead to refer to
433   // a url within our owner.
434   size_t index_in_owner_;
435
436   // Whether the URL has been parsed.
437   mutable bool parsed_;
438
439   // Whether the url was successfully parsed.
440   mutable bool valid_;
441
442   // The parsed URL. All terms have been stripped out of this with
443   // replacements_ giving the index of the terms to replace.
444   mutable std::string parsed_url_;
445
446   // Do we support search term replacement?
447   mutable bool supports_replacements_;
448
449   // The replaceable parts of url (parsed_url_). These are ordered by index
450   // into the string, and may be empty.
451   mutable Replacements replacements_;
452
453   // Host, port, path, key and location of the search term. These are only set
454   // if the url contains one search term.
455   mutable std::string host_;
456   mutable std::string port_;
457   mutable std::string path_;
458   mutable std::string search_term_key_;
459   mutable url::Parsed::ComponentType search_term_key_location_;
460   mutable std::string search_term_value_prefix_;
461   mutable std::string search_term_value_suffix_;
462
463   mutable PostParams post_params_;
464
465   // Whether the contained URL is a pre-populated URL.
466   bool prepopulated_;
467 };
468
469
470 // TemplateURL ----------------------------------------------------------------
471
472 // A TemplateURL represents a single "search engine", defined primarily as a
473 // subset of the Open Search Description Document
474 // (http://www.opensearch.org/Specifications/OpenSearch) plus some extensions.
475 // One TemplateURL contains several TemplateURLRefs, which correspond to various
476 // different capabilities (e.g. doing searches or getting suggestions), as well
477 // as a TemplateURLData containing other details like the name, keyword, etc.
478 //
479 // TemplateURLs are intended to be read-only for most users.
480 // The TemplateURLService, which handles storing and manipulating TemplateURLs,
481 // is made a friend so that it can be the exception to this pattern.
482 class TemplateURL {
483  public:
484   enum Type {
485     // Regular search engine.
486     NORMAL,
487     // Installed by extension through Override Settings API.
488     NORMAL_CONTROLLED_BY_EXTENSION,
489     // The keyword associated with an extension that uses the Omnibox API.
490     OMNIBOX_API_EXTENSION,
491     // Installed only on this device. Should not be synced.
492     LOCAL,
493   };
494
495   // An AssociatedExtensionInfo represents information about the extension that
496   // added the search engine.
497   struct AssociatedExtensionInfo {
498     AssociatedExtensionInfo(const std::string& extension_id,
499                             base::Time install_time,
500                             bool wants_to_be_default_engine);
501     ~AssociatedExtensionInfo();
502
503     // Estimates dynamic memory usage.
504     // See base/trace_event/memory_usage_estimator.h for more info.
505     size_t EstimateMemoryUsage() const;
506
507     std::string extension_id;
508
509     // Used to resolve conflicts when there are multiple extensions specifying
510     // the default search engine. The most recently-installed wins.
511     base::Time install_time;
512
513     // Whether the search engine is supposed to be default.
514     bool wants_to_be_default_engine;
515   };
516
517   explicit TemplateURL(const TemplateURLData& data, Type type = NORMAL);
518
519   // Constructor for extension controlled engine. |type| must be
520   // NORMAL_CONTROLLED_BY_EXTENSION or OMNIBOX_API_EXTENSION.
521   TemplateURL(const TemplateURLData& data,
522               Type type,
523               std::string extension_id,
524               base::Time install_time,
525               bool wants_to_be_default_engine);
526
527   ~TemplateURL();
528
529   // Generates a suitable keyword for the specified url, which must be valid.
530   // This is guaranteed not to return an empty string, since TemplateURLs should
531   // never have an empty keyword.
532   static base::string16 GenerateKeyword(const GURL& url);
533
534   // Generates a favicon URL from the specified url.
535   static GURL GenerateFaviconURL(const GURL& url);
536
537   // Returns true if |t_url| and |data| are equal in all meaningful respects.
538   // Static to allow either or both params to be NULL.
539   static bool MatchesData(const TemplateURL* t_url,
540                           const TemplateURLData* data,
541                           const SearchTermsData& search_terms_data);
542
543   const TemplateURLData& data() const { return data_; }
544
545   const base::string16& short_name() const { return data_.short_name(); }
546   // An accessor for the short_name, but adjusted so it can be appropriately
547   // displayed even if it is LTR and the UI is RTL.
548   base::string16 AdjustedShortNameForLocaleDirection() const;
549
550   const base::string16& keyword() const { return data_.keyword(); }
551
552   const std::string& url() const { return data_.url(); }
553   const std::string& suggestions_url() const { return data_.suggestions_url; }
554   const std::string& image_url() const { return data_.image_url; }
555   const std::string& new_tab_url() const { return data_.new_tab_url; }
556   const std::string& contextual_search_url() const {
557     return data_.contextual_search_url;
558   }
559   const std::string& search_url_post_params() const {
560     return data_.search_url_post_params;
561   }
562   const std::string& suggestions_url_post_params() const {
563     return data_.suggestions_url_post_params;
564   }
565   const std::string& image_url_post_params() const {
566     return data_.image_url_post_params;
567   }
568   const std::vector<std::string>& alternate_urls() const {
569     return data_.alternate_urls;
570   }
571   const GURL& favicon_url() const { return data_.favicon_url; }
572
573   const GURL& logo_url() const { return data_.logo_url; }
574
575   const GURL& doodle_url() const { return data_.doodle_url; }
576
577   const GURL& originating_url() const { return data_.originating_url; }
578
579   bool safe_for_autoreplace() const { return data_.safe_for_autoreplace; }
580
581   const std::vector<std::string>& input_encodings() const {
582     return data_.input_encodings;
583   }
584
585   TemplateURLID id() const { return data_.id; }
586
587   base::Time date_created() const { return data_.date_created; }
588   base::Time last_modified() const { return data_.last_modified; }
589   base::Time last_visited() const { return data_.last_visited; }
590
591   bool created_by_policy() const { return data_.created_by_policy; }
592
593   int usage_count() const { return data_.usage_count; }
594
595   int prepopulate_id() const { return data_.prepopulate_id; }
596
597   const std::string& sync_guid() const { return data_.sync_guid; }
598
599   const std::vector<TemplateURLRef>& url_refs() const { return url_refs_; }
600   const TemplateURLRef& url_ref() const {
601     // Sanity check for https://crbug.com/781703.
602     CHECK(!url_refs_.empty());
603     return url_refs_.back();
604   }
605   const TemplateURLRef& suggestions_url_ref() const {
606     return suggestions_url_ref_;
607   }
608   const TemplateURLRef& image_url_ref() const { return image_url_ref_; }
609   const TemplateURLRef& new_tab_url_ref() const { return new_tab_url_ref_; }
610   const TemplateURLRef& contextual_search_url_ref() const {
611     return contextual_search_url_ref_;
612   }
613
614   Type type() const { return type_; }
615
616   const AssociatedExtensionInfo* GetExtensionInfoForTesting() const {
617     return extension_info_.get();
618   }
619
620   // Returns true if |url| supports replacement.
621   bool SupportsReplacement(const SearchTermsData& search_terms_data) const;
622
623   // Returns true if any URLRefs use Googe base URLs.
624   bool HasGoogleBaseURLs(const SearchTermsData& search_terms_data) const;
625
626   // Returns true if this TemplateURL uses Google base URLs and has a keyword
627   // of "google.TLD".  We use this to decide whether we can automatically
628   // update the keyword to reflect the current Google base URL TLD.
629   bool IsGoogleSearchURLWithReplaceableKeyword(
630       const SearchTermsData& search_terms_data) const;
631
632   // Returns true if the keywords match or if
633   // IsGoogleSearchURLWithReplaceableKeyword() is true for both |this| and
634   // |other|.
635   bool HasSameKeywordAs(const TemplateURLData& other,
636                         const SearchTermsData& search_terms_data) const;
637
638   // Returns the id of the extension that added this search engine. Only call
639   // this for TemplateURLs of type NORMAL_CONTROLLED_BY_EXTENSION or
640   // OMNIBOX_API_EXTENSION.
641   std::string GetExtensionId() const;
642
643   // Returns the type of this search engine, or SEARCH_ENGINE_OTHER if no
644   // engines match.
645   SearchEngineType GetEngineType(
646       const SearchTermsData& search_terms_data) const;
647
648   // Use the alternate URLs and the search URL to match the provided |url|
649   // and extract |search_terms| from it. Returns false and an empty
650   // |search_terms| if no search terms can be matched. The URLs are matched in
651   // the order listed in |url_refs_| (see comment there).
652   bool ExtractSearchTermsFromURL(const GURL& url,
653                                  const SearchTermsData& search_terms_data,
654                                  base::string16* search_terms) const;
655
656   // Returns true if non-empty search terms could be extracted from |url| using
657   // ExtractSearchTermsFromURL(). In other words, this returns whether |url|
658   // could be the result of performing a search with |this|.
659   bool IsSearchURL(const GURL& url,
660                    const SearchTermsData& search_terms_data) const;
661
662   // Given a |url| corresponding to this TemplateURL, identifies the search
663   // terms and replaces them with the ones in |search_terms_args|, leaving the
664   // other parameters untouched. If the replacement fails, returns false and
665   // leaves |result| untouched. This is used by mobile ports to perform query
666   // refinement.
667   bool ReplaceSearchTermsInURL(
668       const GURL& url,
669       const TemplateURLRef::SearchTermsArgs& search_terms_args,
670       const SearchTermsData& search_terms_data,
671       GURL* result) const;
672
673   // Encodes the search terms from |search_terms_args| so that we know the
674   // |input_encoding|. Returns the |encoded_terms| and the
675   // |encoded_original_query|. |encoded_terms| may be escaped as path or query
676   // depending on |is_in_query|; |encoded_original_query| is always escaped as
677   // query.
678   void EncodeSearchTerms(
679       const TemplateURLRef::SearchTermsArgs& search_terms_args,
680       bool is_in_query,
681       std::string* input_encoding,
682       base::string16* encoded_terms,
683       base::string16* encoded_original_query) const;
684
685   // Returns the search url for this template URL.
686   // Returns an empty GURL if this template URL has no url().
687   GURL GenerateSearchURL(const SearchTermsData& search_terms_data) const;
688
689   // TemplateURL internally caches values derived from a passed SearchTermsData
690   // to make its functions quick. This method invalidates any cached values and
691   // it should be called after SearchTermsData has been changed.
692   void InvalidateCachedValues() const;
693
694   // Estimates dynamic memory usage.
695   // See base/trace_event/memory_usage_estimator.h for more info.
696   size_t EstimateMemoryUsage() const;
697
698  private:
699   friend class TemplateURLService;
700
701   void CopyFrom(const TemplateURL& other);
702
703   void SetURL(const std::string& url);
704   void SetPrepopulateId(int id);
705
706   // Resets the keyword if IsGoogleSearchURLWithReplaceableKeyword() or |force|.
707   // The |force| parameter is useful when the existing keyword is known to be
708   // a placeholder.  The resulting keyword is generated using
709   // GenerateSearchURL() and GenerateKeyword().
710   void ResetKeywordIfNecessary(const SearchTermsData& search_terms_data,
711                                bool force);
712
713   // Resizes the |url_refs_| vector, which always holds the search URL as the
714   // last item.
715   void ResizeURLRefVector();
716
717   // Uses the alternate URLs and the search URL to match the provided |url|
718   // and extract |search_terms| from it as well as the |search_terms_component|
719   // (either REF or QUERY) and |search_terms_component| at which the
720   // |search_terms| are found in |url|. See also ExtractSearchTermsFromURL().
721   bool FindSearchTermsInURL(const GURL& url,
722                             const SearchTermsData& search_terms_data,
723                             base::string16* search_terms,
724                             url::Parsed::ComponentType* search_terms_component,
725                             url::Component* search_terms_position) const;
726
727   TemplateURLData data_;
728
729   // Contains TemplateURLRefs corresponding to the alternate URLs and the search
730   // URL, in priority order: the URL at index 0 is treated as the highest
731   // priority and the primary search URL is treated as the lowest priority.  For
732   // example, if a TemplateURL has alternate URL "http://foo/#q={searchTerms}"
733   // and search URL "http://foo/?q={searchTerms}", and the URL to be decoded is
734   // "http://foo/?q=a#q=b", the alternate URL will match first and the decoded
735   // search term will be "b".  Note that since every TemplateURLRef has a
736   // primary search URL, this vector is never empty.
737   std::vector<TemplateURLRef> url_refs_;
738
739   TemplateURLRef suggestions_url_ref_;
740   TemplateURLRef image_url_ref_;
741   TemplateURLRef new_tab_url_ref_;
742   TemplateURLRef contextual_search_url_ref_;
743   std::unique_ptr<AssociatedExtensionInfo> extension_info_;
744
745   const Type type_;
746
747   // Caches the computed engine type across successive calls to GetEngineType().
748   mutable SearchEngineType engine_type_;
749
750   // TODO(sky): Add date last parsed OSD file.
751
752   DISALLOW_COPY_AND_ASSIGN(TemplateURL);
753 };
754
755 #endif  // COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_H_