Skip to content

Instantly share code, notes, and snippets.

@hissy
Last active April 11, 2017 06:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hissy/502b1579c9469b5a95aaeab550411cd6 to your computer and use it in GitHub Desktop.
Save hissy/502b1579c9469b5a95aaeab550411cd6 to your computer and use it in GitHub Desktop.
[concrete5][Legacy] Find duplicate file name and change it
<?php
class ScanDuplicateFileName extends QueueableJob
{
public $jNotUninstallable=0;
public $jSupportsQueue = true;
public function getJobName()
{
return t('Scan Duplicate File Name');
}
public function getJobDescription()
{
return t('Find duplicate file name and change the name');
}
public function start(Zend_Queue $q)
{
Loader::model('file_list');
$list = new FileList();
$files = $list->get();
/** @var File $file */
foreach ($files as $file) {
$q->send($file->getFileID());
}
}
public function finish(Zend_Queue $q)
{
return t('Done.');
}
public function processQueueItem(Zend_Queue_Message $msg)
{
try {
/** @var File|FileVersion $f */
$f = File::getByID($msg->body);
$filename = $f->getFileName();
$files = $this->getDuplicatedFiles($f, $filename);
foreach ($files as $file) {
$this->changeFileName($file);
}
} catch (Exception $e) {
Log::addEntry($e->getMessage());
}
}
public function getDuplicatedFiles(File $f, $filename)
{
$list = new FileList();
$list->filter('fv.fvFilename', $filename);
$list->filter('f.fID', $f->getFileID(), '<>');
return $list->get();
}
public function changeFileName(File $f, $count = 1)
{
$fileName = $f->getFileName();
$fileExt = $f->getExtension();
$newFileName = substr($fileName, 0, strrpos($fileName, '.')) . '_' . $count . '.' . $fileExt;
$files = $this->getDuplicatedFiles($f, $newFileName);
if (count($files)) {
$this->changeFileName($f, ++$count);
} else {
$oldFilePath = $f->getPath();
$f->updateFile($newFileName, $f->getPrefix());
$f = File::getByID($f->getFileID());
$newFilePath = $f->getPath();
if (copy($oldFilePath, $newFilePath)) {
Log::addEntry(sprintf('copy %s to %s: id: %d', $oldFilePath, $newFilePath, $f->getFileID()));
} else {
$f->updateFile($fileName, $f->getPrefix());
}
$f->refreshThumbnails(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment