Search code examples
repositorytypo3extbasefal

How to get all FAL File Objects which are referenced?


I'm trying to make a extbase extension for TYPO3 to get alle file objects with mimetype image/... which referenced by any content, plugin or fluid in typo3.

But i don't know which is the best way to get these data. How should i create a model in my extension and how should i create the correct repository?

If i create a custom query i'm not sure how to return a complete FAL Object which contains any data (like metadata) etc.

hope someone could help me to find the right way, and maybe has a example or something.

thanks a lot


Solution

  • You could do it like this, details are at the bottom:

    1. Get all file references.
    2. Go through them, retrieve the referenced file for each of them and retain only the ones where the field mime_type starts with image/.

    There are two things you probably need to watch out for:

    1. The field mime_type needs to be up to date. Check the FAL scheduler indexing task for that.
    2. Performance. Depending on the number of files you have, it could be much faster to do this with a custom SQL statement which makes use of a JOIN. But you should only do that if performance is a problem.

    How to get all file references:

    First, build your own empty file reference class:

    namespace Vendor/Extkey/Domain/Model;
    
    class FileReference extends \TYPO3\CMS\Extbase\Domain\Model\FileReference {}
    

    Make sure to configure it in your TypoScript to be serialized to the table sys_file_reference:

    config.tx_extbase.persistence {
        classes {
            Vendor\Extkey\Domain\Model\FileReference {
                mapping {
                    tableName = sys_file_reference
                }
            }
        }
    }
    

    Add a repository for the references:

    namespace Vendor/Extkey/Domain/Repository;
    
    class FileReferenceRepository extends \TYPO3\CMS\Extbase\Persistence\Repository {
        public function initializeObject() {
            /** @var \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface */
            $defaultQuerySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\QuerySettingsInterface');
    
            $defaultQuerySettings->setRespectStoragePage(FALSE);
            $this->setDefaultQuerySettings($defaultQuerySettings);
        }
    }
    

    The reference class can be empty, but the repository needs it to be there in order to work correctly. Make sure you add the default query settings to ignore the page id, so you get all non-hidden and non-deleted file references by calling $fileReferenceRepository->findAll().

    How to check the MIME-type of each referenced file:

    You can get the MIME-type of each reference by calling

    $fileReference->getOriginalResource()->getMimeType()
    

    This should automatically fetch the original file from storage and read its MIME-type.