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 initDirAndSelection($httpVars, $additionnalPathes = array(), $testRecycle = false) { $repo = $this->accessDriver->repository; $repo->detectStreamWrapper(true); $userSelection = new UserSelection($repo, $httpVars); $urlBase = $userSelection->currentBaseUrl(); $result = array(); if ($testRecycle) { $recycle = $repo->getOption("RECYCLE_BIN"); if ($recycle != "") { RecycleBinManager::init($urlBase, "/" . $recycle); $result["RECYCLE"] = RecycleBinManager::filterActions($httpVars["get_action"], $userSelection, $httpVars["dir"], $httpVars); // if necessary, check recycle was checked. // We could use a hook instead here? Maybe the full recycle system // could be turned into a plugin $sessionKey = "AJXP_SVN_" . $repo->getId() . "_RECYCLE_CHECKED"; if (isset($_SESSION[$sessionKey])) { $file = RecycleBinManager::getRelativeRecycle() . "/" . RecycleBinManager::getCacheFileName(); $realFile = AJXP_MetaStreamWrapper::getRealFSReference($urlBase . $file); $this->addIfNotVersionned($file, $realFile); $_SESSION[$sessionKey] = true; } } } $result["DIR"] = AJXP_MetaStreamWrapper::getRealFSReference($urlBase . AJXP_Utils::decodeSecureMagic($httpVars["dir"])); $result["ORIGINAL_SELECTION"] = $userSelection; $result["SELECTION"] = array(); if (!$userSelection->isEmpty()) { $files = $userSelection->getFiles(); foreach ($files as $selected) { $result["SELECTION"][] = AJXP_MetaStreamWrapper::getRealFSReference($urlBase . $selected); } } foreach ($additionnalPathes as $parameter => $path) { $result[$parameter] = AJXP_MetaStreamWrapper::getRealFSReference($urlBase . $path); } return $result; }
protected function updateMetaShort($file, $elementId, $shortUrl) { $context = new UserSelection(ConfService::getRepository()); $baseUrl = $context->currentBaseUrl(); $node = new AJXP_Node($baseUrl . $file); if ($node->hasMetaStore()) { $metadata = $node->retrieveMetadata("ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY); if ($elementId != -1) { if (!is_array($metadata["element"][$elementId])) { $metadata["element"][$elementId] = array(); } $metadata["element"][$elementId]["short_form_url"] = $shortUrl; } else { if (isset($metadata["shares"])) { $key = array_pop(array_keys($metadata["shares"])); $metadata["shares"][$key]["short_form_url"] = $shortUrl; } else { $metadata['short_form_url'] = $shortUrl; } } $node->setMetadata("ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY); } }
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; } }
/** * @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); } } } }
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; } }
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)); } } }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $convert = $this->getFilteredOption("IMAGE_MAGICK_CONVERT"); if (empty($convert)) { return false; } $flyThreshold = 1024 * 1024 * intval($this->getFilteredOption("ONTHEFLY_THRESHOLD", $repository)); $selection = new UserSelection($repository, $httpVars); $destStreamURL = $selection->currentBaseUrl(); if ($action == "imagick_data_proxy") { $this->extractAll = false; $file = $selection->getUniqueNode()->getUrl(); if (!file_exists($file) || !is_readable($file)) { throw new Exception("Cannot find file"); } if (isset($httpVars["all"])) { $this->logInfo('Preview', 'Preview content of ' . $file, array("files" => $file)); $this->extractAll = true; } if (($size = filesize($file)) === false) { return false; } else { if ($size > $flyThreshold) { $this->useOnTheFly = true; } else { $this->useOnTheFly = false; } } if ($this->extractAll) { $node = new AJXP_Node($file); AJXP_Controller::applyHook("node.read", array($node)); } $cache = AJXP_Cache::getItem("imagick_" . ($this->extractAll ? "full" : "thumb"), $file, array($this, "generateJpegsCallback")); session_write_close(); $cacheData = $cache->getData(); if (!$this->useOnTheFly && $this->extractAll) { // extract all on first view $ext = pathinfo($file, PATHINFO_EXTENSION); $prefix = str_replace(".{$ext}", "", $cache->getId()); $files = $this->listExtractedJpg($file, $prefix); header("Content-Type: application/json"); print json_encode($files); return false; } else { if ($this->extractAll) { // on the fly extract mode $ext = pathinfo($file, PATHINFO_EXTENSION); $prefix = str_replace(".{$ext}", "", $cache->getId()); $files = $this->listPreviewFiles($file, $prefix); header("Content-Type: application/json"); print json_encode($files); return false; } else { header("Content-Type: image/jpeg; name=\"" . basename($file) . "\""); header("Content-Length: " . strlen($cacheData)); 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 $cacheData; return false; } } } else { if ($action == "get_extracted_page" && isset($httpVars["file"])) { $file = (defined('AJXP_SHARED_CACHE_DIR') ? AJXP_SHARED_CACHE_DIR : AJXP_CACHE_DIR) . "/imagick_full/" . AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!is_file($file)) { $srcfile = AJXP_Utils::decodeSecureMagic($httpVars["src_file"]); if ($repository->hasContentFilter()) { $contentFilter = $repository->getContentFilter(); $srcfile = $contentFilter->filterExternalPath($srcfile); } $size = filesize($destStreamURL . "/" . $srcfile); if ($size > $flyThreshold) { $this->useOnTheFly = true; } else { $this->useOnTheFly = false; } if ($this->useOnTheFly) { $this->onTheFly = true; } $this->generateJpegsCallback($destStreamURL . $srcfile, $file); } if (!is_file($file)) { return false; } header("Content-Type: image/jpeg; name=\"" . basename($file) . "\""); header("Content-Length: " . filesize($file)); header('Cache-Control: public'); readfile($file); exit(1); } else { if ($action == "delete_imagick_data" && !$selection->isEmpty()) { /* $files = $this->listExtractedJpg(AJXP_CACHE_DIR."/".$httpVars["file"]); foreach ($files as $file) { if(is_file(AJXP_CACHE_DIR."/".$file["file"])) unlink(AJXP_CACHE_DIR."/".$file["file"]); } */ } } } }
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::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); if ($selection->isEmpty()) { return; } $node = $selection->getUniqueNode(); $file = $node->getUrl(); AJXP_Controller::applyHook("node.read", array($node)); $wrapperClassName = AJXP_MetaStreamWrapper::actualRepositoryWrapperClass($repository->getId()); $mess = ConfService::getMessages(); switch ($action) { case "eml_get_xml_structure": $params = array('include_bodies' => false, 'decode_bodies' => false, 'decode_headers' => 'UTF-8'); $decoder = $this->getStructureDecoder($file, $wrapperClassName == "imapAccessWrapper"); $xml = $decoder->getXML($decoder->decode($params)); if (function_exists("imap_mime_header_decode")) { $doc = new DOMDocument(); $doc->loadXML($xml); $xPath = new DOMXPath($doc); $headers = $xPath->query("//headername"); $changes = false; foreach ($headers as $headerNode) { if ($headerNode->firstChild->nodeValue == "Subject") { $headerValueNode = $headerNode->nextSibling->nextSibling; $value = $headerValueNode->nodeValue; $elements = imap_mime_header_decode($value); $decoded = ""; foreach ($elements as $element) { $decoded .= $element->text; $charset = $element->charset; } if ($decoded != $value) { $value = SystemTextEncoding::changeCharset($charset, "UTF-8", $decoded); $node = $doc->createElement("headervalue", $value); $res = $headerNode->parentNode->replaceChild($node, $headerValueNode); $changes = true; } } } if ($changes) { $xml = $doc->saveXML(); } } print $xml; break; case "eml_get_bodies": require_once "Mail/mimeDecode.php"; $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false); if ($wrapperClassName == "imapAccessWrapper") { $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId")); $content = $cache->getData(); } else { $content = file_get_contents($file); } $decoder = new Mail_mimeDecode($content); $structure = $decoder->decode($params); $html = $this->_findPartByCType($structure, "text", "html"); $text = $this->_findPartByCType($structure, "text", "plain"); if ($html != false && isset($html->ctype_parameters) && isset($html->ctype_parameters["charset"])) { $charset = $html->ctype_parameters["charset"]; } if (isset($charset)) { header('Content-Type: text/xml; charset=' . $charset); header('Cache-Control: no-cache'); print '<?xml version="1.0" encoding="' . $charset . '"?>'; print '<email_body>'; } else { AJXP_XMLWriter::header("email_body"); } if ($html !== false) { print '<mimepart type="html"><![CDATA['; $text = $html->body; print $text; print "]]></mimepart>"; } if ($text !== false) { print '<mimepart type="plain"><![CDATA['; print $text->body; print "]]></mimepart>"; } AJXP_XMLWriter::close("email_body"); break; case "eml_dl_attachment": $attachId = $httpVars["attachment_id"]; if (!isset($attachId)) { break; } require_once "Mail/mimeDecode.php"; $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false); if ($wrapperClassName == "imapAccessWrapper") { $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId")); $content = $cache->getData(); } else { $content = file_get_contents($file); } $decoder = new Mail_mimeDecode($content); $structure = $decoder->decode($params); $part = $this->_findAttachmentById($structure, $attachId); if ($part !== false) { $fake = new fsAccessDriver("fake", ""); $fake->readFile($part->body, "file", $part->d_parameters['filename'], true); exit; } else { //var_dump($structure); } break; case "eml_cp_attachment": $attachId = $httpVars["attachment_id"]; $destRep = AJXP_Utils::decodeSecureMagic($httpVars["destination"]); if (!isset($attachId)) { AJXP_XMLWriter::sendMessage(null, "Wrong Parameters"); break; } require_once "Mail/mimeDecode.php"; $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false); if ($wrapperClassName == "imapAccessWrapper") { $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId")); $content = $cache->getData(); } else { $content = file_get_contents($file); } $decoder = new Mail_mimeDecode($content); $structure = $decoder->decode($params); $part = $this->_findAttachmentById($structure, $attachId); AJXP_XMLWriter::header(); if ($part !== false) { $destStreamURL = $selection->currentBaseUrl(); if (isset($httpVars["dest_repository_id"])) { $destRepoId = $httpVars["dest_repository_id"]; if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canWrite($destRepoId)) { throw new Exception($mess[364]); } } $destRepoObject = ConfService::getRepositoryById($destRepoId); $destRepoObject->detectStreamWrapper(true); $destStreamURL = "pydio://{$destRepoId}"; } $destFile = $destStreamURL . $destRep . "/" . $part->d_parameters['filename']; $fp = fopen($destFile, "w"); if ($fp !== false) { fwrite($fp, $part->body, strlen($part->body)); fclose($fp); AJXP_XMLWriter::sendMessage(sprintf($mess["editor.eml.7"], $part->d_parameters["filename"], $destRep), NULL); } else { AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.8"]); } } else { AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.9"]); } AJXP_XMLWriter::close(); break; default: break; } }
public function unifyChunks($action, $httpVars, $fileVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $destStreamURL = $selection->currentBaseUrl() . $dir . "/"; $filename = AJXP_Utils::decodeSecureMagic($httpVars["file_name"]); $chunks = array(); $index = 0; while (isset($httpVars["chunk_" . $index])) { $chunks[] = AJXP_Utils::decodeSecureMagic($httpVars["chunk_" . $index]); $index++; } $newDest = fopen($destStreamURL . $filename, "w"); for ($i = 0; $i < count($chunks); $i++) { $part = fopen($destStreamURL . $chunks[$i], "r"); if (is_resource($part)) { while (!feof($part)) { fwrite($newDest, fread($part, 4096)); } fclose($part); } unlink($destStreamURL . $chunks[$i]); } fclose($newDest); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($newDest), false)); }
public function switchAction($action, $httpVars, $fileVars) { //$this->logInfo("DL file", $httpVars); $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $userSelection = new UserSelection($repository); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $currentDirUrl = $userSelection->currentBaseUrl() . $dir . "/"; $dlURL = null; if (isset($httpVars["file"])) { $parts = parse_url($httpVars["file"]); $getPath = $parts["path"]; $basename = basename($getPath); //$dlURL = $httpVars["file"]; } else { if (isset($httpVars["dlfile"])) { $dlFile = $userSelection->currentBaseUrl() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]); $realFile = file_get_contents($dlFile); if (empty($realFile)) { throw new Exception("cannot find file {$dlFile} for download"); } $parts = parse_url($realFile); $getPath = $parts["path"]; $basename = basename($getPath); //$dlURL = $realFile; } else { throw new Exception("Missing argument, either file or dlfile"); } } $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $fsDriver->filterUserSelectionToHidden(array($basename)); switch ($action) { case "external_download": if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) { $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars); if ($unixProcess !== null) { @file_put_contents($currentDirUrl . "." . $basename . ".pid", $unixProcess->getPid()); } AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2); AJXP_XMLWriter::close(); session_write_close(); exit; } require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; session_write_close(); $httpClient = new http_class(); $arguments = array(); $httpClient->GetRequestArguments($httpVars["file"], $arguments); $err = $httpClient->Open($arguments); $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => ""); if (!empty($err)) { throw new Exception($err); } $err = $httpClient->SendRequest($arguments); $httpClient->follow_redirect = true; $pidHiddenFileName = $currentDirUrl . "." . $basename . ".pid"; if (is_file($pidHiddenFileName)) { $pid = file_get_contents($pidHiddenFileName); @unlink($pidHiddenFileName); } if (!empty($err)) { $httpClient->Close(); throw new Exception($err); } $httpClient->ReadReplyHeaders($collectHeaders); $totalSize = -1; if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) { $ar = explode("filename=", $collectHeaders["content-disposition"]); $basename = trim(array_pop($ar)); $basename = str_replace("\"", "", $basename); // Remove quotes } if (!empty($collectHeaders["content-length"])) { $totalSize = intval($collectHeaders["content-length"]); $this->logDebug("Should download {$totalSize} bytes!"); } if ($totalSize != -1) { $node = new AJXP_Node($currentDirUrl . $basename); AJXP_Controller::applyHook("node.before_create", array($node, $totalSize)); } $tmpFilename = $currentDirUrl . $basename . ".dlpart"; $hiddenFilename = $currentDirUrl . "__" . $basename . ".ser"; $filename = $currentDirUrl . $basename; $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize); if (isset($pid)) { $dlData["pid"] = $pid; } //file_put_contents($hiddenFilename, serialize($dlData)); $fpHid = fopen($hiddenFilename, "w"); fputs($fpHid, serialize($dlData)); fclose($fpHid); // NOW READ RESPONSE $destStream = fopen($tmpFilename, "w"); while (true) { $body = ""; $error = $httpClient->ReadReplyBody($body, 1000); if ($error != "" || strlen($body) == 0) { break; } fwrite($destStream, $body, strlen($body)); } fclose($destStream); rename($tmpFilename, $filename); unlink($hiddenFilename); $httpClient->Close(); if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) { AJXP_Controller::applyHook("node.before_path_change", array(new AJXP_Node($dlFile))); unlink($dlFile); AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false)); } $mess = ConfService::getMessages(); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false)); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]); AJXP_XMLWriter::close(); break; case "update_dl_data": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); header("text/plain"); if (is_file($currentDirUrl . $file)) { $node = new AJXP_Node($currentDirUrl . $file); $filesize = filesize($node->getUrl()); echo $filesize; } else { echo "stop"; } break; case "stop_dl": $newName = "__" . str_replace(".dlpart", ".ser", $basename); $hiddenFilename = $currentDirUrl . $newName; $data = @unserialize(@file_get_contents($hiddenFilename)); header("text/plain"); $this->logDebug("Getting {$hiddenFilename}", $data); if (isset($data["pid"])) { $process = new UnixProcess(); $process->setPid($data["pid"]); $process->stop(); unlink($hiddenFilename); unlink($currentDirUrl . $basename); echo 'stop'; } else { echo 'failed'; } break; default: break; } return false; }
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)); } } }
public function postProcess($action, $httpVars, $postProcessData) { if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) { return; } /* If set resumeFileId and resumePartitionIndex, cross-session resume is requested. */ if (isset($httpVars["resumeFileId"]) && isset($httpVars["resumePartitionIndex"])) { header("HTTP/1.1 200 OK"); print "fileId: " . $httpVars["resumeFileId"] . "\n"; print "partitionIndex: " . $httpVars["resumePartitionIndex"]; return; } /*if (self::$skipDecoding) { }*/ if (isset($postProcessData["processor_result"]["ERROR"])) { if (isset($httpVars["lastPartition"]) && isset($httpVars["partitionCount"])) { /* we get the stream url (where all the partitions have been uploaded so far) */ $repository = ConfService::getRepository(); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $repository->detectStreamWrapper(true); $context = new UserSelection($repository); $destStreamURL = $context->currentBaseUrl() . $dir . "/"; if ($httpVars["partitionCount"] > 1) { /* we fetch the information that help us to construct the temp files name */ $fileId = $httpVars["fileId"]; $fileHash = md5($httpVars["fileName"]); /* deletion of all the partitions that have been uploaded */ for ($i = 0; $i < $httpVars["partitionCount"]; $i++) { if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) { unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } } else { $fileName = $httpVars["fileName"]; unlink($destStreamURL . $fileName); } } echo "Error: " . $postProcessData["processor_result"]["ERROR"]["MESSAGE"]; return; } if (!isset($httpVars["partitionRealName"]) && !isset($httpVars["lastPartition"])) { return; } $repository = ConfService::getRepository(); $driver = ConfService::loadDriverForRepository($repository); if (!$repository->detectStreamWrapper(false)) { return false; } if ($httpVars["lastPartition"]) { $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $repository->detectStreamWrapper(true); $context = new UserSelection($repository); $destStreamURL = $context->currentBaseUrl() . $dir . "/"; /* we check if the current file has a relative path (aka we want to upload an entire directory) */ $this->logDebug("Now dispatching relativePath dest:", $httpVars["relativePath"]); $subs = explode("/", $httpVars["relativePath"]); $userfile_name = array_pop($subs); $folderForbidden = false; $all_in_place = true; $partitions_length = 0; $fileId = $httpVars["fileId"]; $fileHash = md5($userfile_name); $partitionCount = $httpVars["partitionCount"]; $fileLength = $_POST["fileLength"]; /* * * Now, we supposed that access driver has already saved uploaded file in to * folderServer with file name is md5 relativePath value. * We try to copy this file to right location in recovery his name. * */ $userfile_name = md5($httpVars["relativePath"]); if (self::$remote) { $partitions = array(); $newPartitions = array(); $index_first_partition = -1; $i = 0; do { $currentFileName = $driver->getFileNameToCopy(); $partitions[] = $driver->getNextFileToCopy(); if ($index_first_partition < 0 && strstr($currentFileName, $fileHash) != false) { $index_first_partition = $i; } else { if ($index_first_partition < 0) { $newPartitions[] = array_pop($partitions); } } } while ($driver->hasFilesToCopy()); } /* if partitionned */ if ($partitionCount > 1) { if (self::$remote) { for ($i = 0; $all_in_place && $i < $partitionCount; $i++) { $partition_file = "{$fileHash}.{$fileId}.{$i}"; if (strstr($partitions[$i]["name"], $partition_file) != false) { $partitions_length += filesize($partitions[$i]["tmp_name"]); } else { $all_in_place = false; } } } else { for ($i = 0; $all_in_place && $i < $partitionCount; $i++) { $partition_file = $destStreamURL . "{$fileHash}.{$fileId}.{$i}"; if (file_exists($partition_file)) { $partitions_length += filesize($partition_file); } else { $all_in_place = false; } } } } else { if (self::$remote) { if (strstr($newPartitions[count($newPartitions) - 1]["name"], $userfile_name) != false) { $partitions_length += filesize($newPartitions[count($newPartitions) - 1]["tmp_name"]); } } else { if (file_exists($destStreamURL . $userfile_name)) { $partitions_length += filesize($destStreamURL . $userfile_name); } } } if (!$all_in_place || $partitions_length != floatval($fileLength)) { echo "Error: Upload validation error!"; /* we delete all the uploaded partitions */ if ($httpVars["partitionCount"] > 1) { for ($i = 0; $i < $partitionCount; $i++) { if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) { unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } } else { $fileName = $httpVars["partitionRealName"]; unlink($destStreamURL . $fileName); } return; } if (count($subs) > 0 && !self::$remote) { $curDir = ""; if (substr($curDir, -1) == "/") { $curDir = substr($curDir, 0, -1); } // Create the folder tree as necessary foreach ($subs as $key => $spath) { $messtmp = ""; $dirname = AJXP_Utils::decodeSecureMagic($spath, AJXP_SANITIZE_FILENAME); $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); //$this->filterUserSelectionToHidden(array($dirname)); if (AJXP_Utils::isHidden($dirname)) { $folderForbidden = true; break; } if (file_exists($destStreamURL . "{$curDir}/{$dirname}")) { // if the folder exists, traverse $this->logDebug("{$curDir}/{$dirname} existing, traversing for {$userfile_name} out of", $httpVars["relativePath"]); $curDir .= "/" . $dirname; continue; } $this->logDebug($destStreamURL . $curDir); $dirMode = 0775; $chmodValue = $repository->getOption("CHMOD_VALUE"); if (isset($chmodValue) && $chmodValue != "") { $dirMode = octdec(ltrim($chmodValue, "0")); if ($dirMode & 0400) { $dirMode |= 0100; } // Owner is allowed to read, allow to list the directory if ($dirMode & 040) { $dirMode |= 010; } // Group is allowed to read, allow to list the directory if ($dirMode & 04) { $dirMode |= 01; } // Other are allowed to read, allow to list the directory } $url = $destStreamURL . $curDir . "/" . $dirname; $old = umask(0); mkdir($url, $dirMode); umask($old); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($url), false)); $curDir .= "/" . $dirname; } } if (!$folderForbidden) { $fileId = $httpVars["fileId"]; $this->logDebug("Should now rebuild file!", $httpVars); // Now move the final file to the right folder // Currently the file is at the base of the current $this->logDebug("PartitionRealName", $destStreamURL . $httpVars["partitionRealName"]); // Get file by name (md5 value) $relPath_md5 = AJXP_Utils::decodeSecureMagic(md5($httpVars["relativePath"])); // original file name $relPath = AJXP_Utils::decodeSecureMagic($httpVars["relativePath"]); $target = $destStreamURL; $target .= self::$remote ? basename($relPath) : $relPath; /* * $current is uploaded file with md5 value as his name * we copy to $relPath and delete md5 file */ $current = $destStreamURL . basename($relPath_md5); if ($httpVars["partitionCount"] > 1) { if (self::$remote) { $test = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"]; $newDest = fopen(AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"], "w"); $newFile = array(); $length = 0; for ($i = 0, $count = count($partitions); $i < $count; $i++) { $currentFile = $partitions[$i]; $currentFileName = $currentFile["tmp_name"]; $part = fopen($currentFileName, "r"); if (is_resource($part)) { while (!feof($part)) { $length += fwrite($newDest, fread($part, 4096)); } fclose($part); } unlink($currentFileName); } $newFile["type"] = $partitions[0]["type"]; $newFile["name"] = $httpVars["partitionRealName"]; $newFile["error"] = 0; $newFile["size"] = $length; $newFile["tmp_name"] = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"]; $newFile["destination"] = $partitions[0]["destination"]; $newPartitions[] = $newFile; } else { $current = $destStreamURL . $httpVars["partitionRealName"]; $newDest = fopen($current, "w"); $fileHash = md5($httpVars["partitionRealName"]); for ($i = 0; $i < $httpVars["partitionCount"]; $i++) { $part = fopen($destStreamURL . "{$fileHash}.{$fileId}.{$i}", "r"); if (is_resource($part)) { while (!feof($part)) { fwrite($newDest, fread($part, 4096)); } fclose($part); } unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } fclose($newDest); } if (!self::$remote && (!self::$wrapperIsRemote || $relPath != $httpVars["partitionRealName"])) { if ($current != $target) { $err = copy($current, $target); } else { $err = true; } } else { for ($i = 0, $count = count($newPartitions); $i < $count; $i++) { $driver->storeFileToCopy($newPartitions[$i]); } } if ($current != $target && $err !== false) { if (!self::$remote) { unlink($current); } AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false)); } else { if ($current == $target) { AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false)); } } } else { // Remove the file, as it should not have been uploaded! //if(!self::$remote) unlink($current); } } }
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"); } } }