Example #1
0
 public function action_download()
 {
     $id = $this->request->param('id');
     $document = ORM::factory('document', $id);
     $path = UPLOAD_PATH;
     $filename = $path . $document->name;
     if (!file_exists($filename) || file_exists($filename) && is_dir($filename)) {
         Request::current()->redirect('error/not_found');
     }
     if (!$document->is_allowed()) {
         Request::current()->redirect('error/access_denied');
     }
     $download_name = str_replace(substr(basename($filename), 0, 13), '', basename($filename));
     //to remove the uniqid prepended to the filename
     header("Pragma: public");
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Type: " . File::mime($filename));
     header("Content-Disposition: attachment; filename=" . $download_name);
     header("Content-Transfer-Encoding: binary");
     readfile($filename);
     exit;
 }
 /**
  * beforeSave callback
  *
  * @param array $options
  * @return boolean true on success
  */
 public function beforeSave($options = array())
 {
     if (!empty($this->data[$this->alias]['file']['tmp_name'])) {
         $File = new File($this->data[$this->alias]['file']['tmp_name']);
         $this->data[$this->alias]['filesize'] = $File->size();
         $this->data[$this->alias]['mime_type'] = $File->mime();
     }
     if (!empty($this->data[$this->alias]['file']['name'])) {
         $this->data[$this->alias]['extension'] = $this->fileExtension($this->data[$this->alias]['file']['name']);
         $this->data[$this->alias]['filename'] = $this->data[$this->alias]['file']['name'];
     }
     if (empty($this->data[$this->alias]['adapter'])) {
         $this->data[$this->alias]['adapter'] = 'S3Storage';
     }
     // Start Auto Creator & Modifier Id Saving
     $exists = $this->exists();
     $user = class_exists('CakeSession') ? CakeSession::read('Auth.User') : null;
     if (!$exists && $this->hasField('creator_id') && empty($this->data[$this->alias]['creator_id'])) {
         $this->data[$this->alias]['creator_id'] = $user['id'];
     }
     if ($this->hasField('modifier_id') && empty($this->data[$this->alias]['modifier_id'])) {
         $this->data[$this->alias]['modifier_id'] = $user['id'];
     }
     // End Auto Creator & Modifier Id Saving
     $Event = new CakeEvent('FileStorage.beforeSave', $this, array('record' => $this->data, 'storage' => $this->getStorageAdapter($this->data[$this->alias]['adapter'])));
     $this->getEventManager()->dispatch($Event);
     if ($Event->isStopped()) {
         return false;
     }
     return true;
 }
Example #3
0
 function replace($path)
 {
     $F = new File($path);
     $md5 = $F->md5();
     $this->path = appPATH . 'qg/file/' . $md5;
     $F->copy($this->path);
     $this->setVs(array('name' => $F->basename(), 'mime' => $F->mime(), 'text' => $F->getText(), 'md5' => $F->md5(), 'size' => $F->size()));
 }
Example #4
0
 /**
  * Output the captcha challenge
  *
  * @param string $group Config group name
  */
 public function action_index($group = 'default')
 {
     // Output the Captcha challenge resource (no html)
     // Pull the config group name from the URL
     $captcha = Captcha::instance($group)->render(FALSE);
     $this->request->headers['Content-Type'] = File::mime($captcha);
     $this->request->headers['Content-length'] = filesize($captcha);
     $this->request->response = $captcha;
 }
Example #5
0
 /**
  * Output the captcha challenge
  *
  * @param string $group Config group name
  */
 public function action_default($group = 'default')
 {
     // Output the Captcha challenge resource (no html)
     // Pull the config group name from the URL
     $captcha = Captcha::instance($group)->render(FALSE);
     $this->request->headers['Content-Type'] = File::mime($captcha);
     // The necessity of this header is questionable and causes problems in Safari and other WebKit browsers.
     // Uncomment at your own peril, scheduled for removal unless a case can be made to keep it.
     //$this->request->headers['Content-Length'] = filesize($captcha);
     $this->request->headers['Connection'] = 'close';
     $this->request->response = $captcha;
 }
Example #6
0
 public function action_asset()
 {
     $asset = Request::instance()->param('filename');
     $file = MODPATH . 'amfphp/assets/' . $asset;
     if (!is_file($file)) {
         throw new Kohana_Exception('Asset does not exist');
     }
     $this->request->headers['Content-Type'] = File::mime($file);
     $this->request->headers['Content-Length'] = filesize($file);
     $this->request->send_headers();
     $content = @fopen($file, 'rb');
     if ($content) {
         fpassthru($content);
         exit;
     }
 }
Example #7
0
 public static function download($path, $name = null, $headers = array())
 {
     if (!file_exists($path)) {
         return Response::code(404);
     }
     if (is_null($name)) {
         $name = basename($path);
     }
     $ext = File::extension($name);
     if ($ext == "") {
         $ext = File::extension($path);
     }
     $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => File::mime(File::extension($path)), 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => File::size($path), 'Content-Disposition' => 'attachment; filename="' . str_replace('"', '\\"', $name) . '"'), $headers);
     foreach ($headers as $k => $v) {
         header($k . ": " . $v);
     }
     readfile($path);
 }
 public static function video_tag($source, array $attributes = NULL)
 {
     if (strpos('//', $source) === FALSE && isset($source[0]) && $source[0] !== '/') {
         $version = '';
         $format = 'mp4';
         if (preg_match('#^(?<source>.+)\\.(?<format>\\w+)$#', $source, $matches)) {
             $source = $matches['source'];
             $format = $matches['format'];
         }
         if (Kohana::$config->load('assets.versionizable') === TRUE) {
             $file_name = Assets::get_file($source, $format);
             if ($file_name && is_file($file_name)) {
                 $version = '-' . hash_hmac_file('md5', $file_name, Kohana::$config->load('assets.versionizable.hmac_password'));
             }
         }
         $source = '/assets/' . $source . $version . '.' . $format;
         $mime = File::mime_by_ext($format);
     } else {
         $mime = File::mime($source);
     }
     return '<video' . HTML::attributes($attributes) . '><source src="' . $source . '" type="' . $mime . '" /><a href="' . $source . '">' . $source . '</a></video>';
 }
Example #9
0
 /**
  * Display a file in the browser.
  *
  *  <code>
  *      File::display('filename.txt');
  *  </code>
  *
  * @param string $file         Full path to file
  * @param string $content_type Content type of the file
  * @param string $filename     Filename of the download
  */
 public static function display($file, $content_type = null, $filename = null)
 {
     // Redefine vars
     $file = (string) $file;
     $content_type = $content_type === null ? null : (string) $content_type;
     $filename = $filename === null ? null : (string) $filename;
     // Check that the file exists and that its readable
     if (file_exists($file) === false || is_readable($file) === false) {
         throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__)));
     }
     // Empty output buffers
     while (ob_get_level() > 0) {
         ob_end_clean();
     }
     // Send headers
     if ($content_type === null) {
         $content_type = File::mime($file);
     }
     if ($filename === null) {
         $filename = basename($file);
     }
     header('Content-type: ' . $content_type);
     header('Content-Disposition: inline; filename="' . $filename . '"');
     header('Content-Length: ' . filesize($file));
     // Read file and write to output
     readfile($file);
     exit;
 }
Example #10
0
 /**
  * Tests File::mime()
  *
  * @test
  * @dataProvider providerMime
  * @param boolean $input  Input for File::mime
  * @param boolean $expected Output for File::mime
  */
 function testMime($input)
 {
     $this->assertSame(1, preg_match('/^(?:application|audio|image|message|multipart|text|video)\\/[a-z.+0-9-]+$/i', File::mime($input)));
 }
Example #11
0
 /**
  * Test mime()
  *
  * @return void
  */
 public function testMime()
 {
     $path = CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
     $file = new File($path);
     $this->assertEquals('image/gif', $file->mime());
 }
Example #12
0
 /**
  * Tests File::mime()
  *
  * @test
  * @dataProvider provider_mime
  * @param boolean $input  Input for File::mime
  * @param boolean $expected Output for File::mime
  */
 public function test_mime($input)
 {
     $this->markTestSkipped('This test doesn\'t do anything useful!');
     $this->assertSame(1, preg_match('/^(?:application|audio|image|message|multipart|text|video)\\/[a-z.+0-9-]+$/i', File::mime($input)));
 }
