/** * Executes the command logic with the specified RPC parameters. * * @param Object $params Command parameters sent from client. * @return Object Result object to be passed back to client. */ public function execute($params) { $toPath = $params->to; $ext = MOXMAN_Util_PathUtils::getExtension($toPath); if ($ext !== 'zip') { $toPath .= '.zip'; } $toFile = MOXMAN::getFile($toPath); $config = $toFile->getConfig(); if ($config->get('general.demo')) { throw new MOXMAN_Exception("This action is restricted in demo mode.", MOXMAN_Exception::DEMO_MODE); } if (!$toFile->canWrite()) { throw new MOXMAN_Exception("No write access to file: " . $toFile->getPublicPath(), MOXMAN_Exception::NO_WRITE_ACCESS); } $zipWriter = new MOXMAN_Zip_ZipWriter(array("compressionLevel" => 5)); $filter = MOXMAN_Vfs_BasicFileFilter::createFromConfig($config); $path = $params->path; foreach ($params->names as $name) { $fromFile = MOXMAN::getFile(MOXMAN_Util_PathUtils::combine($path, $name)); $this->addZipFiles($fromFile, $fromFile->getParent(), $filter, $zipWriter); } $stream = $toFile->open(MOXMAN_Vfs_IFileStream::WRITE); if ($stream) { $stream->write($zipWriter->toString()); $stream->close(); } $this->fireFileAction(MOXMAN_Core_FileActionEventArgs::ADD, $toFile); return $this->fileToJson($toFile); }
private function addVideoMeta(MOXMAN_Vfs_IFile $file, $metaData) { $fileName = $file->getName(); $ext = strtolower(MOXMAN_Util_PathUtils::getExtension($fileName)); if (preg_match('/^(mp4|ogv|webm)$/', $ext)) { $metaData->url_type = MOXMAN_Util_Mime::get($fileName); $name = substr($fileName, 0, strlen($fileName) - strlen($ext)); // Alternative video formats $altExt = array("mp4", "ogv", "webm"); foreach ($altExt as $altExt) { if ($ext != $altExt) { $altFile = MOXMAN::getFile($file->getParent(), $name . $altExt); if ($altFile->exists()) { $metaData->alt_url = $altFile->getUrl(); break; } } } // Alternative image format $altFile = MOXMAN::getFile($file->getParent(), $name . "jpg"); if ($altFile->exists()) { $metaData->alt_img = $altFile->getUrl(); } } }
/** * Get an unique file * * @param MOXMAN_Vfs_IFile $file File object to check against * @return MOXMAN_Vfs_IFile Unique file object. */ public static function uniqueFile(MOXMAN_Vfs_IFile $file) { $fileName = $file->getName(); $ext = MOXMAN_Util_PathUtils::getExtension($fileName); for ($i = 2; $file->exists(); $i++) { if ($file->isFile() && $ext) { $file = MOXMAN::getFile($file->getParent(), basename($fileName, '.' . $ext) . '_' . $i . '.' . $ext); } else { $file = MOXMAN::getFile($file->getParent(), $fileName . '_' . $i); } } return $file; }
/** * Sends the specified file with the correct mime type back to the browser. * This method gets called from the client side using the stream file. * * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler. */ public function processRequest(MOXMAN_Http_Context $httpContext) { $request = $httpContext->getRequest(); $response = $httpContext->getResponse(); try { $file = MOXMAN::getFile($request->get("path")); } catch (Exception $e) { $response->setStatus("500", "Could not resolve path: " . $request->get("path")); if (MOXMAN::getLogger()) { MOXMAN::getLogger()->debug("Could not resolve path: " . $request->get("path")); } return; } // Create thumbnail if ($request->get("thumb")) { try { $file = $this->plugin->createThumbnail($file); } catch (Exception $e) { $response->setStatus("500", "Could not generate thumbnail."); $response->sendContent("Could not generate thumbnail."); return; } } // Fire before stream event $args = new MOXMAN_Vfs_StreamEventArgs($httpContext, $file); $this->plugin->fire("BeforeStream", $args); $file = $args->getFile(); // Stream temp file if it exists if ($tempName = $request->get("tempname")) { $ext = MOXMAN_Util_PathUtils::getExtension($file->getName()); $tempName = "mcic_" . md5(session_id() . $file->getName()) . "." . $ext; $tempFilePath = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir(), $tempName); if (file_exists($tempFilePath)) { $response->sendLocalFile($tempFilePath); return; } } $url = $file->getUrl(); if ($url && !$request->get("stream", false)) { $response->redirect($url); } else { // Force 48h cache time $offset = 48 * 60 * 60; $response->setHeader("Cache-Control", "max-age=" . $offset); $response->setHeader("Date", gmdate("D, d M Y H:i:s", time() + $offset) . " GMT"); $response->setHeader("Expires", gmdate("D, d M Y H:i:s", time() + $offset) . " GMT"); $response->setHeader("Pragma", "public"); $response->sendFile($file); } }
/** * Executes the command logic with the specified RPC parameters. * * @param Object $params Command parameters sent from client. * @return Object Result object to be passed back to client. */ public function execute($params) { if (isset($params->action) && $params->action == "save") { return $this->save($params); } $file = MOXMAN::getFile($params->path); $config = $file->getConfig(); if (!$file->exists()) { throw new MOXMAN_Exception("File doesn't exist: " . $file->getPublicPath(), MOXMAN_Exception::FILE_DOESNT_EXIST); } $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "edit"); if ($filter->accept($file, true) !== MOXMAN_Vfs_CombinedFileFilter::ACCEPTED) { throw new MOXMAN_Exception("Invalid file name for: " . $file->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME); } // Create temp name if not specified $tempname = isset($params->tempname) ? $params->tempname : ""; if (!$tempname) { $ext = MOXMAN_Util_PathUtils::getExtension($file->getName()); $tempname = "mcic_" . md5(session_id() . $file->getName()) . "." . $ext; $tempFilePath = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir(), $tempname); if (file_exists($tempFilePath)) { unlink($tempFilePath); } $file->exportTo($tempFilePath); } else { $tempFilePath = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir(), $tempname); } $imageAlter = new MOXMAN_Media_ImageAlter(); $imageAlter->load($tempFilePath); // Rotate if (isset($params->rotate)) { $imageAlter->rotate($params->rotate); } // Flip if (isset($params->flip)) { $imageAlter->flip($params->flip == "h"); } // Crop if (isset($params->crop)) { $imageAlter->crop($params->crop->x, $params->crop->y, $params->crop->w, $params->crop->h); } // Resize if (isset($params->resize)) { $imageAlter->resize($params->resize->w, $params->resize->h); } $imageAlter->save($tempFilePath, $config->get("edit.jpeg_quality")); return (object) array("path" => $file->getPublicPath(), "tempname" => $tempname); }
/** * Fixes filenames * * @param MOXMAN_Vfs_IFile $file File to fix name on. */ public function renameFile(MOXMAN_Vfs_IFile $file) { $config = $file->getConfig(); $autorename = $config->get("autorename.enabled", ""); $spacechar = $config->get("autorename.space", "_"); $custom = $config->get("autorename.pattern", "/[^0-9a-z\\-_]/i"); $overwrite = $config->get("upload.overwrite", false); $lowercase = $config->get("autorename.lowercase", false); $prefix = $lowercase = $config->get("autorename.prefix", ''); // @codeCoverageIgnoreStart if (!$autorename) { return $file; } // @codeCoverageIgnoreEnd $path = $file->getPath(); $name = $file->getName(); $orgname = $name; $ext = MOXMAN_Util_PathUtils::getExtension($path); $name = preg_replace("/\\." . $ext . "\$/i", "", $name); $name = str_replace(array('\'', '"'), '', $name); $name = htmlentities($name, ENT_QUOTES, 'UTF-8'); $name = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', $name); $name = preg_replace($custom, $spacechar, $name); $name = str_replace(" ", $spacechar, $name); $name = trim($name); if ($lowercase) { $ext = strtolower($ext); $name = strtolower($name); } if ($ext) { $name = $name . "." . $ext; } //add prefix if ($prefix != '') { $aa = explode("-", $name); if (count($aa) == 1) { $name = $prefix . $name; } } // If no change to name after all this, return original file. if ($name === $orgname) { return $file; } // Return new file $toFile = MOXMAN::getFile($file->getParent() . "/" . $name); return $toFile; }
/** * Returns an array with media info. * * @param MOXMAN_Vfs_IFile $file File to get the media info for. * @return Array Name/value array with media info. */ public static function getInfo(MOXMAN_Vfs_IFile $file) { if (!$file->exists()) { return null; } $ext = strtolower(MOXMAN_Util_PathUtils::getExtension($file->getName())); switch ($ext) { case "png": return self::getPngInfo($file); default: if ($file instanceof MOXMAN_Vfs_Local_File) { $size = @getimagesize($file->getPath()); if ($size) { return array("width" => $size[0], "height" => $size[1]); } } } }
/** * Executes the command logic with the specified RPC parameters. * * @param Object $params Command parameters sent from client. * @return Object Result object to be passed back to client. */ public function execute($params) { if (!isset($params->template)) { throw new MOXMAN_Exception("You must specify a path to a template file to be used when creating documents"); } $templateFile = MOXMAN::getFile($params->template); $file = MOXMAN::getFile($params->path, $params->name . '.' . MOXMAN_Util_PathUtils::getExtension($templateFile->getName())); $config = $file->getConfig(); if ($config->get('general.demo')) { throw new MOXMAN_Exception("This action is restricted in demo mode.", MOXMAN_Exception::DEMO_MODE); } if (!$file->canWrite()) { throw new MOXMAN_Exception("No write access to file: " . $file->getPublicPath(), MOXMAN_Exception::NO_WRITE_ACCESS); } if ($file->exists()) { throw new MOXMAN_Exception("File already exist: " . $file->getPublicPath(), MOXMAN_Exception::FILE_EXISTS); } $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "createdoc"); if (!$filter->accept($file, true)) { throw new MOXMAN_Exception("Invalid file name for: " . $file->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME); } // TODO: Security audit this $stream = $templateFile->open(MOXMAN_Vfs_IFileStream::READ); if ($stream) { $content = $stream->readToEnd(); $stream->close(); } // Replace fields if (isset($params->fields)) { foreach ($params->fields as $key => $value) { $content = str_replace('${' . $key . '}', htmlentities($value), $content); } } $args = $this->fireBeforeFileAction("add", $file, strlen($content)); $file = $args->getFile(); // Write contents to file $stream = $file->open(MOXMAN_Vfs_IFileStream::WRITE); if ($stream) { $stream->write($content); $stream->close(); } $this->fireFileAction(MOXMAN_Vfs_FileActionEventArgs::ADD, $file); return $this->fileToJson($file, true); }
/** @ignore */ private function copyFile($fromFile, $toFile) { $config = $toFile->getConfig(); if ($config->get('general.demo')) { throw new MOXMAN_Exception("This action is restricted in demo mode.", MOXMAN_Exception::DEMO_MODE); } if (!$fromFile->exists()) { throw new MOXMAN_Exception("From file doesn't exist: " . $fromFile->getPublicPath(), MOXMAN_Exception::FILE_DOESNT_EXIST); } if (!$toFile->canWrite()) { throw new MOXMAN_Exception("No write access to file: " . $toFile->getPublicPath(), MOXMAN_Exception::NO_WRITE_ACCESS); } $filter = MOXMAN_Vfs_BasicFileFilter::createFromConfig($config); if ($filter->accept($fromFile, $fromFile->isFile()) !== MOXMAN_Vfs_BasicFileFilter::ACCEPTED) { throw new MOXMAN_Exception("Invalid file name for: " . $fromFile->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME); } // Fire before file action event $args = new MOXMAN_Core_FileActionEventArgs(MOXMAN_Core_FileActionEventArgs::COPY, $fromFile); $args->setTargetFile($toFile); $args->getData()->fileSize = $fromFile->getSize(); MOXMAN::getPluginManager()->get("core")->fire("BeforeFileAction", $args); $fromFile = $args->getFile(); $toFile = $args->getTargetFile(); // To file exists generate unique name $fileName = $toFile->getName(); $ext = MOXMAN_Util_PathUtils::getExtension($fileName); for ($i = 2; $toFile->exists(); $i++) { if ($toFile->isFile() && $ext) { $toFile = MOXMAN::getFile($toFile->getParent(), basename($fileName, '.' . $ext) . '_' . $i . '.' . $ext); } else { $toFile = MOXMAN::getFile($toFile->getParent(), $fileName . '_' . $i); } } $fromFile->copyTo($toFile); $this->fireTargetFileAction(MOXMAN_Core_FileActionEventArgs::COPY, $fromFile, $toFile); return $toFile; }
/** * Removes the local temp file for a specific file instance. * * @param MOXMAN_Vfs_IFile File instance used to create a local temp file. */ public function removeLocalTempFile(MOXMAN_Vfs_IFile $file) { if ($file->exists()) { $tempDir = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir($this->config), "moxman_blob_cache"); $tempFile = MOXMAN_Util_PathUtils::combine($tempDir, md5($file->getPath() . $file->getLastModified()) . "." . MOXMAN_Util_PathUtils::getExtension($file->getName())); if (file_exists($tempFile)) { unlink($tempFile); } } }
/** * Creates a thumbnail for the specified file and returns that file object * or the input file if thumbnails are disabled or not supported. * * @param MOXMAN_Vfs_IFile $file File to generate thumbnail for. * @return MOXMAN_Vfs_IFile File instance that got generated or input file. */ public function createThumbnail(MOXMAN_Vfs_IFile $file, $localTempFile = null) { $config = $file->getConfig(); // Thumbnails disabled in config if (!$config->get('thumbnail.enabled')) { return $file; } // File is not an image if (!MOXMAN_Media_ImageAlter::canEdit($file)) { return $file; } // No write access to parent path $dirFile = $file->getParentFile(); if (!$dirFile->canWrite()) { return $file; } $thumbnailFolderPath = MOXMAN_Util_PathUtils::combine($file->getParent(), $config->get('thumbnail.folder')); $thumbnailFile = MOXMAN::getFile($thumbnailFolderPath, $config->get('thumbnail.prefix') . $file->getName()); // Never generate thumbs in thumbs dirs if (basename($file->getParent()) == $config->get('thumbnail.folder')) { return $file; } $thumbnailFolderFile = $thumbnailFile->getParentFile(); if ($thumbnailFile->exists()) { if ($file->isDirectory()) { return $file; } return $thumbnailFile; } if (!$thumbnailFolderFile->exists()) { $thumbnailFolderFile->mkdir(); $this->fireThumbnailFileAction(MOXMAN_Vfs_FileActionEventArgs::ADD, $thumbnailFolderFile); } // TODO: Maybe implement this inside MOXMAN_Media_ImageAlter if ($file instanceof MOXMAN_Vfs_Local_File) { if ($config->get('thumbnail.use_exif') && function_exists("exif_thumbnail") && preg_match('/jpe?g/i', MOXMAN_Util_PathUtils::getExtension($file->getName()))) { $imageType = null; $width = 0; $height = 0; try { // Silently fail this, hence the @, some exif data can be corrupt. $exifImage = @exif_thumbnail($localTempFile ? $localTempFile : $file->getInternalPath(), $width, $height, $imageType); if ($exifImage) { $stream = $thumbnailFile->open(MOXMAN_Vfs_IFileStream::WRITE); $stream->write($exifImage); $stream->close(); $this->fireThumbnailFileAction(MOXMAN_Vfs_FileActionEventArgs::ADD, $thumbnailFile); return $thumbnailFile; } } catch (Exception $e) { // Ignore exif failure } } } $imageAlter = new MOXMAN_Media_ImageAlter(); if ($localTempFile) { $imageAlter->load($localTempFile); } else { $imageAlter->loadFromFile($file); } $imageAlter->createThumbnail($config->get('thumbnail.width'), $config->get('thumbnail.height'), $config->get('thumbnail.mode', "resize")); $imageAlter->saveToFile($thumbnailFile, $config->get('thumbnail.jpeg_quality')); $this->fireThumbnailFileAction(MOXMAN_Vfs_FileActionEventArgs::ADD, $thumbnailFile); return $thumbnailFile; }
/** * Returns true or false if the file is accepted or not. * * @param MOXMAN_Vfs_IFile $file File to grant or deny. * @param Boolean $isFile Default state if the filter is on an non existing file. * @return int Accepted or the reson why it failed. */ public function accept(MOXMAN_Vfs_IFile $file, $isFile = true) { $name = $file->getName(); $absPath = $file->getPath(); $isFile = $file->exists() ? $file->isFile() : $isFile; // Handle file patterns if ($isFile) { if ($this->dirsOnly) { if ($this->logFunction) { $this->log("File denied \"" . $absPath . "\" by \"dirsOnly\"."); } return self::INVALID_TYPE; } // Handle exclude files if (is_array($this->excludeFiles) && $isFile) { foreach ($this->excludeFiles as $fileName) { if ($name == $fileName) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"excludeFiles\"."); } return self::INVALID_NAME; } } } // Handle include files if (is_array($this->includeFiles) && $isFile) { $state = false; foreach ($this->includeFiles as $fileName) { if ($name == $fileName) { $state = true; break; } } if (!$state) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"includeFiles\"."); } return self::INVALID_NAME; } } // Handle exclude pattern if ($this->excludeFilePattern && preg_match($this->excludeFilePattern, $name)) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"excludeFilePattern\"."); } return self::INVALID_NAME; } // Handle include pattern if ($this->includeFilePattern && !preg_match($this->includeFilePattern, $name)) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"includeFilePattern\"."); } return self::INVALID_NAME; } // Handle file extension pattern if (is_array($this->extensions)) { $ext = MOXMAN_Util_PathUtils::getExtension($absPath); $valid = false; foreach ($this->extensions as $extension) { if ($extension == $ext) { $valid = true; break; } } if (!$valid) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"extensions\"."); } return self::INVALID_EXTENSION; } } } else { if ($this->filesOnly) { if ($this->logFunction) { $this->log("Dir denied \"" . $absPath . "\" by \"filesOnly\"."); } return self::INVALID_TYPE; } // Handle exclude folders if (is_array($this->excludeFolders)) { foreach ($this->excludeFolders as $folder) { if (strpos($absPath, $folder) !== false) { if ($this->logFunction) { $this->log('File denied "' . $absPath . '" by "excludeFolders".'); } return self::INVALID_NAME; } } } // Handle include folders if (is_array($this->includeFolders)) { $state = false; foreach ($this->includeFolders as $folder) { if (strpos($absPath, $folder) !== false) { $state = true; break; } } if (!$state) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"includeFolders\"."); } return self::INVALID_NAME; } } // Handle exclude pattern if ($this->excludeDirectoryPattern && preg_match($this->excludeDirectoryPattern, $name)) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"excludeDirectoryPattern\"."); } return self::INVALID_NAME; } // Handle include pattern if ($this->includeDirectoryPattern && !preg_match($this->includeDirectoryPattern, $name)) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"includeDirectoryPattern\"."); } return self::INVALID_NAME; } } // Handle include wildcard pattern if ($this->includeWildcardPattern && !$this->matchWildCard($this->includeWildcardPattern, $name)) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"includeWildcardPattern\"."); } return self::INVALID_NAME; } // Handle exclude wildcard pattern if ($this->excludeWildcardPattern && $this->matchWildCard($this->excludeWildcardPattern, $name)) { if ($this->logFunction) { $this->log("File \"" . $absPath . "\" denied by \"excludeWildcardPattern\"."); } return self::INVALID_NAME; } return self::ACCEPTED; }
/** * Process a request using the specified context. * * @param MOXMAN_Http_Context $httpContext Context instance to pass to use for the handler. */ public function processRequest(MOXMAN_Http_Context $httpContext) { $tempFilePath = null; $chunkFilePath = null; $request = $httpContext->getRequest(); $response = $httpContext->getResponse(); try { // Check if the user is authenticated or not if (!MOXMAN::getAuthManager()->isAuthenticated()) { if (!isset($json->method) || !preg_match('/^(login|logout)$/', $json->method)) { $exception = new MOXMAN_Exception("Access denied by authenticator(s).", 10); $exception->setData(array("login_url" => MOXMAN::getConfig()->get("authenticator.login_page"))); throw $exception; } } $file = MOXMAN::getFile($request->get("path")); $config = $file->getConfig(); if ($config->get('general.demo')) { throw new MOXMAN_Exception("This action is restricted in demo mode.", MOXMAN_Exception::DEMO_MODE); } $maxSizeBytes = preg_replace("/[^0-9.]/", "", $config->get("upload.maxsize")); if (strpos(strtolower($config->get("upload.maxsize")), "k") > 0) { $maxSizeBytes = round(floatval($maxSizeBytes) * 1024); } if (strpos(strtolower($config->get("upload.maxsize")), "m") > 0) { $maxSizeBytes = round(floatval($maxSizeBytes) * 1024 * 1024); } function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } $filename = generateRandomString() . '.' . MOXMAN_Util_PathUtils::getExtension($request->get("name")); $id = $request->get("id"); $loaded = intval($request->get("loaded", "0")); $total = intval($request->get("total", "-1")); $file = MOXMAN::getFile($file->getPath(), $filename); // Generate unique id for first chunk // TODO: We should cleanup orphan ID:s if upload fails etc if ($loaded == 0) { $id = uniqid(); } // Setup path to temp file based on id $tempFilePath = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir(), "mcupload_" . $id . "." . MOXMAN_Util_PathUtils::getExtension($file->getName())); $chunkFilePath = MOXMAN_Util_PathUtils::combine(MOXMAN_Util_PathUtils::getTempDir(), "mcupload_chunk_" . $id . "." . MOXMAN_Util_PathUtils::getExtension($file->getName())); if (!$file->canWrite()) { throw new MOXMAN_Exception("No write access to path: " . $file->getPublicPath(), MOXMAN_Exception::NO_WRITE_ACCESS); } if ($total > $maxSizeBytes) { throw new MOXMAN_Exception("File size to large: " . $file->getPublicPath(), MOXMAN_Exception::FILE_SIZE_TO_LARGE); } // Operations on first chunk if ($loaded == 0) { // Fire before file action add event $args = new MOXMAN_Core_FileActionEventArgs("add", $file); $args->getData()->fileSize = $total; MOXMAN::getPluginManager()->get("core")->fire("BeforeFileAction", $args); $file = $args->getFile(); if ($file->exists()) { if (!$config->get("upload.overwrite") && !$request->get("overwrite")) { throw new MOXMAN_Exception("Target file exists: " . $file->getPublicPath(), MOXMAN_Exception::FILE_EXISTS); } else { MOXMAN::getPluginManager()->get("core")->deleteThumbnail($file); $file->delete(); } } $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "upload"); if ($filter->accept($file) !== MOXMAN_Vfs_CombinedFileFilter::ACCEPTED) { throw new MOXMAN_Exception("Invalid file name for: " . $file->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME); } } $blobSize = 0; $inputFile = $request->getFile("file"); if (!$inputFile) { throw new MOXMAN_Exception("No input file specified."); } if ($loaded === 0) { // Check if we should mock or not if (defined('PHPUNIT')) { if (!copy($inputFile['tmp_name'], $tempFilePath)) { throw new MOXMAN_Exception("Could not move the uploaded temp file."); } } else { if (!move_uploaded_file($inputFile['tmp_name'], $tempFilePath)) { throw new MOXMAN_Exception("Could not move the uploaded temp file."); } } $blobSize = filesize($tempFilePath); } else { // Check if we should mock or not if (defined('PHPUNIT')) { if (!copy($inputFile['tmp_name'], $chunkFilePath)) { throw new MOXMAN_Exception("Could not move the uploaded temp file."); } } else { if (!move_uploaded_file($inputFile['tmp_name'], $chunkFilePath)) { throw new MOXMAN_Exception("Could not move the uploaded temp file."); } } $in = fopen($chunkFilePath, 'r'); if ($in) { $out = fopen($tempFilePath, 'a'); if ($out) { while ($buff = fread($in, 8192)) { $blobSize += strlen($buff); fwrite($out, $buff); } fclose($out); } fclose($in); } unlink($chunkFilePath); } // Import file when all chunks are complete if ($total == -1 || $loaded + $blobSize == $total) { clearstatcache(); // Check if file is valid on last chunk we also check on first chunk but not in the onces in between $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "upload"); if ($filter->accept($file) !== MOXMAN_Vfs_CombinedFileFilter::ACCEPTED) { throw new MOXMAN_Exception("Invalid file name for: " . $file->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME); } // Resize the temporary blob if ($config->get("upload.autoresize") && preg_match('/gif|jpe?g|png/i', MOXMAN_Util_PathUtils::getExtension($tempFilePath)) === 1) { $size = getimagesize($tempFilePath); $maxWidth = $config->get('upload.max_width'); $maxHeight = $config->get('upload.max_height'); if ($size[0] > $maxWidth || $size[1] > $maxHeight) { $imageAlter = new MOXMAN_Media_ImageAlter(); $imageAlter->load($tempFilePath); $imageAlter->resize($maxWidth, $maxHeight, true); $imageAlter->save($tempFilePath, $config->get("upload.autoresize_jpeg_quality")); } } // Create thumbnail and upload then import local blob MOXMAN::getPluginManager()->get("core")->createThumbnail($file, $tempFilePath); $file->importFrom($tempFilePath); unlink($tempFilePath); $args = new MOXMAN_Core_FileActionEventArgs("add", $file); MOXMAN::getPluginManager()->get("core")->fire("FileAction", $args); // In case file is modified $file = $args->getFile(); $result = MOXMAN_Core_Plugin::fileToJson($file, true); } else { $result = $id; } $response->sendJson(array("jsonrpc" => "2.0", "result" => $result, "id" => null)); } catch (Exception $e) { if ($tempFilePath && file_exists($tempFilePath)) { unlink($tempFilePath); } if ($chunkFilePath && file_exists($chunkFilePath)) { unlink($chunkFilePath); } MOXMAN::dispose(); // Closes any open file systems/connections $message = $e->getMessage(); $data = null; // Add file and line number when running in debug mode // @codeCoverageIgnoreStart if (MOXMAN::getConfig()->get("general.debug")) { $message .= " " . $e->getFile() . " (" . $e->getLine() . ")"; } // @codeCoverageIgnoreEnd // Grab the data from the exception if ($e instanceof MOXMAN_Exception && !$data) { $data = $e->getData(); } // Json encode error response $response->sendJson((object) array("jsonrpc" => "2.0", "error" => array("code" => $e->getCode(), "message" => $message, "data" => $data), "id" => null)); } }
/** * Returns true or false if the file is accepted or not. * * @param MOXMAN_Vfs_IFile $file File to grant or deny. * @param Boolean $isFile Default state if the filter is on an non existing file. * @return Boolean True/false if the file is accepted or not. */ public function accept(MOXMAN_Vfs_IFile $file, $isFile = true) { if ($this->isEmpty()) { return true; } $name = $file->getName(); $isFile = $file->exists() ? $file->isFile() : $isFile; // Handle file patterns if ($isFile) { if ($this->dirsOnly) { return false; } // Handle exclude files if ($this->excludeFiles) { foreach ($this->excludeFiles as $fileName) { if ($name == $fileName) { return false; } } } // Handle exclude pattern if ($this->excludeFilePattern && preg_match($this->excludeFilePattern, $name)) { return false; } // Handle include pattern if ($this->includeFilePattern && !preg_match($this->includeFilePattern, $name)) { return false; } // Handle file extension pattern if ($this->extensions) { $ext = MOXMAN_Util_PathUtils::getExtension($name); $valid = false; foreach ($this->extensions as $extension) { if ($extension == $ext) { $valid = true; break; } } if (!$valid) { return false; } } } else { if ($this->filesOnly) { return false; } // Handle exclude pattern if ($this->excludeDirectoryPattern && preg_match($this->excludeDirectoryPattern, $name)) { return false; } // Handle include pattern if ($this->includeDirectoryPattern && !preg_match($this->includeDirectoryPattern, $name)) { return false; } } // Handle include wildcard pattern if ($this->includeWildcardPatternRegExp && !preg_match($this->includeWildcardPatternRegExp, $name)) { return false; } // Handle exclude wildcard pattern if ($this->excludeWildcardPatternRegExp && preg_match($this->excludeWildcardPatternRegExp, $name)) { return false; } return true; }
/** * Returns true/false if the specified file can be altered or not. * * @param MOXMAN_Vfs_IFile $file File to check if can be altered. * @return Boolean True/false if the image can be edited or not. */ public static function canEdit(MOXMAN_Vfs_IFile $file) { $ext = MOXMAN_Util_PathUtils::getExtension($file->getName()); return preg_match('/gif|jpe?g|png|bmp/', $ext) === 1; }