Unreviewed build fix
[WebKit-https.git] / Source / WebCore / editing / cocoa / WebContentReaderCocoa.mm
1 /*
2  * Copyright (C) 2006-2017 Apple 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
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WebContentReader.h"
28
29 #import "ArchiveResource.h"
30 #import "Blob.h"
31 #import "BlobURL.h"
32 #import "CachedResourceLoader.h"
33 #import "CustomHeaderFields.h"
34 #import "DOMURL.h"
35 #import "Document.h"
36 #import "DocumentFragment.h"
37 #import "DocumentLoader.h"
38 #import "Editor.h"
39 #import "EditorClient.h"
40 #import "File.h"
41 #import "Frame.h"
42 #import "FrameLoader.h"
43 #import "FrameLoaderClient.h"
44 #import "HTMLAnchorElement.h"
45 #import "HTMLAttachmentElement.h"
46 #import "HTMLBRElement.h"
47 #import "HTMLBodyElement.h"
48 #import "HTMLDivElement.h"
49 #import "HTMLIFrameElement.h"
50 #import "HTMLImageElement.h"
51 #import "HTMLObjectElement.h"
52 #import "LegacyWebArchive.h"
53 #import "MIMETypeRegistry.h"
54 #import "Page.h"
55 #import "PublicURLManager.h"
56 #import "RenderView.h"
57 #import "RuntimeEnabledFeatures.h"
58 #import "SerializedAttachmentData.h"
59 #import "Settings.h"
60 #import "SocketProvider.h"
61 #import "TypedElementDescendantIterator.h"
62 #import "UTIUtilities.h"
63 #import "WebArchiveResourceFromNSAttributedString.h"
64 #import "WebArchiveResourceWebResourceHandler.h"
65 #import "WebNSAttributedStringExtras.h"
66 #import "markup.h"
67 #import <pal/spi/cocoa/NSAttributedStringSPI.h>
68 #import <wtf/FileSystem.h>
69 #import <wtf/SoftLinking.h>
70 #import <wtf/URLParser.h>
71
72 #if PLATFORM(MAC)
73 #include "LocalDefaultSystemAppearance.h"
74 #endif
75
76 #if (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300)
77 @interface NSAttributedString ()
78 - (NSString *)_htmlDocumentFragmentString:(NSRange)range documentAttributes:(NSDictionary *)dict subresources:(NSArray **)subresources;
79 @end
80 #elif PLATFORM(IOS_FAMILY)
81 SOFT_LINK_PRIVATE_FRAMEWORK(WebKitLegacy)
82 #elif PLATFORM(MAC)
83 SOFT_LINK_FRAMEWORK_IN_UMBRELLA(WebKit, WebKitLegacy)
84 #endif
85
86 #if (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED < 110000) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
87 SOFT_LINK(WebKitLegacy, _WebCreateFragment, void, (WebCore::Document& document, NSAttributedString *string, WebCore::FragmentAndResources& result), (document, string, result))
88 #endif
89
90 namespace WebCore {
91
92 #if PLATFORM(IOSMAC)
93
94 static FragmentAndResources createFragment(Frame&, NSAttributedString *)
95 {
96     return { };
97 }
98
99 #elif (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300)
100
101 static NSDictionary *attributesForAttributedStringConversion()
102 {
103     // This function needs to be kept in sync with identically named one in WebKitLegacy, which is used on older OS versions.
104     RetainPtr<NSMutableArray> excludedElements = adoptNS([[NSMutableArray alloc] initWithObjects:
105         // Omit style since we want style to be inline so the fragment can be easily inserted.
106         @"style",
107         // Omit xml so the result is not XHTML.
108         @"xml",
109         // Omit tags that will get stripped when converted to a fragment anyway.
110         @"doctype", @"html", @"head", @"body",
111         // Omit deprecated tags.
112         @"applet", @"basefont", @"center", @"dir", @"font", @"menu", @"s", @"strike", @"u",
113 #if !ENABLE(ATTACHMENT_ELEMENT)
114         // Omit object so no file attachments are part of the fragment.
115         @"object",
116 #endif
117         nil]);
118
119 #if ENABLE(ATTACHMENT_ELEMENT)
120     if (!RuntimeEnabledFeatures::sharedFeatures().attachmentElementEnabled())
121         [excludedElements addObject:@"object"];
122 #endif
123
124 #if PLATFORM(IOS_FAMILY)
125     static NSString * const NSExcludedElementsDocumentAttribute = @"ExcludedElements";
126 #endif
127
128     NSURL *baseURL = URL::fakeURLWithRelativePart(emptyString());
129
130     // The output base URL needs +1 refcount to work around the fact that NSHTMLReader over-releases it.
131     CFRetain((__bridge CFTypeRef)baseURL);
132
133     return @{
134         NSExcludedElementsDocumentAttribute: excludedElements.get(),
135         @"InterchangeNewline": @YES,
136         @"CoalesceTabSpans": @YES,
137         @"OutputBaseURL": baseURL,
138         @"WebResourceHandler": [[WebArchiveResourceWebResourceHandler new] autorelease],
139     };
140 }
141
142 static FragmentAndResources createFragment(Frame& frame, NSAttributedString *string)
143 {
144     FragmentAndResources result;
145     Document& document = *frame.document();
146
147 #if PLATFORM(MAC)
148     auto* view = frame.view();
149     LocalDefaultSystemAppearance localAppearance(view ? view->useDarkAppearance() : false);
150 #endif
151
152     NSArray *subresources = nil;
153     NSString *fragmentString = [string _htmlDocumentFragmentString:NSMakeRange(0, [string length]) documentAttributes:attributesForAttributedStringConversion() subresources:&subresources];
154     auto fragment = DocumentFragment::create(document);
155     fragment->parseHTML(fragmentString, document.body(), DisallowScriptingAndPluginContent);
156
157     result.fragment = WTFMove(fragment);
158     for (WebArchiveResourceFromNSAttributedString *resource in subresources)
159         result.resources.append(*resource->resource);
160
161     return result;
162 }
163
164 #else
165
166 static FragmentAndResources createFragment(Frame& frame, NSAttributedString *string)
167 {
168     FragmentAndResources result;
169     _WebCreateFragment(*frame.document(), string, result);
170     return result;
171 }
172
173 #endif
174
175 class DeferredLoadingScope {
176 public:
177     DeferredLoadingScope(Frame& frame)
178         : m_frame(frame)
179         , m_cachedResourceLoader(frame.document()->cachedResourceLoader())
180     {
181         if (!frame.page()->defersLoading()) {
182             frame.page()->setDefersLoading(true);
183             m_didEnabledDeferredLoading = true;
184         }
185
186         if (m_cachedResourceLoader->imagesEnabled()) {
187             m_cachedResourceLoader->setImagesEnabled(false);
188             m_didDisableImage = true;
189         }
190     }
191
192     ~DeferredLoadingScope()
193     {
194         if (m_didDisableImage)
195             m_cachedResourceLoader->setImagesEnabled(true);
196         if (m_didEnabledDeferredLoading)
197             m_frame->page()->setDefersLoading(false);
198     }
199
200 private:
201     Ref<Frame> m_frame;
202     Ref<CachedResourceLoader> m_cachedResourceLoader;
203     bool m_didEnabledDeferredLoading { false };
204     bool m_didDisableImage { false };
205 };
206
207
208 static bool shouldReplaceSubresourceURL(const URL& url)
209 {
210     return !(url.protocolIsInHTTPFamily() || url.protocolIsData());
211 }
212
213 static bool shouldReplaceRichContentWithAttachments()
214 {
215 #if ENABLE(ATTACHMENT_ELEMENT)
216     return RuntimeEnabledFeatures::sharedFeatures().attachmentElementEnabled();
217 #else
218     return false;
219 #endif
220 }
221
222 #if ENABLE(ATTACHMENT_ELEMENT)
223
224 static String mimeTypeFromContentType(const String& contentType)
225 {
226     if (contentType == String(kUTTypeVCard)) {
227         // CoreServices erroneously reports that "public.vcard" maps to "text/directory", rather
228         // than either "text/vcard" or "text/x-vcard". Work around this by special casing the
229         // "public.vcard" UTI type. See <rdar://problem/49478229> for more detail.
230         return "text/vcard"_s;
231     }
232     return isDeclaredUTI(contentType) ? MIMETypeFromUTI(contentType) : contentType;
233 }
234
235 static bool contentTypeIsSuitableForInlineImageRepresentation(const String& contentType)
236 {
237     return MIMETypeRegistry::isSupportedImageMIMEType(mimeTypeFromContentType(contentType));
238 }
239
240 static bool supportsClientSideAttachmentData(const Frame& frame)
241 {
242     if (auto* client = frame.editor().client())
243         return client->supportsClientSideAttachmentData();
244
245     return false;
246 }
247
248 #endif
249
250 static Ref<DocumentFragment> createFragmentForImageAttachment(Frame& frame, Document& document, Ref<SharedBuffer>&& buffer, const String& contentType)
251 {
252 #if ENABLE(ATTACHMENT_ELEMENT)
253     auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document);
254     // FIXME: This fallback image name needs to be a localized string.
255     String defaultImageAttachmentName { "image"_s };
256
257     auto fragment = document.createDocumentFragment();
258     if (supportsClientSideAttachmentData(frame)) {
259         frame.editor().registerAttachmentIdentifier(attachment->ensureUniqueIdentifier(), contentType, defaultImageAttachmentName, WTFMove(buffer));
260         if (contentTypeIsSuitableForInlineImageRepresentation(contentType)) {
261             auto image = HTMLImageElement::create(document);
262             image->setAttributeWithoutSynchronization(HTMLNames::srcAttr, DOMURL::createObjectURL(document, Blob::create(buffer.get(), contentType)));
263             image->setAttachmentElement(WTFMove(attachment));
264             fragment->appendChild(WTFMove(image));
265         } else {
266             attachment->updateAttributes(buffer->size(), contentType, defaultImageAttachmentName);
267             fragment->appendChild(WTFMove(attachment));
268         }
269     } else {
270         attachment->setFile(File::create(Blob::create(buffer.get(), contentType), defaultImageAttachmentName), HTMLAttachmentElement::UpdateDisplayAttributes::Yes);
271         fragment->appendChild(WTFMove(attachment));
272     }
273     return fragment;
274 #else
275     UNUSED_PARAM(blob);
276     return document.createDocumentFragment();
277 #endif
278 }
279
280 static void replaceRichContentWithAttachments(Frame& frame, DocumentFragment& fragment, const Vector<Ref<ArchiveResource>>& subresources)
281 {
282 #if ENABLE(ATTACHMENT_ELEMENT)
283     struct AttachmentInsertionInfo {
284         String fileName;
285         String contentType;
286         Ref<SharedBuffer> data;
287         Ref<Element> originalElement;
288     };
289
290     ASSERT(RuntimeEnabledFeatures::sharedFeatures().attachmentElementEnabled());
291     if (subresources.isEmpty())
292         return;
293
294     // FIXME: Handle resources in subframe archives.
295     HashMap<AtomicString, Ref<ArchiveResource>> urlToResourceMap;
296     for (auto& subresource : subresources) {
297         auto& url = subresource->url();
298         if (shouldReplaceSubresourceURL(url))
299             urlToResourceMap.set(url.string(), subresource.copyRef());
300     }
301
302     Vector<SerializedAttachmentData> serializedAttachmentData;
303     for (auto& attachment : descendantsOfType<HTMLAttachmentElement>(fragment)) {
304         auto resourceURL = HTMLAttachmentElement::archiveResourceURL(attachment.uniqueIdentifier());
305         auto resourceEntry = urlToResourceMap.find(resourceURL.string());
306         if (resourceEntry == urlToResourceMap.end())
307             continue;
308
309         auto& resource = resourceEntry->value;
310         serializedAttachmentData.append({ attachment.uniqueIdentifier(), resource->mimeType(), resource->data() });
311     }
312
313     if (!serializedAttachmentData.isEmpty())
314         frame.editor().registerAttachments(WTFMove(serializedAttachmentData));
315
316     Vector<Ref<Element>> elementsToRemove;
317     Vector<AttachmentInsertionInfo> attachmentInsertionInfo;
318     for (auto& image : descendantsOfType<HTMLImageElement>(fragment)) {
319         auto resourceURLString = image.attributeWithoutSynchronization(HTMLNames::srcAttr);
320         if (resourceURLString.isEmpty())
321             continue;
322
323         auto resource = urlToResourceMap.find(resourceURLString);
324         if (resource == urlToResourceMap.end())
325             continue;
326
327         auto name = image.attributeWithoutSynchronization(HTMLNames::altAttr);
328         if (name.isEmpty())
329             name = URL({ }, resourceURLString).lastPathComponent();
330         if (name.isEmpty())
331             name = AtomicString("media");
332
333         attachmentInsertionInfo.append({ name, resource->value->mimeType(), resource->value->data(), image });
334     }
335
336     for (auto& object : descendantsOfType<HTMLObjectElement>(fragment)) {
337         auto resourceURLString = object.attributeWithoutSynchronization(HTMLNames::dataAttr);
338         if (resourceURLString.isEmpty()) {
339             elementsToRemove.append(object);
340             continue;
341         }
342
343         auto resource = urlToResourceMap.find(resourceURLString);
344         if (resource == urlToResourceMap.end())
345             continue;
346
347         auto name = URL({ }, resourceURLString).lastPathComponent();
348         if (name.isEmpty())
349             name = AtomicString("file");
350
351         attachmentInsertionInfo.append({ name, resource->value->mimeType(), resource->value->data(), object });
352     }
353
354     for (auto& info : attachmentInsertionInfo) {
355         auto originalElement = WTFMove(info.originalElement);
356         auto parent = makeRefPtr(originalElement->parentNode());
357         if (!parent)
358             continue;
359
360         auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, fragment.document());
361         if (supportsClientSideAttachmentData(frame)) {
362             if (is<HTMLImageElement>(originalElement.get()) && contentTypeIsSuitableForInlineImageRepresentation(info.contentType)) {
363                 auto& image = downcast<HTMLImageElement>(originalElement.get());
364                 image.setAttributeWithoutSynchronization(HTMLNames::srcAttr, DOMURL::createObjectURL(*frame.document(), Blob::create(info.data, info.contentType)));
365                 image.setAttachmentElement(attachment.copyRef());
366             } else {
367                 attachment->updateAttributes(info.data->size(), info.contentType, info.fileName);
368                 parent->replaceChild(attachment, WTFMove(originalElement));
369             }
370             frame.editor().registerAttachmentIdentifier(attachment->ensureUniqueIdentifier(), WTFMove(info.contentType), WTFMove(info.fileName), WTFMove(info.data));
371         } else {
372             attachment->setFile(File::create(Blob::create(WTFMove(info.data), WTFMove(info.contentType)), WTFMove(info.fileName)), HTMLAttachmentElement::UpdateDisplayAttributes::Yes);
373             parent->replaceChild(WTFMove(attachment), WTFMove(originalElement));
374         }
375     }
376
377     for (auto& elementToRemove : elementsToRemove)
378         elementToRemove->remove();
379 #else
380     UNUSED_PARAM(fragment);
381     UNUSED_PARAM(subresources);
382 #endif
383 }
384
385 RefPtr<DocumentFragment> createFragmentAndAddResources(Frame& frame, NSAttributedString *string)
386 {
387     if (!frame.page() || !frame.document())
388         return nullptr;
389
390     auto& document = *frame.document();
391     if (!document.isHTMLDocument() || !string)
392         return nullptr;
393
394     DeferredLoadingScope scope(frame);
395     auto fragmentAndResources = createFragment(frame, string);
396     if (!fragmentAndResources.fragment)
397         return nullptr;
398
399     if (!RuntimeEnabledFeatures::sharedFeatures().customPasteboardDataEnabled()) {
400         if (DocumentLoader* loader = frame.loader().documentLoader()) {
401             for (auto& resource : fragmentAndResources.resources)
402                 loader->addArchiveResource(resource.copyRef());
403         }
404         return WTFMove(fragmentAndResources.fragment);
405     }
406
407     if (shouldReplaceRichContentWithAttachments()) {
408         replaceRichContentWithAttachments(frame, *fragmentAndResources.fragment, fragmentAndResources.resources);
409         return WTFMove(fragmentAndResources.fragment);
410     }
411
412     HashMap<AtomicString, AtomicString> blobURLMap;
413     for (const Ref<ArchiveResource>& subresource : fragmentAndResources.resources) {
414         auto blob = Blob::create(subresource->data(), subresource->mimeType());
415         String blobURL = DOMURL::createObjectURL(document, blob);
416         blobURLMap.set(subresource->url().string(), blobURL);
417     }
418
419     replaceSubresourceURLs(*fragmentAndResources.fragment, WTFMove(blobURLMap));
420     return WTFMove(fragmentAndResources.fragment);
421 }
422
423 struct MarkupAndArchive {
424     String markup;
425     Ref<ArchiveResource> mainResource;
426     Ref<Archive> archive;
427 };
428
429 static Optional<MarkupAndArchive> extractMarkupAndArchive(SharedBuffer& buffer, const std::function<bool(const String)>& canShowMIMETypeAsHTML)
430 {
431     auto archive = LegacyWebArchive::create(URL(), buffer);
432     if (!archive)
433         return WTF::nullopt;
434
435     RefPtr<ArchiveResource> mainResource = archive->mainResource();
436     if (!mainResource)
437         return WTF::nullopt;
438
439     auto type = mainResource->mimeType();
440     if (!canShowMIMETypeAsHTML(type))
441         return WTF::nullopt;
442
443     return MarkupAndArchive { String::fromUTF8(mainResource->data().data(), mainResource->data().size()), mainResource.releaseNonNull(), archive.releaseNonNull() };
444 }
445
446 static String sanitizeMarkupWithArchive(Frame& frame, Document& destinationDocument, MarkupAndArchive& markupAndArchive, MSOListQuirks msoListQuirks, const std::function<bool(const String)>& canShowMIMETypeAsHTML)
447 {
448     auto page = createPageForSanitizingWebContent();
449     Document* stagingDocument = page->mainFrame().document();
450     ASSERT(stagingDocument);
451     auto fragment = createFragmentFromMarkup(*stagingDocument, markupAndArchive.markup, markupAndArchive.mainResource->url(), DisallowScriptingAndPluginContent);
452
453     if (shouldReplaceRichContentWithAttachments()) {
454         replaceRichContentWithAttachments(frame, fragment, markupAndArchive.archive->subresources());
455         return sanitizedMarkupForFragmentInDocument(WTFMove(fragment), *stagingDocument, msoListQuirks, markupAndArchive.markup);
456     }
457
458     HashMap<AtomicString, AtomicString> blobURLMap;
459     for (const Ref<ArchiveResource>& subresource : markupAndArchive.archive->subresources()) {
460         auto& subresourceURL = subresource->url();
461         if (!shouldReplaceSubresourceURL(subresourceURL))
462             continue;
463         auto blob = Blob::create(subresource->data(), subresource->mimeType());
464         String blobURL = DOMURL::createObjectURL(destinationDocument, blob);
465         blobURLMap.set(subresourceURL.string(), blobURL);
466     }
467
468     auto contentOrigin = SecurityOrigin::create(markupAndArchive.mainResource->url());
469     for (const Ref<Archive>& subframeArchive : markupAndArchive.archive->subframeArchives()) {
470         RefPtr<ArchiveResource> subframeMainResource = subframeArchive->mainResource();
471         if (!subframeMainResource)
472             continue;
473
474         auto type = subframeMainResource->mimeType();
475         if (!canShowMIMETypeAsHTML(type))
476             continue;
477
478         auto subframeURL = subframeMainResource->url();
479         if (!shouldReplaceSubresourceURL(subframeURL))
480             continue;
481
482         MarkupAndArchive subframeContent = { String::fromUTF8(subframeMainResource->data().data(), subframeMainResource->data().size()),
483             subframeMainResource.releaseNonNull(), subframeArchive.copyRef() };
484         auto subframeMarkup = sanitizeMarkupWithArchive(frame, destinationDocument, subframeContent, MSOListQuirks::Disabled, canShowMIMETypeAsHTML);
485
486         CString utf8 = subframeMarkup.utf8();
487         Vector<uint8_t> blobBuffer;
488         blobBuffer.reserveCapacity(utf8.length());
489         blobBuffer.append(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length());
490         auto blob = Blob::create(WTFMove(blobBuffer), type);
491
492         String subframeBlobURL = DOMURL::createObjectURL(destinationDocument, blob);
493         blobURLMap.set(subframeURL.string(), subframeBlobURL);
494     }
495
496     replaceSubresourceURLs(fragment.get(), WTFMove(blobURLMap));
497
498     return sanitizedMarkupForFragmentInDocument(WTFMove(fragment), *stagingDocument, msoListQuirks, markupAndArchive.markup);
499 }
500
501 bool WebContentReader::readWebArchive(SharedBuffer& buffer)
502 {
503     if (frame.settings().preferMIMETypeForImages() || !frame.document())
504         return false;
505
506     DeferredLoadingScope scope(frame);
507     auto result = extractMarkupAndArchive(buffer, [&] (const String& type) {
508         return frame.loader().client().canShowMIMETypeAsHTML(type);
509     });
510     if (!result)
511         return false;
512     
513     if (!RuntimeEnabledFeatures::sharedFeatures().customPasteboardDataEnabled()) {
514         fragment = createFragmentFromMarkup(*frame.document(), result->markup, result->mainResource->url(), DisallowScriptingAndPluginContent);
515         if (DocumentLoader* loader = frame.loader().documentLoader())
516             loader->addAllArchiveResources(result->archive.get());
517         return true;
518     }
519
520     if (!shouldSanitize()) {
521         fragment = createFragmentFromMarkup(*frame.document(), result->markup, result->mainResource->url(), DisallowScriptingAndPluginContent);
522         return true;
523     }
524
525     String sanitizedMarkup = sanitizeMarkupWithArchive(frame, *frame.document(), *result, msoListQuirksForMarkup(), [&] (const String& type) {
526         return frame.loader().client().canShowMIMETypeAsHTML(type);
527     });
528     fragment = createFragmentFromMarkup(*frame.document(), sanitizedMarkup, WTF::blankURL(), DisallowScriptingAndPluginContent);
529
530     if (!fragment)
531         return false;
532
533     return true;
534 }
535
536 bool WebContentMarkupReader::readWebArchive(SharedBuffer& buffer)
537 {
538     if (!frame.document())
539         return false;
540
541     auto result = extractMarkupAndArchive(buffer, [&] (const String& type) {
542         return frame.loader().client().canShowMIMETypeAsHTML(type);
543     });
544     if (!result)
545         return false;
546
547     if (!shouldSanitize()) {
548         markup = result->markup;
549         return true;
550     }
551
552     markup = sanitizeMarkupWithArchive(frame, *frame.document(), *result, msoListQuirksForMarkup(), [&] (const String& type) {
553         return frame.loader().client().canShowMIMETypeAsHTML(type);
554     });
555
556     return true;
557 }
558
559 static String stripMicrosoftPrefix(const String& string)
560 {
561 #if PLATFORM(MAC)
562     // This code was added to make HTML paste from Microsoft Word on Mac work, back in 2004.
563     // It's a simple-minded way to ignore the CF_HTML clipboard format, just skipping over the
564     // description part and parsing the entire context plus fragment.
565     if (string.startsWith("Version:")) {
566         size_t location = string.findIgnoringASCIICase("<html");
567         if (location != notFound)
568             return string.substring(location);
569     }
570 #endif
571     return string;
572 }
573
574 bool WebContentReader::readHTML(const String& string)
575 {
576     if (frame.settings().preferMIMETypeForImages() || !frame.document())
577         return false;
578     Document& document = *frame.document();
579
580     String stringOmittingMicrosoftPrefix = stripMicrosoftPrefix(string);
581     if (stringOmittingMicrosoftPrefix.isEmpty())
582         return false;
583
584     String markup;
585     if (RuntimeEnabledFeatures::sharedFeatures().customPasteboardDataEnabled() && shouldSanitize()) {
586         markup = sanitizeMarkup(stringOmittingMicrosoftPrefix, msoListQuirksForMarkup(), WTF::Function<void (DocumentFragment&)> { [] (DocumentFragment& fragment) {
587             removeSubresourceURLAttributes(fragment, [] (const URL& url) {
588                 return shouldReplaceSubresourceURL(url);
589             });
590         } });
591     } else
592         markup = stringOmittingMicrosoftPrefix;
593
594     addFragment(createFragmentFromMarkup(document, markup, emptyString(), DisallowScriptingAndPluginContent));
595     return true;
596 }
597
598 bool WebContentMarkupReader::readHTML(const String& string)
599 {
600     if (!frame.document())
601         return false;
602
603     String rawHTML = stripMicrosoftPrefix(string);
604     if (shouldSanitize()) {
605         markup = sanitizeMarkup(rawHTML, msoListQuirksForMarkup(), WTF::Function<void (DocumentFragment&)> { [] (DocumentFragment& fragment) {
606             removeSubresourceURLAttributes(fragment, [] (const URL& url) {
607                 return shouldReplaceSubresourceURL(url);
608             });
609         } });
610     } else
611         markup = rawHTML;
612
613     return !markup.isEmpty();
614 }
615
616 bool WebContentReader::readRTFD(SharedBuffer& buffer)
617 {
618     if (frame.settings().preferMIMETypeForImages() || !frame.document())
619         return false;
620
621     auto string = adoptNS([[NSAttributedString alloc] initWithRTFD:buffer.createNSData().get() documentAttributes:nullptr]);
622     auto fragment = createFragmentAndAddResources(frame, string.get());
623     if (!fragment)
624         return false;
625     addFragment(fragment.releaseNonNull());
626
627     return true;
628 }
629
630 bool WebContentMarkupReader::readRTFD(SharedBuffer& buffer)
631 {
632     if (!frame.document())
633         return false;
634     auto string = adoptNS([[NSAttributedString alloc] initWithRTFD:buffer.createNSData().get() documentAttributes:nullptr]);
635     auto fragment = createFragmentAndAddResources(frame, string.get());
636     if (!fragment)
637         return false;
638
639     markup = serializeFragment(*fragment, SerializedNodes::SubtreeIncludingNode);
640     return true;
641 }
642
643 bool WebContentReader::readRTF(SharedBuffer& buffer)
644 {
645     if (frame.settings().preferMIMETypeForImages())
646         return false;
647
648     auto string = adoptNS([[NSAttributedString alloc] initWithRTF:buffer.createNSData().get() documentAttributes:nullptr]);
649     auto fragment = createFragmentAndAddResources(frame, string.get());
650     if (!fragment)
651         return false;
652     addFragment(fragment.releaseNonNull());
653
654     return true;
655 }
656
657 bool WebContentMarkupReader::readRTF(SharedBuffer& buffer)
658 {
659     if (!frame.document())
660         return false;
661     auto string = adoptNS([[NSAttributedString alloc] initWithRTF:buffer.createNSData().get() documentAttributes:nullptr]);
662     auto fragment = createFragmentAndAddResources(frame, string.get());
663     if (!fragment)
664         return false;
665     markup = serializeFragment(*fragment, SerializedNodes::SubtreeIncludingNode);
666     return true;
667 }
668
669 bool WebContentReader::readPlainText(const String& text)
670 {
671     if (!allowPlainText)
672         return false;
673
674     addFragment(createFragmentFromText(context, [text precomposedStringWithCanonicalMapping]));
675
676     madeFragmentFromPlainText = true;
677     return true;
678 }
679
680 bool WebContentReader::readImage(Ref<SharedBuffer>&& buffer, const String& type)
681 {
682     ASSERT(frame.document());
683     auto& document = *frame.document();
684     if (shouldReplaceRichContentWithAttachments())
685         addFragment(createFragmentForImageAttachment(frame, document, WTFMove(buffer), type));
686     else
687         addFragment(createFragmentForImageAndURL(document, DOMURL::createObjectURL(document, Blob::create(buffer.get(), type))));
688
689     return fragment;
690 }
691
692 #if ENABLE(ATTACHMENT_ELEMENT)
693
694 static Ref<HTMLElement> attachmentForFilePath(Frame& frame, const String& path)
695 {
696     auto document = makeRef(*frame.document());
697     auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document);
698     if (!supportsClientSideAttachmentData(frame)) {
699         attachment->setFile(File::create(path), HTMLAttachmentElement::UpdateDisplayAttributes::Yes);
700         return attachment;
701     }
702
703     String contentType;
704     Optional<uint64_t> fileSizeForDisplay;
705     if (FileSystem::fileIsDirectory(path, FileSystem::ShouldFollowSymbolicLinks::Yes))
706         contentType = kUTTypeDirectory;
707     else {
708         long long fileSize;
709         FileSystem::getFileSize(path, fileSize);
710         fileSizeForDisplay = fileSize;
711         contentType = File::contentTypeForFile(path);
712         if (contentType.isEmpty())
713             contentType = kUTTypeData;
714     }
715
716     frame.editor().registerAttachmentIdentifier(attachment->ensureUniqueIdentifier(), contentType, path);
717
718     if (contentTypeIsSuitableForInlineImageRepresentation(contentType)) {
719         auto image = HTMLImageElement::create(document);
720         image->setAttributeWithoutSynchronization(HTMLNames::srcAttr, DOMURL::createObjectURL(document, File::create(path)));
721         image->setAttachmentElement(WTFMove(attachment));
722         return image;
723     }
724
725     attachment->updateAttributes(WTFMove(fileSizeForDisplay), contentType, FileSystem::pathGetFileName(path));
726     return attachment;
727 }
728
729 static Ref<HTMLElement> attachmentForData(Frame& frame, SharedBuffer& buffer, const String& contentType, const String& name)
730 {
731     auto document = makeRef(*frame.document());
732     auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document);
733     auto mimeType = mimeTypeFromContentType(contentType);
734     auto typeForAttachmentElement = mimeType.isEmpty() ? contentType : mimeType;
735
736     // FIXME: We should instead ask CoreServices for a preferred name corresponding to the given content type.
737     static const char* defaultAttachmentName = "file";
738
739     String fileName;
740     if (name.isEmpty())
741         fileName = defaultAttachmentName;
742     else
743         fileName = name;
744
745     if (!supportsClientSideAttachmentData(frame)) {
746         attachment->setFile(File::create(Blob::create(buffer, WTFMove(typeForAttachmentElement)), fileName));
747         return attachment;
748     }
749
750     frame.editor().registerAttachmentIdentifier(attachment->ensureUniqueIdentifier(), typeForAttachmentElement, fileName, buffer);
751
752     if (contentTypeIsSuitableForInlineImageRepresentation(typeForAttachmentElement)) {
753         auto image = HTMLImageElement::create(document);
754         image->setAttributeWithoutSynchronization(HTMLNames::srcAttr, DOMURL::createObjectURL(document, File::create(Blob::create(buffer, WTFMove(typeForAttachmentElement)), WTFMove(fileName))));
755         image->setAttachmentElement(WTFMove(attachment));
756         return image;
757     }
758
759     attachment->updateAttributes({ buffer.size() }, WTFMove(typeForAttachmentElement), WTFMove(fileName));
760     return attachment;
761 }
762
763 #endif // ENABLE(ATTACHMENT_ELEMENT)
764
765 bool WebContentReader::readFilePaths(const Vector<String>& paths)
766 {
767     if (paths.isEmpty() || !frame.document())
768         return false;
769
770     auto& document = *frame.document();
771     if (!fragment)
772         fragment = document.createDocumentFragment();
773
774 #if ENABLE(ATTACHMENT_ELEMENT)
775     if (RuntimeEnabledFeatures::sharedFeatures().attachmentElementEnabled()) {
776         for (auto& path : paths)
777             fragment->appendChild(attachmentForFilePath(frame, path));
778     }
779 #endif
780
781     return true;
782 }
783
784 bool WebContentReader::readURL(const URL& url, const String& title)
785 {
786     if (url.isEmpty())
787         return false;
788
789 #if PLATFORM(IOS_FAMILY)
790     // FIXME: This code shouldn't be accessing selection and changing the behavior.
791     if (!frame.editor().client()->hasRichlyEditableSelection()) {
792         if (readPlainText([(NSURL *)url absoluteString]))
793             return true;
794     }
795
796     if ([(NSURL *)url isFileURL])
797         return false;
798 #endif // PLATFORM(IOS_FAMILY)
799
800     auto document = makeRef(*frame.document());
801     auto anchor = HTMLAnchorElement::create(document.get());
802     anchor->setAttributeWithoutSynchronization(HTMLNames::hrefAttr, url.string());
803
804     NSString *linkText = title.isEmpty() ? [(NSURL *)url absoluteString] : (NSString *)title;
805     anchor->appendChild(document->createTextNode([linkText precomposedStringWithCanonicalMapping]));
806
807     auto newFragment = document->createDocumentFragment();
808     if (fragment)
809         newFragment->appendChild(HTMLBRElement::create(document.get()));
810     newFragment->appendChild(anchor);
811     addFragment(WTFMove(newFragment));
812     return true;
813 }
814
815 bool WebContentReader::readDataBuffer(SharedBuffer& buffer, const String& type, const String& name)
816 {
817     if (buffer.isEmpty())
818         return false;
819
820     if (!shouldReplaceRichContentWithAttachments())
821         return false;
822
823     auto document = makeRefPtr(frame.document());
824     if (!document)
825         return false;
826
827     if (!fragment)
828         fragment = document->createDocumentFragment();
829
830 #if ENABLE(ATTACHMENT_ELEMENT)
831     fragment->appendChild(attachmentForData(frame, buffer, type, name));
832 #else
833     UNUSED_PARAM(type);
834     UNUSED_PARAM(name);
835 #endif
836     return true;
837 }
838
839 }