예제 #1
1
 /**
  * @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);
                 }
             }
         });
     }
 }
 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;
 }
 /**
  * @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);
         }
     }
 }
예제 #4
0
 /**
  * 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;
 }
 protected function clusterization()
 {
     $flattenTransitionMatrix = $this->matrix->flatten(Matrix::FLATTEN_MATRIX_BY_INDEX);
     $path = \Yii::getAlias('@runtime/transition_cluster');
     FileHelper::createDirectory($path);
     /** @var string $filename Temp file */
     $filename = tempnam($path, 'tmp');
     // Write strings to file
     $f = fopen($filename, 'w');
     foreach ($flattenTransitionMatrix as $key => $value) {
         fwrite($f, $value['source'] . "\t" . $value['target'] . "\t" . $value['value'] . PHP_EOL);
     }
     // matrix diagonal cells for consistent output
     foreach ($this->matrix->getWindowIds() as $key => $winId) {
         fwrite($f, $key . "\t" . $key . "\t" . '0' . PHP_EOL);
     }
     fclose($f);
     chmod($filename, 0666);
     // make clusters
     $cmdPath = \Yii::getAlias('@app/scikit/transition-cluster.py');
     $cmd = "python {$cmdPath} {$filename}";
     $clusterRaw = [];
     $exitCode = 0;
     $result = exec($cmd, $clusterRaw, $exitCode);
     if ($exitCode != 0) {
         return [];
         //            throw new Exception('Can\'t run cluster command. ' . $result);
     }
     unlink($filename);
     $winIdCluster = [];
     foreach ($this->matrix->getWindowIds() as $key => $winId) {
         $winIdCluster[$winId] = $clusterRaw[$key];
     }
     return $winIdCluster;
 }
예제 #6
0
 public static function clusterizeStrings(array $windows)
 {
     $path = \Yii::getAlias('@runtime/string_cluster');
     FileHelper::createDirectory($path);
     /** @var string $filename Temp file */
     $filename = tempnam($path, 'tmp');
     // Write strings to file
     $f = fopen($filename, 'w');
     foreach ($windows as $win) {
         fwrite($f, $win['title'] . PHP_EOL);
     }
     fclose($f);
     chmod($filename, 0666);
     // make clusters
     $cmdPath = \Yii::getAlias('@app/scikit/string-cluster.py');
     $cmd = "python {$cmdPath} < {$filename}";
     $clusterRaw = [];
     $exitCode = 0;
     $result = exec($cmd, $clusterRaw, $exitCode);
     if ($exitCode != 0) {
         return [];
         //            throw new Exception('Can\'t run cluster command. ' . $result);
     }
     unlink($filename);
     // Transform results
     $winIdCluster = [];
     foreach ($windows as $key => $window) {
         $winIdCluster[$window['id']] = $clusterRaw[$key];
     }
     return [$clusterRaw, $winIdCluster];
 }
예제 #7
0
파일: Image.php 프로젝트: Kulkow/mainsite
 public function upload($file = 'file', $rules = array(), $type = NULL)
 {
     $this->file = UploadedFile::getInstance($this, $file);
     if (!empty($rules)) {
         //createValidator
     }
     if ($this->validate()) {
         $this->realname = $this->file->getBaseName();
         $this->alt = $this->realname;
         $this->ext = $this->file->getExtension();
         $this->type = $type ? $type : '';
         do {
             $this->path = static::random('hexdec', 3) . '/' . static::random('hexdec', 3);
         } while (file_exists($this->_server_path('original')));
         $this->alt = urldecode($_FILES['image']['name']);
         $this->timestamp = time();
         FileHelper::createDirectory($this->_server_path(), 0775, TRUE);
         if (!file_exists($this->_server_path())) {
             exit;
         }
         $this->save();
         $this->file->saveAs($this->_server_path('original'));
         return $this->resize($this->type);
     } else {
         return $model->errors;
     }
 }
