@@ -693,27 +693,34 @@ public function deleteAttachments(File $source): void {
693693 * @param File $source
694694 * @param File $target
695695 *
696+ * @return array file id translation map
696697 * @throws InvalidPathException
697698 * @throws NoUserException
698699 * @throws NotFoundException
699700 * @throws NotPermittedException
700701 * @throws LockedException
701702 */
702- public function copyAttachments (File $ source , File $ target ): void {
703+ public function copyAttachments (File $ source , File $ target ): array {
703704 try {
704705 $ sourceAttachmentDir = $ this ->getAttachmentDirectoryForFile ($ source );
705706 } catch (NotFoundException $ e ) {
706707 // silently return if no attachment dir was found for source file
707- return ;
708+ return [] ;
708709 }
709710 // create a new attachment dir next to the new file
710711 $ targetAttachmentDir = $ this ->getAttachmentDirectoryForFile ($ target , true );
711712 // copy the attachment files
713+ $ fileIdMapping = [];
712714 foreach ($ sourceAttachmentDir ->getDirectoryListing () as $ sourceAttachment ) {
713715 if ($ sourceAttachment instanceof File) {
714- $ targetAttachmentDir ->newFile ($ sourceAttachment ->getName (), $ sourceAttachment ->getContent ());
716+ $ newFile = $ targetAttachmentDir ->newFile ($ sourceAttachment ->getName (), $ sourceAttachment ->getContent ());
717+ $ fileIdMapping [] = [
718+ $ sourceAttachment ->getId (),
719+ $ newFile ->getId ()
720+ ];
715721 }
716722 }
723+ return $ fileIdMapping ;
717724 }
718725
719726 public static function replaceAttachmentFolderId (File $ source , File $ target ): void {
@@ -735,4 +742,18 @@ public static function replaceAttachmentFolderId(File $source, File $target): vo
735742 $ target ->putContent ($ content );
736743 }
737744 }
745+
746+ public static function replaceAttachmentFileIds (File $ target , array $ fileIdMapping ): void {
747+ $ targetId = $ target ->getId ();
748+ $ patterns = [];
749+ $ replacements = [];
750+ foreach ($ fileIdMapping as $ mapping ) {
751+ $ patterns [] = '/\[\b((\S+\/f\/) ' . $ mapping [0 ] . ')\b\]\(\b\1\b/ ' ;
752+ $ replacements [] = '[${2} ' . $ mapping [1 ] . '](${2} ' . $ mapping [1 ];
753+ }
754+ $ content = preg_replace ($ patterns , $ replacements , $ target ->getContent ());
755+ if ($ content !== null ) {
756+ $ target ->putContent ($ content );
757+ }
758+ }
738759}
0 commit comments