Hotlist Slow: Remove extra thread pool created by VolumeMountWatcherWin.
[chromium-blink-merge.git] / components / search_engines / template_url.cc
blob007121864b5bca1aaaceea7a19620d5a496c121e
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.
5 #include "components/search_engines/template_url.h"
7 #include <string>
8 #include <vector>
10 #include "base/basictypes.h"
11 #include "base/command_line.h"
12 #include "base/format_macros.h"
13 #include "base/i18n/icu_string_conversions.h"
14 #include "base/i18n/rtl.h"
15 #include "base/logging.h"
16 #include "base/metrics/field_trial.h"
17 #include "base/rand_util.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_split.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "components/google/core/browser/google_util.h"
24 #include "components/metrics/proto/omnibox_input_type.pb.h"
25 #include "components/search_engines/search_engines_switches.h"
26 #include "components/search_engines/search_terms_data.h"
27 #include "google_apis/google_api_keys.h"
28 #include "net/base/escape.h"
29 #include "net/base/mime_util.h"
30 #include "net/base/net_util.h"
31 #include "url/gurl.h"
33 namespace {
35 // The TemplateURLRef has any number of terms that need to be replaced. Each of
36 // the terms is enclosed in braces. If the character preceeding the final
37 // brace is a ?, it indicates the term is optional and can be replaced with
38 // an empty string.
39 const char kStartParameter = '{';
40 const char kEndParameter = '}';
41 const char kOptional = '?';
43 // Known parameters found in the URL.
44 const char kSearchTermsParameter[] = "searchTerms";
45 const char kSearchTermsParameterFull[] = "{searchTerms}";
46 const char kCountParameter[] = "count";
47 const char kStartIndexParameter[] = "startIndex";
48 const char kStartPageParameter[] = "startPage";
49 const char kLanguageParameter[] = "language";
50 const char kInputEncodingParameter[] = "inputEncoding";
51 const char kOutputEncodingParameter[] = "outputEncoding";
53 const char kGoogleAssistedQueryStatsParameter[] = "google:assistedQueryStats";
55 // Host/Domain Google searches are relative to.
56 const char kGoogleBaseURLParameter[] = "google:baseURL";
57 const char kGoogleBaseURLParameterFull[] = "{google:baseURL}";
59 // Like google:baseURL, but for the Search Suggest capability.
60 const char kGoogleBaseSuggestURLParameter[] = "google:baseSuggestURL";
61 const char kGoogleBaseSuggestURLParameterFull[] = "{google:baseSuggestURL}";
62 const char kGoogleBookmarkBarPinnedParameter[] = "google:bookmarkBarPinned";
63 const char kGoogleContextualSearchContextData[] =
64 "google:contextualSearchContextData";
65 const char kGoogleContextualSearchVersion[] = "google:contextualSearchVersion";
66 const char kGoogleCurrentPageUrlParameter[] = "google:currentPageUrl";
67 const char kGoogleCursorPositionParameter[] = "google:cursorPosition";
68 const char kGoogleForceInstantResultsParameter[] = "google:forceInstantResults";
69 const char kGoogleImageSearchSource[] = "google:imageSearchSource";
70 const char kGoogleImageThumbnailParameter[] = "google:imageThumbnail";
71 const char kGoogleImageOriginalWidth[] = "google:imageOriginalWidth";
72 const char kGoogleImageOriginalHeight[] = "google:imageOriginalHeight";
73 const char kGoogleImageURLParameter[] = "google:imageURL";
74 const char kGoogleInputTypeParameter[] = "google:inputType";
75 const char kGoogleInstantExtendedEnabledParameter[] =
76 "google:instantExtendedEnabledParameter";
77 const char kGoogleInstantExtendedEnabledKey[] =
78 "google:instantExtendedEnabledKey";
79 const char kGoogleInstantExtendedEnabledKeyFull[] =
80 "{google:instantExtendedEnabledKey}";
81 const char kGoogleNTPIsThemedParameter[] = "google:ntpIsThemedParameter";
82 const char kGoogleOmniboxStartMarginParameter[] =
83 "google:omniboxStartMarginParameter";
84 const char kGoogleOriginalQueryForSuggestionParameter[] =
85 "google:originalQueryForSuggestion";
86 const char kGooglePageClassificationParameter[] = "google:pageClassification";
87 const char kGooglePrefetchQuery[] = "google:prefetchQuery";
88 const char kGoogleRLZParameter[] = "google:RLZ";
89 const char kGoogleSearchClient[] = "google:searchClient";
90 const char kGoogleSearchFieldtrialParameter[] =
91 "google:searchFieldtrialParameter";
92 const char kGoogleSearchVersion[] = "google:searchVersion";
93 const char kGoogleSessionToken[] = "google:sessionToken";
94 const char kGoogleSourceIdParameter[] = "google:sourceId";
95 const char kGoogleSuggestAPIKeyParameter[] = "google:suggestAPIKeyParameter";
96 const char kGoogleSuggestClient[] = "google:suggestClient";
97 const char kGoogleSuggestRequestId[] = "google:suggestRid";
99 // Same as kSearchTermsParameter, with no escaping.
100 const char kGoogleUnescapedSearchTermsParameter[] =
101 "google:unescapedSearchTerms";
102 const char kGoogleUnescapedSearchTermsParameterFull[] =
103 "{google:unescapedSearchTerms}";
105 // Display value for kSearchTermsParameter.
106 const char kDisplaySearchTerms[] = "%s";
108 // Display value for kGoogleUnescapedSearchTermsParameter.
109 const char kDisplayUnescapedSearchTerms[] = "%S";
111 // Used if the count parameter is not optional. Indicates we want 10 search
112 // results.
113 const char kDefaultCount[] = "10";
115 // Used if the parameter kOutputEncodingParameter is required.
116 const char kOutputEncodingType[] = "UTF-8";
118 // Attempts to encode |terms| and |original_query| in |encoding| and escape
119 // them. |terms| may be escaped as path or query depending on |is_in_query|;
120 // |original_query| is always escaped as query. Returns whether the encoding
121 // process succeeded.
122 bool TryEncoding(const base::string16& terms,
123 const base::string16& original_query,
124 const char* encoding,
125 bool is_in_query,
126 base::string16* escaped_terms,
127 base::string16* escaped_original_query) {
128 DCHECK(escaped_terms);
129 DCHECK(escaped_original_query);
130 std::string encoded_terms;
131 if (!base::UTF16ToCodepage(terms, encoding,
132 base::OnStringConversionError::SKIP, &encoded_terms))
133 return false;
134 *escaped_terms = base::UTF8ToUTF16(is_in_query ?
135 net::EscapeQueryParamValue(encoded_terms, true) :
136 net::EscapePath(encoded_terms));
137 if (original_query.empty())
138 return true;
139 std::string encoded_original_query;
140 if (!base::UTF16ToCodepage(original_query, encoding,
141 base::OnStringConversionError::SKIP, &encoded_original_query))
142 return false;
143 *escaped_original_query = base::UTF8ToUTF16(
144 net::EscapeQueryParamValue(encoded_original_query, true));
145 return true;
148 // Extract query key and host given a list of parameters coming from the URL
149 // query or ref.
150 std::string FindSearchTermsKey(const std::string& params) {
151 if (params.empty())
152 return std::string();
153 url::Component query, key, value;
154 query.len = static_cast<int>(params.size());
155 while (url::ExtractQueryKeyValue(params.c_str(), &query, &key, &value)) {
156 if (key.is_nonempty() && value.is_nonempty()) {
157 std::string value_string = params.substr(value.begin, value.len);
158 if (value_string.find(kSearchTermsParameterFull, 0) !=
159 std::string::npos ||
160 value_string.find(kGoogleUnescapedSearchTermsParameterFull, 0) !=
161 std::string::npos) {
162 return params.substr(key.begin, key.len);
166 return std::string();
169 bool IsTemplateParameterString(const std::string& param) {
170 return (param.length() > 2) && (*(param.begin()) == kStartParameter) &&
171 (*(param.rbegin()) == kEndParameter);
174 } // namespace
177 // TemplateURLRef::SearchTermsArgs --------------------------------------------
179 TemplateURLRef::SearchTermsArgs::SearchTermsArgs(
180 const base::string16& search_terms)
181 : search_terms(search_terms),
182 input_type(metrics::OmniboxInputType::INVALID),
183 accepted_suggestion(NO_SUGGESTIONS_AVAILABLE),
184 cursor_position(base::string16::npos),
185 enable_omnibox_start_margin(false),
186 page_classification(metrics::OmniboxEventProto::INVALID_SPEC),
187 bookmark_bar_pinned(false),
188 append_extra_query_params(false),
189 force_instant_results(false),
190 from_app_list(false),
191 contextual_search_params(ContextualSearchParams()) {
194 TemplateURLRef::SearchTermsArgs::~SearchTermsArgs() {
197 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
198 ContextualSearchParams()
199 : version(-1),
200 start(base::string16::npos),
201 end(base::string16::npos),
202 resolve(true) {
205 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
206 ContextualSearchParams(
207 const int version,
208 const std::string& selection,
209 const std::string& base_page_url,
210 const bool resolve)
211 : version(version),
212 start(base::string16::npos),
213 end(base::string16::npos),
214 selection(selection),
215 base_page_url(base_page_url),
216 resolve(resolve) {
219 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
220 ContextualSearchParams(
221 const int version,
222 const size_t start,
223 const size_t end,
224 const std::string& selection,
225 const std::string& content,
226 const std::string& base_page_url,
227 const std::string& encoding,
228 const bool resolve)
229 : version(version),
230 start(start),
231 end(end),
232 selection(selection),
233 content(content),
234 base_page_url(base_page_url),
235 encoding(encoding),
236 resolve(resolve) {
239 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
240 ~ContextualSearchParams() {
243 // TemplateURLRef -------------------------------------------------------------
245 TemplateURLRef::TemplateURLRef(TemplateURL* owner, Type type)
246 : owner_(owner),
247 type_(type),
248 index_in_owner_(0),
249 parsed_(false),
250 valid_(false),
251 supports_replacements_(false),
252 search_term_key_location_(url::Parsed::QUERY),
253 prepopulated_(false) {
254 DCHECK(owner_);
255 DCHECK_NE(INDEXED, type_);
258 TemplateURLRef::TemplateURLRef(TemplateURL* owner, size_t index_in_owner)
259 : owner_(owner),
260 type_(INDEXED),
261 index_in_owner_(index_in_owner),
262 parsed_(false),
263 valid_(false),
264 supports_replacements_(false),
265 search_term_key_location_(url::Parsed::QUERY),
266 prepopulated_(false) {
267 DCHECK(owner_);
268 DCHECK_LT(index_in_owner_, owner_->URLCount());
271 TemplateURLRef::~TemplateURLRef() {
274 std::string TemplateURLRef::GetURL() const {
275 switch (type_) {
276 case SEARCH: return owner_->url();
277 case SUGGEST: return owner_->suggestions_url();
278 case INSTANT: return owner_->instant_url();
279 case IMAGE: return owner_->image_url();
280 case NEW_TAB: return owner_->new_tab_url();
281 case CONTEXTUAL_SEARCH: return owner_->contextual_search_url();
282 case INDEXED: return owner_->GetURL(index_in_owner_);
283 default: NOTREACHED(); return std::string(); // NOLINT
287 std::string TemplateURLRef::GetPostParamsString() const {
288 switch (type_) {
289 case INDEXED:
290 case SEARCH: return owner_->search_url_post_params();
291 case SUGGEST: return owner_->suggestions_url_post_params();
292 case INSTANT: return owner_->instant_url_post_params();
293 case NEW_TAB: return std::string();
294 case CONTEXTUAL_SEARCH: return std::string();
295 case IMAGE: return owner_->image_url_post_params();
296 default: NOTREACHED(); return std::string(); // NOLINT
300 bool TemplateURLRef::UsesPOSTMethod(
301 const SearchTermsData& search_terms_data) const {
302 ParseIfNecessary(search_terms_data);
303 return !post_params_.empty();
306 bool TemplateURLRef::EncodeFormData(const PostParams& post_params,
307 PostContent* post_content) const {
308 if (post_params.empty())
309 return true;
310 if (!post_content)
311 return false;
313 const char kUploadDataMIMEType[] = "multipart/form-data; boundary=";
314 const char kMultipartBoundary[] = "----+*+----%016" PRIx64 "----+*+----";
315 // Each name/value pair is stored in a body part which is preceded by a
316 // boundary delimiter line. Uses random number generator here to create
317 // a unique boundary delimiter for form data encoding.
318 std::string boundary = base::StringPrintf(kMultipartBoundary,
319 base::RandUint64());
320 // Sets the content MIME type.
321 post_content->first = kUploadDataMIMEType;
322 post_content->first += boundary;
323 // Encodes the post parameters.
324 std::string* post_data = &post_content->second;
325 post_data->clear();
326 for (const auto& param : post_params) {
327 DCHECK(!param.name.empty());
328 net::AddMultipartValueForUpload(param.name, param.value, boundary,
329 param.content_type, post_data);
331 net::AddMultipartFinalDelimiterForUpload(boundary, post_data);
332 return true;
335 bool TemplateURLRef::SupportsReplacement(
336 const SearchTermsData& search_terms_data) const {
337 ParseIfNecessary(search_terms_data);
338 return valid_ && supports_replacements_;
341 std::string TemplateURLRef::ReplaceSearchTerms(
342 const SearchTermsArgs& search_terms_args,
343 const SearchTermsData& search_terms_data,
344 PostContent* post_content) const {
345 ParseIfNecessary(search_terms_data);
346 if (!valid_)
347 return std::string();
349 std::string url(HandleReplacements(search_terms_args, search_terms_data,
350 post_content));
352 GURL gurl(url);
353 if (!gurl.is_valid())
354 return url;
356 std::vector<std::string> query_params;
357 if (search_terms_args.append_extra_query_params) {
358 std::string extra_params(
359 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
360 switches::kExtraSearchQueryParams));
361 if (!extra_params.empty())
362 query_params.push_back(extra_params);
364 if (!search_terms_args.suggest_query_params.empty())
365 query_params.push_back(search_terms_args.suggest_query_params);
366 if (!gurl.query().empty())
367 query_params.push_back(gurl.query());
369 if (query_params.empty())
370 return url;
372 GURL::Replacements replacements;
373 std::string query_str = JoinString(query_params, "&");
374 replacements.SetQueryStr(query_str);
375 return gurl.ReplaceComponents(replacements).possibly_invalid_spec();
378 bool TemplateURLRef::IsValid(const SearchTermsData& search_terms_data) const {
379 ParseIfNecessary(search_terms_data);
380 return valid_;
383 base::string16 TemplateURLRef::DisplayURL(
384 const SearchTermsData& search_terms_data) const {
385 ParseIfNecessary(search_terms_data);
386 base::string16 result(base::UTF8ToUTF16(GetURL()));
387 if (valid_ && !replacements_.empty()) {
388 ReplaceSubstringsAfterOffset(&result, 0,
389 base::ASCIIToUTF16(kSearchTermsParameterFull),
390 base::ASCIIToUTF16(kDisplaySearchTerms));
391 ReplaceSubstringsAfterOffset(&result, 0,
392 base::ASCIIToUTF16(kGoogleUnescapedSearchTermsParameterFull),
393 base::ASCIIToUTF16(kDisplayUnescapedSearchTerms));
395 return result;
398 // static
399 std::string TemplateURLRef::DisplayURLToURLRef(
400 const base::string16& display_url) {
401 base::string16 result = display_url;
402 ReplaceSubstringsAfterOffset(&result, 0,
403 base::ASCIIToUTF16(kDisplaySearchTerms),
404 base::ASCIIToUTF16(kSearchTermsParameterFull));
405 ReplaceSubstringsAfterOffset(
406 &result, 0,
407 base::ASCIIToUTF16(kDisplayUnescapedSearchTerms),
408 base::ASCIIToUTF16(kGoogleUnescapedSearchTermsParameterFull));
409 return base::UTF16ToUTF8(result);
412 const std::string& TemplateURLRef::GetHost(
413 const SearchTermsData& search_terms_data) const {
414 ParseIfNecessary(search_terms_data);
415 return host_;
418 const std::string& TemplateURLRef::GetPath(
419 const SearchTermsData& search_terms_data) const {
420 ParseIfNecessary(search_terms_data);
421 return path_;
424 const std::string& TemplateURLRef::GetSearchTermKey(
425 const SearchTermsData& search_terms_data) const {
426 ParseIfNecessary(search_terms_data);
427 return search_term_key_;
430 base::string16 TemplateURLRef::SearchTermToString16(
431 const std::string& term) const {
432 const std::vector<std::string>& encodings = owner_->input_encodings();
433 base::string16 result;
435 std::string unescaped = net::UnescapeURLComponent(
436 term,
437 net::UnescapeRule::REPLACE_PLUS_WITH_SPACE |
438 net::UnescapeRule::URL_SPECIAL_CHARS);
439 for (size_t i = 0; i < encodings.size(); ++i) {
440 if (base::CodepageToUTF16(unescaped, encodings[i].c_str(),
441 base::OnStringConversionError::FAIL, &result))
442 return result;
445 // Always fall back on UTF-8 if it works.
446 if (base::CodepageToUTF16(unescaped, base::kCodepageUTF8,
447 base::OnStringConversionError::FAIL, &result))
448 return result;
450 // When nothing worked, just use the escaped text. We have no idea what the
451 // encoding is. We need to substitute spaces for pluses ourselves since we're
452 // not sending it through an unescaper.
453 result = base::UTF8ToUTF16(term);
454 std::replace(result.begin(), result.end(), '+', ' ');
455 return result;
458 bool TemplateURLRef::HasGoogleBaseURLs(
459 const SearchTermsData& search_terms_data) const {
460 ParseIfNecessary(search_terms_data);
461 for (size_t i = 0; i < replacements_.size(); ++i) {
462 if ((replacements_[i].type == GOOGLE_BASE_URL) ||
463 (replacements_[i].type == GOOGLE_BASE_SUGGEST_URL))
464 return true;
466 return false;
469 bool TemplateURLRef::ExtractSearchTermsFromURL(
470 const GURL& url,
471 base::string16* search_terms,
472 const SearchTermsData& search_terms_data,
473 url::Parsed::ComponentType* search_terms_component,
474 url::Component* search_terms_position) const {
475 DCHECK(search_terms);
476 search_terms->clear();
478 ParseIfNecessary(search_terms_data);
480 // We need a search term in the template URL to extract something.
481 if (search_term_key_.empty())
482 return false;
484 // TODO(beaudoin): Support patterns of the form http://foo/{searchTerms}/
485 // See crbug.com/153798
487 // Fill-in the replacements. We don't care about search terms in the pattern,
488 // so we use the empty string.
489 // Currently we assume the search term only shows in URL, not in post params.
490 GURL pattern(ReplaceSearchTerms(SearchTermsArgs(base::string16()),
491 search_terms_data, NULL));
492 // Host, path and port must match.
493 if (url.port() != pattern.port() ||
494 url.host() != host_ ||
495 url.path() != path_) {
496 return false;
499 // Parameter must be present either in the query or the ref.
500 const std::string& params(
501 (search_term_key_location_ == url::Parsed::QUERY) ?
502 url.query() : url.ref());
504 url::Component query, key, value;
505 query.len = static_cast<int>(params.size());
506 bool key_found = false;
507 while (url::ExtractQueryKeyValue(params.c_str(), &query, &key, &value)) {
508 if (key.is_nonempty()) {
509 if (params.substr(key.begin, key.len) == search_term_key_) {
510 // Fail if search term key is found twice.
511 if (key_found) {
512 search_terms->clear();
513 return false;
515 key_found = true;
516 // Extract the search term.
517 *search_terms = net::UnescapeAndDecodeUTF8URLComponent(
518 params.substr(value.begin, value.len),
519 net::UnescapeRule::SPACES |
520 net::UnescapeRule::URL_SPECIAL_CHARS |
521 net::UnescapeRule::REPLACE_PLUS_WITH_SPACE);
522 if (search_terms_component)
523 *search_terms_component = search_term_key_location_;
524 if (search_terms_position)
525 *search_terms_position = value;
529 return key_found;
532 void TemplateURLRef::InvalidateCachedValues() const {
533 supports_replacements_ = valid_ = parsed_ = false;
534 host_.clear();
535 path_.clear();
536 search_term_key_.clear();
537 replacements_.clear();
538 post_params_.clear();
541 bool TemplateURLRef::ParseParameter(size_t start,
542 size_t end,
543 std::string* url,
544 Replacements* replacements) const {
545 DCHECK(start != std::string::npos &&
546 end != std::string::npos && end > start);
547 size_t length = end - start - 1;
548 bool optional = false;
549 if ((*url)[end - 1] == kOptional) {
550 optional = true;
551 length--;
553 std::string parameter(url->substr(start + 1, length));
554 std::string full_parameter(url->substr(start, end - start + 1));
555 // Remove the parameter from the string. For parameters who replacement is
556 // constant and already known, just replace them directly. For other cases,
557 // like parameters whose values may change over time, use |replacements|.
558 url->erase(start, end - start + 1);
559 if (parameter == kSearchTermsParameter) {
560 replacements->push_back(Replacement(SEARCH_TERMS, start));
561 } else if (parameter == kCountParameter) {
562 if (!optional)
563 url->insert(start, kDefaultCount);
564 } else if (parameter == kGoogleAssistedQueryStatsParameter) {
565 replacements->push_back(Replacement(GOOGLE_ASSISTED_QUERY_STATS, start));
566 } else if (parameter == kGoogleBaseURLParameter) {
567 replacements->push_back(Replacement(GOOGLE_BASE_URL, start));
568 } else if (parameter == kGoogleBaseSuggestURLParameter) {
569 replacements->push_back(Replacement(GOOGLE_BASE_SUGGEST_URL, start));
570 } else if (parameter == kGoogleBookmarkBarPinnedParameter) {
571 replacements->push_back(Replacement(GOOGLE_BOOKMARK_BAR_PINNED, start));
572 } else if (parameter == kGoogleCurrentPageUrlParameter) {
573 replacements->push_back(Replacement(GOOGLE_CURRENT_PAGE_URL, start));
574 } else if (parameter == kGoogleCursorPositionParameter) {
575 replacements->push_back(Replacement(GOOGLE_CURSOR_POSITION, start));
576 } else if (parameter == kGoogleForceInstantResultsParameter) {
577 replacements->push_back(Replacement(GOOGLE_FORCE_INSTANT_RESULTS, start));
578 } else if (parameter == kGoogleImageOriginalHeight) {
579 replacements->push_back(
580 Replacement(TemplateURLRef::GOOGLE_IMAGE_ORIGINAL_HEIGHT, start));
581 } else if (parameter == kGoogleImageOriginalWidth) {
582 replacements->push_back(
583 Replacement(TemplateURLRef::GOOGLE_IMAGE_ORIGINAL_WIDTH, start));
584 } else if (parameter == kGoogleImageSearchSource) {
585 replacements->push_back(
586 Replacement(TemplateURLRef::GOOGLE_IMAGE_SEARCH_SOURCE, start));
587 } else if (parameter == kGoogleImageThumbnailParameter) {
588 replacements->push_back(
589 Replacement(TemplateURLRef::GOOGLE_IMAGE_THUMBNAIL, start));
590 } else if (parameter == kGoogleImageURLParameter) {
591 replacements->push_back(Replacement(TemplateURLRef::GOOGLE_IMAGE_URL,
592 start));
593 } else if (parameter == kGoogleInputTypeParameter) {
594 replacements->push_back(Replacement(TemplateURLRef::GOOGLE_INPUT_TYPE,
595 start));
596 } else if (parameter == kGoogleInstantExtendedEnabledParameter) {
597 replacements->push_back(Replacement(GOOGLE_INSTANT_EXTENDED_ENABLED,
598 start));
599 } else if (parameter == kGoogleInstantExtendedEnabledKey) {
600 url->insert(start, google_util::kInstantExtendedAPIParam);
601 } else if (parameter == kGoogleNTPIsThemedParameter) {
602 replacements->push_back(Replacement(GOOGLE_NTP_IS_THEMED, start));
603 } else if (parameter == kGoogleOmniboxStartMarginParameter) {
604 replacements->push_back(Replacement(GOOGLE_OMNIBOX_START_MARGIN, start));
605 } else if (parameter == kGoogleContextualSearchVersion) {
606 replacements->push_back(
607 Replacement(GOOGLE_CONTEXTUAL_SEARCH_VERSION, start));
608 } else if (parameter == kGoogleContextualSearchContextData) {
609 replacements->push_back(
610 Replacement(GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA, start));
611 } else if (parameter == kGoogleOriginalQueryForSuggestionParameter) {
612 replacements->push_back(Replacement(GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION,
613 start));
614 } else if (parameter == kGooglePageClassificationParameter) {
615 replacements->push_back(Replacement(GOOGLE_PAGE_CLASSIFICATION, start));
616 } else if (parameter == kGooglePrefetchQuery) {
617 replacements->push_back(Replacement(GOOGLE_PREFETCH_QUERY, start));
618 } else if (parameter == kGoogleRLZParameter) {
619 replacements->push_back(Replacement(GOOGLE_RLZ, start));
620 } else if (parameter == kGoogleSearchClient) {
621 replacements->push_back(Replacement(GOOGLE_SEARCH_CLIENT, start));
622 } else if (parameter == kGoogleSearchFieldtrialParameter) {
623 replacements->push_back(Replacement(GOOGLE_SEARCH_FIELDTRIAL_GROUP, start));
624 } else if (parameter == kGoogleSearchVersion) {
625 replacements->push_back(Replacement(GOOGLE_SEARCH_VERSION, start));
626 } else if (parameter == kGoogleSessionToken) {
627 replacements->push_back(Replacement(GOOGLE_SESSION_TOKEN, start));
628 } else if (parameter == kGoogleSourceIdParameter) {
629 #if defined(OS_ANDROID)
630 url->insert(start, "sourceid=chrome-mobile&");
631 #else
632 url->insert(start, "sourceid=chrome&");
633 #endif
634 } else if (parameter == kGoogleSuggestAPIKeyParameter) {
635 url->insert(start,
636 net::EscapeQueryParamValue(google_apis::GetAPIKey(), false));
637 } else if (parameter == kGoogleSuggestClient) {
638 replacements->push_back(Replacement(GOOGLE_SUGGEST_CLIENT, start));
639 } else if (parameter == kGoogleSuggestRequestId) {
640 replacements->push_back(Replacement(GOOGLE_SUGGEST_REQUEST_ID, start));
641 } else if (parameter == kGoogleUnescapedSearchTermsParameter) {
642 replacements->push_back(Replacement(GOOGLE_UNESCAPED_SEARCH_TERMS, start));
643 } else if (parameter == kInputEncodingParameter) {
644 replacements->push_back(Replacement(ENCODING, start));
645 } else if (parameter == kLanguageParameter) {
646 replacements->push_back(Replacement(LANGUAGE, start));
647 } else if (parameter == kOutputEncodingParameter) {
648 if (!optional)
649 url->insert(start, kOutputEncodingType);
650 } else if ((parameter == kStartIndexParameter) ||
651 (parameter == kStartPageParameter)) {
652 // We don't support these.
653 if (!optional)
654 url->insert(start, "1");
655 } else if (!prepopulated_) {
656 // If it's a prepopulated URL, we know that it's safe to remove unknown
657 // parameters, so just ignore this and return true below. Otherwise it could
658 // be some garbage but can also be a javascript block. Put it back.
659 url->insert(start, full_parameter);
660 return false;
662 return true;
665 std::string TemplateURLRef::ParseURL(const std::string& url,
666 Replacements* replacements,
667 PostParams* post_params,
668 bool* valid) const {
669 *valid = false;
670 std::string parsed_url = url;
671 for (size_t last = 0; last != std::string::npos; ) {
672 last = parsed_url.find(kStartParameter, last);
673 if (last != std::string::npos) {
674 size_t template_end = parsed_url.find(kEndParameter, last);
675 if (template_end != std::string::npos) {
676 // Since we allow Javascript in the URL, {} pairs could be nested. Match
677 // only leaf pairs with supported parameters.
678 size_t next_template_start = parsed_url.find(kStartParameter, last + 1);
679 if (next_template_start == std::string::npos ||
680 next_template_start > template_end) {
681 // If successful, ParseParameter erases from the string as such no
682 // need to update |last|. If failed, move |last| to the end of pair.
683 if (!ParseParameter(last, template_end, &parsed_url, replacements)) {
684 // |template_end| + 1 may be beyond the end of the string.
685 last = template_end;
687 } else {
688 last = next_template_start;
690 } else {
691 // Open brace without a closing brace, return.
692 return std::string();
697 // Handles the post parameters.
698 const std::string& post_params_string = GetPostParamsString();
699 if (!post_params_string.empty()) {
700 typedef std::vector<std::string> Strings;
701 Strings param_list;
702 base::SplitString(post_params_string, ',', &param_list);
704 for (Strings::const_iterator iterator = param_list.begin();
705 iterator != param_list.end(); ++iterator) {
706 Strings parts;
707 // The '=' delimiter is required and the name must be not empty.
708 base::SplitString(*iterator, '=', &parts);
709 if ((parts.size() != 2U) || parts[0].empty())
710 return std::string();
712 std::string& value = parts[1];
713 size_t replacements_size = replacements->size();
714 if (IsTemplateParameterString(value))
715 ParseParameter(0, value.length() - 1, &value, replacements);
716 PostParam param = { parts[0], value };
717 post_params->push_back(param);
718 // If there was a replacement added, points its index to last added
719 // PostParam.
720 if (replacements->size() > replacements_size) {
721 DCHECK_EQ(replacements_size + 1, replacements->size());
722 Replacement* r = &replacements->back();
723 r->is_post_param = true;
724 r->index = post_params->size() - 1;
727 DCHECK(!post_params->empty());
730 *valid = true;
731 return parsed_url;
734 void TemplateURLRef::ParseIfNecessary(
735 const SearchTermsData& search_terms_data) const {
736 if (!parsed_) {
737 InvalidateCachedValues();
738 parsed_ = true;
739 parsed_url_ = ParseURL(GetURL(), &replacements_, &post_params_, &valid_);
740 supports_replacements_ = false;
741 if (valid_) {
742 bool has_only_one_search_term = false;
743 for (Replacements::const_iterator i = replacements_.begin();
744 i != replacements_.end(); ++i) {
745 if ((i->type == SEARCH_TERMS) ||
746 (i->type == GOOGLE_UNESCAPED_SEARCH_TERMS)) {
747 if (has_only_one_search_term) {
748 has_only_one_search_term = false;
749 break;
751 has_only_one_search_term = true;
752 supports_replacements_ = true;
755 // Only parse the host/key if there is one search term. Technically there
756 // could be more than one term, but it's uncommon; so we punt.
757 if (has_only_one_search_term)
758 ParseHostAndSearchTermKey(search_terms_data);
763 void TemplateURLRef::ParseHostAndSearchTermKey(
764 const SearchTermsData& search_terms_data) const {
765 std::string url_string(GetURL());
766 ReplaceSubstringsAfterOffset(&url_string, 0,
767 kGoogleBaseURLParameterFull,
768 search_terms_data.GoogleBaseURLValue());
769 ReplaceSubstringsAfterOffset(&url_string, 0,
770 kGoogleBaseSuggestURLParameterFull,
771 search_terms_data.GoogleBaseSuggestURLValue());
773 search_term_key_.clear();
774 host_.clear();
775 path_.clear();
776 search_term_key_location_ = url::Parsed::REF;
778 GURL url(url_string);
779 if (!url.is_valid())
780 return;
782 std::string query_key = FindSearchTermsKey(url.query());
783 std::string ref_key = FindSearchTermsKey(url.ref());
784 if (query_key.empty() == ref_key.empty())
785 return; // No key or multiple keys found. We only handle having one key.
786 search_term_key_ = query_key.empty() ? ref_key : query_key;
787 search_term_key_location_ =
788 query_key.empty() ? url::Parsed::REF : url::Parsed::QUERY;
789 host_ = url.host();
790 path_ = url.path();
793 void TemplateURLRef::HandleReplacement(const std::string& name,
794 const std::string& value,
795 const Replacement& replacement,
796 std::string* url) const {
797 size_t pos = replacement.index;
798 if (replacement.is_post_param) {
799 DCHECK_LT(pos, post_params_.size());
800 DCHECK(!post_params_[pos].name.empty());
801 post_params_[pos].value = value;
802 } else {
803 url->insert(pos, name.empty() ? value : (name + "=" + value + "&"));
807 std::string TemplateURLRef::HandleReplacements(
808 const SearchTermsArgs& search_terms_args,
809 const SearchTermsData& search_terms_data,
810 PostContent* post_content) const {
811 if (replacements_.empty()) {
812 if (!post_params_.empty())
813 EncodeFormData(post_params_, post_content);
814 return parsed_url_;
817 // Determine if the search terms are in the query or before. We're escaping
818 // space as '+' in the former case and as '%20' in the latter case.
819 bool is_in_query = true;
820 for (Replacements::iterator i = replacements_.begin();
821 i != replacements_.end(); ++i) {
822 if (i->type == SEARCH_TERMS) {
823 base::string16::size_type query_start = parsed_url_.find('?');
824 is_in_query = query_start != base::string16::npos &&
825 (static_cast<base::string16::size_type>(i->index) > query_start);
826 break;
830 std::string input_encoding;
831 base::string16 encoded_terms;
832 base::string16 encoded_original_query;
833 owner_->EncodeSearchTerms(search_terms_args, is_in_query, &input_encoding,
834 &encoded_terms, &encoded_original_query);
836 std::string url = parsed_url_;
838 // replacements_ is ordered in ascending order, as such we need to iterate
839 // from the back.
840 for (Replacements::reverse_iterator i = replacements_.rbegin();
841 i != replacements_.rend(); ++i) {
842 switch (i->type) {
843 case ENCODING:
844 HandleReplacement(std::string(), input_encoding, *i, &url);
845 break;
847 case GOOGLE_ASSISTED_QUERY_STATS:
848 DCHECK(!i->is_post_param);
849 if (!search_terms_args.assisted_query_stats.empty()) {
850 // Get the base URL without substituting AQS to avoid infinite
851 // recursion. We need the URL to find out if it meets all
852 // AQS requirements (e.g. HTTPS protocol check).
853 // See TemplateURLRef::SearchTermsArgs for more details.
854 SearchTermsArgs search_terms_args_without_aqs(search_terms_args);
855 search_terms_args_without_aqs.assisted_query_stats.clear();
856 GURL base_url(ReplaceSearchTerms(
857 search_terms_args_without_aqs, search_terms_data, NULL));
858 if (base_url.SchemeIs(url::kHttpsScheme)) {
859 HandleReplacement(
860 "aqs", search_terms_args.assisted_query_stats, *i, &url);
863 break;
865 case GOOGLE_BASE_URL:
866 DCHECK(!i->is_post_param);
867 HandleReplacement(
868 std::string(), search_terms_data.GoogleBaseURLValue(), *i, &url);
869 break;
871 case GOOGLE_BASE_SUGGEST_URL:
872 DCHECK(!i->is_post_param);
873 HandleReplacement(
874 std::string(), search_terms_data.GoogleBaseSuggestURLValue(), *i,
875 &url);
876 break;
878 case GOOGLE_BOOKMARK_BAR_PINNED:
879 if (search_terms_data.IsShowingSearchTermsOnSearchResultsPages()) {
880 // Log whether the bookmark bar is pinned when the user is seeing
881 // InstantExtended on the SRP.
882 DCHECK(!i->is_post_param);
883 HandleReplacement(
884 "bmbp", search_terms_args.bookmark_bar_pinned ? "1" : "0", *i,
885 &url);
887 break;
889 case GOOGLE_CURRENT_PAGE_URL:
890 DCHECK(!i->is_post_param);
891 if (!search_terms_args.current_page_url.empty()) {
892 const std::string& escaped_current_page_url =
893 net::EscapeQueryParamValue(search_terms_args.current_page_url,
894 true);
895 HandleReplacement("url", escaped_current_page_url, *i, &url);
897 break;
899 case GOOGLE_CURSOR_POSITION:
900 DCHECK(!i->is_post_param);
901 if (search_terms_args.cursor_position != base::string16::npos)
902 HandleReplacement(
903 "cp",
904 base::StringPrintf("%" PRIuS, search_terms_args.cursor_position),
906 &url);
907 break;
909 case GOOGLE_FORCE_INSTANT_RESULTS:
910 DCHECK(!i->is_post_param);
911 HandleReplacement(std::string(),
912 search_terms_data.ForceInstantResultsParam(
913 search_terms_args.force_instant_results),
915 &url);
916 break;
918 case GOOGLE_INPUT_TYPE:
919 DCHECK(!i->is_post_param);
920 HandleReplacement(
921 "oit", base::IntToString(search_terms_args.input_type), *i, &url);
922 break;
924 case GOOGLE_INSTANT_EXTENDED_ENABLED:
925 DCHECK(!i->is_post_param);
926 HandleReplacement(std::string(),
927 search_terms_data.InstantExtendedEnabledParam(
928 type_ == SEARCH),
930 &url);
931 break;
933 case GOOGLE_NTP_IS_THEMED:
934 DCHECK(!i->is_post_param);
935 HandleReplacement(
936 std::string(), search_terms_data.NTPIsThemedParam(), *i, &url);
937 break;
939 case GOOGLE_OMNIBOX_START_MARGIN:
940 DCHECK(!i->is_post_param);
941 if (search_terms_args.enable_omnibox_start_margin) {
942 int omnibox_start_margin = search_terms_data.OmniboxStartMargin();
943 if (omnibox_start_margin >= 0) {
944 HandleReplacement("es_sm", base::IntToString(omnibox_start_margin),
945 *i, &url);
948 break;
950 case GOOGLE_CONTEXTUAL_SEARCH_VERSION:
951 if (search_terms_args.contextual_search_params.version >= 0) {
952 HandleReplacement(
953 "ctxs",
954 base::IntToString(
955 search_terms_args.contextual_search_params.version),
957 &url);
959 break;
961 case GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA: {
962 DCHECK(!i->is_post_param);
963 std::string context_data;
965 const SearchTermsArgs::ContextualSearchParams& params =
966 search_terms_args.contextual_search_params;
968 if (params.start != std::string::npos) {
969 context_data.append("ctxs_start=" + base::IntToString(
970 params.start) + "&");
973 if (params.end != std::string::npos) {
974 context_data.append("ctxs_end=" + base::IntToString(
975 params.end) + "&");
978 if (!params.selection.empty())
979 context_data.append("q=" + params.selection + "&");
981 if (!params.content.empty())
982 context_data.append("ctxs_content=" + params.content + "&");
984 if (!params.base_page_url.empty())
985 context_data.append("ctxsl_url=" + params.base_page_url + "&");
987 if (!params.encoding.empty()) {
988 context_data.append("ctxs_encoding=" + params.encoding + "&");
991 context_data.append(
992 params.resolve ? "ctxsl_resolve=1" : "ctxsl_resolve=0");
994 HandleReplacement(std::string(), context_data, *i, &url);
995 break;
998 case GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION:
999 DCHECK(!i->is_post_param);
1000 if (search_terms_args.accepted_suggestion >= 0 ||
1001 !search_terms_args.assisted_query_stats.empty()) {
1002 HandleReplacement(
1003 "oq", base::UTF16ToUTF8(encoded_original_query), *i, &url);
1005 break;
1007 case GOOGLE_PAGE_CLASSIFICATION:
1008 if (search_terms_args.page_classification !=
1009 metrics::OmniboxEventProto::INVALID_SPEC) {
1010 HandleReplacement(
1011 "pgcl", base::IntToString(search_terms_args.page_classification),
1012 *i, &url);
1014 break;
1016 case GOOGLE_PREFETCH_QUERY: {
1017 const std::string& query = search_terms_args.prefetch_query;
1018 const std::string& type = search_terms_args.prefetch_query_type;
1019 if (!query.empty() && !type.empty()) {
1020 HandleReplacement(
1021 std::string(), "pfq=" + query + "&qha=" + type + "&", *i, &url);
1023 break;
1026 case GOOGLE_RLZ: {
1027 DCHECK(!i->is_post_param);
1028 // On platforms that don't have RLZ, we still want this branch
1029 // to happen so that we replace the RLZ template with the
1030 // empty string. (If we don't handle this case, we hit a
1031 // NOTREACHED below.)
1032 base::string16 rlz_string = search_terms_data.GetRlzParameterValue(
1033 search_terms_args.from_app_list);
1034 if (!rlz_string.empty()) {
1035 HandleReplacement("rlz", base::UTF16ToUTF8(rlz_string), *i, &url);
1037 break;
1040 case GOOGLE_SEARCH_CLIENT: {
1041 DCHECK(!i->is_post_param);
1042 std::string client = search_terms_data.GetSearchClient();
1043 if (!client.empty())
1044 HandleReplacement("client", client, *i, &url);
1045 break;
1048 case GOOGLE_SEARCH_FIELDTRIAL_GROUP:
1049 // We are not currently running any fieldtrials that modulate the search
1050 // url. If we do, then we'd have some conditional insert such as:
1051 // url.insert(i->index, used_www ? "gcx=w&" : "gcx=c&");
1052 break;
1054 case GOOGLE_SEARCH_VERSION:
1055 if (search_terms_data.EnableAnswersInSuggest())
1056 HandleReplacement("gs_rn", "42", *i, &url);
1057 break;
1059 case GOOGLE_SESSION_TOKEN: {
1060 std::string token = search_terms_args.session_token;
1061 if (!token.empty())
1062 HandleReplacement("psi", token, *i, &url);
1063 break;
1066 case GOOGLE_SUGGEST_CLIENT:
1067 HandleReplacement(
1068 std::string(), search_terms_data.GetSuggestClient(), *i, &url);
1069 break;
1071 case GOOGLE_SUGGEST_REQUEST_ID:
1072 HandleReplacement(
1073 std::string(), search_terms_data.GetSuggestRequestIdentifier(), *i,
1074 &url);
1075 break;
1077 case GOOGLE_UNESCAPED_SEARCH_TERMS: {
1078 std::string unescaped_terms;
1079 base::UTF16ToCodepage(search_terms_args.search_terms,
1080 input_encoding.c_str(),
1081 base::OnStringConversionError::SKIP,
1082 &unescaped_terms);
1083 HandleReplacement(std::string(), unescaped_terms, *i, &url);
1084 break;
1087 case LANGUAGE:
1088 HandleReplacement(
1089 std::string(), search_terms_data.GetApplicationLocale(), *i, &url);
1090 break;
1092 case SEARCH_TERMS:
1093 HandleReplacement(
1094 std::string(), base::UTF16ToUTF8(encoded_terms), *i, &url);
1095 break;
1097 case GOOGLE_IMAGE_THUMBNAIL:
1098 HandleReplacement(
1099 std::string(), search_terms_args.image_thumbnail_content, *i, &url);
1100 post_params_[i->index].content_type = "image/jpeg";
1101 break;
1103 case GOOGLE_IMAGE_URL:
1104 if (search_terms_args.image_url.is_valid()) {
1105 HandleReplacement(
1106 std::string(), search_terms_args.image_url.spec(), *i, &url);
1108 break;
1110 case GOOGLE_IMAGE_ORIGINAL_WIDTH:
1111 if (!search_terms_args.image_original_size.IsEmpty()) {
1112 HandleReplacement(
1113 std::string(),
1114 base::IntToString(search_terms_args.image_original_size.width()),
1115 *i, &url);
1117 break;
1119 case GOOGLE_IMAGE_ORIGINAL_HEIGHT:
1120 if (!search_terms_args.image_original_size.IsEmpty()) {
1121 HandleReplacement(
1122 std::string(),
1123 base::IntToString(search_terms_args.image_original_size.height()),
1124 *i, &url);
1126 break;
1128 case GOOGLE_IMAGE_SEARCH_SOURCE:
1129 HandleReplacement(
1130 std::string(), search_terms_data.GoogleImageSearchSource(), *i,
1131 &url);
1132 break;
1134 default:
1135 NOTREACHED();
1136 break;
1140 if (!post_params_.empty())
1141 EncodeFormData(post_params_, post_content);
1143 return url;
1147 // TemplateURL ----------------------------------------------------------------
1149 TemplateURL::AssociatedExtensionInfo::AssociatedExtensionInfo(
1150 Type type,
1151 const std::string& extension_id)
1152 : type(type),
1153 extension_id(extension_id),
1154 wants_to_be_default_engine(false) {
1155 DCHECK_NE(NORMAL, type);
1158 TemplateURL::AssociatedExtensionInfo::~AssociatedExtensionInfo() {
1161 TemplateURL::TemplateURL(const TemplateURLData& data)
1162 : data_(data),
1163 url_ref_(this, TemplateURLRef::SEARCH),
1164 suggestions_url_ref_(this,
1165 TemplateURLRef::SUGGEST),
1166 instant_url_ref_(this,
1167 TemplateURLRef::INSTANT),
1168 image_url_ref_(this, TemplateURLRef::IMAGE),
1169 new_tab_url_ref_(this, TemplateURLRef::NEW_TAB),
1170 contextual_search_url_ref_(this, TemplateURLRef::CONTEXTUAL_SEARCH) {
1171 SetPrepopulateId(data_.prepopulate_id);
1173 if (data_.search_terms_replacement_key ==
1174 kGoogleInstantExtendedEnabledKeyFull) {
1175 data_.search_terms_replacement_key = google_util::kInstantExtendedAPIParam;
1179 TemplateURL::~TemplateURL() {
1182 // static
1183 base::string16 TemplateURL::GenerateKeyword(const GURL& url) {
1184 DCHECK(url.is_valid());
1185 // Strip "www." off the front of the keyword; otherwise the keyword won't work
1186 // properly. See http://code.google.com/p/chromium/issues/detail?id=6984 .
1187 // Special case: if the host was exactly "www." (not sure this can happen but
1188 // perhaps with some weird intranet and custom DNS server?), ensure we at
1189 // least don't return the empty string.
1190 base::string16 keyword(net::StripWWWFromHost(url));
1191 return keyword.empty() ? base::ASCIIToUTF16("www") : keyword;
1194 // static
1195 GURL TemplateURL::GenerateFaviconURL(const GURL& url) {
1196 DCHECK(url.is_valid());
1197 GURL::Replacements rep;
1199 const char favicon_path[] = "/favicon.ico";
1200 int favicon_path_len = arraysize(favicon_path) - 1;
1202 rep.SetPath(favicon_path, url::Component(0, favicon_path_len));
1203 rep.ClearUsername();
1204 rep.ClearPassword();
1205 rep.ClearQuery();
1206 rep.ClearRef();
1207 return url.ReplaceComponents(rep);
1210 // static
1211 bool TemplateURL::MatchesData(const TemplateURL* t_url,
1212 const TemplateURLData* data,
1213 const SearchTermsData& search_terms_data) {
1214 if (!t_url || !data)
1215 return !t_url && !data;
1217 return (t_url->short_name() == data->short_name) &&
1218 t_url->HasSameKeywordAs(*data, search_terms_data) &&
1219 (t_url->url() == data->url()) &&
1220 (t_url->suggestions_url() == data->suggestions_url) &&
1221 (t_url->instant_url() == data->instant_url) &&
1222 (t_url->image_url() == data->image_url) &&
1223 (t_url->new_tab_url() == data->new_tab_url) &&
1224 (t_url->search_url_post_params() == data->search_url_post_params) &&
1225 (t_url->suggestions_url_post_params() ==
1226 data->suggestions_url_post_params) &&
1227 (t_url->instant_url_post_params() == data->instant_url_post_params) &&
1228 (t_url->image_url_post_params() == data->image_url_post_params) &&
1229 (t_url->favicon_url() == data->favicon_url) &&
1230 (t_url->safe_for_autoreplace() == data->safe_for_autoreplace) &&
1231 (t_url->show_in_default_list() == data->show_in_default_list) &&
1232 (t_url->input_encodings() == data->input_encodings) &&
1233 (t_url->alternate_urls() == data->alternate_urls) &&
1234 (t_url->search_terms_replacement_key() ==
1235 data->search_terms_replacement_key);
1238 base::string16 TemplateURL::AdjustedShortNameForLocaleDirection() const {
1239 base::string16 bidi_safe_short_name = data_.short_name;
1240 base::i18n::AdjustStringForLocaleDirection(&bidi_safe_short_name);
1241 return bidi_safe_short_name;
1244 bool TemplateURL::ShowInDefaultList(
1245 const SearchTermsData& search_terms_data) const {
1246 return data_.show_in_default_list &&
1247 url_ref_.SupportsReplacement(search_terms_data);
1250 bool TemplateURL::SupportsReplacement(
1251 const SearchTermsData& search_terms_data) const {
1252 return url_ref_.SupportsReplacement(search_terms_data);
1255 bool TemplateURL::HasGoogleBaseURLs(
1256 const SearchTermsData& search_terms_data) const {
1257 return url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1258 suggestions_url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1259 instant_url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1260 image_url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1261 new_tab_url_ref_.HasGoogleBaseURLs(search_terms_data);
1264 bool TemplateURL::IsGoogleSearchURLWithReplaceableKeyword(
1265 const SearchTermsData& search_terms_data) const {
1266 return (GetType() == NORMAL) &&
1267 url_ref_.HasGoogleBaseURLs(search_terms_data) &&
1268 google_util::IsGoogleHostname(base::UTF16ToUTF8(data_.keyword()),
1269 google_util::DISALLOW_SUBDOMAIN);
1272 bool TemplateURL::HasSameKeywordAs(
1273 const TemplateURLData& other,
1274 const SearchTermsData& search_terms_data) const {
1275 return (data_.keyword() == other.keyword()) ||
1276 (IsGoogleSearchURLWithReplaceableKeyword(search_terms_data) &&
1277 TemplateURL(other).IsGoogleSearchURLWithReplaceableKeyword(
1278 search_terms_data));
1281 TemplateURL::Type TemplateURL::GetType() const {
1282 return extension_info_ ? extension_info_->type : NORMAL;
1285 std::string TemplateURL::GetExtensionId() const {
1286 DCHECK(extension_info_);
1287 return extension_info_->extension_id;
1290 size_t TemplateURL::URLCount() const {
1291 // Add 1 for the regular search URL.
1292 return data_.alternate_urls.size() + 1;
1295 const std::string& TemplateURL::GetURL(size_t index) const {
1296 DCHECK_LT(index, URLCount());
1298 return (index < data_.alternate_urls.size()) ?
1299 data_.alternate_urls[index] : url();
1302 bool TemplateURL::ExtractSearchTermsFromURL(
1303 const GURL& url,
1304 const SearchTermsData& search_terms_data,
1305 base::string16* search_terms) {
1306 return FindSearchTermsInURL(url, search_terms_data, search_terms, NULL, NULL);
1309 bool TemplateURL::IsSearchURL(
1310 const GURL& url,
1311 const SearchTermsData& search_terms_data) {
1312 base::string16 search_terms;
1313 return ExtractSearchTermsFromURL(url, search_terms_data, &search_terms) &&
1314 !search_terms.empty();
1317 bool TemplateURL::HasSearchTermsReplacementKey(const GURL& url) const {
1318 // Look for the key both in the query and the ref.
1319 std::string params[] = {url.query(), url.ref()};
1321 for (int i = 0; i < 2; ++i) {
1322 url::Component query, key, value;
1323 query.len = static_cast<int>(params[i].size());
1324 while (url::ExtractQueryKeyValue(params[i].c_str(), &query, &key, &value)) {
1325 if (key.is_nonempty() &&
1326 params[i].substr(key.begin, key.len) ==
1327 search_terms_replacement_key()) {
1328 return true;
1332 return false;
1335 bool TemplateURL::ReplaceSearchTermsInURL(
1336 const GURL& url,
1337 const TemplateURLRef::SearchTermsArgs& search_terms_args,
1338 const SearchTermsData& search_terms_data,
1339 GURL* result) {
1340 // TODO(beaudoin): Use AQS from |search_terms_args| too.
1341 url::Parsed::ComponentType search_term_component;
1342 url::Component search_terms_position;
1343 base::string16 search_terms;
1344 if (!FindSearchTermsInURL(url, search_terms_data, &search_terms,
1345 &search_term_component, &search_terms_position)) {
1346 return false;
1348 DCHECK(search_terms_position.is_nonempty());
1350 // FindSearchTermsInURL only returns true for search terms in the query or
1351 // ref, so we can call EncodeSearchTerm with |is_in_query| = true, since query
1352 // and ref are encoded in the same way.
1353 std::string input_encoding;
1354 base::string16 encoded_terms;
1355 base::string16 encoded_original_query;
1356 EncodeSearchTerms(search_terms_args, true, &input_encoding,
1357 &encoded_terms, &encoded_original_query);
1359 std::string old_params(
1360 (search_term_component == url::Parsed::REF) ? url.ref() : url.query());
1361 std::string new_params(old_params, 0, search_terms_position.begin);
1362 new_params += base::UTF16ToUTF8(search_terms_args.search_terms);
1363 new_params += old_params.substr(search_terms_position.end());
1364 GURL::Replacements replacements;
1365 if (search_term_component == url::Parsed::REF)
1366 replacements.SetRefStr(new_params);
1367 else
1368 replacements.SetQueryStr(new_params);
1369 *result = url.ReplaceComponents(replacements);
1370 return true;
1373 void TemplateURL::EncodeSearchTerms(
1374 const TemplateURLRef::SearchTermsArgs& search_terms_args,
1375 bool is_in_query,
1376 std::string* input_encoding,
1377 base::string16* encoded_terms,
1378 base::string16* encoded_original_query) const {
1380 std::vector<std::string> encodings(input_encodings());
1381 if (std::find(encodings.begin(), encodings.end(), "UTF-8") == encodings.end())
1382 encodings.push_back("UTF-8");
1383 for (std::vector<std::string>::const_iterator i(encodings.begin());
1384 i != encodings.end(); ++i) {
1385 if (TryEncoding(search_terms_args.search_terms,
1386 search_terms_args.original_query, i->c_str(),
1387 is_in_query, encoded_terms, encoded_original_query)) {
1388 *input_encoding = *i;
1389 return;
1392 NOTREACHED();
1395 GURL TemplateURL::GenerateSearchURL(
1396 const SearchTermsData& search_terms_data) const {
1397 if (!url_ref_.IsValid(search_terms_data))
1398 return GURL();
1400 if (!url_ref_.SupportsReplacement(search_terms_data))
1401 return GURL(url());
1403 // Use something obscure for the search terms argument so that in the rare
1404 // case the term replaces the URL it's unlikely another keyword would have the
1405 // same url.
1406 // TODO(jnd): Add additional parameters to get post data when the search URL
1407 // has post parameters.
1408 return GURL(url_ref_.ReplaceSearchTerms(
1409 TemplateURLRef::SearchTermsArgs(
1410 base::ASCIIToUTF16("blah.blah.blah.blah.blah")),
1411 search_terms_data, NULL));
1414 void TemplateURL::CopyFrom(const TemplateURL& other) {
1415 if (this == &other)
1416 return;
1418 data_ = other.data_;
1419 url_ref_.InvalidateCachedValues();
1420 suggestions_url_ref_.InvalidateCachedValues();
1421 instant_url_ref_.InvalidateCachedValues();
1422 SetPrepopulateId(other.data_.prepopulate_id);
1425 void TemplateURL::SetURL(const std::string& url) {
1426 data_.SetURL(url);
1427 url_ref_.InvalidateCachedValues();
1430 void TemplateURL::SetPrepopulateId(int id) {
1431 data_.prepopulate_id = id;
1432 const bool prepopulated = id > 0;
1433 url_ref_.prepopulated_ = prepopulated;
1434 suggestions_url_ref_.prepopulated_ = prepopulated;
1435 instant_url_ref_.prepopulated_ = prepopulated;
1438 void TemplateURL::ResetKeywordIfNecessary(
1439 const SearchTermsData& search_terms_data,
1440 bool force) {
1441 if (IsGoogleSearchURLWithReplaceableKeyword(search_terms_data) || force) {
1442 DCHECK(GetType() != OMNIBOX_API_EXTENSION);
1443 GURL url(GenerateSearchURL(search_terms_data));
1444 if (url.is_valid())
1445 data_.SetKeyword(GenerateKeyword(url));
1449 bool TemplateURL::FindSearchTermsInURL(
1450 const GURL& url,
1451 const SearchTermsData& search_terms_data,
1452 base::string16* search_terms,
1453 url::Parsed::ComponentType* search_term_component,
1454 url::Component* search_terms_position) {
1455 DCHECK(search_terms);
1456 search_terms->clear();
1458 // Try to match with every pattern.
1459 for (size_t i = 0; i < URLCount(); ++i) {
1460 TemplateURLRef ref(this, i);
1461 if (ref.ExtractSearchTermsFromURL(url, search_terms, search_terms_data,
1462 search_term_component, search_terms_position)) {
1463 // If ExtractSearchTermsFromURL() returns true and |search_terms| is empty
1464 // it means the pattern matched but no search terms were present. In this
1465 // case we fail immediately without looking for matches in subsequent
1466 // patterns. This means that given patterns
1467 // [ "http://foo/#q={searchTerms}", "http://foo/?q={searchTerms}" ],
1468 // calling ExtractSearchTermsFromURL() on "http://foo/?q=bar#q=' would
1469 // return false. This is important for at least Google, where such URLs
1470 // are invalid.
1471 return !search_terms->empty();
1474 return false;