Remove Broken Atttachments From Page

Last modified by Clemens Robbenhaar on 2021/03/18 11:28

cogChecks all attachments on a given page and removes the broken ones.
Type
Category
Developed by

Clemens Robbenhaar

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

Paste the following code in a new wiki page, update the targetDoc to point the page. Change the def doIt = true to def doIt = false for a dry run.

Tested with XWiki 11.10.2. Modifies your database without asking for permission. Might bite your foot or run away with your dog.

{{groovy}}
import com.xpn.xwiki.*;
import com.xpn.xwiki.api.*;
import com.xpn.xwiki.doc.*;

// here type in path to the document in question
def targetDoc = xwiki.getDocument("Sandbox.WebHome")

def needsSave = false

targetDoc.getAttachmentList().each( { att ->
 def doIt = true
 def success = true
 try {
    att.getAttachment().loadAttachmentContent(xcontext.getContext())
 } catch (XWikiException e) {
    success = false
 }

 def attName = att.getFilename()
 if (success) {
    println "* attachment ${attName} ok"
 } else {
    println "* attachment ${attName} (% style='color:red' %)missing(%%)"
   if (doIt) {
      targetDoc.document.removeAttachment(att.getAttachment(), false)
      needsSave = true
   }
 }
})

println ""
if (needsSave) {
  targetDoc.save("removed broken attachments", true)
  println "removed broken attachments"
} else {
  println "all attachments ok"
}

{{/groovy}}

The code needs programming rights to run properly.

This snippet reuses the Delete Attachment and maybe can be combined with the Attachments Checker to wire out all broken attachments.

     

Get Connected