Example #13
0
 /**
  * Send file download as the response. All execution will be halted when
  * this method is called! Use TRUE for the filename to send the current
  * response as the file content. The third parameter allows the following
  * options to be set:
  *
  * Type      | Option    | Description                        | Default Value
  * ----------|-----------|------------------------------------|--------------
  * `boolean` | inline    | Display inline instead of download | `FALSE`
  * `string`  | mime_type | Manual mime type                   | Automatic
  * `boolean` | delete    | Delete the file after sending      | `FALSE`
  *
  * Download a file that already exists:
  *
  *     $request->send_file('media/packages/kohana.zip');
  *
  * Download generated content as a file:
  *
  *     $request->response($content);
  *     $request->send_file(TRUE, $filename);
  *
  * [!!] No further processing can be done after this method is called!
  *
  * @param   string   filename with path, or TRUE for the current response
  * @param   string   downloaded file name
  * @param   array    additional options
  * @return  void
  * @throws  Kohana_Exception
  * @uses    File::mime_by_ext
  * @uses    File::mime
  * @uses    Request::send_headers
  */
 public function send_file($filename, $download = NULL, array $options = NULL)
 {
     if (!empty($options['mime_type'])) {
         // The mime-type has been manually set
         $mime = $options['mime_type'];
     }
     if ($filename === TRUE) {
         if (empty($download)) {
             throw new Kohana_Exception('Download name must be provided for streaming files');
         }
         // Temporary files will automatically be deleted
         $options['delete'] = FALSE;
         if (!isset($mime)) {
             // Guess the mime using the file extension
             $mime = File::mime_by_ext(strtolower(pathinfo($download, PATHINFO_EXTENSION)));
         }
         // Force the data to be rendered if
         $file_data = (string) $this->_body;
         // Get the content size
         $size = strlen($file_data);
         // Create a temporary file to hold the current response
         $file = tmpfile();
         // Write the current response into the file
         fwrite($file, $file_data);
         // File data is no longer needed
         unset($file_data);
     } else {
         // Get the complete file path
         $filename = realpath($filename);
         if (empty($download)) {
             // Use the file name as the download file name
             $download = pathinfo($filename, PATHINFO_BASENAME);
         }
         // Get the file size
         $size = filesize($filename);
         if (!isset($mime)) {
             // Get the mime type
             $mime = File::mime($filename);
         }
         // Open the file for reading
         $file = fopen($filename, 'rb');
     }
     if (!is_resource($file)) {
         throw new Kohana_Exception('Could not read file to send: :file', array(':file' => $download));
     }
     // Inline or download?
     $disposition = empty($options['inline']) ? 'attachment' : 'inline';
     // Calculate byte range to download.
     list($start, $end) = $this->_calculate_byte_range($size);
     if (!empty($options['resumable'])) {
         if ($start > 0 or $end < $size - 1) {
             // Partial Content
             $this->_status = 206;
         }
         // Range of bytes being sent
         $this->_header['content-range'] = 'bytes ' . $start . '-' . $end . '/' . $size;
         $this->_header['accept-ranges'] = 'bytes';
     }
     // Set the headers for a download
     $this->_header['content-disposition'] = $disposition . '; filename="' . $download . '"';
     $this->_header['content-type'] = $mime;
     $this->_header['content-length'] = (string) ($end - $start + 1);
     if (Request::user_agent('browser') === 'Internet Explorer') {
         // Naturally, IE does not act like a real browser...
         if (Request::$initial->secure()) {
             // http://support.microsoft.com/kb/316431
             $this->_header['pragma'] = $this->_header['cache-control'] = 'public';
         }
         if (version_compare(Request::user_agent('version'), '8.0', '>=')) {
             // http://ajaxian.com/archives/ie-8-security
             $this->_header['x-content-type-options'] = 'nosniff';
         }
     }
     // Send all headers now
     $this->send_headers();
     while (ob_get_level()) {
         // Flush all output buffers
         ob_end_flush();
     }
     // Manually stop execution
     ignore_user_abort(TRUE);
     if (!Kohana::$safe_mode) {
         // Keep the script running forever
         set_time_limit(0);
     }
     // Send data in 16kb blocks
     $block = 1024 * 16;
     fseek($file, $start);
     while (!feof($file) and ($pos = ftell($file)) <= $end) {
         if (connection_aborted()) {
             break;
         }
         if ($pos + $block > $end) {
             // Don't read past the buffer.
             $block = $end - $pos + 1;
         }
         // Output a block of the file
         echo fread($file, $block);
         // Send the data now
         flush();
     }
     // Close the file
     fclose($file);
     if (!empty($options['delete'])) {
         try {
             // Attempt to remove the file
             unlink($filename);
         } catch (Exception $e) {
             // Create a text version of the exception
             $error = Kohana_Exception::text($e);
             if (is_object(Kohana::$log)) {
                 // Add this exception to the log
                 Kohana::$log->add(Log::ERROR, $error);
                 // Make sure the logs are written
                 Kohana::$log->write();
             }
             // Do NOT display the exception, it will corrupt the output!
         }
     }
     // Stop execution
     exit;
 }
Example #14
0
 /**
  * 设置真实的文件类型
  *
  * @return boolean|Core_Upload
  */
 protected function check_real_mime()
 {
     // 真实类型检测
     if ($this->config['mimes_check']) {
         $type = File::mime($this->file['tmp_name']);
         if (false === $type) {
             throw new Exception('Upload error type', Upload::ERR_EXTENSION);
         } else {
             $this->file['type'] = $type;
         }
     }
     return $this;
 }
Example #15
0
 /**
  * Create the image HTTP headers
  * 
  * @param  string     path to the file to server (either default or cached version)
  */
 private function _create_headers($file_data)
 {
     // Create the required header vars
     $last_modified = gmdate('D, d M Y H:i:s', filemtime($file_data)) . ' GMT';
     $content_type = File::mime($file_data);
     $content_length = filesize($file_data);
     $expires = gmdate('D, d M Y H:i:s', time() + $this->config['cache_expire']) . ' GMT';
     $max_age = 'max-age=' . $this->config['cache_expire'] . ', public';
     // Some required headers
     header("Last-Modified: {$last_modified}");
     header("Content-Type: {$content_type}");
     header("Content-Length: {$content_length}");
     // How long to hold in the browser cache
     header("Expires: {$expires}");
     /**
      * Public in the Cache-Control lets proxies know that it is okay to
      * cache this content. If this is being served over HTTPS, there may be
      * sensitive content and therefore should probably not be cached by
      * proxy servers.
      */
     header("Cache-Control: {$max_age}");
     // Set the 304 Not Modified if required
     $this->_modified_headers($last_modified);
     /**
      * The "Connection: close" header allows us to serve the file and let
      * the browser finish processing the script so we can do extra work
      * without making the user wait. This header must come last or the file
      * size will not properly work for images in the browser's cache
      */
     header("Connection: close");
 }
 /**
  * Checks the mime type of a file
  *
  * @param string|array $check
  * @param array $mimeTypes to check for
  * @return boolean Success
  * @throws CakeException when mime type can not be determined.
  */
 public static function mimeType($check, $mimeTypes = array())
 {
     if (is_array($check) && isset($check['tmp_name'])) {
         $check = $check['tmp_name'];
     }
     $File = new File($check);
     $mime = $File->mime();
     if ($mime === false) {
         throw new CakeException(__d('cake_dev', 'Can not determine the mimetype.'));
     }
     return in_array($mime, $mimeTypes);
 }
