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, $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 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 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); } }
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)); } } }
/** * Get a "usable" reference to a file : the real file or a tmp copy. * * @param string $path * @param bool $persistent * @return string */ public static function getRealFSReference($path, $persistent = false) { $url = self::translateURL($path); if (self::$linkNode !== null) { $isRemote = AJXP_MetaStreamWrapper::wrapperIsRemote($url); $realFilePointer = AJXP_MetaStreamWrapper::getRealFSReference($url, true); if (!$isRemote) { $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION); $tmpname = tempnam(AJXP_Utils::getAjxpTmpDir(), "real-file-inbox-pointer") . "." . $ext; copy($realFilePointer, $tmpname); $realFilePointer = $tmpname; } ConfService::loadDriverForRepository(self::$linkNode->getRepository()); return $realFilePointer; } else { $tmpname = tempnam(AJXP_Utils::getAjxpTmpDir(), "real-file-inbox-pointer"); $source = fopen($url, "r"); $dest = fopen($tmpname, "w"); stream_copy_to_stream($source, $dest); return $tmpname; } }
/** * 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; }
/** * @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, $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)); } }
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; }
/** * @param String $srcdir Url of source file * @param String $dstdir Url of dest file * @param Array $errors Array of errors * @param Array $success Array of success * @param bool $verbose Boolean * @param bool $convertSrcFile Boolean * @param array $srcRepoData Set of data concerning source repository: base_url, recycle option * @param array $destRepoData Set of data concerning destination repository: base_url, chmod option * @return int */ protected function dircopy($srcdir, $dstdir, &$errors, &$success, $verbose = false, $convertSrcFile = true, $srcRepoData = array(), $destRepoData = array()) { $num = 0; //$verbose = true; $recurse = array(); if (!is_dir($dstdir)) { $dirMode = 0755; $chmodValue = $destRepoData["chmod"]; //$this->repository->getOption("CHMOD_VALUE"); if (isset($chmodValue) && $chmodValue != "") { $dirMode = octdec(ltrim($chmodValue, "0")); if ($dirMode & 0400) { $dirMode |= 0100; } // User 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 } $old = umask(0); mkdir($dstdir, $dirMode); umask($old); } if ($curdir = opendir($srcdir)) { while (($file = readdir($curdir)) !== FALSE) { if ($file != '.' && $file != '..') { $srcfile = $srcdir . "/" . $file; $dstfile = $dstdir . "/" . $file; if (is_file($srcfile)) { if (is_file($dstfile)) { $ow = filemtime($srcfile) - filemtime($dstfile); } else { $ow = 1; } if ($ow > 0) { try { if ($convertSrcFile) { $tmpPath = AJXP_MetaStreamWrapper::getRealFSReference($srcfile); } else { $tmpPath = $srcfile; } if ($verbose) { echo "Copying '{$tmpPath}' to '{$dstfile}'..."; } copy($tmpPath, $dstfile); $success[] = $srcfile; $num++; $this->changeMode($dstfile, $destRepoData); } catch (Exception $e) { $errors[] = $srcfile; } } } else { $recurse[] = array("src" => $srcfile, "dest" => $dstfile); } } } closedir($curdir); foreach ($recurse as $rec) { if ($verbose) { echo "Dircopy {$srcfile}"; } $num += $this->dircopy($rec["src"], $rec["dest"], $errors, $success, $verbose, $convertSrcFile, $srcRepoData, $destRepoData); } } return $num; }