/** * Deletes config file * @return bool * @throws \T4\Core\Exception|\T4\Fs\Exception */ public function delete() { if (empty($this->__path)) { throw new Exception('Empty path for config delete'); } return Helpers::removeFile($this->__path); }
public function actionExtension($name) { $name = ucfirst($name); $dirname = ROOT_PATH_PROTECTED . DS . 'Extensions' . DS . $name; $nameSpace = 'APP\\Extensions\\' . $name; \T4\Fs\Helpers::mkDir($dirname); $fileName = $dirname . DS . 'Extension.php'; $content = <<<FILE <?php namespace {$nameSpace}; class Extension extends \\T4\\Core\\Extension { public function init() { } } FILE; file_put_contents($fileName, $content); $this->writeLn('Extension ' . $name . ' is created in ' . $dirname); }
/** * Публикует ресурс (файл или директорию) * Возвращает публичный URL ресурса * @param string $path * @return string */ public function publish($path) { // Получаем абсолютный путь в ФС до ресурса и узнаем тип ресурса $realPath = $this->getRealPath($path); // TODO: смущает меня этот кусок, если честно. Надо внимательно его перепроверить. foreach ($this->assets as $asset) { if (false !== strpos($realPath, $asset['path'])) { return str_replace(DS, '/', str_replace($asset['path'], $asset['url'], $realPath)); } } $type = is_dir($realPath) ? 'dir' : 'file'; // Получаем время последней модификации ресурса // и, заодно, путь до него и до возможной публикации clearstatcache(true, $realPath); if ('dir' == $type) { $baseRealPath = $realPath; $lastModifiedTime = Helpers::dirMTime($realPath . DS . '.'); } else { $baseRealPath = pathinfo($realPath, PATHINFO_DIRNAME); $baseRealName = pathinfo($realPath, PATHINFO_BASENAME); $lastModifiedTime = filemtime($realPath); } $pathHash = substr(md5($baseRealPath), 0, 12); $assetBasePath = ROOT_PATH_PUBLIC . DS . 'Assets' . DS . $pathHash; $assetBaseUrl = '/Assets/' . $pathHash; // Вариант 1 - такого пути в папке Assets нет if (!is_readable($assetBasePath)) { Helpers::mkDir($assetBasePath); if ('dir' == $type) { Helpers::copyDir($realPath, $assetBasePath); } else { Helpers::copyFile($realPath, $assetBasePath); } } else { // Вариант 2 - нужный путь уже есть, нужно проверить наличие там нашего файла clearstatcache(); if ('file' == $type) { // Файл не найден, копируем его // Файл найден, но протух - перезаписываем if (!is_readable($assetBasePath . DS . $baseRealName) || $lastModifiedTime >= filemtime($assetBasePath . DS . $baseRealName)) { Helpers::copyFile($realPath, $assetBasePath); } } else { // Это папка. Она уже скопирована. Но протухла if ($lastModifiedTime >= filemtime($assetBasePath . DS . '.')) { Helpers::copyDir($realPath, $assetBasePath); } } } $asset =& $this->assets[]; $asset['path'] = $realPath; $asset['url'] = str_replace(DS, '/', str_replace($baseRealPath, $assetBaseUrl, $realPath)); return $asset['url']; }
public function deleteImage($item) { if ($item->image) { try { Helpers::removeFile(ROOT_PATH_PUBLIC . $item->image); } catch (\T4\Fs\Exception $e) { return false; } } return true; }
public function __invoke($name = '') { if (empty($this->formFieldName) && !empty($name)) { $this->formFieldName = $name; } if (empty($this->formFieldName)) { throw new Exception('Empty form field name for file upload'); } if (empty($this->uploadPath)) { throw new Exception('Invalid upload path'); } $realUploadPath = \T4\Fs\Helpers::getRealPath($this->uploadPath); if (!is_dir($realUploadPath)) { try { \T4\Fs\Helpers::mkDir($realUploadPath); } catch (\T4\Fs\Exception $e) { throw new Exception($e->getMessage()); } } $request = Application::getInstance()->request; if (!$request->isUploaded($this->formFieldName)) { throw new Exception('File for \'' . $this->formFieldName . '\' is not uploaded'); } if (!$this->isUploaded($this->formFieldName)) { throw new Exception('Error while uploading file \'' . $this->formFieldName . '\': ' . $request->files->{$this->formFieldName}->error); } if ($request->isUploadedArray($this->formFieldName)) { $ret = []; foreach ($request->files->{$this->formFieldName} as $n => $file) { if (!$this->checkExtension($file->name)) { throw new Exception('Invalid file extension'); } $uploadedFileName = $this->suggestUploadedFileName($realUploadPath, $file->name); if (move_uploaded_file($file->tmp_name, $realUploadPath . DS . $uploadedFileName)) { $ret[$n] = $this->uploadPath . '/' . $uploadedFileName; } else { $ret[$n] = false; } } return $ret; } else { $file = $request->files->{$this->formFieldName}; if (!$this->checkExtension($file->name)) { throw new Exception('Invalid file extension'); } $uploadedFileName = $this->suggestUploadedFileName($realUploadPath, $file->name); if (move_uploaded_file($file->tmp_name, $realUploadPath . DS . $uploadedFileName)) { return $this->uploadPath . '/' . $uploadedFileName; } else { return false; } } }
public function deleteImage($path) { if ($this->image) { try { $this->image = ''; Helpers::removeFile(ROOT_PATH_PUBLIC . $path); } catch (\T4\Fs\Exception $e) { return false; } } return true; }
protected function getModules() { static $modules = null; if (null === $modules) { $dirs = Helpers::listDir(ROOT_PATH_PROTECTED . DS . 'Modules'); $modules = new Collection(); foreach ($dirs as $dir) { $moduleClassName = '\\App\\Modules\\' . basename($dir) . '\\Module'; if (class_exists($moduleClassName)) { $modules[] = new $moduleClassName(); } } } return $modules; }
public function __invoke($key, $callback, $time = self::DEFAULT_CACHE_TIME) { $cachePath = $this->path; if (!is_readable($cachePath)) { Helpers::mkDir($cachePath); } $fileName = $cachePath . DS . md5($key) . '.cache'; clearstatcache(true, $fileName); if (!file_exists($fileName) || time() - filemtime($fileName) > (int) $time) { $res = call_user_func($callback); file_put_contents($fileName, serialize($res)); return $res; } else { return unserialize(file_get_contents($fileName)); } }
public function testSuggestUploadedFileName() { $uploader = new \T4\Http\Uploader(); $reflector = new ReflectionMethod($uploader, 'suggestUploadedFileName'); $reflector->setAccessible(true); $tmpDir = __DIR__ . DS . md5(time()); \T4\Fs\Helpers::mkDir($tmpDir); $this->assertEquals('test', $reflector->invokeArgs($uploader, [$tmpDir, 'test'])); $this->assertEquals('test.html', $reflector->invokeArgs($uploader, [$tmpDir, 'test.html'])); file_put_contents($tmpDir . DS . 'test.html', 'TEST'); $this->assertEquals('test_1.html', $reflector->invokeArgs($uploader, [$tmpDir, 'test.html'])); file_put_contents($tmpDir . DS . 'test_1.html', 'TEST'); $this->assertEquals('test_2.html', $reflector->invokeArgs($uploader, [$tmpDir, 'test.html'])); $this->assertEquals('test_2.html', $reflector->invokeArgs($uploader, [$tmpDir, 'test_1.html'])); unlink($tmpDir . DS . 'test.html'); unlink($tmpDir . DS . 'test_1.html'); rmdir($tmpDir); }
public function actionAploadImg() { $realUploadPath = \T4\Fs\Helpers::getRealPath($this->app->request->post->path); if (!is_dir($realUploadPath)) { try { \T4\Fs\Helpers::mkDir($realUploadPath); } catch (\T4\Fs\Exception $e) { throw new Exception($e->getMessage()); } } // Helpers::mkDir(ROOT_PATH_PUBLIC . DS .'/images/pages'); $uploaddir = $realUploadPath; $file = $this->app->request->post->value; $name = $this->app->request->post->name; // Получаем расширение файла $getMime = explode('.', $name); $mime = end($getMime); // Выделим данные $data = explode(',', $file); // Декодируем данные, закодированные алгоритмом MIME base64 $encodedData = str_replace(' ', '+', $data[1]); $decodedData = base64_decode($encodedData); var_dump($decodedData); var_dump($uploaddir . $name); // Создаем изображение на сервере if (file_put_contents($uploaddir . $name, $decodedData)) { echo $name . ":загружен успешно"; } else { // Показать сообщение об ошибке, если что-то пойдет не так. echo "Что-то пошло не так. Убедитесь, что файл не поврежден!"; } //$lin='__'.lcfirst($this->app->request->post->class).'_id'; $item = new SiteImage(); $subclass = $this->app->request->post->subclass; $namefield = $this->app->request->post->namefield; $item->{$namefield} = $this->app->request->post->path . $name; $item->published = date('Y-m-d H:i:s', time()); $item->{$subclass} = $this->app->request->post->id; $item->save(); die; //$this->redirect('admin/rubrics?id='.$this->app->request->post->pageid); }
protected function getMigrations($module = null) { $migrations = []; $migrationsDir = $this->getMigrationsPath($module); $pathToMigrations = Helpers::listDir($migrationsDir, \SCANDIR_SORT_ASCENDING); foreach ($pathToMigrations as $migration) { if (is_file($migration)) { $migrations[] = basename(substr(strrchr($migration, '_'), 1), '.php'); } } if (empty($migrations)) { $this->writeLn(ucfirst($module) . ' has no migrations'); } return $migrations; }
public function addTemplatePath($path) { $this->paths[] = Helpers::getRealPath($path) ?: $path; }