private function createAndReturnTempDir() : string { $tempDir = sys_get_temp_dir() . '/php7_codesniffer'; FileSystem::delete($tempDir); FileSystem::createDir($tempDir); return $tempDir; }
/** * @param string $file */ public function unlinkFile($file) { if (empty($file) && !is_file($file)) { return; } FileSystem::delete($file); $dir1 = dirname($file); $isEmpty = !(new \FilesystemIterator($dir1))->valid(); if (!$isEmpty) { return; } FileSystem::delete($dir1); $dir2 = dirname($dir1); $isEmpty = !(new \FilesystemIterator($dir2))->valid(); if (!$isEmpty) { return; } FileSystem::delete($dir2); $dir3 = dirname($dir2); $isEmpty = !(new \FilesystemIterator($dir3))->valid(); if (!$isEmpty) { return; } FileSystem::delete($dir3); }
protected function deleteImage($path) { $file = $this->rootDir . DIRECTORY_SEPARATOR . $path; if (file_exists($file)) { Nette\Utils\FileSystem::delete($file); } }
/** * @param string $imageName image name is comprised of UUID and original name (UUID/origName.extension) * @throws DBALException * @throws FileRemovalException */ public function removeImage($imageName) { $id = mb_substr($imageName, 0, mb_strpos($imageName, '/')); $file = sprintf('%s/%s', $this->imageFileRoot, $imageName); try { $this->em->beginTransaction(); $d = $this->em->createQuery('DELETE ' . Image::class . ' i WHERE i.id = :id')->execute(['id' => $id]); $directory = sprintf('%s/%s', $this->imageFileRoot, $id); // checks whether directory exists (each directory has always one file) if ($d > 0 and \file_exists($directory) and is_dir($directory)) { $r = \unlink($file); // and if so then remove file in it if ($r === false) { // file couldn't be removed $this->em->rollback(); $this->em->close(); throw new FileRemovalException(); } else { // remove directory FileSystem::delete($directory); } } $this->em->commit(); } catch (DBALException $e) { $this->em->rollback(); $this->em->close(); throw $e; } }
public function wipeCache() { $paths = [realpath($this->tempDir . '/cache'), realpath($this->tempDir . '/proxy')]; foreach (Nette\Utils\Finder::find('*')->in($paths) as $k => $file) { Nette\Utils\FileSystem::delete($k); } }
/** * Store basic file. * For use in nette see *storeNetteFile* * * @param $sourceFile * @param $orginalName * @param bool $deleteOrginalFile * @return mixed * @throws \Nette\IOException */ public function store($sourceFile, $orginalName, $deleteOrginalFile = false) { $path = $this->processStorePath($this->storePath, $orginalName); $thumbs = $this->createThumbs($sourceFile); $identifier = $this->backend->save($sourceFile, $orginalName, $path, $thumbs); if ($deleteOrginalFile) { FileSystem::delete($sourceFile); } return $identifier; }
/** * @param Nette\Application\UI\Form $form * @param $values */ public function deleteFormSubmitted(Nette\Application\UI\Form $form, $values) { if ($this->fileManager->isFeatureEnabled('deleteFile') && $form->submitted === $form['delete']) { $name = self::getPath($this, $values->file); Nette\Utils\FileSystem::delete($name); $this->onFileDelete($name); $this->flashMessage('fileManager.alert.fileDeleted', 'success'); } $this->fileList->go('this', ['view' => 'Default']); }
public function deleteExperiment($experimentId) { try { $experiment = $this->getExperimentById($experimentId); \Nette\Utils\FileSystem::delete(__DIR__ . '/../../data/' . $experiment['url_key']); return $this->db->table('experiments')->wherePrimary($experimentId)->delete(); } catch (\Exception $exception) { return FALSE; } }
/** * @param Photoset $photoset * @param boolean $noSlug * @param boolean $dryRun * @param string $dir * @param boolean $cleanDir * @return string */ private function managePhotosetDir(Photoset $photoset, $noSlug, $dryRun, $dir, $cleanDir) { $dirName = $this->dirnameCreator->create($photoset, $dir, $noSlug); if ($cleanDir && is_dir($dirName) && !$dryRun) { \Nette\Utils\FileSystem::delete($dirName); } if (!is_dir($dirName) && !$dryRun) { \Nette\Utils\FileSystem::createDir($dirName); } return $dirName; }
private function handleInvalidation(Listing $listing) { $cache = $this->cacheFactory->getCache($listing->user->id, $listing->year); // removal of all generated pdf files of given Listing $generatedFiles = $cache->load('generatedPdfFilesByListing/' . $listing->getId()); if ($generatedFiles !== null) { foreach ($generatedFiles as $key => $filePath) { if (!is_dir($filePath) and file_exists($filePath)) { FileSystem::delete($filePath); } } } $cache->clean([Cache::TAGS => 'listing/' . $listing->id]); }
/** * Factory for settings db host. * @param class Translator * @param callable * @return Form */ public function databaseHostFactory($translator, callable $onSuccess) { $form = $this->forms->create($translator); $form->addText('host', 'install.db.host')->setRequired('install.form.empty'); $form->addText('user', 'install.db.user')->setRequired('install.form.empty'); $form->addText('password', 'install.db.pass'); $form->addText('database', 'install.db.name')->setRequired('install.form.empty'); $form->addText('prefix', 'install.db.prefix')->setAttribute('placeholder', 'ns_'); // Database drivers. $drivers = ['mysql' => 'MySQL', 'mysqli' => 'MySQLi']; $form->addSelect('driver', 'install.db.driver', $drivers)->setRequired(); $form->addSubmit('send', 'install.db.send'); $form->onSuccess[] = function (Form $form, $values) use($onSuccess) { try { // Testing database connection. if (\dibi::connect($values)) { // Parameters for generate config neon file. $arr = ['extensions' => ['dibi' => 'Dibi\\Bridges\\Nette\\DibiExtension22'], 'dibi' => ['host' => $values->host, 'username' => $values->user, 'password' => $values->password, 'database' => $values->database, 'driver' => $values->driver, 'lazy' => TRUE, 'substitutes' => ['prefix' => $values->prefix]]]; // Generate and save the configuration file $this->loader->save($arr, $this->dirs->getAppDir() . '/modules/app.db.neon'); // Removing the old cache for updating the configuration file. FileSystem::delete($this->dirs->getTempDir() . '/cache/Nette.Configurator'); // Save the installation step into the cache. $this->steps->setToCache(Steps::Step1, rand(1, 9)); // Save db prefix. if ($values->prefix) { $this->sessions->getSessionSection()->prefix = $values->prefix; } } } catch (\Dibi\Exception $e) { // Server database type error. if ($e->getCode() == 0) { $form->addError('install.db.driver.catch'); // Host server not found. } elseif ($e->getCode() == 2002) { $form->addError('install.db.host.catch'); // The user or password was not verified. } elseif ($e->getCode() == 1045) { $form->addError('install.db.auth.catch'); // The database name was not found } elseif ($e->getCode() == 1049) { $form->addError('install.db.name.catch'); } return; } $onSuccess(); }; return $form; }
/** * Akce pro smazání obsahu adresáře, do kterého se ukládá aplikační cache * @throws \Nette\Application\AbortException */ public function actionClean() { $deletedArr = []; $errorArr = []; foreach (Finder::find('*')->in(CACHE_DIRECTORY) as $file => $info) { try { FileSystem::delete($file); $deletedArr[] = $file; } catch (\Exception $e) { $errorArr[] = $file; } } $response = ['state' => empty($errorArr) ? 'OK' : 'error', 'deleted' => $deletedArr, 'errors' => $errorArr]; $this->sendJson($response); }
/** * @param IListingPdfFile[] $pdfFiles * @param string $zipStorageFilePath * @return null */ private function zipFiles(array $pdfFiles, $zipStorageFilePath) { if (file_exists($zipStorageFilePath) and !is_dir($zipStorageFilePath)) { FileSystem::delete($zipStorageFilePath); } $zip = new \ZipArchive(); if ($zip->open($zipStorageFilePath, \ZipArchive::CREATE) !== true) { return null; } /** @var IListingPdfFile $pdfFile */ foreach ($pdfFiles as $pdfFile) { if (!file_exists($pdfFile->getStoragePath())) { FileSystem::write($pdfFile->getStoragePath(), $pdfFile->getPdfContent()); } $zip->addFile($pdfFile->getStoragePath(), $pdfFile->getFileName()); } $zip->close(); return $zipStorageFilePath; }
/** * @param Nette\Application\UI\Form $form * @param $values */ public function deleteFormSubmitted(Nette\Application\UI\Form $form, $values) { $goToDir = $this->getDirectory(); $name = $this->getAbsoluteDirectory(); if ($this->fileManager->isFeatureEnabled('deleteDir') && !$this->fileManager->isRootSelected() && $form->submitted === $form['delete']) { Nette\Utils\FileSystem::delete($this->getAbsoluteDirectory()); $goToDir = Zax\Utils\PathHelpers::getParentDir($this->getDirectory()); $this->onDirDelete($name); $this->flashMessage('fileManager.alert.dirDeleted', 'success'); } else { if ($this->fileManager->isFeatureEnabled('truncateDir') && $form->submitted === $form['truncate']) { foreach (Nette\Utils\Finder::find('*')->in($this->getAbsoluteDirectory()) as $k => $file) { Nette\Utils\FileSystem::delete($k); } $this->onDirTruncate($name); $this->flashMessage('fileManager.alert.dirTruncated', 'success'); } } $this->fileManager->setDirectory($goToDir); $this->fileManager->go('this', ['dir' => $goToDir, 'view' => 'Default', 'directoryList-view' => 'Default']); }
private function removeBackupFile(DatabaseBackupFile $file) { if (file_exists($file->getFilePath()) and !is_dir($file->getFilePath())) { FileSystem::delete($file->getFilePath()); } }
private function generate() { try { CLI::write('Generating application:', 0, TRUE, FALSE, TRUE); (new Builder\Builder(static::$settings))->build(); for ($i = 0; $i <= 99; $i++) { CLI::write("\r => Generating application: {$i}% completed", TRUE, FALSE, FALSE); usleep(25000); } CLI::write("\r => Generating application: SUCCESS ", 0, FALSE); CLI::write('Cleaning Nette Cache:', 0, TRUE, FALSE, TRUE); \Nette\Utils\FileSystem::delete(static::$settings->netteRoot . '/temp/cache'); CLI::write('SUCCESS', 0, FALSE); CLI::write('Application successfully built in ' . number_format(microtime(TRUE) - static::$startTime - 2, 2, '.', ' ') . ' seconds.', 0, TRUE, TRUE, TRUE); } catch (\Doctrine\ORM\Mapping\MappingException $e) { CLI::write('ERROR', 0, FALSE); CLI::write($e->getMessage(), TRUE, 1); } catch (\Exception $e) { CLI::write('ERROR', 0, FALSE); CLI::write($e->getMessage(), TRUE, 1); } }
/** * @param string $dir * @param string $filename * @return void */ public function delete($dir, $filename) { $filter = array_keys($this->dimensions); if ($this->saveOriginal) { $filter[] = 'orig'; } $filter = array_map(function ($i) use($filename) { return $i . '_' . $filename; }, $filter); $filter[] = $filename; $dir = $this->getBasePath() . '/' . $this->getRelativePath() . '/' . $dir; $dir = Utils::normalizePath($dir); if (!is_dir($dir)) { return; } foreach (Finder::findFiles($filter)->in($dir) as $filePath => $file) { FileSystem::delete($filePath); } }
/** * @return string */ public function process() { if ($this->processedFile) { return $this->processedFile; } $name = $this->cache->load($this->getCacheKey()); if ($name === NULL) { $this->cache->save($this->getCacheKey(), $name = $this->makeFileName(), [Nette\Caching\Cache::FILES => $this->files]); } $path = $this->outputDir . '/' . $name; if (!file_exists($path)) { foreach (Nette\Utils\Finder::findFiles('*.' . $this->getExtension())->in($this->outputDir) as $k => $file) { Nette\Utils\FileSystem::delete($k); } file_put_contents($path, $this->minify($this->combineFiles())); } return $this->processedFile = $path; }
public function deleteTask($taskId) { try { $task = $this->getTaskById($taskId); $experiment = $task->experiment; \Nette\Utils\FileSystem::delete(__DIR__ . '/../../data/' . $experiment['url_key'] . '/' . $task['url_key']); return $this->db->table('tasks')->wherePrimary($taskId)->delete(); } catch (\Exception $exception) { return FALSE; } }
private function getImageColorInfo($filename) { $filenameSample = $filename . '.sample.jpg'; if (file_exists($filename)) { if (!file_exists($filenameSample)) { $imageFile = Image::fromFile($filename); $imageFile->resize(200, 200, Image::FILL); $imageFile->save($filenameSample, 100, Image::JPEG); } $client = new Client(); $image = $client->loadJpeg($filenameSample); $palette = $image->extract(6); $dominantColor = ColorThief::getColor($filenameSample); $dominantColor = \Aprila\Utils\Colors::rgbToHex($dominantColor); $color = new Color($dominantColor); $isDark = $color->isDark(); $imageColorInfo = ['main' => $dominantColor, 'palette' => $palette, 'isDark' => $isDark]; FileSystem::delete($filenameSample); return $imageColorInfo; } return []; }
function showMyTemplates() { $customer = $this->add('xepan\\commerce\\Model_Customer'); $customer->loadLoggedIn(); $template_grid = $this->add('xepan\\base\\Grid', null, 'my_template', ['view\\tool\\mytemplate']); $template_grid->setModel('xepan\\epanservices\\Model_MyTemplates'); $template_grid->addHook('formatRow', function ($g) { $item = $this->add('xepan\\commerce\\Model_Item')->load($g->model->id); $g->current_row_html['preview_image'] = $item['first_image']; $g->current_row_html['preview_url'] = 'http://' . $item['sku'] . '.epan.in'; }); $vp = $this->add('VirtualPage'); $vp->set(function ($p) { $item_id = $this->app->stickyGET('item_id'); $item = $p->add('xepan\\commerce\\Model_Item')->load($item_id); $template_name = $item['sku']; if (!file_exists(realpath($this->app->pathfinder->base_location->base_path . '/websites/' . $template_name))) { throw new \Exception('Template not found: Folder do not exist in websites.'); } $customer = $p->add('xepan\\commerce\\Model_Customer'); $customer->loadLoggedIn(); $epan = $p->add('xepan\\epanservices\\Model_Epan'); $epan->addCondition('created_by_id', $customer->id); $form = $p->add('Form'); $form->addField('xepan\\commerce\\DropDown', 'epan')->setModel($epan); if ($form->isSubmitted()) { $model_epan = $p->add('xepan\\epanservices\\Model_Epan')->load($form['epan']); $folder_name = $model_epan['name']; if (!$model_epan->loaded()) { throw new \Exception("Epan model not loaded"); } // NUMBER OF TEMPLATES (NUMBER OF THIS TEMPLATE PURCHASED?) $epan_template = $this->add('xepan\\epanservices\\Model_MyTemplates'); $epan_template->addCondition('id', $item_id); $template_count = $epan_template->count()->getOne(); // NUMBER OF EPANS ON WHICH THIS TEMPLATE IS APPLIED $applied_count_epan = $this->add('xepan\\epanservices\\Model_Epan'); $applied_count_epan->addCondition('created_by_id', $customer->id); $applied_count_epan->addCondition('xepan_template_id', $item_id); $epan_count = $applied_count_epan->count()->getOne(); // NO MORE TEMPLATES LEFT TO APPLY if ($epan_count == $template_count) { return $form->error('epan', 'You have already applied this template. Please buy or use any other template'); } if (file_exists(realpath($this->app->pathfinder->base_location->base_path . '/websites/' . $folder_name . '/www'))) { $fs = \Nette\Utils\FileSystem::delete('./websites/' . $folder_name . '/www'); } $fs = \Nette\Utils\FileSystem::createDir('./websites/' . $folder_name . '/www'); $fs = \Nette\Utils\FileSystem::copy('./websites/' . $template_name, './websites/' . $folder_name . '/www', true); $model_epan['xepan_template_id'] = $item_id; $model_epan->save(); return $form->js()->univ()->successMessage('Template Applied')->execute(); } }); $template_grid->on('click', '.xepan-change-template', function ($js, $data) use($vp) { return $js->univ()->dialogURL("APPLY NEW TEMPLATE", $this->api->url($vp->getURL(), ['item_id' => $data['id']])); }); }
public function handleDeletePhoto($photoId, $startChar) { if ($this->isAjax()) { try { $photo = $this->photoFacade->findOneById($photoId); if ($this->user->isAllowed("DeletePhoto") || $photo->user->id == $this->user->id) { FileSystem::delete("img/articles/miniatures/" . $photo->filepath); FileSystem::delete("img/articles/midiatures/" . $photo->filepath); FileSystem::delete("img/articles/" . $photo->filepath); $this->photoFacade->delete($photo); $this->template->photoPreview = null; $this->redrawControl("articleWrapper"); $this->redrawControl("photoPreview"); $this->template->choosenPhoto = $this->photoFacade->findOneById(42); $this->template->photoId = 42; $this->redrawControl("photoField"); $this->handleLoadPhotosByStartCharTag($startChar); } } catch (EntityNotFoundException $ex) { \Tracy\Debugger::log($ex); } } else { $this->redirect("this"); } }
/** * @param string */ private function moveData($dataPath) { if ($this->verbose) { $this->writeln('Moving pages data'); } try { FileSystem::delete($this->dataPath); } catch (\Nette\IOException $e) { throw new \NetteAddons\InvalidStateException('Moving pages data failed', NULL, $e); } $dataPath = $this->getBaseDataPath($dataPath); foreach (Finder::findFiles('*')->from($dataPath) as $file) { /** @var \SplFileInfo $file */ $destinationPath = str_replace($dataPath, $this->dataPath, $file->getRealPath()); FileSystem::rename($file->getRealPath(), $destinationPath); } }
function swipeEverything($epan = null) { if (!$epan) { $epan = $this['name']; } if ($epan instanceof \xepan\epanservices\Model_Epan) { $epan = $epan['name']; } if (!file_exists(realpath('websites/' . $epan . '/config.php'))) { return; } include_once 'websites/' . $epan . '/config.php'; preg_match('|([a-z]+)://([^:]*)(:(.*))?@([A-Za-z0-9\\.-]*)' . '(/([0-9a-zA-Z_/\\.-]*))|', $config['dsn'], $matches); $fs = \Nette\Utils\FileSystem::delete('./websites/' . $epan); $this->app->db->dsql()->expr("GRANT ALL PRIVILEGES ON `*`.* To '{$matches['2']}'@'%';")->execute(); $this->app->db->dsql()->expr("DROP USER `{$matches['2']}`@'%'")->execute(); $this->app->db->dsql()->expr("DROP DATABASE IF EXISTS `{$matches['7']}`;")->execute(); }
/** * @param string filepath (namespace/file.ext) * @return void */ public function delete($file) { FileSystem::delete($this->getPath($file)); FileSystem::delete($this->directory . '/' . $this->formatThumbnailPath($file, NULL)); }
/** * Clean up - delete downloaded files */ public function __destruct() { foreach ($this->toDelete as $file) { FileSystem::delete($file); } }
/** * @inheritdoc */ public function deleteAll() { foreach ($this->findFiles() as $file) { FileSystem::delete($file); } }
/** * activate configuration * @param string $sopClassPath * @return void */ public function activateConfig($sopClassPath) { $outputText = $this->defaultValues; $table = $this->getTable(); $values = $table->where("active", 1); foreach ($values as $value) { $outputText .= $value->name . "\t" . $value->sop . "\t" . $value->application . "\t" . $value->transfer . "\n"; } \Nette\Utils\FileSystem::delete($sopClassPath); \Nette\Utils\FileSystem::write($sopClassPath, $outputText); $table2 = $this->getTable(); $table2->where("activated", 0); $table2->update(array("activated" => 1)); return; }
/** * Formulář pro upload souboru * @return Form */ public function createComponentUploadForm() { $form = new Form(); $form->setTranslator($this->translator); $form->addUpload('file', 'Upload file:')->setRequired('Je nutné vybrat soubor pro import!')->addRule(Form::MAX_FILE_SIZE, 'Nahrávaný soubor je příliš velký', $this->fileImportsFacade->getMaximumFileUploadSize()); $form->addSubmit('submit', 'Upload file...')->onClick[] = function (SubmitButton $submitButton) { /** @var Form $form */ $form = $submitButton->getForm(true); /** @var FileUpload $file */ $file = $form->getValues()->file; #region detekce typu souboru $fileType = $this->fileImportsFacade->detectFileType($file->getName()); if ($fileType == FileImportsFacade::FILE_TYPE_UNKNOWN) { //jedná se o nepodporovaný typ souboru try { FileSystem::delete($this->fileImportsFacade->getTempFilename()); } catch (\Exception $e) { } $form->addError($this->translate('Incorrect file type!')); return; } #endregion detekce typu souboru #region přesun souboru $filename = $this->fileImportsFacade->getTempFilename(); $file->move($this->fileImportsFacade->getFilePath($filename)); #endregion přesun souboru #region pokus o automatickou extrakci souboru if ($fileType == FileImportsFacade::FILE_TYPE_ZIP) { $fileType = $this->fileImportsFacade->tryAutoUnzipFile($filename); } #endregion pokus o automatickou extrakci souboru #region výběr akce dle typu souboru $this->redirect('Data:uploadData', array('file' => $filename, 'type' => $fileType, 'name' => FileImportsFacade::sanitizeFileNameForImport($file->getName()))); #endregion výběr akce dle typu souboru }; $form->addSubmit('storno', 'storno')->setValidationScope([])->onClick[] = function () { $this->redirect('Data:newMiner'); }; return $form; }
/** * @param $dir * @param $filename * @return mixed|void */ public function delete($dir, $filename) { $dir = $this->getBasePath() . '/' . $this->getRelativePath() . '/' . $dir; $dir = Utils::normalizePath($dir); FileSystem::delete($dir . '/' . $filename); }