Skip to content

Instantly share code, notes, and snippets.

@datyger
Last active February 20, 2020 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save datyger/18cf79da6823229ec98b814827f115d5 to your computer and use it in GitHub Desktop.
Save datyger/18cf79da6823229ec98b814827f115d5 to your computer and use it in GitHub Desktop.
Liferay 6.2 script to remove all old document versions except the latest version. This version can be tasked per-site and /or specific site's folder.
// Find and delete old versions of docs per site...
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import java.util.List;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.repository.model.FileVersion;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLFileVersionLocalServiceUtil;
import com.liferay.portlet.documentlibrary.model.DLFileVersion;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
import java.text.SimpleDateFormat;
import com.liferay.portal.kernel.util.FastDateFormatFactoryUtil;
previewMode = true;
if(previewMode) {
out.println(
"""<div class="portlet-msg-alert">Preview mode is on: switch off the flag and execute this script
again to make changes to the database</div>""")
}
def SCRIPT_ID = "Remove-File-Versions-Site"
outputFile = new File(
"""${System.getProperty("liferay.home")}/scripting/out-${SCRIPT_ID}.txt""")
outputFile.getParentFile().mkdirs()
def trace(message) {
out.println(message)
outputFile << "${message}\n"
}
// Param1: Group ID
// Param2: Folder ID - Use "0" to clean the entire site.
listFiles(219471, 0);
def listFiles(groupId, folderId) {
allfiles = DLAppServiceUtil.getFileEntries(groupId,folderId);
for (FileEntry file:allfiles) {
List results = file.getFileVersions(-1);
//lrlatestversion = file.getVersion();
thisFEId = file.getFileEntryId();
thisVersionColl = DLFileVersionLocalServiceUtil.getLatestFileVersion(thisFEId,true);
trueLatestVersion = thisVersionColl.getVersion();
for(FileVersion fv : results){
try {
if(fv.getVersion() != trueLatestVersion){
trace('This version: ' + fv.getVersion() + ' with Title=' + fv.getTitle() + ' is older than ' + trueLatestVersion + ' so deleting ' + fv.getVersion() );
if(!previewMode) {
DLAppServiceUtil.deleteFileVersion(file.getFileEntryId(), fv.getVersion() );
}
}
} catch (Exception e1) {
println(e1)
e1.printStackTrace(out)
}
}
}
allfolders = DLAppServiceUtil.getFolders(groupId,folderId);
for (Folder folder:allfolders) {
try {
trace("Checking Folder: " + folder.getName());
listFiles(groupId,folder.getFolderId());
} catch (Exception e2) {
println(e2)
e2.printStackTrace(out)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment