Example #1
0
 /**
  * Renders a view with a layout.
  * @param string $layout name of the view to be rendered.
  * @param array $placeholders list placeholders.
  * @param string $defaultPathLayout
  * @param bool $isAjax
  * @return string the rendering result. Null if the rendering result is not required.
  * @throws \Exception
  */
 public function render($layout, array $placeholders = [], $defaultPathLayout = '@views', $isAjax = false)
 {
     $layout = FileHelper::normalizePath(Alias::getAlias($layout));
     if (!strstr($layout, DS)) {
         $class = explode('\\', get_class($this));
         $layout = Alias::getAlias($defaultPathLayout) . DS . 'layouts' . DS . strtolower(str_replace('Controller', '', array_pop($class))) . DS . $layout;
     }
     return $this->getTemplate()->render($layout, $placeholders, $this, $isAjax);
 }
Example #2
0
 public function __construct($min = null, $max = null, $inclusive = false, $config = [])
 {
     parent::__construct($config);
     if (!is_null($min) && !is_null($max) && $min > $max) {
         throw new ValidateException(sprintf('%s cannot be less than  %s for validation', $min, $max));
     }
     $this->params['minValue'] = \rock\helpers\FileHelper::sizeToBytes($min);
     $this->params['maxValue'] = \rock\helpers\FileHelper::sizeToBytes($max);
     $this->params['inclusive'] = $inclusive;
 }
Example #3
0
 /**
  * @inheritdoc
  */
 public function validate($input)
 {
     if ($input instanceof UploadedFile) {
         if ($input->error !== UPLOAD_ERR_OK) {
             $this->params['mimeTypes'] = $this->toString($this->params['mimeTypes']);
             return false;
         }
         $input = $input->tempName;
     }
     if (in_array(\rock\helpers\FileHelper::getMimeType($input), $this->toArray($this->params['mimeTypes']), true)) {
         return true;
     }
     if (is_array($this->params['mimeTypes'])) {
         $this->params['mimeTypes'] = $this->toString($this->params['mimeTypes']);
     }
     return false;
 }
Example #4
0
 public function get()
 {
     if (!($dataImage = $this->captcha->get())) {
         return '#';
     }
     if ($dataImage['mime_type'] === 'image/x-png') {
         $ext = '.png';
     } elseif ($dataImage['mime_type'] === 'image/jpeg') {
         $ext = '.jpg';
     } else {
         $ext = '.gif';
     }
     $uniq = uniqid();
     $path = Alias::getAlias('@assets') . DS . 'cache' . DS . 'captcha' . DS . $uniq . $ext;
     if (FileHelper::create($path, $dataImage['image'])) {
         return Alias::getAlias('@web') . '/cache/captcha/' . $uniq . $ext;
     }
     return '#';
 }
Example #5
0
 /**
  * @inheritdoc
  */
 public function validate($input)
 {
     if ($input instanceof UploadedFile) {
         if ($input->error !== UPLOAD_ERR_OK) {
             $this->params['extensions'] = $this->toString($this->params['extensions']);
             return false;
         }
         $extension = mb_strtolower($input->extension, 'utf-8');
         $input = $input->tempName;
     } elseif (is_string($input)) {
         if (!($extension = strtolower(pathinfo($input, PATHINFO_EXTENSION)))) {
             $this->params['extensions'] = $this->toString($this->params['extensions']);
             return false;
         }
         //$extension = $extension['extension'];
     } else {
         throw new ValidateException(ValidateException::UNKNOWN_VAR, ['name' => 'input']);
     }
     if ($this->params['checkExtensionByMimeType']) {
         $mimeType = \rock\helpers\FileHelper::getMimeType($input);
         if ($mimeType === null) {
             $this->params['extensions'] = $this->toString($this->params['extensions']);
             return false;
         }
         $extensionsByMimeType = \rock\helpers\FileHelper::getExtensionsByMimeType($mimeType);
         if (!in_array($extension, $extensionsByMimeType, true)) {
             $this->params['extensions'] = $this->toString($this->params['extensions']);
             return false;
         }
     }
     if (!in_array($extension, $this->toArray($this->params['extensions']), true)) {
         $this->params['extensions'] = $this->toString($this->params['extensions']);
         return false;
     }
     return true;
 }
