Don't preload rarely seen large images
[chromium-blink-merge.git] / components / search_engines / template_url.cc
blobb30914c082c6960fb65e9f6361a3e6212b80f417
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_piece.h"
20 #include "base/strings/string_split.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "components/google/core/browser/google_util.h"
25 #include "components/metrics/proto/omnibox_input_type.pb.h"
26 #include "components/search_engines/search_engines_switches.h"
27 #include "components/search_engines/search_terms_data.h"
28 #include "google_apis/google_api_keys.h"
29 #include "net/base/escape.h"
30 #include "net/base/mime_util.h"
31 #include "net/base/net_util.h"
32 #include "ui/base/device_form_factor.h"
33 #include "url/gurl.h"
35 namespace {
37 // The TemplateURLRef has any number of terms that need to be replaced. Each of
38 // the terms is enclosed in braces. If the character preceeding the final
39 // brace is a ?, it indicates the term is optional and can be replaced with
40 // an empty string.
41 const char kStartParameter = '{';
42 const char kEndParameter = '}';
43 const char kOptional = '?';
45 // Known parameters found in the URL.
46 const char kSearchTermsParameter[] = "searchTerms";
47 const char kSearchTermsParameterFull[] = "{searchTerms}";
48 const char kSearchTermsParameterFullEscaped[] = "%7BsearchTerms%7D";
50 // Same as kSearchTermsParameter, with no escaping.
51 const char kGoogleUnescapedSearchTermsParameter[] =
52 "google:unescapedSearchTerms";
53 const char kGoogleUnescapedSearchTermsParameterFull[] =
54 "{google:unescapedSearchTerms}";
56 // Display value for kSearchTermsParameter.
57 const char kDisplaySearchTerms[] = "%s";
59 // Display value for kGoogleUnescapedSearchTermsParameter.
60 const char kDisplayUnescapedSearchTerms[] = "%S";
62 // Used if the count parameter is not optional. Indicates we want 10 search
63 // results.
64 const char kDefaultCount[] = "10";
66 // Used if the output encoding parameter is required.
67 const char kOutputEncodingType[] = "UTF-8";
69 // Attempts to encode |terms| and |original_query| in |encoding| and escape
70 // them. |terms| may be escaped as path or query depending on |is_in_query|;
71 // |original_query| is always escaped as query. Returns whether the encoding
72 // process succeeded.
73 bool TryEncoding(const base::string16& terms,
74 const base::string16& original_query,
75 const char* encoding,
76 bool is_in_query,
77 base::string16* escaped_terms,
78 base::string16* escaped_original_query) {
79 DCHECK(escaped_terms);
80 DCHECK(escaped_original_query);
81 std::string encoded_terms;
82 if (!base::UTF16ToCodepage(terms, encoding,
83 base::OnStringConversionError::SKIP, &encoded_terms))
84 return false;
85 *escaped_terms = base::UTF8ToUTF16(is_in_query ?
86 net::EscapeQueryParamValue(encoded_terms, true) :
87 net::EscapePath(encoded_terms));
88 if (original_query.empty())
89 return true;
90 std::string encoded_original_query;
91 if (!base::UTF16ToCodepage(original_query, encoding,
92 base::OnStringConversionError::SKIP, &encoded_original_query))
93 return false;
94 *escaped_original_query = base::UTF8ToUTF16(
95 net::EscapeQueryParamValue(encoded_original_query, true));
96 return true;
99 // Extract query key and host given a list of parameters coming from the URL
100 // query or ref.
101 std::string FindSearchTermsKey(const std::string& params) {
102 if (params.empty())
103 return std::string();
104 url::Component query, key, value;
105 query.len = static_cast<int>(params.size());
106 while (url::ExtractQueryKeyValue(params.c_str(), &query, &key, &value)) {
107 if (key.is_nonempty() && value.is_nonempty()) {
108 const base::StringPiece value_string(params.c_str() + value.begin,
109 value.len);
110 if (value_string.find(kSearchTermsParameterFull, 0) !=
111 base::StringPiece::npos ||
112 value_string.find(kGoogleUnescapedSearchTermsParameterFull, 0) !=
113 base::StringPiece::npos) {
114 return params.substr(key.begin, key.len);
118 return std::string();
121 // Extract the position of the search terms' parameter in the URL path.
122 bool FindSearchTermsInPath(const std::string& path,
123 url::Component* parameter_position) {
124 DCHECK(parameter_position);
125 parameter_position->reset();
126 const size_t begin = path.find(kSearchTermsParameterFullEscaped);
127 if (begin == std::string::npos)
128 return false;
129 parameter_position->begin = begin;
130 parameter_position->len = arraysize(kSearchTermsParameterFullEscaped) - 1;
131 return true;
134 bool IsTemplateParameterString(const std::string& param) {
135 return (param.length() > 2) && (*(param.begin()) == kStartParameter) &&
136 (*(param.rbegin()) == kEndParameter);
139 } // namespace
142 // TemplateURLRef::SearchTermsArgs --------------------------------------------
144 TemplateURLRef::SearchTermsArgs::SearchTermsArgs(
145 const base::string16& search_terms)
146 : search_terms(search_terms),
147 input_type(metrics::OmniboxInputType::INVALID),
148 accepted_suggestion(NO_SUGGESTIONS_AVAILABLE),
149 cursor_position(base::string16::npos),
150 enable_omnibox_start_margin(false),
151 page_classification(metrics::OmniboxEventProto::INVALID_SPEC),
152 bookmark_bar_pinned(false),
153 append_extra_query_params(false),
154 force_instant_results(false),
155 from_app_list(false),
156 contextual_search_params(ContextualSearchParams()) {
159 TemplateURLRef::SearchTermsArgs::~SearchTermsArgs() {
162 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
163 ContextualSearchParams()
164 : version(-1),
165 start(base::string16::npos),
166 end(base::string16::npos),
167 resolve(true) {
170 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
171 ContextualSearchParams(
172 const int version,
173 const std::string& selection,
174 const std::string& base_page_url,
175 const bool resolve)
176 : version(version),
177 start(base::string16::npos),
178 end(base::string16::npos),
179 selection(selection),
180 base_page_url(base_page_url),
181 resolve(resolve) {
184 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
185 ContextualSearchParams(
186 const int version,
187 const size_t start,
188 const size_t end,
189 const std::string& selection,
190 const std::string& content,
191 const std::string& base_page_url,
192 const std::string& encoding,
193 const bool resolve)
194 : version(version),
195 start(start),
196 end(end),
197 selection(selection),
198 content(content),
199 base_page_url(base_page_url),
200 encoding(encoding),
201 resolve(resolve) {
204 TemplateURLRef::SearchTermsArgs::ContextualSearchParams::
205 ~ContextualSearchParams() {
208 // TemplateURLRef -------------------------------------------------------------
210 TemplateURLRef::TemplateURLRef(const TemplateURL* owner, Type type)
211 : owner_(owner),
212 type_(type),
213 index_in_owner_(0),
214 parsed_(false),
215 valid_(false),
216 supports_replacements_(false),
217 search_term_position_in_path_(std::string::npos),
218 search_term_key_location_(url::Parsed::QUERY),
219 prepopulated_(false) {
220 DCHECK(owner_);
221 DCHECK_NE(INDEXED, type_);
224 TemplateURLRef::TemplateURLRef(const TemplateURL* owner, size_t index_in_owner)
225 : owner_(owner),
226 type_(INDEXED),
227 index_in_owner_(index_in_owner),
228 parsed_(false),
229 valid_(false),
230 supports_replacements_(false),
231 search_term_position_in_path_(std::string::npos),
232 search_term_key_location_(url::Parsed::QUERY),
233 prepopulated_(false) {
234 DCHECK(owner_);
235 DCHECK_LT(index_in_owner_, owner_->URLCount());
238 TemplateURLRef::~TemplateURLRef() {
241 std::string TemplateURLRef::GetURL() const {
242 switch (type_) {
243 case SEARCH: return owner_->url();
244 case SUGGEST: return owner_->suggestions_url();
245 case INSTANT: return owner_->instant_url();
246 case IMAGE: return owner_->image_url();
247 case NEW_TAB: return owner_->new_tab_url();
248 case CONTEXTUAL_SEARCH: return owner_->contextual_search_url();
249 case INDEXED: return owner_->GetURL(index_in_owner_);
250 default: NOTREACHED(); return std::string(); // NOLINT
254 std::string TemplateURLRef::GetPostParamsString() const {
255 switch (type_) {
256 case INDEXED:
257 case SEARCH: return owner_->search_url_post_params();
258 case SUGGEST: return owner_->suggestions_url_post_params();
259 case INSTANT: return owner_->instant_url_post_params();
260 case NEW_TAB: return std::string();
261 case CONTEXTUAL_SEARCH: return std::string();
262 case IMAGE: return owner_->image_url_post_params();
263 default: NOTREACHED(); return std::string(); // NOLINT
267 bool TemplateURLRef::UsesPOSTMethod(
268 const SearchTermsData& search_terms_data) const {
269 ParseIfNecessary(search_terms_data);
270 return !post_params_.empty();
273 bool TemplateURLRef::EncodeFormData(const PostParams& post_params,
274 PostContent* post_content) const {
275 if (post_params.empty())
276 return true;
277 if (!post_content)
278 return false;
280 const char kUploadDataMIMEType[] = "multipart/form-data; boundary=";
281 const char kMultipartBoundary[] = "----+*+----%016" PRIx64 "----+*+----";
282 // Each name/value pair is stored in a body part which is preceded by a
283 // boundary delimiter line. Uses random number generator here to create
284 // a unique boundary delimiter for form data encoding.
285 std::string boundary = base::StringPrintf(kMultipartBoundary,
286 base::RandUint64());
287 // Sets the content MIME type.
288 post_content->first = kUploadDataMIMEType;
289 post_content->first += boundary;
290 // Encodes the post parameters.
291 std::string* post_data = &post_content->second;
292 post_data->clear();
293 for (const auto& param : post_params) {
294 DCHECK(!param.name.empty());
295 net::AddMultipartValueForUpload(param.name, param.value, boundary,
296 param.content_type, post_data);
298 net::AddMultipartFinalDelimiterForUpload(boundary, post_data);
299 return true;
302 bool TemplateURLRef::SupportsReplacement(
303 const SearchTermsData& search_terms_data) const {
304 ParseIfNecessary(search_terms_data);
305 return valid_ && supports_replacements_;
308 std::string TemplateURLRef::ReplaceSearchTerms(
309 const SearchTermsArgs& search_terms_args,
310 const SearchTermsData& search_terms_data,
311 PostContent* post_content) const {
312 ParseIfNecessary(search_terms_data);
313 if (!valid_)
314 return std::string();
316 std::string url(HandleReplacements(search_terms_args, search_terms_data,
317 post_content));
319 GURL gurl(url);
320 if (!gurl.is_valid())
321 return url;
323 std::vector<std::string> query_params;
324 if (search_terms_args.append_extra_query_params) {
325 std::string extra_params(
326 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
327 switches::kExtraSearchQueryParams));
328 if (!extra_params.empty())
329 query_params.push_back(extra_params);
331 if (!search_terms_args.suggest_query_params.empty())
332 query_params.push_back(search_terms_args.suggest_query_params);
333 if (!gurl.query().empty())
334 query_params.push_back(gurl.query());
336 if (query_params.empty())
337 return url;
339 GURL::Replacements replacements;
340 std::string query_str = JoinString(query_params, "&");
341 replacements.SetQueryStr(query_str);
342 return gurl.ReplaceComponents(replacements).possibly_invalid_spec();
345 bool TemplateURLRef::IsValid(const SearchTermsData& search_terms_data) const {
346 ParseIfNecessary(search_terms_data);
347 return valid_;
350 base::string16 TemplateURLRef::DisplayURL(
351 const SearchTermsData& search_terms_data) const {
352 ParseIfNecessary(search_terms_data);
353 std::string result(GetURL());
354 if (valid_ && !replacements_.empty()) {
355 base::ReplaceSubstringsAfterOffset(&result, 0,
356 kSearchTermsParameterFull,
357 kDisplaySearchTerms);
358 base::ReplaceSubstringsAfterOffset(&result, 0,
359 kGoogleUnescapedSearchTermsParameterFull,
360 kDisplayUnescapedSearchTerms);
362 return base::UTF8ToUTF16(result);
365 // static
366 std::string TemplateURLRef::DisplayURLToURLRef(
367 const base::string16& display_url) {
368 std::string result = base::UTF16ToUTF8(display_url);
369 base::ReplaceSubstringsAfterOffset(&result, 0,
370 kDisplaySearchTerms,
371 kSearchTermsParameterFull);
372 base::ReplaceSubstringsAfterOffset(&result, 0,
373 kDisplayUnescapedSearchTerms,
374 kGoogleUnescapedSearchTermsParameterFull);
375 return result;
378 const std::string& TemplateURLRef::GetHost(
379 const SearchTermsData& search_terms_data) const {
380 ParseIfNecessary(search_terms_data);
381 return host_;
384 const std::string& TemplateURLRef::GetPath(
385 const SearchTermsData& search_terms_data) const {
386 ParseIfNecessary(search_terms_data);
387 return path_;
390 const std::string& TemplateURLRef::GetSearchTermKey(
391 const SearchTermsData& search_terms_data) const {
392 ParseIfNecessary(search_terms_data);
393 return search_term_key_;
396 size_t TemplateURLRef::GetSearchTermPositionInPath(
397 const SearchTermsData& search_terms_data) const {
398 ParseIfNecessary(search_terms_data);
399 return search_term_position_in_path_;
402 url::Parsed::ComponentType TemplateURLRef::GetSearchTermKeyLocation(
403 const SearchTermsData& search_terms_data) const {
404 ParseIfNecessary(search_terms_data);
405 return search_term_key_location_;
408 base::string16 TemplateURLRef::SearchTermToString16(
409 const std::string& term) const {
410 const std::vector<std::string>& encodings = owner_->input_encodings();
411 base::string16 result;
413 net::UnescapeRule::Type unescape_rules =
414 net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS;
415 if (search_term_key_location_ != url::Parsed::PATH)
416 unescape_rules |= net::UnescapeRule::REPLACE_PLUS_WITH_SPACE;
418 std::string unescaped = net::UnescapeURLComponent(term, unescape_rules);
419 for (size_t i = 0; i < encodings.size(); ++i) {
420 if (base::CodepageToUTF16(unescaped, encodings[i].c_str(),
421 base::OnStringConversionError::FAIL, &result))
422 return result;
425 // Always fall back on UTF-8 if it works.
426 if (base::CodepageToUTF16(unescaped, base::kCodepageUTF8,
427 base::OnStringConversionError::FAIL, &result))
428 return result;
430 // When nothing worked, just use the escaped text. We have no idea what the
431 // encoding is. We need to substitute spaces for pluses ourselves since we're
432 // not sending it through an unescaper.
433 result = base::UTF8ToUTF16(term);
434 if (unescape_rules & net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)
435 std::replace(result.begin(), result.end(), '+', ' ');
436 return result;
439 bool TemplateURLRef::HasGoogleBaseURLs(
440 const SearchTermsData& search_terms_data) const {
441 ParseIfNecessary(search_terms_data);
442 for (size_t i = 0; i < replacements_.size(); ++i) {
443 if ((replacements_[i].type == GOOGLE_BASE_URL) ||
444 (replacements_[i].type == GOOGLE_BASE_SUGGEST_URL))
445 return true;
447 return false;
450 bool TemplateURLRef::ExtractSearchTermsFromURL(
451 const GURL& url,
452 base::string16* search_terms,
453 const SearchTermsData& search_terms_data,
454 url::Parsed::ComponentType* search_terms_component,
455 url::Component* search_terms_position) const {
456 DCHECK(search_terms);
457 search_terms->clear();
459 ParseIfNecessary(search_terms_data);
461 // We need a search term in the template URL to extract something.
462 if (search_term_key_.empty() &&
463 (search_term_key_location_ != url::Parsed::PATH))
464 return false;
466 // Fill-in the replacements. We don't care about search terms in the pattern,
467 // so we use the empty string.
468 // Currently we assume the search term only shows in URL, not in post params.
469 GURL pattern(ReplaceSearchTerms(SearchTermsArgs(base::string16()),
470 search_terms_data, NULL));
471 // Host, path and port must match.
472 if ((url.port() != pattern.port()) ||
473 (url.host() != host_) ||
474 ((url.path() != path_) &&
475 (search_term_key_location_ != url::Parsed::PATH))) {
476 return false;
479 std::string source;
480 url::Component position;
482 if (search_term_key_location_ == url::Parsed::PATH) {
483 source = url.path();
485 // Characters in the path before and after search terms must match.
486 if (source.length() < path_.length())
487 return false;
488 position.begin = search_term_position_in_path_;
489 position.len = source.length() - path_.length();
490 if (source.substr(0, position.begin) + source.substr(position.end()) !=
491 path_)
492 return false;
493 } else {
494 DCHECK(search_term_key_location_ == url::Parsed::QUERY ||
495 search_term_key_location_ == url::Parsed::REF);
496 source = (search_term_key_location_ == url::Parsed::QUERY) ?
497 url.query() : url.ref();
499 url::Component query, key, value;
500 query.len = static_cast<int>(source.size());
501 bool key_found = false;
502 while (url::ExtractQueryKeyValue(source.c_str(), &query, &key, &value)) {
503 if (key.is_nonempty()) {
504 if (source.substr(key.begin, key.len) == search_term_key_) {
505 // Fail if search term key is found twice.
506 if (key_found)
507 return false;
508 key_found = true;
509 position = value;
513 if (!key_found)
514 return false;
517 // Extract the search term.
518 *search_terms = SearchTermToString16(
519 source.substr(position.begin, position.len));
520 if (search_terms_component)
521 *search_terms_component = search_term_key_location_;
522 if (search_terms_position)
523 *search_terms_position = position;
524 return true;
527 void TemplateURLRef::InvalidateCachedValues() const {
528 supports_replacements_ = valid_ = parsed_ = false;
529 host_.clear();
530 path_.clear();
531 search_term_key_.clear();
532 search_term_position_in_path_ = std::string::npos;
533 search_term_key_location_ = url::Parsed::QUERY;
534 replacements_.clear();
535 post_params_.clear();
538 bool TemplateURLRef::ParseParameter(size_t start,
539 size_t end,
540 std::string* url,
541 Replacements* replacements) const {
542 DCHECK(start != std::string::npos &&
543 end != std::string::npos && end > start);
544 size_t length = end - start - 1;
545 bool optional = false;
546 // Make a copy of |url| that can be referenced in StringPieces below. |url| is
547 // modified, so that can't be used in StringPiece.
548 const std::string original_url(*url);
549 if (original_url[end - 1] == kOptional) {
550 optional = true;
551 length--;
554 const base::StringPiece parameter(original_url.begin() + start + 1,
555 original_url.begin() + start + 1 + length);
556 const base::StringPiece full_parameter(original_url.begin() + start,
557 original_url.begin() + end + 1);
558 // Remove the parameter from the string. For parameters who replacement is
559 // constant and already known, just replace them directly. For other cases,
560 // like parameters whose values may change over time, use |replacements|.
561 url->erase(start, end - start + 1);
562 if (parameter == kSearchTermsParameter) {
563 replacements->push_back(Replacement(SEARCH_TERMS, start));
564 } else if (parameter == "count") {
565 if (!optional)
566 url->insert(start, kDefaultCount);
567 } else if (parameter == "google:assistedQueryStats") {
568 replacements->push_back(Replacement(GOOGLE_ASSISTED_QUERY_STATS, start));
569 } else if (parameter == "google:baseURL") {
570 replacements->push_back(Replacement(GOOGLE_BASE_URL, start));
571 } else if (parameter == "google:baseSuggestURL") {
572 replacements->push_back(Replacement(GOOGLE_BASE_SUGGEST_URL, start));
573 } else if (parameter == "google:bookmarkBarPinned") {
574 replacements->push_back(Replacement(GOOGLE_BOOKMARK_BAR_PINNED, start));
575 } else if (parameter == "google:currentPageUrl") {
576 replacements->push_back(Replacement(GOOGLE_CURRENT_PAGE_URL, start));
577 } else if (parameter == "google:cursorPosition") {
578 replacements->push_back(Replacement(GOOGLE_CURSOR_POSITION, start));
579 } else if (parameter == "google:forceInstantResults") {
580 replacements->push_back(Replacement(GOOGLE_FORCE_INSTANT_RESULTS, start));
581 } else if (parameter == "google:imageOriginalHeight") {
582 replacements->push_back(
583 Replacement(TemplateURLRef::GOOGLE_IMAGE_ORIGINAL_HEIGHT, start));
584 } else if (parameter == "google:imageOriginalWidth") {
585 replacements->push_back(
586 Replacement(TemplateURLRef::GOOGLE_IMAGE_ORIGINAL_WIDTH, start));
587 } else if (parameter == "google:imageSearchSource") {
588 replacements->push_back(
589 Replacement(TemplateURLRef::GOOGLE_IMAGE_SEARCH_SOURCE, start));
590 } else if (parameter == "google:imageThumbnail") {
591 replacements->push_back(
592 Replacement(TemplateURLRef::GOOGLE_IMAGE_THUMBNAIL, start));
593 } else if (parameter == "google:imageURL") {
594 replacements->push_back(Replacement(TemplateURLRef::GOOGLE_IMAGE_URL,
595 start));
596 } else if (parameter == "google:inputType") {
597 replacements->push_back(Replacement(TemplateURLRef::GOOGLE_INPUT_TYPE,
598 start));
599 } else if (parameter == "google:instantExtendedEnabledParameter") {
600 replacements->push_back(Replacement(GOOGLE_INSTANT_EXTENDED_ENABLED,
601 start));
602 } else if (parameter == "google:instantExtendedEnabledKey") {
603 url->insert(start, google_util::kInstantExtendedAPIParam);
604 } else if (parameter == "google:ntpIsThemedParameter") {
605 replacements->push_back(Replacement(GOOGLE_NTP_IS_THEMED, start));
606 } else if (parameter == "google:omniboxStartMarginParameter") {
607 replacements->push_back(Replacement(GOOGLE_OMNIBOX_START_MARGIN, start));
608 } else if (parameter == "google:contextualSearchVersion") {
609 replacements->push_back(
610 Replacement(GOOGLE_CONTEXTUAL_SEARCH_VERSION, start));
611 } else if (parameter == "google:contextualSearchContextData") {
612 replacements->push_back(
613 Replacement(GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA, start));
614 } else if (parameter == "google:originalQueryForSuggestion") {
615 replacements->push_back(Replacement(GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION,
616 start));
617 } else if (parameter == "google:pageClassification") {
618 replacements->push_back(Replacement(GOOGLE_PAGE_CLASSIFICATION, start));
619 } else if (parameter == "google:prefetchQuery") {
620 replacements->push_back(Replacement(GOOGLE_PREFETCH_QUERY, start));
621 } else if (parameter == "google:RLZ") {
622 replacements->push_back(Replacement(GOOGLE_RLZ, start));
623 } else if (parameter == "google:searchClient") {
624 replacements->push_back(Replacement(GOOGLE_SEARCH_CLIENT, start));
625 } else if (parameter == "google:searchFieldtrialParameter") {
626 replacements->push_back(Replacement(GOOGLE_SEARCH_FIELDTRIAL_GROUP, start));
627 } else if (parameter == "google:searchVersion") {
628 replacements->push_back(Replacement(GOOGLE_SEARCH_VERSION, start));
629 } else if (parameter == "google:sessionToken") {
630 replacements->push_back(Replacement(GOOGLE_SESSION_TOKEN, start));
631 } else if (parameter == "google:sourceId") {
632 #if defined(OS_ANDROID) || defined(OS_IOS)
633 url->insert(start, "sourceid=chrome-mobile&");
634 #else
635 url->insert(start, "sourceid=chrome&");
636 #endif
637 } else if (parameter == "google:suggestAPIKeyParameter") {
638 url->insert(start,
639 net::EscapeQueryParamValue(google_apis::GetAPIKey(), false));
640 } else if (parameter == "google:suggestClient") {
641 replacements->push_back(Replacement(GOOGLE_SUGGEST_CLIENT, start));
642 } else if (parameter == "google:suggestRid") {
643 replacements->push_back(Replacement(GOOGLE_SUGGEST_REQUEST_ID, start));
644 } else if (parameter == kGoogleUnescapedSearchTermsParameter) {
645 replacements->push_back(Replacement(GOOGLE_UNESCAPED_SEARCH_TERMS, start));
646 } else if (parameter == "yandex:searchPath") {
647 switch (ui::GetDeviceFormFactor()) {
648 case ui::DEVICE_FORM_FACTOR_DESKTOP:
649 url->insert(start, "yandsearch");
650 break;
651 case ui::DEVICE_FORM_FACTOR_PHONE:
652 url->insert(start, "touchsearch");
653 break;
654 case ui::DEVICE_FORM_FACTOR_TABLET:
655 url->insert(start, "padsearch");
656 break;
658 } else if (parameter == "inputEncoding") {
659 replacements->push_back(Replacement(ENCODING, start));
660 } else if (parameter == "language") {
661 replacements->push_back(Replacement(LANGUAGE, start));
662 } else if (parameter == "outputEncoding") {
663 if (!optional)
664 url->insert(start, kOutputEncodingType);
665 } else if ((parameter == "startIndex") || (parameter == "startPage")) {
666 // We don't support these.
667 if (!optional)
668 url->insert(start, "1");
669 } else if (!prepopulated_) {
670 // If it's a prepopulated URL, we know that it's safe to remove unknown
671 // parameters, so just ignore this and return true below. Otherwise it could
672 // be some garbage but can also be a javascript block. Put it back.
673 url->insert(start, full_parameter.data(), full_parameter.size());
674 return false;
676 return true;
679 std::string TemplateURLRef::ParseURL(const std::string& url,
680 Replacements* replacements,
681 PostParams* post_params,
682 bool* valid) const {
683 *valid = false;
684 std::string parsed_url = url;
685 for (size_t last = 0; last != std::string::npos; ) {
686 last = parsed_url.find(kStartParameter, last);
687 if (last != std::string::npos) {
688 size_t template_end = parsed_url.find(kEndParameter, last);
689 if (template_end != std::string::npos) {
690 // Since we allow Javascript in the URL, {} pairs could be nested. Match
691 // only leaf pairs with supported parameters.
692 size_t next_template_start = parsed_url.find(kStartParameter, last + 1);
693 if (next_template_start == std::string::npos ||
694 next_template_start > template_end) {
695 // If successful, ParseParameter erases from the string as such no
696 // need to update |last|. If failed, move |last| to the end of pair.
697 if (!ParseParameter(last, template_end, &parsed_url, replacements)) {
698 // |template_end| + 1 may be beyond the end of the string.
699 last = template_end;
701 } else {
702 last = next_template_start;
704 } else {
705 // Open brace without a closing brace, return.
706 return std::string();
711 // Handles the post parameters.
712 const std::string& post_params_string = GetPostParamsString();
713 if (!post_params_string.empty()) {
714 typedef std::vector<std::string> Strings;
715 Strings param_list;
716 base::SplitString(post_params_string, ',', &param_list);
718 for (Strings::const_iterator iterator = param_list.begin();
719 iterator != param_list.end(); ++iterator) {
720 Strings parts;
721 // The '=' delimiter is required and the name must be not empty.
722 base::SplitString(*iterator, '=', &parts);
723 if ((parts.size() != 2U) || parts[0].empty())
724 return std::string();
726 std::string& value = parts[1];
727 size_t replacements_size = replacements->size();
728 if (IsTemplateParameterString(value))
729 ParseParameter(0, value.length() - 1, &value, replacements);
730 PostParam param = { parts[0], value };
731 post_params->push_back(param);
732 // If there was a replacement added, points its index to last added
733 // PostParam.
734 if (replacements->size() > replacements_size) {
735 DCHECK_EQ(replacements_size + 1, replacements->size());
736 Replacement* r = &replacements->back();
737 r->is_post_param = true;
738 r->index = post_params->size() - 1;
741 DCHECK(!post_params->empty());
744 *valid = true;
745 return parsed_url;
748 void TemplateURLRef::ParseIfNecessary(
749 const SearchTermsData& search_terms_data) const {
750 if (!parsed_) {
751 InvalidateCachedValues();
752 parsed_ = true;
753 parsed_url_ = ParseURL(GetURL(), &replacements_, &post_params_, &valid_);
754 supports_replacements_ = false;
755 if (valid_) {
756 bool has_only_one_search_term = false;
757 for (Replacements::const_iterator i = replacements_.begin();
758 i != replacements_.end(); ++i) {
759 if ((i->type == SEARCH_TERMS) ||
760 (i->type == GOOGLE_UNESCAPED_SEARCH_TERMS)) {
761 if (has_only_one_search_term) {
762 has_only_one_search_term = false;
763 break;
765 has_only_one_search_term = true;
766 supports_replacements_ = true;
769 // Only parse the host/key if there is one search term. Technically there
770 // could be more than one term, but it's uncommon; so we punt.
771 if (has_only_one_search_term)
772 ParseHostAndSearchTermKey(search_terms_data);
777 void TemplateURLRef::ParseHostAndSearchTermKey(
778 const SearchTermsData& search_terms_data) const {
779 std::string url_string(GetURL());
780 base::ReplaceSubstringsAfterOffset(
781 &url_string, 0, "{google:baseURL}",
782 search_terms_data.GoogleBaseURLValue());
783 base::ReplaceSubstringsAfterOffset(
784 &url_string, 0, "{google:baseSuggestURL}",
785 search_terms_data.GoogleBaseSuggestURLValue());
787 search_term_key_.clear();
788 search_term_position_in_path_ = std::string::npos;
789 host_.clear();
790 path_.clear();
791 search_term_key_location_ = url::Parsed::QUERY;
793 GURL url(url_string);
794 if (!url.is_valid())
795 return;
797 std::string query_key = FindSearchTermsKey(url.query());
798 std::string ref_key = FindSearchTermsKey(url.ref());
799 url::Component parameter_position;
800 const bool in_query = !query_key.empty();
801 const bool in_ref = !ref_key.empty();
802 const bool in_path = FindSearchTermsInPath(url.path(), &parameter_position);
803 if (in_query ? (in_ref || in_path) : (in_ref == in_path))
804 return; // No key or multiple keys found. We only handle having one key.
806 host_ = url.host();
807 path_ = url.path();
808 if (in_query) {
809 search_term_key_ = query_key;
810 search_term_key_location_ = url::Parsed::QUERY;
811 } else if (in_ref) {
812 search_term_key_ = ref_key;
813 search_term_key_location_ = url::Parsed::REF;
814 } else {
815 DCHECK(in_path);
816 DCHECK_GE(parameter_position.begin, 1); // Path must start with '/'.
817 search_term_key_location_ = url::Parsed::PATH;
818 search_term_position_in_path_ = parameter_position.begin;
819 // Remove the "{searchTerms}" itself from |path_|.
820 path_.erase(parameter_position.begin, parameter_position.len);
824 void TemplateURLRef::HandleReplacement(const std::string& name,
825 const std::string& value,
826 const Replacement& replacement,
827 std::string* url) const {
828 size_t pos = replacement.index;
829 if (replacement.is_post_param) {
830 DCHECK_LT(pos, post_params_.size());
831 DCHECK(!post_params_[pos].name.empty());
832 post_params_[pos].value = value;
833 } else {
834 url->insert(pos, name.empty() ? value : (name + "=" + value + "&"));
838 std::string TemplateURLRef::HandleReplacements(
839 const SearchTermsArgs& search_terms_args,
840 const SearchTermsData& search_terms_data,
841 PostContent* post_content) const {
842 if (replacements_.empty()) {
843 if (!post_params_.empty())
844 EncodeFormData(post_params_, post_content);
845 return parsed_url_;
848 // Determine if the search terms are in the query or before. We're escaping
849 // space as '+' in the former case and as '%20' in the latter case.
850 bool is_in_query = true;
851 for (Replacements::iterator i = replacements_.begin();
852 i != replacements_.end(); ++i) {
853 if (i->type == SEARCH_TERMS) {
854 base::string16::size_type query_start = parsed_url_.find('?');
855 is_in_query = query_start != base::string16::npos &&
856 (static_cast<base::string16::size_type>(i->index) > query_start);
857 break;
861 std::string input_encoding;
862 base::string16 encoded_terms;
863 base::string16 encoded_original_query;
864 owner_->EncodeSearchTerms(search_terms_args, is_in_query, &input_encoding,
865 &encoded_terms, &encoded_original_query);
867 std::string url = parsed_url_;
869 // replacements_ is ordered in ascending order, as such we need to iterate
870 // from the back.
871 for (Replacements::reverse_iterator i = replacements_.rbegin();
872 i != replacements_.rend(); ++i) {
873 switch (i->type) {
874 case ENCODING:
875 HandleReplacement(std::string(), input_encoding, *i, &url);
876 break;
878 case GOOGLE_ASSISTED_QUERY_STATS:
879 DCHECK(!i->is_post_param);
880 if (!search_terms_args.assisted_query_stats.empty()) {
881 // Get the base URL without substituting AQS to avoid infinite
882 // recursion. We need the URL to find out if it meets all
883 // AQS requirements (e.g. HTTPS protocol check).
884 // See TemplateURLRef::SearchTermsArgs for more details.
885 SearchTermsArgs search_terms_args_without_aqs(search_terms_args);
886 search_terms_args_without_aqs.assisted_query_stats.clear();
887 GURL base_url(ReplaceSearchTerms(
888 search_terms_args_without_aqs, search_terms_data, NULL));
889 if (base_url.SchemeIsCryptographic()) {
890 HandleReplacement(
891 "aqs", search_terms_args.assisted_query_stats, *i, &url);
894 break;
896 case GOOGLE_BASE_URL:
897 DCHECK(!i->is_post_param);
898 HandleReplacement(
899 std::string(), search_terms_data.GoogleBaseURLValue(), *i, &url);
900 break;
902 case GOOGLE_BASE_SUGGEST_URL:
903 DCHECK(!i->is_post_param);
904 HandleReplacement(
905 std::string(), search_terms_data.GoogleBaseSuggestURLValue(), *i,
906 &url);
907 break;
909 case GOOGLE_BOOKMARK_BAR_PINNED:
910 if (search_terms_data.IsShowingSearchTermsOnSearchResultsPages()) {
911 // Log whether the bookmark bar is pinned when the user is seeing
912 // InstantExtended on the SRP.
913 DCHECK(!i->is_post_param);
914 HandleReplacement(
915 "bmbp", search_terms_args.bookmark_bar_pinned ? "1" : "0", *i,
916 &url);
918 break;
920 case GOOGLE_CURRENT_PAGE_URL:
921 DCHECK(!i->is_post_param);
922 if (!search_terms_args.current_page_url.empty()) {
923 const std::string& escaped_current_page_url =
924 net::EscapeQueryParamValue(search_terms_args.current_page_url,
925 true);
926 HandleReplacement("url", escaped_current_page_url, *i, &url);
928 break;
930 case GOOGLE_CURSOR_POSITION:
931 DCHECK(!i->is_post_param);
932 if (search_terms_args.cursor_position != base::string16::npos)
933 HandleReplacement(
934 "cp",
935 base::StringPrintf("%" PRIuS, search_terms_args.cursor_position),
937 &url);
938 break;
940 case GOOGLE_FORCE_INSTANT_RESULTS:
941 DCHECK(!i->is_post_param);
942 HandleReplacement(std::string(),
943 search_terms_data.ForceInstantResultsParam(
944 search_terms_args.force_instant_results),
946 &url);
947 break;
949 case GOOGLE_INPUT_TYPE:
950 DCHECK(!i->is_post_param);
951 HandleReplacement(
952 "oit", base::IntToString(search_terms_args.input_type), *i, &url);
953 break;
955 case GOOGLE_INSTANT_EXTENDED_ENABLED:
956 DCHECK(!i->is_post_param);
957 HandleReplacement(std::string(),
958 search_terms_data.InstantExtendedEnabledParam(
959 type_ == SEARCH),
961 &url);
962 break;
964 case GOOGLE_NTP_IS_THEMED:
965 DCHECK(!i->is_post_param);
966 HandleReplacement(
967 std::string(), search_terms_data.NTPIsThemedParam(), *i, &url);
968 break;
970 case GOOGLE_OMNIBOX_START_MARGIN:
971 DCHECK(!i->is_post_param);
972 if (search_terms_args.enable_omnibox_start_margin) {
973 int omnibox_start_margin = search_terms_data.OmniboxStartMargin();
974 if (omnibox_start_margin >= 0) {
975 HandleReplacement("es_sm", base::IntToString(omnibox_start_margin),
976 *i, &url);
979 break;
981 case GOOGLE_CONTEXTUAL_SEARCH_VERSION:
982 if (search_terms_args.contextual_search_params.version >= 0) {
983 HandleReplacement(
984 "ctxs",
985 base::IntToString(
986 search_terms_args.contextual_search_params.version),
988 &url);
990 break;
992 case GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA: {
993 DCHECK(!i->is_post_param);
994 std::string context_data;
996 const SearchTermsArgs::ContextualSearchParams& params =
997 search_terms_args.contextual_search_params;
999 if (params.start != std::string::npos) {
1000 context_data.append("ctxs_start=" + base::IntToString(
1001 params.start) + "&");
1004 if (params.end != std::string::npos) {
1005 context_data.append("ctxs_end=" + base::IntToString(
1006 params.end) + "&");
1009 if (!params.selection.empty())
1010 context_data.append("q=" + params.selection + "&");
1012 if (!params.content.empty())
1013 context_data.append("ctxs_content=" + params.content + "&");
1015 if (!params.base_page_url.empty())
1016 context_data.append("ctxsl_url=" + params.base_page_url + "&");
1018 if (!params.encoding.empty()) {
1019 context_data.append("ctxs_encoding=" + params.encoding + "&");
1022 context_data.append(
1023 params.resolve ? "ctxsl_resolve=1" : "ctxsl_resolve=0");
1025 HandleReplacement(std::string(), context_data, *i, &url);
1026 break;
1029 case GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION:
1030 DCHECK(!i->is_post_param);
1031 if (search_terms_args.accepted_suggestion >= 0 ||
1032 !search_terms_args.assisted_query_stats.empty()) {
1033 HandleReplacement(
1034 "oq", base::UTF16ToUTF8(encoded_original_query), *i, &url);
1036 break;
1038 case GOOGLE_PAGE_CLASSIFICATION:
1039 if (search_terms_args.page_classification !=
1040 metrics::OmniboxEventProto::INVALID_SPEC) {
1041 HandleReplacement(
1042 "pgcl", base::IntToString(search_terms_args.page_classification),
1043 *i, &url);
1045 break;
1047 case GOOGLE_PREFETCH_QUERY: {
1048 const std::string& query = search_terms_args.prefetch_query;
1049 const std::string& type = search_terms_args.prefetch_query_type;
1050 if (!query.empty() && !type.empty()) {
1051 HandleReplacement(
1052 std::string(), "pfq=" + query + "&qha=" + type + "&", *i, &url);
1054 break;
1057 case GOOGLE_RLZ: {
1058 DCHECK(!i->is_post_param);
1059 // On platforms that don't have RLZ, we still want this branch
1060 // to happen so that we replace the RLZ template with the
1061 // empty string. (If we don't handle this case, we hit a
1062 // NOTREACHED below.)
1063 base::string16 rlz_string = search_terms_data.GetRlzParameterValue(
1064 search_terms_args.from_app_list);
1065 if (!rlz_string.empty()) {
1066 HandleReplacement("rlz", base::UTF16ToUTF8(rlz_string), *i, &url);
1068 break;
1071 case GOOGLE_SEARCH_CLIENT: {
1072 DCHECK(!i->is_post_param);
1073 std::string client = search_terms_data.GetSearchClient();
1074 if (!client.empty())
1075 HandleReplacement("client", client, *i, &url);
1076 break;
1079 case GOOGLE_SEARCH_FIELDTRIAL_GROUP:
1080 // We are not currently running any fieldtrials that modulate the search
1081 // url. If we do, then we'd have some conditional insert such as:
1082 // url.insert(i->index, used_www ? "gcx=w&" : "gcx=c&");
1083 break;
1085 case GOOGLE_SEARCH_VERSION:
1086 if (search_terms_data.EnableAnswersInSuggest())
1087 HandleReplacement("gs_rn", "42", *i, &url);
1088 break;
1090 case GOOGLE_SESSION_TOKEN: {
1091 std::string token = search_terms_args.session_token;
1092 if (!token.empty())
1093 HandleReplacement("psi", token, *i, &url);
1094 break;
1097 case GOOGLE_SUGGEST_CLIENT:
1098 HandleReplacement(
1099 std::string(), search_terms_data.GetSuggestClient(), *i, &url);
1100 break;
1102 case GOOGLE_SUGGEST_REQUEST_ID:
1103 HandleReplacement(
1104 std::string(), search_terms_data.GetSuggestRequestIdentifier(), *i,
1105 &url);
1106 break;
1108 case GOOGLE_UNESCAPED_SEARCH_TERMS: {
1109 std::string unescaped_terms;
1110 base::UTF16ToCodepage(search_terms_args.search_terms,
1111 input_encoding.c_str(),
1112 base::OnStringConversionError::SKIP,
1113 &unescaped_terms);
1114 HandleReplacement(std::string(), unescaped_terms, *i, &url);
1115 break;
1118 case LANGUAGE:
1119 HandleReplacement(
1120 std::string(), search_terms_data.GetApplicationLocale(), *i, &url);
1121 break;
1123 case SEARCH_TERMS:
1124 HandleReplacement(
1125 std::string(), base::UTF16ToUTF8(encoded_terms), *i, &url);
1126 break;
1128 case GOOGLE_IMAGE_THUMBNAIL:
1129 HandleReplacement(
1130 std::string(), search_terms_args.image_thumbnail_content, *i, &url);
1131 post_params_[i->index].content_type = "image/jpeg";
1132 break;
1134 case GOOGLE_IMAGE_URL:
1135 if (search_terms_args.image_url.is_valid()) {
1136 HandleReplacement(
1137 std::string(), search_terms_args.image_url.spec(), *i, &url);
1139 break;
1141 case GOOGLE_IMAGE_ORIGINAL_WIDTH:
1142 if (!search_terms_args.image_original_size.IsEmpty()) {
1143 HandleReplacement(
1144 std::string(),
1145 base::IntToString(search_terms_args.image_original_size.width()),
1146 *i, &url);
1148 break;
1150 case GOOGLE_IMAGE_ORIGINAL_HEIGHT:
1151 if (!search_terms_args.image_original_size.IsEmpty()) {
1152 HandleReplacement(
1153 std::string(),
1154 base::IntToString(search_terms_args.image_original_size.height()),
1155 *i, &url);
1157 break;
1159 case GOOGLE_IMAGE_SEARCH_SOURCE:
1160 HandleReplacement(
1161 std::string(), search_terms_data.GoogleImageSearchSource(), *i,
1162 &url);
1163 break;
1165 default:
1166 NOTREACHED();
1167 break;
1171 if (!post_params_.empty())
1172 EncodeFormData(post_params_, post_content);
1174 return url;
1178 // TemplateURL ----------------------------------------------------------------
1180 TemplateURL::AssociatedExtensionInfo::AssociatedExtensionInfo(
1181 Type type,
1182 const std::string& extension_id)
1183 : type(type),
1184 extension_id(extension_id),
1185 wants_to_be_default_engine(false) {
1186 DCHECK_NE(NORMAL, type);
1189 TemplateURL::AssociatedExtensionInfo::~AssociatedExtensionInfo() {
1192 TemplateURL::TemplateURL(const TemplateURLData& data)
1193 : data_(data),
1194 url_ref_(this, TemplateURLRef::SEARCH),
1195 suggestions_url_ref_(this,
1196 TemplateURLRef::SUGGEST),
1197 instant_url_ref_(this,
1198 TemplateURLRef::INSTANT),
1199 image_url_ref_(this, TemplateURLRef::IMAGE),
1200 new_tab_url_ref_(this, TemplateURLRef::NEW_TAB),
1201 contextual_search_url_ref_(this, TemplateURLRef::CONTEXTUAL_SEARCH) {
1202 SetPrepopulateId(data_.prepopulate_id);
1204 if (data_.search_terms_replacement_key ==
1205 "{google:instantExtendedEnabledKey}") {
1206 data_.search_terms_replacement_key = google_util::kInstantExtendedAPIParam;
1210 TemplateURL::~TemplateURL() {
1213 // static
1214 base::string16 TemplateURL::GenerateKeyword(const GURL& url) {
1215 DCHECK(url.is_valid());
1216 // Strip "www." off the front of the keyword; otherwise the keyword won't work
1217 // properly. See http://code.google.com/p/chromium/issues/detail?id=6984 .
1218 // Special case: if the host was exactly "www." (not sure this can happen but
1219 // perhaps with some weird intranet and custom DNS server?), ensure we at
1220 // least don't return the empty string.
1221 base::string16 keyword(net::StripWWWFromHost(url));
1222 return keyword.empty() ? base::ASCIIToUTF16("www") : keyword;
1225 // static
1226 GURL TemplateURL::GenerateFaviconURL(const GURL& url) {
1227 DCHECK(url.is_valid());
1228 GURL::Replacements rep;
1230 const char favicon_path[] = "/favicon.ico";
1231 int favicon_path_len = arraysize(favicon_path) - 1;
1233 rep.SetPath(favicon_path, url::Component(0, favicon_path_len));
1234 rep.ClearUsername();
1235 rep.ClearPassword();
1236 rep.ClearQuery();
1237 rep.ClearRef();
1238 return url.ReplaceComponents(rep);
1241 // static
1242 bool TemplateURL::MatchesData(const TemplateURL* t_url,
1243 const TemplateURLData* data,
1244 const SearchTermsData& search_terms_data) {
1245 if (!t_url || !data)
1246 return !t_url && !data;
1248 return (t_url->short_name() == data->short_name()) &&
1249 t_url->HasSameKeywordAs(*data, search_terms_data) &&
1250 (t_url->url() == data->url()) &&
1251 (t_url->suggestions_url() == data->suggestions_url) &&
1252 (t_url->instant_url() == data->instant_url) &&
1253 (t_url->image_url() == data->image_url) &&
1254 (t_url->new_tab_url() == data->new_tab_url) &&
1255 (t_url->search_url_post_params() == data->search_url_post_params) &&
1256 (t_url->suggestions_url_post_params() ==
1257 data->suggestions_url_post_params) &&
1258 (t_url->instant_url_post_params() == data->instant_url_post_params) &&
1259 (t_url->image_url_post_params() == data->image_url_post_params) &&
1260 (t_url->favicon_url() == data->favicon_url) &&
1261 (t_url->safe_for_autoreplace() == data->safe_for_autoreplace) &&
1262 (t_url->show_in_default_list() == data->show_in_default_list) &&
1263 (t_url->input_encodings() == data->input_encodings) &&
1264 (t_url->alternate_urls() == data->alternate_urls) &&
1265 (t_url->search_terms_replacement_key() ==
1266 data->search_terms_replacement_key);
1269 base::string16 TemplateURL::AdjustedShortNameForLocaleDirection() const {
1270 base::string16 bidi_safe_short_name = data_.short_name();
1271 base::i18n::AdjustStringForLocaleDirection(&bidi_safe_short_name);
1272 return bidi_safe_short_name;
1275 bool TemplateURL::ShowInDefaultList(
1276 const SearchTermsData& search_terms_data) const {
1277 return data_.show_in_default_list &&
1278 url_ref_.SupportsReplacement(search_terms_data);
1281 bool TemplateURL::SupportsReplacement(
1282 const SearchTermsData& search_terms_data) const {
1283 return url_ref_.SupportsReplacement(search_terms_data);
1286 bool TemplateURL::HasGoogleBaseURLs(
1287 const SearchTermsData& search_terms_data) const {
1288 return url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1289 suggestions_url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1290 instant_url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1291 image_url_ref_.HasGoogleBaseURLs(search_terms_data) ||
1292 new_tab_url_ref_.HasGoogleBaseURLs(search_terms_data);
1295 bool TemplateURL::IsGoogleSearchURLWithReplaceableKeyword(
1296 const SearchTermsData& search_terms_data) const {
1297 return (GetType() == NORMAL) &&
1298 url_ref_.HasGoogleBaseURLs(search_terms_data) &&
1299 google_util::IsGoogleHostname(base::UTF16ToUTF8(data_.keyword()),
1300 google_util::DISALLOW_SUBDOMAIN);
1303 bool TemplateURL::HasSameKeywordAs(
1304 const TemplateURLData& other,
1305 const SearchTermsData& search_terms_data) const {
1306 return (data_.keyword() == other.keyword()) ||
1307 (IsGoogleSearchURLWithReplaceableKeyword(search_terms_data) &&
1308 TemplateURL(other).IsGoogleSearchURLWithReplaceableKeyword(
1309 search_terms_data));
1312 TemplateURL::Type TemplateURL::GetType() const {
1313 return extension_info_ ? extension_info_->type : NORMAL;
1316 std::string TemplateURL::GetExtensionId() const {
1317 DCHECK(extension_info_);
1318 return extension_info_->extension_id;
1321 size_t TemplateURL::URLCount() const {
1322 // Add 1 for the regular search URL.
1323 return data_.alternate_urls.size() + 1;
1326 const std::string& TemplateURL::GetURL(size_t index) const {
1327 DCHECK_LT(index, URLCount());
1329 return (index < data_.alternate_urls.size()) ?
1330 data_.alternate_urls[index] : url();
1333 bool TemplateURL::ExtractSearchTermsFromURL(
1334 const GURL& url,
1335 const SearchTermsData& search_terms_data,
1336 base::string16* search_terms) const {
1337 return FindSearchTermsInURL(url, search_terms_data, search_terms, NULL, NULL);
1340 bool TemplateURL::IsSearchURL(const GURL& url,
1341 const SearchTermsData& search_terms_data) const {
1342 base::string16 search_terms;
1343 return ExtractSearchTermsFromURL(url, search_terms_data, &search_terms) &&
1344 !search_terms.empty();
1347 bool TemplateURL::HasSearchTermsReplacementKey(const GURL& url) const {
1348 // Look for the key both in the query and the ref.
1349 std::string params[] = {url.query(), url.ref()};
1351 for (int i = 0; i < 2; ++i) {
1352 url::Component query, key, value;
1353 query.len = static_cast<int>(params[i].size());
1354 while (url::ExtractQueryKeyValue(params[i].c_str(), &query, &key, &value)) {
1355 if (key.is_nonempty() &&
1356 params[i].substr(key.begin, key.len) ==
1357 search_terms_replacement_key()) {
1358 return true;
1362 return false;
1365 bool TemplateURL::ReplaceSearchTermsInURL(
1366 const GURL& url,
1367 const TemplateURLRef::SearchTermsArgs& search_terms_args,
1368 const SearchTermsData& search_terms_data,
1369 GURL* result) {
1370 // TODO(beaudoin): Use AQS from |search_terms_args| too.
1371 url::Parsed::ComponentType search_term_component;
1372 url::Component search_terms_position;
1373 base::string16 search_terms;
1374 if (!FindSearchTermsInURL(url, search_terms_data, &search_terms,
1375 &search_term_component, &search_terms_position)) {
1376 return false;
1378 DCHECK(search_terms_position.is_nonempty());
1380 // Query and ref are encoded in the same way.
1381 const bool is_in_query = (search_term_component != url::Parsed::PATH);
1383 std::string input_encoding;
1384 base::string16 encoded_terms;
1385 base::string16 encoded_original_query;
1386 EncodeSearchTerms(search_terms_args, is_in_query, &input_encoding,
1387 &encoded_terms, &encoded_original_query);
1389 std::string old_params;
1390 if (search_term_component == url::Parsed::QUERY) {
1391 old_params = url.query();
1392 } else if (search_term_component == url::Parsed::REF) {
1393 old_params = url.ref();
1394 } else {
1395 DCHECK_EQ(search_term_component, url::Parsed::PATH);
1396 old_params = url.path();
1399 std::string new_params(old_params, 0, search_terms_position.begin);
1400 new_params += base::UTF16ToUTF8(encoded_terms);
1401 new_params += old_params.substr(search_terms_position.end());
1402 GURL::Replacements replacements;
1404 if (search_term_component == url::Parsed::QUERY) {
1405 replacements.SetQueryStr(new_params);
1406 } else if (search_term_component == url::Parsed::REF) {
1407 replacements.SetRefStr(new_params);
1408 } else {
1409 DCHECK_EQ(search_term_component, url::Parsed::PATH);
1410 replacements.SetPathStr(new_params);
1413 *result = url.ReplaceComponents(replacements);
1414 return true;
1417 void TemplateURL::EncodeSearchTerms(
1418 const TemplateURLRef::SearchTermsArgs& search_terms_args,
1419 bool is_in_query,
1420 std::string* input_encoding,
1421 base::string16* encoded_terms,
1422 base::string16* encoded_original_query) const {
1424 std::vector<std::string> encodings(input_encodings());
1425 if (std::find(encodings.begin(), encodings.end(), "UTF-8") == encodings.end())
1426 encodings.push_back("UTF-8");
1427 for (std::vector<std::string>::const_iterator i(encodings.begin());
1428 i != encodings.end(); ++i) {
1429 if (TryEncoding(search_terms_args.search_terms,
1430 search_terms_args.original_query, i->c_str(),
1431 is_in_query, encoded_terms, encoded_original_query)) {
1432 *input_encoding = *i;
1433 return;
1436 NOTREACHED();
1439 GURL TemplateURL::GenerateSearchURL(
1440 const SearchTermsData& search_terms_data) const {
1441 if (!url_ref_.IsValid(search_terms_data))
1442 return GURL();
1444 if (!url_ref_.SupportsReplacement(search_terms_data))
1445 return GURL(url());
1447 // Use something obscure for the search terms argument so that in the rare
1448 // case the term replaces the URL it's unlikely another keyword would have the
1449 // same url.
1450 // TODO(jnd): Add additional parameters to get post data when the search URL
1451 // has post parameters.
1452 return GURL(url_ref_.ReplaceSearchTerms(
1453 TemplateURLRef::SearchTermsArgs(
1454 base::ASCIIToUTF16("blah.blah.blah.blah.blah")),
1455 search_terms_data, NULL));
1458 void TemplateURL::CopyFrom(const TemplateURL& other) {
1459 if (this == &other)
1460 return;
1462 data_ = other.data_;
1463 url_ref_.InvalidateCachedValues();
1464 suggestions_url_ref_.InvalidateCachedValues();
1465 instant_url_ref_.InvalidateCachedValues();
1466 SetPrepopulateId(other.data_.prepopulate_id);
1469 void TemplateURL::SetURL(const std::string& url) {
1470 data_.SetURL(url);
1471 url_ref_.InvalidateCachedValues();
1474 void TemplateURL::SetPrepopulateId(int id) {
1475 data_.prepopulate_id = id;
1476 const bool prepopulated = id > 0;
1477 url_ref_.prepopulated_ = prepopulated;
1478 suggestions_url_ref_.prepopulated_ = prepopulated;
1479 instant_url_ref_.prepopulated_ = prepopulated;
1482 void TemplateURL::ResetKeywordIfNecessary(
1483 const SearchTermsData& search_terms_data,
1484 bool force) {
1485 if (IsGoogleSearchURLWithReplaceableKeyword(search_terms_data) || force) {
1486 DCHECK(GetType() != OMNIBOX_API_EXTENSION);
1487 GURL url(GenerateSearchURL(search_terms_data));
1488 if (url.is_valid())
1489 data_.SetKeyword(GenerateKeyword(url));
1493 bool TemplateURL::FindSearchTermsInURL(
1494 const GURL& url,
1495 const SearchTermsData& search_terms_data,
1496 base::string16* search_terms,
1497 url::Parsed::ComponentType* search_term_component,
1498 url::Component* search_terms_position) const {
1499 DCHECK(search_terms);
1500 search_terms->clear();
1502 // Try to match with every pattern.
1503 for (size_t i = 0; i < URLCount(); ++i) {
1504 TemplateURLRef ref(this, i);
1505 if (ref.ExtractSearchTermsFromURL(url, search_terms, search_terms_data,
1506 search_term_component, search_terms_position)) {
1507 // If ExtractSearchTermsFromURL() returns true and |search_terms| is empty
1508 // it means the pattern matched but no search terms were present. In this
1509 // case we fail immediately without looking for matches in subsequent
1510 // patterns. This means that given patterns
1511 // [ "http://foo/#q={searchTerms}", "http://foo/?q={searchTerms}" ],
1512 // calling ExtractSearchTermsFromURL() on "http://foo/?q=bar#q=' would
1513 // return false. This is important for at least Google, where such URLs
1514 // are invalid.
1515 return !search_terms->empty();
1518 return false;