Example #17
0
 /**
  * 创建一个CURL对象
  *
  * @param string $url URL地址
  * @param int $timeout 超时时间
  * @return resource fsockopen returns a file pointer which may be used
  */
 protected function _create($url, $timeout)
 {
     if (false === strpos($url, '://')) {
         preg_match('#^(http(?:s)?\\://[^/]+/)#', $_SERVER["SCRIPT_URI"], $m);
         $the_url = $m[1] . ltrim($url, '/');
     } else {
         $the_url = $url;
     }
     preg_match('#^(http(?:s)?)\\://([^/]+)(/.*)$#', $the_url, $m);
     $hostname = $m[2];
     $uri = $m[3];
     list($host, $port) = explode(':', $hostname, 2);
     if ($this->ip) {
         $host = $this->ip;
     }
     if ($m[1] == 'https') {
         $host = 'tls://' . $host;
     }
     if (!$port) {
         if ($m[1] == 'https') {
             $port = 443;
         } else {
             $port = 80;
         }
     }
     $ch = fsockopen($host, $port, $errno, $errstr, $timeout);
     $header = array('Host' => $hostname, 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Connection' => 'close');
     if ($this->cookies) {
         $header['Cookie'] = is_array($this->cookies) ? http_build_query($this->cookies, '', ';') : $this->cookies;
     }
     if ($this->referer) {
         $header['Referer'] = $this->referer;
     }
     if ($this->agent) {
         $header['User-Agent'] = $this->agent;
     } elseif (array_key_exists('HTTP_USER_AGENT', $_SERVER)) {
         $header['User-Agent'] = $_SERVER['HTTP_USER_AGENT'];
     }
     if ($this->header) {
         $header = array();
         foreach ($this->header as $item) {
             # 防止有重复的header
             if (preg_match('#(^[^:]*):(.*)$#', $item, $m)) {
                 $header[trim($m[1])] = trim($m[2]);
             }
         }
     }
     if ($this->files) {
         $boundary = '----------------------------' . substr(md5(microtime(1) . mt_rand()), 0, 12);
         $vars = "--{$boundary}\r\n";
         if ($this->_post_data[$url]) {
             if (!is_array($this->_post_data[$url])) {
                 parse_str($this->_post_data[$url], $post);
             } else {
                 $post = $this->_post_data[$url];
             }
             // form data
             foreach ($post as $key => $val) {
                 $vars .= "Content-Disposition: form-data; name=\"" . rawurlencode($key) . "\"\r\n";
                 $vars .= "Content-type:application/x-www-form-urlencoded\r\n\r\n";
                 $vars .= rawurlencode($val) . "\r\n";
                 $vars .= "--{$boundary}\r\n";
             }
         }
         foreach ($this->files as $name => $filename) {
             $vars .= "Content-Disposition: form-data; name=\"" . $name . "\"; filename=\"" . rawurlencode(basename($filename)) . "\"\r\n";
             $vars .= "Content-Type: " . File::mime($filename) . "\r\n\r\n";
             $vars .= file_get_contents($filename) . "\r\n";
             $vars .= "--{$boundary}\r\n";
         }
         $vars .= "--\r\n\r\n";
         $header['Content-Type'] = 'multipart/form-data; boundary=' . $boundary;
     } else {
         if (isset($this->_post_data[$url]) && $this->_post_data[$url]) {
             # 设置POST数据
             $vars = is_array($this->_post_data[$url]) ? http_build_query($this->_post_data[$url]) : (string) $this->_post_data[$url];
             $header['Content-Type'] = 'application/x-www-form-urlencoded';
         } else {
             $vars = '';
         }
     }
     # 设置长度
     $header['Content-Length'] = strlen($vars);
     $str = $this->method . ' ' . $uri . ' HTTP/1.1' . "\r\n";
     foreach ($header as $k => $v) {
         $str .= $k . ' :' . str_replace(array("\r", "\n"), '', $v) . "\r\n";
     }
     $str .= "\r\n";
     # 写入头信息
     fwrite($ch, $str);
     if ($vars) {
         # 追加POST数据
         fwrite($ch, $vars);
     }
     return $ch;
 }
Example #18
0
 /**
  * Upload getter and setter. Setting the value to `NULL` will remove it.
  *
  *     // Set the "image" file path for uploading
  *     $request->upload('image', $file_path);
  *
  *     // Get the "image" file path
  *     $key = $request->param('oauth_consumer_key');
  *
  * @param   string   upload name
  * @param   mixed    upload file path
  * @return  mixed    when getting
  * @return  $this    when setting
  * @uses    Request::param
  */
 public function upload($name, $value = NULL)
 {
     if ($value !== NULL) {
         // This is an upload parameter
         $this->upload[$name] = TRUE;
         // Get the mime type of the image
         $mime = File::mime($value);
         // Format the image path for CURL
         $value = "@{$value};type={$mime}";
     }
     return $this->param($name, $value, FALSE);
 }
Example #19
0
 /**
  * Open a file, detect its mime-type and create an image resrource from it.
  * @param  array $file Attributes of file from the $_FILES array
  * @return mixed
  */
 private function open_image($file)
 {
     // If $file isn't an array, we'll turn it into one.
     if (!is_array($file)) {
         $file = array('type' => File::mime(strtolower(File::extension($file))), 'tmp_name' => $file);
     }
     $mime = $file['type'];
     $file_path = $file['tmp_name'];
     switch ($mime) {
         case 'image/pjpeg':
             // IE6
         // IE6
         case File::mime('jpg'):
             $img = @imagecreatefromjpeg($file_path);
             break;
         case File::mime('gif'):
             $img = @imagecreatefromgif($file_path);
             break;
         case File::mime('png'):
             $img = @imagecreatefrompng($file_path);
             break;
         default:
             $img = false;
             break;
     }
     return $img;
 }
Example #20
0
 static function place($file, array $attributes = array())
 {
     $attributes += array('uploader' => null, 'desc' => '', 'mime' => null, 'name' => null, 'ext' => null);
     if (!empty($attributes['name'])) {
         $attributes['name'] = basename($attributes['name']);
     } else {
         $ext = strtolower(ltrim($attributes['ext'], '.'));
         $attributes['name'] = substr(uniqid(), 0, 8) . ".{$ext}";
         $msg = "Placing a file without explicit name, generated random: {$attributes['name']}.";
         Log::info_File($msg);
     }
     $ext = $attributes['ext'] = strtolower(ltrim(S::ext($attributes['name']), '.'));
     $ext === '' and $attributes['ext'] = 'dat';
     $dest = static::generatePath($attributes['name']);
     S::mkdirOf($dest);
     $attributes['path'] = S::tryUnprefix($dest, static::storage());
     if (is_resource($file)) {
         $attributes['size'] = static::streamCopyTo($dest, $file);
     } else {
         $attributes['size'] = strlen($file);
         if (!file_put_contents($dest, $file, LOCK_EX)) {
             throw new Error("Cannot write new File data [{$dest}].");
         }
     }
     try {
         // explicit ID so it's harder to guess new file's ID (e.g. to access it directly
         // from web) since they're not sequental.
         $attributes['id'] = static::generateID();
         $model = with(new static())->fill_raw($attributes);
         $model->md5 = md5_file($dest);
         $model->mime = $attributes['mime'] ?: \File::mime($model->ext, '');
         return Event::insertModel($model, 'file');
     } catch (\Exception $e) {
         unlink($dest);
         throw $e;
     }
 }
Example #21
0
 private function _formatContent()
 {
     global $C;
     $lf = $this->_lf;
     if ($this->_lastContent != $this->content && $this->_formattedContent != $this->content || $this->forceReformatContent) {
         $this->forceReformatContent = false;
         $this->_boundary = "_=======" . @date('YmdHms') . time() . "=======_";
         $this->_lastContent = $this->content;
         $c = $this->content;
         $cImgs = "";
         $formattedContent = "";
         //Get server from 'from' e-mail for imgs cids. eg: server.com.br
         $arr = explode("@", $this->_from[0]);
         $server = $arr[1];
         if ($this->attachImages) {
             //Find: <img... src=""...> and <... url() ...>
             $c = $this->content;
             $i = 0;
             $imgs = array();
             while (preg_match('#<img(.+?)' . preg_quote("src", '/') . '(.+?)>|<(.+?)' . preg_quote("background=", '/') . '(.+?)>#i', $c, $m) && $i < 150) {
                 if (strpos($m[0], "background=") > 0) {
                     $imgs[] = array($m[0], str_replace(array("'", "\""), "", $m[4]));
                     $pos = strpos($c, $m[0]) + strlen($m[0]);
                 } else {
                     $p2 = (int) strpos($m[2], '"', 2);
                     $p1 = (int) strpos($m[2], "'", 2);
                     if ($p1 == 0) {
                         $p1 = $p2;
                     }
                     $imgs[] = array($m[0], substr($m[2], 2, $p1 - 2));
                     $pos = strpos($c, $m[0]) + strlen($m[0]);
                 }
                 $c = substr($c, $pos);
                 $i++;
             }
             //Replace imgs urls to imgs cids and generate contents.
             $c = $this->content;
             $imgTags = array();
             $imgFiles = array();
             $allowedExtensions = array("jpg", "gif", "png");
             foreach ($imgs as $v) {
                 $tag = $v[0];
                 $path = $v[1];
                 if (array_search(File::extension($path), $allowedExtensions) !== false && array_search($tag, $imgTags) === false) {
                     $fileName = File::fileName($path);
                     $id = "IMG_" . str_replace(array("." . $ext, " "), "", $fileName) . "@" . $server;
                     $img = str_replace($path, "cid:" . $id, $tag);
                     if (strpos($c, $tag) !== false) {
                         $imgTags[] = $tag;
                         if (strpos($img, "moz-do-not-send=\"false\"") == false && strpos($img, "<img") !== false) {
                             $img = substr($img, 0, strlen($img) - 1) . " moz-do-not-send=\"false\">";
                         } elseif (strpos($img, "url(") !== false) {
                         }
                         $c = str_replace($tag, $img, $c);
                         if (array_search($path, $imgFiles) === false) {
                             $imgFiles[] = $path;
                             $cImgs .= "--" . $this->_boundary . $lf;
                             $mime = File::mime($ext);
                             $cImgs .= "Content-type: " . $mime . "; name=\"" . $fileName . "\"" . $lf;
                             $cImgs .= "Content-Transfer-Encoding: base64" . $lf;
                             $cImgs .= "Content-ID: <" . $id . ">" . $lf . $lf;
                             $cImgs .= chunk_split(base64_encode($file->readFile($v[1]))) . $lf . $lf;
                         }
                     }
                 }
             }
         }
         //Text plain content
         /*$formattedContent = "--" . $this->_boundary . "\n";
         		$formattedContent .= "Content-Type: text/plan; charset=iso-8859-1\n\n";
         		$formattedContent .= strip_tags(str_replace(array("\r\n", "\n\r", "\n", "<br>"), array("", "", "", "\n"), str_replace(array("<br/>", "<br />"), "<br>", substr($c, (int)strpos($c, "<body"))))) . "\n";*/
         //echo $c;
         //Html content
         if ($cImgs != "") {
             $formattedContent .= "--" . $this->_boundary . $lf;
             $formattedContent .= "Content-Type: text/html; charset=UTF-8" . $lf . $lf;
             $formattedContent .= $c . $lf . $lf;
         } else {
             $formattedContent = $c;
         }
         //Images contents
         if ($cImgs != "") {
             $formattedContent .= $cImgs;
             $formattedContent .= "--" . $this->_boundary . "--" . $lf;
         }
         $this->_formattedContent = $formattedContent;
     }
 }
Example #22
0
 /**
  * Create a new download response instance.
  *
  * <code>
  *		// Create a download response to a given file
  *		return Response::download('path/to/file.jpg');
  *
  *		// Create a download response with a given file name
  *		return Response::download('path/to/file.jpg', 'your_file.jpg');
  * </code>
  *
  * @param  string    $path
  * @param  string    $name
  * @param  array     $headers
  * @return Response
  */
 public static function download($path, $name = null, $headers = array())
 {
     if (is_null($name)) {
         $name = basename($path);
     }
     $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => File::mime(File::extension($path)), 'Content-Disposition' => 'attachment; filename="' . $name . '"', 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => File::size($path)), $headers);
     return new static(File::get($path), 200, $headers);
 }
