sintonia/legacy/application/models/airtime/CcFiles.php

530 lines
17 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Skeleton subclass for representing a row from the 'cc_files' table.
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*/
class InvalidMetadataException extends Exception {}
class LibreTimeFileNotFoundException extends Exception {}
class OverDiskQuotaException extends Exception {}
2021-10-11 16:10:47 +02:00
class CcFiles extends BaseCcFiles
{
public const MUSIC_DIRS_STOR_PK = 1;
2021-10-11 16:10:47 +02:00
public const IMPORT_STATUS_SUCCESS = 0;
public const IMPORT_STATUS_PENDING = 1;
public const IMPORT_STATUS_FAILED = 2;
// fields that are not modifiable via our RESTful API
2021-10-11 16:10:47 +02:00
private static $blackList = [
'id',
'directory',
'filepath',
'file_exists',
'mtime',
'utime',
'lptime',
'silan_check',
'is_scheduled',
2021-10-11 16:10:47 +02:00
'is_playlist',
];
// fields we should never expose through our RESTful API
2021-10-11 16:10:47 +02:00
private static $privateFields = [
'file_exists',
'silan_check',
'is_scheduled',
2021-10-11 16:10:47 +02:00
'is_playlist',
];
/**
* Retrieve a sanitized version of the file metadata, suitable for public access.
2021-10-11 16:10:47 +02:00
*
* @param mixed $fileId
*/
public static function getSanitizedFileById($fileId)
{
$file = CcFilesQuery::create()->findPk($fileId);
if ($file) {
return CcFiles::sanitizeResponse($file);
}
2021-10-11 16:10:47 +02:00
throw new LibreTimeFileNotFoundException();
}
/** Used to create a CcFiles object from an array containing metadata and a file uploaded by POST.
* This is used by our Media REST API!
*
2021-10-11 16:10:47 +02:00
* @param $fileArray An array containing metadata for a CcFiles object
*
* @return object the sanitized response
2022-09-12 13:16:14 +02:00
*
* @throws Exception
*/
public static function createFromUpload($fileArray)
{
if (Application_Model_Systemstatus::isDiskOverQuota()) {
throw new OverDiskQuotaException();
}
/* If full_path is set, the post request came from ftp.
* Users are allowed to upload folders via ftp. If this is the case
* we need to include the folder name with the file name, otherwise
* files won't get removed from the organize folder.
*/
// Extract the original filename, which we set as the temporary title for the track
// until it's finished being processed by the analyzer.
$originalFilename = $fileArray['file']['name'];
$tempFilePath = $fileArray['file']['tmp_name'];
try {
return self::createAndImport($fileArray, $tempFilePath, $originalFilename);
2015-03-25 15:51:51 +01:00
} catch (Exception $e) {
if (file_exists($tempFilePath)) {
unlink($tempFilePath);
}
2021-10-11 16:10:47 +02:00
throw $e;
}
}
/** Import a music file to the library from a local file on disk (something pre-existing).
* This function allows you to copy a file rather than move it, which is useful for importing
* static music files (like sample tracks).
2021-10-11 16:10:47 +02:00
*
* @param string $filePath the full path to the audio file to import
* @param bool $copyFile True if you want to just copy the false, false if you want to move it (default false)
* @param mixed $fileArray
*
* @throws Exception
*/
2021-10-11 16:10:47 +02:00
public static function createFromLocalFile($fileArray, $filePath, $copyFile = false)
{
$info = pathinfo($filePath);
2021-10-11 16:10:47 +02:00
$fileName = basename($filePath) . '.' . $info['extension'];
self::createAndImport($fileArray, $filePath, $fileName, $copyFile);
}
/** Create a new CcFiles object/row and import a file for it.
* You shouldn't call this directly. Either use createFromUpload() or createFromLocalFile().
2021-10-11 16:10:47 +02:00
*
* @param array $fileArray Any metadata to pre-fill for the audio file
* @param string $filePath The full path to the audio file to import
* @param string $originalFilename
2021-10-11 16:10:47 +02:00
* @param bool $copyFile
*
2022-09-12 13:16:14 +02:00
* @return mixed
*
* @throws Exception
* @throws PropelException
*/
2021-10-11 16:10:47 +02:00
private static function createAndImport($fileArray, $filePath, $originalFilename, $copyFile = false)
{
$file = new CcFiles();
2021-10-11 16:10:47 +02:00
try {
// Only accept files with a file extension that we support.
// Let the analyzer do the heavy lifting in terms of mime verification and playability
$fileExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
if (!in_array(strtolower($fileExtension), array_values(FileDataHelper::getUploadAudioMimeTypeArray()))) {
2021-10-11 16:10:47 +02:00
throw new Exception('Bad file extension.');
}
$fileArray = self::removeBlacklistedFields($fileArray);
self::validateFileArray($fileArray);
// Early md5dum processing
$md5 = md5_file($filePath);
$importedStorageDir = Config::getStoragePath() . 'imported/' . self::getOwnerId() . '/';
2021-10-11 16:10:47 +02:00
$importedDbPath = 'imported/' . self::getOwnerId() . '/';
$artwork = FileDataHelper::saveArtworkData($filePath, $originalFilename, $importedStorageDir, $importedDbPath);
$trackTypeId = FileDataHelper::saveTrackType();
$file->fromArray($fileArray);
$file->setDbOwnerId(self::getOwnerId());
2021-10-11 16:10:47 +02:00
$now = new DateTime('now', new DateTimeZone('UTC'));
$file->setDbTrackTitle($originalFilename);
$file->setDbMd5($md5);
$file->setDbArtwork($artwork);
if ($trackTypeId) {
$file->setDbTrackTypeId($trackTypeId);
}
$file->setDbUtime($now);
$file->setDbHidden(true);
$file->save();
2021-10-11 16:10:47 +02:00
Application_Service_MediaService::importFileToLibrary(
$file->getPrimaryKey(),
2021-10-11 16:10:47 +02:00
self::getOwnerId(),
$file->getDbTrackTypeId(),
$originalFilename,
$filePath,
2021-10-11 16:10:47 +02:00
$copyFile
);
return CcFiles::sanitizeResponse($file);
} catch (Exception $e) {
$file->setDbImportStatus(self::IMPORT_STATUS_FAILED);
$file->setDbHidden(true);
$file->save();
2021-10-11 16:10:47 +02:00
throw $e;
}
}
/** Update a file with metadata specified in an array.
* @param $fileId string The ID of the file to update in the DB
* @param $fileArray array An associative array containing metadata. Replaces those fields if they exist.
2021-10-11 16:10:47 +02:00
*
2022-09-12 13:16:14 +02:00
* @return array a sanitized version of the file metadata array
*
* @throws Exception
Vendorize ZF1, fix PHPUnit and configure travis This a a rather large commit due to the nature of the stuff it is touching. To get PHPUnit up and running again I had to update some deps and I did so by vendorizing them. The vendorizing of zf1 makes sense since distros are already considering to drop it from their repos. * [x] install vendorized zf1 with composer * [x] load composer autoloader before zf1 * [x] Implement headAction for all Zend_Rest_Controller based controllers * [x] switch to yml dataset to get around string only limitations of xml sets (also removed warning in readme) * [x] use year 2044 as hardcoded date for tests since it is in the future and has the same days like previously used 2016 * [x] make tests easier to run when accessing phpunit directly * [x] clean up test helper to always use airtime.conf * [x] switch test dbname to libretime_test * [x] test db username password switched to libretime/libretime * [x] install phpunit with composer in a clear version (make tests easier to reproduce on other platforms) * [x] remove local libs from airtime repo (most of airtime_mvc/library was not needed of in vendor already) * [x] configure composer autoloading and use it (also removed requires that are not needed anymore) * [x] add LibreTime prefix for FileNotFoundException (phing had a similar class and these are all pre-namespace style) * [x] add .travis.yml file * [x] make etc and logdir configurable with LIBRETIME_CONF_DIR and LIBRETIME_LOG_DIR env (so travis can change it) * [x] slight cleanup in config for travis not to fail * [x] add cloud_storage.conf for during test runs * [x] rewrite mvc testing docs and move them to docs/ folder * [x] don't use `static::class` in a class that does not have a parent class, use `__CLASS__` instead. * [x] don't use `<ClassName>::class`, since we already know what class we want `"<ClassName>"` ist just fine. * [x] fix "can't use method in write context" errors on 5.4 (also helps the optimizer) * [x] add build status badge on main README.md Fixes https://github.com/LibreTime/libretime/issues/4 The PHP parts of https://github.com/LibreTime/libretime/pull/10 get obsoleted by this change and it will need rebasing. This also contains https://github.com/LibreTime/libretime/pull/8, the late static binding compat code was broken for no reason and until CentOS drops php 5.4 there is no reason I'm aware of not to support it. I inlined #8 since the test would be failing on php 5.4 without the change. If you want to run tests you need to run `composer install` in the root directory and then `cd airtime_mvc/tests && ../../vendor/bin/phpunit`. For the tests to run the user `libretime` needs to be allowed to create the `libretime_test` database. See `docs/TESTING.md` for more info on getting set up.
2017-02-20 21:47:53 +01:00
* @throws LibreTimeFileNotFoundException
* @throws PropelException
*/
public static function updateFromArray($fileId, $fileArray)
{
$file = CcFilesQuery::create()->findPk($fileId);
$fileArray = self::removeBlacklistedFields($fileArray);
$fileArray = self::stripTimeStampFromYearTag($fileArray);
try {
self::validateFileArray($fileArray);
if ($file) {
$file->fromArray($fileArray, BasePeer::TYPE_FIELDNAME);
// Our RESTful API takes "full_path" as a field, which we then split and translate to match
// our internal schema. Internally, file path is stored relative to a directory, with the directory
// as a foreign key to cc_music_dirs.
2021-10-11 16:10:47 +02:00
if (isset($fileArray['full_path'])) {
$fileSizeBytes = filesize($fileArray['full_path']);
if (!isset($fileSizeBytes) || $fileSizeBytes === false) {
2021-10-11 16:10:47 +02:00
throw new LibreTimeFileNotFoundException("Invalid filesize for {$fileId}");
}
Application_Model_Preference::updateDiskUsage($fileSizeBytes);
2021-10-11 16:10:47 +02:00
$fullPath = $fileArray['full_path'];
$storDir = Config::getStoragePath();
$pos = strpos($fullPath, $storDir);
2021-10-11 16:10:47 +02:00
if ($pos !== false) {
assert($pos == 0); // Path must start with the stor directory path
$filePathRelativeToStor = substr($fullPath, strlen($storDir));
$file->setDbFilepath($filePathRelativeToStor);
}
}
} else {
Vendorize ZF1, fix PHPUnit and configure travis This a a rather large commit due to the nature of the stuff it is touching. To get PHPUnit up and running again I had to update some deps and I did so by vendorizing them. The vendorizing of zf1 makes sense since distros are already considering to drop it from their repos. * [x] install vendorized zf1 with composer * [x] load composer autoloader before zf1 * [x] Implement headAction for all Zend_Rest_Controller based controllers * [x] switch to yml dataset to get around string only limitations of xml sets (also removed warning in readme) * [x] use year 2044 as hardcoded date for tests since it is in the future and has the same days like previously used 2016 * [x] make tests easier to run when accessing phpunit directly * [x] clean up test helper to always use airtime.conf * [x] switch test dbname to libretime_test * [x] test db username password switched to libretime/libretime * [x] install phpunit with composer in a clear version (make tests easier to reproduce on other platforms) * [x] remove local libs from airtime repo (most of airtime_mvc/library was not needed of in vendor already) * [x] configure composer autoloading and use it (also removed requires that are not needed anymore) * [x] add LibreTime prefix for FileNotFoundException (phing had a similar class and these are all pre-namespace style) * [x] add .travis.yml file * [x] make etc and logdir configurable with LIBRETIME_CONF_DIR and LIBRETIME_LOG_DIR env (so travis can change it) * [x] slight cleanup in config for travis not to fail * [x] add cloud_storage.conf for during test runs * [x] rewrite mvc testing docs and move them to docs/ folder * [x] don't use `static::class` in a class that does not have a parent class, use `__CLASS__` instead. * [x] don't use `<ClassName>::class`, since we already know what class we want `"<ClassName>"` ist just fine. * [x] fix "can't use method in write context" errors on 5.4 (also helps the optimizer) * [x] add build status badge on main README.md Fixes https://github.com/LibreTime/libretime/issues/4 The PHP parts of https://github.com/LibreTime/libretime/pull/10 get obsoleted by this change and it will need rebasing. This also contains https://github.com/LibreTime/libretime/pull/8, the late static binding compat code was broken for no reason and until CentOS drops php 5.4 there is no reason I'm aware of not to support it. I inlined #8 since the test would be failing on php 5.4 without the change. If you want to run tests you need to run `composer install` in the root directory and then `cd airtime_mvc/tests && ../../vendor/bin/phpunit`. For the tests to run the user `libretime` needs to be allowed to create the `libretime_test` database. See `docs/TESTING.md` for more info on getting set up.
2017-02-20 21:47:53 +01:00
throw new LibreTimeFileNotFoundException();
}
2021-10-11 16:10:47 +02:00
$now = new DateTime('now', new DateTimeZone('UTC'));
$file->setDbMtime($now);
$file->save();
2021-10-11 16:10:47 +02:00
} catch (LibreTimeFileNotFoundException $e) {
$file->setDbImportStatus(self::IMPORT_STATUS_FAILED);
$file->setDbHidden(true);
$file->save();
2021-10-11 16:10:47 +02:00
throw $e;
}
return CcFiles::sanitizeResponse($file);
}
/** Delete a file from the database and disk.
* @param $id The file ID
2021-10-11 16:10:47 +02:00
*
* @throws DeleteScheduledFileException
* @throws Exception
* @throws FileNoPermissionException
Vendorize ZF1, fix PHPUnit and configure travis This a a rather large commit due to the nature of the stuff it is touching. To get PHPUnit up and running again I had to update some deps and I did so by vendorizing them. The vendorizing of zf1 makes sense since distros are already considering to drop it from their repos. * [x] install vendorized zf1 with composer * [x] load composer autoloader before zf1 * [x] Implement headAction for all Zend_Rest_Controller based controllers * [x] switch to yml dataset to get around string only limitations of xml sets (also removed warning in readme) * [x] use year 2044 as hardcoded date for tests since it is in the future and has the same days like previously used 2016 * [x] make tests easier to run when accessing phpunit directly * [x] clean up test helper to always use airtime.conf * [x] switch test dbname to libretime_test * [x] test db username password switched to libretime/libretime * [x] install phpunit with composer in a clear version (make tests easier to reproduce on other platforms) * [x] remove local libs from airtime repo (most of airtime_mvc/library was not needed of in vendor already) * [x] configure composer autoloading and use it (also removed requires that are not needed anymore) * [x] add LibreTime prefix for FileNotFoundException (phing had a similar class and these are all pre-namespace style) * [x] add .travis.yml file * [x] make etc and logdir configurable with LIBRETIME_CONF_DIR and LIBRETIME_LOG_DIR env (so travis can change it) * [x] slight cleanup in config for travis not to fail * [x] add cloud_storage.conf for during test runs * [x] rewrite mvc testing docs and move them to docs/ folder * [x] don't use `static::class` in a class that does not have a parent class, use `__CLASS__` instead. * [x] don't use `<ClassName>::class`, since we already know what class we want `"<ClassName>"` ist just fine. * [x] fix "can't use method in write context" errors on 5.4 (also helps the optimizer) * [x] add build status badge on main README.md Fixes https://github.com/LibreTime/libretime/issues/4 The PHP parts of https://github.com/LibreTime/libretime/pull/10 get obsoleted by this change and it will need rebasing. This also contains https://github.com/LibreTime/libretime/pull/8, the late static binding compat code was broken for no reason and until CentOS drops php 5.4 there is no reason I'm aware of not to support it. I inlined #8 since the test would be failing on php 5.4 without the change. If you want to run tests you need to run `composer install` in the root directory and then `cd airtime_mvc/tests && ../../vendor/bin/phpunit`. For the tests to run the user `libretime` needs to be allowed to create the `libretime_test` database. See `docs/TESTING.md` for more info on getting set up.
2017-02-20 21:47:53 +01:00
* @throws LibreTimeFileNotFoundException
* @throws PropelException
*/
public static function deleteById($id)
{
$file = CcFilesQuery::create()->findPk($id);
if ($file) {
$con = Propel::getConnection();
2015-03-03 18:52:41 +01:00
$storedFile = Application_Model_StoredFile::RecallById($id, $con);
$storedFile->delete();
} else {
Vendorize ZF1, fix PHPUnit and configure travis This a a rather large commit due to the nature of the stuff it is touching. To get PHPUnit up and running again I had to update some deps and I did so by vendorizing them. The vendorizing of zf1 makes sense since distros are already considering to drop it from their repos. * [x] install vendorized zf1 with composer * [x] load composer autoloader before zf1 * [x] Implement headAction for all Zend_Rest_Controller based controllers * [x] switch to yml dataset to get around string only limitations of xml sets (also removed warning in readme) * [x] use year 2044 as hardcoded date for tests since it is in the future and has the same days like previously used 2016 * [x] make tests easier to run when accessing phpunit directly * [x] clean up test helper to always use airtime.conf * [x] switch test dbname to libretime_test * [x] test db username password switched to libretime/libretime * [x] install phpunit with composer in a clear version (make tests easier to reproduce on other platforms) * [x] remove local libs from airtime repo (most of airtime_mvc/library was not needed of in vendor already) * [x] configure composer autoloading and use it (also removed requires that are not needed anymore) * [x] add LibreTime prefix for FileNotFoundException (phing had a similar class and these are all pre-namespace style) * [x] add .travis.yml file * [x] make etc and logdir configurable with LIBRETIME_CONF_DIR and LIBRETIME_LOG_DIR env (so travis can change it) * [x] slight cleanup in config for travis not to fail * [x] add cloud_storage.conf for during test runs * [x] rewrite mvc testing docs and move them to docs/ folder * [x] don't use `static::class` in a class that does not have a parent class, use `__CLASS__` instead. * [x] don't use `<ClassName>::class`, since we already know what class we want `"<ClassName>"` ist just fine. * [x] fix "can't use method in write context" errors on 5.4 (also helps the optimizer) * [x] add build status badge on main README.md Fixes https://github.com/LibreTime/libretime/issues/4 The PHP parts of https://github.com/LibreTime/libretime/pull/10 get obsoleted by this change and it will need rebasing. This also contains https://github.com/LibreTime/libretime/pull/8, the late static binding compat code was broken for no reason and until CentOS drops php 5.4 there is no reason I'm aware of not to support it. I inlined #8 since the test would be failing on php 5.4 without the change. If you want to run tests you need to run `composer install` in the root directory and then `cd airtime_mvc/tests && ../../vendor/bin/phpunit`. For the tests to run the user `libretime` needs to be allowed to create the `libretime_test` database. See `docs/TESTING.md` for more info on getting set up.
2017-02-20 21:47:53 +01:00
throw new LibreTimeFileNotFoundException();
}
}
private static function validateFileArray(&$fileArray)
{
// Sanitize any wildly incorrect metadata before it goes to be validated
FileDataHelper::sanitizeData($fileArray);
// EditAudioMD form is used here for validation
$fileForm = new Application_Form_EditAudioMD();
$fileForm->startForm(0); // The file ID doesn't matter here
$fileForm->populate($fileArray);
/*
* Here we are truncating metadata of any characters greater than the
* max string length set in the database. In the rare case a track's
* genre is more than 64 chars, for example, we don't want to reject
* tracks for that reason
*/
2021-10-11 16:10:47 +02:00
foreach ($fileArray as $tag => &$value) {
if ($fileForm->getElement($tag)) {
$stringLengthValidator = $fileForm->getElement($tag)->getValidator('StringLength');
// $stringLengthValidator will be false if the StringLength validator doesn't exist on the current element
// in which case we don't have to truncate the extra characters
if ($stringLengthValidator) {
$value = substr($value, 0, $stringLengthValidator->getMax());
}
$value = self::stripInvalidUtf8Characters($value);
}
}
if (!$fileForm->isValidPartial($fileArray)) {
$errors = $fileForm->getErrors();
$messages = $fileForm->getMessages();
Logging::error($messages);
2021-10-11 16:10:47 +02:00
throw new Exception("Data validation failed: {$errors} - {$messages}");
}
return true;
}
public function getCueLength()
2021-10-11 16:10:47 +02:00
{
$cuein = $this->getDbCuein();
$cueout = $this->getDbCueout();
2021-10-11 16:10:47 +02:00
$cueinSec = Application_Common_DateHelper::calculateLengthInSeconds($cuein);
$cueoutSec = Application_Common_DateHelper::calculateLengthInSeconds($cueout);
$lengthSec = bcsub($cueoutSec, $cueinSec, 6);
2021-10-11 16:10:47 +02:00
return Application_Common_DateHelper::secondsToPlaylistTime($lengthSec);
}
public function setDbTrackNumber($v)
{
$max = 2 ** 31 - 1;
$v = ($v > $max) ? $max : $v;
return parent::setDbTrackNumber($v);
}
// returns true if the file exists and is not hidden
2021-10-11 16:10:47 +02:00
public function visible()
{
return $this->getDbFileExists() && !$this->getDbHidden();
}
public function reassignTo($user)
2012-09-19 16:23:54 +02:00
{
2021-10-11 16:10:47 +02:00
$this->setDbOwnerId($user->getDbId());
$this->save();
}
/**
2021-10-11 16:10:47 +02:00
* Strips out the private fields we do not want to send back in API responses.
*
* @param CcFiles $file a CcFiles object
*
* @return array
*/
// TODO: rename this function?
2021-10-11 16:10:47 +02:00
public static function sanitizeResponse($file)
{
$response = $file->toArray(BasePeer::TYPE_FIELDNAME);
foreach (self::$privateFields as $key) {
unset($response[$key]);
}
return $response;
}
/**
* Returns the file size in bytes.
*/
public function getFileSize()
{
return $this->getDbFilesize();
}
public function getFilename()
{
$info = pathinfo($this->getAbsoluteFilePath());
2015-07-15 19:12:56 +02:00
// filename doesn't contain the extension because PHP is awful
2015-07-15 19:12:56 +02:00
$mime = $this->getDbMime();
$extension = FileDataHelper::getFileExtensionFromMime($mime);
return $info['filename'] . $extension;
}
/**
* Returns the file's absolute file path stored on disk.
*/
public function getURLsForTrackPreviewOrDownload()
{
2021-10-11 16:10:47 +02:00
return [$this->getAbsoluteFilePath()];
}
/**
* Returns the file's absolute file path stored on disk.
*/
public function getAbsoluteFilePath()
{
$directory = Config::getStoragePath();
2021-10-11 16:10:47 +02:00
$filepath = $this->getDbFilepath();
return Application_Common_OsPath::join($directory, $filepath);
}
/**
* Returns the artwork's absolute file path stored on disk.
*/
public function getAbsoluteArtworkPath()
{
$directory = Config::getStoragePath();
2021-10-11 16:10:47 +02:00
$filepath = $this->getDbArtwork();
return Application_Common_OsPath::join($directory, $filepath);
}
/**
* Strips out fields from incoming request data that should never be modified
2021-10-11 16:10:47 +02:00
* from outside of Airtime.
*
* @param array $data
*/
private static function removeBlacklistedFields($data)
{
foreach (self::$blackList as $key) {
unset($data[$key]);
}
return $data;
}
private static function getOwnerId()
{
try {
if (Zend_Auth::getInstance()->hasIdentity()) {
$service_user = new Application_Service_UserService();
2021-10-11 16:10:47 +02:00
return $service_user->getCurrentUser()->getDbId();
}
2021-10-11 16:10:47 +02:00
$defaultOwner = CcSubjsQuery::create()
->filterByDbType('A')
->orderByDbId()
->findOne();
2021-10-11 16:10:47 +02:00
if (!$defaultOwner) {
// what to do if there is no admin user?
// should we handle this case?
return null;
}
return $defaultOwner->getDbId();
} catch (Exception $e) {
Logging::info($e->getMessage());
}
}
2021-10-11 16:10:47 +02:00
/*
* It's possible that the year tag will be a timestamp but Airtime doesn't support this.
* The year field in cc_files can only be 16 chars max.
*
* This functions strips the year field of it's timestamp, if one, and leaves just the year
*/
private static function stripTimeStampFromYearTag($metadata)
{
2021-10-11 16:10:47 +02:00
if (isset($metadata['year'])) {
2021-10-12 11:09:46 +02:00
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})(?:\s+(\d{2}):(\d{2}):(\d{2}))?$/', $metadata['year'])) {
2021-10-11 16:10:47 +02:00
$metadata['year'] = substr($metadata['year'], 0, 4);
}
}
2021-10-11 16:10:47 +02:00
return $metadata;
}
private static function stripInvalidUtf8Characters($string)
{
// Remove invalid UTF-8 characters
// reject overly long 2 byte sequences, as well as characters above U+10000 and replace with ?
2021-10-11 16:10:47 +02:00
$string = preg_replace(
'/[\x00-\x08\x10\x0B\x0C\x0E-\x19\x7F]' .
2022-06-19 15:58:45 +02:00
'|[\x00-\x7F][\x80-\xBF]+' .
'|([\xC0\xC1]|[\xF0-\xFF])[\x80-\xBF]*' .
'|[\xC2-\xDF]((?![\x80-\xBF])|[\x80-\xBF]{2,})' .
'|[\xE0-\xEF](([\x80-\xBF](?![\x80-\xBF]))|(?![\x80-\xBF]{2})|[\x80-\xBF]{3,})/S',
2021-10-11 16:10:47 +02:00
'?',
$string
);
// reject overly long 3 byte sequences and UTF-16 surrogates and replace with ?
2021-10-11 16:10:47 +02:00
$string = preg_replace('/\xE0[\x80-\x9F][\x80-\xBF]' .
'|\xED[\xA0-\xBF][\x80-\xBF]/S', '?', $string);
// Do a final encoding conversion to
2021-10-11 16:10:47 +02:00
return mb_convert_encoding($string, 'UTF-8', 'UTF-8');
}
private function removeEmptySubFolders($path)
{
2021-10-11 16:10:47 +02:00
exec("find {$path} -empty -type d -delete");
}
/**
* Checks if the file is a regular file that can be previewed and downloaded.
*/
2014-11-12 20:42:34 +01:00
public function isValidPhysicalFile()
{
return is_file($this->getAbsoluteFilePath());
}
/**
* Deletes the file from the stor directory on disk.
*/
public function deletePhysicalFile()
{
$filepath = $this->getAbsoluteFilePath();
$artworkpath = $this->getAbsoluteArtworkPath();
if (file_exists($filepath)) {
unlink($filepath);
// also delete related images (dataURI and jpeg files)
2021-10-11 16:10:47 +02:00
foreach (glob("{$artworkpath}*", GLOB_NOSORT) as $filename) {
unlink($filename);
}
unlink($artworkpath);
} else {
2021-10-11 16:10:47 +02:00
throw new Exception('Could not locate file ' . $filepath);
}
}
2014-11-12 20:42:34 +01:00
/**
* This function refers to the file's Amazon S3 resource id.
* Returns null because cc_files are stored on local disk.
*/
public function getResourceId()
{
return null;
}
public function getCcFileId()
{
return $this->id;
}
} // CcFiles