コード例 #1
2
 /**
  * Сгенерировать карту классов для автоподгрузки.
  */
 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);
 }
コード例 #2
1
ファイル: AssetConverterTest.php プロジェクト: howq/yii2
 protected function tearDown()
 {
     if (is_dir($this->tmpPath)) {
         FileHelper::removeDirectory($this->tmpPath);
     }
     parent::tearDown();
 }
コード例 #3
1
 public function tearDown()
 {
     FileHelper::removeDirectory($this->sourcePath);
     if (file_exists($this->configFileName)) {
         unlink($this->configFileName);
     }
 }
コード例 #4
1
 public function cleanAssetDir()
 {
     $now = time();
     $asset_temp_dirs = glob($this->asset_dir . '/*', GLOB_ONLYDIR);
     // check if less than want to keep
     if (count($asset_temp_dirs) <= $this->keep) {
         return 0;
     }
     // get all dirs and sort by modified
     $modified = [];
     foreach ($asset_temp_dirs as $asset_temp_dir) {
         $modified[$asset_temp_dir] = filemtime($asset_temp_dir);
     }
     asort($modified);
     $nbr_dirs = count($modified);
     // keep last dirs
     for ($i = min($nbr_dirs, $this->keep); $i > 0; $i--) {
         array_pop($modified);
     }
     if ($this->dry_run) {
         $msg_try = 'would have ';
     } else {
         $msg_try = '';
     }
     // remove dirs
     foreach ($modified as $dir => $mod) {
         $this->echo_msg($msg_try . 'removed ' . $dir . ', last modified ' . Yii::$app->formatter->asDatetime($mod));
         if (!$this->dry_run) {
             FileHelper::removeDirectory($dir);
         }
     }
     return $this->dry_run ? 0 : $nbr_dirs;
 }
コード例 #5
1
 public function tearDown()
 {
     $filePath = $this->getTestFilePath();
     if (file_exists($filePath)) {
         FileHelper::removeDirectory($filePath);
     }
 }
コード例 #6
1
ファイル: View.php プロジェクト: audriusdob/yii2-minify-view
 /**
  * @throws \rmrevin\yii\minify\Exception
  */
 public function init()
 {
     parent::init();
     $minify_path = $this->minify_path = (string) \Yii::getAlias($this->minify_path);
     if (!file_exists($minify_path)) {
         helpers\FileHelper::createDirectory($minify_path);
     }
     if (!is_readable($minify_path)) {
         throw new Exception('Directory for compressed assets is not readable.');
     }
     if (!is_writable($minify_path)) {
         throw new Exception('Directory for compressed assets is not writable.');
     }
     if (true === $this->compress_output) {
         \Yii::$app->response->on(\yii\web\Response::EVENT_BEFORE_SEND, function (\yii\base\Event $Event) {
             /** @var \yii\web\Response $Response */
             $Response = $Event->sender;
             if ($Response->format === \yii\web\Response::FORMAT_HTML) {
                 if (!empty($Response->data)) {
                     $Response->data = HtmlCompressor::compress($Response->data, $this->compress_options);
                 }
                 if (!empty($Response->content)) {
                     $Response->content = HtmlCompressor::compress($Response->content, $this->compress_options);
                 }
             }
         });
     }
 }