Example #23
0
 $id = (int) $_POST['id'];
 $filename = $_FILES['file']['name'];
 // no file!
 if ($_FILES['file']['size'] <= 0) {
     $last_message = 'Failed';
     header('Location:error.php?ec=11&last_message=' . urlencode($last_message));
     exit;
 }
 // Check ini max upload size
 if ($_FILES['file']['error'] == 1) {
     $last_message = 'Upload Failed - check your upload_max_filesize directive in php.ini';
     header('Location: error.php?last_message=' . urlencode($last_message));
     exit;
 }
 // Lets try and determine the true file-type
 $file_mime = File::mime($_FILES['file']['tmp_name'], $_FILES['file']['name']);
 // check file type
 foreach ($GLOBALS['CONFIG']['allowedFileTypes'] as $thistype) {
     if ($file_mime == $thistype) {
         $allowedFile = 1;
         break;
     } else {
         $allowedFile = 0;
     }
 }
 // illegal file type!
 if ($allowedFile != 1) {
     $last_message = 'MIMETYPE: ' . $file_mime . ' Failed';
     header('Location:error.php?ec=13&last_message=' . urlencode($last_message));
     exit;
 }
Example #24
0
 /**
  * Send file download as the response. All execution will be halted when
  * this method is called! Use TRUE for the filename to send the current
  * response as the file content. The third parameter allows the following
  * options to be set:
  *
  * Type      | Option    | Description                        | Default Value
  * ----------|-----------|------------------------------------|--------------
  * `boolean` | inline    | Display inline instead of download | `FALSE`
  * `string`  | mime_type | Manual mime type                   | Automatic
  * `boolean` | delete    | Delete the file after sending      | `FALSE`
  *
  * Download a file that already exists:
  *
  *     $request->send_file('media/packages/kohana.zip');
  *
  * Download generated content as a file:
  *
  *     $request->response = $content;
  *     $request->send_file(TRUE, $filename);
  *
  * [!!] No further processing can be done after this method is called!
  *
  * @param   string   filename with path, or TRUE for the current response
  * @param   string   downloaded file name
  * @param   array    additional options
  * @return  void
  * @throws  Kohana_Exception
  * @uses    File::mime_by_ext
  * @uses    File::mime
  * @uses    Request::send_headers
  */
 public function send_file($filename, $download = NULL, array $options = NULL)
 {
     if (!empty($options['mime_type'])) {
         // The mime-type has been manually set
         $mime = $options['mime_type'];
     }
     if ($filename === TRUE) {
         if (empty($download)) {
             throw new Kohana_Exception('Download name must be provided for streaming files');
         }
         // Temporary files will automatically be deleted
         $options['delete'] = FALSE;
         if (!isset($mime)) {
             // Guess the mime using the file extension
             $mime = File::mime_by_ext(strtolower(pathinfo($download, PATHINFO_EXTENSION)));
         }
         // Get the content size
         $size = strlen($this->response);
         // Create a temporary file to hold the current response
         $file = tmpfile();
         // Write the current response into the file
         fwrite($file, $this->response);
         // Prepare the file for reading
         fseek($file, 0);
     } else {
         // Get the complete file path
         $filename = realpath($filename);
         if (empty($download)) {
             // Use the file name as the download file name
             $download = pathinfo($filename, PATHINFO_BASENAME);
         }
         // Get the file size
         $size = filesize($filename);
         if (!isset($mime)) {
             // Get the mime type
             $mime = File::mime($filename);
         }
         // Open the file for reading
         $file = fopen($filename, 'rb');
     }
     // Inline or download?
     $disposition = empty($options['inline']) ? 'attachment' : 'inline';
     // Set the headers for a download
     $this->headers['Content-Disposition'] = $disposition . '; filename="' . $download . '"';
     $this->headers['Content-Type'] = $mime;
     $this->headers['Content-Length'] = $size;
     if (!empty($options['resumable'])) {
         // @todo: ranged download processing
     }
     // Send all headers now
     $this->send_headers();
     while (ob_get_level()) {
         // Flush all output buffers
         ob_end_flush();
     }
     // Manually stop execution
     ignore_user_abort(TRUE);
     // Keep the script running forever
     set_time_limit(0);
     // Send data in 16kb blocks
     $block = 1024 * 16;
     while (!feof($file)) {
         if (connection_aborted()) {
             break;
         }
         // Output a block of the file
         echo fread($file, $block);
         // Send the data now
         flush();
     }
     // Close the file
     fclose($file);
     if (!empty($options['delete'])) {
         try {
             // Attempt to remove the file
             unlink($filename);
         } catch (Exception $e) {
             // Create a text version of the exception
             $error = Kohana::exception_text($e);
             if (is_object(Kohana::$log)) {
                 // Add this exception to the log
                 Kohana::$log->add(Kohana::ERROR, $error);
                 // Make sure the logs are written
                 Kohana::$log->write();
             }
             // Do NOT display the exception, it will corrupt the output!
         }
     }
     // Stop execution
     exit;
 }
