Découvrez les nouveautés de cette version : Fonctionnalités, améliorations et évolutions vous attendent ! 👉 Cliquez ici pour en savoir plus

Code source wiki de FileUploader

Version 1.1 par Admin le 24/03/2023 - 15:51

Masquer les derniers auteurs
Admin 1.1 1 {{velocity output="false"}}
2 #macro (createAttachment $fileName)
3 #set ($document = $doc)
4 #if ("$!request.document" != '')
5 #set ($document = $xwiki.getDocument($request.document))
6 #end
7 #if ($document && $document.hasAccessLevel('edit'))
8 ## If the attachment is uploaded to a new document then make sure we create the document with the right default
9 ## locale. See CKEDITOR-316: Document translations are created when uploading a file from the WYSIWYG editor in a
10 ## multi-language wiki. The following code replicates the behavior of the Upload action, but it has the desired
11 ## effect only on XWiki 11.9+
12 #if ($document.isNew())
13 #set ($rootLocale = $services.localization.toLocale(''))
14 #set ($discard = $document.setLocale($rootLocale))
15 #if ($rootLocale.equals($document.getDefaultLocale()))
16 #set ($discard = $document.setDefaultLocale($xwiki.getLocalePreference()))
17 #end
18 ## We also need to make sure the new document is created with the right syntax (e.g. the one coming from the
19 ## template used to create the document rather than the default wiki syntax).
20 #if ("$!request.syntax" != '')
21 #set ($discard = $document.setSyntaxId($request.syntax))
22 #end
23 #end
24 ## FIXME: Get the file content as an input stream instead of a byte array, but for this we need to expose
25 ## getFileItemInputStream in the public API of the fileupload plugin (or use a script service).
26 #set ($bytes = $xwiki.fileupload.getFileItemData('upload'))
27 #if (!$bytes)
28 ## Empty file (unfortunately getFileItemData returns null instead of an empty byte array).
29 #set ($bytes = [])
30 #end
31 #set ($discard = $document.addAttachment($fileName, $bytes))
32 #set ($discard = $document.save($services.localization.render('core.comment.uploadAttachmentComment', [$fileName])))
33 #sendSuccess($document $fileName)
34 #else
35 ## Forbidden
36 #sendError(403 'You are not allowed to perform this action.')
37 #end
38 #end
39
40 ## Old way of uploading, with a save of the document for each upload.
41 #macro (handleUploadRequest)
42 #set ($fileName = $xwiki.fileupload.getFileName('upload'))
43 #if ("$!fileName" != '')
44 #if ($services.csrf.isTokenValid($request.form_token))
45 #if ($fileName.startsWith('__fileCreatedFromDataURI__.'))
46 ## We need to generate a new name so that we don't overwrite existing attachments.
47 #set ($extension = $stringtool.substringAfter($fileName, '.'))
48 #set ($fileName = "${datetool.date.time}-${mathtool.random(100, 1000)}.$extension")
49 #end
50 #createAttachment($fileName)
51 #else
52 #sendError(403 "$services.localization.render('ckeditor.upload.error.csrf')")
53 #end
54 #else
55 ## Bad Request
56 #sendError(400 "$services.localization.render('ckeditor.upload.error.emptyReturn')")
57 #end
58 #end
59
60 ## New way of handling attachment without saving immediately the document.
61 #macro (handleTemporaryUploadRequest)
62 #if ($services.csrf.isTokenValid($request.form_token))
63 #set ($document = $doc)
64 #if ("$!request.document" != '')
65 #set ($document = $xwiki.getDocument($request.document))
66 #end
67 #set ($reference = $document.documentReference)
68 #try('uploadTemporaryAttachmentException')
69 #if ("$!request.filename" != '')
70 ## If the filename is explicitly provided, no need to recompute it.
71 #set ($fileName = $request.filename)
72 #else
73 #set ($fileName = $request.getPart('upload').getSubmittedFileName())
74 #if ($fileName.startsWith('__fileCreatedFromDataURI__.'))
75 ## We need to generate a new name so that we don't overwrite existing attachments.
76 #set ($extension = $stringtool.substringAfter($fileName, '.'))
77 #set ($fileName = "${datetool.date.time}-${mathtool.random(100, 1000)}.$extension")
78 #end
79 #end
80 #set ($attachment = $services.temporaryAttachments.uploadTemporaryAttachment($reference, 'upload', $fileName))
81 #end
82 #if ($attachment)
83 #sendSuccess($document, $attachment.filename)
84 #elseif ("$!uploadTemporaryAttachmentException" != '')
85 ## The exception is wrapped in an org.apache.velocity.exception.MethodInvocationException
86 #set ($validationException = $uploadTemporaryAttachmentException.cause)
87 #if ($validationException.translationKey)
88 #sendError(400 "$services.localization.render($validationException.translationKey, $validationException.translationParameters)")
89 #else
90 #sendError(400 "$services.localization.render('ckeditor.upload.error.emptyReturn')")
91 #end
92 #else
93 #sendError(400 "$services.localization.render('ckeditor.upload.error.emptyReturn')")
94 #end
95 #else
96 #sendError(403 "$services.localization.render('ckeditor.upload.error.csrf')")
97 #end
98 #end
99
100 #macro (sendSuccess $document $fileName)
101 #set ($url = $document.getAttachmentURL($fileName))
102 #set ($attachmentReference = $services.model.createAttachmentReference($document.documentReference, $fileName))
103 #set ($resourceReference = {
104 'type': 'attach',
105 'reference': $services.model.serialize($attachmentReference, $document.documentReference)
106 })
107 #set ($discard = $response.setContentType('application/json'))
108 #if ($request.initiator == 'filetools')
109 $jsontool.serialize({
110 'uploaded': 1,
111 'fileName': $fileName,
112 'url': $url,
113 'resourceReference': $resourceReference
114 })
115 #else
116 ## JSON expected by the filebrowser plugin.
117 $jsontool.serialize({
118 'uploaded': 1,
119 'url': $url,
120 'fileName': $fileName,
121 'message': {
122 'resourceReference': $resourceReference
123 }
124 })
125 #end
126 #end
127
128 #macro (sendError $code $message)
129 #set ($discard = $response.setContentType('application/json'))
130 ## The filetools plugin doesn't display the proper message if we call sendError() or setStatus() on the response.
131 #if ($request.initiator != 'filetools')
132 #set ($discard = $response.setStatus($code))
133 #end
134 $jsontool.serialize({
135 'uploaded': 0,
136 'error': {
137 'number': $code,
138 'message': $message
139 }
140 })
141 #end
142 {{/velocity}}
143
144 {{velocity wiki="false"}}
145 #if ($xcontext.action == 'get')
146 ## We fallback on the old mechanism also in case of editing a translation to avoid any problem.
147 ## See: XWIKI-20034
148 #set ($document = $tdoc)
149 #if ("$!request.document" != '')
150 #set ($document = $xwiki.getDocument($request.document))
151 #end
152 ## Special handling if we're editing a translation that does not exist yet: in such case we cannot rely on $document.isTranslation because the context $tdoc
153 ## automatically fallback on the default locale in view mode, and we're getting this through a /get/ request.
154 ## See: XWIKI-20537
155 #set ($isNewTranslation = false)
156 #if ($document.locale == "" && $services.localization.currentLocale != $services.localization.defaultLocale)
157 #set ($docRefWithLocale = $services.model.createDocumentReference($document.documentReference, $services.localization.currentLocale))
158 #set ($isNewTranslation = $xwiki.getDocument($docRefWithLocale).isNew())
159 #end
160 #if ($request.getHeader('X-XWiki-Temporary-Attachment-Support') == 'true' && !$document.isTranslation() && !$isNewTranslation)
161 #handleTemporaryUploadRequest()
162 #else
163 #handleUploadRequest()
164 #end
165 #end
166 {{/velocity}}