Skip to content

Commit

Permalink
Garbage collector now removes all empty temporary upload folders.
Browse files Browse the repository at this point in the history
Resolve #10746
  • Loading branch information
andris-sevcenko committed Mar 29, 2022
1 parent 0e38663 commit 8aa9197
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -7,6 +7,7 @@
- Added `craft\base\FsInterface::write()`.
- Added `craft\services\Assets::getImagePreviewUrl()`.
- Added `craft\web\CpScreenResponseBehavior::selectedSubnavItem()`. ([#10784](https://github.com/craftcms/cms/discussions/10784))
- Garbage collector now removes all empty temporary upload folders. ([#10746](https://github.com/craftcms/cms/issues/10746))

### Changed
- Sites’ Language settings now use Selectize inputs. ([#10810](https://github.com/craftcms/cms/discussions/10810))
Expand Down
31 changes: 31 additions & 0 deletions src/services/Gc.php
Expand Up @@ -21,6 +21,7 @@
use craft\elements\MatrixBlock;
use craft\elements\Tag;
use craft\elements\User;
use craft\fs\Temp;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\records\Volume;
Expand Down Expand Up @@ -138,6 +139,8 @@ public function run(bool $force = false): void
]);

$this->hardDeleteVolumes();

$this->removeEmptyTempFolders();
}

/**
Expand Down Expand Up @@ -293,6 +296,34 @@ public function deletePartialElements(string $elementType, string $table, string
$this->db->createCommand($sql, ['type' => $elementType])->execute();
}

/**
* Find all temp upload folders with no assets in them and remove them.
*
* @throws \craft\errors\FsException
* @throws \yii\base\Exception
* @throws \yii\base\InvalidConfigException
*/
public function removeEmptyTempFolders(): void
{
$emptyFolders = (new Query())
->from(['folders' => Table::VOLUMEFOLDERS])
->select(['folders.id', 'folders.path'])
->leftJoin(['assets' => Table::ASSETS], '[[assets.folderId]] = [[folders.id]]')
->where(['folders.volumeId' => null, 'assets.id' => null])
->andWhere(['not', ['folders.parentId' => null]])
->pairs();

$fs = Craft::createObject(Temp::class);

foreach ($emptyFolders as $emptyFolderPath) {
if ($fs->directoryExists($emptyFolderPath)) {
$fs->deleteDirectory($emptyFolderPath);
}
}

VolumeFolder::deleteAll(['id' => array_keys($emptyFolders)]);
}

/**
* Returns whether we should be hard-deleting soft-deleted objects.
*
Expand Down

0 comments on commit 8aa9197

Please sign in to comment.