Example #25
0
 /**
  * Checks the mime type of a file.
  *
  * @param string|array $check Value to check.
  * @param array|string $mimeTypes Array of mime types or regex pattern to check.
  * @return bool Success
  * @throws CakeException when mime type can not be determined.
  */
 public static function mimeType($check, $mimeTypes = array())
 {
     if (is_array($check) && isset($check['tmp_name'])) {
         $check = $check['tmp_name'];
     }
     $File = new File($check);
     $mime = $File->mime();
     if ($mime === false) {
         throw new CakeException(__d('cake_dev', 'Can not determine the mimetype.'));
     }
     if (is_string($mimeTypes)) {
         return self::_check($mime, $mimeTypes);
     }
     foreach ($mimeTypes as $key => $val) {
         $mimeTypes[$key] = strtolower($val);
     }
     return in_array($mime, $mimeTypes);
 }
Example #26
0
 // First we need to make sure all files are allowed types
 for ($count = 0; $count < $numberOfFiles; $count++) {
     if (empty($_FILES['file']['name'][$count])) {
         $last_message = $GLOBALS['lang']['addpage_file_missing'];
         header('Location: error.php?last_message=' . urlencode($last_message));
         exit;
     }
     // Check ini max upload size
     if ($_FILES['file']['error'][$count] == 1) {
         $last_message = 'Upload Failed - check your upload_max_filesize directive in php.ini';
         header('Location: error.php?last_message=' . urlencode($last_message));
         exit;
     }
     $tmp_name[$count] = realpath($_FILES['file']['tmp_name'][$count]);
     // Lets lookup the try mime type
     $file_mime = File::mime($tmp_name[$count], $_FILES['file']['name'][$count]);
     $allowedFile = 0;
     // check file type
     foreach ($GLOBALS['CONFIG']['allowedFileTypes'] as $allowed_type) {
         if ($file_mime == $allowed_type) {
             $allowedFile = 1;
             break;
         }
     }
     // illegal file type!
     if (!isset($allowedFile) || $allowedFile != 1) {
         $last_message = 'MIMETYPE: ' . $file_mime . ' Failed';
         header('Location:error.php?ec=13&last_message=' . urlencode($last_message));
         exit;
     }
 }
 /**
  * Test mime()
  *
  * @return void
  */
 public function testMime()
 {
     $this->skipIf(!function_exists('finfo_open') && !function_exists('mime_content_type'), 'Not able to read mime type');
     $path = CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
     $file = new File($path);
     $expected = 'image/gif';
     if (function_exists('mime_content_type') && false === mime_content_type($file->pwd())) {
         $expected = false;
     }
     $this->assertEquals($expected, $file->mime());
 }
Example #28
0
/*
* @name   Preview
* @desc   Open preview on blank page
*/
$p->route('/action/uploads/preview/(:any)', function ($file) use($p) {
    // remove dir
    $link = str_replace(UPLOADS, '', base64_decode($file));
    $link = str_replace('\\', '/', $link);
    $link = str_replace('//', '/', $link);
    // check mime types
    $template = '';
    // decode file
    $path = base64_decode($file);
    $link = Url::sanitizeURL($link);
    // check mime types
    if (File::mime($path)) {
        if (File::ext($path) == 'jpg' || File::ext($path) == 'JPG' || File::ext($path) == 'png' || File::ext($path) == 'PNG' || File::ext($path) == 'jpeg' || File::ext($path) == 'JPEG' || File::ext($path) == 'gif') {
            // get image size
            list($width, $height) = getimagesize($path);
            // image template
            $template = '
          <div class="box-1 col">
            <div class="media">
              <div class="image-media">
                <img src="' . $p::$site['url'] . '/public/uploads/' . $link . '"/>
              </div>
              <div class="info-media">
                <ul>
                  <li><b>Filename: </b>' . File::name($path) . '</li>
                  <li><b>Extension: </b>' . File::ext($path) . '</li>
                  <li><b>Size: </b>' . $width . 'x' . $height . 'px</li>
Example #29
0
 /**
  * testMimeTypeFalse method
  *
  * @expectedException CakeException
  * @return void
  */
 public function testMimeTypeFalse()
 {
     $image = CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
     $File = new File($image, false);
     $this->skipIf($File->mime(), 'mimeType can be determined, no Exception will be thrown');
     Validation::mimeType($image, array('image/gif'));
 }
Example #30
0
 public function action_index($subdir = NULL)
 {
     //получаем все папки из папки baseDir
     $dir = $this->uploads_dir();
     if (isset($_POST['delPictures'])) {
         $dirName = $this->request->param('id');
         $arr = $_POST;
         unset($arr['dirName']);
         unset($arr['delPictures']);
         foreach ($arr as $picture => $value) {
             $path = $dir . $dirName . '/' . str_replace('^', '.', $picture);
             //var_dump($path);
             if (file_exists($path)) {
                 // удаляем файл
                 unlink($path);
             }
         }
     }
     if (isset($_POST['deleteDir'])) {
         $dirName = Arr::get($_POST, 'dirName') . '/';
         $result = $this->RemoveDir($dirName);
         //chdir ($parent); //путь где создавать папку
         //mkdir ($folderName, 0770); //имя папки и атрибуты на папку
     }
     if (isset($_POST['add_folder'])) {
         $folderName = Arr::get($_POST, 'folderName');
         $base = new Model_Base();
         $folderName = $base->str2url($folderName);
         $parent = $dir . Arr::get($_POST, 'parentName');
         //var_dump($parent);
         chdir($parent);
         //путь где создавать папку
         mkdir($folderName, 0777);
         //имя папки и атрибуты на папку
     }
     if (isset($_POST['filesUpload'])) {
         //get uploadDir
         $uploadDir = Arr::get($_POST, 'dir');
         //перебираем массив файлов
         for ($i = 0; $i < count($_FILES['file']['name']); ++$i) {
             if ($_FILES['file']['size'][$i] > 3300000) {
                 echo 'Файл не должен быть больше 3 Мб';
             } else {
                 $ext = explode('.', $_FILES['file']['name'][$i]);
                 $extension = array_pop($ext);
                 $base = new Model_Base();
                 $extarr = explode('.', $_FILES['file']['name'][$i]);
                 $ext = array_pop($extarr);
                 $name = implode('', $extarr);
                 $filename = $base->str2url($name) . '.' . $ext;
                 //$filename = substr(md5(microtime() * time()),0,rand(20,10)).'.'.$extension;
                 if (copy($_FILES['file']['tmp_name'][$i], $uploadDir . "/" . $filename)) {
                     $img = $uploadDir . "/" . $filename;
                 }
             }
         }
     }
     $folder = $dir . $this->request->param('id');
     if ($folder) {
         if (is_dir($folder)) {
             if ($dh = opendir($folder)) {
                 while (($file = readdir($dh)) !== false) {
                     if (filetype($folder . '/' . $file) != 'dir') {
                         $this->files[] = array('name' => $file, 'mime' => File::mime($folder . '/' . $file));
                     }
                 }
                 closedir($dh);
             }
         }
     }
     $folders = $this->getFolders();
     $this->template->content = View::factory('admin/admFiles', array('folders' => $folders, 'files' => $this->files, 'basedir' => $folder, 'user' => $this->user));
 }