Clean up orphaned attachments when upgrading to 5.5
authorTim Düsterhus <duesterhus@woltlab.com>
Thu, 13 Jan 2022 10:19:09 +0000 (11:19 +0100)
committerTim Düsterhus <duesterhus@woltlab.com>
Thu, 13 Jan 2022 11:51:38 +0000 (12:51 +0100)
Resolves #158

files/acp/update_com.woltlab.wcf.conversation_5.5_cleanup_orphaned_attachments.php [new file with mode: 0644]
package.xml

diff --git a/files/acp/update_com.woltlab.wcf.conversation_5.5_cleanup_orphaned_attachments.php b/files/acp/update_com.woltlab.wcf.conversation_5.5_cleanup_orphaned_attachments.php
new file mode 100644 (file)
index 0000000..3075b33
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * Deletes orphaned attachments.
+ *
+ * @author  Tim Duesterhus
+ * @copyright   2001-2022 WoltLab GmbH
+ * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
+ * @package WoltLabSuite\Core
+ */
+
+use wcf\data\attachment\AttachmentAction;
+use wcf\data\object\type\ObjectTypeCache;
+use wcf\system\package\SplitNodeException;
+use wcf\system\WCF;
+
+$objectType = ObjectTypeCache::getInstance()
+    ->getObjectTypeByName('com.woltlab.wcf.attachment.objectType', 'com.woltlab.wcf.conversation.message');
+
+$sql = "SELECT  attachmentID
+        FROM    wcf1_attachment
+        WHERE   objectTypeID = ?
+            AND objectID NOT IN (
+                SELECT  messageID
+                FROM    wcf1_conversation_message
+            )";
+$statement = WCF::getDB()->prepare($sql, 100);
+$attachmentIDs = $statement->fetchAll(\PDO::FETCH_COLUMN);
+
+if (empty($attachmentIDs)) {
+    return;
+}
+
+(new AttachmentAction([$attachmentIDs], 'delete'))->executeAction();
+
+// If we reached this location we processed at least one attachment.
+// If this was the final attachment the next iteration will abort this
+// script early, thus not splitting the node.
+throw new SplitNodeException();
index 428e1821704f527487fe6fa26bcd0f2a8924c217..6f3ee5c303d75742f2ada6c9804df29b93da0b9b 100644 (file)
@@ -53,5 +53,7 @@
 
                <instruction type="language" />
                <instruction type="objectType" />
+
+               <instruction type="script">acp/update_com.woltlab.wcf.conversation_5.5_cleanup_orphaned_attachments.php</instruction>
        </instructions>
 </package>