예제 #8
0
 /**
  * Закачивает файл `$_FILES['file']`
  *
  * @return string JSON Response
  *                [[
  *                    $tempUploadedFileName,
  *                    $fileName
  *                ]]
  */
 public function actionUpload()
 {
     $this->actionUpload_clearTempFolder();
     $output_dir = FileUploadMany::$uploadDirectory;
     $info = parse_url($_SERVER['HTTP_REFERER']);
     if ($info['host'] != $_SERVER['SERVER_NAME']) {
         return self::jsonError('Не тот сайт');
     }
     if (isset($_FILES['file'])) {
         $file = $_FILES['file'];
         $ret = [];
         $error = $file['error'];
         //You need to handle  both cases
         //If Any browser does not support serializing of multiple files using FormData()
         if (!is_array($file['name'])) {
             $fileName = \cs\services\UploadFolderDispatcher::generateFileName($file['name']);
             $destPathFull = Yii::getAlias($output_dir);
             FileHelper::createDirectory($destPathFull);
             $destPathFull = $destPathFull . '/' . $fileName;
             move_uploaded_file($file['tmp_name'], $destPathFull);
             $ret[] = [$fileName, $file['name']];
         } else {
             $fileCount = count($file['name']);
             $dir = Yii::getAlias($output_dir);
             for ($i = 0; $i < $fileCount; $i++) {
                 $fileName = $file['name'][$i];
                 move_uploaded_file($file['tmp_name'][$i], $dir . '/' . $fileName);
                 $ret[] = [$fileName, $file['name'][$i]];
             }
         }
         return self::jsonSuccess($ret);
     }
 }
예제 #9
0
 public function actionIndex($name, $type)
 {
     $dir = Yii::getAlias("@webroot/{$this->dir}/_{$type}/");
     if (file_exists($dir . $name)) {
         $this->printFile($dir . $name);
     }
     FileHelper::createDirectory($dir);
     $crop = 1;
     if (strpos($type, 'x') !== false) {
         list($width, $height) = explode('x', trim($type, '!^'));
         if (!$width || !$height || strpos($type, '^')) {
             $crop = 0;
         } elseif (strpos($type, '!')) {
             $crop = 2;
         }
     } else {
         $width = $height = $type;
         $crop = 0;
     }
     $fromDir = Yii::getAlias("@webroot/{$this->dir}/tmp/");
     $from = $fromDir . $name;
     if (!file_exists($from)) {
         $name = 'default.jpg';
         $fromDir = Yii::getAlias("@runtime/");
         file_put_contents($fromDir . $name, base64_decode($this->default));
     }
     $thumb = Image::thumbnail(Yii::getAlias($fromDir . $name), $width, $height, $crop);
     $thumb->save($dir . $name, ['quality' => $this->quality, 'png_compression_level' => 9]);
     $this->printFile($dir . $name);
 }
예제 #10
0
파일: File.php 프로젝트: Cranky4/qwen23
 /**
  * @return \app\modules\document\models\Attachment|bool
  * @throws \yii\base\Exception
  */
 public function upload()
 {
     if ($this->validate()) {
         $root = \Yii::getAlias('@webroot');
         $path = '/uploads/' . date('Y-m-d');
         $uploadPath = $root . $path;
         $file = $this->file;
         //check for the existence of a folder
         if (!file_exists($uploadPath)) {
             FileHelper::createDirectory($uploadPath, 0777, true);
         }
         //check for file with same name is exists
         $srcPath = $path . '/' . $file->name;
         $savePath = $uploadPath . '/' . $file->name;
         if (file_exists($savePath)) {
             $t = time();
             $savePath = $uploadPath . '/' . $t . "_" . $file->name;
             $srcPath = $path . '/' . $t . "_" . $file->name;
         }
         //move uploaded file and save it into database
         if ($file->saveAs($savePath)) {
             return Attachment::createNew($file, $srcPath);
         }
     }
     return false;
 }
예제 #11
0
 /**
  * @throws \rmrevin\yii\minify\Exception
  */
 public function init()
 {
     parent::init();
     if (php_sapi_name() !== 'cli') {
         $urlDetails = \Yii::$app->urlManager->parseRequest(\Yii::$app->request);
         if (in_array($urlDetails[0], $this->exclude_routes)) {
             $this->enableMinify = false;
         }
     }
     $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, ['extra' => true]);
                 }
                 if (!empty($Response->content)) {
                     $Response->content = HtmlCompressor::compress($Response->content, ['extra' => true]);
                 }
             }
         });
     }
 }
