public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } if (!isset($this->pluginConf)) { $this->pluginConf = array("GENERATE_THUMBNAIL" => false); } $selection = new UserSelection($repository, $httpVars); $destStreamURL = $selection->currentBaseUrl(); if ($action == "preview_data_proxy") { $file = $selection->getUniqueFile(); if (!file_exists($destStreamURL . $file) || !is_readable($destStreamURL . $file)) { header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\""); header("Content-Length: 0"); return; } $this->logInfo('Preview', 'Preview content of ' . $file, array("files" => $selection->getUniqueFile())); if (isset($httpVars["get_thumb"]) && $httpVars["get_thumb"] == "true" && $this->getFilteredOption("GENERATE_THUMBNAIL", $repository->getId())) { $dimension = 200; if (isset($httpVars["dimension"]) && is_numeric($httpVars["dimension"])) { $dimension = $httpVars["dimension"]; } $this->currentDimension = $dimension; $cacheItem = AJXP_Cache::getItem("diaporama_" . $dimension, $destStreamURL . $file, array($this, "generateThumbnail")); $data = $cacheItem->getData(); $cId = $cacheItem->getId(); header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($cId)) . "; name=\"" . basename($cId) . "\""); header("Content-Length: " . strlen($data)); header('Cache-Control: public'); header("Pragma:"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); print $data; } else { //$filesize = filesize($destStreamURL.$file); $node = new AJXP_Node($destStreamURL . $file); $fp = fopen($destStreamURL . $file, "r"); $stat = fstat($fp); $filesize = $stat["size"]; header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\""); header("Content-Length: " . $filesize); header('Cache-Control: public'); header("Pragma:"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($destStreamURL . $file, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($node)); } } }
protected function filecopy($srcFile, $destFile) { if (AJXP_MetaStreamWrapper::nodesUseSameWrappers($srcFile, $destFile)) { $srcFilePath = str_replace($this->urlBase, "", $srcFile); $destFilePath = str_replace($this->urlBase, "", $destFile); $destDirPath = dirname($destFilePath); list($connection, $remote_base_path) = sftpAccessWrapper::getSshConnection($srcFile); $remoteSrc = $remote_base_path . $srcFilePath; $remoteDest = $remote_base_path . $destDirPath; $this->logDebug("SSH2 CP", array("cmd" => 'cp ' . $remoteSrc . ' ' . $remoteDest)); ssh2_exec($connection, 'cp ' . $remoteSrc . ' ' . $remoteDest); AJXP_Controller::applyHook("node.change", array(new AJXP_Node($srcFile), new AJXP_Node($destFile), true)); } else { parent::filecopy($srcFile, $destFile); } }
public function getCacheImpl() { $pluginInstance = null; if (!isset(self::$cacheInstance) || isset($this->pluginConf["UNIQUE_INSTANCE_CONFIG"]["instance_name"]) && self::$cacheInstance->getId() != $this->pluginConf["UNIQUE_INSTANCE_CONFIG"]["instance_name"]) { if (isset($this->pluginConf["UNIQUE_INSTANCE_CONFIG"])) { $pluginInstance = ConfService::instanciatePluginFromGlobalParams($this->pluginConf["UNIQUE_INSTANCE_CONFIG"], "AbstractCacheDriver"); if ($pluginInstance != false) { AJXP_PluginsService::getInstance()->setPluginUniqueActiveForType("cache", $pluginInstance->getName(), $pluginInstance); } } self::$cacheInstance = $pluginInstance; if ($pluginInstance !== null && is_a($pluginInstance, "AbstractCacheDriver") && $pluginInstance->supportsPatternDelete(AJXP_CACHE_SERVICE_NS_NODES)) { AJXP_MetaStreamWrapper::appendMetaWrapper("pydio.cache", "CacheStreamLayer"); } } return self::$cacheInstance; }
/** * Detect if this plugin declares a StreamWrapper, and if yes loads it and register the stream. * @param bool $register * @return array|bool */ public function detectStreamWrapper($register = false) { if (isset($this->streamData)) { if ($this->streamData === false) { return false; } $streamData = $this->streamData; // include wrapper, no other checks needed. include_once AJXP_INSTALL_PATH . "/" . $streamData["filename"]; } else { if ($this->manifestXML != null) { $this->unserializeManifest(); } $files = $this->xPath->query("class_stream_wrapper"); if (!$files->length) { $this->streamData = false; return false; } $streamData = $this->nodeAttrToHash($files->item(0)); if (!is_file(AJXP_INSTALL_PATH . "/" . $streamData["filename"])) { $this->streamData = false; return false; } include_once AJXP_INSTALL_PATH . "/" . $streamData["filename"]; if (!class_exists($streamData["classname"])) { $this->streamData = false; return false; } $this->streamData = $streamData; } if ($register) { $pServ = AJXP_PluginsService::getInstance(); $wrappers = stream_get_wrappers(); if (!in_array($streamData["protocol"], $wrappers)) { stream_wrapper_register($streamData["protocol"], $streamData["classname"]); $pServ->registerWrapperClass($streamData["protocol"], $streamData["classname"]); } AJXP_MetaStreamWrapper::register($wrappers); } return $streamData; }
public function extractExif($actionName, $httpVars, $fileVars) { $repo = $this->accessDriver->repository; $userSelection = new UserSelection($this->accessDriver->repository, $httpVars); $repo->detectStreamWrapper(true); $selectedNode = $userSelection->getUniqueNode(); $realFile = AJXP_MetaStreamWrapper::getRealFSReference($selectedNode->getUrl()); AJXP_Utils::safeIniSet('exif.encode_unicode', 'UTF-8'); $exifData = @exif_read_data($realFile, 0, TRUE); if ($exifData === false || !is_array($exifData)) { return; } if ($exifData !== false && isset($exifData["GPS"])) { $exifData["COMPUTED_GPS"] = $this->convertGPSData($exifData); } $iptc = $this->extractIPTC($realFile); if (count($iptc)) { $exifData["IPTC"] = $iptc; } $excludeTags = array(); // array("componentsconfiguration", "filesource", "scenetype", "makernote", "datadump"); $format = "xml"; if (isset($httpVars["format"]) && $httpVars["format"] == "json") { $format = "json"; } $filteredData = array(); foreach ($exifData as $section => $data) { $filteredData[$section] = array(); foreach ($data as $key => $value) { if (is_array($value)) { $value = implode(",", $value); } if (in_array(strtolower($key), $excludeTags)) { continue; } if (strpos($key, "UndefinedTag:") === 0) { continue; } $value = preg_replace('/[^[:print:]]/', '', $value); $filteredData[$section][$key] = SystemTextEncoding::toUTF8($value); } } if ($format == "xml") { AJXP_XMLWriter::header("metadata", array("file" => $selectedNode->getPath(), "type" => "EXIF")); foreach ($filteredData as $section => $data) { print "<exifSection name='{$section}'>"; foreach ($data as $key => $value) { print "<exifTag name=\"{$key}\">" . AJXP_Utils::xmlEntities($value) . "</exifTag>"; } print "</exifSection>"; } AJXP_XMLWriter::close("metadata"); } else { HTMLWriter::charsetHeader("application/json"); echo json_encode($filteredData); } }
/** * Read a file (by chunks) and copy the data directly inside the given stream. * * @param string $path * @param resource $stream */ public static function copyFileInStream($path, $stream) { $url = self::translateURL($path); AJXP_MetaStreamWrapper::copyFileInStream($url, $stream); /* $wrapperClass = AJXP_MetaStreamWrapper::actualRepositoryWrapperClass(parse_url($url, PHP_URL_HOST)); call_user_func(array($wrapperClass, "copyFileInStream"), $url, $stream); */ if (self::$linkNode !== null) { ConfService::loadDriverForRepository(self::$linkNode->getRepository()); } }
/** * Get a real reference to the filesystem. Remote wrappers will copy the file locally. * This will last the time of the script and will be removed afterward. * @return string */ public function getRealFile() { if (!isset($this->realFilePointer)) { $this->realFilePointer = AJXP_MetaStreamWrapper::getRealFSReference($this->_url, true); $isRemote = AJXP_MetaStreamWrapper::wrapperIsRemote($this->_url); if ($isRemote) { register_shutdown_function(array("AJXP_Utils", "silentUnlink"), $this->realFilePointer); } } return $this->realFilePointer; }
public function preProcess($action, &$httpVars, &$fileVars) { if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) { return; } $repository = ConfService::getRepository(); $driver = ConfService::loadDriverForRepository($repository); if (method_exists($driver, "storeFileToCopy")) { self::$remote = true; } if ($repository->detectStreamWrapper(true)) { $wrapperName = AJXP_MetaStreamWrapper::actualRepositoryWrapperClass($repository->getId()); if ($wrapperName == "ajxp.ftp" || $wrapperName == "ajxp.remotefs") { $this->logDebug("Skip decoding"); self::$skipDecoding = true; } $this->logDebug("Stream is", $wrapperName); self::$wrapperIsRemote = call_user_func(array($wrapperName, "isRemote")); } $this->logDebug("Jumploader HttpVars", $httpVars); $this->logDebug("Jumploader FileVars", $fileVars); $httpVars["dir"] = base64_decode(str_replace(" ", "+", $httpVars["dir"])); $index = $httpVars["partitionIndex"]; $realName = $fileVars["userfile_0"]["name"]; /* if fileId is not set, request for cross-session resume (only if the protocol is not ftp)*/ if (!isset($httpVars["fileId"])) { $this->logDebug("Trying Cross-Session Resume request"); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $repository->detectStreamWrapper(true); $context = new UserSelection($repository); $destStreamURL = $context->currentBaseUrl() . $dir; $fileHash = md5($httpVars["fileName"]); if (!self::$remote) { $resumeIndexes = array(); $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($destStreamURL)); $it->setMaxDepth(0); while ($it->valid()) { if (!$it->isDot()) { $subPathName = $it->getSubPathName(); AJXP_LOGGER::debug("Iterator SubPathName: " . $it->getSubPathName()); if (strstr($subPathName, $fileHash) != false) { $explodedSubPathName = explode('.', $subPathName); $resumeFileId = $explodedSubPathName[1]; $resumeIndexes[] = $explodedSubPathName[2]; $this->logDebug("Current Index: " . $explodedSubPathName[2]); } } $it->next(); } /* no valid temp file found. return. */ if (empty($resumeIndexes)) { $this->logDebug("No Cross-Session Resume request"); return; } AJXP_LOGGER::debug("ResumeFileID: " . $resumeFileId); AJXP_LOGGER::debug("Max Resume Index: " . max($resumeIndexes)); $nextResumeIndex = max($resumeIndexes) + 1; AJXP_LOGGER::debug("Next Resume Index: " . $nextResumeIndex); if (isset($resumeFileId)) { $this->logDebug("ResumeFileId is set. Returning values: fileId: " . $resumeFileId . ", partitionIndex: " . $nextResumeIndex); $httpVars["resumeFileId"] = $resumeFileId; $httpVars["resumePartitionIndex"] = $nextResumeIndex; } } return; } /* if the file has to be partitioned */ if (isset($httpVars["partitionCount"]) && intval($httpVars["partitionCount"]) > 1) { $this->logDebug("Partitioned upload"); $fileId = $httpVars["fileId"]; $fileHash = md5($realName); /* In order to enable cross-session resume, temp files must not depend on session. * Now named after and md5() of the original file name. */ $this->logDebug("Filename: " . $realName . ", File hash: " . $fileHash); $fileVars["userfile_0"]["name"] = "{$fileHash}.{$fileId}.{$index}"; $httpVars["lastPartition"] = false; } else { /* * If we wan to upload a folderUpload to folderServer * Temporarily,put all files in this folder to folderServer. * But a same file name may be existed in folderServer, * this can cause error of uploading. * * We rename this file by his relativePath. At the postProcess session, we will use this name * to copy to right location * */ $file_tmp_md5 = md5($httpVars["relativePath"]); $fileVars["userfile_0"]["name"] = $file_tmp_md5; } /* if we received the last partition */ if (intval($index) == intval($httpVars["partitionCount"]) - 1) { $httpVars["lastPartition"] = true; $httpVars["partitionRealName"] = $realName; } }
public function unifyChunks($action, &$httpVars, &$fileVars) { $filename = AJXP_Utils::decodeSecureMagic($httpVars["name"]); $tmpName = $fileVars["file"]["tmp_name"]; $chunk = $httpVars["chunk"]; $chunks = $httpVars["chunks"]; //error_log("currentChunk:".$chunk." chunks: ".$chunks); $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $userSelection = new UserSelection($repository); $dir = AJXP_Utils::securePath($httpVars["dir"]); $destStreamURL = $userSelection->currentBaseUrl() . $dir . "/"; $driver = ConfService::loadDriverForRepository($repository); $remote = false; if (method_exists($driver, "storeFileToCopy")) { $remote = true; $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($repository->getOption("TMP_UPLOAD")); // Make tmp folder a bit more unique using secure_token $tmpFolder = $destCopy . "/" . $httpVars["secure_token"]; if (!is_dir($tmpFolder)) { @mkdir($tmpFolder, 0700, true); } $target = $tmpFolder . '/' . $filename; $fileVars["file"]["destination"] = base64_encode($dir); } else { if (AJXP_MetaStreamWrapper::wrapperIsRemote($destStreamURL)) { $remote = true; $tmpFolder = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["secure_token"]; if (!is_dir($tmpFolder)) { @mkdir($tmpFolder, 0700, true); } $target = $tmpFolder . '/' . $filename; } else { $target = $destStreamURL . $filename; } } //error_log("Directory: ".$dir); // Clean the fileName for security reasons //$filename = preg_replace('/[^\w\._]+/', '', $filename); $contentType = ""; // Look for the content type header if (isset($_SERVER["HTTP_CONTENT_TYPE"])) { $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; } if (isset($_SERVER["CONTENT_TYPE"])) { $contentType = $_SERVER["CONTENT_TYPE"]; } // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5 if (strpos($contentType, "multipart") !== false) { if (isset($tmpName) && is_uploaded_file($tmpName)) { //error_log("tmpName: ".$tmpName); // Open temp file $out = fopen($target, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen($tmpName, "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); @unlink($tmpName); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } } else { // Open temp file $out = fopen($target, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } /* we apply the hook if we are uploading the last chunk */ if ($chunk == $chunks - 1) { if (!$remote) { AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($destStreamURL . $filename), false)); } else { if (method_exists($driver, "storeFileToCopy")) { $fileVars["file"]["tmp_name"] = $target; $fileVars["file"]["name"] = $filename; $driver->storeFileToCopy($fileVars["file"]); AJXP_Controller::findActionAndApply("next_to_remote", array(), array()); } else { // Remote Driver case: copy temp file to destination $node = new AJXP_Node($destStreamURL . $filename); AJXP_Controller::applyHook("node.before_create", array($node, filesize($target))); AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destStreamURL))); $res = copy($target, $destStreamURL . $filename); if ($res) { @unlink($target); } AJXP_Controller::applyHook("node.change", array(null, $node, false)); } } } // Return JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepositoryById($httpVars["repository_id"]); if (!$repository->detectStreamWrapper(true)) { return false; } if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) { AuthService::logUser("guest", null); $loggedUser = AuthService::getLoggedUser(); } if (!$loggedUser->canSwitchTo($repository->getId())) { echo "You do not have permissions to access this resource"; return false; } } $selection = new UserSelection($repository, $httpVars); if ($action == "open_file") { $selectedNode = $selection->getUniqueNode(); $selectedNodeUrl = $selectedNode->getUrl(); if (!file_exists($selectedNodeUrl) || !is_readable($selectedNodeUrl)) { echo "File does not exist"; return false; } $filesize = filesize($selectedNodeUrl); $fp = fopen($selectedNodeUrl, "rb"); $fileMime = "application/octet-stream"; //Get mimetype with fileinfo PECL extension if (class_exists("finfo")) { $finfo = new finfo(FILEINFO_MIME); $fileMime = $finfo->buffer(fread($fp, 2000)); } //Get mimetype with (deprecated) mime_content_type if (strpos($fileMime, "application/octet-stream") === 0 && function_exists("mime_content_type")) { $fileMime = @mime_content_type($fp); } //Guess mimetype based on file extension if (strpos($fileMime, "application/octet-stream") === 0) { $fileExt = substr(strrchr(basename($selectedNodeUrl), '.'), 1); if (empty($fileExt)) { $fileMime = "application/octet-stream"; } else { $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i"; $lines = file($this->getBaseDir() . "/resources/other/mime.types"); foreach ($lines as $line) { if (substr($line, 0, 1) == '#') { continue; } // skip comments $line = rtrim($line) . " "; if (!preg_match($regex, $line, $matches)) { continue; } // no match to the extension $fileMime = $matches[1]; } } } fclose($fp); // If still no mimetype, give up and serve application/octet-stream if (empty($fileMime)) { $fileMime = "application/octet-stream"; } //Send headers HTMLWriter::generateInlineHeaders(basename($selectedNodeUrl), $filesize, $fileMime); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($selectedNodeUrl, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($selectedNode)); $this->logInfo('Download', 'Read content of ' . $selectedNodeUrl, array("files" => $selectedNodeUrl)); } }
/** * @param String $action * @param Array $httpVars * @param Array $fileVars * @throws Exception */ public function receiveAction($action, $httpVars, $fileVars) { //VAR CREATION OUTSIDE OF ALL CONDITIONS, THEY ARE "MUST HAVE" VAR !! $messages = ConfService::getMessages(); $repository = ConfService::getRepository(); $userSelection = new UserSelection($repository, $httpVars); $nodes = $userSelection->buildNodes(); $currentDirPath = AJXP_Utils::safeDirname($userSelection->getUniqueNode()->getPath()); $currentDirPath = rtrim($currentDirPath, "/") . "/"; $currentDirUrl = $userSelection->currentBaseUrl() . $currentDirPath; if (empty($httpVars["compression_id"])) { $compressionId = sha1(rand()); $httpVars["compression_id"] = $compressionId; } else { $compressionId = $httpVars["compression_id"]; } $progressCompressionFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressCompressionID-" . $compressionId . ".txt"; if (empty($httpVars["extraction_id"])) { $extractId = sha1(rand()); $httpVars["extraction_id"] = $extractId; } else { $extractId = $httpVars["extraction_id"]; } $progressExtractFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressExtractID-" . $extractId . ".txt"; if ($action == "compression") { $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); $archiveFormat = $httpVars["type_archive"]; $tabTypeArchive = array(".tar", ".tar.gz", ".tar.bz2"); $acceptedExtension = false; foreach ($tabTypeArchive as $extensionArchive) { if ($extensionArchive == $archiveFormat) { $acceptedExtension = true; break; } } if ($acceptedExtension == false) { file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.16"]); throw new AJXP_Exception($messages["compression.16"]); } $typeArchive = $httpVars["type_archive"]; //if we can run in background we do it if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { $archivePath = $currentDirPath . $archiveName; file_put_contents($progressCompressionFileName, $messages["compression.5"]); AJXP_Controller::applyActionInBackground($repository->getId(), "compression", $httpVars); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $messages["compression.5"], true, 2); AJXP_XMLWriter::close(); return null; } else { $maxAuthorizedSize = 4294967296; $currentDirUrlLength = strlen($currentDirUrl); $tabFolders = array(); $tabAllRecursiveFiles = array(); $tabFilesNames = array(); foreach ($nodes as $node) { $nodeUrl = $node->getUrl(); if (is_file($nodeUrl) && filesize($nodeUrl) < $maxAuthorizedSize) { array_push($tabAllRecursiveFiles, $nodeUrl); array_push($tabFilesNames, substr($nodeUrl, $currentDirUrlLength)); } if (is_dir($nodeUrl)) { array_push($tabFolders, $nodeUrl); } } //DO A FOREACH OR IT'S GONNA HAVE SOME SAMES FILES NAMES foreach ($tabFolders as $value) { $dossiers = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($value)); foreach ($dossiers as $file) { if ($file->isDir()) { continue; } array_push($tabAllRecursiveFiles, $file->getPathname()); array_push($tabFilesNames, substr($file->getPathname(), $currentDirUrlLength)); } } //WE STOP IF IT'S JUST AN EMPTY FOLDER OR NO FILES if (empty($tabFilesNames)) { file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.17"]); throw new AJXP_Exception($messages["compression.17"]); } try { $tmpArchiveName = tempnam(AJXP_Utils::getAjxpTmpDir(), "tar-compression") . ".tar"; $archive = new PharData($tmpArchiveName); } catch (Exception $e) { file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage()); throw $e; } $counterCompression = 0; //THE TWO ARRAY ARE MERGED FOR THE FOREACH LOOP $tabAllFiles = array_combine($tabAllRecursiveFiles, $tabFilesNames); foreach ($tabAllFiles as $fullPath => $fileName) { try { $archive->addFile(AJXP_MetaStreamWrapper::getRealFSReference($fullPath), $fileName); $counterCompression++; file_put_contents($progressCompressionFileName, sprintf($messages["compression.6"], round($counterCompression / count($tabAllFiles) * 100, 0, PHP_ROUND_HALF_DOWN) . " %")); } catch (Exception $e) { unlink($tmpArchiveName); file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage()); throw $e; } } $finalArchive = $tmpArchiveName; if ($typeArchive != ".tar") { $archiveTypeCompress = substr(strrchr($typeArchive, "."), 1); file_put_contents($progressCompressionFileName, sprintf($messages["compression.7"], strtoupper($archiveTypeCompress))); if ($archiveTypeCompress == "gz") { $archive->compress(Phar::GZ); } elseif ($archiveTypeCompress == "bz2") { $archive->compress(Phar::BZ2); } $finalArchive = $tmpArchiveName . "." . $archiveTypeCompress; } $destArchive = AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $archiveName); rename($finalArchive, $destArchive); AJXP_Controller::applyHook("node.before_create", array($destArchive, filesize($destArchive))); if (file_exists($tmpArchiveName)) { unlink($tmpArchiveName); unlink(substr($tmpArchiveName, 0, -4)); } $newNode = new AJXP_Node($currentDirUrl . $archiveName); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); file_put_contents($progressCompressionFileName, "SUCCESS"); } } elseif ($action == "check_compression_status") { $archivePath = AJXP_Utils::decodeSecureMagic($httpVars["archive_path"]); $progressCompression = file_get_contents($progressCompressionFileName); $substrProgressCompression = substr($progressCompression, 0, 5); if ($progressCompression != "SUCCESS" && $substrProgressCompression != "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $progressCompression, true, 5); AJXP_XMLWriter::close(); } elseif ($progressCompression == "SUCCESS") { $newNode = new AJXP_Node($userSelection->currentBaseUrl() . $archivePath); $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array()); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($messages["compression.8"], null); AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true); AJXP_XMLWriter::close(); if (file_exists($progressCompressionFileName)) { unlink($progressCompressionFileName); } } elseif ($substrProgressCompression == "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $progressCompression); AJXP_XMLWriter::close(); if (file_exists($progressCompressionFileName)) { unlink($progressCompressionFileName); } } } elseif ($action == "extraction") { $fileArchive = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["file"]), AJXP_SANITIZE_DIRNAME); $fileArchive = substr(strrchr($fileArchive, DIRECTORY_SEPARATOR), 1); $authorizedExtension = array("tar" => 4, "gz" => 7, "bz2" => 8); $acceptedArchive = false; $extensionLength = 0; $counterExtract = 0; $currentAllPydioPath = $currentDirUrl . $fileArchive; $pharCurrentAllPydioPath = "phar://" . AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath); $pathInfoCurrentAllPydioPath = pathinfo($currentAllPydioPath, PATHINFO_EXTENSION); //WE TAKE ONLY TAR, TAR.GZ AND TAR.BZ2 ARCHIVES foreach ($authorizedExtension as $extension => $strlenExtension) { if ($pathInfoCurrentAllPydioPath == $extension) { $acceptedArchive = true; $extensionLength = $strlenExtension; break; } } if ($acceptedArchive == false) { file_put_contents($progressExtractFileName, "Error : " . $messages["compression.15"]); throw new AJXP_Exception($messages["compression.15"]); } $onlyFileName = substr($fileArchive, 0, -$extensionLength); $lastPosOnlyFileName = strrpos($onlyFileName, "-"); $tmpOnlyFileName = substr($onlyFileName, 0, $lastPosOnlyFileName); $counterDuplicate = substr($onlyFileName, $lastPosOnlyFileName + 1); if (!is_int($lastPosOnlyFileName) || !is_int($counterDuplicate)) { $tmpOnlyFileName = $onlyFileName; $counterDuplicate = 1; } while (file_exists($currentDirUrl . $onlyFileName)) { $onlyFileName = $tmpOnlyFileName . "-" . $counterDuplicate; $counterDuplicate++; } if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { file_put_contents($progressExtractFileName, $messages["compression.12"]); AJXP_Controller::applyActionInBackground($repository->getId(), "extraction", $httpVars); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $messages["compression.12"], true, 2); AJXP_XMLWriter::close(); return null; } mkdir($currentDirUrl . $onlyFileName, 0777, true); chmod(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), 0777); try { $archive = new PharData(AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath)); $fichiersArchive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharCurrentAllPydioPath)); foreach ($fichiersArchive as $file) { $fileGetPathName = $file->getPathname(); if ($file->isDir()) { continue; } $fileNameInArchive = substr(strstr($fileGetPathName, $fileArchive), strlen($fileArchive) + 1); try { $archive->extractTo(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), $fileNameInArchive, false); } catch (Exception $e) { file_put_contents($progressExtractFileName, "Error : " . $e->getMessage()); throw new AJXP_Exception($e); } $counterExtract++; file_put_contents($progressExtractFileName, sprintf($messages["compression.13"], round($counterExtract / $archive->count() * 100, 0, PHP_ROUND_HALF_DOWN) . " %")); } } catch (Exception $e) { file_put_contents($progressExtractFileName, "Error : " . $e->getMessage()); throw new AJXP_Exception($e); } file_put_contents($progressExtractFileName, "SUCCESS"); $newNode = new AJXP_Node($currentDirUrl . $onlyFileName); AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array()); } elseif ($action == "check_extraction_status") { $currentDirUrl = $httpVars["currentDirUrl"]; $onlyFileName = $httpVars["onlyFileName"]; $progressExtract = file_get_contents($progressExtractFileName); $substrProgressExtract = substr($progressExtract, 0, 5); if ($progressExtract != "SUCCESS" && $progressExtract != "INDEX" && $substrProgressExtract != "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $progressExtract, true, 4); AJXP_XMLWriter::close(); } elseif ($progressExtract == "SUCCESS") { $newNode = new AJXP_Node($currentDirUrl . $onlyFileName); $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array()); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(sprintf($messages["compression.14"], $onlyFileName), null); AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $newNode->getRepositoryId()), "starting indexation", true, 5); AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true); AJXP_XMLWriter::close(); if (file_exists($progressExtractFileName)) { unlink($progressExtractFileName); } } elseif ($substrProgressExtract == "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $progressExtract); AJXP_XMLWriter::close(); if (file_exists($progressExtractFileName)) { unlink($progressExtractFileName); } } } }
/** * Enter description here... * * @param string $path * @param int $options * @return bool */ public function rmdir($path, $options) { if (is_resource($options)) { return rmdir(AJXP_MetaStreamWrapper::translateScheme($path), $options); } else { return rmdir(AJXP_MetaStreamWrapper::translateScheme($path)); } }
/** * Enter description here... * * @param string $path * @param int $flags * @return array */ public function url_stat($path, $flags) { $stat = @stat(AJXP_MetaStreamWrapper::translateScheme($path)); if ($stat === false) { return null; } return $stat; }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $destStreamURL = $selection->currentBaseUrl(); if ($action == "post_to_zohoserver") { $sheetExt = explode(",", "xls,xlsx,ods,sxc,csv,tsv"); $presExt = explode(",", "ppt,pps,odp,sxi"); $docExt = explode(",", "doc,docx,rtf,odt,sxw"); require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); } else { $file = $selection->getUniqueFile(); } if (!is_readable($destStreamURL . $file)) { throw new Exception("Cannot find file!"); } $target = base64_decode($httpVars["parent_url"]); $tmp = AJXP_MetaStreamWrapper::getRealFSReference($destStreamURL . $file); $tmp = SystemTextEncoding::fromUTF8($tmp); $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); $this->logInfo('Preview', 'Posting content of ' . $file . ' to Zoho server', array("files" => $file)); $extension = strtolower(pathinfo(urlencode(basename($file)), PATHINFO_EXTENSION)); $httpClient = new http_class(); $httpClient->request_method = "POST"; $secureToken = $httpVars["secure_token"]; $_SESSION["ZOHO_CURRENT_EDITED"] = $destStreamURL . $file; $_SESSION["ZOHO_CURRENT_UUID"] = md5(rand() . "-" . microtime()); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository)) { $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository); } else { $saveUrl = $target . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/save_zoho.php"; } $b64Sig = $this->signID($_SESSION["ZOHO_CURRENT_UUID"]); $params = array('id' => $_SESSION["ZOHO_CURRENT_UUID"], 'apikey' => $this->getFilteredOption("ZOHO_API_KEY", $repository), 'output' => 'url', 'lang' => "en", 'filename' => urlencode(basename($file)), 'persistence' => 'false', 'format' => $extension, 'mode' => 'normaledit', 'saveurl' => $saveUrl . "?signature=" . $b64Sig); $service = "exportwriter"; if (in_array($extension, $sheetExt)) { $service = "sheet"; } else { if (in_array($extension, $presExt)) { $service = "show"; } else { if (in_array($extension, $docExt)) { $service = "exportwriter"; } } } $arguments = array(); $httpClient->GetRequestArguments("https://" . $service . ".zoho.com/remotedoc.im", $arguments); $arguments["PostValues"] = $params; $arguments["PostFiles"] = array("content" => array("FileName" => $tmp, "Content-Type" => "automatic/name")); $err = $httpClient->Open($arguments); if (empty($err)) { $err = $httpClient->SendRequest($arguments); if (empty($err)) { $response = ""; while (true) { $body = ""; $error = $httpClient->ReadReplyBody($body, 1000); if ($error != "" || strlen($body) == 0) { break; } $response .= $body; } $result = trim($response); $matchlines = explode("\n", $result); $resultValues = array(); foreach ($matchlines as $line) { list($key, $val) = explode("=", $line, 2); $resultValues[$key] = $val; } if ($resultValues["RESULT"] == "TRUE" && isset($resultValues["URL"])) { header("Location: " . $resultValues["URL"]); } else { echo "Zoho API Error " . $resultValues["ERROR_CODE"] . " : " . $resultValues["WARNING"]; echo "<script>window.parent.setTimeout(function(){parent.hideLightBox();}, 2000);</script>"; } } $httpClient->Close(); } } else { if ($action == "retrieve_from_zohoagent") { $targetFile = $_SESSION["ZOHO_CURRENT_EDITED"]; $id = $_SESSION["ZOHO_CURRENT_UUID"]; $ext = pathinfo($targetFile, PATHINFO_EXTENSION); $node = new AJXP_Node($targetFile); $node->loadNodeInfo(); AJXP_Controller::applyHook("node.before_change", array(&$node)); $b64Sig = $this->signID($id); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository)) { $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository) . "?ajxp_action=get_file&name=" . $id . "&ext=" . $ext . "&signature=" . $b64Sig; $data = AJXP_Utils::getRemoteContent($url); if (strlen($data)) { file_put_contents($targetFile, $data); echo "MODIFIED"; } } else { if (is_file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext)) { copy(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext, $targetFile); unlink(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext); echo "MODIFIED"; } } $this->logInfo('Edit', 'Retrieved content of ' . $node->getUrl(), array("files" => $node->getUrl())); AJXP_Controller::applyHook("node.change", array(null, &$node)); } } }
/** * Apply specific operation to set a node as hidden. * Can be overwritten, or will probably do nothing. * @param AJXP_Node $node */ public function setHiddenAttribute($node) { if (AJXP_MetaStreamWrapper::actualRepositoryWrapperClass($node->getRepositoryId()) == "fsAccessWrapper" && strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $realPath = AJXP_MetaStreamWrapper::getRealFSReference($node->getUrl()); @shell_exec("attrib +H " . escapeshellarg($realPath)); } }
/** * @param $filePath * @param $repoData */ protected function changeMode($filePath, $repoData) { $chmodValue = $repoData["chmod"]; if (isset($chmodValue) && $chmodValue != "") { $chmodValue = octdec(ltrim($chmodValue, "0")); AJXP_MetaStreamWrapper::changeMode($filePath, $chmodValue); } }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $node = $selection->getUniqueNode(); if ($action == "read_video_data") { if (!file_exists($node->getUrl()) || !is_readable($node->getUrl())) { throw new Exception("Cannot find file!"); } $this->logDebug("Reading video"); session_write_close(); $filesize = filesize($node->getUrl()); $filename = $node->getUrl(); $basename = AJXP_Utils::safeBasename($filename); //$fp = fopen($destStreamURL.$file, "r"); if (preg_match("/\\.ogv\$/", $basename)) { header("Content-Type: video/ogg; name=\"" . $basename . "\""); } else { if (preg_match("/\\.mp4\$/", $basename)) { header("Content-Type: video/mp4; name=\"" . $basename . "\""); } else { if (preg_match("/\\.m4v\$/", $basename)) { header("Content-Type: video/x-m4v; name=\"" . $basename . "\""); } else { if (preg_match("/\\.webm\$/", $basename)) { header("Content-Type: video/webm; name=\"" . $basename . "\""); } } } } if (isset($_SERVER['HTTP_RANGE']) && $filesize != 0) { $this->logDebug("Http range", array($_SERVER['HTTP_RANGE'])); // multiple ranges, which can become pretty complex, so ignore it for now $ranges = explode('=', $_SERVER['HTTP_RANGE']); $offsets = explode('-', $ranges[1]); $offset = floatval($offsets[0]); if ($offset == 0) { $this->logInfo('Preview', 'Streaming content of ' . $filename, array("files" => $filename)); } $length = floatval($offsets[1]) - $offset + 1; if (!$length) { $length = $filesize - $offset; } if ($length + $offset > $filesize || $length < 0) { $length = $filesize - $offset; } header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length - 1) . '/' . $filesize); header('Accept-Ranges:bytes'); header("Content-Length: " . $length); $file = fopen($filename, 'rb'); if (!is_resource($file)) { throw new Exception("Cannot open file {$file}!"); } fseek($file, 0); $relOffset = $offset; while ($relOffset > 2000000000.0) { // seek to the requested offset, this is 0 if it's not a partial content request fseek($file, 2000000000, SEEK_CUR); $relOffset -= 2000000000; // This works because we never overcome the PHP 32 bit limit } fseek($file, $relOffset, SEEK_CUR); while (ob_get_level()) { ob_end_flush(); } $readSize = 0.0; while (!feof($file) && $readSize < $length && connection_status() == 0) { if ($length < 2048) { echo fread($file, $length); } else { echo fread($file, 2048); } $readSize += 2048.0; flush(); } fclose($file); } else { $this->logInfo('Preview', 'Streaming content of ' . $filename, array("files" => $filename)); header("Content-Length: " . $filesize); header("Content-Range: bytes 0-" . ($filesize - 1) . "/" . $filesize . ";"); header('Cache-Control: public'); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($node->getUrl(), $stream); fflush($stream); fclose($stream); } AJXP_Controller::applyHook("node.read", array($node)); } else { if ($action == "get_sess_id") { HTMLWriter::charsetHeader("text/plain"); print session_id(); } } }
public function makeZip($src, $dest, $basedir) { @set_time_limit(0); require_once AJXP_BIN_FOLDER . "/pclzip.lib.php"; $zipEncoding = ConfService::getCoreConf("ZIP_ENCODING"); $filePaths = array(); foreach ($src as $item) { $url = $this->urlBase . ($item[0] == "/" ? "" : "/") . AJXP_Utils::securePath($item); $realFile = AJXP_MetaStreamWrapper::getRealFSReference($url); //$basedir = trim(dirname($realFile))."/"; if (basename($item) == "") { $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $realFile); } else { $shortName = basename($item); if (!empty($zipEncoding)) { $test = iconv(SystemTextEncoding::getEncoding(), $zipEncoding, $shortName); if ($test !== false) { $shortName = $test; } } $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $realFile, PCLZIP_ATT_FILE_NEW_SHORT_NAME => $shortName); } } self::$filteringDriverInstance = $this; $archive = new PclZip($dest); if ($basedir == "__AJXP_ZIP_FLAT__/") { $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_ADD_TEMP_FILE_ON, PCLZIP_CB_PRE_ADD, 'zipPreAddCallback'); } else { $basedir = AJXP_MetaStreamWrapper::getRealFSReference($this->urlBase) . trim($basedir); $this->logDebug("Basedir", array($basedir)); $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_PATH, $basedir, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_ADD_TEMP_FILE_ON, PCLZIP_CB_PRE_ADD, 'zipPreAddCallback'); } if (!$vList) { throw new Exception("Zip creation error : ({$dest}) " . $archive->errorInfo(true)); } self::$filteringDriverInstance = null; return $vList; }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $selectedNode = $selection->getUniqueNode(); $selectedNodeUrl = $selectedNode->getUrl(); if ($action == "post_to_server") { // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $legacyFilePath = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $legacyFilePath); $selectedNodeUrl = $selectedNode->getUrl(); } $target = rtrim(base64_decode($httpVars["parent_url"]), '/') . "/plugins/editor.pixlr"; $tmp = AJXP_MetaStreamWrapper::getRealFSReference($selectedNodeUrl); $tmp = SystemTextEncoding::fromUTF8($tmp); $this->logInfo('Preview', 'Sending content of ' . $selectedNodeUrl . ' to Pixlr server.', array("files" => $selectedNodeUrl)); AJXP_Controller::applyHook("node.read", array($selectedNode)); $saveTarget = $target . "/fake_save_pixlr.php"; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $saveTarget = $target . "/fake_save_pixlr_" . md5($httpVars["secure_token"]) . ".php"; } $params = array("referrer" => "Pydio", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $saveTarget, "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($selectedNodeUrl)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source"); require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; $arguments = array(); $httpClient = new http_class(); $httpClient->request_method = "POST"; $httpClient->GetRequestArguments("https://pixlr.com/editor/", $arguments); $arguments["PostValues"] = $params; $arguments["PostFiles"] = array("image" => array("FileName" => $tmp, "Content-Type" => "automatic/name")); $err = $httpClient->Open($arguments); if (empty($err)) { $err = $httpClient->SendRequest($arguments); if (empty($err)) { $response = ""; while (true) { $header = array(); $error = $httpClient->ReadReplyHeaders($header, 1000); if ($error != "" || $header != null) { break; } $response .= $header; } } } header("Location: {$header['location']}"); //$response"); } else { if ($action == "retrieve_pixlr_image") { $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]); $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $file); $selectedNode->loadNodeInfo(); $this->logInfo('Edit', 'Retrieving content of ' . $file . ' from Pixlr server.', array("files" => $file)); AJXP_Controller::applyHook("node.before_change", array(&$selectedNode)); $url = $httpVars["new_url"]; $urlParts = parse_url($url); $query = $urlParts["query"]; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $scriptName = basename($urlParts["path"]); $token = str_replace(array("fake_save_pixlr_", ".php"), "", $scriptName); if ($token != md5($httpVars["secure_token"])) { throw new AJXP_Exception("Invalid Token, this could mean some security problem!"); } } $params = array(); parse_str($query, $params); $image = $params['image']; $headers = get_headers($image, 1); $content_type = explode("/", $headers['Content-Type']); if ($content_type[0] != "image") { throw new AJXP_Exception("Invalid File Type"); } $content_length = intval($headers["Content-Length"]); if ($content_length != 0) { AJXP_Controller::applyHook("node.before_change", array(&$selectedNode, $content_length)); } $orig = fopen($image, "r"); $target = fopen($selectedNode->getUrl(), "w"); if (is_resource($orig) && is_resource($target)) { while (!feof($orig)) { fwrite($target, fread($orig, 4096)); } fclose($orig); fclose($target); } clearstatcache(true, $selectedNode->getUrl()); $selectedNode->loadNodeInfo(true); AJXP_Controller::applyHook("node.change", array(&$selectedNode, &$selectedNode)); } } }
/** * @param String $file URL of the file to commit (probably a metadata) * @param AJXP_Node $ajxpNode Optionnal node to commit along. */ public function commitFile($file, $ajxpNode = null) { $repo = $this->accessDriver->repository; $repo->detectStreamWrapper(); $realFile = AJXP_MetaStreamWrapper::getRealFSReference($file); $res = ExecSvnCmd("svn status ", $realFile); if (count($res[IDX_STDOUT]) && substr($res[IDX_STDOUT][0], 0, 1) == "?") { $res2 = ExecSvnCmd("svn add", "{$realFile}"); } if ($ajxpNode != null) { $nodeRealFile = AJXP_MetaStreamWrapper::getRealFSReference($ajxpNode->getUrl()); try { ExecSvnCmd("svn propset metachange " . time(), $nodeRealFile); } catch (Exception $e) { $this->commitChanges("COMMIT_META", $realFile, array()); return; } // WILL COMMIT BOTH AT ONCE $command = "svn commit"; $user = AuthService::getLoggedUser()->getId(); $switches = "-m \"Pydio||{$user}||COMMIT_META||file:" . escapeshellarg($file) . "\""; ExecSvnCmd($command, array($realFile, $nodeRealFile), $switches); ExecSvnCmd('svn update', dirname($nodeRealFile), ''); } else { $this->commitChanges("COMMIT_META", $realFile, array()); } }
public function switchAction($action, $httpVars, $fileVars) { $mess = ConfService::getMessages(); $timestamp_url = $this->getFilteredOption("TIMESTAMP_URL"); $timestamp_login = $this->getFilteredOption("USER"); $timestamp_password = $this->getFilteredOption("PASS"); //Check if the configuration has been initiated if (empty($timestamp_url) || empty($timestamp_login) || !empty($timestamp_password)) { throw new AJXP_Exception($mess["timestamp.4"]); $this->logError("Config", "TimeStamp : configuration is needed"); return false; } //Check if after being initiated, conf. fields have some values if (strlen($timestamp_url) < 2 || strlen($timestamp_login) < 2 || strlen($timestamp_password) < 2) { throw new AJXP_Exception($mess["timestamp.4"]); $this->logError("Config", "TimeStamp : configuration is incorrect"); return false; } //Get active repository $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $destStreamURL = $selection->currentBaseUrl(); $fileName = $selection->getUniqueFile(); $fileUrl = $destStreamURL . $fileName; $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true); //Hash the file, to send it to Universign $hashedDataToTimestamp = hash_file('sha256', $file); //Check that a tokken is not going to be timestamped ! if (substr("{$file}", -4) != '.ers') { if (file_exists($file . '.ers')) { throw new AJXP_Exception($mess["timestamp.1"]); return false; } else { //Prepare the query that will be sent to Universign $dataToSend = array('hashAlgo' => 'SHA256', 'withCert' => 'true', 'hashValue' => $hashedDataToTimestamp); $dataQuery = http_build_query($dataToSend); //Check if allow_url_fopen is allowed on the server. If not, it will use cUrl if (ini_get('allow_url_fopen')) { $context_options = array('http' => array('method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($dataQuery) . "\r\n" . "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password) . "\r\n", 'content' => $dataQuery)); //Get the result from Universign $context = stream_context_create($context_options); $fp = fopen($timestamp_url, 'r', false, $context); $tsp = stream_get_contents($fp); } else { $timestamp_header = array("Content-type: application/x-www-form-urlencoded", "Content-Length: " . strlen($dataQuery), "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password)); $timeout = 5; $ch = curl_init($timestamp_url); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataQuery); curl_setopt($ch, CURLOPT_HTTPHEADER, $timestamp_header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Get the result from Universign $tsp = curl_exec($ch); curl_close($ch); } //Save the result to a file file_put_contents($file . '.ers', $tsp); //Send the succesful message $this->logInfo("TimeStamp", array("files" => $file, "destination" => $file . '.ers')); AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::sendMessage($mess["timestamp.3"] . $fileName, null); AJXP_XMLWriter::close(); } } else { throw new AJXP_Exception($mess["timestamp.2"]); return false; } }
/** * @param AJXP_Node $ajxpNode * @param Boolean $isParent */ public function extractMimeHeaders(&$ajxpNode, $isParent = false) { if ($isParent) { return; } $currentNode = $ajxpNode->getUrl(); $metadata = $ajxpNode->metadata; $wrapperClassName = AJXP_MetaStreamWrapper::actualRepositoryWrapperClass($ajxpNode->getRepositoryId()); $noMail = true; if ($metadata["is_file"] && ($wrapperClassName == "imapAccessWrapper" || preg_match("/\\.eml\$/i", $currentNode))) { $noMail = false; } if ($wrapperClassName == "imapAccessWrapper" && !$metadata["is_file"]) { $metadata["mimestring"] = "Mailbox"; } $parsed = parse_url($currentNode); if ($noMail || isset($parsed["fragment"]) && strpos($parsed["fragment"], "attachments") === 0) { EmlParser::$currentListingOnlyEmails = FALSE; return; } if (EmlParser::$currentListingOnlyEmails === NULL) { EmlParser::$currentListingOnlyEmails = true; } if ($wrapperClassName == "imapAccessWrapper") { $cachedFile = AJXP_Cache::getItem("eml_remote", $currentNode, null, array("EmlParser", "computeCacheId")); $realFile = $cachedFile->getId(); if (!is_file($realFile)) { $cachedFile->getData(); // trigger loading! } } else { $realFile = $ajxpNode->getRealFile(); } $cacheItem = AJXP_Cache::getItem("eml_mimes", $realFile, array($this, "mimeExtractorCallback")); $data = unserialize($cacheItem->getData()); $data["ajxp_mime"] = "eml"; $data["mimestring"] = "Email"; $metadata = array_merge($metadata, $data); if ($wrapperClassName == "imapAccessWrapper" && $metadata["eml_attachments"] != "0" && strpos($_SERVER["HTTP_USER_AGENT"], "ajaxplorer-ios") !== false) { $metadata["is_file"] = false; $metadata["nodeName"] = basename($currentNode) . "#attachments"; } $ajxpNode->metadata = $metadata; }
public function switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = $this->accessDriver->repository; if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); switch ($actionName) { case "filehasher_signature": $file = $selection->getUniqueNode(); if (!file_exists($file->getUrl())) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $file->getUrl(), array($this, "generateSignature")); $data = $cacheItem->getData(); header("Content-Type:application/octet-stream"); header("Content-Length", strlen($data)); echo $data; break; case "filehasher_delta": case "filehasher_patch": // HANDLE UPLOAD DATA $this->logDebug("Received signature file, should compute delta now"); if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) { throw new Exception("These action should find uploaded data"); } $signature_delta_file = $fileVars["userfile_0"]["tmp_name"]; $fileUrl = $selection->getUniqueNode()->getUrl(); $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true); if ($actionName == "filehasher_delta") { $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); $this->logDebug("Received signature file, should compute delta now"); rsync_generate_delta($signature_delta_file, $file, $deltaFile); $this->logDebug("Computed delta file, size is " . filesize($deltaFile)); header("Content-Type:application/octet-stream"); header("Content-Length:" . filesize($deltaFile)); readfile($deltaFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; rsync_patch_file($file, $signature_delta_file, $patched); rename($patched, $file); $node = $selection->getUniqueNode(); AJXP_Controller::applyHook("node.change", array($node, $node, false)); header("Content-Type:text/plain"); echo md5_file($file); } break; case "stat_hash": clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $node = $selection->getUniqueNode(); $stat = @stat($node->getUrl()); if (!$stat || !is_readable($node->getUrl())) { print '{}'; } else { if (is_file($node->getUrl())) { if (isset($_SERVER["HTTP_RANGE"])) { $fullSize = floatval($stat['size']); $ranges = explode('=', $_SERVER["HTTP_RANGE"]); $offsets = explode('-', $ranges[1]); $offset = floatval($offsets[0]); $length = floatval($offsets[1]) - $offset; if (!$length) { $length = $fullSize - $offset; } if ($length + $offset > $fullSize || $length < 0) { $length = $fullSize - $offset; } $hash = $this->getPartialHash($node, $offset, $length); } else { $hash = $this->getFileHash($selection->getUniqueNode()); } } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $node = new AJXP_Node($selection->currentBaseUrl() . $path); $stat = @stat($selection->currentBaseUrl() . $path); if (!$stat || !is_readable($node->getUrl())) { $stat = '{}'; } else { if (!is_dir($node->getUrl())) { $hash = $this->getFileHash($node); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; $stat = json_encode($stat); } print json_encode(SystemTextEncoding::toUTF8($path)) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; break; } }
public function switchAction($action, $httpVars, $postProcessData) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } if ($action == "audio_proxy") { $selection = new UserSelection($repository, $httpVars); $destStreamURL = $selection->currentBaseUrl(); $node = new AJXP_Node($destStreamURL . "/" . $selection->getUniqueFile()); // Backward compat // May be a backward compatibility problem, try to base64decode the filepath if (!file_exists($node->getUrl()) && strpos($httpVars["file"], "base64encoded:") === false) { $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); if (!file_exists($destStreamURL . $file)) { throw new Exception("Cannot find file!"); } else { $node = new AJXP_Node($destStreamURL . $file); } } if (!is_readable($node->getUrl())) { throw new Exception("Cannot find file!"); } $fileUrl = $node->getUrl(); $localName = basename($fileUrl); $cType = "audio/" . array_pop(explode(".", $localName)); $size = filesize($node->getUrl()); header("Content-Type: " . $cType . "; name=\"" . $localName . "\""); header("Content-Length: " . $size); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($fileUrl, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($node)); $this->logInfo('Preview', 'Read content of ' . $node->getUrl(), array("files" => $node->getUrl())); //exit(1); } else { if ($action == "ls") { if (!isset($httpVars["playlist"])) { // This should not happen anyway, because of the applyCondition. AJXP_Controller::passProcessDataThrough($postProcessData); return false; } // We transform the XML into XSPF $xmlString = $postProcessData["ob_output"]; $xmlDoc = new DOMDocument(); $xmlDoc->loadXML($xmlString); $xElement = $xmlDoc->documentElement; header("Content-Type:application/xspf+xml;charset=UTF-8"); print '<?xml version="1.0" encoding="UTF-8"?>'; print '<playlist version="1" xmlns="http://xspf.org/ns/0/">'; print "<trackList>"; foreach ($xElement->childNodes as $child) { $isFile = $child->getAttribute("is_file") == "true"; $label = $child->getAttribute("text"); $ar = explode(".", $label); $ext = strtolower(end($ar)); if (!$isFile || $ext != "mp3") { continue; } print "<track><location>" . AJXP_SERVER_ACCESS . "?secure_token=" . AuthService::getSecureToken() . "&get_action=audio_proxy&file=" . base64_encode($child->getAttribute("filename")) . "</location><title>" . $label . "</title></track>"; } print "</trackList>"; AJXP_XMLWriter::close("playlist"); } } }