/**
  * Action to download a folder defined by request param "fid" as a zip file.
  *
  * @throws HttpException
  */
 public function actionDownloadZippedFolder()
 {
     // cleanup all old files
     $this->cleanup();
     // init output directory
     $outputPath = $this->getZipOutputPath();
     // check validity of currentFolder
     $currentFolder = $this->getCurrentFolder();
     if (empty($currentFolder)) {
         throw new HttpException(404, Yii::t('CfilesModule.base', 'The folder with the id %id% does not exist.', ['%id%' => (int) Yii::$app->request->get('fid')]));
     }
     // zip the current folder
     $zipTitle = $this->zipDir($currentFolder, $outputPath);
     $zipPath = $outputPath . DIRECTORY_SEPARATOR . $zipTitle;
     // check if the zip was created
     if (!file_exists($zipPath)) {
         throw new HttpException(404, Yii::t('CfilesModule.base', 'The archive could not be created.'));
     }
     // deliver the zip
     $options = ['inline' => false, 'mimeType' => FileHelper::getMimeTypeByExtension($zipPath)];
     if (!Setting::Get('useXSendfile', 'file')) {
         Yii::$app->response->sendFile($zipPath, $zipTitle, $options);
     } else {
         if (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
             // set nginx specific X-Sendfile header name
             $options['xHeader'] = 'X-Accel-Redirect';
             // make path relative to docroot
             $docroot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
             if (substr($zipPath, 0, strlen($docroot)) == $docroot) {
                 $zipPath = substr($zipPath, strlen($docroot));
             }
         }
         Yii::$app->response->xSendFile($zipPath, null, $options);
     }
 }
예제 #2
0
 public function run($url = null)
 {
     /**
      * @var ImageCache $imageCache
      */
     $imageCache = Yii::$app->get('imageCache');
     $cachedUrl = $url ?: Yii::$app->request->getUrl();
     $preg = '/^' . preg_quote(Yii::getAlias($imageCache->cacheUrl), '/') . '\\/(.*?)\\/(.*?)\\.(.*?)$/';
     if (preg_match($preg, $cachedUrl, $matches)) {
         $presetName = $matches[1];
         $imagePath = Yii::getAlias($imageCache->staticPath . DIRECTORY_SEPARATOR . $matches[2] . '.' . $matches[3]);
         $format = strtolower($matches[3]);
         if (file_exists($imagePath)) {
             try {
                 $image = $imageCache->getImage($imagePath, $presetName);
                 if ($image && $image->isValid()) {
                     if ($imageCache->actionSavesFile) {
                         $cachedPath = Yii::getAlias($imageCache->cachePath . DIRECTORY_SEPARATOR . $presetName . DIRECTORY_SEPARATOR . $matches[2] . '.' . $matches[3]);
                         //var_dump($cachedPath);
                         FileHelper::createDirectory(dirname($cachedPath));
                         $image->save($cachedPath);
                     }
                     Yii::$app->response->format = Response::FORMAT_RAW;
                     Yii::$app->getResponse()->getHeaders()->set('Pragma', 'public')->set('Expires', '0')->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')->set('Content-Transfer-Encoding', 'binary')->set('Content-type', FileHelper::getMimeTypeByExtension($imagePath));
                     return $image->get($format);
                 }
             } catch (\Exception $e) {
                 throw new BadRequestHttpException();
             }
         } else {
             throw new NotFoundHttpException();
         }
     }
     throw new BadRequestHttpException('Wrong url format!');
 }
예제 #3
0
 public function printFile($file)
 {
     Yii::$app->response->format = Response::FORMAT_RAW;
     header("Expires: " . gmdate('r', time() + 60 * 60 * 24 * 30));
     header("Last-Modified: " . gmdate('r'));
     header('Content-Type: ' . FileHelper::getMimeTypeByExtension($file, FileHelper::$mimeMagicFile));
     header("Content-Length: " . filesize($file));
     readfile($file);
 }
예제 #4
0
 public function run()
 {
     /* @var $request \yii\web\Request */
     /* @var $response \yii\web\Response */
     $request = Yii::$app->request;
     $response = Yii::$app->response;
     $reportName = $request->getQueryParam('name', $this->name);
     $outputType = $request->getQueryParam('outputType', $this->outputType);
     $params = $request->getQueryParam('params', []);
     $return = $this->report->renderReport($reportName, ['params' => $params], $outputType);
     if ($outputType != BirtReport::OUTPUT_TYPE_HTML) {
         $response->format = Response::FORMAT_RAW;
         $fileName = explode('.', $reportName, 1)[0] . '.' . $outputType;
         $mimeType = \yii\helpers\FileHelper::getMimeTypeByExtension($fileName);
         $response->setDownloadHeaders($fileName, $mimeType);
     }
     return $return;
 }
예제 #5
0
 public function validateExtension($attribute, $params)
 {
     $file = $this->{$attribute};
     $pathinfo = pathinfo(mb_strtolower($file->name, 'utf-8'));
     if (!empty($pathinfo['extension'])) {
         $extension = $pathinfo['extension'];
     } else {
         return false;
     }
     if ($this->checkExtensionByMimeType) {
         $mimeType = FileHelper::getMimeType($file->tempName, null, false);
         if ($mimeType === null) {
             return false;
         }
         if (!FileHelper::getMimeTypeByExtension($file)) {
             return false;
         }
     }
     if (!in_array($extension, $this->extensions, true)) {
         return false;
     }
     return true;
 }
예제 #6
0
 /**
  * @return string
  */
 public function actionUpload()
 {
     $magic = new Magic(['scenario' => 'many']);
     $magic->load(Yii::$app->request->post());
     $magic->files = UploadedFile::getInstances($magic, 'files');
     if ($magic->validate()) {
         foreach ($magic->files as $file) {
             $model = new Magic(['scenario' => 'one']);
             $model->load(Yii::$app->request->post());
             $model->file = $file;
             $model->label = StringHelper::basename($model->file->name, '.' . $model->file->extension);
             $model->mime = FileHelper::getMimeTypeByExtension($model->file);
             $model->setSrc();
             $model->file->saveAs($model->getSrcPath());
             if ($model->getType() == 'image') {
                 $model->setPreview();
                 Image::thumbnail($model->getSrcPath(), Magic::PREVIEW_WIDTH, Magic::PREVIEW_HEIGHT)->save($model->getPreviewPath(), ['quality' => 75]);
             }
             $model->save();
         }
     }
     return $this->display($magic);
 }
예제 #7
0
 /**
  * Download file from PHPWord instance
  * @param PHPWord $phpWord reference to phpWord
  * @param string $fileName file name
  * @param string $format file save format
  */
 public function download(PHPWord &$phpWord, $fileName, $format = 'Word2007')
 {
     if (!in_array($format, array_keys(static::$map))) {
         $format = $this->defaultFormat;
     }
     $fileName .= '.' . static::$map[$format];
     header('Content-Type: ' . FileHelper::getMimeTypeByExtension($fileName));
     header('Content-Disposition: attachment;filename="' . $fileName . '"');
     header('Cache-Control: max-age=0');
     header('Cache-Control: max-age=1');
     // If you're serving to IE 9, then the following may be needed
     // If you're serving to IE over SSL, then the following may be needed
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     // Date in the past
     header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
     // always modified
     header('Cache-Control: cache, must-revalidate');
     // HTTP/1.1
     header('Pragma: public');
     // HTTP/1.0
     $writer = IOFactory::createWriter($phpWord, $format);
     $writer->save('php://output');
     Yii::$app->end();
 }
예제 #8
0
 /**
  * Downloads a file
  */
 public function actionDownload()
 {
     // GUID of file
     $guid = Yii::$app->request->get('guid');
     // Force Download Flag
     $download = Yii::$app->request->get('download', 0);
     // Optional suffix of file (e.g. scaled variant of image)
     $suffix = Yii::$app->request->get('suffix');
     $file = File::findOne(['guid' => $guid]);
     if ($file == null) {
         throw new HttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
     }
     if (!$file->canRead()) {
         throw new HttpException(401, Yii::t('FileModule.controllers_FileController', 'Insufficient permissions!'));
     }
     $filePath = $file->getPath();
     $fileName = $file->getFilename($suffix);
     if (!file_exists($filePath . DIRECTORY_SEPARATOR . $fileName)) {
         throw new HttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
     }
     $options = ['inline' => false, 'mimeType' => FileHelper::getMimeTypeByExtension($fileName)];
     if ($download != 1 && in_array($options['mimeType'], Yii::$app->getModule('file')->inlineMimeTypes)) {
         $options['inline'] = true;
     }
     if (!Setting::Get('useXSendfile', 'file')) {
         Yii::$app->response->sendFile($filePath . DIRECTORY_SEPARATOR . $fileName, $fileName, $options);
     } else {
         if (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
             // set nginx specific X-Sendfile header name
             $options['xHeader'] = 'X-Accel-Redirect';
             // make path relative to docroot
             $docroot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
             if (substr($filePath, 0, strlen($docroot)) == $docroot) {
                 $filePath = substr($filePath, strlen($docroot));
             }
         }
         Yii::$app->response->xSendFile($filePath . DIRECTORY_SEPARATOR . $fileName, null, $options);
     }
 }
예제 #9
0
 /**
  * Sends existing file to a browser as a download using x-sendfile.
  *
  * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
  * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
  * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
  * increase in performance as the web application is allowed to terminate earlier while the webserver is
  * handling the request.
  *
  * The request is sent to the server through a special non-standard HTTP-header.
  * When the web server encounters the presence of such header it will discard all output and send the file
  * specified by that header using web server internals including all optimizations like caching-headers.
  *
  * As this header directive is non-standard different directives exists for different web servers applications:
  *
  * - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
  * - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  * - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  * - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
  * - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
  *
  * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
  * a proper xHeader should be sent.
  *
  * **Note**
  *
  * This option allows to download files that are not under web folders, and even files that are otherwise protected
  * (deny from all) like `.htaccess`.
  *
  * **Side effects**
  *
  * If this option is disabled by the web server, when this method is called a download configuration dialog
  * will open but the downloaded file will have 0 bytes.
  *
  * **Known issues**
  *
  * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
  * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
  * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
  *
  * **Example**
  *
  * ```php
  * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
  * ```
  *
  * @param string $filePath file name with full path
  * @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
  * @param array $options additional options for sending the file. The following options are supported:
  *
  *  - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
  *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  *    meaning a download dialog will pop up.
  *  - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
  *
  * @return $this the response object itself
  * @see sendFile()
  */
 public function xSendFile($filePath, $attachmentName = null, $options = [])
 {
     if ($attachmentName === null) {
         $attachmentName = basename($filePath);
     }
     if (isset($options['mimeType'])) {
         $mimeType = $options['mimeType'];
     } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
         $mimeType = 'application/octet-stream';
     }
     if (isset($options['xHeader'])) {
         $xHeader = $options['xHeader'];
     } else {
         $xHeader = 'X-Sendfile';
     }
     $disposition = empty($options['inline']) ? 'attachment' : 'inline';
     $this->getHeaders()->setDefault($xHeader, $filePath)->setDefault('Content-Type', $mimeType)->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
     $this->format = self::FORMAT_RAW;
     return $this;
 }
예제 #10
0
 /**
  * Returns MIME of the file
  * @return string
  */
 public function getImportedMime()
 {
     return FileHelper::getMimeTypeByExtension($this->file->name);
 }
 protected static function extendOptions(array $options)
 {
     $parsed_url = parse_url($options['url']);
     $headers = @get_headers($options['url'], 1);
     if (!$parsed_url || !$headers || !preg_match('/^(HTTP)(.*)(200)(.*)/i', $headers[0])) {
         $options['error'] = UPLOAD_ERR_NO_FILE;
     }
     $fname = explode('/', $parsed_url['path']);
     $options['name'] = end($fname);
     $options['baseName'] = explode('.', $options['name'], 1);
     $ext = explode('.', $options['name']);
     $options['extension'] = mb_strtolower(end($ext));
     $options['size'] = isset($headers['Content-Length']) ? $headers['Content-Length'] : 0;
     $options['type'] = isset($headers['Content-Type']) ? $headers['Content-Type'] : FileHelper::getMimeTypeByExtension($options['name']);
     return $options;
 }