예제 #12
0
 public function actionInit()
 {
     $dir = Yii::getAlias('@app/rbac');
     if (!file_exists($dir)) {
         FileHelper::createDirectory($dir);
         echo 'RBAC configs dir was created.' . PHP_EOL;
     }
     /** @var BaseManager $authManager */
     $authManager = \Yii::$app->getModule('admin')->get('authManager');
     if ($this->confirm('Configure from role container?')) {
         /** @var Role[] $roles */
         $roles = \Yii::$app->getModule('admin')->get('roleContainer')->getRoles($authManager);
         foreach ($roles as $role) {
             $authManager->add($role);
         }
     } else {
         $file = Yii::getAlias('@app/config/admin_rbac.php');
         if (file_exists($file)) {
             include $file;
         } else {
             echo 'You must create file "@app/config/admin_rbac.php"' . PHP_EOL;
             //@TODO propose to create file
         }
     }
     echo 'RABC was configured' . PHP_EOL;
 }
예제 #13
0
 /**
  * Creates a new Product model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Product(['scenario' => 'create']);
     $model->date = date('Y-m-d H:i');
     if ($model->load(Yii::$app->request->post())) {
         $model->image = UploadedFile::getInstance($model, 'image');
         $model->images = UploadedFile::getInstances($model, 'images');
         if ($model->validate() && $model->save() && $model->image) {
             // Working directory
             $dir = Yii::getAlias('@frontend/web/uploads/product/' . $model->id);
             FileHelper::createDirectory($dir);
             // Save main image
             $model->image->saveAs($dir . '/main.jpg');
             // Save images
             if ($model->images) {
                 foreach ($model->images as $image) {
                     $imageModel = new Image();
                     $imageModel->model_id = $model->id;
                     $imageModel->save();
                     $image->saveAs($dir . '/' . $imageModel->id . '.jpg');
                 }
             }
         }
         return $this->redirect(['view', 'id' => $model->id]);
     }
     return $this->render('create', ['model' => $model]);
 }
 public function actionData($file = false)
 {
     \Yii::$app->response->format = Response::FORMAT_JSON;
     if (\Yii::$app->request->isPost) {
         /**@var Module $module */
         $module = Module::getInstance();
         $model = new DynamicModel(['file' => null]);
         $model->addRule('file', 'file', ['extensions' => $module->expansions, 'maxSize' => $module->maxSize]);
         $model->file = UploadedFile::getInstanceByName('image');
         if ($model->validate()) {
             if (!is_dir(\Yii::getAlias($module->uploadDir))) {
                 FileHelper::createDirectory(\Yii::getAlias($module->uploadDir));
             }
             $oldFileName = $model->file->name;
             $newFileName = $module->isFileNameUnique ? uniqid() . '.' . $model->file->extension : $oldFileName;
             $newFullFileName = \Yii::getAlias($module->uploadDir) . DIRECTORY_SEPARATOR . $newFileName;
             if ($model->file->saveAs($newFullFileName)) {
                 return ['id' => $oldFileName, 'url' => \Yii::$app->request->getHostInfo() . str_replace('@webroot', '', $module->uploadDir) . '/' . $newFileName];
             }
         } else {
             \Yii::$app->response->statusCode = 500;
             return $model->getFirstError('file');
         }
     } elseif (\Yii::$app->request->isDelete && $file) {
         return true;
     }
     throw new BadRequestHttpException();
 }
예제 #15
0
 protected function setUp()
 {
     parent::setUp();
     FileHelper::createDirectory($this->getParam('components')['assetManager']['basePath']);
     file_put_contents(__DIR__ . '/runtime/compress.html', '');
     $this->mock_application();
 }
