Example #1
0
 /**
  * Tests getRealType
  *
  * @issue  1442
  * @author Serghei Iakovlev <*****@*****.**>
  * @author Dreamszhu <*****@*****.**>
  * @since  2013-10-26
  */
 public function testRealType()
 {
     if (!extension_loaded('fileinfo')) {
         $this->markTestSkipped('Warning: fileinfo extension is not loaded');
     }
     $this->specify("getRealType does not returns real type", function () {
         $file = new File(['name' => 'test', 'type' => 'text/plain', 'tmp_name' => PATH_DATA . '/assets/phalconphp.jpg', 'size' => 1, 'error' => 0]);
         expect($file->getType())->equals('text/plain');
         expect($file->getRealType())->equals('image/jpeg');
     });
 }
Example #2
0
 public static function storeAttachment(\Phalcon\Http\Request\File $attachment)
 {
     $uploadDir = 'files';
     //上传路径的设置
     $time = time();
     $path = static::makePath($uploadDir, $time);
     $ext = preg_replace('%^.*?(\\.[\\w]+)$%', "\$1", $attachment->getName());
     //获取文件的后缀
     $url = md5($attachment->getName());
     $filename = $path . $time . $url . $ext;
     $attachment->moveTo($filename);
     return $filename;
 }
Example #3
0
 public function upload(File $file)
 {
     if ($file->getError()) {
         throw new Exception\IOException('ERR_FILE_UPLOAD_FAILED');
     }
     $originalName = $file->getName();
     $tmp = $file->getTempName();
     $fileSize = $file->getSize();
     $type = $file->getType();
     $filenameArray = explode(".", $originalName);
     $fileExtension = strtolower(array_pop($filenameArray));
     $originalFileName = implode('.', $filenameArray);
     $fileName = Tag::friendlyTitle($originalFileName);
     $fileHash = null;
     if ($fileName == '-') {
         $fileName = Text::random(Text::RANDOM_ALNUM, 6);
     }
     //hash file less then 10M
     if ($fileSize < 1048576 * 10) {
         $fileHash = hash_file('CRC32', $tmp, false);
     }
     if (false === strpos($type, 'image')) {
         $isImage = 0;
     } else {
         $isImage = 1;
     }
     $fileinfo = array('title' => $originalFileName, 'status' => 'published', 'storageAdapter' => 'local', 'originalName' => $originalName, 'fileSize' => $fileSize, 'mimeType' => $type, 'fileExtension' => $fileExtension, 'fileHash' => $fileHash, 'isImage' => $isImage, 'fileName' => $fileName . '.' . $fileExtension, 'createdAt' => time());
     if ($isImage) {
         $image = getimagesize($tmp);
         $fileinfo['imageWidth'] = $image[0];
         $fileinfo['imageHeight'] = $image[1];
     }
     $filesystem = $this->getDI()->getFileSystem();
     $path = md5(microtime());
     $path = str_split($path, 2);
     $pathlevel = $this->getUploadPathLevel();
     $pathlevel = $pathlevel > 6 ? 6 : $pathlevel;
     $path = array_slice($path, 0, $pathlevel);
     $filePath = implode('/', $path);
     $path = $filePath . '/' . $fileName . '.' . $fileExtension;
     $fileinfo['filePath'] = $filePath;
     $this->assign($fileinfo);
     if ($this->save()) {
         if (!$filesystem->has($path)) {
             if ($filesystem->write($path, file_get_contents($tmp))) {
                 unlink($tmp);
             } else {
                 throw new Exception\IOException('ERR_FILE_MOVE_TO_STORAGE_FAILED');
             }
         } else {
             throw new Exception\ResourceConflictException('ERR_FILE_UPLOAD_BY_CONFLICT_NAME');
         }
     } else {
         throw new Exception\RuntimeException('ERR_FILE_SAVE_TO_DB_FAILED');
     }
     return $this;
 }