コード例 #7
0
ファイル: MigrateTrait.php プロジェクト: deesoft/yii2-console
 /**
  * @return array all directories
  */
 protected function getDirectories()
 {
     if ($this->_paths === null) {
         $paths = ArrayHelper::getValue(Yii::$app->params, $this->paramVar, []);
         $paths = array_merge($paths, $this->migrationLookup);
         $extra = !empty($this->extraFile) && is_file($this->extraFile = Yii::getAlias($this->extraFile)) ? require $this->extraFile : [];
         $paths = array_merge($extra, $paths);
         $p = [];
         foreach ($paths as $path) {
             $p[Yii::getAlias($path, false)] = true;
         }
         unset($p[false]);
         $currentPath = Yii::getAlias($this->migrationPath);
         if (!isset($p[$currentPath])) {
             $p[$currentPath] = true;
             if (!empty($this->extraFile)) {
                 $extra[] = $this->migrationPath;
                 FileHelper::createDirectory(dirname($this->extraFile));
                 file_put_contents($this->extraFile, "<?php\nreturn " . VarDumper::export($extra) . ";\n", LOCK_EX);
             }
         }
         $this->_paths = array_keys($p);
         foreach ($this->migrationNamespaces as $namespace) {
             $path = str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace)));
             $this->_paths[$namespace] = $path;
         }
     }
     return $this->_paths;
 }
コード例 #8
0
 public function actionIndex()
 {
     $src = DOCGEN_PATH . '/swagger-ui/';
     $dst = Yii::getAlias('@app') . '/web/apidoc/';
     FileHelper::copyDirectory($src, $dst);
     return Controller::EXIT_CODE_NORMAL;
 }
コード例 #9
0
ファイル: Theme.php プロジェクト: sheillendra/yii2-theme
 /**
  * @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;
 }
コード例 #10
0
ファイル: TestCase.php プロジェクト: rmrevin/yii2-file
 protected function tearDown()
 {
     parent::tearDown();
     FileHelper::removeDirectory(\Yii::$app->getModule('file')->upload_path);
     FileHelper::removeDirectory(\Yii::$app->getModule('file')->storage_path);
     $this->destroyApplication();
 }
コード例 #11
0
 public function init()
 {
     parent::init();
     $extJsSrcDir = Yii::getAlias($this->extJsDir);
     $extJsSrcExtendDir = Yii::getAlias($this->extJsExtendDir);
     $dstDir = Yii::getAlias($this->dstPath);
     $extJsDstDir = $dstDir . DIRECTORY_SEPARATOR . 'extjs';
     $extJsExtendDstDir = $dstDir . DIRECTORY_SEPARATOR . 'extjs-extend';
     if (!is_dir($dstDir)) {
         if (!is_dir($dstDir)) {
             FileHelper::createDirectory($dstDir);
         }
     }
     if (!is_dir($extJsDstDir)) {
         symlink($extJsSrcDir, $extJsDstDir);
     }
     if (!is_dir($extJsExtendDstDir)) {
         symlink($extJsSrcExtendDir, $extJsExtendDstDir);
     }
     $data = DpConfig::find()->all();
     $config = [];
     foreach ($data as $item) {
         $config[$item['name']] = $item['value'];
     }
     $this->config = $config;
     $this->identity = Yii::$app->user->identity;
 }
コード例 #12
0
ファイル: BaseApplication.php プロジェクト: huasxin/lulucms2
 public function loadActiveModules($isAdmin)
 {
     $moduleManager = LuLu::getService('modularityService');
     
     $this->activeModules = $moduleManager->getActiveModules($isAdmin);
     
     $module = $isAdmin ? 'AdminModule' : 'HomeModule';
     foreach ($this->activeModules as $m)
     {
         $moduleId = $m['id'];
         $moduleDir = $m['dir'];
         $ModuleClassName = $m['dir_class'];
         
         $this->setModule($moduleId, [
             'class' => 'source\modules\\' . $moduleDir . '\\' . $module
         ]);
         
         
         $serviceFile= LuLu::getAlias('@source').'\modules\\' .$moduleDir.'\\'.$ModuleClassName.'Service.php';
         
         if(FileHelper::exist($serviceFile))
         {
             $serviceClass = 'source\modules\\' .$moduleDir.'\\'.$ModuleClassName.'Service.php';
             $serviceInstance = new $serviceClass();
             $this->set($serviceInstance->getServiceId(), $serviceInstance);
         }
     }
 }
コード例 #13
0
 /**
  * @hass-todo 没有添加事务
  * @return string
  */
 public function actionIndex()
 {
     $model = new MigrationUtility();
     $upStr = new OutputString();
     $downStr = new OutputString();
     if ($model->load(\Yii::$app->getRequest()->post())) {
         if (!empty($model->tableSchemas)) {
             list($up, $down) = $this->generalTableSchemas($model->tableSchemas, $model->tableOption, $model->foreignKeyOnUpdate, $model->foreignKeyOnDelete);
             $upStr->outputStringArray = array_merge($upStr->outputStringArray, $up->outputStringArray);
             $downStr->outputStringArray = array_merge($downStr->outputStringArray, $down->outputStringArray);
         }
         if (!empty($model->tableDatas)) {
             list($up, $down) = $this->generalTableDatas($model->tableDatas);
             $upStr->outputStringArray = array_merge($upStr->outputStringArray, $up->outputStringArray);
             $downStr->outputStringArray = array_merge($downStr->outputStringArray, $down->outputStringArray);
         }
         $path = Yii::getAlias($model->migrationPath);
         if (!is_dir($path)) {
             FileHelper::createDirectory($path);
         }
         $name = 'm' . gmdate('ymd_His') . '_' . $model->migrationName;
         $file = $path . DIRECTORY_SEPARATOR . $name . '.php';
         $content = $this->renderFile(Yii::getAlias("@hass/migration/views/migration.php"), ['className' => $name, 'up' => $upStr->output(), 'down' => $downStr->output()]);
         file_put_contents($file, $content);
         $this->flash("success", "迁移成功,保存在" . $file);
     }
     if ($model->migrationPath == null) {
         $model->migrationPath = $this->module->migrationPath;
     }
     return $this->render('index', ['model' => $model]);
 }