예제 #16
0
 /**
  *  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;
 }
예제 #17
0
 /**
  * Upload file
  *
  * @access public
  * @param $attr
  * @param $name
  * @param $ext
  * @param $path
  * @param array $allowed list of allowed file types
  * @return boolean
  * @throws \yii\base\ErrorException
  */
 public function upload($attr, $name, $ext, $path, array $allowed = [])
 {
     $this->uploadErrors = [];
     $allowed = array_filter($allowed);
     $attr = str_replace('[]', '', $attr);
     $files = UploadedFile::getInstancesByName($attr);
     $uploaded = [];
     if (!$files) {
         $this->uploadErrors[] = Yii::t('app', 'Select at least one file');
         return false;
     }
     $filesCount = sizeof($files);
     foreach ($files as $file) {
         if ($filesCount > 1) {
             $name = Yii::$app->getSecurity()->generateRandomString();
         }
         if ($file->getHasError()) {
             $this->uploadErrors[] = Yii::t('app', static::$errors[$file->error]);
             continue;
         }
         if (!in_array($file->type, static::$mimeTypes)) {
             $this->uploadErrors[] = Yii::t('app', '{file} has invalid file type', ['file' => $file->baseName]);
             continue;
         }
         if ($allowed && !in_array($file->extension, $allowed)) {
             $this->uploadErrors[] = Yii::t('app', '{file} has invalid file type', ['file' => $file->baseName]);
             continue;
         }
         FileHelper::createDirectory($path);
         if ($file->saveAs($path . '/' . $name . '.' . $ext)) {
             $uploaded[] = ['path' => $path, 'name' => $name, 'ext' => $ext];
         }
     }
     return $uploaded;
 }
예제 #18
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.');
 }
예제 #19
0
 /**
  * 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);
     }
 }
 /**
  * @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]);
 }
예제 #21
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);
 }
예제 #22
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;
 }
예제 #23
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]);
 }
예제 #24
0
 /**
  * @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;
 }
예제 #25
0
 /**
  * @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);
     }
 }
예제 #26
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())));
     }
 }
예제 #27
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;
         }
     }
 }
예제 #28
-1
 /**
  * 数据库升级
  *
  * @param string $savePath 数据库保存路径
  * @return bool true 更新状态
  * @throws LocationException
  * @throws \yii\base\Exception
  */
 public function upgrade($savePath = '@wsl/ip2location/../data/qqwry.dat')
 {
     $savePath = Yii::getAlias($savePath);
     if (!FileHelper::createDirectory(dirname($savePath), 0777)) {
         throw new LocationException($savePath . ' is not write');
     }
     $copyWriteContent = file_get_contents($this->copyWriteUrl);
     $qqWryFileContent = file_get_contents($this->qqWryUrl);
     $key = ArrayHelper::getValue(unpack('V6', $copyWriteContent), 6);
     if (!$key) {
         return false;
     }
     for ($i = 0; $i < 0x200; $i++) {
         $key *= 0x805;
         $key++;
         $key = $key & 0xff;
         $qqWryFileContent[$i] = chr(ord($qqWryFileContent[$i]) ^ $key);
     }
     $qqWryFileContent = gzuncompress($qqWryFileContent);
     $fp = fopen($savePath, 'wb');
     if ($fp) {
         fwrite($fp, $qqWryFileContent);
         fclose($fp);
     }
     return true;
 }
예제 #29
-1
 /**
  * Create new unique file name
  *
  * @param UploadedFile $uploadedFile
  * @param int          $prefix
  *
  * @return string
  */
 protected function createFileName($uploadedFile, $prefix = 1)
 {
     $_fileName = time() . $prefix . '.' . $uploadedFile->getExtension();
     $uploadedFile->name = $this->path . $_fileName;
     \yii\helpers\FileHelper::createDirectory($this->path, 0775, true);
     return file_exists($uploadedFile->name) ? $this->createFileName($uploadedFile, $prefix + 1) : $_fileName;
 }
예제 #30
-2
 public function createStoreDir($event)
 {
     if ($this->owner->handler == $this->handlerName) {
         $path = $this->createHierarchyPath();
         FileHelper::createDirectory(Yii::getAlias($this->base . $path));
     }
 }