/** * Сгенерировать карту классов для автоподгрузки. */ public function actionGenerate() { $root = '@app'; $root = Yii::getAlias($root); $root = FileHelper::normalizePath($root); $mapFile = '@app/config/classes.php'; $mapFile = Yii::getAlias($mapFile); $options = ['filter' => function ($path) { if (is_file($path)) { $file = basename($path); if ($file[0] < 'A' || $file[0] > 'Z') { return false; } } return; }, 'only' => ['*.php'], 'except' => ['/views/', '/vendor/', '/config/', '/tests/']]; $files = FileHelper::findFiles($root, $options); $map = []; foreach ($files as $file) { if (strpos($file, $root) !== 0) { throw new \Exception("Something wrong: {$file}\n"); } $path = str_replace('\\', '/', substr($file, strlen($root))); $map['app' . substr(str_replace('/', '\\', $path), 0, -4)] = $file; } $this->generateMapFile($mapFile, $map); }
/** * @inheritdoc */ public function init() { if ($this->path === null) { throw new InvalidConfigException("Empty \"{$this->path}\"."); } $this->path = FileHelper::normalizePath($this->path) . DIRECTORY_SEPARATOR; }
/** * @inheritdoc */ public function applyTo($path) { $pathMap = $this->pathMap; if (empty($pathMap)) { if (($basePath = $this->getBasePath()) === null) { throw new InvalidConfigException('The "basePath" property must be set.'); } $pathMap = [Yii::$app->getBasePath() => [$basePath]]; } $module = Yii::$app->controller->module; if (!$module instanceof \yii\web\Application) { $pathMap['@app/modules/' . $module->id . '/views'] = [$pathMap['@app/views'][0] . '/' . $module->id]; } #debug // echo '<pre>'; // print_r(Yii::$app->controller->module); // echo '</pre>'; #end debug #debug echo '<pre>'; print_r($pathMap); echo '</pre>'; #end debug $path = FileHelper::normalizePath($path); #debug echo 'path: ', $path, '<br/>'; #end debug foreach ($pathMap as $from => $tos) { $from = FileHelper::normalizePath(Yii::getAlias($from)) . DIRECTORY_SEPARATOR; #debug echo 'from: ', $from, '<br/>'; #end debug if (strpos($path, $from) === 0) { $n = strlen($from); foreach ((array) $tos as $to) { $to = FileHelper::normalizePath(Yii::getAlias($to)) . DIRECTORY_SEPARATOR; #debug echo 'to: ', $to, '<br/>'; #end debug $file = $to . substr($path, $n); if (is_file($file)) { #debug echo 'return file: ', $file, '<br/>'; if (strpos($path, 'layouts')) { exit; } #end debug return $file; } } } } #debug echo 'return path: ', $path, '<br/>'; if (strpos($path, 'layouts')) { exit; } #end debug return $path; }
/** * @inheritdoc */ public function init() { parent::init(); $this->uploadDir = !empty(\Yii::$app->getModule('core')->fileUploadPath) ? \Yii::$app->getModule('core')->fileUploadPath : $this->uploadDir; $this->uploadDir = FileHelper::normalizePath(\Yii::getAlias($this->uploadDir)); $this->additionalRenderData['uploadDir'] = $this->uploadDir; }
/** * Returns UploadFile created from url * Notice that this file cannot be saved by move_uploaded_file * @param $url * @throws \yii\base\InvalidConfigException */ public static function getFromUrl($url) { $tmpFile = null; if (static::isExternalUrl($url)) { //External url $tmpFile = static::downloadToTmp($url); } else { //File must be in static folder $staticPath = Yii::getAlias('@static/'); $path = str_replace(Yii::getAlias('@staticUrl/'), Yii::getAlias('@static/'), Yii::getAlias($url), $count); //If we can replace static url to path if ($count > 0) { //Check staticPath after normalize $path = FileHelper::normalizePath($path); if (strpos($path, $staticPath) === 0) { if (file_exists($path)) { $tmpFile = tempnam(sys_get_temp_dir(), 'CURL'); if (!copy($path, $tmpFile)) { $tmpFile = null; } } } } } if ($tmpFile) { return new static(['name' => basename($url), 'tempName' => $tmpFile, 'type' => FileHelper::getMimeType($tmpFile), 'size' => filesize($tmpFile), 'error' => UPLOAD_ERR_OK]); } return null; }
/** * @inheritdoc */ public function init() { parent::init(); $this->uploadDir = Yii::$app->getModule('core')->visitorsFileUploadPath; $this->uploadDir = FileHelper::normalizePath(Yii::getAlias($this->uploadDir)); $this->additionalRenderData['uploadDir'] = $this->uploadDir; }
public function run($id) { $id = (int) $id; $userId = Adver::getUserIdFromAdver($id); $output = []; if ($userId != Yii::$app->getUser()->id) { $output = ['error' => true, 'message' => '<div class="alert alert-danger">' . Yii::t('app', 'The requested page does not exist.') . '</div>']; } if (empty($output) && !Gallery::checkLimitation($id)) { $output = ['error' => true, 'message' => '<div class="alert alert-danger">' . Yii::t('app', 'Image limitation per advertisement reached!') . '</div>']; } if (empty($output)) { $model = new Gallery(['scenario' => 'new']); if ($model->load(Yii::$app->request->post())) { $model->image = UploadedFile::getInstance($model, 'image'); if ($model->image) { $model->name = Yii::$app->helper->safeFile($model->image->baseName) . '-' . Yii::$app->getSecurity()->generateRandomString(6) . '-' . time() . '.' . $model->image->extension; $path = $model->getImagePath($id) . DIRECTORY_SEPARATOR . $model->name; $path = FileHelper::normalizePath($path); $model->adver_id = $id; if ($model->validate() && $model->image->saveAs($path, false)) { if ($model->save()) { $output = ['error' => false, 'message' => '<div class="alert alert-success">' . Yii::t('app', 'Image saved!') . '</div>']; } else { $output = ['error' => true, 'message' => '<div class="alert alert-danger">' . Yii::t('app', 'Error on saving image.') . '</div>']; } } } } if (empty($output)) { $output = ['error' => true, 'message' => \yii\helpers\Html::errorSummary($model, ["class" => "alert alert-danger"])]; } } return \yii\helpers\Json::encode($output); }
/** * @inheritdoc */ public function attach($owner) { parent::attach($owner); if (!is_array($this->attributes) || empty($this->attributes)) { throw new InvalidParamException('Invalid or empty attributes array.'); } else { foreach ($this->attributes as $attribute => $config) { if (!isset($config['path']) || empty($config['path'])) { throw new InvalidParamException('Path must be set for all attributes.'); } if (!isset($config['tempPath']) || empty($config['tempPath'])) { throw new InvalidParamException('Temporary path must be set for all attributes.'); } if (!isset($config['url']) || empty($config['url'])) { $config['url'] = $this->publish($config['path']); } $this->attributes[$attribute]['path'] = FileHelper::normalizePath(Yii::getAlias($config['path'])) . DIRECTORY_SEPARATOR; $this->attributes[$attribute]['tempPath'] = FileHelper::normalizePath(Yii::getAlias($config['tempPath'])) . DIRECTORY_SEPARATOR; $this->attributes[$attribute]['url'] = rtrim($config['url'], '/') . '/'; $validator = Validator::createValidator('string', $this->owner, $attribute); $this->owner->validators[] = $validator; unset($validator); } } }
/** * @inheritdoc * @param \yii\gii\CodeFile $file */ protected function isPhpSafe($file) { $actions = $this->getActionIDs(); $viewFile = $this->getViewFile(reset($actions) ?: 'index'); $viewFileDir = FileHelper::normalizePath(dirname($viewFile)); return FileHelper::normalizePath(dirname($file->path)) === $viewFileDir; }
/** * Get prefixed path. * * @param string $path * @param string $prefix * * @return string */ protected function getPrefixedPath($path, $prefix) { if (substr($path, 0, 1) !== '/') { $path = '/' . $path; } $path = FileHelper::normalizePath($path); $prefixedPath = Yii::getAlias($prefix . $path); return $prefixedPath; }
/** * @inheritdoc */ protected function findFiles($path, $except = []) { if (empty($except)) { $except = ['README.md']; } $path = FileHelper::normalizePath($path); $options = ['only' => ['*.md'], 'except' => $except]; return FileHelper::findFiles($path, $options); }
public static function getImagePath($adverId) { $path = Yii::getAlias('@common/assets/images/gallery/' . (string) ((int) ($adverId / 10000) + 1) . '/' . $adverId); $path = FileHelper::normalizePath($path); if (!is_dir($path)) { FileHelper::createDirectory($path); } return $path; }
public static function loadTemplate($path) { $path = Yii::getAlias(self::TEMPLATES_ALIAS . '/' . $path); $path = FileHelper::normalizePath($path); $model = new self(); $model->templatePath = $path; $model->getTemplateContents(); return $model; }
public static function getAttachmentPath($adverId) { $path = Yii::getAlias('@common/assets/attachment/' . (string) ((int) ($adverId / 10000) + 1) . '/' . $adverId); $path = FileHelper::normalizePath($path); if (!is_file($path)) { FileHelper::createDirectory($path); } return $path; }
public function init() { if ($this->caseSensitivity) { Analyzer::setDefault(new Utf8()); } else { Analyzer::setDefault(new CaseInsensitive()); } $this->indexDirectory = FileHelper::normalizePath(Yii::getAlias($this->indexDirectory)); $this->luceneIndex = $this->getLuceneIndex($this->indexDirectory); }
public function init() { QueryParser::setDefaultEncoding('UTF-8'); if ($this->caseSensitivity) { Analyzer::setDefault($this->parseNumeric ? new Utf8Num() : new Utf8()); } else { Analyzer::setDefault($this->parseNumeric ? new CaseInsensitiveNum() : new CaseInsensitive()); } $this->indexDirectory = FileHelper::normalizePath(Yii::getAlias($this->indexDirectory)); $this->luceneIndex = $this->getLuceneIndex($this->indexDirectory); }
protected static function getFilePath($file) { if (strpos($file, '@') !== 0) { $file = '@webroot/' . $file; } $file = FileHelper::normalizePath(Yii::getAlias($file)); if (!is_file($file)) { return false; } return $file; }
/** * Creates a class map for the core Yii classes. * @param string $root the root path of Yii framework. Defaults to YII2_PATH. * @param string $mapFile the file to contain the class map. Defaults to YII2_PATH . '/classes.php'. */ public function actionCreate($root = null, $mapFile = null) { if ($root === null) { $root = YII2_PATH; } $root = FileHelper::normalizePath($root); if ($mapFile === null) { $mapFile = YII2_PATH . '/classes.php'; } $options = ['filter' => function ($path) { if (is_file($path)) { $file = basename($path); if ($file[0] < 'A' || $file[0] > 'Z') { return false; } } return null; }, 'only' => ['*.php'], 'except' => ['/Yii.php', '/BaseYii.php', '/console/']]; $files = FileHelper::findFiles($root, $options); $map = []; foreach ($files as $file) { if (strpos($file, $root) !== 0) { throw new Exception("Something wrong: {$file}\n"); } $path = str_replace('\\', '/', substr($file, strlen($root))); $map[$path] = " 'yii" . substr(str_replace('/', '\\', $path), 0, -4) . "' => YII2_PATH . '{$path}',"; } ksort($map); $map = implode("\n", $map); $output = <<<EOD <?php /** * Yii core class map. * * This file is automatically generated by the "build classmap" command under the "build" folder. * Do not modify it directly. * * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ return [ {$map} ]; EOD; if (is_file($mapFile) && file_get_contents($mapFile) === $output) { echo "Nothing changed.\n"; } else { file_put_contents($mapFile, $output); echo "Class map saved in {$mapFile}\n"; } }
public static function start($path) { $dir = FileHelper::normalizePath(rtrim($path, DIRECTORY_SEPARATOR)); $autoloads = FileHelper::findFiles($dir, ["only" => ["autoload.php"], "filter" => function ($file) use($dir) { if (substr_count($file, DIRECTORY_SEPARATOR) - 4 > substr_count($dir, DIRECTORY_SEPARATOR)) { return false; } }]); foreach ($autoloads as $path) { require_once $path; } }
public function init() { if ($this->path === null) { throw new InvalidConfigException('The "path" attribute must be set.'); } else { $this->path = getcwd() . $this->path; $this->path = FileHelper::normalizePath(Yii::getAlias($this->path)) . DIRECTORY_SEPARATOR; if (!FileHelper::createDirectory($this->path)) { throw new InvalidCallException("Directory specified in 'path' attribute doesn't exist or cannot be created."); } } }
/** * @inheritdoc */ public function pathIsNotIgnored($filePath) { $path = ltrim(FileHelper::normalizePath($filePath), DIRECTORY_SEPARATOR); $command = ['status', '-i', escapeshellcmd($path)]; $result = $this->wrapper->execute($command, $this->projectPath, true, true); foreach ($result as $row) { $row = preg_replace('#^I[\\s]+(.*)#i', '$1', $row); if ($row === $filePath) { return false; } } return true; }
public static function thumbnailImg($filename, $width, $height, $mode = self::THUMBNAIL_OUTBOUND, $options = [], $isWatermark = false) { $filename = FileHelper::normalizePath(Yii::getAlias($filename)); try { $thumbnailFileUrl = self::thumbnailFileUrl($filename, $width, $height, $mode, $isWatermark); } catch (FileNotFoundException $e) { return 'File doesn\'t exist'; } catch (\Exception $e) { Yii::warning("{$e->getCode()}\n{$e->getMessage()}\n{$e->getFile()}"); return 'Error ' . $e->getCode(); } return Html::img($thumbnailFileUrl, $options); }
/** * Constructor * * @param string $pathName * @param BaseRepository $repository * @param string|null $status file status in revision * * @throws CommonException */ public function __construct($pathName, BaseRepository $repository, $status = null) { $this->name = basename($pathName); $this->path = FileHelper::normalizePath($pathName); // first character for status $this->status = !is_null($status) ? substr($status, 0, 1) : $status; $this->repository = $repository; if (!StringHelper::startsWith($this->path, $repository->getProjectPath())) { throw new CommonException("Path {$this->path} outband of repository"); } $this->relativePath = substr($this->path, strlen($repository->getProjectPath())); parent::__construct([]); }
/** * Validates and saves the image. * Creates the folder to store images if necessary. * @return boolean */ public function upload() { try { if ($this->validate()) { $save_path = FileHelper::normalizePath(Yii::getAlias('@app/web/' . self::UPLOAD_DIR)); FileHelper::createDirectory($save_path); $this->url = Yii::getAlias('@web/' . self::UPLOAD_DIR . '/' . $this->image->baseName . '.' . $this->image->extension); return $this->image->saveAs(FileHelper::normalizePath($save_path . '/' . $this->image->baseName . '.' . $this->image->extension)); } } catch (Exception $e) { Yii::error($e->getMessage()); } return false; }
public function actionAutoload() { $dir = FileHelper::normalizePath(rtrim(\Yii::$app->params["workBenchPath"]), DIRECTORY_SEPARATOR); $composers = FileHelper::findFiles($dir, ["only" => ["composer.json"], "filter" => function ($file) use($dir) { if (substr_count($file, DIRECTORY_SEPARATOR) - 3 > substr_count($dir, DIRECTORY_SEPARATOR)) { return false; } }]); foreach ($composers as $file) { chdir(dirname($file)); passthru('composer dump-autoload --optimize'); } echo 'dump-autoload package!'; }
/** * @inheritdoc */ public function run(&$cmdParams, &$params) { $res = true; $taskRunner = $this->taskRunner; $pathFrom = !empty($cmdParams[0]) ? $taskRunner->parsePath($cmdParams[0]) : ''; $pathTo = !empty($cmdParams[1]) ? $taskRunner->parsePath($cmdParams[1]) : ''; $overwrite = !empty($cmdParams[2]) ? $cmdParams[2] : false; if (empty($pathFrom) || empty($pathTo)) { throw new Exception('mv: Origin and destination cannot be empty'); } if (!file_exists($pathFrom)) { $this->controller->stderr("Not found: {$pathFrom}\n", Console::FG_RED); } else { $insidePathTo = FileHelper::normalizePath($pathTo) . DIRECTORY_SEPARATOR . basename($pathFrom); if (is_file($pathFrom) && is_dir($pathTo)) { $pathTo = $insidePathTo; } $this->controller->stdout("Move (overwrite: " . ($overwrite ? 'yes' : 'no') . ") \n " . $pathFrom . " to \n " . $pathTo); if (!$this->controller->dryRun) { if (!$overwrite && is_dir($pathFrom) && is_dir($pathTo)) { if (!file_exists($insidePathTo)) { // not overwriting; copy the source directory into the destination folder: $res = rename($pathFrom, $insidePathTo); } else { $this->controller->stdout("\n"); $this->controller->warn("Destination directory {$insidePathTo} already exists; not overwriting"); } } elseif (!$overwrite && is_file($pathFrom) && is_file($pathTo)) { $this->controller->stdout("\n"); $this->controller->warn("Destination file {$pathTo} already exists; not overwriting"); } elseif (is_dir($pathFrom) && is_file($pathTo)) { $this->controller->stdout("\n"); $this->controller->stderr("Trying to move a directory to a file: {$pathTo}", Console::FG_RED); } elseif (!file_exists($pathTo) || $overwrite && is_dir($pathFrom) && is_dir($pathTo) || $overwrite && is_file($pathFrom) && is_file($pathTo)) { // if destination exists, overwrite it with the source file/dir // note: if pathTo is a directory, it has to be empty in order to be overwritten try { $res = rename($pathFrom, $pathTo); } catch (ErrorException $e) { $this->controller->stdout("\n"); $this->controller->warn($e->getMessage()); } } } else { $this->controller->stdout(' [dry run]', Console::FG_YELLOW); } $this->controller->stdout("\n"); } return $res; }
public function findDefaultViewFile($view, $context = null) { foreach ((array) $this->defaultPath as $path) { $to = FileHelper::normalizePath(Yii::getAlias($path)) . DIRECTORY_SEPARATOR; $file = $to . $view . '.' . $this->defaultExtension; if ($this->defaultExtension !== 'php' && !is_file($path)) { $file = $to . $view . '.php'; } if (is_file($file) && !in_array($file, $this->viewFiles)) { return $file; } } return parent::findViewFile($view, $context); }
/** * @inheritdoc */ function upload($dir = null, $name = null) { if ($dir === null) { return false; } FileHelper::createDirectory($dir); $this->name = empty($name) ? $this->generateName() : $name; $target = FileHelper::normalizePath($dir . '/' . $this->name); //throw new \Exception($target); if (!rename($this->tmp_name, $target)) { return false; } $this->tmp_name = $target; return true; }
/** * * @return type */ public function run() { $error = 'file don\'t exist'; if ($file = Yii::$app->getRequest()->post($this->paramName)) { $filename = FileHelper::normalizePath($this->path . '/' . $file); if (is_file($filename)) { $error = unlink($filename) ? 'file deleted' : 'can not delete file'; } } if (Yii::$app->getRequest()->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; } $result = ['error' => $error]; return $result; }
/** * @param $file string|\yii\web\UploadedFile * @return object * @throws InvalidConfigException */ public static function create($file) { if (is_a($file, self::className())) { return $file; } // UploadedFile if (is_a($file, UploadedFile::className())) { if ($file->error) { throw new InvalidParamException("File upload error \"{$file->error}\""); } return \Yii::createObject(['class' => self::className(), 'path' => $file->tempName, 'extension' => $file->getExtension()]); } else { return \Yii::createObject(['class' => self::className(), 'path' => FileHelper::normalizePath($file)]); } }