コード例 #14
0
 public function actionIndex()
 {
     $file = UploadedFile::getInstanceByName('imgFile');
     $basePath = dirname(\Yii::getAlias('@common'));
     $date = date("Y{$this->separator}m", time());
     $uploadPath = "../uploads/Attachment/{$date}";
     if (!is_dir($basePath . "/" . $uploadPath)) {
         FileHelper::createDirectory($basePath . "/" . $uploadPath);
     }
     if (preg_match('/(\\.[\\S\\s]+)$/', $file->name, $match)) {
         $filename = md5(uniqid(rand())) . $match[1];
     } else {
         $filename = $file->name;
     }
     $uploadData = ['type' => $file->type, 'name' => $filename, 'size' => $file->size, 'path' => "/" . $uploadPath, 'module' => null, 'controller' => null, 'action' => null, 'user_id' => \Yii::$app->user->isGuest ? 0 : \Yii::$app->user->identity->id];
     $module = \Yii::$app->controller->module;
     Upload::$db = $module->db;
     $model = new Upload();
     $model->setAttributes($uploadData);
     $model->validate();
     if ($model->save() && $file->saveAs($basePath . '/' . $uploadPath . '/' . $filename)) {
         return Json::encode(array('error' => 0, 'url' => "/" . $uploadPath . '/' . $filename, 'id' => $model->id, 'name' => $file->name));
     } else {
         return Json::encode(array('error' => 1, 'msg' => Json::encode($model->getErrors())));
     }
 }
コード例 #15
0
 public function init()
 {
     if (!isset($this->runtimePath)) {
         $this->runtimePath = Yii::$app->runtimePath;
     }
     $this->configFile = $this->runtimePath . '/halo/active-plugins.php';
     if (!is_dir(dirname($this->configFile))) {
         FileHelper::createDirectory(dirname($this->configFile));
     }
     if (file_exists($this->configFile)) {
         $this->_activePlugins = (require $this->configFile);
     } else {
         $this->_activePlugins = [];
     }
     foreach (glob($this->pluginPath . '/*', GLOB_ONLYDIR) as $vendorPath) {
         foreach (glob($vendorPath . '/*', GLOB_ONLYDIR) as $pluginPath) {
             $pluginInfoFile = $pluginPath . '/plugin.json';
             if (!is_file($pluginInfoFile)) {
                 // not plugin
                 continue;
             }
             $pluginId = basename($vendorPath) . '.' . basename($pluginPath);
             $pluginInfo = json_decode(file_get_contents($pluginInfoFile), true);
             if ($pluginInfo === null) {
                 // something wrong, can not read plugin.json
                 continue;
             }
             $this->_availablePlugins[$pluginId] = $pluginInfo;
         }
     }
 }
