public function accessPreprocess($actionName, &$httpVars, &$filesVar) { if ($actionName == "apply_check_hook") { if (!in_array($httpVars["hook_name"], array("before_create", "before_path_change", "before_change"))) { return; } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $node = $selection->getUniqueNode($this); AJXP_Controller::applyHook("node." . $httpVars["hook_name"], array($node, $httpVars["hook_arg"])); } if ($actionName == "ls") { // UPWARD COMPATIBILTY if (isset($httpVars["options"])) { if ($httpVars["options"] == "al") { $httpVars["mode"] = "file_list"; } else { if ($httpVars["options"] == "a") { $httpVars["mode"] = "search"; } else { if ($httpVars["options"] == "d") { $httpVars["skipZip"] = "true"; } } } // skip "complete" mode that was in fact quite the same as standard tree listing (dz) } } }
/** * @param string $action * @param array $httpVars * @param array $fileVars */ public function applyChangeLock($actionName, $httpVars, $fileVars) { if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection($repo, $httpVars); $unlock = isset($httpVars["unlock"]) ? true : false; if ($unlock) { $this->metaStore->removeMetadata($selection->getUniqueNode(), self::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL); } else { $this->metaStore->setMetadata($selection->getUniqueNode(), SimpleLockManager::METADATA_LOCK_NAMESPACE, array("lock_user" => AuthService::getLoggedUser()->getId()), false, AJXP_METADATA_SCOPE_GLOBAL); } AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); }
/** * @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 switchActions($actionName, $httpVars, $fileVars) { switch ($actionName) { case "toggle_watch": $us = new UserSelection(); $us->initFromHttpVars($httpVars); $node = $us->getUniqueNode($this->accessDriver); $node->loadNodeInfo(); $cmd = $httpVars["watch_action"]; $meta = $this->metaStore->retrieveMetadata($node, self::$META_WATCH_NAMESPACE, false, AJXP_METADATA_SCOPE_REPOSITORY); $userId = AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getId() : "shared"; if ($cmd == "watch_stop" && isset($meta) && isset($meta[$userId])) { unset($meta[$userId]); $this->metaStore->removeMetadata($node, self::$META_WATCH_NAMESPACE, false, AJXP_METADATA_SCOPE_REPOSITORY); } else { switch ($cmd) { case "watch_change": $type = self::$META_WATCH_CHANGE; break; case "watch_read": $type = self::$META_WATCH_READ; break; case "watch_both": $type = self::$META_WATCH_BOTH; break; default: break; } $meta[$userId] = $type; $this->metaStore->setMetadata($node, self::$META_WATCH_NAMESPACE, $meta, false, AJXP_METADATA_SCOPE_REPOSITORY); } AJXP_XMLWriter::header(); $node->metadata = array(); $node->loadNodeInfo(true, false, "all"); $this->enrichNode($node); AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => array($node->getPath() => $node)), true); AJXP_XMLWriter::close(); break; default: break; } }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepositoryById($httpVars["repository_id"]); if (!$repository->detectStreamWrapper(true)) { return false; } if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) { AuthService::logUser("guest", null); $loggedUser = AuthService::getLoggedUser(); } if (!$loggedUser->canSwitchTo($repository->getId())) { echo "You do not have permissions to access this resource"; return false; } } $selection = new UserSelection($repository, $httpVars); if ($action == "open_file") { $selectedNode = $selection->getUniqueNode(); $selectedNodeUrl = $selectedNode->getUrl(); if (!file_exists($selectedNodeUrl) || !is_readable($selectedNodeUrl)) { echo "File does not exist"; return false; } $filesize = filesize($selectedNodeUrl); $fp = fopen($selectedNodeUrl, "rb"); $fileMime = "application/octet-stream"; //Get mimetype with fileinfo PECL extension if (class_exists("finfo")) { $finfo = new finfo(FILEINFO_MIME); $fileMime = $finfo->buffer(fread($fp, 2000)); } //Get mimetype with (deprecated) mime_content_type if (strpos($fileMime, "application/octet-stream") === 0 && function_exists("mime_content_type")) { $fileMime = @mime_content_type($fp); } //Guess mimetype based on file extension if (strpos($fileMime, "application/octet-stream") === 0) { $fileExt = substr(strrchr(basename($selectedNodeUrl), '.'), 1); if (empty($fileExt)) { $fileMime = "application/octet-stream"; } else { $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i"; $lines = file($this->getBaseDir() . "/resources/other/mime.types"); foreach ($lines as $line) { if (substr($line, 0, 1) == '#') { continue; } // skip comments $line = rtrim($line) . " "; if (!preg_match($regex, $line, $matches)) { continue; } // no match to the extension $fileMime = $matches[1]; } } } fclose($fp); // If still no mimetype, give up and serve application/octet-stream if (empty($fileMime)) { $fileMime = "application/octet-stream"; } //Send headers HTMLWriter::generateInlineHeaders(basename($selectedNodeUrl), $filesize, $fileMime); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($selectedNodeUrl, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($selectedNode)); $this->logInfo('Download', 'Read content of ' . $selectedNodeUrl, array("files" => $selectedNodeUrl)); } }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $selectedNode = $selection->getUniqueNode(); $selectedNodeUrl = $selectedNode->getUrl(); if ($action == "post_to_server") { // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $legacyFilePath = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $legacyFilePath); $selectedNodeUrl = $selectedNode->getUrl(); } $target = rtrim(base64_decode($httpVars["parent_url"]), '/') . "/plugins/editor.pixlr"; $tmp = AJXP_MetaStreamWrapper::getRealFSReference($selectedNodeUrl); $tmp = SystemTextEncoding::fromUTF8($tmp); $this->logInfo('Preview', 'Sending content of ' . $selectedNodeUrl . ' to Pixlr server.', array("files" => $selectedNodeUrl)); AJXP_Controller::applyHook("node.read", array($selectedNode)); $saveTarget = $target . "/fake_save_pixlr.php"; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $saveTarget = $target . "/fake_save_pixlr_" . md5($httpVars["secure_token"]) . ".php"; } $params = array("referrer" => "Pydio", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $saveTarget, "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($selectedNodeUrl)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source"); require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; $arguments = array(); $httpClient = new http_class(); $httpClient->request_method = "POST"; $httpClient->GetRequestArguments("https://pixlr.com/editor/", $arguments); $arguments["PostValues"] = $params; $arguments["PostFiles"] = array("image" => array("FileName" => $tmp, "Content-Type" => "automatic/name")); $err = $httpClient->Open($arguments); if (empty($err)) { $err = $httpClient->SendRequest($arguments); if (empty($err)) { $response = ""; while (true) { $header = array(); $error = $httpClient->ReadReplyHeaders($header, 1000); if ($error != "" || $header != null) { break; } $response .= $header; } } } header("Location: {$header['location']}"); //$response"); } else { if ($action == "retrieve_pixlr_image") { $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]); $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $file); $selectedNode->loadNodeInfo(); $this->logInfo('Edit', 'Retrieving content of ' . $file . ' from Pixlr server.', array("files" => $file)); AJXP_Controller::applyHook("node.before_change", array(&$selectedNode)); $url = $httpVars["new_url"]; $urlParts = parse_url($url); $query = $urlParts["query"]; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $scriptName = basename($urlParts["path"]); $token = str_replace(array("fake_save_pixlr_", ".php"), "", $scriptName); if ($token != md5($httpVars["secure_token"])) { throw new AJXP_Exception("Invalid Token, this could mean some security problem!"); } } $params = array(); parse_str($query, $params); $image = $params['image']; $headers = get_headers($image, 1); $content_type = explode("/", $headers['Content-Type']); if ($content_type[0] != "image") { throw new AJXP_Exception("Invalid File Type"); } $content_length = intval($headers["Content-Length"]); if ($content_length != 0) { AJXP_Controller::applyHook("node.before_change", array(&$selectedNode, $content_length)); } $orig = fopen($image, "r"); $target = fopen($selectedNode->getUrl(), "w"); if (is_resource($orig) && is_resource($target)) { while (!feof($orig)) { fwrite($target, fread($orig, 4096)); } fclose($orig); fclose($target); } clearstatcache(true, $selectedNode->getUrl()); $selectedNode->loadNodeInfo(true); AJXP_Controller::applyHook("node.change", array(&$selectedNode, &$selectedNode)); } } }
/** * @param String $actionName * @param Array $httpVars * @param Array $fileVars */ public function switchActions($actionName, $httpVars, $fileVars) { $userSelection = new UserSelection($this->accessDriver->repository, $httpVars); $uniqNode = $userSelection->getUniqueNode(); $feedStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("feed"); $existingFeed = $uniqNode->retrieveMetadata(AJXP_META_SPACE_COMMENTS, false); if ($existingFeed == null) { $existingFeed = array(); } $mess = ConfService::getMessages(); switch ($actionName) { case "post_comment": $uId = AuthService::getLoggedUser()->getId(); $limit = $this->getFilteredOption("COMMENT_SIZE_LIMIT"); if (!empty($limit)) { $content = substr(AJXP_Utils::decodeSecureMagic($httpVars["content"]), 0, $limit); } else { $content = AJXP_Utils::decodeSecureMagic($httpVars["content"]); } $com = array("date" => time(), "author" => $uId, "content" => $content); $existingFeed[] = $com; if ($feedStore !== false) { $feedStore->persistMetaObject($uniqNode->getPath(), base64_encode($content), $uniqNode->getRepositoryId(), $uniqNode->getRepository()->securityScope(), $uniqNode->getRepository()->getOwner(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath()); } else { $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false); $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $existingFeed, false); } HTMLWriter::charsetHeader("application/json"); $com["hdate"] = AJXP_Utils::relativeDate($com["date"], $mess); $com["path"] = $uniqNode->getPath(); echo json_encode($com); break; case "load_comments_feed": HTMLWriter::charsetHeader("application/json"); if ($feedStore !== false) { $sortBy = isset($httpVars["sort_by"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_by"]) : "date"; $sortDir = isset($httpVars["sort_dir"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_dir"]) : "asc"; $offset = isset($httpVars["offset"]) ? intval($httpVars["offset"]) : 0; $limit = isset($httpVars["limit"]) ? intval($httpVars["limit"]) : 100; $uniqNode->loadNodeInfo(); $data = $feedStore->findMetaObjectsByIndexPath($this->accessDriver->repository->getId(), $uniqNode->getPath(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath(), $offset, $limit, $sortBy, $sortDir, !$uniqNode->isLeaf()); $theFeed = array(); foreach ($data as $stdObject) { $rPath = substr($stdObject->path, strlen($uniqNode->getPath())); if ($rPath == false && $stdObject->path == $uniqNode->getPath()) { $rPath = ""; } $rPath = ltrim($rPath, "/"); $newItem = array("date" => $stdObject->date, "hdate" => AJXP_Utils::relativeDate($stdObject->date, $mess), "author" => $stdObject->author, "content" => base64_decode($stdObject->content), "path" => $stdObject->path, "rpath" => $rPath, "uuid" => $stdObject->uuid); if (isset($previous) && $previous["author"] == $newItem["author"] && $previous["path"] == $newItem["path"] && $previous["hdate"] == $newItem["hdate"]) { $theFeed[count($theFeed) - 1]["content"] .= '<br>' . $newItem["content"]; } else { $theFeed[] = $newItem; } $previous = $newItem; } echo json_encode($theFeed); } else { foreach ($existingFeed as &$item) { $item["hdate"] = AJXP_Utils::relativeDate($item["date"], $mess); } echo json_encode($existingFeed); } break; case "delete_comment": $data = json_decode($httpVars["comment_data"], true); if ($feedStore === false) { $reFeed = array(); if ($data["author"] != AuthService::getLoggedUser()->getId()) { break; } foreach ($existingFeed as $fElement) { if ($fElement["date"] == $data["date"] && $fElement["author"] == $data["author"] && $fElement["content"] == $data["content"]) { continue; } $fElement["hdate"] = AJXP_Utils::relativeDate($fElement["date"], $mess); $reFeed[] = $fElement; } $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false); $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $reFeed, false); HTMLWriter::charsetHeader("application/json"); echo json_encode($reFeed); } else { $feedStore->dismissAlertById($data["uuid"], 1); } break; default: break; } }
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 switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $this->streamData = $streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); switch ($actionName) { case "filehasher_signature": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!file_exists($destStreamURL . $file)) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $destStreamURL . $file, 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"); } $uploadedData = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-sig"); move_uploaded_file($fileVars["userfile_0"]["tmp_name"], $uploadedData); $fileUrl = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]); $file = call_user_func(array($this->streamData["classname"], "getRealFSReference"), $fileUrl, true); if ($actionName == "filehasher_delta") { $signatureFile = $uploadedData; $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); $this->logDebug("Received signature file, should compute delta now"); rsync_generate_delta($signatureFile, $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($signatureFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; $deltaFile = $uploadedData; rsync_patch_file($file, $deltaFile, $patched); rename($patched, $file); unlink($deltaFile); header("Content-Type:text/plain"); echo md5_file($file); } break; case "stat_hash": $selection = new UserSelection(); $selection->initFromArray($httpVars); clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $node = $selection->getUniqueNode($this->accessDriver); $stat = @stat($node->getUrl()); if (!$stat) { print '{}'; } else { if ($node->isLeaf()) { $hash = $this->getFileHash($selection->getUniqueNode($this->accessDriver)); } 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($destStreamURL . $path); $stat = @stat($destStreamURL . $path); if (!$stat) { $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($path) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; break; } }
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 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; } }
/** * @param $httpVars * @param Repository $repository * @param AbstractAccessDriver $accessDriver * @return mixed An array containing the hash (0) and the generated url (1) */ public function createSharedMinisite($httpVars, $repository, $accessDriver) { $uniqueUser = null; if (isset($httpVars["repository_id"]) && isset($httpVars["guest_user_id"])) { $existingData = $this->getShareStore()->loadShare($httpVars["hash"]); $existingU = ""; if (isset($existingData["PRELOG_USER"])) { $existingU = $existingData["PRELOG_USER"]; } else { if (isset($existingData["PRESET_LOGIN"])) { $existingU = $existingData["PRESET_LOGIN"]; } } $uniqueUser = $httpVars["guest_user_id"]; if (isset($httpVars["guest_user_pass"]) && strlen($httpVars["guest_user_pass"]) && $uniqueUser == $existingU) { //$userPass = $httpVars["guest_user_pass"]; // UPDATE GUEST USER PASS HERE AuthService::updatePassword($uniqueUser, $httpVars["guest_user_pass"]); } else { if (isset($httpVars["guest_user_pass"]) && $httpVars["guest_user_pass"] == "") { } else { if (isset($existingData["PRESET_LOGIN"])) { $httpVars["KEEP_PRESET_LOGIN"] = true; } } } } else { if (isset($httpVars["create_guest_user"])) { // Create a guest user $userId = substr(md5(time()), 0, 12); $pref = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId()); if (!empty($pref)) { $userId = $pref . $userId; } if (!empty($httpVars["guest_user_pass"])) { $userPass = $httpVars["guest_user_pass"]; } else { $userPass = substr(md5(time()), 13, 24); } $uniqueUser = $userId; } } if (isset($uniqueUser)) { if (isset($userPass)) { $httpVars["user_pass_0"] = $httpVars["shared_pass"] = $userPass; } $httpVars["user_0"] = $uniqueUser; $httpVars["entry_type_0"] = "user"; $httpVars["right_read_0"] = isset($httpVars["simple_right_read"]) ? "true" : "false"; $httpVars["right_write_0"] = isset($httpVars["simple_right_write"]) ? "true" : "false"; $httpVars["right_watch_0"] = "false"; $httpVars["disable_download"] = isset($httpVars["simple_right_download"]) ? false : true; if ($httpVars["right_read_0"] == "false" && !$httpVars["disable_download"]) { $httpVars["right_read_0"] = "true"; } if ($httpVars["right_write_0"] == "false" && $httpVars["right_read_0"] == "false") { return "share_center.58"; } } $httpVars["minisite"] = true; $httpVars["selection"] = true; if (!isset($userSelection)) { $userSelection = new UserSelection($repository, $httpVars); $setFilter = false; if ($userSelection->isUnique()) { $node = $userSelection->getUniqueNode($this->accessDriver); $node->loadNodeInfo(); if ($node->isLeaf()) { $setFilter = true; $httpVars["file"] = "/"; } } else { $setFilter = true; } $nodes = $userSelection->buildNodes($this->accessDriver); $hasDir = false; $hasFile = false; foreach ($nodes as $n) { $n->loadNodeInfo(); if ($n->isLeaf()) { $hasFile = true; } else { $hasDir = true; } } if ($hasDir && !$this->getAuthorization("folder", "minisite") || $hasFile && !$this->getAuthorization("file")) { return 103; } if ($setFilter) { $httpVars["filter_nodes"] = $nodes; } if (!isset($httpVars["repo_label"])) { $first = $userSelection->getUniqueNode($this->accessDriver); $httpVars["repo_label"] = SystemTextEncoding::toUTF8($first->getLabel()); } } $newRepo = $this->createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser); if (!is_a($newRepo, "Repository")) { return $newRepo; } $newId = $newRepo->getId(); $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); $this->initPublicFolder($downloadFolder); if (isset($existingData)) { $data = $existingData; } else { $data = array("REPOSITORY" => $newId); } if (isset($data["PRELOG_USER"])) { unset($data["PRELOG_USER"]); } if (isset($data["PRESET_LOGIN"])) { unset($data["PRESET_LOGIN"]); } if (isset($httpVars["create_guest_user"]) && isset($userId) || isset($httpVars["guest_user_id"])) { if (!isset($userId)) { $userId = $httpVars["guest_user_id"]; } if (empty($httpVars["guest_user_pass"]) && !isset($httpVars["KEEP_PRESET_LOGIN"])) { $data["PRELOG_USER"] = $userId; } else { $data["PRESET_LOGIN"] = $userId; } } $data["DOWNLOAD_DISABLED"] = $httpVars["disable_download"]; $data["AJXP_APPLICATION_BASE"] = AJXP_Utils::detectServerURL(true); if (isset($httpVars["minisite_layout"])) { $data["AJXP_TEMPLATE_NAME"] = $httpVars["minisite_layout"]; } if (isset($httpVars["expiration"]) && intval($httpVars["expiration"]) > 0) { $data["EXPIRE_TIME"] = time() + intval($httpVars["expiration"]) * 86400; } if (isset($httpVars["downloadlimit"]) && intval($httpVars["downloadlimit"]) > 0) { $data["DOWNLOAD_LIMIT"] = intval($httpVars["downloadlimit"]); } if (AuthService::usersEnabled()) { $data["OWNER_ID"] = AuthService::getLoggedUser()->getId(); } if (!isset($httpVars["repository_id"])) { try { $forceHash = null; if (isset($httpVars["custom_handle"]) && !empty($httpVars["custom_handle"])) { // Existing already $value = AJXP_Utils::sanitize($httpVars["custom_handle"], AJXP_SANITIZE_ALPHANUM); $value = strtolower($value); $test = $this->getShareStore()->loadShare($value); $mess = ConfService::getMessages(); if (!empty($test)) { throw new Exception($mess["share_center.172"]); } $forceHash = $value; } $hash = $this->getShareStore()->storeShare($repository->getId(), $data, "minisite", $forceHash); } catch (Exception $e) { return $e->getMessage(); } $url = $this->buildPublicletLink($hash); $this->logInfo("New Share", array("file" => "'" . $httpVars['file'] . "'", "url" => $url, "expiration" => $data['EXPIRE_TIME'], "limit" => $data['DOWNLOAD_LIMIT'], "repo_uuid" => $repository->uuid)); AJXP_Controller::applyHook("node.share.create", array('type' => 'minisite', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url, 'new_repository' => &$newRepo)); } else { try { $hash = $httpVars["hash"]; $updateHash = null; if (isset($httpVars["custom_handle"]) && !empty($httpVars["custom_handle"]) && $httpVars["custom_handle"] != $httpVars["hash"]) { // Existing already $value = AJXP_Utils::sanitize($httpVars["custom_handle"], AJXP_SANITIZE_ALPHANUM); $value = strtolower($value); $test = $this->getShareStore()->loadShare($value); if (!empty($test)) { throw new Exception("Sorry hash already exists"); } $updateHash = $value; } $hash = $this->getShareStore()->storeShare($repository->getId(), $data, "minisite", $hash, $updateHash); } catch (Exception $e) { return $e->getMessage(); } $url = $this->buildPublicletLink($hash); $this->logInfo("Update Share", array("file" => "'" . $httpVars['file'] . "'", "url" => $url, "expiration" => $data['EXPIRE_TIME'], "limit" => $data['DOWNLOAD_LIMIT'], "repo_uuid" => $repository->uuid)); AJXP_Controller::applyHook("node.share.update", array('type' => 'minisite', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url, 'new_repository' => &$newRepo)); } return array($hash, $url); }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $node = $selection->getUniqueNode(); if ($action == "read_video_data") { if (!file_exists($node->getUrl()) || !is_readable($node->getUrl())) { throw new Exception("Cannot find file!"); } $this->logDebug("Reading video"); session_write_close(); $filesize = filesize($node->getUrl()); $filename = $node->getUrl(); $basename = AJXP_Utils::safeBasename($filename); //$fp = fopen($destStreamURL.$file, "r"); if (preg_match("/\\.ogv\$/", $basename)) { header("Content-Type: video/ogg; name=\"" . $basename . "\""); } else { if (preg_match("/\\.mp4\$/", $basename)) { header("Content-Type: video/mp4; name=\"" . $basename . "\""); } else { if (preg_match("/\\.m4v\$/", $basename)) { header("Content-Type: video/x-m4v; name=\"" . $basename . "\""); } else { if (preg_match("/\\.webm\$/", $basename)) { header("Content-Type: video/webm; name=\"" . $basename . "\""); } } } } if (isset($_SERVER['HTTP_RANGE']) && $filesize != 0) { $this->logDebug("Http range", array($_SERVER['HTTP_RANGE'])); // multiple ranges, which can become pretty complex, so ignore it for now $ranges = explode('=', $_SERVER['HTTP_RANGE']); $offsets = explode('-', $ranges[1]); $offset = floatval($offsets[0]); if ($offset == 0) { $this->logInfo('Preview', 'Streaming content of ' . $filename, array("files" => $filename)); } $length = floatval($offsets[1]) - $offset + 1; if (!$length) { $length = $filesize - $offset; } if ($length + $offset > $filesize || $length < 0) { $length = $filesize - $offset; } header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length - 1) . '/' . $filesize); header('Accept-Ranges:bytes'); header("Content-Length: " . $length); $file = fopen($filename, 'rb'); if (!is_resource($file)) { throw new Exception("Cannot open file {$file}!"); } fseek($file, 0); $relOffset = $offset; while ($relOffset > 2000000000.0) { // seek to the requested offset, this is 0 if it's not a partial content request fseek($file, 2000000000, SEEK_CUR); $relOffset -= 2000000000; // This works because we never overcome the PHP 32 bit limit } fseek($file, $relOffset, SEEK_CUR); while (ob_get_level()) { ob_end_flush(); } $readSize = 0.0; while (!feof($file) && $readSize < $length && connection_status() == 0) { if ($length < 2048) { echo fread($file, $length); } else { echo fread($file, 2048); } $readSize += 2048.0; flush(); } fclose($file); } else { $this->logInfo('Preview', 'Streaming content of ' . $filename, array("files" => $filename)); header("Content-Length: " . $filesize); header("Content-Range: bytes 0-" . ($filesize - 1) . "/" . $filesize . ";"); header('Cache-Control: public'); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($node->getUrl(), $stream); fflush($stream); fclose($stream); } AJXP_Controller::applyHook("node.read", array($node)); } else { if ($action == "get_sess_id") { HTMLWriter::charsetHeader("text/plain"); print session_id(); } } }
public function switchAction($actionName, $httpVars, $fileVars) { $this->baseURL = rtrim($this->getFilteredOption("ETHERPAD_SERVER"), "/"); $this->apiKey = $this->getFilteredOption("ETHERPAD_APIKEY"); $userSelection = new UserSelection(ConfService::getRepository(), $httpVars); if ($userSelection->isEmpty()) { throw new Exception("Empty selection"); } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } $selectedNode = $userSelection->getUniqueNode(); $selectedNode->loadNodeInfo(); if (!$selectedNode->isLeaf()) { throw new Exception("Cannot handle folders, please select a file!"); } $nodeExtension = strtolower(pathinfo($selectedNode->getPath(), PATHINFO_EXTENSION)); // Determine pad ID if ($nodeExtension == "pad") { $padID = file_get_contents($selectedNode->getUrl()); } else { // TRY TO LOAD PAD ID FROM NODE SHARED METADATA $metadata = $selectedNode->retrieveMetadata("etherpad", AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false); if (isset($metadata["pad_id"])) { $padID = $metadata["pad_id"]; } else { $padID = AJXP_Utils::generateRandomString(); $selectedNode->setMetadata("etherpad", array("pad_id" => $padID), AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false); } } require_once "etherpad-client/etherpad-lite-client.php"; $client = new EtherpadLiteClient($this->apiKey, $this->baseURL . "/api"); $loggedUser = AuthService::getLoggedUser(); $userName = $loggedUser->getId(); $userLabel = $loggedUser->mergedRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userName); $res = $client->createAuthorIfNotExistsFor($userName, $userLabel); $authorID = $res->authorID; $res2 = $client->createGroupIfNotExistsFor($loggedUser->getGroupPath()); $groupID = $res2->groupID; $fullId = $groupID . "\$" . $padID; if ($actionName == "etherpad_create") { $resP = $client->listPads($groupID); $currentContent = file_get_contents($selectedNode->getUrl()); if ($nodeExtension == "html" && strpos($currentContent, "<html>") === false) { $currentContent = "<html><head></head><body>{$currentContent}</body></html>"; } if (!in_array($fullId, $resP->padIDs)) { $client->createGroupPad($groupID, $padID, null); if ($nodeExtension == "html" && !empty($currentContent)) { $client->setHTML($fullId, $currentContent); } else { if ($nodeExtension != "pad") { $client->setText($fullId, $currentContent); } } } else { if ($nodeExtension != "pad") { // If someone is already connected, do not override. $existingAuthors = $client->listAuthorsOfPad($fullId); if (!count($existingAuthors->authorIDs)) { if ($nodeExtension == "html" && !empty($currentContent)) { $client->setHTML($fullId, $currentContent); } else { $client->setText($fullId, $currentContent); } } } } $res4 = $client->createSession($groupID, $authorID, time() + 14400); $sessionID = $res4->sessionID; setcookie('sessionID', $sessionID, null, "/"); $padID = $groupID . '$' . $padID; $data = array("url" => $this->baseURL . "/p/" . $padID, "padID" => $padID, "sessionID" => $sessionID); HTMLWriter::charsetHeader('application/json'); echo json_encode($data); } else { if ($actionName == "etherpad_save") { $padID = $httpVars["pad_id"]; if ($nodeExtension == "html" || $nodeExtension == "pad") { $res = $client->getHTML($padID); $content = $res->html; } else { $res = $client->getText($padID); $content = $res->text; } if ($nodeExtension == "pad") { // Create a new file and save the content in it. $origUrl = $selectedNode->getUrl(); $mess = ConfService::getMessages(); $dateStamp = date(" Y-m-d H:i", time()); $startUrl = preg_replace('"\\.pad$"', $dateStamp . '.html', $origUrl); $newNode = new AJXP_Node($startUrl); AJXP_Controller::applyHook("node.before_create", array($newNode, strlen($content))); file_put_contents($newNode->getUrl(), $content); AJXP_Controller::applyHook("node.change", array(null, $newNode)); } else { AJXP_Controller::applyHook("node.before_change", array($selectedNode, strlen($content))); file_put_contents($selectedNode->getUrl(), $content); clearstatcache(true, $selectedNode->getUrl()); $selectedNode->loadNodeInfo(true); AJXP_Controller::applyHook("node.change", array($selectedNode, $selectedNode)); } } else { if ($actionName == "etherpad_close") { // WE SHOULD DETECT IF THERE IS NOBODY CONNECTED ANYMORE, AND DELETE THE PAD. // BUT SEEMS LIKE THERE'S NO WAY TO PROPERLY REMOVE AN AUTHOR VIA API $sessionID = $httpVars["session_id"]; $client->deleteSession($sessionID); } else { if ($actionName == "etherpad_proxy_api") { if ($httpVars["api_action"] == "list_pads") { $res = $client->listPads($groupID); } else { if ($httpVars["api_action"] == "list_authors_for_pad") { $res = $client->listAuthorsOfPad($httpVars["pad_id"]); } } HTMLWriter::charsetHeader("application/json"); echo json_encode($res); } else { if ($actionName == "etherpad_get_content") { HTMLWriter::charsetHeader("text/plain"); echo $client->getText($httpVars["pad_id"])->text; } } } } } return null; }
/** * @param AJXP_Node $ajxpNode * @param array $httpVars * @param bool $update * @return Repository[]|ShareLink[] * @throws Exception */ public function shareNode($ajxpNode, $httpVars, &$update) { $hiddenUserEntries = array(); $originalHttpVars = $httpVars; $ocsStore = new Pydio\OCS\Model\SQLStore(); $ocsClient = new Pydio\OCS\Client\OCSClient(); $userSelection = new UserSelection($this->repository, $httpVars); $mess = ConfService::getMessages(); /** * @var ShareLink[] $shareObjects */ $shareObjects = array(); // PUBLIC LINK if (isset($httpVars["enable_public_link"])) { if (!$this->getAuthorization($ajxpNode->isLeaf() ? "file" : "folder", "minisite")) { throw new Exception($mess["share_center." . ($ajxpNode->isLeaf() ? "225" : "226")]); } $this->shareObjectFromParameters($httpVars, $hiddenUserEntries, $shareObjects, "public"); } else { if (isset($httpVars["disable_public_link"])) { $this->getShareStore()->deleteShare("minisite", $httpVars["disable_public_link"], true); } } if (isset($httpVars["ocs_data"])) { $ocsData = json_decode($httpVars["ocs_data"], true); $removeLinks = $ocsData["REMOVE"]; foreach ($removeLinks as $linkHash) { // Delete Link, delete invitation(s) $this->getShareStore()->deleteShare("minisite", $linkHash, true); $invitations = $ocsStore->invitationsForLink($linkHash); foreach ($invitations as $invitation) { $ocsStore->deleteInvitation($invitation); $ocsClient->cancelInvitation($invitation); } } $newLinks = $ocsData["LINKS"]; foreach ($newLinks as $linkData) { $this->shareObjectFromParameters($linkData, $hiddenUserEntries, $shareObjects, "targetted", $userSelection->getUniqueNode()->getLabel()); } } $this->filterHttpVarsFromUniqueNode($httpVars, $ajxpNode); $users = array(); $groups = array(); $this->getRightsManager()->createUsersFromParameters($httpVars, $users, $groups); if ((count($users) || count($groups)) && !$this->getAuthorization($ajxpNode->isLeaf() ? "file" : "folder", "workspace")) { $users = $groups = array(); } foreach ($hiddenUserEntries as $entry) { $users[$entry["ID"]] = $entry; } if (!count($users) && !count($groups)) { ob_start(); unset($originalHttpVars["hash"]); $this->switchAction("unshare", $originalHttpVars, array()); ob_end_clean(); return null; } $newRepo = $this->createSharedRepository($httpVars, $repoUpdate, $users, $groups); foreach ($shareObjects as $shareObject) { $shareObject->setParentRepositoryId($this->repository->getId()); $shareObject->attachToRepository($newRepo->getId()); $shareObject->save(); if ($shareObject instanceof \Pydio\OCS\Model\TargettedLink) { $invitation = $shareObject->getPendingInvitation(); if (!empty($invitation)) { $ocsStore->generateInvitationId($invitation); try { $ocsClient->sendInvitation($invitation); } catch (Exception $e) { $this->getShareStore()->deleteShare("minisite", $shareObject->getHash(), true); $shareUserId = $shareObject->getUniqueUser(); unset($users[$shareUserId]); if (!count($users) && !count($groups)) { $this->getShareStore()->deleteShare("repository", $newRepo->getId()); } throw $e; } $ocsStore->storeInvitation($invitation); } } else { $this->getPublicAccessManager()->initFolder(); $url = $this->getPublicAccessManager()->buildPublicLink($shareObject->getHash()); $existingShortForm = $shareObject->getShortFormUrl(); if (empty($existingShortForm)) { $shortForm = ""; AJXP_Controller::applyHook("url.shorten", array($url, &$shortForm)); if (!empty($shortForm)) { $shareObject->setShortFormUrl($shortForm); $shareObject->save(); } } } } $shareObjects[] = $newRepo; return $shareObjects; }
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 Repository $parentRepository * @param Repository $childRepository * @param bool $isUpdate * @param array $users * @param array $groups * @param UserSelection $selection * @param bool|false $disableDownload * @throws Exception */ public function assignSharedRepositoryPermissions($parentRepository, $childRepository, $isUpdate, $users, $groups, $selection) { $childRepoId = $childRepository->getId(); if ($isUpdate) { $this->unregisterRemovedUsers($childRepoId, $users, $groups, $selection->getUniqueNode()); } $confDriver = ConfService::getConfStorageImpl(); $loggedUser = AuthService::getLoggedUser(); foreach ($users as $userName => $userEntry) { if (AuthService::userExists($userName, "r")) { $userObject = $confDriver->createUserObject($userName); if (isset($userEntry["HIDDEN"]) && isset($userEntry["UPDATE_PASSWORD"])) { AuthService::updatePassword($userName, $userEntry["UPDATE_PASSWORD"]); } } else { $mess = ConfService::getMessages(); $hiddenUserLabel = "[" . $mess["share_center.109"] . "] " . AJXP_Utils::sanitize($childRepository->getDisplay(), AJXP_SANITIZE_EMAILCHARS); $userObject = $this->createNewUser($loggedUser, $userName, $userEntry["PASSWORD"], isset($userEntry["HIDDEN"]), $hiddenUserLabel); } // ASSIGN NEW REPO RIGHTS $userObject->personalRole->setAcl($childRepoId, $userEntry["RIGHT"]); // FORK MASK IF THERE IS ANY $childMask = $this->forkMaskIfAny($loggedUser, $parentRepository->getId(), $selection->getUniqueNode()); if ($childMask != null) { $userObject->personalRole->setMask($childRepoId, $childMask); } // CREATE A MINISITE-LIKE ROLE FOR THIS REPOSITORY if (isset($userEntry["HIDDEN"]) && !isset($userEntry["REMOTE"])) { $minisiteRole = $this->createRoleForMinisite($childRepoId, $userEntry["DISABLE_DOWNLOAD"], $isUpdate); if ($minisiteRole != null) { $userObject->addRole($minisiteRole); } } // ADD "my shared files" REPO OTHERWISE SOME USER CANNOT ACCESS if (!isset($userEntry["HIDDEN"]) && $childRepository->hasContentFilter()) { $inboxRepo = ConfService::getRepositoryById("inbox"); $currentAcl = $userObject->mergedRole->getAcl("inbox"); if ($inboxRepo !== null && empty($currentAcl)) { $userObject->personalRole->setAcl("inbox", "rw"); } } $userObject->save("superuser"); } foreach ($groups as $group => $groupEntry) { $r = $groupEntry["RIGHT"]; $grRole = AuthService::getRole($group, true); $grRole->setAcl($childRepoId, $r); AuthService::updateRole($grRole); } }