Example #4
0
 /**
  * 新增专题
  */
 public function formAction()
 {
     //定义js匿名函数
     $execJs = function ($msg) {
         $js = "<script type='text/javascript'>\r\n                        //禁止回退\r\n                        window.history.forward(1);\r\n                            alert('{$msg}');\r\n                        location.href = history.go(-1);\r\n                    </script>";
         die($js);
     };
     $validate = new \Validate();
     $data['file_cat_id'] = $validate->getPost('file_cat_id', \Validate::int());
     //专题类型
     //验证参数
     if ($validate->getMessage()) {
         $execJs('参数错误');
     }
     //验证文件
     if (!isset($_FILES['doc'])) {
         $execJs('非法操作');
     }
     //验证zip压缩文件
     $doc = new File($_FILES['doc']);
     if ($doc->getExtension() != 'doc' && $doc->getExtension() != 'docx' && $doc->getExtension() != 'ppt' && $doc->getExtension() != 'pptx') {
         $execJs('请上传doc、docx、ppt、pptx类型的文件');
     }
     $file_name = $doc->getName();
     //创建目录
     $file_path = FILE_PATH . '/file/' . $data['file_cat_id'];
     $util = new \FileUtil();
     $util->mkdir($file_path);
     $data['file_url'] = '/file/' . $data['file_cat_id'] . '/' . md5($file_name . time()) . '.' . $doc->getExtension();
     $file_url = FILE_PATH . $data['file_url'];
     $data['file_name'] = $file_name;
     //移动资源文件,并重命名,与phtml文件相同
     $doc->moveTo($file_url);
     $result = (new \File())->addFile($this->session->get('id'), $data);
     if ($result != 200) {
         //删除所有专题相关文件
         $this->unlink($file_url);
         $execJs('上传失败');
     }
     $execJs('专题添加成功');
 }
Example #5
0
 /**
  * Check file allowed extensions
  *
  * @param \Phalcon\Http\Request\File $file
  * @param mixed $value
  * @return bool
  */
 public function checkMimes(\Phalcon\Http\Request\File $file, $value)
 {
     //conversion to the desired format
     if (is_array($value) === false) {
         $value = [$value];
     }
     if (in_array($file->getRealType(), $value) === false) {
         $this->errors[] = sprintf(Message::get('INVALID_MIME_TYPES'), $file->getName(), implode(',', $value));
         return false;
     }
     return true;
 }
Example #6
0
 /**
  * File class constructor
  * 
  * @param array $file
  * @param mixed $key
  *
  * @access public
  * @return void
  */
 public function __construct(array $file, $key = NULL)
 {
     parent::__construct($file, $key);
     $this->file = $file;
     $this->setAdapter(self::ADAPTER_GD);
 }
Example #7
0
 public function __construct(array $file, $key = null)
 {
     parent::__construct($file, $key);
     $this->offsetImport($file);
 }
Example #8
0
 /**
  * 新增专题
  */
 public function formAction()
 {
     //定义js匿名函数
     $execJs = function ($msg) {
         $js = "<script type='text/javascript'>\r\n                        //禁止回退\r\n                        window.history.forward(1);\r\n                            alert('{$msg}');\r\n                        location.href = history.go(-1);\r\n                    </script>";
         die($js);
     };
     //定义随机数匿名函数
     $rand = function ($len) {
         $base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
         $rand_str = '';
         for ($i = 0; $i < $len; $i++) {
             $rand_str .= $base[mt_rand(0, 61)];
         }
         return $rand_str;
     };
     $validate = new \Validate();
     $data['top_type'] = $validate->getPost('top_type', \Validate::int());
     //专题类型
     $data['top_name'] = $validate->getPost('top_name', ['length' => ['max' => 30, 'min' => 0]], ['slashes' => true, 'html' => true]);
     //专题标题
     $data['top_summary'] = $validate->getPost('top_summary', ['length' => ['max' => 200, 'min' => 0]], ['slashes' => true, 'html' => true]);
     //专题备注
     $data['top_remark'] = $validate->getPost('top_remark', ['length' => ['max' => 50, 'min' => 0]], ['slashes' => true, 'html' => true]);
     //专题备注
     //验证参数
     if ($validate->getMessage()) {
         $execJs('参数错误');
     }
     //验证文件
     if (!isset($_FILES['zip']) || !isset($_FILES['top_thumb'])) {
         $execJs('非法操作');
     }
     //验证缩略图
     $thumb = new File($_FILES['top_thumb']);
     $extensions = ['png', 'jpg', 'gif'];
     if (!in_array($thumb->getExtension(), $extensions)) {
         $execJs('请上传png、jpg、gif类型图片');
     }
     //声明图片地址
     $pic_name = md5(microtime(true)) . '.' . $thumb->getExtension();
     $pic_add = $this->mkdir('topic', $pic_name);
     $data['top_thumb'] = $pic_add['data_file'];
     //移动图片
     $thumb->moveTo($pic_add['host_file']);
     //验证zip压缩文件
     $zip = new File($_FILES['zip']);
     if ($zip->getExtension() != 'zip') {
         $execJs('请上传zip压缩文件');
     }
     //解压缩
     $archive = new \ZipArchive();
     if (!$archive->open($zip->getTempName())) {
         $execJs('zip压缩文件已损坏');
     }
     //12位随机数专题序列号,并检查是否重复
     $data['top_unique'] = '';
     while (1) {
         $data['top_unique'] = $rand(12);
         if ((new \Topic())->isTopicExist($data['top_unique']) == 404) {
             break;
         }
     }
     //创建临时解压目录
     $zip_path = TEMP_PATH . '/tmp' . $data['top_unique'];
     $util = new \FileUtil();
     $util->mkdir($zip_path);
     //解压到临时目录
     if ($archive->extractTo($zip_path)) {
         //判断上传文件结构
         if (!is_file($zip_path . '/index.html') || !is_dir($zip_path . '/index')) {
             $this->unlink($pic_add['host_file']);
             $util->rm($zip_path);
             $execJs('zip压缩文件内容与要求不匹配');
         }
         //定义html,以及phtml文件路径
         $html_file = $zip_path . '/index.html';
         $phtml_file = TOPIC_HTML_PATH . '/' . $data['top_unique'] . '.phtml';
         //分别以只读,和只写方式打开html,phtml文件
         $html_handle = fopen($html_file, 'r');
         $phtml_handle = fopen($phtml_file, 'w');
         //读取html文件,写入phtml
         while (!feof($html_handle)) {
             $code = fgets($html_handle);
             //逐行读取html
             $code = preg_replace('/([src|href]=[\'\\"])(index)/', '$1/extract/' . $data['top_unique'], $code);
             //替换链接
             fwrite($phtml_handle, $code);
             //写入phtml
         }
         //关闭指针
         fclose($html_handle);
         fclose($phtml_handle);
         //移动资源文件,并重命名,与phtml文件相同
         $util->mv($zip_path . '/index', TOPIC_ROOT_PATH . '/' . $data['top_unique'], true);
     }
     //删除临时文件夹
     $util->rm($zip_path);
     //关闭zip指针
     $archive->close();
     $result = (new \Topic())->addTopic($this->session->get('id'), $data);
     if ($result != 200) {
         //删除所有专题相关文件
         $this->unlink($pic_add['host_file']);
         $this->unlink(TOPIC_HTML_PATH . '/' . $data['top_unique'] . '.phtml');
         $util->rm(TOPIC_ROOT_PATH . '/' . $data['top_unique']);
         $execJs('专题添加失败');
     }
     $execJs('专题添加成功');
 }
Example #9
0
 public function moveTo($destination)
 {
     return parent::moveTo($destination);
 }
Example #10
0
 /**
  * Check maximum file size
  *
  * @param File $file
  * @param $value
  * @return bool
  * @throws \Exception
  */
 public function checkMaxsize(File $file, $value)
 {
     if ($file->getSize() > (int) $value && $value !== null) {
         throw new \Exception(sprintf('The %s file is big. The maximum allowable %s', $file->getName(), $this->bytes($value)));
     }
     return true;
 }
Example #11
0
 /**
  * Check maximum file size
  *
  * @param \Phalcon\Http\Request\File $file
  * @param mixed $value
  * @return bool
  */
 public function checkMaxsize(\Phalcon\Http\Request\File $file, $value)
 {
     $pass = true;
     if ($value !== null && is_numeric($value)) {
         if ($file->getSize() > (int) $value) {
             $pass = false;
         }
     }
     return $pass;
 }
Example #12
0
 /**
  * Validates the file extension
  *
  * @param UploadedFile $uploadedFile
  *
  * @return void
  * @throws Exception
  */
 private function validateExtension(UploadedFile $uploadedFile)
 {
     $pathInfo = pathinfo($uploadedFile->getName());
     if (!isset($pathInfo['extension'])) {
         throw new Exception('No Extension Found(' . $uploadedFile->getName() . ')', 401);
     }
     $extension = strtolower($pathInfo['extension']);
     if (!in_array($extension, $this->getAllowedExtensions())) {
         throw new Exception('Invalid Type of File Uploaded, valid types: ' . implode(', ', $this->getAllowedExtensions()), 401);
     }
 }