コード例 #16
0
 /**
  * @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;
 }
コード例 #17
0
 /**
  * (non-PHPdoc)
  * EXTRA: 
  * @see \yii\web\AssetManager::publishDirectory()
  * 
  *  [const-dir] contain directory name or empty if copy current asset directly to base assets' dir 
  */
 public function publishDirectory($src, $options)
 {
     throw new \yii\base\Exception('works but block support until it will be required. skip testing purpose');
     // default behavior with hashed dir
     if (!isset($options['const-dir'])) {
         return parent::publishDirectory($src, $options);
     }
     //
     // my custom : don't generate random dir, instead, use custom if set
     //
     $dstDir = $this->basePath . (!empty($options['const-dir']) ? '/' . $options['const-dir'] : '');
     //dont copy if already was copied
     // TODO: add datetime checks
     if (file_exists($dstDir)) {
         return [$dstDir, $this->baseUrl];
     }
     // A. copy only subdirs if set
     if (!empty($options['sub-dirs']) && is_array($options['sub-dirs'])) {
         foreach ($options['sub-dirs'] as $subdir) {
             if (is_dir($src . '/' . $subdir)) {
                 FileHelper::copyDirectory($src . '/' . $subdir, $dstDir . '/' . $subdir, ['dirMode' => $this->dirMode, 'fileMode' => $this->fileMode, 'beforeCopy' => @$options['beforeCopy'], 'afterCopy' => @$options['afterCopy'], 'forceCopy' => @$options['forceCopy']]);
             }
             //TODO: else write error log
         }
     } else {
         //copy whole dir
         FileHelper::copyDirectory($src, $dstDir, ['dirMode' => $this->dirMode, 'fileMode' => $this->fileMode, 'beforeCopy' => @$options['beforeCopy'], 'afterCopy' => @$options['afterCopy'], 'forceCopy' => @$options['forceCopy']]);
     }
     return [$dstDir, $this->baseUrl];
 }
コード例 #18
0
ファイル: UploadForm.php プロジェクト: kd-brinex/kd
 public function getText()
 {
     $file = FileHelper::localize($this->textFile);
     //        FileHelper::getMimeType()
     $f = file('uploads/' . $file->name);
     return $f;
 }
コード例 #19
0
 public function up()
 {
     // Creates folders for media manager
     $webroot = Yii::getAlias('@app/web');
     foreach (['upload', 'files'] as $folder) {
         $path = $webroot . '/' . $folder;
         if (!file_exists($path)) {
             echo "mkdir('{$path}', 0777)...";
             if (mkdir($path, 0777, true)) {
                 echo "done.\n";
             } else {
                 echo "failed.\n";
             }
         }
     }
     // Creates the default platform config
     /** @var \gromver\platform\basic\console\modules\main\Module $main */
     $cmf = Yii::$app->grom;
     $paramsPath = Yii::getAlias($cmf->paramsPath);
     $paramsFile = $paramsPath . DIRECTORY_SEPARATOR . 'params.php';
     $params = $cmf->params;
     $model = new \gromver\models\ObjectModel(\gromver\platform\basic\modules\main\models\PlatformParams::className());
     $model->setAttributes($params);
     echo 'Setup application config: ' . PHP_EOL;
     $this->readStdinUser('Site Name (My Site)', $model, 'siteName', 'My Site');
     $this->readStdinUser('Admin Email (admin@email.com)', $model, 'adminEmail', '*****@*****.**');
     $this->readStdinUser('Support Email (support@email.com)', $model, 'supportEmail', '*****@*****.**');
     if ($model->validate()) {
         \yii\helpers\FileHelper::createDirectory($paramsPath);
         file_put_contents($paramsFile, '<?php return ' . var_export($model->toArray(), true) . ';');
         @chmod($paramsFile, 0777);
     }
     echo 'Setup complete.' . PHP_EOL;
 }
