Wiki source code of Attachments

Last modified by Vincent Massol on 2026/10/07 11:31

Hide last authors
Vincent Massol 1.1 1 {{velocity output="false"}}
Thomas Mortagne 13.1 2 #set ($translationPrefix = 'xe.attachmentSelector')
3
Vincent Massol 1.1 4 #if ($request.xaction == 'postUpload')
5 #set ($targetDocument = $xwiki.getDocument($request.get('docname')))
Vincent Massol 5.1 6 #set ($targetAttachDocument = $xwiki.getDocument($request.get('targetdocname')))
7
Vincent Massol 1.1 8 #set ($fieldname = $request.get('fieldname'))
Thomas Mortagne 13.1 9 #set ($comment = $services.localization.render("${translationPrefix}.postUpload.comment", [$fieldname]))
Vincent Massol 1.1 10 #set ($docAction = $request.get('docAction'))
Vincent Massol 5.1 11 #set ($attachmentList = $targetAttachDocument.getAttachmentList())
Vincent Massol 1.1 12 #if ($attachmentList && $attachmentList.size() > 0)
Simon Urli 14.1 13 #set ($sortedAttachments = $collectiontool.sort($attachmentList, 'date:desc'))
Vincent Massol 1.1 14 #set ($lastAttachment = $sortedAttachments.get(0))
15 #end
Thomas Mortagne 9.1 16 $response.sendRedirect($targetDocument.getURL($docAction, $escapetool.url({
17 $fieldname: $lastAttachment.filename,
Thomas Mortagne 13.1 18 'comment': $comment,
Thomas Mortagne 9.1 19 'form_token': $request.form_token
20 })))
Vincent Massol 1.1 21 #stop
22 #end
23 {{/velocity}}
24
25 {{velocity output="false"}}
26 ##
27 ## Macros
28 ##
29 #set ($attachmentPickerDocName = 'XWiki.AttachmentSelector')
30
31 $xwiki.ssx.use($attachmentPickerDocName)
32 $xwiki.jsx.use($attachmentPickerDocName)
33
34 #**
35 * Displays the attachment gallery as a list of attachment boxes, starting with special boxes for uploading a new attachment and for setting a default value.
Vincent Massol 5.1 36 *
37 * @param $targetDocument the document to recieve the field value being modified
38 * @param $targetAttachDocument the document to list/save attachments to
Vincent Massol 1.1 39 * @param $options generic picker options
40 *#
Thomas Mortagne 23.1 41 #macro (_attachmentPicker_displayAttachmentGallery $targetDocument, $targetAttachDocument, $options)
Vincent Massol 1.1 42 #set ($currentValue = $targetDocument.getValue($options.property))
Vincent Massol 5.1 43 #if ("$!{targetAttachDocument.getAttachment($currentValue)}" == '')
Vincent Massol 1.1 44 #set ($currentValue = "$!{options.defaultValue}")
45 #end
46 (% class="gallery" %)(((
Vincent Massol 5.1 47 ## Only display the upload form if they have edit permission on targetAttachDocument
Thomas Mortagne 23.1 48 #_attachmentPicker_displayUploadForm($targetDocument, $targetAttachDocument, $options)
49 #_attachmentPicker_displayAttachmentGalleryEmptyValue($targetDocument, $targetAttachDocument, $options, $currentValue)
Simon Urli 18.1 50 #if ("$!services.temporaryAttachments" != '')
51 #set ($unsortedAttachments = $services.temporaryAttachments.listAllAttachments($targetAttachDocument))
52 #set ($sortedAttachments = $collectiontool.sort($unsortedAttachments, "${options.sortAttachmentsBy}"))
53 #else
54 #set ($sortedAttachments = $collectiontool.sort($targetAttachDocument.getAttachmentList(), "${options.sortAttachmentsBy}") )
Vincent Massol 5.1 55 #end
Vincent Massol 1.1 56 #foreach ($attachment in $sortedAttachments)
57 #set ($extension = $attachment.getFilename())
58 #set ($extension = $extension.substring($mathtool.add($extension.lastIndexOf('.'), 1)).toLowerCase())
59 #if ($options.filter.size() == 0 || $options.filter.contains($extension))
Thomas Mortagne 23.1 60 #_attachmentPicker_displayAttachmentBox($attachment $targetDocument $targetAttachDocument, $options $currentValue)
Vincent Massol 1.1 61 #end
62 #end
63 )))
64 #end
65
66 #**
67 * Displays an attachment box.
Vincent Massol 5.1 68 *
Vincent Massol 1.1 69 * @param $attachment the target attachment to display
70 * @param $targetDocument the document being modified
71 * @param $options generic picker options
72 * @param $currentValue the currently selected file, used for determining if the box should be highlighted as the current value
73 *#
Thomas Mortagne 23.1 74 #macro (_attachmentPicker_displayAttachmentBox $attachment $targetDocument $targetAttachDocument, $options $currentValue)
Simon Urli 18.1 75 #set ($hasTemporaryAttachment = "$!services.temporaryAttachments" != '')
76 #set ($canEdit = $xwiki.hasAccessLevel('edit', $xcontext.user, ${targetAttachDocument.fullName}))
77 #set ($isTemporaryAttachment = false)
78 #if(!$hasTemporaryAttachment)
79 #set ($canDeleteAttachment = $canEdit)
Vincent Massol 1.1 80 #else
Simon Urli 18.1 81 #set ($isTemporaryAttachment = $services.temporaryAttachments.temporaryAttachmentExists($attachment))
82 ## TODO: Update once it is made possible to delete temporary attachments (see XWIKI-20225).
83 #set ($canDeleteAttachment = !$isTemporaryAttachment && $canEdit)
Vincent Massol 1.1 84 #end
Simon Urli 18.1 85 #set ($cssClasses = [])
86 #if ($options.displayImage && $attachment.isImage())
87 #set ($discard = $cssClasses.add('gallery_image'))
88 #end
89 #if ($isTemporaryAttachment)
90 #set ($discard = $cssClasses.add('temporary_attachment'))
91 #end
Thomas Mortagne 23.1 92 #_attachmentPicker_displayStartFrame({'value' : $attachment.filename, 'text' : $attachment.filename, 'cssClass' : "${stringtool.join($cssClasses, ' ')}"} $currentValue)
93 #_attachmentPicker_displayAttachmentDetails($attachment $options)
Vincent Massol 1.1 94 #set ($returnURL = $escapetool.url($doc.getURL('view', $request.queryString)))
Vincent Massol 5.1 95 #set ($deleteURL = $targetAttachDocument.getAttachmentURL($attachment.filename, 'delattachment', "xredirect=${returnURL}&form_token=$!{services.csrf.getToken()}") )
96 #set ($viewURL = $targetAttachDocument.getAttachmentURL($attachment.filename) )##{'name' : 'download', 'url' : $viewURL, 'rel' : '__blank'}
Simon Urli 17.1 97 #set ($selectURL = $targetDocument.getURL(${options.get('docAction')}, $escapetool.url({
98 "${options.get('classname')}_${options.get('object')}_${options.get('property')}": ${attachment.filename},
99 'form_token': $!{services.csrf.getToken()}
100 })))
Simon Urli 18.1 101 ## Delete action is only proposed for users with the edit right on the document.
102 ## If the temporary attachment is available, the delete action is only allowed for non-temporary attachments.
Thomas Mortagne 23.1 103 #set ($attachmentActions = [{'name' : 'select', 'url' : $selectURL, 'icon' : 'check', 'extraCssClass' : 'btn btn-xs btn-success'}])
Simon Urli 18.1 104 #if($canDeleteAttachment)
Thomas Mortagne 23.1 105 #set ($discard = $attachmentActions.add({'name' : 'delete', 'url' : $deleteURL, 'icon' : 'cross', 'extraCssClass' : 'btn btn-xs btn-danger'}))
Simon Urli 18.1 106 #end
107 #define($additionalContent)
108 #if ($isTemporaryAttachment)
109 #set ($titleMessage = $services.localization.render('attachment.attachmentSelector.attachmentBox.temporaryAttachmentTitle'))
110 #set ($titleMessage = $services.rendering.escape($titleMessage, 'xwiki/2.1'))
111 (% title="$titleMessage" %)$services.icon.render('clock')(%%)
112 #end
113 #end
Thomas Mortagne 23.1 114 #_attachmentPicker_displayEndFrame ($attachmentActions $additionalContent)
Vincent Massol 1.1 115 #end
116
117 #**
118 * Writes the wiki code used at the start of an attachment box. Outputs the attachment title bar, and opens the inner frame div.
Vincent Massol 5.1 119 *
Vincent Massol 1.1 120 * @param $boxOptions a map of parameters/options for the current attachment, holding, for example, the attachment name (boxOptions.value),
121 * the title to display (boxOptions.text), optional extra CSS classnames to put on the box (boxOptions.cssClass)
122 * @param $currentValue the currently selected file, used for determining if this attachment should be highlighted as the current value
123 *#
Thomas Mortagne 23.1 124 #macro (_attachmentPicker_displayStartFrame $boxOptions $currentValue)
Vincent Massol 1.1 125 (% class="gallery_attachmentbox $!{boxOptions.cssClass} #if ("$!{boxOptions.value}" == $currentValue) current#{end}" %)(((
Simon Urli 17.1 126 (% class="gallery_attachmenttitle" title="$services.rendering.escape($!{boxOptions.value}, 'xwiki/2.1')" %)(((
Thomas Mortagne 23.1 127 #if($!{boxOptions.cssClass} == 'gallery_upload')$services.icon.render('add') #end##
Simon Urli 17.1 128 $services.rendering.escape($boxOptions.text, 'xwiki/2.1')
129 )))
Vincent Massol 1.1 130 (% class="gallery_attachmentframe" %)(((
131 #end
132
133 #**
134 * Displays details about an attachment inside the attachment box. If the attachment is an image and the "displayImage" option is on,
135 * then the image is displayed. Otherwise, some basic information is displayed: the version, the size, the date and the author.
Vincent Massol 5.1 136 *
Vincent Massol 1.1 137 * @param $attachment the target attachment to display
138 * @param $options generic picker options
139 *#
Thomas Mortagne 23.1 140 #macro (_attachmentPicker_displayAttachmentDetails $attachment $options)
Vincent Massol 1.1 141 #if ($attachment)
Thomas Mortagne 13.1 142 ## Compute the attachment reference because there's no getter.
143 #set ($attachmentReference = $services.model.createAttachmentReference($attachment.document.documentReference,
144 $attachment.filename))
Simon Urli 17.1 145 #set ($attachmentStringReference = $services.rendering.escape($services.model.serialize($attachmentReference, 'default'), 'xwiki/2.1'))
Vincent Massol 1.1 146 #if ($attachment.isImage() && $options.displayImage)
Thomas Mortagne 13.1 147 ## We add the version to the query string in order to invalidate the cache when an image attachment is replaced.
148 #set ($queryString = $escapetool.url({'version': $attachment.version}))
Simon Urli 14.1 149 [[[[image:${attachmentStringReference}||width=180 queryString="$queryString"]]>>attach:$attachmentStringReference]]
Vincent Massol 1.1 150 #else
Simon Urli 17.1 151 * (% class="mime" %){{html wiki=false clean=false}}#mimetypeimg($attachment.getMimeType().toLowerCase() $attachment.getFilename().toLowerCase()){{/html}}(%%) (% class="filename" %)$services.rendering.escape($attachment.getFilename(), 'xwiki/2.1')(% %)
Thomas Mortagne 13.1 152 * v$attachment.getVersion() (#dynamicsize($attachment.longSize))
Marius Dumitru Florea 6.1 153 * $services.localization.render('core.viewers.attachments.author', [$!{xwiki.getUserName($attachment.author, false)}]) $services.localization.render('core.viewers.attachments.date', [$!{xwiki.formatDate($attachment.date, 'dd/MM/yyyy hh:mm')}])
Simon Urli 14.1 154 * (% class="buttonwrapper" %)[[${services.localization.render("${translationPrefix}.actions.download")}>>attach:${attachmentStringReference}||title="$services.localization.render("${translationPrefix}.actions.download")" rel="__blank" class="button"]](%%)
Vincent Massol 1.1 155 #end
156 #end
157 #end
158
159 #**
160 * Writes the wiki code used at the end of an attachment box. Closes the inner frame div, and outputs the attachment actions.
Vincent Massol 5.1 161 *
Vincent Massol 1.1 162 * @param $actions a list of maps defining action buttons, where each entry contains a subset of the following:
163 * <dl>
164 * <dt>name</dt>
165 * <dd>identifies the action; the name is used as a CSS classname, and in the translation key for the display text, as "xe.attachmentSelector.actions.<name>"</dd>
166 * <dt>url</dt>
167 * <dd>the destination of the button</dd>
168 * <dt>rel</dt>
169 * <dd>an optional parameter to be used in the "rel" HTML attribute; for example "__blank" can be used to open the link in a new tab/window</dd>
170 * </dl>
Simon Urli 18.1 171 * @param $additionalContent optional additional content that does not follow the structure of the actions
Vincent Massol 1.1 172 *#
Thomas Mortagne 23.1 173 #macro (_attachmentPicker_displayEndFrame $actions $additionalContent)
Vincent Massol 1.1 174 )))## attachmentframe
175 (% class="gallery_actions" %)(((
176 #foreach ($action in $actions)
Marius Dumitru Florea 6.1 177 #set( $actionname = $services.localization.render("${translationPrefix}.actions.${action.name}") )
Vincent Massol 28.1 178 ## Escape the URL so that it cannot break out of the link syntax, whatever its origin.
179 #set ($actionURL = $services.rendering.escape($action.url, 'xwiki/2.1'))
Thomas Mortagne 23.1 180 [[${services.icon.render($action.icon)}(% class="sr-only"%)${actionname}(%%)>>##
Vincent Massol 28.1 181 path:${actionURL}||class="tool ${action.name} $!{action.extraCssClass}"##
Thomas Mortagne 23.1 182 title="${actionname}" #if($action.rel) rel="${action.rel}"#end]]##
Vincent Massol 1.1 183 #end
Simon Urli 18.1 184 $!additionalContent
Vincent Massol 1.1 185 )))## actions
186 )))## attachmentbox
187 #end
188
189 #**
190 * Displays the upload box used for adding and selecting a new attachment.
Vincent Massol 5.1 191 *
192 * @param $targetDocument the document with the property being modified
193 * @param $targetAttachDocument the document to upload the attachment to
Vincent Massol 1.1 194 * @param $options generic picker options
195 *#
Thomas Mortagne 23.1 196 #macro (_attachmentPicker_displayUploadForm $targetDocument, $targetAttachDocument, $options)
197 #_attachmentPicker_displayStartFrame({
Marius Dumitru Florea 6.1 198 'value' : $services.localization.render("${translationPrefix}.upload.title"),
199 'text' : $services.localization.render("${translationPrefix}.upload.title"),
Vincent Massol 1.1 200 'cssClass' : 'gallery_upload'
Vincent Massol 5.1 201 } $NULL)
Vincent Massol 1.1 202 {{html clean="false"}}
Vincent Massol 5.1 203 <form action="$targetAttachDocument.getURL('upload')" enctype="multipart/form-data" method="post" id="uploadAttachment" class="uploadAttachment xform">
Vincent Massol 1.1 204 <div class="gallery_upload_input">
205 #if (${options.rawfilter} != '')
Vincent Massol 8.1 206 <span class="xHint">$escapetool.xml($services.localization.render("${translationPrefix}.upload.hint", [${options.rawfilter}]))</span>
Vincent Massol 1.1 207 #end
Thomas Mortagne 13.1 208 <input type="file" name="filepath" id="attachfile" class="noitems" title="$!{escapetool.xml($options.rawfilter)}"/>
Vincent Massol 5.1 209 <input type="hidden" name="xredirect" value="$xwiki.getDocument($attachmentPickerDocName).getURL('get', "xaction=postUpload&amp;docAction=$!{escapetool.url($options.get('docAction'))}&amp;targetdocname=$!{escapetool.url($targetAttachDocument.fullName)}&amp;docname=$!{escapetool.url($targetDocument.fullName)}&amp;fieldname=$!{escapetool.url($options.get('classname'))}_$!{escapetool.url($options.get('object'))}_$!{escapetool.url($options.get('property'))}&amp;form_token=$!{services.csrf.getToken()}")" />
Vincent Massol 1.1 210 <input type="hidden" name="docname" value="$!{escapetool.xml($targetDocument.fullName)}" />
211 <input type="hidden" name="classname" value="$!{escapetool.xml($options.get('classname'))}" />
212 <input type="hidden" name="object" value="$!{escapetool.xml($options.get('object'))}" />
213 <input type="hidden" name="property" value="$!{escapetool.xml($options.get('property'))}" />
214 <input type="hidden" name="form_token" value="$!{services.csrf.getToken()}" />
215 </div>
Thomas Mortagne 13.1 216 #if ("$!currentValue" != '' && $currentValue != $options.defaultValue)
217 <div>
218 <label>
219 <input type="checkbox" name="filename" value="$!escapetool.xml($currentValue)"
220 />$services.localization.render('attachmentSelector.replace',
221 ["<strong>$!escapetool.xml($currentValue)</strong>"])
222 </label>
223 <span class="xHint">$escapetool.xml($services.localization.render('attachmentSelector.replace.hint'))</span>
224 </div>
225 #end
226 #if ($xwiki.hasEditComment() && $options.versionSummary)
227 <div>
228 #if ($xwiki.isEditCommentFieldHidden())
229 <input type="hidden" name="comment" value="$!escapetool.xml($request.comment)" />
230 #else
231 <label for="commentinput">$services.localization.render('core.comment')</label>
232 <input type="text" name="comment" id="commentinput" value="$!escapetool.xml($request.comment)"
233 title="$services.localization.render('core.comment.tooltip')" />
234 #end
235 </div>
236 #end
Vincent Massol 1.1 237 <div class="buttons">
238 <span class="buttonwrapper">
Marius Dumitru Florea 6.1 239 <input type="submit" name="action_upload" class="button " value='$services.localization.render("${translationPrefix}.upload.submit")' title='$services.localization.render("${translationPrefix}.upload.submit")'/>
Vincent Massol 1.1 240 </span>
241 </div>
242 </form>
243 {{/html}}
Thomas Mortagne 23.1 244 #_attachmentPicker_displayEndFrame ([])
Vincent Massol 1.1 245 #end
246
247 #**
248 * Displays the "empty value" box, used for unsetting the field value.
Vincent Massol 5.1 249 *
Vincent Massol 1.1 250 * @param $targetDocument the document being modified
Vincent Massol 5.1 251 * @param $targetAttachDocument the document that the attachments will the loaded from/saved to
Vincent Massol 1.1 252 * @param $options generic picker options
253 * @param $currentValue the currently selected file, used for determining if the empty box should be highlighted as the current value
254 *#
Thomas Mortagne 23.1 255 #macro (_attachmentPicker_displayAttachmentGalleryEmptyValue $targetDocument, $targetAttachDocument, $options, $currentValue)
Vincent Massol 1.1 256 #if ("$!{options.get('defaultValue')}" != '')
257 #set ($reference = ${options.get('defaultValue')})
258 #set ($docNameLimit = $reference.indexOf('@'))
259 #if ($docNameLimit > 0)
260 #set ($docName = $reference.substring(0, $docNameLimit))
261 #else
Vincent Massol 5.1 262 #set ($docName = $targetAttachDocument.fullName)
Vincent Massol 1.1 263 #end
264 #set ($attachmentName = $reference.substring($mathtool.add($docNameLimit, 1)))
265 #set ($defaultAttachment = $xwiki.getDocument($docName).getAttachment($attachmentName))
266 #if ($defaultAttachment.isImage())
267 #set($dcssClass = 'gallery_image')
268 #end
269 #end
Thomas Mortagne 23.1 270 #_attachmentPicker_displayStartFrame({'cssClass' : "gallery_emptyChoice $!{dcssClass}", 'text' : $services.localization.render("${translationPrefix}.default"), 'value' : "${options.defaultValue}"} $currentValue)
271 #_attachmentPicker_displayAttachmentDetails($defaultAttachment $options)
Vincent Massol 1.1 272 #set ($returnURL = $escapetool.url($doc.getURL('view', $request.queryString)))
Vincent Massol 28.1 273 #set ($selectURL = $targetDocument.getURL(${options.get('docAction')}, $escapetool.url({
274 "${options.get('classname')}_${options.get('object')}_${options.get('property')}": '',
275 'form_token': $!{services.csrf.getToken()}
276 })))
Thomas Mortagne 23.1 277 #_attachmentPicker_displayEndFrame ([{'name' : 'select', 'url' : $selectURL, 'icon' : 'check', 'extraCssClass' : 'btn btn-xs btn-success'}])
Vincent Massol 1.1 278 #end
279 {{/velocity}}
280
281 {{velocity}}
282 #if ($request.docname)
283 #set ($targetDocument = $xwiki.getDocument($request.docname))
Vincent Massol 5.1 284 #if ($request.targetdocname)
285 ## Use the target document if it exists.
286 #set ($targetAttachDocument = $xwiki.getDocument($request.targetdocname))
287 #else
288 ## Otherwise, just use the current document as the target to save/load attachments
289 #set ($targetAttachDocument = $targetDocument)
290 #end
Vincent Massol 1.1 291 #if ("$!{request.savemode}" == 'direct')
292 #set($docAction = 'save')
293 #else
Vincent Massol 5.1 294 #set($docAction = $targetAttachDocument.getDefaultEditMode())
Vincent Massol 1.1 295 #end
296 #set ($filter = [])
297 #set ($rawfilter = '')
298 #if ("$!{request.filter}" != '')
299 #foreach ($value in $request.filter.trim().split('\s*+[,|; ]\s*+'))
300 #if ("$!value" != '')
301 #set ($discard = $filter.add($value.toLowerCase()))
302 #set ($rawfilter = "${rawfilter}, ${value}")
303 #end
304 #end
305 #if ($rawfilter != '')
306 #set ($rawfilter = $rawfilter.substring(2))
307 #end
308 #end
309 #if ("$!{request.displayImage}" == 'true')
310 #set ($displayImage = true)
311 #else
312 #set ($displayImage = false)
313 #end
Vincent Massol 5.1 314 ### Determine attachment sorting
315 #set($sortAttachmentsBy = "$!{request.sortAttachmentsBy}")
316 #set ($validAttachmentProperties = ['filename', 'date', 'filesize', 'author', 'version', 'mimeType'])
317 #if($sortAttachmentsBy == '' || $validAttachmentProperties.indexOf($sortAttachmentsBy) == -1)
318 ### Default to sorting by filename, sort not requested.
319 #set($sortAttachmentsBy = "filename")
320 #end
321 ### Set attachment sorting direction
322 #if($sortAttachmentsBy == 'date')
323 ### Sort the date descending
324 #set($sortAttachmentsBy = "date:desc")
325 #else
326 ### Sort everything else ascending
327 #set($sortAttachmentsBy = "${sortAttachmentsBy}:asc")
328 #end
Vincent Massol 1.1 329 #set ($options = {
330 'classname' : ${request.get('classname')},
Simon Urli 14.1 331 'object' : $!{numbertool.toNumber($request.object).intValue()},
Vincent Massol 1.1 332 'property' : ${request.property},
333 'displayImage' : ${displayImage},
334 'docAction' : ${docAction},
335 'defaultValue' : "$!{request.defaultValue}",
336 'rawfilter': "$!{rawfilter}",
Vincent Massol 5.1 337 'filter': ${filter},
Thomas Mortagne 13.1 338 'sortAttachmentsBy': ${sortAttachmentsBy},
339 'versionSummary': $request.versionSummary.equals('true')
Vincent Massol 1.1 340 })
341 $!targetDocument.use($targetDocument.getObject($options.classname, $options.object))##
Thomas Mortagne 23.1 342 #_attachmentPicker_displayAttachmentGallery($targetDocument, $targetAttachDocument, $options)
Vincent Massol 1.1 343
Simon Urli 18.1 344 #set ($cancelLinkName = $services.rendering.escape($services.rendering.escape($services.localization.render("${translationPrefix}.cancel"), 'xwiki/2.1'), 'xwiki/2.1'))
345 #set ($cancelLinkTarget = $services.rendering.escape($services.model.serialize($targetDocument), 'xwiki/2.1'))
Vincent Massol 1.1 346 (% class="gallery_buttons buttons" %)(((
Simon Urli 18.1 347 (% class="buttonwrapper secondary" %)[[$cancelLinkName>>$cancelLinkTarget||class="button secondary" id="attachment-picker-close"]]
Vincent Massol 1.1 348 )))
349 #end
350 {{/velocity}}

Get Connected