initial import
[vuplus_webkit] / Source / WebKit / chromium / src / WebPageSerializer.cpp
1 /*
2  * Copyright (C) 2009 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 "WebPageSerializer.h"
33
34 #include "DocumentLoader.h"
35 #include "Element.h"
36 #include "Frame.h"
37 #include "HTMLAllCollection.h"
38 #include "HTMLFrameOwnerElement.h"
39 #include "HTMLInputElement.h"
40 #include "HTMLNames.h"
41 #include "KURL.h"
42 #include "MHTMLArchive.h"
43 #include "PageSerializer.h"
44 #include "Vector.h"
45
46 #include "WebCString.h"
47 #include "WebFrame.h"
48 #include "WebFrameImpl.h"
49 #include "WebPageSerializerClient.h"
50 #include "WebPageSerializerImpl.h"
51 #include "WebString.h"
52 #include "WebURL.h"
53 #include "WebVector.h"
54 #include "WebView.h"
55 #include "WebViewImpl.h"
56
57 #include <wtf/text/StringConcatenate.h>
58
59 using namespace WebCore;
60
61 namespace {
62
63 KURL getSubResourceURLFromElement(Element* element)
64 {
65     ASSERT(element);
66     const QualifiedName* attributeName = 0;
67     if (element->hasTagName(HTMLNames::imgTag) || element->hasTagName(HTMLNames::scriptTag))
68         attributeName = &HTMLNames::srcAttr;
69     else if (element->hasTagName(HTMLNames::inputTag)) {
70         HTMLInputElement* input = static_cast<HTMLInputElement*>(element);
71         if (input->isImageButton())
72             attributeName = &HTMLNames::srcAttr;
73     } else if (element->hasTagName(HTMLNames::bodyTag)
74                || element->hasTagName(HTMLNames::tableTag)
75                || element->hasTagName(HTMLNames::trTag)
76                || element->hasTagName(HTMLNames::tdTag))
77         attributeName = &HTMLNames::backgroundAttr;
78     else if (element->hasTagName(HTMLNames::blockquoteTag)
79              || element->hasTagName(HTMLNames::qTag)
80              || element->hasTagName(HTMLNames::delTag)
81              || element->hasTagName(HTMLNames::insTag))
82         attributeName = &HTMLNames::citeAttr;
83     else if (element->hasTagName(HTMLNames::linkTag)) {
84         // If the link element is not css, ignore it.
85         if (equalIgnoringCase(element->getAttribute(HTMLNames::typeAttr), "text/css")) {
86             // FIXME: Add support for extracting links of sub-resources which
87             // are inside style-sheet such as @import, @font-face, url(), etc.
88             attributeName = &HTMLNames::hrefAttr;
89         }
90     } else if (element->hasTagName(HTMLNames::objectTag))
91         attributeName = &HTMLNames::dataAttr;
92     else if (element->hasTagName(HTMLNames::embedTag))
93         attributeName = &HTMLNames::srcAttr;
94
95     if (!attributeName)
96         return KURL();
97
98     String value = element->getAttribute(*attributeName);
99     // Ignore javascript content.
100     if (value.isEmpty() || value.stripWhiteSpace().startsWith("javascript:", false))
101         return KURL();
102   
103     return element->document()->completeURL(value);
104 }
105
106 void retrieveResourcesForElement(Element* element,
107                                  Vector<Frame*>* visitedFrames,
108                                  Vector<Frame*>* framesToVisit,
109                                  Vector<KURL>* frameURLs,
110                                  Vector<KURL>* resourceURLs)
111 {
112     // If the node is a frame, we'll process it later in retrieveResourcesForFrame.
113     if ((element->hasTagName(HTMLNames::iframeTag) || element->hasTagName(HTMLNames::frameTag)
114         || element->hasTagName(HTMLNames::objectTag) || element->hasTagName(HTMLNames::embedTag))
115             && element->isFrameOwnerElement()) {
116         Frame* frame = static_cast<HTMLFrameOwnerElement*>(element)->contentFrame();
117         if (frame) {
118             if (!visitedFrames->contains(frame))
119                 framesToVisit->append(frame);
120             return;
121         }
122     }
123
124     KURL url = getSubResourceURLFromElement(element);
125     if (url.isEmpty() || !url.isValid())
126         return; // No subresource for this node.
127
128     // Ignore URLs that have a non-standard protocols. Since the FTP protocol
129     // does no have a cache mechanism, we skip it as well.
130     if (!url.protocolInHTTPFamily() && !url.isLocalFile())
131         return;
132
133     if (!resourceURLs->contains(url))
134         resourceURLs->append(url);
135 }
136
137 void retrieveResourcesForFrame(Frame* frame,
138                                const WebKit::WebVector<WebKit::WebCString>& supportedSchemes,
139                                Vector<Frame*>* visitedFrames,
140                                Vector<Frame*>* framesToVisit,
141                                Vector<KURL>* frameURLs,
142                                Vector<KURL>* resourceURLs)
143 {
144     KURL frameURL = frame->loader()->documentLoader()->request().url();
145
146     // If the frame's URL is invalid, ignore it, it is not retrievable.
147     if (!frameURL.isValid())
148         return;
149
150     // Ignore frames from unsupported schemes.
151     bool isValidScheme = false;
152     for (size_t i = 0; i < supportedSchemes.size(); ++i) {
153         if (frameURL.protocolIs(static_cast<CString>(supportedSchemes[i]).data())) {
154             isValidScheme = true;
155             break;
156         }
157     }
158     if (!isValidScheme)
159         return;
160
161     // If we have already seen that frame, ignore it.
162     if (visitedFrames->contains(frame))
163         return;
164     visitedFrames->append(frame);
165     if (!frameURLs->contains(frameURL))
166         frameURLs->append(frameURL);
167   
168     // Now get the resources associated with each node of the document.
169     RefPtr<HTMLAllCollection> allNodes = frame->document()->all();
170     for (unsigned i = 0; i < allNodes->length(); ++i) {
171         Node* node = allNodes->item(i);
172         // We are only interested in HTML resources.
173         if (!node->isElementNode())
174             continue;
175         retrieveResourcesForElement(static_cast<Element*>(node),
176                                     visitedFrames, framesToVisit,
177                                     frameURLs, resourceURLs);
178     }
179 }
180
181 } // namespace
182
183 namespace WebKit {
184
185 void WebPageSerializer::serialize(WebView* view, WebVector<WebPageSerializer::Resource>* resourcesParam)
186 {
187     Vector<PageSerializer::Resource> resources;
188     PageSerializer serializer(&resources);
189     serializer.serialize(static_cast<WebViewImpl*>(view)->page());
190
191     Vector<Resource> result;
192     for (Vector<PageSerializer::Resource>::const_iterator iter = resources.begin(); iter != resources.end(); ++iter) {
193         Resource resource;
194         resource.url = iter->url;
195         resource.mimeType = iter->mimeType.ascii();
196         // FIXME: we are copying all the resource data here. Idealy we would have a WebSharedData().
197         resource.data = WebCString(iter->data->data(), iter->data->size());
198         result.append(resource);
199     }
200
201     *resourcesParam = result;         
202 }
203
204 WebCString WebPageSerializer::serializeToMHTML(WebView* view)
205 {
206     RefPtr<SharedBuffer> mhtml = MHTMLArchive::generateMHTMLData(static_cast<WebViewImpl*>(view)->page());
207     // FIXME: we are copying all the data here. Idealy we would have a WebSharedData().
208     return WebCString(mhtml->data(), mhtml->size());
209 }
210
211 WebCString WebPageSerializer::serializeToMHTMLUsingBinaryEncoding(WebView* view)
212 {
213     RefPtr<SharedBuffer> mhtml = MHTMLArchive::generateMHTMLDataUsingBinaryEncoding(static_cast<WebViewImpl*>(view)->page());
214     // FIXME: we are copying all the data here. Idealy we would have a WebSharedData().
215     return WebCString(mhtml->data(), mhtml->size());
216 }
217
218 bool WebPageSerializer::serialize(WebFrame* frame,
219                                   bool recursive,
220                                   WebPageSerializerClient* client,
221                                   const WebVector<WebURL>& links,
222                                   const WebVector<WebString>& localPaths,
223                                   const WebString& localDirectoryName)
224 {
225     WebPageSerializerImpl serializerImpl(
226         frame, recursive, client, links, localPaths, localDirectoryName);
227     return serializerImpl.serialize();
228 }
229
230 bool WebPageSerializer::retrieveAllResources(WebView* view,
231                                              const WebVector<WebCString>& supportedSchemes,
232                                              WebVector<WebURL>* resourceURLs,
233                                              WebVector<WebURL>* frameURLs) {
234     WebFrameImpl* mainFrame = static_cast<WebFrameImpl*>(view->mainFrame());
235     if (!mainFrame)
236         return false;
237
238     Vector<Frame*> framesToVisit;
239     Vector<Frame*> visitedFrames;
240     Vector<KURL> frameKURLs;
241     Vector<KURL> resourceKURLs;
242     
243     // Let's retrieve the resources from every frame in this page.
244     framesToVisit.append(mainFrame->frame());
245     while (!framesToVisit.isEmpty()) {
246         Frame* frame = framesToVisit[0];
247         framesToVisit.remove(0);
248         retrieveResourcesForFrame(frame, supportedSchemes,
249                                   &visitedFrames, &framesToVisit,
250                                   &frameKURLs, &resourceKURLs);
251     }
252
253     // Converts the results to WebURLs.
254     WebVector<WebURL> resultResourceURLs(resourceKURLs.size());
255     for (size_t i = 0; i < resourceKURLs.size(); ++i) {
256         resultResourceURLs[i] = resourceKURLs[i];
257         // A frame's src can point to the same URL as another resource, keep the
258         // resource URL only in such cases.
259         size_t index = frameKURLs.find(resourceKURLs[i]);
260         if (index != notFound)
261             frameKURLs.remove(index);
262     }
263     *resourceURLs = resultResourceURLs;
264     WebVector<WebURL> resultFrameURLs(frameKURLs.size());
265     for (size_t i = 0; i < frameKURLs.size(); ++i)
266         resultFrameURLs[i] = frameKURLs[i];
267     *frameURLs = resultFrameURLs;
268     
269     return true;
270 }
271
272 WebString WebPageSerializer::generateMetaCharsetDeclaration(const WebString& charset)
273 {
274     return makeString("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=", static_cast<const String&>(charset), "\">");
275 }
276
277 WebString WebPageSerializer::generateMarkOfTheWebDeclaration(const WebURL& url)
278 {
279     return String::format("\n<!-- saved from url=(%04d)%s -->\n",
280                           static_cast<int>(url.spec().length()),
281                           url.spec().data());
282 }
283
284 WebString WebPageSerializer::generateBaseTagDeclaration(const WebString& baseTarget)
285 {
286     if (baseTarget.isEmpty())
287         return makeString("<base href=\".\">");
288     return makeString("<base href=\".\" target=\"", static_cast<const String&>(baseTarget), "\">");
289 }
290
291 } // namespace WebKit