예제 #12
0
 /**
  * Action to download a zip of the selected items.
  *
  * @return Ambigous <\humhub\modules\cfiles\controllers\type, string>
  */
 public function actionDownloadArchive()
 {
     if (Setting::Get('disableZipSupport', 'cfiles')) {
         throw new HttpException(404, Yii::t('CfilesModule.base', 'Archive (zip) support is not enabled.'));
     }
     $selectedItems = Yii::$app->request->post('selected');
     $items = [];
     // download selected items if there are some
     if (is_array($selectedItems)) {
         foreach ($selectedItems as $itemId) {
             $item = $this->module->getItemById($itemId);
             if ($item !== null) {
                 $items[] = $item;
             }
         }
     } else {
         // check validity of currentFolder
         $items = $this->getCurrentFolder();
         if (empty($items)) {
             throw new HttpException(404, Yii::t('CfilesModule.base', 'The folder with the id %id% does not exist.', ['%id%' => (int) Yii::$app->request->get('fid')]));
         }
     }
     // cleanup all old files
     $this->cleanup();
     // init output directory
     $outputPath = $this->getZipOutputPath();
     $zipTitle = $this->archive($items, $outputPath);
     $zipPath = $outputPath . DIRECTORY_SEPARATOR . $zipTitle;
     // check if the zip was created
     if (!file_exists($zipPath)) {
         throw new HttpException(500, Yii::t('CfilesModule.base', 'The archive could not be created.'));
     }
     // deliver the zip
     $options = ['inline' => false, 'mimeType' => FileHelper::getMimeTypeByExtension($zipPath)];
     if (!Setting::Get('useXSendfile', 'file')) {
         Yii::$app->response->sendFile($zipPath, $zipTitle, $options);
     } else {
         if (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
             // set nginx specific X-Sendfile header name
             $options['xHeader'] = 'X-Accel-Redirect';
             // make path relative to docroot
             $docroot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
             if (substr($zipPath, 0, strlen($docroot)) == $docroot) {
                 $zipPath = substr($zipPath, strlen($docroot));
             }
         }
         Yii::$app->response->xSendFile($zipPath, null, $options);
     }
 }
예제 #13
0
 /**
  * Sends existing file to a browser as a download using x-sendfile.
  *
  * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
  * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
  * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
  * increase in performance as the web application is allowed to terminate earlier while the webserver is
  * handling the request.
  *
  * The request is sent to the server through a special non-standard HTTP-header.
  * When the web server encounters the presence of such header it will discard all output and send the file
  * specified by that header using web server internals including all optimizations like caching-headers.
  *
  * As this header directive is non-standard different directives exists for different web servers applications:
  *
  * - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
  * - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  * - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  * - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
  * - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
  *
  * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
  * a proper xHeader should be sent.
  *
  * **Note**
  *
  * This option allows to download files that are not under web folders, and even files that are otherwise protected
  * (deny from all) like `.htaccess`.
  *
  * **Side effects**
  *
  * If this option is disabled by the web server, when this method is called a download configuration dialog
  * will open but the downloaded file will have 0 bytes.
  *
  * **Known issues**
  *
  * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
  * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
  * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
  *
  * **Example**
  *
  * ~~~
  * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
  * ~~~
  *
  * @param string $filePath file name with full path
  * @param string $mimeType the MIME type of the file. If null, it will be determined based on `$filePath`.
  * @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
  * @param string $xHeader the name of the x-sendfile header.
  * @return static the response object itself
  */
 public function xSendFile($filePath, $attachmentName = null, $mimeType = null, $xHeader = 'X-Sendfile')
 {
     if ($mimeType === null && ($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
         $mimeType = 'application/octet-stream';
     }
     if ($attachmentName === null) {
         $attachmentName = basename($filePath);
     }
     $this->getHeaders()->setDefault($xHeader, $filePath)->setDefault('Content-Type', $mimeType)->setDefault('Content-Disposition', "attachment; filename=\"{$attachmentName}\"");
     return $this;
 }
예제 #14
0
 public function testGetMimeTypeByExtension()
 {
     $magicFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type.php';
     $mimeTypeMap = ['txa' => 'application/json', 'txb' => 'another/mime'];
     $magicFileContent = '<?php return ' . var_export($mimeTypeMap, true) . ';';
     file_put_contents($magicFile, $magicFileContent);
     foreach ($mimeTypeMap as $extension => $mimeType) {
         $fileName = 'test.' . $extension;
         $this->assertNull(FileHelper::getMimeTypeByExtension($fileName));
         $this->assertEquals($mimeType, FileHelper::getMimeTypeByExtension($fileName, $magicFile));
     }
 }
예제 #15
0
 /**
  * Set model attributes from UploadedFile
  * @param UploadedFile $file
  * @return $this
  */
 public function setFile(UploadedFile $file)
 {
     $this->file = $file;
     $this->name = $file->name;
     if ($this->unique === true && $file->extension) {
         $this->setUriName(uniqid() . '.' . $file->extension);
     } else {
         $this->setUriName($this->name);
     }
     if (file_exists($this->filePath)) {
         $this->setUriName($file->baseName . uniqid() . '.' . $file->extension);
     }
     $this->mime = FileHelper::getMimeTypeByExtension($this->name);
     $this->size = $file->size;
     return $this;
 }
 public function render($type = null)
 {
     $fileName = $this->getTypePath($type);
     if ($fileName === false) {
         return null;
     }
     $mimeType = FileHelper::getMimeTypeByExtension($fileName);
     header('Content-type: ' . $mimeType);
     if ($type !== null) {
         if (!file_exists($fileName)) {
             $params = $this->getTypeParams($type);
             echo $this->processTypeImage($type, $params['processOn'] == self::PT_DEMAND);
         } else {
             return readfile($fileName);
         }
     } else {
         return readfile($fileName);
     }
 }
예제 #17
0
        header('HTTP/1.0 400 Bad Request');
        exit('Preset not found.');
    }
    $imagePath = Yii::getAlias($imageCache->staticPath . DIRECTORY_SEPARATOR . $matches[2] . '.' . $matches[3]);
    $format = strtolower($matches[3]);
    if (file_exists($imagePath)) {
        try {
            $image = $imageCache->getImage($imagePath, $presetName);
            if ($image && $image->isValid()) {
                $preset = $imageCache->presets[$presetName];
                $saveOptions = ArrayHelper::merge($imageCache->saveOptions, ArrayHelper::remove($preset, 'save', []));
                if ($imageCache->actionSavesFile) {
                    $cachedPath = Yii::getAlias($imageCache->cachePath . DIRECTORY_SEPARATOR . $presetName . DIRECTORY_SEPARATOR . $matches[2] . '.' . $matches[3]);
                    //var_dump($cachedPath);
                    FileHelper::createDirectory(dirname($cachedPath));
                    $image->save($cachedPath);
                }
                header('Content-type: ' . FileHelper::getMimeTypeByExtension($imagePath), true, 200);
                exit($image->get($format, $saveOptions));
            }
        } catch (Exception $e) {
            header('HTTP/1.0 400 Bad Request');
            exit($e);
        }
    } else {
        header('HTTP/1.0 404 Not Found');
        exit('Not Found');
    }
}
header('HTTP/1.0 400 Bad Request');
exit('Bad Request');
 private function fetchFiles($files, &$images, $name = 'file')
 {
     $errors = [];
     $type = Yii::$app->request->post('type');
     $type_id = Yii::$app->request->post('type_id');
     $hash = Yii::$app->request->post('hash');
     // Check access. if `$type_id` is null, then access check must be only in ConnectFileSequence behaviour
     if (!is_null($type_id)) {
         $acl = VariationHelper::getAclOfType($type);
         if (!AccessControl::checkAccess($acl, $type_id)) {
             Yii::warning('Someone trying to upload file with no access.', 'file-processor');
             return ['You have no access to perform this upload'];
         }
     }
     if (isset($files['tmp_name'])) {
         $file_temp_name = $files['tmp_name'];
         $file_real_name = basename($files['name']);
         if (is_uploaded_file($file_temp_name)) {
             $mime = FileHelper::getMimeType($file_temp_name);
             if (is_null($mime)) {
                 $mime = FileHelper::getMimeTypeByExtension($file_real_name);
             }
             if (strpos($mime, 'image') !== false) {
                 $file_dimensions = getimagesize($file_temp_name);
             } else {
                 $file_dimensions = [null, null];
             }
             // insert into db
             $model = new Uploads();
             $model->type = $type;
             $model->type_id = $type_id;
             $model->hash = $hash;
             $model->ord = Uploads::getMaxOrderValue($type, $type_id, $hash) + 1;
             $model->filename = Uploads::generateBaseFileName($file_real_name);
             $model->original = $file_real_name;
             $model->mime = $mime;
             $model->size = filesize($file_temp_name);
             $model->width = $file_dimensions[0];
             $model->height = $file_dimensions[1];
             // save model, save file and fill response array
             if ($model->save()) {
                 // load configuration
                 $config = VariationHelper::getConfigOfType($model->type);
                 $errors = array_merge($errors, $model->process($file_temp_name, $config));
                 // insert id of uploaded file into attribute in model (if needed)
                 Uploads::updateConnectedModelAttribute($config, $model->type_id, $model->id);
                 if (empty($errors)) {
                     $images[$name] = ['width' => $model->width, 'height' => $model->height, 'mime' => $model->mime, 'size' => $model->size, 'id' => $model->id, 'type' => $model->type, 'type_id' => $model->type_id, 'hash' => $model->hash, 'errors' => null];
                 } else {
                     $model->removeFile();
                 }
             } else {
                 Yii::warning('file was unable to be saved. Errors: ' . VarDumper::dumpAsString($model->getErrors()), 'file-processor');
                 array_push($errors, 'File was unable to be saved.');
             }
         } else {
             array_push($errors, 'File was unable to be uploaded.');
         }
     } else {
         foreach ($files as $name => $file) {
             $errors = array_merge($errors, $this->fetchFiles($file, $images, $name));
         }
     }
     return $errors;
 }
예제 #19
0
 public function run()
 {
     //set RAW response
     $response = Yii::$app->response;
     $response->format = Response::FORMAT_RAW;
     try {
         $imagePath = $this->imageFileInfo->getFilePath();
         $image = Image::getImagine()->open($imagePath);
         $requestThumbModel = $this->thumbRequest;
         $requestWidth = $requestThumbModel->w;
         $requestHeight = $requestThumbModel->h;
         $requestType = $requestThumbModel->t;
         $requestQuality = $requestThumbModel->q;
         $thumbSavePath = $this->thumbFileInfo->getFilePath($this->thumbDirectoryPath . DIRECTORY_SEPARATOR);
         $thumbExtension = $this->thumbFileInfo->extension;
         switch ($requestType) {
             case ThumbRequest::TYPE_CROP:
                 $this->cropImageByResize($image, $requestWidth, $requestHeight);
                 break;
             case ThumbRequest::TYPE_AUTO:
                 $this->resizeImageByAuto($image, $requestWidth, $requestHeight);
                 break;
             case ThumbRequest::TYPE_FORCE:
                 $this->resizeImageByForce($image, $requestWidth, $requestHeight);
                 break;
             default:
                 throw new Exception('Internal Error');
         }
         $image->save($thumbSavePath, ['quality' => $requestQuality]);
         if (false === chmod($thumbSavePath, $this->thumbFileChmod)) {
             throw new Exception("CHMOD {$this->thumbFileChmod}: {$thumbSavePath} FAIL.");
         }
         $response->headers->set('Content-type', FileHelper::getMimeTypeByExtension('.' . $thumbExtension));
         return $image->get($thumbExtension);
     } catch (Exception $e) {
         throw new NotFoundHttpException($e->getMessage());
     }
 }
예제 #20
0
 /**
  * Runs the action.
  * @param string $bucket name of the file source bucket
  * @param string $filename name of the file to be downloaded.
  * @return Response response.
  * @throws NotFoundHttpException if bucket or file does not exist.
  */
 public function run($bucket, $filename)
 {
     if (!$this->isBucketAllowed($bucket)) {
         throw new NotFoundHttpException("Bucket '{$bucket}' does not exist.");
     }
     $this->fileStorage = Instance::ensure($this->fileStorage, 'yii2tech\\filestorage\\StorageInterface');
     if (!$this->fileStorage->hasBucket($bucket)) {
         throw new NotFoundHttpException("Bucket '{$bucket}' does not exist.");
     }
     $bucket = $this->fileStorage->getBucket($bucket);
     if ($this->checkFileExistence && !$bucket->fileExists($filename)) {
         throw new NotFoundHttpException("File '{$filename}' does not exist at bucket '{$bucket->getName()}' does not exist.");
     }
     $response = Yii::$app->getResponse();
     $response->content = $bucket->getFileContent($filename);
     $response->format = Response::FORMAT_RAW;
     $mimeType = FileHelper::getMimeTypeByExtension($filename);
     if (empty($mimeType)) {
         $mimeType = 'application/octet-stream';
     }
     $response->getHeaders()->add('Content-Type', $mimeType);
     return $response;
 }