Example #6
0
 /**
  * Normalize path.
  * @param string $path
  * @return string
  * @throws TemplateException
  * @throws \Exception
  */
 protected function normalizePath($path)
 {
     $path = Alias::getAlias($path, ['lang' => $this->locale]);
     $path = FileHelper::normalizePath($path, DIRECTORY_SEPARATOR, false);
     if (!pathinfo($path, PATHINFO_EXTENSION)) {
         $path .= '.' . $this->defaultExtension;
     }
     $normalizePath = $path;
     // relative path
     if ((strpos($normalizePath, DIRECTORY_SEPARATOR) === false || strpos($normalizePath, '.' . DIRECTORY_SEPARATOR) !== false) && $this->path) {
         $normalizePath = dirname($this->path) . DIRECTORY_SEPARATOR . $normalizePath;
         $normalizePath = realpath($normalizePath);
     }
     if (!file_exists($normalizePath)) {
         throw new TemplateException(TemplateException::UNKNOWN_FILE, ['path' => $path]);
     }
     return $normalizePath;
 }
Example #7
0
 /**
  * Creates UploadedFile instances from $_FILE recursively.
  * @param string $key key for identifying uploaded file: class name and sub-array indexes
  * @param mixed $names file names provided by PHP
  * @param mixed $tempNames temporary file names provided by PHP
  * @param mixed $types file types provided by PHP
  * @param mixed $sizes file sizes provided by PHP
  * @param mixed $errors uploading issues provided by PHP
  */
 private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors)
 {
     if (is_array($names)) {
         foreach ($names as $i => $name) {
             self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
         }
     } else {
         $config = ['class' => static::className(), 'name' => $names, 'tempName' => $tempNames, 'type' => $types, 'size' => FileHelper::fixedIntegerOverflow($sizes), 'error' => $errors];
         self::$_files[$key] = static::getSelfInstance($config);
     }
 }
Example #8
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
  * Rock::$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 static the response object itself
  */
 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', "{$disposition}; filename=\"{$attachmentName}\"");
     return $this;
 }
Example #9
0
 public function __construct($minValue, $inclusive = false, $config = [])
 {
     parent::__construct($config);
     $this->params['minValue'] = FileHelper::sizeToBytes($minValue);
     $this->params['inclusive'] = $inclusive;
 }
Example #10
0
File: Log.php Project: romeoz/rock
 protected function defaultHandlers()
 {
     $path = $path = Alias::getAlias('@runtime/logs');
     FileHelper::createDirectory($path);
     $paths = [self::DEBUG => "{$path}/debug.log", self::INFO => "{$path}/info.log", self::NOTICE => "{$path}/error.log", self::WARNING => "{$path}/error.log", self::ERROR => "{$path}/error.log", self::CRITICAL => "{$path}/error.log", self::ALERT => "{$path}/error.log", self::EMERGENCY => "{$path}/error.log"];
     $formatter = new LineFormatter("[%datetime%]\t%level_name%\t%extra.hash%\t%message%\t%extra.user_id%\t%extra.user_ip%\t%extra.user_agent%\n");
     $this->logger->pushProcessor(function ($record) {
         $record['extra']['hash'] = substr(md5($record['message']), -6);
         $record['extra']['user_agent'] = strip_tags($_SERVER['HTTP_USER_AGENT']);
         $record['extra']['user_ip'] = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
         $record['extra']['user_id'] = isset($_SESSION['user']['id']) ? $_SESSION['user']['id'] : 'NULL';
         return $record;
     });
     $handlers = [];
     foreach ($paths as $level => $path) {
         $handlers[$level] = (new StreamHandler($path, $level, false))->setFormatter($formatter);
     }
     return $handlers;
 }
Example #11
0
 public function __construct($maxValue = null, $inclusive = false, $config = [])
 {
     parent::__construct($config);
     $this->params['maxValue'] = class_exists('rock\\file\\UploadedFile') ? UploadedFile::getSizeLimit($maxValue) : FileHelper::sizeToBytes(ini_get('upload_max_filesize'));
     $this->params['inclusive'] = $inclusive;
 }
Example #12
0
 /**
  * Create file
  *
  * @param string $path
  * @param string $value
  * @return bool
  */
 protected function createFile($path, $value)
 {
     return FileHelper::create($path, "<?php\n" . $value, LOCK_EX);
 }
Example #13
0
 /**
  * Get a file's metadata
  *
  * ```php
  * getMetadata('cache/file.tmp')
  * getMetadata('~/file.tmp$/')
  * ```
  *
  * @param  string $path path to file or regexp pattern
  * @return array|false           file metadata or FALSE when fails
  *                               to fetch it from existing file
  */
 public function getMetadata($path)
 {
     if (StringHelper::isRegexp($path) && !($path = $this->searchByPattern($path))) {
         return false;
     }
     try {
         if ($metadata = parent::getMetadata($path)) {
             if (!isset($metadata['dirname'])) {
                 $metadata['dirname'] = FileHelper::dirname($metadata['path']);
             }
             if (!isset($metadata['basename'])) {
                 $metadata['basename'] = FileHelper::basename($metadata['path']);
             }
         }
         return $metadata;
     } catch (\Exception $e) {
         $this->errors[] = $e->getMessage();
     }
     return false;
 }