コード例 #20
0
 /**
  * @param integer $id
  * @return mixed
  */
 public function actionFiles($id, $id_parent = null)
 {
     $model = $this->findModel($id);
     $files = Module::getInst()->files;
     $startPath = '';
     if (!isset($files[$model->type])) {
         throw new InvalidConfigException('The "files" property for type(' . $model->type . ') must be set.');
     }
     if (isset($files[$model->type]['startPath'])) {
         $startPath = strtr($files[$model->type]['startPath'], ['{id}' => $model->id]);
     }
     foreach ($files[$model->type]['dirs'] as $path) {
         $dir = Yii::getAlias(strtr($path, ['{id}' => $model->id]));
         \yii\helpers\FileHelper::createDirectory($dir);
     }
     if (!$id_parent) {
         $id_parent = 0;
     }
     $elfinderData = [];
     //for https://github.com/pavlinter/yii2-adm-app
     $elfinderData['w'] = isset($files[$model->type]['maxWidth']) ? $files[$model->type]['maxWidth'] : 0;
     $elfinderData['h'] = isset($files[$model->type]['maxHeight']) ? $files[$model->type]['maxWidth'] : 0;
     $elfinderData['watermark'] = isset($files[$model->type]['watermark']) && $files[$model->type]['watermark'] ? 1 : 0;
     return $this->render('files', ['model' => $model, 'startPath' => $startPath, 'id_parent' => $id_parent, 'elfinderData' => $elfinderData]);
 }
コード例 #21
0
ファイル: MessageController.php プロジェクト: freddykr/humhub
 /**
  * @inheritdoc
  */
 protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
 {
     $dirNameBase = $dirName;
     foreach ($messages as $category => $msgs) {
         /**
          * Fix Directory
          */
         $module = $this->getModuleByCategory($category);
         if ($module !== null) {
             // Use Module Directory
             $dirName = str_replace(Yii::getAlias("@humhub/messages"), $module->getBasePath() . '/messages', $dirNameBase);
             preg_match('/.*?Module\\.(.*)/', $category, $result);
             $category = $result[1];
         } else {
             // Use Standard HumHub Directory
             $dirName = $dirNameBase;
         }
         $file = str_replace("\\", '/', "{$dirName}/{$category}.php");
         $path = dirname($file);
         FileHelper::createDirectory($path);
         $msgs = array_values(array_unique($msgs));
         $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
         $this->stdout("Saving messages to {$coloredFileName}...\n");
         $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
     }
 }
コード例 #22
0
 /**
  * @return string
  * @throws \yii\base\Exception
  */
 public function actionCropImg()
 {
     $path = Cloud::getInstance()->cloudPath;
     $pathWeb = Cloud::getInstance()->webCloudPath;
     FileHelper::createDirectory($path);
     $filename = basename(Yii::$app->request->post('imgUrl'));
     // original sizes
     $imgInitW = Yii::$app->request->post('imgInitW');
     $imgInitH = Yii::$app->request->post('imgInitH');
     // resized sizes
     $imgW = Yii::$app->request->post('imgW');
     $imgH = Yii::$app->request->post('imgH');
     // offsets
     $imgX1 = Yii::$app->request->post('imgX1');
     $imgY1 = Yii::$app->request->post('imgY1');
     // crop box
     $cropW = Yii::$app->request->post('cropW');
     $cropH = Yii::$app->request->post('cropH');
     // rotation angle
     $angle = Yii::$app->request->post('rotation');
     $originalImage = Image::getImagine()->open($path . $filename);
     $cropFilename = strtr($filename, ['big_' => 'crop_']);
     $originalImage->resize(new Box($imgW, $imgH))->rotate($angle)->crop(new Point($imgX1, $imgY1), new Box($cropW, $cropH));
     $originalImage->save($path . $cropFilename);
     if (strpos($filename, 'big_') === 0) {
         unlink($path . $filename);
     }
     $json['status'] = 'success';
     $json['url'] = Url::to($pathWeb . $cropFilename, true);
     return Json::encode($json);
 }
