Changes for page Attachments

Last modified by editors on 2023/06/04 16:45

<
From version < 2.1 >
edited by superadmin
on 2023/06/04 09:33
To version < 3.1
edited by editors
on 2023/06/04 16:45
Change comment: Install extension [org.xwiki.platform:xwiki-platform-attachment-ui/14.10.11]

Summary

Details

Page properties
Author
... ... @@ -1,1 +1,1 @@
1 -XWiki.superadmin
1 +xwiki:XWiki.Admin
Content
... ... @@ -45,11 +45,14 @@
45 45   #end
46 46   (% class="gallery" %)(((
47 47   ## Only display the upload form if they have edit permission on targetAttachDocument
48 - #if ($xwiki.hasAccessLevel('edit',$xcontext.user,${targetAttachDocument.fullName}))
49 - #attachmentPicker_displayUploadForm($targetDocument, $targetAttachDocument, $options)
50 - #end
48 + #attachmentPicker_displayUploadForm($targetDocument, $targetAttachDocument, $options)
51 51   #attachmentPicker_displayAttachmentGalleryEmptyValue($targetDocument, $targetAttachDocument, $options, $currentValue)
52 - #set ($sortedAttachments = $collectiontool.sort($targetAttachDocument.getAttachmentList(), "${options.sortAttachmentsBy}") )
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}") )
55 + #end
53 53   #foreach ($attachment in $sortedAttachments)
54 54   #set ($extension = $attachment.getFilename())
55 55   #set ($extension = $extension.substring($mathtool.add($extension.lastIndexOf('.'), 1)).toLowerCase())
... ... @@ -69,18 +69,46 @@
69 69   * @param $currentValue the currently selected file, used for determining if the box should be highlighted as the current value
70 70   *#
71 71  #macro (attachmentPicker_displayAttachmentBox $attachment $targetDocument $targetAttachDocument, $options $currentValue)
72 - #if ($options.displayImage && $attachment.isImage())
73 - #set ($cssClass = 'gallery_image')
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)
74 74   #else
75 - #set ($cssClass = '')
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)
76 76   #end
77 - #attachmentPicker_displayStartFrame({'value' : $attachment.filename, 'text' : $attachment.filename, 'cssClass' : "$!{cssClass}"} $currentValue)
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
92 + #attachmentPicker_displayStartFrame({'value' : $attachment.filename, 'text' : $attachment.filename, 'cssClass' : "${stringtool.join($cssClasses, ' ')}"} $currentValue)
78 78   #attachmentPicker_displayAttachmentDetails($attachment $options)
79 79   #set ($returnURL = $escapetool.url($doc.getURL('view', $request.queryString)))
80 80   #set ($deleteURL = $targetAttachDocument.getAttachmentURL($attachment.filename, 'delattachment', "xredirect=${returnURL}&form_token=$!{services.csrf.getToken()}") )
81 81   #set ($viewURL = $targetAttachDocument.getAttachmentURL($attachment.filename) )##{'name' : 'download', 'url' : $viewURL, 'rel' : '__blank'}
82 - #set ($selectURL = $targetDocument.getURL(${options.get('docAction')}, "${options.get('classname')}_${options.get('object')}_${options.get('property')}=${attachment.filename}&form_token=$!{services.csrf.getToken()}"))
83 - #attachmentPicker_displayEndFrame ([{'name' : 'select', 'url' : $selectURL}, {'name' : 'delete', 'url' : $deleteURL}])
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 + })))
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.
103 + #set ($attachmentActions = [{'name' : 'select', 'url' : $selectURL}])
104 + #if($canDeleteAttachment)
105 + #set ($discard = $attachmentActions.add({'name' : 'delete', 'url' : $deleteURL}))
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
114 + #attachmentPicker_displayEndFrame ($attachmentActions $additionalContent)
84 84  #end
85 85  
86 86  #**
... ... @@ -92,7 +92,9 @@
92 92   *#
93 93  #macro (attachmentPicker_displayStartFrame $boxOptions $currentValue)
94 94   (% class="gallery_attachmentbox $!{boxOptions.cssClass} #if ("$!{boxOptions.value}" == $currentValue) current#{end}" %)(((
95 - (% class="gallery_attachmenttitle" title="$!{boxOptions.value}" %)((($boxOptions.text)))
126 + (% class="gallery_attachmenttitle" title="$services.rendering.escape($!{boxOptions.value}, 'xwiki/2.1')" %)(((
127 + $services.rendering.escape($boxOptions.text, 'xwiki/2.1')
128 + )))
96 96   (% class="gallery_attachmentframe" %)(((
97 97  #end
98 98  
... ... @@ -108,13 +108,13 @@
108 108   ## Compute the attachment reference because there's no getter.
109 109   #set ($attachmentReference = $services.model.createAttachmentReference($attachment.document.documentReference,
110 110   $attachment.filename))
111 - #set ($attachmentStringReference = $services.model.serialize($attachmentReference, 'default'))
144 + #set ($attachmentStringReference = $services.rendering.escape($services.model.serialize($attachmentReference, 'default'), 'xwiki/2.1'))
112 112   #if ($attachment.isImage() && $options.displayImage)
113 113   ## We add the version to the query string in order to invalidate the cache when an image attachment is replaced.
114 114   #set ($queryString = $escapetool.url({'version': $attachment.version}))
115 115   [[[[image:${attachmentStringReference}||width=180 queryString="$queryString"]]>>attach:$attachmentStringReference]]
116 116   #else
117 - * (% class="mime" %){{html wiki=false clean=false}}#mimetypeimg($attachment.getMimeType().toLowerCase() $attachment.getFilename().toLowerCase()){{/html}}(%%) (% class="filename" %)$attachment.getFilename()(% %)
150 + * (% 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')(% %)
118 118   * v$attachment.getVersion() (#dynamicsize($attachment.longSize))
119 119   * $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')}])
120 120   * (% class="buttonwrapper" %)[[${services.localization.render("${translationPrefix}.actions.download")}>>attach:${attachmentStringReference}||title="$services.localization.render("${translationPrefix}.actions.download")" rel="__blank" class="button"]](%%)
... ... @@ -134,8 +134,9 @@
134 134   * <dt>rel</dt>
135 135   * <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>
136 136   * </dl>
170 + * @param $additionalContent optional additional content that does not follow the structure of the actions
137 137   *#
138 -#macro (attachmentPicker_displayEndFrame $actions)
172 +#macro (attachmentPicker_displayEndFrame $actions $additionalContent)
139 139   )))## attachmentframe
140 140   (% class="gallery_actions" %)(((
141 141   #foreach ($action in $actions)
... ... @@ -142,6 +142,7 @@
142 142   #set( $actionname = $services.localization.render("${translationPrefix}.actions.${action.name}") )
143 143   [[${actionname}>>path:${action.url}||class="tool ${action.name}" title="${actionname}" #if($action.rel) rel="${action.rel}"#end]]##
144 144   #end
179 + $!additionalContent
145 145   )))## actions
146 146   )))## attachmentbox
147 147  #end
... ... @@ -298,8 +298,10 @@
298 298   $!targetDocument.use($targetDocument.getObject($options.classname, $options.object))##
299 299   #attachmentPicker_displayAttachmentGallery($targetDocument, $targetAttachDocument, $options)
300 300  
336 + #set ($cancelLinkName = $services.rendering.escape($services.rendering.escape($services.localization.render("${translationPrefix}.cancel"), 'xwiki/2.1'), 'xwiki/2.1'))
337 + #set ($cancelLinkTarget = $services.rendering.escape($services.model.serialize($targetDocument), 'xwiki/2.1'))
301 301   (% class="gallery_buttons buttons" %)(((
302 - (% class="buttonwrapper secondary" %)[[$services.localization.render("${translationPrefix}.cancel")>>${targetDocument}||class="button secondary" id="attachment-picker-close"]]
339 + (% class="buttonwrapper secondary" %)[[$cancelLinkName>>$cancelLinkTarget||class="button secondary" id="attachment-picker-close"]]
303 303   )))
304 304  #end
305 305  {{/velocity}}
XWiki.JavaScriptExtension[0]
Code
... ... @@ -1,4 +1,66 @@
1 1  var XWiki = (function(XWiki) {
2 + function uploadTemporaryAttachment() {
3 + // Require jquery locally until we are able to fully migrate this code away from prototype.
4 + const form = this.property.up('form');
5 + require(['jquery'], function ($) {
6 + const data = new FormData();
7 + const uploadedFile = $('#attachfile')[0].files[0];
8 + const filenameCheckbox = $("#uploadAttachment input[name='filename']");
9 +
10 + // TODO: Fix replace currently selected checkbox (see XWIKI-20181).
11 + data.append('upload', uploadedFile);
12 + const notification = new XWiki.widgets.Notification(
13 + "$services.localization.render('xe.attachmentSelector.upload.inProgress')", 'inprogress');
14 + const params = {
15 + 'form_token': $(form).find('[name="form_token"]').val(),
16 + 'sheet': 'CKEditor.FileUploader',
17 + 'outputSyntax': 'plain'
18 + };
19 +
20 + // Update the name of the file with the name of the currently selected attachment if required.
21 + if (filenameCheckbox.prop('checked')) {
22 + params['filename'] = filenameCheckbox.val()
23 + }
24 +
25 + $.ajax({
26 + 'url': XWiki.currentDocument.getURL('get', new URLSearchParams(params).toString()),
27 + method: 'POST',
28 + data: data,
29 + processData: false,
30 + contentType: false, // Sets the 'multipart/form-data' automatically
31 + headers: {
32 + 'X-XWiki-Temporary-Attachment-Support': true
33 + }
34 + }).done(function (response) {
35 + #set ($successMessage = $escapetool.javascript($services.localization.render('attachment.attachmentSelector.temporaryUpload.success')))
36 + notification.replace(new XWiki.widgets.Notification("$successMessage", 'done'));
37 + // Add a field with the name of the uploaded file so that it is moved from the temporary
38 + // attachments to the persisded ones on save.
39 + $(form).append($('<input/>')
40 + .prop('type', 'hidden')
41 + .prop('name', 'uploadedFiles')
42 + .prop('value', response.fileName))
43 + $(form).find('input[type="hidden"].property-reference').prop('value', response.fileName);
44 + this.updateAttachment(response.fileName, response.url);
45 + this.dialog.closeDialog();
46 + }.bind(this)).fail(function () {
47 + #set ($errorMessage = $escapetool.javascript($services.localization.render('attachment.attachmentSelector.temporaryUpload.failure')))notification.replace(new XWiki.widgets.Notification("$errorMessage", 'error'));
48 + });
49 + }.bind(this));
50 + }
51 +
52 + function directUploadAttachment(uploadForm) {
53 + // FIXME This fails in HTML5, will deal with it later:
54 + // this.property.down('input').value = uploadForm.down('input[type="file"]').value;
55 + // uploadForm.xredirect.value = window.location.pathname;
56 + document.observe('xwiki:document:saved', function () {
57 + new XWiki.widgets.Notification("$services.localization.render('xe.attachmentSelector.upload.inProgress')",
58 + 'inprogress');
59 + uploadForm.submit();
60 + })
61 + document.fire('xwiki:actions:save', {'continue': true, form: this.property.up('form')});
62 + }
63 +
2 2   /** Handles the gallery buttons directly in the current page without reloading the window. */
3 3   XWiki.AttachmentPicker = Class.create({
4 4   /**
... ... @@ -60,21 +60,23 @@
60 60   new XWiki.widgets.Notification("$services.localization.render('xe.attachmentSelector.upload.error.badExtension')", 'error');
61 61   hasErrors = true;
62 62   }
125 + const beforeUploadEvent = Event.fire(document, 'xwiki:actions:beforeUpload', {
126 + file: fileInput.files[0]
127 + });
128 +
129 + if (beforeUploadEvent.defaultPrevented) {
130 + hasErrors = true;
131 + }
63 63   }.bind(this));
64 - // No form submission by AJAX right now, because file uploads can't be done this way without HTML5, this is future work
65 - // Save the document before submitting, since the current form data will be lost otherwise
66 66   if (!hasErrors) {
67 67   if (this.directSave) {
68 68   uploadForm.submit();
69 69   } else {
70 - // FIXME This fails in HTML5, will deal with it later:
71 - // this.property.down('input').value = uploadForm.down('input[type="file"]').value;
72 - // uploadForm.xredirect.value = window.location.pathname;
73 - document.observe('xwiki:document:saved', function() {
74 - new XWiki.widgets.Notification("$services.localization.render('xe.attachmentSelector.upload.inProgress')", 'inprogress');
75 - uploadForm.submit();
76 - })
77 - document.fire('xwiki:actions:save', {'continue': true, form: this.property.up('form')});
137 + if ("$!services.temporaryAttachments" != '') {
138 + uploadTemporaryAttachment.call(this);
139 + } else {
140 + directUploadAttachment.call(this, uploadForm);
141 + }
78 78   }
79 79   }
80 80   }.bindAsEventListener(this));
... ... @@ -173,10 +173,7 @@
173 173   this.dialog.closeDialog();
174 174   }.bindAsEventListener(this),
175 175   onFailure : function(response) {
176 - var failureReason = response.statusText;
177 - if (response.statusText == '' /* No response */ || response.status == 12031 /* In IE */) {
178 - failureReason = 'Server not responding';
179 - }
240 + var failureReason = response.statusText || 'Server not responding';
180 180   if (targetElement._x_notif) {
181 181   targetElement._x_notif.replace(new XWiki.widgets.Notification("$services.localization.render('core.widgets.confirmationBox.notification.failed')" + failureReason, "error"));
182 182   } else {
... ... @@ -183,9 +183,6 @@
183 183   new XWiki.widgets.Notification(this.interactionParameters.failureMessageText + failureReason, "error");
184 184   }
185 185   },
186 - on1223 : function(response) {
187 - response.request.options.onSuccess(response);
188 - },
189 189   on0 : function(response) {
190 190   response.request.options.onFailure(response);
191 191   },
XWiki.StyleSheetExtension[0]
Code
... ... @@ -140,9 +140,6 @@
140 140   ## Make this box twice as large as the others
141 141   width: ${uploadBoxSize}px;
142 142  }
143 -* html .gallery_upload {
144 - width: ${mathtool.add($uploadBoxSize, 2)}px;
145 -}
146 146  .gallery_upload, .gallery_upload:hover {
147 147   background-color: $theme.backgroundSecondaryColor;
148 148  }
XWiki.WikiMacroClass[0]
Macro code
... ... @@ -33,7 +33,7 @@
33 33  #set ($property = "$!{xcontext.macro.params.property}")
34 34  #set ($object = $numbertool.toNumber("$!{xcontext.macro.params.object}").intValue())
35 35  #if ("$!{object}" != $!{xcontext.macro.params.object})
36 - #set ($object = ${doc.getObject($classname).number})
36 + #set ($object = ${targetdoc.getObject($classname).number})
37 37   #if ("$!{object}" == '')
38 38   #set ($object = 0)
39 39   #end
... ... @@ -45,9 +45,18 @@
45 45   #set ($displayImage = false)
46 46  #end
47 47  #if ($displayImage)
48 - #set ($alt = "$!{xcontext.macro.params.alternateText}")
49 - #set ($width = "$!{xcontext.macro.params.width}")
50 - #set ($height = "$!{xcontext.macro.params.height}")
48 + #set ($alt = '')
49 + #set ($width = '')
50 + #set ($height = '')
51 + #if ($xcontext.macro.params.alternateText)
52 + #set ($alt = "$services.rendering.escape($!{xcontext.macro.params.alternateText}, 'xwiki/2.1')")
53 + #end
54 + #if ($xcontext.macro.params.width)
55 + #set ($width = "$services.rendering.escape($!{xcontext.macro.params.width}, 'xwiki/2.1')")
56 + #end
57 + #if ($xcontext.macro.params.height)
58 + #set ($height = "$services.rendering.escape($!{xcontext.macro.params.height}, 'xwiki/2.1')")
59 + #end
51 51   #set ($imageParams = '')
52 52   #if ("${width}" != '')
53 53   #set($imageParams = "$!{imageParams} width=${width}")
... ... @@ -85,7 +85,7 @@
85 85   #set ($savemode = 'form')
86 86  #end
87 87  
88 -#set ($propValue = "$!{doc.getObject($classname, $object).getProperty($property).value}")
97 +#set ($propValue = "$!{targetdoc.getObject($classname, $object).getProperty($property).value}")
89 89  ##
90 90  
91 91  #macro (attachmentPicker_displayAttachment $name $displayImage $withLink $forceElement)
... ... @@ -112,9 +112,9 @@
112 112   #set ($attachmentResource = '')
113 113   #end
114 114   #if ($displayImage)
115 - (% class="$!{cssClass}#if (!$attachment) hidden#end" %)(((#if ("$!{attachmentResource}" != '' || $forceElement)#if($withLink)[[#end[[image:${attachmentResource}$!{imageParams}]]#if($withLink)>>attach:${attachmentResource}||rel=lightbox]]#{end}#end)))##
124 + (% class="$!{cssClass}#if (!$attachment) hidden#end" %)(((#if ("$!{attachmentResource}" != '' || $forceElement)#if($withLink)[[#end[[image:$services.rendering.escape(${attachmentResource}, 'xwiki/2.1')$!{imageParams}]]#if($withLink)>>attach:$services.rendering.escape(${attachmentResource},'xwiki/2.1')||rel=lightbox]]#{end}#end)))##
116 116   #else
117 - (% class="$!{cssClass}" %)#if ("$!{attachmentResource}" != '' || $forceElement)#if ($withLink)[[attach:${attachmentResource}||rel=__blank]]#{else}(% class="displayed" %)#if($targetPermView)$!{attachmentName}#{else}Access Denied#{end}(% %)#{end}#end(%%)##
126 + (% class="$!{cssClass}" %)#if ("$!{attachmentResource}" != '' || $forceElement)#if ($withLink)[[attach:${attachmentResource}||rel=__blank]]#{else}(% class="displayed" %)#if($targetPermView)$!{services.rendering.escape($!{attachmentName}, 'xwiki/2.1')}#{else}Access Denied#{end}(% %)#{end}#end(%%)##
118 118   #end
119 119  #end
120 120  
... ... @@ -122,7 +122,7 @@
122 122  ## 1. Edit the current page
123 123  ## 2. View the target attachment page. (can be the same page)
124 124  #macro (attachmentPicker_displayButton)
125 - #if ($hasEdit && $targetPermView)
134 + #if ($targetPermView)
126 126   #set ($queryString = {
127 127   'docname': $doc.fullName,
128 128   'classname': $classname,
... ... @@ -137,8 +137,9 @@
137 137   #if ($hasTargetDoc)
138 138   #set ($queryString.targetdocname = $targetdoc.fullName)
139 139   #end
140 - (% class="buttonwrapper" %)[[$buttontext>>${xcontext.macro.doc.fullName}||queryString="$escapetool.url($queryString)"
141 - class="attachment-picker-start button" title="$buttontext"]](%%)##
149 + #set ($linkLabel = $services.rendering.escape($services.rendering.escape($buttontext, 'xwiki/2.1'), 'xwiki/2.1'))
150 + (% class="buttonwrapper" %)[[$linkLabel>>${xcontext.macro.doc.fullName}||queryString="$escapetool.url($queryString)"
151 + class="attachment-picker-start button" title="$services.rendering.escape($buttontext, 'xwiki/2.1')"]](%%)##
142 142   #end
143 143  #end
144 144  {{/velocity}}
... ... @@ -149,7 +149,7 @@
149 149  #elseif ($xcontext.action == 'inline' || $xcontext.action == 'edit')
150 150   (% class="attachment-picker" %)(((##
151 151   #attachmentPicker_displayAttachment($propValue $displayImage false true) #attachmentPicker_displayButton()##
152 - {{html}}<input type="hidden" name="${classname}_${object}_${property}" value="${propValue}"/>{{/html}}##
162 + {{html}}<input type="hidden" name="$escapetool.xml("${classname}_${object}_${property}")" value="$escapetool.xml("${propValue}")" class="property-reference"/>{{/html}}##
153 153   )))
154 154  #else
155 155   #attachmentPicker_displayAttachment($propValue $displayImage $link false)
Default category
... ... @@ -1,1 +1,0 @@
1 -Development
Default categories
... ... @@ -1,0 +1,1 @@
1 +Development

My Recent Modifications

Need help?

If you need help with XWiki you can contact: