Example #1
0
 /**
  * 创建本地文件夹
  * @param string $dir 文件夹路径
  * @param int $mode 权限
  * @param bool $recursive
  * @return mixed $value 返回最终需要执行完的结果
  */
 public static function MkDirsLocal($dir, $mode = 0777, $recursive = true)
 {
     if (is_null($dir) || $dir == "") {
         return false;
     }
     if (is_dir($dir) || $dir == "/") {
         return true;
     }
     if (MUtils::MkDirsLocal(dirname($dir), $mode, $recursive)) {
         return mkdir($dir, $mode);
     }
     return false;
 }
Example #2
0
 /**
  * 打包下载
  * @param $paths
  * @param $filePath
  * @throws MFileopsException
  */
 public function downloadToPackage($paths, $filePath)
 {
     $userId = $this->user['id'];
     $parentPath = dirname($filePath);
     $isSharedPath = false;
     //主要用于判断是否为被共享文件
     if (dirname(MiniUtil::getRelativePath($filePath)) == "/" . $userId) {
         $permission = MConst::SUPREME_PERMISSION;
     } else {
         $pathArr = explode('/', $filePath);
         $masterId = $pathArr[1];
         if ($masterId != $userId) {
             $isSharedPath = true;
         } else {
             $model = new GeneralFolderPermissionBiz($parentPath);
             if ($model->isParentShared($parentPath)) {
                 //如果是父目录被共享
                 $isSharedPath = true;
             }
         }
         if ($isSharedPath) {
             $permissionArr = UserPermissionBiz::getInstance()->getPermission($parentPath, $userId);
             if (!isset($permissionArr)) {
                 $permission = MConst::SUPREME_PERMISSION;
             } else {
                 $permission = $permissionArr['permission'];
                 $privilegeModel = new PrivilegeBiz();
                 $this->share_filter->slaves = $privilegeModel->getSlaveIdsByPath($permissionArr['share_root_path']);
                 $this->share_filter->is_shared = true;
             }
         } else {
             $permission = MConst::SUPREME_PERMISSION;
         }
     }
     $miniPermission = new MiniPermission($permission);
     $canDownload = $miniPermission->canDownload();
     if (!$canDownload) {
         throw new MFileopsException(Yii::t('api', 'no permission'), MConst::HTTP_CODE_409);
     }
     $arr = explode('/', $filePath);
     $isRoot = false;
     $isMine = false;
     if (count($arr) == 3) {
         $isRoot = true;
     }
     $fileOwnerId = $arr[1];
     $currentUser = $this->user;
     $currentUserId = $currentUser['user_id'];
     if ($fileOwnerId == $currentUserId) {
         $isMine = true;
     }
     if ($isRoot && !$isMine) {
         //如果是在根目录下且不是自己的目录 则后台控制不准取消共享
         throw new MFileopsException(Yii::t('api', 'Internal Server Error'), MConst::HTTP_CODE_409);
     }
     //打包下载限制
     header("Content-type: text/html; charset=utf-8");
     $limit = new DownloadPackageLimit();
     $limitCount = $limit->getLimitCount();
     $limitSize = $limit->getLimitSize();
     $code = '';
     $fileNames = array();
     $user = $this->user;
     $userId = $user['user_id'];
     $paths = explode(',', $paths);
     foreach ($paths as $path) {
         $file = MiniFile::getInstance()->getByPath($path);
         if (empty($file)) {
             echo "批量下载的文件存在不存在的文件";
             exit;
         }
         $code = $code . ',' . $file['id'];
         array_push($fileNames, $file['file_name']);
     }
     if (count($fileNames) > 1) {
         $packageName = 'miniyun';
     } else {
         $packageName = $fileNames[0];
     }
     //创建临时文件夹
     $fileSystem = new CFileSystem();
     MUtils::MkDirsLocal(DOCUMENT_TEMP . $userId);
     $storePath = DOCUMENT_TEMP . $userId . "/" . $packageName;
     $array = array();
     $ids = explode(",", $code);
     foreach ($ids as $id) {
         $file = MiniFile::getInstance()->getById($id);
         if (empty($file)) {
             continue;
         }
         if ($file["file_type"] == MConst::OBJECT_TYPE_FILE) {
             //属于自己的文件
             $array[] = $file;
         } else {
             //不属于自己的文件
             //查询共有多少个子目录
             $array[] = $file;
             $files = MiniFile::getInstance()->getChildrenByPath($file["file_path"]);
             $array = array_merge($array, $files);
         }
     }
     if (count($array) > $limitCount) {
         echo "批量下载单次最大文件数不能超过:" . $limitCount;
         exit;
     }
     $size = $this->calculateSize($array);
     if ($size > $limitSize * 1024 * 1024) {
         echo "批量下载单次最大文件大小不能超过:" . $limitSize . "M";
         exit;
     }
     $path = CUtils::removeUserFromPath($array[0]["file_path"]);
     $removeParent = pathinfo($path, PATHINFO_DIRNAME);
     if (strlen($removeParent) == 1) {
         $removeParent = "";
     }
     //zip压缩
     $zip = new ZipArchive();
     $zipFile = $storePath . ".zip";
     //删除上次存在的压缩文件
     $fileSystem->delete($zipFile);
     try {
         $zipFile = mb_convert_encoding($zipFile, "gb2312", "UTF-8");
     } catch (Exception $e) {
         $zipFile = $zipFile;
     }
     if ($zip->open($zipFile, ZIPARCHIVE::OVERWRITE) === TRUE) {
         //执行拷贝操作
         foreach ($array as $file) {
             $fileType = $file["file_type"];
             $filePath = $file["file_path"];
             //获取存储文件的绝对路径
             if (!empty($removeParent)) {
                 $relativePath = CUtils::str_replace_once($removeParent, "", CUtils::removeUserFromPath($filePath));
             } else {
                 $relativePath = CUtils::removeUserFromPath($filePath);
             }
             //打包加上nick
             $relativePath = $packageName . $relativePath;
             //转换文件编码为中文编码
             try {
                 $store = mb_convert_encoding($relativePath, "gb2312", "UTF-8");
             } catch (Exception $e) {
                 $store = $relativePath;
             }
             $hasRead = true;
             if ($userId == $file["user_id"] && $fileType == MConst::OBJECT_TYPE_FILE) {
                 //属于自己的文件
                 $this->addToFile($zip, $file, $store, $fileSystem);
             } elseif ($userId != $file["user_id"] && $fileType == MConst::OBJECT_TYPE_FILE) {
                 //不属于自己的文件
                 if ($hasRead) {
                     $this->addToFile($zip, $file, $store, $fileSystem);
                 }
             } elseif ($userId == $file["user_id"] && $fileType == MConst::OBJECT_TYPE_DIRECTORY) {
                 //属于自己的文件夹
                 $this->addToFolder($zip, $store);
             } else {
                 //不属于自己的文件夹
                 if ($hasRead) {
                     $this->addToFolder($zip, $store);
                 }
             }
         }
         $zip->close();
         //关闭
     }
     if (!file_exists($zipFile)) {
         echo Yii::t('i18n', 'no_privilege');
         Yii::app()->end();
     }
     //进行下载
     CUtils::output($zipFile, "application/octet-stream", $packageName . ".zip");
 }
Example #3
0
 /**
  * 在线浏览文件获得内容
  * @param string $path 文件当前路径
  * @param string $type 文件类型,可选择pdf/png
  * @throws
  * @return NULL
  */
 public function previewContent($path, $type)
 {
     $file = MiniFile::getInstance()->getByPath($path);
     // 权限处理
     if (empty($file)) {
         return array('success' => false, 'msg' => 'file not existed');
     }
     $fileBiz = new FileBiz();
     $canRead = $fileBiz->privilege($path);
     if (!$canRead) {
         throw new MFileopsException(Yii::t('api', 'no permission'), MConst::HTTP_CODE_409);
     }
     //获得文件当前版本对应的version
     $version = PluginMiniDocVersion::getInstance()->getVersion($file["version_id"]);
     $signature = $version["file_signature"];
     $localPath = PluginMiniDocOption::getInstance()->getMiniDocCachePath() . $signature . "/" . $signature . "." . $type;
     if (!file_exists($localPath)) {
         //文档还在转换中
         $node = PluginMiniDocNode::getInstance()->getConvertNode($signature);
         if (empty($node)) {
             throw new MFileopsException(Yii::t('api', 'convert error'), MConst::HTTP_CODE_412);
         }
         //根据情况判断是否需要向迷你文档拉取内容
         $parentPath = dirname($localPath);
         //如果缓存目录不存在,则需要创建
         if (!file_exists($parentPath)) {
             MUtils::MkDirsLocal($parentPath);
         }
         //文件不存在,则需要从迷你文档拉取文件内容
         $url = PluginMiniDocNode::getInstance()->getDownloadUrl($node["id"], $version, $type);
         $http = new HttpClient();
         $http->get($url);
         $status = $http->get_status();
         if ($status == "200") {
             $content = $http->get_body();
             //把文件内容存储到本地硬盘
             file_put_contents($localPath, $content);
             Yii::log($signature . " get " . $type . " success", CLogger::LEVEL_INFO, "doc.convert");
         } else {
             if (!($version["doc_convert_status"] == -1)) {
                 //如迷你文档服务器不存在该文档,说明迷你文档服务器发生了变动
                 //这个时候自动启动负载均衡机制,把文档重新转换
                 PluginMiniDocVersion::getInstance()->pushConvertSignature($signature, "");
                 Yii::log($signature . " get " . $type . " error", CLogger::LEVEL_ERROR, "doc.convert");
             }
         }
     }
     if (file_exists($localPath)) {
         if ($type === "png") {
             $contentType = "image/png";
         }
         if ($type === "pdf") {
             $contentType = "Content-type: application/pdf";
         }
         //Firefox+混合云模式下直接输出内容
         //其它浏览器使用sendfile模式输出内容
         $isSendFile = true;
         if (MiniUtil::isMixCloudVersion()) {
             $ua = isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : NULL;
             if (strpos($ua, "Firefox") > 0 || strpos($ua, "Safari") > 0) {
                 $isSendFile = false;
             }
         }
         if ($isSendFile) {
             header('Location: ' . MiniHttp::getMiniHost() . "assets/minidoc/" . $signature . "/" . $signature . "." . $type);
         } else {
             Header("Content-type: " . $contentType);
             echo file_get_contents($localPath);
             exit;
         }
     }
 }
Example #4
0
 /**
  * 创建对象
  */
 public function create()
 {
     // 查询文件信息
     $path = MiniUtil::getAbsolutePath($this->user_id, $this->path);
     $file = MiniFile::getInstance()->getByPath($path);
     if (empty($file)) {
         throw new MException(Yii::t('api', MConst::PATH_ERROR), MConst::HTTP_CODE_404);
     }
     $fileName = $file["file_name"];
     $fileSize = $file["file_size"];
     $versionId = $file["version_id"];
     // 检查是否支持缩略图
     $this->checkExistThumbnail($fileName, $fileSize);
     // 获取文件版本
     $version = MFileVersions::queryFileVersionByID($versionId);
     if (count($version) == 0) {
         throw new MException(Yii::t('api', MConst::PATH_ERROR), MConst::HTTP_CODE_404);
     }
     // 获取文件存储路径
     $isTmp = false;
     $signature = $_REQUEST["signature"];
     if (empty($signature) || $signature === "undefined") {
         $signature = $version[0]["file_signature"];
     }
     // 缩略图大小
     $sizeInfo = self::$sizes[$this->size];
     if ($sizeInfo === NULL) {
         $sizeStr = strtolower($this->size);
         $sizeList = explode("x", $sizeStr);
         $sizeInfo = array("w" => $sizeList[0], "h" => $sizeList[1]);
     }
     $this->width = $sizeInfo["w"];
     $this->height = $sizeInfo["h"];
     // 检查缩略图是否存在
     $thumbnail = THUMBNAIL_TEMP . MiniUtil::getPathBySplitStr($signature);
     $thumbnail .= "_{$this->width}_{$this->height}.{$this->format}";
     if (file_exists($thumbnail) == true) {
         //直接跳转,避免重复生成缩略图
         $url = MiniHttp::getMiniHost() . "assets/thumbnails/" . MiniUtil::getPathBySplitStr($signature);
         $url .= "_{$this->width}_{$this->height}.{$this->format}";
         header('Location: ' . $url);
         exit;
     }
     //判断文件是否在迷你存储中,兼容非迷你存储的文件
     $version = MiniVersion::getInstance()->getBySignature($signature);
     $meta = MiniVersionMeta::getInstance()->getMeta($version["id"], "store_id");
     $thumbnailData = array();
     if (!empty($meta)) {
         //为迷你存储缩略图添加hook
         $thumbnailData["signature"] = $signature;
         $storePath = apply_filters("image_path", $thumbnailData);
     }
     if (empty($storePath) || $storePath === $thumbnailData) {
         //data源处理对象
         $dataObj = Yii::app()->data;
         $signaturePath = MiniUtil::getPathBySplitStr($signature);
         if ($dataObj->isExistLocal()) {
             $storePath = $dataObj->documentStorePath($signaturePath) . $signaturePath;
         }
     }
     if (file_exists($storePath) == false) {
         throw new MException(Yii::t('api', "The file path was not found."), MConst::HTTP_CODE_404);
     }
     $pathInfo = MUtils::pathinfo_utf($fileName);
     $extension = $pathInfo["extension"];
     $tmpPath = DOCUMENT_TEMP . $signature . ".{$extension}";
     // 缩略图对象
     $this->handler = NULL;
     $this->image = $tmpPath;
     $this->resize = true;
     // 创建缩略图片父目录
     if (file_exists(dirname($thumbnail)) == false) {
         if (MUtils::MkDirsLocal(dirname($thumbnail)) == false) {
             throw new MException(Yii::t('api', "The file path was not found."), MConst::HTTP_CODE_404);
         }
     }
     // 临时文件父目录
     if (file_exists(dirname($tmpPath)) == false) {
         if (MUtils::MkDirsLocal(dirname($tmpPath)) == false) {
             throw new MException(Yii::t('api', "The file path was not found."), MConst::HTTP_CODE_404);
         }
     }
     // 拷贝文件到临时目录
     if (file_exists($tmpPath) == false) {
         if (copy($storePath, $tmpPath) == false) {
             throw new MException(Yii::t('api', "The file path was not found."), MConst::HTTP_CODE_404);
         }
     }
     // 如果图片格式与后缀不一致,转换为一致的
     if ($this->format != strtolower($extension)) {
         $fm = new Image($tmpPath);
         $format_path = DOCUMENT_TEMP . $signature . ".{$this->format}";
         $fm->save($format_path);
         // 转换成功删除临时文件
         unlink($tmpPath);
         $this->image = $format_path;
     }
     if ($isTmp) {
         unlink($storePath);
     }
     // 初始化图像对象
     try {
         $this->handler = new Image($this->image, isset($this->config) ? $this->config : NULL);
     } catch (MException $e) {
         Yii::log("Exception : {$e->getTraceAsString()}");
         throw new MException(Yii::t('api', "The image is invalid and cannot be thumbnailed."), MConst::HTTP_CODE_415);
     }
     // 生成缩略图
     if ($this->resize == true) {
         $this->handler->resize($this->width, $this->height)->rotate(0)->quality(75)->sharpen(20);
         $chmod = 0644;
         $keep_actions = true;
         try {
             $this->handler->save($thumbnail, $chmod, $keep_actions);
             $this->handler->setImageFile($thumbnail);
             $this->image = $thumbnail;
             @unlink($format_path);
         } catch (MException $e) {
             Yii::trace("Exception : {$e}", "miniyun.api");
             throw new MException(Yii::t('api', "The image is invalid and cannot be thumbnailed."), MConst::HTTP_CODE_415);
         }
     }
 }
Example #5
0
 private function hanleDescription($des_path, $cache, $total_size, $block_size, $hash)
 {
     //
     // 如果描述文件或者临时文件不存在则创建
     //
     $blocks = "";
     $count = $this->handleGetBlockCount($total_size, $block_size);
     if (!file_exists($des_path)) {
         if (!MUtils::MkDirsLocal(dirname($des_path))) {
             throw new MFilesException(Yii::t('api', MConst::INTERNAL_SERVER_ERROR), MConst::HTTP_CODE_500);
         }
         $description = array();
         for ($i = 0; $i < $count; $i++) {
             $blocks .= "0";
         }
         $description['hash'] = $hash;
         $description['total_size'] = $total_size;
         $description['block_size'] = $block_size;
         $description['blocks'] = $blocks;
         file_put_contents($des_path, serialize($description));
     } else {
         $str = file_get_contents($des_path);
         $description = unserialize($str);
     }
     // 临时文件
     if (!file_exists($cache) || filesize($cache) != $total_size) {
         $fp = fopen($cache, "wb");
         fseek($fp, $total_size - 1);
         fwrite($fp, "");
         fclose($fp);
         $blocks = "";
         for ($i = 0; $i < $count; $i++) {
             $blocks .= "0";
         }
         $description['blocks'] = $blocks;
     }
     //
     // 如果总大小不一致,则返回错误
     //
     if ($total_size != $description['total_size']) {
         throw new MFilesException(Yii::t('api', MConst::PARAMS_ERROR), MConst::HTTP_CODE_400);
     }
     return $description;
 }