private function sendRequest(MOXMAN_Util_Config $config) { $secretKey = $config->get("ExternalAuthenticator.secret_key"); $authUrl = $config->get("ExternalAuthenticator.external_auth_url"); $url = ""; $defaultPort = 80; if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") { $url = "https://"; $defaultPort = 443; } $url .= $_SERVER['HTTP_HOST']; if ($_SERVER['SERVER_PORT'] != $defaultPort) { $url .= ':' . $defaultPort; } $httpClient = new MOXMAN_Http_HttpClient($url); $httpClient->setProxy($config->get("general.http_proxy", "")); $authUrl = MOXMAN_Util_PathUtils::toAbsolute(dirname($_SERVER["REQUEST_URI"]) . '/plugins/ExternalAuthenticator', $authUrl); $request = $httpClient->createRequest($authUrl, "POST"); $authUser = $config->get("ExternalAuthenticator.basic_auth_user"); $authPw = $config->get("ExternalAuthenticator.basic_auth_password"); if ($authUser && $authPw) { $request->setAuth($authUser, $authPw); } $cookie = isset($_SERVER["HTTP_COOKIE"]) ? $_SERVER["HTTP_COOKIE"] : ""; if ($cookie) { $request->setHeader('cookie', $cookie); } $seed = hash_hmac('sha256', $cookie . uniqid() . time(), $secretKey); $hash = hash_hmac('sha256', $seed, $secretKey); $response = $request->send(array("seed" => $seed, "hash" => $hash)); if ($response->getCode() < 200 || $response->getCode() > 399) { throw new MOXMAN_Exception("Did not get a proper http status code from Auth url: " . $url . $authUrl . ".", $response->getCode()); } return $response->getBody(); }
/** * Initializes the storage instance. * * @param MOXMAN_Util_Config $config Config instance. * @param int $type Storage type to use, can be any of the type constants. * @param string $name Name of the user/group if those types are used or an empty string. */ public function initialize($config, $type, $name) { $this->config = $config; $this->type = $type; $this->name = $name; $this->storagePath = MOXMAN_Util_PathUtils::combine($config->get("storage.path"), ($name ? $type . "." . $name : $type) . ".json"); }
/** * 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); }
/** * 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) { $request = $httpContext->getRequest(); $response = $httpContext->getResponse(); $path = $request->get("path"); $names = explode('/', $request->get("names", "")); $zipName = $request->get("zipname", "files.zip"); if (count($names) === 1) { $file = MOXMAN::getFile(MOXMAN_Util_PathUtils::combine($path, $names[0])); $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig(MOXMAN::getFile($path)->getConfig(), "download"); if (!$filter->accept($file)) { throw new MOXMAN_Exception("Invalid file name for: " . $file->getPublicPath(), MOXMAN_Exception::INVALID_FILE_NAME); } if ($file->isFile()) { $response->sendFile($file, true); return; } } // Download multiple files as zip $zipWriter = new MOXMAN_Zip_ZipWriter(array("compressionLevel" => 0)); // Setup download headers $response->disableCache(); $response->setHeader("Content-type", "application/octet-stream"); $response->setHeader("Content-Disposition", 'attachment; filename="' . $zipName . '"'); $filter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig(MOXMAN::getFile($path)->getConfig(), "download"); // Combine files to zip foreach ($names as $name) { $fromFile = MOXMAN::getFile(MOXMAN_Util_PathUtils::combine($path, $name)); $this->addZipFiles($fromFile, $fromFile->getParent(), $filter, $zipWriter); } $response->sendContent($zipWriter->toString()); }
/** * Verifies the input path against various exploits and throws exceptions if one is found. * * @param String $path Path to verify. * @param String $fileType File type to verify path against. Values: dir or file. */ public function verifyPath($path, $fileType = null) { // Verfiy that the path doesn't have any abnormalities if (preg_match('/\\\\|\\.\\.\\/|[\\x00-\\x19]/', $path)) { throw new MOXMAN_Exception("Specified path has invalid characters."); } $path = MOXMAN_Util_PathUtils::toUnixPath($path); if (preg_match('~IIS/(\\d+\\.\\d+)~', $_SERVER['SERVER_SOFTWARE'], $matches)) { $version = floatval($matches[1]); if ($version < 7) { if (strpos($path, ';') !== false) { if ($this->getConfig()->get("filesystem.local.warn_semicolon", true)) { throw new MOXMAN_Exception("IIS 6 doesn't support semicolon in paths for security reasons.", MOXMAN_Exception::INVALID_FILE_NAME); } } if (preg_match('/\\.[^\\/]+\\//', $path) || $fileType == "dir" && strpos($path, '.') !== false) { if ($this->getConfig()->get("filesystem.local.warn_dot_dirs", true)) { throw new MOXMAN_Exception("IIS 6 don't support dots in directory names for security reasons.", MOXMAN_Exception::INVALID_FILE_NAME); } } } } else { if (preg_match('/.(php|inc|php\\d+|phtml|php[st])\\.[^\\/]+/', $path)) { if ($this->getConfig()->get("filesystem.local.warn_double_exts", true)) { throw new MOXMAN_Exception("Double extensions is not allowed for security reasons.", MOXMAN_Exception::INVALID_FILE_NAME); } } } }
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(); } } }
/** * Returns a config based on the specified file. * * @param MOXMAN_Vfs_IFile $file File to get the config for. * @return MOXMAN_Util_Config Config for the specified file. */ public function getConfig(MOXMAN_Vfs_IFile $file) { $config = clone $this->config; $path = $file->isFile() ? $file->getParent() : $file->getPath(); $root = $this->fileSystem->getRootPath(); $mcAccessFile = $this->config->get("filesystem.local.access_file_name", "mc_access"); $user = MOXMAN::getUser(); $configFiles = array(); $targetConfigPath = $path . '/' . $mcAccessFile; // Collect config files while ($path && strlen($path) >= strlen($root)) { if (file_exists($path . '/' . $mcAccessFile)) { $configFiles[] = $path . '/' . $mcAccessFile; } $path = MOXMAN_Util_PathUtils::getParent($path); } // Extend current config with the config files for ($i = count($configFiles) - 1; $i >= 0; $i--) { // Parse mc_access file $iniParser = new MOXMAN_Util_IniParser(); $iniParser->load($configFiles[$i]); // Loop and extend it $items = $iniParser->getItems(); foreach ($items as $key => $value) { // Group specific config if (is_array($value)) { $targetGroups = explode(',', $key); foreach ($targetGroups as $targetGroup) { if ($user->isMemberOf($targetGroup)) { foreach ($value as $key2 => $value2) { if (strpos($key2, '_') === 0) { if ($targetConfigPath == $configFiles[$i]) { $key2 = substr($key2, 1); } else { continue; } } $config->put($key2, $value2); } } } } else { if (strpos($key, '_') === 0) { if ($targetConfigPath == $configFiles[$i]) { $key = substr($key, 1); } else { continue; } } $config->put($key, $value); } } } return $config; }
/** * Returns a file object out of the specified URL. * * @param string Absolute URL for the specified file. * @return MOXMAN_Vfs_IFile File that got resolved or null if it wasn't found. */ public function getFile($url) { $prefix = "http://memory"; $file = null; if (strpos($url, $prefix) === 0) { $filePath = substr($url, strlen($prefix)); if (MOXMAN_Util_PathUtils::isChildOf($filePath, $this->fileSystem->getRootPath())) { return $this->fileSystem->getFile($filePath); } } return $file; }
/** * 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); } }
/** * 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) { $config = MOXMAN::getConfig(); $response = $httpContext->getResponse(); $response->disableCache(); $response->setHeader('Content-type', 'text/html'); if (!$config->get("general.debug")) { $response->sendContent("Debugging not configured, you need to set general.debug to true in config.php file."); return; } $request = $httpContext->getRequest(); if ($request->get("info")) { phpinfo(); return; } $sitepaths = MOXMAN_Util_PathUtils::getSitePaths(); $scriptFilename = $_SERVER["SCRIPT_FILENAME"]; if (realpath($scriptFilename) != $scriptFilename) { $scriptFilename = $scriptFilename . "<br />(" . realpath($scriptFilename) . ")"; } if (function_exists("imagecreatefromjpeg")) { $gdInfo = gd_info(); $outInfo = "Ver:" . $gdInfo["GD Version"]; $outInfo .= " GIF:" . ($gdInfo["GIF Create Support"] ? "Y" : "N"); $outInfo .= " PNG:" . ($gdInfo["PNG Support"] ? "Y" : "N"); $outInfo .= " JPEG:" . ($gdInfo["JPEG Support"] ? "Y" : "N"); } else { $outInfo = "N/A"; $gdInfo = array(); } $user = MOXMAN::getAuthManager()->getUser(); $result = array("MOXMAN_ROOT" => MOXMAN_ROOT, "realpath('.')" => realpath("."), "Config.php rootpath" => $config->get("filesystem.rootpath"), "Config.php wwwroot" => $config->get("filesystem.local.wwwroot"), "wwwroot resolve" => $sitepaths["wwwroot"], "wwwroot realpath" => realpath($sitepaths["wwwroot"]), "prefix resolve" => $sitepaths["prefix"], "storage path" => MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path")), "storage writable" => is_writable(MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path"))), "script filename" => $scriptFilename, "script name" => $_SERVER["SCRIPT_NAME"], "GD" => $outInfo, "memory_limit" => @ini_get("memory_limit"), "upload_max_filesize" => @ini_get("upload_max_filesize"), "post_max_size" => @ini_get("post_max_size"), "file_uploads" => @ini_get("file_uploads") ? "Yes" : "No", "PHP Version" => phpversion(), "Time" => date('Y-m-d H:i:s', time()), "Time UTC" => date('Y-m-d H:i:s', time() - date("Z")), "Authenticated" => MOXMAN::getAuthManager()->isAuthenticated(), "User" => $user ? $user->getName() : "N/A"); $out = "<html><body><table border='1'>"; foreach ($result as $name => $value) { if ($value === true) { $value = "True"; } else { if ($value === false) { $value = "False"; } } $out .= "<tr>"; $out .= "<td>" . $name . " </td><td>" . $value . " </td>"; $out .= "</tr>"; } $out .= "</table><a href='?action=debug&info=true'>Show phpinfo</a>"; $out .= "</body></html>"; $response->sendContent($out); }
/** * Returns a file object out of the specified URL. * * @param string Absolute URL for the specified file. * @return MOXMAN_Vfs_IFile File that got resolved or null if it wasn't found. */ public function getFile($url) { $file = null; $prefix = $this->fileSystem->getContainerOption("urlprefix"); $containerName = $this->fileSystem->getContainerOption("name"); $containerKey = $this->fileSystem->getContainerOption("key"); $match = MOXMAN_Util_PathUtils::combine($prefix, $containerName); if (strpos($url, $match) === 0) { $bucketpath = MOXMAN_Util_PathUtils::combine($prefix, $containerName); $filePath = MOXMAN_Util_PathUtils::combine("azure://" . $containerKey, substr($url, strlen($bucketpath))); if (MOXMAN_Util_PathUtils::isChildOf($filePath, $this->fileSystem->getRootPath())) { return $this->fileSystem->getFile($filePath); } } return $file; }
/** * Returns a file object out of the specified URL. * * @param string Absolute URL for the specified file. * @return MOXMAN_Vfs_IFile File that got resolved or null if it wasn't found. */ public function getFile($url) { $file = null; $prefix = $this->fileSystem->getBucketOption("urlprefix"); $prefix = preg_replace('/^https?:\\/\\//', '//', $prefix); $url = preg_replace('/^https?:\\/\\//', '//', $url); if (strpos($url, $prefix) === 0) { $bucketKey = $this->fileSystem->getBucketOption("key"); $path = urldecode(substr($url, strlen($prefix))); $filePath = MOXMAN_Util_PathUtils::combine("s3://" . $bucketKey, $path); if (MOXMAN_Util_PathUtils::isChildOf($filePath, $this->fileSystem->getRootPath())) { return $this->fileSystem->getFile($filePath); } } return $file; }
/** * 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 a file object out of the specified URL. * * @param string Absolute URL for the specified file. * @return MOXMAN_Vfs_IFile File that got resolved or null if it wasn't found. */ public function getFile($url) { $config = $this->fileSystem->getConfig(); $file = null; // Get config items $wwwroot = $config->get("filesystem.local.wwwroot"); $prefix = $config->get("filesystem.local.urlprefix"); $paths = MOXMAN_Util_PathUtils::getSitePaths(); // No wwwroot specified try to figure out a wwwroot if (!$wwwroot) { $wwwroot = $paths["wwwroot"]; } else { // Force the www root to an absolute file system path $wwwroot = MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $wwwroot); } // Add prefix to URL if ($prefix == "") { $prefix = MOXMAN_Util_PathUtils::combine("{proto}://{host}", $paths["prefix"]); } // Replace protocol if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") { $prefix = str_replace("{proto}", "https", $prefix); } else { $prefix = str_replace("{proto}", "http", $prefix); } // Replace host/port $prefix = str_replace("{host}", $_SERVER['HTTP_HOST'], $prefix); $prefix = str_replace("{port}", $_SERVER['SERVER_PORT'], $prefix); // Remove prefix from url if ($prefix && strpos($url, $prefix) === 0) { $url = substr($url, strlen($prefix)); } // Parse url and check if path part of the URL is within the root of the file system $url = parse_url($url); if (isset($url["path"])) { $path = MOXMAN_Util_PathUtils::combine($wwwroot, $url["path"]); if (MOXMAN_Util_PathUtils::isChildOf($path, $this->fileSystem->getRootPath())) { // Crop away root path part and glue it back on again since the case might be different // For example: c:/inetpub/wwwroot and C:/InetPub/WWWRoot this will force it into the // valid fileSystem root path prefix $path = substr($path, strlen($this->fileSystem->getRootPath())); $path = MOXMAN_Util_PathUtils::combine($this->fileSystem->getRootPath(), $path); $file = $this->fileSystem->getFile($path); } } return $file; }
public function authenticate(MOXMAN_Auth_User $user) { $config = MOXMAN::getConfig(); $secretKey = $config->get("ExternalAuthenticator.secret_key"); $authUrl = $config->get("ExternalAuthenticator.external_auth_url"); if (!$secretKey || !$authUrl) { throw new MOXMAN_Exception("No key/url set for ExternalAuthenticator, check config."); } // Build url if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") { $url = "https://"; } else { $url = "http://"; } $url .= $_SERVER['HTTP_HOST']; if ($_SERVER['SERVER_PORT'] != 80) { $url .= ':' . $_SERVER['SERVER_PORT']; } $httpClient = new MOXMAN_Http_HttpClient($url); $authUrl = MOXMAN_Util_PathUtils::toAbsolute(dirname($_SERVER["REQUEST_URI"]) . '/plugins/ExternalAuthenticator', $authUrl); $request = $httpClient->createRequest($url . $authUrl); $cookie = ''; foreach ($_COOKIE as $name => $value) { $cookie .= ($cookie ? '; ' : '') . $name . '=' . $value; } $request->setHeader('cookie', $cookie); $seed = $cookie . uniqid() . time(); $hash = hash_hmac('sha256', $seed, $secretKey); $response = $request->send(array("seed" => $seed, "hash" => $hash)); $json = json_decode($response->getBody()); if (!$json) { throw new MOXMAN_Exception("Did not get a proper JSON response from Auth url."); } if (isset($json->result)) { foreach ($json->result as $key => $value) { $key = str_replace('_', '.', $key); $config->put($key, $value); } return true; } else { if (isset($json->error)) { throw new MOXMAN_Exception($json->error->message . " - " . $json->error->code); } else { throw new MOXMAN_Exception("Generic unknown error, did not get a proper JSON response from Auth url."); } } }
/** * 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); }
public static function locate($optionName, $pathLocations) { $rootPath = MOXMAN_ROOT; $fullPath = MOXMAN::getConfig()->get($optionName); if ($fullPath) { return $fullPath; } while ($rootPath) { foreach ($pathLocations as $path) { $fullPath = MOXMAN_Util_PathUtils::combine($rootPath, $path); if (file_exists($fullPath)) { return $fullPath; } } if (dirname($rootPath) === $rootPath) { break; } $rootPath = dirname($rootPath); } throw new MOXMAN_Exception("Error could not locate library/framework. Please configure: " . $optionName); }
/** * Returns a MOXMAN_Vfs_IFile instance based on the specified path. * * @param string $path Path of the file to retrive. * @return MOXMAN_Vfs_IFile File instance for the specified path. */ public function getFile($path) { // Get file from cache if ($this->cache->has($path)) { return $this->cache->get($path); } // Never give access to the mc_access file if ($this->getConfig()->get("filesystem.local.access_file_name") === basename($path)) { throw new MOXMAN_Exception("Can't access the access_file_name."); } MOXMAN_Util_PathUtils::verifyPath($path, true); // Force the path to an absolute path $path = MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $path); // If the path is out side the root then return null if (!MOXMAN_Util_PathUtils::isChildOf($path, $this->rootPath)) { $null = null; return $null; } // Create the file and put it in the cache $file = new MOXMAN_Vfs_Local_File($this, $path); $this->cache->put($path, $file); return $file; }
/** * 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) { $config = MOXMAN::getConfig(); if (!$config->get("general.debug")) { return; } $request = $httpContext->getRequest(); if ($request->get("info")) { phpinfo(); die; } $response = $httpContext->getResponse(); $response->disableCache(); $response->setHeader('Content-type', 'text/html'); $sitepaths = MOXMAN_Util_PathUtils::getSitePaths(); $scriptFilename = $_SERVER["SCRIPT_FILENAME"]; if (realpath($scriptFilename) != $scriptFilename) { $scriptFilename = $scriptFilename . "<br />(" . realpath($scriptFilename) . ")"; } $result = array("MOXMAN_ROOT" => MOXMAN_ROOT, "realpath('.')" => realpath("."), "Config.php rootpath" => $config->get("filesystem.rootpath"), "Config.php wwwroot" => $config->get("filesystem.local.wwwroot"), "wwwroot resolve" => $sitepaths["wwwroot"], "wwwroot realpath" => realpath($sitepaths["wwwroot"]), "prefix resolve" => $sitepaths["prefix"], "storage path" => MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path")), "storage writable" => is_writable(MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $config->get("storage.path"))), "script filename" => $scriptFilename, "script name" => $_SERVER["SCRIPT_NAME"]); $out = "<html><body><table border='1'>"; foreach ($result as $name => $value) { if ($value === true) { $value = "True"; } else { if ($value === false) { $value = "False"; } } $out .= "<tr>"; $out .= "<td>" . $name . " </td><td>" . $value . " </td>"; $out .= "</tr>"; } $out .= "</table><a href='?action=debug&info=true'>Show phpinfo</a>"; $out .= "</body></html>"; $response->sendContent($out); }
/** @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; }
/** * Returns an URL for the specified file object. * * @param MOXMAN_Vfs_IFile $file File to get the absolute URL for. * @return String Absolute URL for the specified file. */ public function getUrl(MOXMAN_Vfs_IFile $file) { $config = $file->getConfig(); // Get config items $wwwroot = $config->get("filesystem.local.wwwroot"); $prefix = $config->get("filesystem.local.urlprefix"); $suffix = $config->get("filesystem.local.urlsuffix"); $paths = MOXMAN_Util_PathUtils::getSitePaths(); // No wwwroot specified try to figure out a wwwroot if (!$wwwroot) { $wwwroot = $paths["wwwroot"]; } else { // Force the www root to an absolute file system path $wwwroot = MOXMAN_Util_PathUtils::toAbsolute(MOXMAN_ROOT, $wwwroot); } // Add prefix to URL if ($prefix == "") { $prefix = MOXMAN_Util_PathUtils::combine("{proto}://{host}", $paths["prefix"]); } // Replace protocol if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") { $prefix = str_replace("{proto}", "https", $prefix); } else { $prefix = str_replace("{proto}", "http", $prefix); } // Replace host/port $prefix = str_replace("{host}", $_SERVER['HTTP_HOST'], $prefix); $prefix = str_replace("{port}", $_SERVER['SERVER_PORT'], $prefix); // Insert path into URL $url = substr($file->getPath(), strlen($wwwroot)); $url = MOXMAN_Util_PathUtils::combine($prefix, $url); // Add suffix to URL if ($suffix) { $url .= $suffix; } return $url; }
/** * Lists files in the specified path and returns an array with stat info details. * * @param String $path Path to list files in. * @return Array Array with stat info name/value arrays. */ private function getFileList($path) { $files = array(); $prefix = $path === "/" ? "" : substr($path, 1) . "/"; $xml = $this->sendXmlRequest(array("query" => array("comp" => "list", "restype" => "container", "prefix" => $prefix, "delimiter" => "/", "maxresults" => 99999))); // List dirs if (isset($xml->Blobs->BlobPrefix)) { foreach ($xml->Blobs->BlobPrefix as $blobPrefix) { if ($prefix != $blobPrefix->Name) { $stat = array("name" => basename($blobPrefix->Name), "isdir" => true, "size" => 0, "mdate" => 0); $path = MOXMAN_Util_PathUtils::combine($path, $stat["name"]); $files[] = $stat; } } } // List files if (isset($xml->Blobs->Blob)) { foreach ($xml->Blobs->Blob as $blob) { if ($prefix != $blob->Name) { $stat = array("name" => basename($blob->Name), "isdir" => false, "size" => intval($blob->Properties->{"Content-Length"}), "mdate" => strtotime($blob->Properties->{"Last-Modified"})); $path = MOXMAN_Util_PathUtils::combine($path, $stat["name"]); $files[] = $stat; } } } return $files; }
private function deleteRecursive($path) { $handle = $this->fileSystem->getConnection(); $files = array(); $dirs = array(); $lines = ftp_rawlist($handle, $path); foreach ($lines as $line) { $matches = null; $unixRe = '/^([\\-ld])((?:[\\-r][\\-w][\\-xs]){3})\\s+(\\d+)\\s+(\\w+)\\s+([\\-\\w]+)\\s+(\\d+)\\s+(\\w+\\s+\\d+\\s+[\\w:]+)\\s+(.+)$/'; $windowsRe = "/^([^\\s]+\\s+[^\\s]+)\\s+((?:<DIR>|[\\w]+)?)\\s+(.+)\$/"; if (preg_match($unixRe, $line, $matches)) { $filePath = MOXMAN_Util_PathUtils::combine($path, $matches[8]); if ($matches[1] === "d") { $dirs[] = $filePath; } else { $files[] = $filePath; } } else { if (preg_match($windowsRe, $line, $matches)) { $filePath = MOXMAN_Util_PathUtils::combine($path, $matches[3]); if ($matches[2] === "<DIR>") { $dirs[] = $filePath; } else { $files[] = $filePath; } } else { // Unknown format throw new MOXMAN_Exception("Unknown FTP list format: " . $line); } } } // Delete files in dir foreach ($files as $file) { ftp_delete($handle, $file); } // Delete directories in dir foreach ($dirs as $dir) { $this->deleteRecursive($dir); } // Delete dir ftp_rmdir($handle, $path); }
/** * 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); } } }
/** * Converts a file instance to a JSON serializable object. * * @param MOXMAN_Vfs_IFile $file File to convert into JSON format. * @param Boolean $meta State if the meta data should be returned or not. * @return stdClass JSON serializable object. */ public static function fileToJson($file, $meta = false) { $config = $file->getConfig(); $renameFilter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "rename"); $editFilter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "edit"); $viewFilter = MOXMAN_Vfs_CombinedFileFilter::createFromConfig($config, "view"); $configuredFilter = new MOXMAN_Vfs_BasicFileFilter(); $configuredFilter->setIncludeDirectoryPattern($config->get('filesystem.include_directory_pattern')); $configuredFilter->setExcludeDirectoryPattern($config->get('filesystem.exclude_directory_pattern')); $configuredFilter->setIncludeFilePattern($config->get('filesystem.include_file_pattern')); $configuredFilter->setExcludeFilePattern($config->get('filesystem.exclude_file_pattern')); $configuredFilter->setIncludeExtensions($config->get('filesystem.extensions')); $result = (object) array("path" => $file->getPublicPath(), "size" => $file->getSize(), "lastModified" => $file->getLastModified(), "isFile" => $file->isFile(), "canRead" => $file->canRead(), "canWrite" => $file->canWrite(), "canEdit" => $file->isFile() && $editFilter->accept($file), "canRename" => $renameFilter->accept($file), "canView" => $file->isFile() && $viewFilter->accept($file), "canPreview" => $file->isFile() && MOXMAN_Media_ImageAlter::canEdit($file), "visible" => $configuredFilter->accept($file), "exists" => $file->exists()); if ($meta) { $args = new MOXMAN_Vfs_CustomInfoEventArgs(MOXMAN_Vfs_CustomInfoEventArgs::INSERT_TYPE, $file); MOXMAN::getPluginManager()->get("core")->fire("CustomInfo", $args); $metaData = (object) array_merge($file->getMetaData()->getAll(), $args->getInfo()); if (MOXMAN_Media_ImageAlter::canEdit($file)) { $thumbnailFolderPath = MOXMAN_Util_PathUtils::combine($file->getParent(), $config->get('thumbnail.folder')); $thumbnailFile = MOXMAN::getFile($thumbnailFolderPath, $config->get('thumbnail.prefix') . $file->getName()); // TODO: Implement stat info cache layer here if ($file instanceof MOXMAN_Vfs_Local_File) { $info = MOXMAN_Media_MediaInfo::getInfo($file->getPath()); $metaData->width = $info["width"]; $metaData->height = $info["height"]; } if ($thumbnailFile->exists()) { $metaData->thumb_url = $thumbnailFile->getUrl(); // Get image size server side only on local filesystem if ($file instanceof MOXMAN_Vfs_Local_File) { $info = MOXMAN_Media_MediaInfo::getInfo($thumbnailFile->getPath()); $metaData->thumb_width = $info["width"]; $metaData->thumb_height = $info["height"]; } } } $metaData->url = $file->getUrl(); $result->meta = $metaData; } return $result; }
/** * 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; }
/** * 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) { $fromFile = MOXMAN::getFile($params->from); $toFile = MOXMAN::getFile($params->to); $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); } $paths = array(); $fileSystemManager = MOXMAN::getFileSystemManager(); $zipArchive = new ZipArchive(); $localTempFilePath = null; $result = array(); if ($fromFile instanceof MOXMAN_Vfs_Local_File) { $res = $zipArchive->open($fromFile->getPath()); } else { $localTempFilePath = $fileSystemManager->getLocalTempPath($fromFile); $fromFile->exportTo($localTempFilePath); $res = $zipArchive->open($localTempFilePath); } if ($res) { for ($i = 0; $i < $zipArchive->numFiles; $i++) { $stat = $zipArchive->statIndex($i); $paths[] = $stat["name"]; } $filter = MOXMAN_Vfs_BasicFileFilter::createFromConfig($config); $fileSystem = $toFile->getFileSystem(); foreach ($paths as $path) { $isFile = !preg_match('/\\/$/', $path); $toPath = MOXMAN_Util_PathUtils::combine($toFile->getPath(), iconv('cp437', 'UTF-8', $path)); $targetFile = MOXMAN::getFile($toPath); if ($filter->accept($targetFile, $isFile) === MOXMAN_Vfs_IFileFilter::ACCEPTED) { if ($isFile) { $content = $zipArchive->getFromName($path); // Fire before file action add event $args = new MOXMAN_Core_FileActionEventArgs("add", $targetFile); $args->getData()->fileSize = strlen($content); MOXMAN::getPluginManager()->get("core")->fire("BeforeFileAction", $args); $targetFile = $args->getFile(); $targetFile = $this->mkdirs($targetFile, true); $stream = $targetFile->open(MOXMAN_Vfs_IFileStream::WRITE); $stream->write($content); $stream->close(); //echo "Create file: ". $targetFile->getPublicPath() ."\n"; $this->fireFileAction(MOXMAN_Core_FileActionEventArgs::ADD, $targetFile); } else { $targetFile = $this->mkdirs($targetFile); } $result[] = $this->fileToJson($targetFile); } } $zipArchive->close(); if ($localTempFilePath) { $fileSystemManager->removeLocalTempFile($fromFile); } } return $result; }
/** * Returns the meta data file instance used to store meta information. * * @param MOXMAN_Vfs_IFile $file File instance to get the meta data file for. * @return MOXMAN_Vfs_IFile Meta data file. */ protected function getMetaFile(MOXMAN_Vfs_IFile $file) { $metaFile = null; if ($file->exists()) { $parent = $file->getParentFile(); // Check if file isn't a root file if ($parent !== null) { $metaFile = $parent->getFileSystem()->getFile(MOXMAN_Util_PathUtils::combine($parent->getPath(), "meta.dat")); } } return $metaFile; }