コード例 #23
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     if ($this->path === null) {
         throw new InvalidConfigException("Empty \"{$this->path}\".");
     }
     $this->path = FileHelper::normalizePath($this->path) . DIRECTORY_SEPARATOR;
 }
コード例 #24
0
ファイル: TempFile.php プロジェクト: yii2tech/html2pdf
 /**
  * Prepares raw destination file name for the file copy/move operation:
  * resolves path alias and creates missing directories.
  * @param string $destinationFileName destination file name
  * @return string real destination file name
  */
 protected function prepareDestinationFileName($destinationFileName)
 {
     $destinationFileName = Yii::getAlias($destinationFileName);
     $destinationPath = dirname($destinationFileName);
     FileHelper::createDirectory($destinationPath);
     return $destinationFileName;
 }
コード例 #25
0
 /**
  * @return string
  */
 public function actionUpload()
 {
     /* @var Cloud*/
     $cloud = Cloud::getInst();
     $path = $cloud->storage->getPath();
     $uploader = new UploadHandler();
     FileHelper::createDirectory($path);
     // Specify the list of valid extensions, ex. array("jpeg", "xml", "bmp")
     $uploader->allowedExtensions = [];
     // all files types allowed by default
     // Specify max file size in bytes.
     $uploader->sizeLimit = 20 * 1024 * 1024;
     // default is 10 MiB
     $method = Yii::$app->request->getMethod();
     if ($method == "POST") {
         // Assumes you have a chunking.success.endpoint set to point here with a query parameter of "done".
         // For example: /myserver/handlers/endpoint.php?done
         if (isset($_GET["done"])) {
             $result = $uploader->combineChunks($path);
         } else {
             // Call handleUpload() with the name of the folder, relative to PHP's getcwd()
             $result = $uploader->handleUpload($path, uniqid());
             // To return a name used for uploaded file you can use the following line.
             $result["uploadName"] = $uploader->getUploadName();
         }
         return Json::encode($result);
     } else {
         if ($method == "DELETE") {
             $result = $uploader->handleDelete($path);
             return Json::encode($result);
         }
     }
 }
コード例 #26
0
ファイル: ImageHelper.php プロジェクト: rocketyang/admap
 /**
  *  fetch image from protected location and manipulate it and copy to public folder to show in front-end
  *  This function cache the fetched image with same width and height before
  * 
  * @author A.Jafaripur <*****@*****.**>
  * 
  * @param integer $id image id number to seprate the folder in public folder
  * @param string $path original image path
  * @param float $width width of image for resize
  * @param float $heigh height of image for resize
  * @param integer $quality quality of output image
  * @return string fetched image url
  */
 public function getImage($id, $path, $width, $heigh, $quality = 70)
 {
     $fileName = $this->getFileName(Yii::getAlias($path));
     $fileNameWithoutExt = $this->getFileNameWithoutExtension($fileName);
     $ext = $this->getFileExtension($fileName);
     if ($width == 0 && $heigh == 0) {
         $size = Image::getImagine()->open($path)->getSize();
         $width = $size->getWidth();
         $heigh = $size->getHeight();
     }
     $newFileName = $fileNameWithoutExt . 'x' . $width . 'w' . $heigh . 'h' . '.' . $ext;
     $upload_number = (int) ($id / 2000) + 1;
     $savePath = Yii::getAlias('@webroot/images/' . $upload_number);
     $baseImageUrl = Yii::$app->getRequest()->getBaseUrl() . '/images/' . $upload_number;
     FileHelper::createDirectory($savePath);
     $savePath .= DIRECTORY_SEPARATOR . $newFileName;
     if ($width == 0 && $heigh == 0) {
         copy($path, $savePath);
     } else {
         if (!file_exists($savePath)) {
             Image::thumbnail($path, $width, $heigh)->interlace(\Imagine\Image\ImageInterface::INTERLACE_PLANE)->save($savePath, ['quality' => $quality]);
         }
     }
     return $baseImageUrl . '/' . $newFileName;
 }
