- add third_party src.
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / loader / FormSubmission.cpp
1 /*
2  * Copyright (C) 2010 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
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
13  * distribution.
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.
17  *
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.
29  */
30
31 #include "config.h"
32 #include "core/loader/FormSubmission.h"
33
34 #include "HTMLNames.h"
35 #include "RuntimeEnabledFeatures.h"
36 #include "core/dom/Document.h"
37 #include "core/events/Event.h"
38 #include "core/html/DOMFormData.h"
39 #include "core/html/HTMLFormControlElement.h"
40 #include "core/html/HTMLFormElement.h"
41 #include "core/html/HTMLInputElement.h"
42 #include "core/html/parser/HTMLParserIdioms.h"
43 #include "core/loader/FormState.h"
44 #include "core/loader/FrameLoadRequest.h"
45 #include "core/loader/FrameLoader.h"
46 #include "platform/network/FormData.h"
47 #include "platform/network/FormDataBuilder.h"
48 #include "wtf/CurrentTime.h"
49 #include "wtf/text/TextEncoding.h"
50
51 namespace WebCore {
52
53 using namespace HTMLNames;
54
55 static int64_t generateFormDataIdentifier()
56 {
57     // Initialize to the current time to reduce the likelihood of generating
58     // identifiers that overlap with those from past/future browser sessions.
59     static int64_t nextIdentifier = static_cast<int64_t>(currentTime() * 1000000.0);
60     return ++nextIdentifier;
61 }
62
63 static void appendMailtoPostFormDataToURL(KURL& url, const FormData& data, const String& encodingType)
64 {
65     String body = data.flattenToString();
66
67     if (equalIgnoringCase(encodingType, "text/plain")) {
68         // Convention seems to be to decode, and s/&/\r\n/. Also, spaces are encoded as %20.
69         body = decodeURLEscapeSequences(body.replaceWithLiteral('&', "\r\n").replace('+', ' ') + "\r\n");
70     }
71
72     Vector<char> bodyData;
73     bodyData.append("body=", 5);
74     FormDataBuilder::encodeStringAsFormData(bodyData, body.utf8());
75     body = String(bodyData.data(), bodyData.size()).replaceWithLiteral('+', "%20");
76
77     String query = url.query();
78     if (!query.isEmpty())
79         query.append('&');
80     query.append(body);
81     url.setQuery(query);
82 }
83
84 void FormSubmission::Attributes::parseAction(const String& action)
85 {
86     // FIXME: Can we parse into a KURL?
87     m_action = stripLeadingAndTrailingHTMLSpaces(action);
88 }
89
90 String FormSubmission::Attributes::parseEncodingType(const String& type)
91 {
92     if (equalIgnoringCase(type, "multipart/form-data"))
93         return "multipart/form-data";
94     if (equalIgnoringCase(type, "text/plain"))
95         return "text/plain";
96     return "application/x-www-form-urlencoded";
97 }
98
99 void FormSubmission::Attributes::updateEncodingType(const String& type)
100 {
101     m_encodingType = parseEncodingType(type);
102     m_isMultiPartForm = (m_encodingType == "multipart/form-data");
103 }
104
105 FormSubmission::Method FormSubmission::Attributes::parseMethodType(const String& type)
106 {
107     if (equalIgnoringCase(type, "post"))
108         return FormSubmission::PostMethod;
109     if (RuntimeEnabledFeatures::dialogElementEnabled() && equalIgnoringCase(type, "dialog"))
110         return FormSubmission::DialogMethod;
111     return FormSubmission::GetMethod;
112 }
113
114 void FormSubmission::Attributes::updateMethodType(const String& type)
115 {
116     m_method = parseMethodType(type);
117 }
118
119 String FormSubmission::Attributes::methodString(Method method)
120 {
121     switch (method) {
122     case GetMethod:
123         return "get";
124     case PostMethod:
125         return "post";
126     case DialogMethod:
127         return "dialog";
128     }
129     ASSERT_NOT_REACHED();
130     return emptyString();
131 }
132
133 void FormSubmission::Attributes::copyFrom(const Attributes& other)
134 {
135     m_method = other.m_method;
136     m_isMultiPartForm = other.m_isMultiPartForm;
137
138     m_action = other.m_action;
139     m_target = other.m_target;
140     m_encodingType = other.m_encodingType;
141     m_acceptCharset = other.m_acceptCharset;
142 }
143
144 inline FormSubmission::FormSubmission(Method method, const KURL& action, const String& target, const String& contentType, PassRefPtr<FormState> state, PassRefPtr<FormData> data, const String& boundary, PassRefPtr<Event> event)
145     : m_method(method)
146     , m_action(action)
147     , m_target(target)
148     , m_contentType(contentType)
149     , m_formState(state)
150     , m_formData(data)
151     , m_boundary(boundary)
152     , m_event(event)
153 {
154 }
155
156 inline FormSubmission::FormSubmission(const String& result)
157     : m_method(DialogMethod)
158     , m_result(result)
159 {
160 }
161
162 PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attributes& attributes, PassRefPtr<Event> event, FormSubmissionTrigger trigger)
163 {
164     ASSERT(form);
165
166     HTMLFormControlElement* submitButton = 0;
167     if (event && event->target()) {
168         for (Node* node = event->target()->toNode(); node; node = node->parentOrShadowHostNode()) {
169             if (node->isElementNode() && toElement(node)->isFormControlElement()) {
170                 submitButton = toHTMLFormControlElement(node);
171                 break;
172             }
173         }
174     }
175
176     FormSubmission::Attributes copiedAttributes;
177     copiedAttributes.copyFrom(attributes);
178     if (submitButton) {
179         String attributeValue;
180         if (!(attributeValue = submitButton->fastGetAttribute(formactionAttr)).isNull())
181             copiedAttributes.parseAction(attributeValue);
182         if (!(attributeValue = submitButton->fastGetAttribute(formenctypeAttr)).isNull())
183             copiedAttributes.updateEncodingType(attributeValue);
184         if (!(attributeValue = submitButton->fastGetAttribute(formmethodAttr)).isNull())
185             copiedAttributes.updateMethodType(attributeValue);
186         if (!(attributeValue = submitButton->fastGetAttribute(formtargetAttr)).isNull())
187             copiedAttributes.setTarget(attributeValue);
188     }
189
190     if (copiedAttributes.method() == DialogMethod)
191         return adoptRef(new FormSubmission(submitButton->resultForDialogSubmit()));
192
193     Document& document = form->document();
194     KURL actionURL = document.completeURL(copiedAttributes.action().isEmpty() ? document.url().string() : copiedAttributes.action());
195     bool isMailtoForm = actionURL.protocolIs("mailto");
196     bool isMultiPartForm = false;
197     String encodingType = copiedAttributes.encodingType();
198
199     if (copiedAttributes.method() == PostMethod) {
200         isMultiPartForm = copiedAttributes.isMultiPartForm();
201         if (isMultiPartForm && isMailtoForm) {
202             encodingType = "application/x-www-form-urlencoded";
203             isMultiPartForm = false;
204         }
205     }
206     WTF::TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : FormDataBuilder::encodingFromAcceptCharset(copiedAttributes.acceptCharset(), document.inputEncoding(), document.defaultCharset());
207     RefPtr<DOMFormData> domFormData = DOMFormData::create(dataEncoding.encodingForFormSubmission());
208     Vector<pair<String, String> > formValues;
209
210     bool containsPasswordData = false;
211     for (unsigned i = 0; i < form->associatedElements().size(); ++i) {
212         FormAssociatedElement* control = form->associatedElements()[i];
213         HTMLElement* element = toHTMLElement(control);
214         if (!element->isDisabledFormControl())
215             control->appendFormData(*domFormData, isMultiPartForm);
216         if (element->hasTagName(inputTag)) {
217             HTMLInputElement* input = toHTMLInputElement(element);
218             if (input->isTextField())
219                 formValues.append(pair<String, String>(input->name().string(), input->value()));
220             if (input->isPasswordField() && !input->value().isEmpty())
221                 containsPasswordData = true;
222         }
223     }
224
225     RefPtr<FormData> formData;
226     String boundary;
227
228     if (isMultiPartForm) {
229         formData = domFormData->createMultiPartFormData(domFormData->encoding());
230         boundary = formData->boundary().data();
231     } else {
232         formData = domFormData->createFormData(domFormData->encoding(), attributes.method() == GetMethod ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
233         if (copiedAttributes.method() == PostMethod && isMailtoForm) {
234             // Convert the form data into a string that we put into the URL.
235             appendMailtoPostFormDataToURL(actionURL, *formData, encodingType);
236             formData = FormData::create();
237         }
238     }
239
240     formData->setIdentifier(generateFormDataIdentifier());
241     formData->setContainsPasswordData(containsPasswordData);
242     String targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document.baseTarget() : copiedAttributes.target();
243     RefPtr<FormState> formState = FormState::create(form, formValues, &document, trigger);
244     return adoptRef(new FormSubmission(copiedAttributes.method(), actionURL, targetOrBaseTarget, encodingType, formState.release(), formData.release(), boundary, event));
245 }
246
247 KURL FormSubmission::requestURL() const
248 {
249     if (m_method == FormSubmission::PostMethod)
250         return m_action;
251
252     KURL requestURL(m_action);
253     requestURL.setQuery(m_formData->flattenToString());
254     return requestURL;
255 }
256
257 void FormSubmission::populateFrameLoadRequest(FrameLoadRequest& frameRequest)
258 {
259     if (!m_target.isEmpty())
260         frameRequest.setFrameName(m_target);
261
262     if (!m_referrer.isEmpty())
263         frameRequest.resourceRequest().setHTTPReferrer(m_referrer);
264
265     if (m_method == FormSubmission::PostMethod) {
266         frameRequest.resourceRequest().setHTTPMethod("POST");
267         frameRequest.resourceRequest().setHTTPBody(m_formData);
268
269         // construct some user headers if necessary
270         if (m_boundary.isEmpty())
271             frameRequest.resourceRequest().setHTTPContentType(m_contentType);
272         else
273             frameRequest.resourceRequest().setHTTPContentType(m_contentType + "; boundary=" + m_boundary);
274     }
275
276     frameRequest.resourceRequest().setURL(requestURL());
277     FrameLoader::addHTTPOriginIfNeeded(frameRequest.resourceRequest(), m_origin);
278 }
279
280 }