2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "public/web/WebSearchableFormData.h"
34 #include "core/HTMLNames.h"
35 #include "core/InputTypeNames.h"
36 #include "core/dom/Document.h"
37 #include "core/html/FormDataList.h"
38 #include "core/html/HTMLFormControlElement.h"
39 #include "core/html/HTMLFormElement.h"
40 #include "core/html/HTMLInputElement.h"
41 #include "core/html/HTMLOptionElement.h"
42 #include "core/html/HTMLSelectElement.h"
43 #include "platform/network/FormDataBuilder.h"
44 #include "public/web/WebFormElement.h"
45 #include "public/web/WebInputElement.h"
46 #include "wtf/text/TextEncoding.h"
50 using namespace HTMLNames;
54 // Gets the encoding for the form.
55 void GetFormEncoding(const HTMLFormElement* form, WTF::TextEncoding* encoding)
57 String str(form->getAttribute(HTMLNames::accept_charsetAttr));
58 str.replace(',', ' ');
59 Vector<String> charsets;
60 str.split(' ', charsets);
61 for (Vector<String>::const_iterator i(charsets.begin()); i != charsets.end(); ++i) {
62 *encoding = WTF::TextEncoding(*i);
63 if (encoding->isValid())
66 if (!form->document().loader())
68 *encoding = WTF::TextEncoding(form->document().encoding());
71 // Returns true if the submit request results in an HTTP URL.
72 bool IsHTTPFormSubmit(const HTMLFormElement* form)
74 // FIXME: This function is insane. This is an overly complicated way to get this information.
75 String action(form->action());
76 // The isNull() check is trying to avoid completeURL returning KURL() when passed a null string.
77 return form->document().completeURL(action.isNull() ? "" : action).protocolIs("http");
80 // If the form does not have an activated submit button, the first submit
81 // button is returned.
82 HTMLFormControlElement* GetButtonToActivate(HTMLFormElement* form)
84 HTMLFormControlElement* firstSubmitButton = 0;
85 const FormAssociatedElement::List& element = form->associatedElements();
86 for (FormAssociatedElement::List::const_iterator i(element.begin()); i != element.end(); ++i) {
87 if (!(*i)->isFormControlElement())
89 HTMLFormControlElement* control = toHTMLFormControlElement(*i);
90 if (control->isActivatedSubmit()) {
91 // There's a button that is already activated for submit, return 0.
94 if (!firstSubmitButton && control->isSuccessfulSubmitButton())
95 firstSubmitButton = control;
97 return firstSubmitButton;
100 // Returns true if the selected state of all the options matches the default
102 bool IsSelectInDefaultState(HTMLSelectElement* select)
104 const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& listItems = select->listItems();
105 if (select->multiple() || select->size() > 1) {
106 for (WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >::const_iterator i(listItems.begin()); i != listItems.end(); ++i) {
107 if (!isHTMLOptionElement(*i))
109 HTMLOptionElement* optionElement = toHTMLOptionElement(*i);
110 if (optionElement->selected() != optionElement->hasAttribute(selectedAttr))
116 // The select is rendered as a combobox (called menulist in WebKit). At
117 // least one item is selected, determine which one.
118 HTMLOptionElement* initialSelected = 0;
119 for (WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >::const_iterator i(listItems.begin()); i != listItems.end(); ++i) {
120 if (!isHTMLOptionElement(*i))
122 HTMLOptionElement* optionElement = toHTMLOptionElement(*i);
123 if (optionElement->hasAttribute(selectedAttr)) {
124 // The page specified the option to select.
125 initialSelected = optionElement;
128 if (!initialSelected)
129 initialSelected = optionElement;
131 return !initialSelected || initialSelected->selected();
134 // Returns true if the form element is in its default state, false otherwise.
135 // The default state is the state of the form element on initial load of the
136 // page, and varies depending upon the form element. For example, a checkbox is
137 // in its default state if the checked state matches the state of the checked attribute.
138 bool IsInDefaultState(HTMLFormControlElement* formElement)
141 if (isHTMLInputElement(*formElement)) {
142 const HTMLInputElement& inputElement = toHTMLInputElement(*formElement);
143 if (inputElement.type() == InputTypeNames::checkbox || inputElement.type() == InputTypeNames::radio)
144 return inputElement.checked() == inputElement.hasAttribute(checkedAttr);
145 } else if (isHTMLSelectElement(*formElement)) {
146 return IsSelectInDefaultState(toHTMLSelectElement(formElement));
151 // Look for a suitable search text field in a given HTMLFormElement
152 // Return nothing if one of those items are found:
153 // - A text area field
154 // - A file upload field
155 // - A Password field
156 // - More than one text field
157 HTMLInputElement* findSuitableSearchInputElement(const HTMLFormElement* form)
159 HTMLInputElement* textElement = 0;
160 const FormAssociatedElement::List& element = form->associatedElements();
161 for (FormAssociatedElement::List::const_iterator i(element.begin()); i != element.end(); ++i) {
162 if (!(*i)->isFormControlElement())
165 HTMLFormControlElement* control = toHTMLFormControlElement(*i);
167 if (control->isDisabledFormControl() || control->name().isNull())
170 if (!IsInDefaultState(control) || isHTMLTextAreaElement(*control))
173 if (isHTMLInputElement(*control) && control->willValidate()) {
174 const HTMLInputElement& input = toHTMLInputElement(*control);
176 // Return nothing if a file upload field or a password field are found.
177 if (input.type() == InputTypeNames::file || input.type() == InputTypeNames::password)
180 if (input.isTextField()) {
182 // The auto-complete bar only knows how to fill in one value.
183 // This form has multiple fields; don't treat it as searchable.
186 textElement = toHTMLInputElement(control);
193 // Build a search string based on a given HTMLFormElement and HTMLInputElement
195 // Search string output example from www.google.com:
196 // "hl=en&source=hp&biw=1085&bih=854&q={searchTerms}&btnG=Google+Search&aq=f&aqi=&aql=&oq="
198 // Return false if the provided HTMLInputElement is not found in the form
199 bool buildSearchString(const HTMLFormElement* form, Vector<char>* encodedString, WTF::TextEncoding* encoding, const HTMLInputElement* textElement)
201 bool isElementFound = false;
203 const FormAssociatedElement::List& elements = form->associatedElements();
204 for (FormAssociatedElement::List::const_iterator i(elements.begin()); i != elements.end(); ++i) {
205 if (!(*i)->isFormControlElement())
208 HTMLFormControlElement* control = toHTMLFormControlElement(*i);
210 if (control->isDisabledFormControl() || control->name().isNull())
213 RefPtrWillBeRawPtr<FormDataList> dataList = FormDataList::create(*encoding);
214 if (!control->appendFormData(*dataList, false))
217 const FormDataList::FormDataListItems& items = dataList->items();
218 for (FormDataList::FormDataListItems::const_iterator j(items.begin()); j != items.end(); ++j) {
219 if (!encodedString->isEmpty())
220 encodedString->append('&');
221 FormDataBuilder::encodeStringAsFormData(*encodedString, j->data());
222 encodedString->append('=');
224 if (control == textElement) {
225 encodedString->append("{searchTerms}", 13);
226 isElementFound = true;
228 FormDataBuilder::encodeStringAsFormData(*encodedString, j->data());
231 return isElementFound;
235 WebSearchableFormData::WebSearchableFormData(const WebFormElement& form, const WebInputElement& selectedInputElement)
237 RefPtrWillBeRawPtr<HTMLFormElement> formElement = static_cast<PassRefPtrWillBeRawPtr<HTMLFormElement> >(form);
238 HTMLInputElement* inputElement = static_cast<PassRefPtrWillBeRawPtr<HTMLInputElement> >(selectedInputElement).get();
240 // Only consider forms that GET data.
241 // Allow HTTPS only when an input element is provided.
242 if (equalIgnoringCase(formElement->getAttribute(methodAttr), "post")
243 || (!IsHTTPFormSubmit(formElement.get()) && !inputElement))
246 Vector<char> encodedString;
247 WTF::TextEncoding encoding;
249 GetFormEncoding(formElement.get(), &encoding);
250 if (!encoding.isValid()) {
251 // Need a valid encoding to encode the form elements.
252 // If the encoding isn't found webkit ends up replacing the params with
253 // empty strings. So, we don't try to do anything here.
257 // Look for a suitable search text field in the form when a
258 // selectedInputElement is not provided.
260 inputElement = findSuitableSearchInputElement(formElement.get());
262 // Return if no suitable text element has been found.
267 HTMLFormControlElement* firstSubmitButton = GetButtonToActivate(formElement.get());
268 if (firstSubmitButton) {
269 // The form does not have an active submit button, make the first button
270 // active. We need to do this, otherwise the URL will not contain the
271 // name of the submit button.
272 firstSubmitButton->setActivatedSubmit(true);
275 bool isValidSearchString = buildSearchString(formElement.get(), &encodedString, &encoding, inputElement);
277 if (firstSubmitButton)
278 firstSubmitButton->setActivatedSubmit(false);
280 // Return if the search string is not valid.
281 if (!isValidSearchString)
284 String action(formElement->action());
285 KURL url(formElement->document().completeURL(action.isNull() ? "" : action));
286 RefPtr<FormData> formData = FormData::create(encodedString);
287 url.setQuery(formData->flattenToString());
289 m_encoding = String(encoding.name());