コード例 #27
0
 public function itemList($options = [])
 {
     $session = Yii::$app->session;
     $moduleId = Yii::$app->controller->module->id;
     if (isset($options['sub-directory'])) {
         $session->set($moduleId, ['path' => '/' . ltrim($options['sub-directory'], '/')]);
     }
     //$session->remove($moduleId);
     $dir = $this->routes->uploadDir . $session->get($moduleId)['path'];
     if (is_dir($dir)) {
         //echo $dir;
         $files = \yii\helpers\FileHelper::findFiles($dir, ['recursive' => false]);
         $files_r = [];
         if (!isset($options['show-directory']) || intval($options['show-directory']) === 1) {
             foreach (glob($dir . '/*', GLOB_ONLYDIR) as $filename) {
                 $files_r[] = $filename;
             }
         }
         foreach ($files as $value) {
             $files_r[] = str_replace('\\', '/', $value);
         }
     } else {
         $message = 'Path ' . $session->get($moduleId)['path'] . ' not found!.';
         $session->remove($moduleId);
         throw new \yii\web\HttpException(500, $message);
     }
     return $files_r;
 }
コード例 #28
0
ファイル: FileMutex.php プロジェクト: nanodesu88/yii2
 /**
  * Initializes mutex component implementation dedicated for UNIX, GNU/Linux, Mac OS X, and other UNIX-like
  * operating systems.
  * @throws InvalidConfigException
  */
 public function init()
 {
     $this->mutexPath = Yii::getAlias($this->mutexPath);
     if (!is_dir($this->mutexPath)) {
         FileHelper::createDirectory($this->mutexPath, $this->dirMode, true);
     }
 }
コード例 #29
0
 public function actionIndex()
 {
     $error = false;
     @chdir(Yii::getAlias('@app'));
     foreach ($this->folders as $folder => $writable) {
         if (!file_exists($folder)) {
             $mode = $writable ? 0777 : 0775;
             if (FileHelper::createDirectory($folder, $mode)) {
                 $this->outputSuccess("{$folder}: successfully created directory");
             } else {
                 $error = true;
                 $this->outputError("{$folder}: unable to create directory");
             }
         } else {
             $this->outputSuccess("{$folder}: directory exists");
         }
         if ($writable) {
             if (!is_writable($folder)) {
                 $error = true;
                 $this->outputError("{$folder}: is not writable, please change permissions.");
             }
         }
     }
     foreach ($this->files as $file) {
         if (file_exists($file)) {
             $this->outputSuccess("{$file}: file exists.");
         } else {
             $error = true;
             $this->outputError("{$file}: file does not exists!");
         }
     }
     return $error ? $this->outputError('Health check found errors!') : $this->outputSuccess('O.K.');
 }
コード例 #30
-2
 public function createStoreDir($event)
 {
     if ($this->owner->handler == $this->handlerName) {
         $path = $this->createHierarchyPath();
         FileHelper::createDirectory(Yii::getAlias($this->base . $path));
     }
 }