/** * Filter the very basic keywords from the XML : AJXP_USER, AJXP_INSTALL_PATH, AJXP_DATA_PATH * Calls the vars.filter hooks. * @static * @param $value * @return mixed|string */ public static function filter($value) { if (is_string($value) && strpos($value, "AJXP_USER") !== false) { if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { $loggedUser = $loggedUser->getId(); $value = str_replace("AJXP_USER", $loggedUser, $value); } else { return ""; } } else { $value = str_replace("AJXP_USER", "shared", $value); } } if (is_string($value) && strpos($value, "AJXP_INSTALL_PATH") !== false) { $value = str_replace("AJXP_INSTALL_PATH", AJXP_INSTALL_PATH, $value); } if (is_string($value) && strpos($value, "AJXP_DATA_PATH") !== false) { $value = str_replace("AJXP_DATA_PATH", AJXP_DATA_PATH, $value); } $tab = array(&$value); AJXP_Controller::applyIncludeHook("vars.filter", $tab); return $value; }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } if (!isset($this->pluginConf)) { $this->pluginConf = array("GENERATE_THUMBNAIL" => false); } $streamData = $repository->streamData; $this->streamData = $streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); if ($action == "preview_data_proxy") { $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!file_exists($destStreamURL . $file)) { header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\""); header("Content-Length: 0"); return; } if (isset($httpVars["get_thumb"]) && $this->getFilteredOption("GENERATE_THUMBNAIL", $repository->getId())) { $dimension = 200; if (isset($httpVars["dimension"]) && is_numeric($httpVars["dimension"])) { $dimension = $httpVars["dimension"]; } $this->currentDimension = $dimension; $cacheItem = AJXP_Cache::getItem("diaporama_" . $dimension, $destStreamURL . $file, array($this, "generateThumbnail")); $data = $cacheItem->getData(); $cId = $cacheItem->getId(); header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($cId)) . "; name=\"" . basename($cId) . "\""); header("Content-Length: " . strlen($data)); header('Cache-Control: public'); header("Pragma:"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); print $data; } else { //$filesize = filesize($destStreamURL.$file); $node = new AJXP_Node($destStreamURL . $file); $fp = fopen($destStreamURL . $file, "r"); $stat = fstat($fp); $filesize = $stat["size"]; header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\""); header("Content-Length: " . $filesize); header('Cache-Control: public'); header("Pragma:"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); $class = $streamData["classname"]; $stream = fopen("php://output", "a"); call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($node)); } } }
public function switchAction($action, $httpVars, $postProcessData) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . "/"; if ($action == "audio_proxy") { $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); $cType = "audio/" . array_pop(explode(".", $file)); $localName = basename($file); header("Content-Type: " . $cType . "; name=\"" . $localName . "\""); header("Content-Length: " . filesize($destStreamURL . $file)); $stream = fopen("php://output", "a"); call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream); fflush($stream); fclose($stream); $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); //exit(1); } else { if ($action == "ls") { if (!isset($httpVars["playlist"])) { // This should not happen anyway, because of the applyCondition. AJXP_Controller::passProcessDataThrough($postProcessData); return; } // We transform the XML into XSPF $xmlString = $postProcessData["ob_output"]; $xmlDoc = new DOMDocument(); $xmlDoc->loadXML($xmlString); $xElement = $xmlDoc->documentElement; header("Content-Type:application/xspf+xml;charset=UTF-8"); print '<?xml version="1.0" encoding="UTF-8"?>'; print '<playlist version="1" xmlns="http://xspf.org/ns/0/">'; print "<trackList>"; foreach ($xElement->childNodes as $child) { $isFile = $child->getAttribute("is_file") == "true"; $label = $child->getAttribute("text"); $ar = explode(".", $label); $ext = strtolower(end($ar)); if (!$isFile || $ext != "mp3") { continue; } print "<track><location>" . AJXP_SERVER_ACCESS . "?secure_token=" . AuthService::getSecureToken() . "&get_action=audio_proxy&file=" . base64_encode($child->getAttribute("filename")) . "</location><title>" . $label . "</title></track>"; } print "</trackList>"; AJXP_XMLWriter::close("playlist"); } } }
public function processUserAccessPoint($action, $httpVars, $fileVars) { switch ($action) { case "user_access_point": $uri = explode("/", trim($_SERVER["REQUEST_URI"], "/")); array_shift($uri); $action = array_shift($uri); $this->processSubAction($action, $uri); $_SESSION['OVERRIDE_GUI_START_PARAMETERS'] = array("REBASE" => "../../", "USER_GUI_ACTION" => $action); AJXP_Controller::findActionAndApply("get_boot_gui", array(), array()); unset($_SESSION['OVERRIDE_GUI_START_PARAMETERS']); break; case "reset-password-ask": // This is a reset password request, generate a token and store it. // Find user by id if (AuthService::userExists($httpVars["email"])) { // Send email $userObject = ConfService::getConfStorageImpl()->createUserObject($httpVars["email"]); $email = $userObject->personalRole->filterParameterValue("core.conf", "email", AJXP_REPO_SCOPE_ALL, ""); if (!empty($email)) { $uuid = AJXP_Utils::generateRandomString(48); ConfService::getConfStorageImpl()->saveTemporaryKey("password-reset", $uuid, AJXP_Utils::decodeSecureMagic($httpVars["email"]), array()); $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer"); if ($mailer !== false) { $mess = ConfService::getMessages(); $link = AJXP_Utils::detectServerURL() . "/user/reset-password/" . $uuid; $mailer->sendMail(array($email), $mess["gui.user.1"], $mess["gui.user.7"] . "<a href=\"{$link}\">{$link}</a>"); } else { echo 'ERROR: There is no mailer configured, please contact your administrator'; } } } // Prune existing expired tokens ConfService::getConfStorageImpl()->pruneTemporaryKeys("password-reset", 20); echo "SUCCESS"; break; case "reset-password": ConfService::getConfStorageImpl()->pruneTemporaryKeys("password-reset", 20); // This is a reset password if (isset($httpVars["key"]) && isset($httpVars["user_id"])) { $key = ConfService::getConfStorageImpl()->loadTemporaryKey("password-reset", $httpVars["key"]); if ($key != null && $key["user_id"] == $httpVars["user_id"] && AuthService::userExists($key["user_id"])) { AuthService::updatePassword($key["user_id"], $httpVars["new_pass"]); } ConfService::getConfStorageImpl()->deleteTemporaryKey("password-reset", $httpVars["key"]); } AuthService::disconnect(); echo 'SUCCESS'; break; default: break; } }
public function switchAction($actionName, $httpVars, $fileVars) { if ($actionName == "search-cart-download") { // Pipe SEARCH + DOWNLOAD actions. $indexer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("index"); if ($indexer == false) { return; } $httpVars["return_selection"] = true; unset($httpVars["get_action"]); $res = AJXP_Controller::findActionAndApply("search", $httpVars, $fileVars); if (isset($res) && is_array($res)) { $newHttpVars = array("selection_nodes" => $res, "dir" => "__AJXP_ZIP_FLAT__/", "archive_name" => $httpVars["archive_name"]); AJXP_Controller::findActionAndApply("download", $newHttpVars, array()); } } }
/** * Filter the very basic keywords from the XML : AJXP_USER, AJXP_INSTALL_PATH, AJXP_DATA_PATH * Calls the vars.filter hooks. * @static * @param $value * @return mixed|string */ public static function filter($value) { if (is_string($value) && strpos($value, "AJXP_USER") !== false) { if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { if ($loggedUser->hasParent() && $loggedUser->getResolveAsParent()) { $loggedUserId = $loggedUser->getParent(); } else { $loggedUserId = $loggedUser->getId(); } $value = str_replace("AJXP_USER", $loggedUserId, $value); } else { return ""; } } else { $value = str_replace("AJXP_USER", "shared", $value); } } if (is_string($value) && strpos($value, "AJXP_GROUP_PATH") !== false) { if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { $gPath = $loggedUser->getGroupPath(); $value = str_replace("AJXP_GROUP_PATH_FLAT", str_replace("/", "_", trim($gPath, "/")), $value); $value = str_replace("AJXP_GROUP_PATH", $gPath, $value); } else { return ""; } } else { $value = str_replace(array("AJXP_GROUP_PATH", "AJXP_GROUP_PATH_FLAT"), "shared", $value); } } if (is_string($value) && strpos($value, "AJXP_INSTALL_PATH") !== false) { $value = str_replace("AJXP_INSTALL_PATH", AJXP_INSTALL_PATH, $value); } if (is_string($value) && strpos($value, "AJXP_DATA_PATH") !== false) { $value = str_replace("AJXP_DATA_PATH", AJXP_DATA_PATH, $value); } $tab = array(&$value); AJXP_Controller::applyIncludeHook("vars.filter", $tab); return $value; }
public static function getNodeData($nodePath) { $basename = basename(parse_url($nodePath, PHP_URL_PATH)); if (empty($basename)) { return ['stat' => stat(AJXP_Utils::getAjxpTmpDir())]; } $allNodes = self::getNodes(false); $nodeData = $allNodes[$basename]; if (!isset($nodeData["stat"])) { if (in_array(pathinfo($basename, PATHINFO_EXTENSION), array("error", "invitation"))) { $stat = stat(AJXP_Utils::getAjxpTmpDir()); } else { $url = $nodeData["url"]; $node = new AJXP_Node($nodeData["url"]); $node->getRepository()->driverInstance = null; try { ConfService::loadDriverForRepository($node->getRepository()); $node->getRepository()->detectStreamWrapper(true); if ($node->getRepository()->hasContentFilter()) { $node->setLeaf(true); } AJXP_Controller::applyHook("node.read", array(&$node)); $stat = stat($url); } catch (Exception $e) { $stat = stat(AJXP_Utils::getAjxpTmpDir()); } if (is_array($stat) && AuthService::getLoggedUser() != null) { $acl = AuthService::getLoggedUser()->mergedRole->getAcl($nodeData["meta"]["shared_repository_id"]); if ($acl == "r") { self::disableWriteInStat($stat); } } self::$output[$basename]["stat"] = $stat; } $nodeData["stat"] = $stat; } return $nodeData; }
public function postProcess($action, $httpVars, $postProcessData) { if (!self::$active) { return false; } $this->logDebug("FlexProc is active=" . self::$active, $postProcessData); $result = $postProcessData["processor_result"]; if (isset($result["SUCCESS"]) && $result["SUCCESS"] === true) { header('HTTP/1.0 200 OK'); if (isset($result["UPDATED_NODE"])) { AJXP_Controller::applyHook("node.change", array($result["UPDATED_NODE"], $result["UPDATED_NODE"], false)); } else { AJXP_Controller::applyHook("node.change", array(null, $result["CREATED_NODE"], false)); } //die("200 OK"); } else { if (isset($result["ERROR"]) && is_array($result["ERROR"])) { $code = $result["ERROR"]["CODE"]; $message = $result["ERROR"]["MESSAGE"]; //header("HTTP/1.0 $code $message"); die("Error {$code} {$message}"); } } }
/** Cypher the publiclet object data and write to disk. * @param array $data The publiclet data array to write * The data array must have the following keys: * - DRIVER The driver used to get the file's content * - OPTIONS The driver options to be successfully constructed (usually, the user and password) * - FILE_PATH The path to the file's content * - PASSWORD If set, the written publiclet will ask for this password before sending the content * - ACTION If set, action to perform * - USER If set, the AJXP user * - EXPIRE_TIME If set, the publiclet will deny downloading after this time, and probably self destruct. * - AUTHOR_WATCH If set, will post notifications for the publiclet author each time the file is loaded * @param AbstractAccessDriver $accessDriver * @param Repository $repository * @param ShareStore $shareStore * @param PublicAccessManager $publicAccessManager * @return string|array An array containing the hash (0) and the generated url (1) */ public function writePubliclet(&$data, $accessDriver, $repository, $shareStore, $publicAccessManager) { $downloadFolder = $publicAccessManager->getPublicDownloadFolder(); $publicAccessManager->initFolder(); if (!is_dir($downloadFolder)) { return "ERROR : Public URL folder does not exist!"; } if (!function_exists("mcrypt_create_iv")) { return "ERROR : MCrypt must be installed to use publiclets!"; } $data["PLUGIN_ID"] = $accessDriver->getId(); $data["BASE_DIR"] = $accessDriver->getBaseDir(); //$data["REPOSITORY"] = $repository; if (AuthService::usersEnabled()) { $data["OWNER_ID"] = AuthService::getLoggedUser()->getId(); } $shareStore->storeSafeCredentialsIfNeeded($data, $accessDriver, $repository); // Force expanded path in publiclet $copy = clone $repository; $copy->addOption("PATH", $repository->getOption("PATH")); $data["REPOSITORY"] = $copy; if ($data["ACTION"] == "") { $data["ACTION"] = "download"; } try { $hash = $shareStore->storeShare($repository->getId(), $data, "publiclet"); } catch (Exception $e) { return $e->getMessage(); } $shareStore->resetDownloadCounter($hash, AuthService::getLoggedUser()->getId()); $url = $publicAccessManager->buildPublicLink($hash); AJXP_Logger::log2(LOG_LEVEL_INFO, __CLASS__, "New Share", array("file" => "'" . $copy->display . ":/" . $data['FILE_PATH'] . "'", "files" => "'" . $copy->display . ":/" . $data['FILE_PATH'] . "'", "url" => $url, "expiration" => $data['EXPIRE_TIME'], "limit" => $data['DOWNLOAD_LIMIT'], "repo_uuid" => $copy->uuid)); AJXP_Controller::applyHook("node.share.create", array('type' => 'file', 'repository' => &$copy, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url)); return array($hash, $url); }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $convert = $this->getFilteredOption("IMAGE_MAGICK_CONVERT"); if (empty($convert)) { return false; } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); $flyThreshold = 1024 * 1024 * intval($this->getFilteredOption("ONTHEFLY_THRESHOLD", $repository->getId())); $selection = new UserSelection($repository); $selection->initFromHttpVars($httpVars); if ($action == "imagick_data_proxy") { $this->extractAll = false; if (isset($httpVars["all"])) { $this->extractAll = true; } $file = $selection->getUniqueFile(); if (($size = filesize($destStreamURL . $file)) === false) { return false; } else { if ($size > $flyThreshold) { $this->useOnTheFly = true; } else { $this->useOnTheFly = false; } } if ($this->extractAll) { $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); } $cache = AJXP_Cache::getItem("imagick_" . ($this->extractAll ? "full" : "thumb"), $destStreamURL . $file, array($this, "generateJpegsCallback")); $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($destStreamURL . $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($destStreamURL . $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"]); } */ } } } }
/** * Dynamically replace XML keywords with their live values. * AJXP_SERVER_ACCESS, AJXP_MIMES_*,AJXP_ALL_MESSAGES, etc. * @static * @param string $xml * @param bool $stripSpaces * @return mixed */ public static function replaceAjxpXmlKeywords($xml, $stripSpaces = false) { $messages = ConfService::getMessages(); $confMessages = ConfService::getMessagesConf(); $matches = array(); if (isset($_SESSION["AJXP_SERVER_PREFIX_URI"])) { //$xml = str_replace("AJXP_THEME_FOLDER", $_SESSION["AJXP_SERVER_PREFIX_URI"].AJXP_THEME_FOLDER, $xml); $xml = str_replace("AJXP_SERVER_ACCESS", $_SESSION["AJXP_SERVER_PREFIX_URI"] . AJXP_SERVER_ACCESS, $xml); } else { //$xml = str_replace("AJXP_THEME_FOLDER", AJXP_THEME_FOLDER, $xml); $xml = str_replace("AJXP_SERVER_ACCESS", AJXP_SERVER_ACCESS, $xml); } $xml = str_replace("AJXP_APPLICATION_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $xml); $xml = str_replace("AJXP_MIMES_EDITABLE", AJXP_Utils::getAjxpMimes("editable"), $xml); $xml = str_replace("AJXP_MIMES_IMAGE", AJXP_Utils::getAjxpMimes("image"), $xml); $xml = str_replace("AJXP_MIMES_AUDIO", AJXP_Utils::getAjxpMimes("audio"), $xml); $xml = str_replace("AJXP_MIMES_ZIP", AJXP_Utils::getAjxpMimes("zip"), $xml); $authDriver = ConfService::getAuthDriverImpl(); if ($authDriver != NULL) { $loginRedirect = $authDriver->getLoginRedirect(); $xml = str_replace("AJXP_LOGIN_REDIRECT", $loginRedirect !== false ? "'" . $loginRedirect . "'" : "false", $xml); } $xml = str_replace("AJXP_REMOTE_AUTH", "false", $xml); $xml = str_replace("AJXP_NOT_REMOTE_AUTH", "true", $xml); $xml = str_replace("AJXP_ALL_MESSAGES", "MessageHash=" . json_encode(ConfService::getMessages()) . ";", $xml); if (preg_match_all("/AJXP_MESSAGE(\\[.*?\\])/", $xml, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $messId = str_replace("]", "", str_replace("[", "", $match[1])); $xml = str_replace("AJXP_MESSAGE[{$messId}]", $messages[$messId], $xml); } } if (preg_match_all("/CONF_MESSAGE(\\[.*?\\])/", $xml, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $messId = str_replace(array("[", "]"), "", $match[1]); $message = $messId; if (array_key_exists($messId, $confMessages)) { $message = $confMessages[$messId]; } $xml = str_replace("CONF_MESSAGE[{$messId}]", AJXP_Utils::xmlEntities($message), $xml); } } if (preg_match_all("/MIXIN_MESSAGE(\\[.*?\\])/", $xml, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $messId = str_replace(array("[", "]"), "", $match[1]); $message = $messId; if (array_key_exists($messId, $confMessages)) { $message = $confMessages[$messId]; } $xml = str_replace("MIXIN_MESSAGE[{$messId}]", AJXP_Utils::xmlEntities($message), $xml); } } if ($stripSpaces) { $xml = preg_replace("/[\n\r]?/", "", $xml); $xml = preg_replace("/\t/", " ", $xml); } $xml = str_replace(array('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', 'xsi:noNamespaceSchemaLocation="file:../core.ajaxplorer/ajxp_registry.xsd"'), "", $xml); $tab = array(&$xml); AJXP_Controller::applyIncludeHook("xml.filter", $tab); return $xml; }
public function recomputeQuotaUsage($oldNode = null, $newNode = null, $copy = false) { $repoOptions = $this->getWorkingRepositoryOptions(); $q = $this->accessDriver->directoryUsage("", $repoOptions); $this->storeUsage($q); $t = $this->getAuthorized(); AJXP_Controller::applyHook("msg.instant", array("<metaquota usage='{$q}' total='{$t}'/>", $this->accessDriver->repository->getId())); }
public function unifyChunks($action, $httpVars, $fileVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/"; $filename = AJXP_Utils::decodeSecureMagic($httpVars["file_name"]); $chunks = array(); $index = 0; while (isset($httpVars["chunk_" . $index])) { $chunks[] = AJXP_Utils::decodeSecureMagic($httpVars["chunk_" . $index]); $index++; } $newDest = fopen($destStreamURL . $filename, "w"); for ($i = 0; $i < count($chunks); $i++) { $part = fopen($destStreamURL . $chunks[$i], "r"); while (!feof($part)) { fwrite($newDest, fread($part, 4096)); } fclose($part); unlink($destStreamURL . $chunks[$i]); } fclose($newDest); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($newDest), false)); }
/** * We have to override the standard copyOrMoveFile, as feof() does * not seem to work with ssh2.ftp stream... * Maybe something to search hear http://www.mail-archive.com/php-general@lists.php.net/msg169992.html? * * @param string $destDir * @param string $srcFile * @param array $error * @param array $success * @param boolean $move */ function copyOrMoveFile($destDir, $srcFile, &$error, &$success, $move = false) { $mess = ConfService::getMessages(); $destFile = $this->urlBase . $destDir . "/" . basename($srcFile); $realSrcFile = $this->urlBase . $srcFile; if (!file_exists($realSrcFile)) { $error[] = $mess[100] . $srcFile; return; } if (dirname($realSrcFile) == dirname($destFile)) { if ($move) { $error[] = $mess[101]; return; } else { $base = basename($srcFile); $i = 1; if (is_file($realSrcFile)) { $dotPos = strrpos($base, "."); if ($dotPos > -1) { $radic = substr($base, 0, $dotPos); $ext = substr($base, $dotPos); } } // auto rename file $i = 1; $newName = $base; while (file_exists($this->urlBase . $destDir . "/" . $newName)) { $suffix = "-{$i}"; if (isset($radic)) { $newName = $radic . $suffix . $ext; } else { $newName = $base . $suffix; } $i++; } $destFile = $this->urlBase . $destDir . "/" . $newName; } } if (!is_file($realSrcFile)) { $errors = array(); $succFiles = array(); if ($move) { if (file_exists($destFile)) { $this->deldir($destFile); } $res = rename($realSrcFile, $destFile); } else { $dirRes = $this->dircopy($realSrcFile, $destFile, $errors, $succFiles); } if (count($errors) || isset($res) && $res !== true) { $error[] = $mess[114]; return; } } else { if ($move) { if (file_exists($destFile)) { unlink($destFile); } $res = rename($realSrcFile, $destFile); AJXP_Controller::applyHook("move.metadata", array($realSrcFile, $destFile, false)); } else { try { // BEGIN OVERRIDING list($connection, $remote_base_path) = sftpAccessWrapper::getSshConnection($realSrcFile); $remoteSrc = $remote_base_path . $srcFile; $remoteDest = $remote_base_path . $destDir; AJXP_Logger::debug("SSH2 CP", array("cmd" => 'cp ' . $remoteSrc . ' ' . $remoteDest)); ssh2_exec($connection, 'cp ' . $remoteSrc . ' ' . $remoteDest); AJXP_Controller::applyHook("move.metadata", array($realSrcFile, $destFile, true)); // END OVERRIDING } catch (Exception $e) { $error[] = $e->getMessage(); return; } } } if ($move) { // Now delete original // $this->deldir($realSrcFile); // both file and dir $messagePart = $mess[74] . " " . SystemTextEncoding::toUTF8($destDir); if (RecycleBinManager::recycleEnabled() && $destDir == RecycleBinManager::getRelativeRecycle()) { RecycleBinManager::fileToRecycle($srcFile); $messagePart = $mess[123] . " " . $mess[122]; } if (isset($dirRes)) { $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ") "; } else { $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart; } } else { if (RecycleBinManager::recycleEnabled() && $destDir == "/" . $this->repository->getOption("RECYCLE_BIN")) { RecycleBinManager::fileToRecycle($srcFile); } if (isset($dirRes)) { $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir) . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ")"; } else { $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir); } } }
//echo("NEXT REPO ".$nextRepositories." (".$options["r"].")\n"); //echo("NEXT USERS ".$nextUsers." ( ".$originalOptUser." )\n"); if (!empty($nextUsers) || !empty($nextRepositories) || !empty($optUserQueue)) { if (!empty($nextUsers)) { sleep(1); $process = AJXP_Controller::applyActionInBackground($options["r"], $optAction, $optArgs, $nextUsers, $optStatusFile); if ($process != null && is_a($process, "UnixProcess") && isset($optStatusFile)) { file_put_contents($optStatusFile, "RUNNING:" . $process->getPid()); } } if (!empty($optUserQueue)) { sleep(1); //echo("Should go to next with $optUserQueue"); $process = AJXP_Controller::applyActionInBackground($options["r"], $optAction, $optArgs, "queue:" . $optUserQueue, $optStatusFile); if ($process != null && is_a($process, "UnixProcess") && isset($optStatusFile)) { file_put_contents($optStatusFile, "RUNNING:" . $process->getPid()); } } if (!empty($nextRepositories)) { sleep(1); $process = AJXP_Controller::applyActionInBackground($nextRepositories, $optAction, $optArgs, $originalOptUser, $optStatusFile); if ($process != null && is_a($process, "UnixProcess") && isset($optStatusFile)) { file_put_contents($optStatusFile, "RUNNING:" . $process->getPid()); } } } else { if (isset($optStatusFile)) { $status = explode(":", file_get_contents($optStatusFile)); file_put_contents($optStatusFile, "FINISHED" . (in_array("QUEUED", $status) ? ":QUEUED" : "")); } }
/** * See static method * @param $repoId * @return int */ public function deleteRepositoryInst($repoId) { AJXP_Controller::applyHook("workspace.before_delete", array($repoId)); $confStorage = self::getConfStorageImpl(); $res = $confStorage->deleteRepository($repoId); if ($res == -1) { return $res; } AJXP_Controller::applyHook("workspace.after_delete", array($repoId)); AJXP_Logger::info(__CLASS__, "Delete Repository", array("repo_id" => $repoId)); $this->invalidateLoadedRepositories(); }
//------------------------------------------------------------ if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($action == "upload" && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRepositoryId() . "")) && isset($_FILES['Filedata'])) { header('HTTP/1.0 ' . '410 Not authorized'); die('Error 410 Not authorized!'); } } // THIS FIRST DRIVERS DO NOT NEED ID CHECK //$ajxpDriver = AJXP_PluginsService::findPlugin("gui", "ajax"); $authDriver = ConfService::getAuthDriverImpl(); // DRIVERS BELOW NEED IDENTIFICATION CHECK if (!AuthService::usersEnabled() || ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") || AuthService::getLoggedUser() != null) { $confDriver = ConfService::getConfStorageImpl(); $Driver = ConfService::loadRepositoryDriver(); } AJXP_PluginsService::getInstance()->initActivePlugins(); require_once AJXP_BIN_FOLDER . "/class.AJXP_Controller.php"; $xmlResult = AJXP_Controller::findActionAndApply($action, array_merge($_GET, $_POST), $_FILES); if ($xmlResult !== false && $xmlResult != "") { AJXP_XMLWriter::header(); print $xmlResult; AJXP_XMLWriter::close(); } else { if (isset($requireAuth) && AJXP_Controller::$lastActionNeedsAuth) { AJXP_XMLWriter::header(); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); } } session_write_close();
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)); } } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) { // Force legacy theme for the moment $this->pluginConf["GUI_THEME"] = "oxygen"; } if (!defined("AJXP_THEME_FOLDER")) { define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res"); define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]); } foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } if (isset($dir) && $action != "upload") { $dir = SystemTextEncoding::fromUTF8($dir); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // GET AN HTML TEMPLATE //------------------------------------ case "get_template": HTMLWriter::charsetHeader(); $folder = CLIENT_RESOURCES_FOLDER . "/html"; if (isset($httpVars["pluginName"])) { $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]); if (isset($httpVars["pluginPath"])) { $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]); } } $crtTheme = $this->pluginConf["GUI_THEME"]; $thFolder = AJXP_THEME_FOLDER . "/html"; if (isset($template_name)) { if (is_file($thFolder . "/" . $template_name)) { include $thFolder . "/" . $template_name; } else { if (is_file($folder . "/" . $template_name)) { include $folder . "/" . $template_name; } } } break; //------------------------------------ // GET I18N MESSAGES //------------------------------------ //------------------------------------ // GET I18N MESSAGES //------------------------------------ case "get_i18n_messages": $refresh = false; if (isset($httpVars["lang"])) { ConfService::setLanguage($httpVars["lang"]); $refresh = true; } HTMLWriter::charsetHeader('text/javascript'); HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh)); break; //------------------------------------ // SEND XML REGISTRY //------------------------------------ //------------------------------------ // SEND XML REGISTRY //------------------------------------ case "get_xml_registry": $regDoc = AJXP_PluginsService::getXmlRegistry(); $changes = AJXP_Controller::filterActionsRegistry($regDoc); if ($changes) { AJXP_PluginsService::updateXmlRegistry($regDoc); } if (isset($_GET["xPath"])) { $regPath = new DOMXPath($regDoc); $nodes = $regPath->query($_GET["xPath"]); AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $_GET["xPath"])); if ($nodes->length) { print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML($nodes->item(0))); } AJXP_XMLWriter::close("ajxp_registry_part"); } else { AJXP_Utils::safeIniSet("zlib.output_compression", "4096"); header('Content-Type: application/xml; charset=UTF-8'); print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML()); } break; //------------------------------------ // DISPLAY DOC //------------------------------------ //------------------------------------ // DISPLAY DOC //------------------------------------ case "display_doc": HTMLWriter::charsetHeader(); echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($_GET["doc_file"]))); break; //------------------------------------ // GET BOOT GUI //------------------------------------ //------------------------------------ // GET BOOT GUI //------------------------------------ case "get_boot_gui": header("X-UA-Compatible: chrome=1"); HTMLWriter::charsetHeader(); if (!is_file(TESTS_RESULT_FILE)) { $outputArray = array(); $testedParams = array(); $passed = AJXP_Utils::runTests($outputArray, $testedParams); if (!$passed && !isset($_GET["ignore_tests"])) { die(AJXP_Utils::testResultsToTable($outputArray, $testedParams)); } else { AJXP_Utils::testResultsToFile($outputArray, $testedParams); } } $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop"); if (AuthService::usersEnabled()) { AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : ""); AuthService::bootSequence($START_PARAMETERS); if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) { if (AuthService::getDefaultRootId() == -1) { AuthService::disconnect(); } else { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canRead(ConfService::getCurrentRootDirIndex()) && AuthService::getDefaultRootId() != ConfService::getCurrentRootDirIndex()) { ConfService::switchRootDir(AuthService::getDefaultRootId()); } } } } AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION); $confErrors = ConfService::getErrors(); if (count($confErrors)) { $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors)); } $JSON_START_PARAMETERS = json_encode($START_PARAMETERS); $crtTheme = $this->pluginConf["GUI_THEME"]; if (ConfService::getConf("JS_DEBUG")) { if (!isset($mess)) { $mess = ConfService::getMessages(); } if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) { include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html"; } else { include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html"; } } else { if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) { $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html"); } else { $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html"); } if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) { $content = str_replace("ajaxplorer_boot.js", "ajaxplorer_boot_protolegacy.js", $content); } $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false); if ($JSON_START_PARAMETERS) { $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content); } print $content; } break; //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ case "get_boot_conf": if (isset($_GET["server_prefix_uri"])) { $_SESSION["AJXP_SERVER_PREFIX_URI"] = $_GET["server_prefix_uri"]; } $config = array(); $config["ajxpResourcesFolder"] = "plugins/gui.ajax/res"; $config["ajxpServerAccess"] = AJXP_SERVER_ACCESS; $config["zipEnabled"] = ConfService::zipEnabled(); $config["multipleFilesDownloadEnabled"] = ConfService::getCoreConf("ZIP_CREATION"); $config["customWording"] = array("welcomeMessage" => $this->pluginConf["CUSTOM_WELCOME_MESSAGE"], "title" => ConfService::getCoreConf("APPLICATION_TITLE"), "icon" => $this->pluginConf["CUSTOM_ICON"], "iconWidth" => $this->pluginConf["CUSTOM_ICON_WIDTH"], "iconHeight" => $this->pluginConf["CUSTOM_ICON_HEIGHT"], "iconOnly" => $this->pluginConf["CUSTOM_ICON_ONLY"], "titleFontSize" => $this->pluginConf["CUSTOM_FONT_SIZE"]); $config["usersEnabled"] = AuthService::usersEnabled(); $config["loggedUser"] = AuthService::getLoggedUser() != null; $config["currentLanguage"] = ConfService::getLanguage(); $config["session_timeout"] = intval(ini_get("session.gc_maxlifetime")); if (!isset($this->pluginConf["CLIENT_TIMEOUT_TIME"]) || $this->pluginConf["CLIENT_TIMEOUT_TIME"] == "") { $to = $config["session_timeout"]; } else { $to = $this->pluginConf["CLIENT_TIMEOUT_TIME"]; } $config["client_timeout"] = $to; $config["client_timeout_warning"] = $this->pluginConf["CLIENT_TIMEOUT_WARN"]; $config["availableLanguages"] = ConfService::getConf("AVAILABLE_LANG"); $config["usersEditable"] = ConfService::getAuthDriverImpl()->usersEditable(); $config["ajxpVersion"] = AJXP_VERSION; $config["ajxpVersionDate"] = AJXP_VERSION_DATE; if (stristr($_SERVER["HTTP_USER_AGENT"], "msie 6")) { $config["cssResources"] = array("css/pngHack/pngHack.css"); } if (!empty($this->pluginConf['GOOGLE_ANALYTICS_ID'])) { $config["googleAnalyticsData"] = array("id" => $this->pluginConf['GOOGLE_ANALYTICS_ID'], "domain" => $this->pluginConf['GOOGLE_ANALYTICS_DOMAIN'], "event" => $this->pluginConf['GOOGLE_ANALYTICS_EVENT']); } $config["i18nMessages"] = ConfService::getMessages(); $config["password_min_length"] = ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth"); $config["SECURE_TOKEN"] = AuthService::generateSecureToken(); $config["streaming_supported"] = "true"; $config["theme"] = $this->pluginConf["GUI_THEME"]; header("Content-type:application/json;charset=UTF-8"); print json_encode($config); break; default: break; } return false; }
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 postProcess($action, $httpVars, $postProcessData) { if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) { return; } /* If set resumeFileId and resumePartitionIndex, cross-session resume is requested. */ if (isset($httpVars["resumeFileId"]) && isset($httpVars["resumePartitionIndex"])) { header("HTTP/1.1 200 OK"); print "fileId: " . $httpVars["resumeFileId"] . "\n"; print "partitionIndex: " . $httpVars["resumePartitionIndex"]; return; } /*if (self::$skipDecoding) { }*/ if (isset($postProcessData["processor_result"]["ERROR"])) { if (isset($httpVars["lastPartition"]) && isset($httpVars["partitionCount"])) { /* we get the stream url (where all the partitions have been uploaded so far) */ $repository = ConfService::getRepository(); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/"; if ($httpVars["partitionCount"] > 1) { /* we fetch the information that help us to construct the temp files name */ $fileId = $httpVars["fileId"]; $fileHash = md5($httpVars["fileName"]); /* deletion of all the partitions that have been uploaded */ for ($i = 0; $i < $httpVars["partitionCount"]; $i++) { if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) { unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } } else { $fileName = $httpVars["fileName"]; unlink($destStreamURL . $fileName); } } echo "Error: " . $postProcessData["processor_result"]["ERROR"]["MESSAGE"]; return; } if (!isset($httpVars["partitionRealName"]) && !isset($httpVars["lastPartition"])) { return; } $repository = ConfService::getRepository(); $driver = ConfService::loadDriverForRepository($repository); if (!$repository->detectStreamWrapper(false)) { return false; } if ($httpVars["lastPartition"]) { $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/"; /* we check if the current file has a relative path (aka we want to upload an entire directory) */ $this->logDebug("Now dispatching relativePath dest:", $httpVars["relativePath"]); $subs = explode("/", $httpVars["relativePath"]); $userfile_name = array_pop($subs); $folderForbidden = false; $all_in_place = true; $partitions_length = 0; $fileId = $httpVars["fileId"]; $fileHash = md5($userfile_name); $partitionCount = $httpVars["partitionCount"]; $fileLength = $_POST["fileLength"]; /* * * Now, we supposed that access driver has already saved uploaded file in to * folderServer with file name is md5 relativePath value. * We try to copy this file to right location in recovery his name. * */ $userfile_name = md5($httpVars["relativePath"]); if (self::$remote) { $partitions = array(); $newPartitions = array(); $index_first_partition = -1; $i = 0; do { $currentFileName = $driver->getFileNameToCopy(); $partitions[] = $driver->getNextFileToCopy(); if ($index_first_partition < 0 && strstr($currentFileName, $fileHash) != false) { $index_first_partition = $i; } else { if ($index_first_partition < 0) { $newPartitions[] = array_pop($partitions); } } } while ($driver->hasFilesToCopy()); } /* if partitionned */ if ($partitionCount > 1) { if (self::$remote) { for ($i = 0; $all_in_place && $i < $partitionCount; $i++) { $partition_file = "{$fileHash}.{$fileId}.{$i}"; if (strstr($partitions[$i]["name"], $partition_file) != false) { $partitions_length += filesize($partitions[$i]["tmp_name"]); } else { $all_in_place = false; } } } else { for ($i = 0; $all_in_place && $i < $partitionCount; $i++) { $partition_file = $destStreamURL . "{$fileHash}.{$fileId}.{$i}"; if (file_exists($partition_file)) { $partitions_length += filesize($partition_file); } else { $all_in_place = false; } } } } else { if (self::$remote) { if (strstr($newPartitions[count($newPartitions) - 1]["name"], $userfile_name) != false) { $partitions_length += filesize($newPartitions[count($newPartitions) - 1]["tmp_name"]); } } else { if (file_exists($destStreamURL . $userfile_name)) { $partitions_length += filesize($destStreamURL . $userfile_name); } } } if (!$all_in_place || $partitions_length != floatval($fileLength)) { echo "Error: Upload validation error!"; /* we delete all the uploaded partitions */ if ($httpVars["partitionCount"] > 1) { for ($i = 0; $i < $partitionCount; $i++) { if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) { unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } } else { $fileName = $httpVars["partitionRealName"]; unlink($destStreamURL . $fileName); } return; } if (count($subs) > 0 && !self::$remote) { $curDir = ""; if (substr($curDir, -1) == "/") { $curDir = substr($curDir, 0, -1); } // Create the folder tree as necessary foreach ($subs as $key => $spath) { $messtmp = ""; $dirname = AJXP_Utils::decodeSecureMagic($spath, AJXP_SANITIZE_FILENAME); $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); //$this->filterUserSelectionToHidden(array($dirname)); if (AJXP_Utils::isHidden($dirname)) { $folderForbidden = true; break; } if (file_exists($destStreamURL . "{$curDir}/{$dirname}")) { // if the folder exists, traverse $this->logDebug("{$curDir}/{$dirname} existing, traversing for {$userfile_name} out of", $httpVars["relativePath"]); $curDir .= "/" . $dirname; continue; } $this->logDebug($destStreamURL . $curDir); $dirMode = 0775; $chmodValue = $repository->getOption("CHMOD_VALUE"); if (isset($chmodValue) && $chmodValue != "") { $dirMode = octdec(ltrim($chmodValue, "0")); if ($dirMode & 0400) { $dirMode |= 0100; } // Owner is allowed to read, allow to list the directory if ($dirMode & 040) { $dirMode |= 010; } // Group is allowed to read, allow to list the directory if ($dirMode & 04) { $dirMode |= 01; } // Other are allowed to read, allow to list the directory } $url = $destStreamURL . $curDir . "/" . $dirname; $old = umask(0); mkdir($url, $dirMode); umask($old); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($url), false)); $curDir .= "/" . $dirname; } } if (!$folderForbidden) { $fileId = $httpVars["fileId"]; $this->logDebug("Should now rebuild file!", $httpVars); // Now move the final file to the right folder // Currently the file is at the base of the current $this->logDebug("PartitionRealName", $destStreamURL . $httpVars["partitionRealName"]); // Get file by name (md5 value) $relPath_md5 = AJXP_Utils::decodeSecureMagic(md5($httpVars["relativePath"])); // original file name $relPath = AJXP_Utils::decodeSecureMagic($httpVars["relativePath"]); $target = $destStreamURL; $target .= self::$remote ? basename($relPath) : $relPath; /* * $current is uploaded file with md5 value as his name * we copy to $relPath and delete md5 file */ $current = $destStreamURL . basename($relPath_md5); if ($httpVars["partitionCount"] > 1) { if (self::$remote) { $test = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"]; $newDest = fopen(AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"], "w"); $newFile = array(); $length = 0; for ($i = 0, $count = count($partitions); $i < $count; $i++) { $currentFile = $partitions[$i]; $currentFileName = $currentFile["tmp_name"]; $part = fopen($currentFileName, "r"); while (!feof($part)) { $length += fwrite($newDest, fread($part, 4096)); } fclose($part); unlink($currentFileName); } $newFile["type"] = $partitions[0]["type"]; $newFile["name"] = $httpVars["partitionRealName"]; $newFile["error"] = 0; $newFile["size"] = $length; $newFile["tmp_name"] = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"]; $newFile["destination"] = $partitions[0]["destination"]; $newPartitions[] = $newFile; } else { $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w"); $fileHash = md5($httpVars["partitionRealName"]); for ($i = 0; $i < $httpVars["partitionCount"]; $i++) { $part = fopen($destStreamURL . "{$fileHash}.{$fileId}.{$i}", "r"); while (!feof($part)) { fwrite($newDest, fread($part, 4096)); } fclose($part); unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}"); } } fclose($newDest); } if (!self::$remote && (!self::$wrapperIsRemote || $relPath != $httpVars["partitionRealName"])) { $err = copy($current, $target); } else { for ($i = 0, $count = count($newPartitions); $i < $count; $i++) { $driver->storeFileToCopy($newPartitions[$i]); } } if ($err !== false) { if (!self::$remote) { unlink($current); } AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false)); } else { if ($current == $target) { AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false)); } } } else { // Remove the file, as it should not have been uploaded! //if(!self::$remote) unlink($current); } } }
/** * Delete a user in the auth driver impl * @static * @param $userId * @return bool */ static function deleteUser($userId) { $userId = AuthService::filterUserSensitivity($userId); AJXP_Controller::applyHook("user.before_delete", array($userId)); $authDriver = ConfService::getAuthDriverImpl(); $authDriver->deleteUser($userId); $subUsers = array(); AJXP_User::deleteUser($userId, $subUsers); foreach ($subUsers as $deletedUser) { $authDriver->deleteUser($deletedUser); } AJXP_Controller::applyHook("user.after_delete", array($userId)); AJXP_Logger::logAction("Delete User", array("user_id" => $userId, "sub_user" => implode(",", $subUsers))); return true; }
public function switchAction($action, $httpVars, $fileVars) { $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::decodeSecureMagic($dir); if ($dir == "/") { $dir = ""; } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { //$this->filterUserSelectionToHidden($selection->getFiles()); } $urlBase = "pydio://" . ConfService::getRepository()->getId(); $mess = ConfService::getMessages(); switch ($action) { case "monitor_compression": $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]); $percent = 0; if (is_file($percentFile)) { $percent = intval(file_get_contents($percentFile)); } if ($percent < 100) { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1); AJXP_XMLWriter::close(); } else { @unlink($percentFile); AJXP_XMLWriter::header(); if ($httpVars["on_end"] == "reload") { AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } else { $archiveName = AJXP_Utils::sanitize($httpVars["archive_name"], AJXP_SANITIZE_FILENAME); $archiveName = str_replace("'", "\\'", $archiveName); $jsCode = "\n PydioApi.getClient().downloadSelection(null, \$('download_form'), 'postcompress_download', {ope_id:'" . $httpVars["ope_id"] . "',archive_name:'" . $archiveName . "'});\n "; AJXP_XMLWriter::triggerBgJsAction($jsCode, $mess["powerfs.3"], true); AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } AJXP_XMLWriter::close(); } break; case "postcompress_download": $archive = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); if (is_file($archive)) { if (!$fsDriver->getFilteredOption("USE_XSENDFILE", ConfService::getRepository()) && !$fsDriver->getFilteredOption("USE_XACCELREDIRECT", ConfService::getRepository())) { register_shutdown_function("unlink", $archive); } $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true); } else { echo "<script>alert('Cannot find archive! Is ZIP correctly installed?');</script>"; } break; case "compress": case "precompress": $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) { $opeId = substr(md5(time()), 0, 10); $httpVars["ope_id"] = $opeId; AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars); AJXP_XMLWriter::header(); $bgParameters = array("dir" => SystemTextEncoding::toUTF8($dir), "archive_name" => SystemTextEncoding::toUTF8($archiveName), "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId); AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true); AJXP_XMLWriter::close(); session_write_close(); exit; } $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir; $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"]; $compressLocally = $action == "compress" ? true : false; // List all files $todo = array(); $args = array(); $replaceSearch = array($rootDir, "\\"); $replaceReplace = array("", "/"); foreach ($selection->getFiles() as $selectionFile) { $baseFile = $selectionFile; $args[] = escapeshellarg(substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1))); $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile); $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/"); if (is_dir($selectionFile)) { $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST); foreach ($objects as $name => $object) { $todo[] = str_replace($replaceSearch, $replaceReplace, $name); } } if (trim($baseFile, "/") == "") { // ROOT IS SELECTED, FIX IT $args = array(escapeshellarg(basename($rootDir))); $rootDir = dirname($rootDir); break; } } $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";"; if (!$compressLocally) { $archiveName = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . $archiveName; } chdir($rootDir); $cmd = $this->getFilteredOption("ZIP_PATH") . " -r " . escapeshellarg($archiveName) . " " . implode(" ", $args); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $c = $fsDriver->getConfigs(); if ((!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) && stripos(PHP_OS, "win") === false) { $cmd .= " -x .\\*"; } $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED"; $proc = popen($cmd, "r"); $toks = array(); $handled = array(); $finishedEchoed = false; while (!feof($proc)) { set_time_limit(20); $results = fgets($proc, 256); if (strlen($results) == 0) { } else { $tok = strtok($results, "\n"); while ($tok !== false) { $toks[] = $tok; if ($tok == "ZIP_FINISHED") { $finishedEchoed = true; } else { $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches); if ($test !== false) { $handled[] = $matches[2]; } } $tok = strtok("\n"); } if ($finishedEchoed) { $percent = 100; } else { $percent = min(round(count($handled) / count($todo) * 100), 100); } file_put_contents($percentFile, $percent); } // avoid a busy wait if ($percent < 100) { usleep(1); } } pclose($proc); file_put_contents($percentFile, 100); break; default: break; } }
public function editMeta($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); $nodes = $selection->buildNodes(); $nodesDiffs = array(); $def = $this->getMetaDefinition(); foreach ($nodes as $ajxpNode) { $newValues = array(); //$ajxpNode->setDriver($this->accessDriver); AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode)); foreach ($def as $key => $data) { if (isset($httpVars[$key])) { $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]); if ($data["type"] == "tags") { $this->updateTags(AJXP_Utils::decodeSecureMagic($httpVars[$key])); } } else { if (!isset($original)) { $original = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL); } if (isset($original) && isset($original[$key])) { $newValues[$key] = $original[$key]; } } } $ajxpNode->setMetadata("users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL); AJXP_Controller::applyHook("node.meta_change", array($ajxpNode)); $nodesDiffs[$ajxpNode->getPath()] = $ajxpNode; } AJXP_XMLWriter::header(); AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => $nodesDiffs), true); AJXP_XMLWriter::close(); }
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) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } if (isset($dir) && $action != "upload") { $dir = SystemTextEncoding::fromUTF8($dir); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // SWITCH THE ROOT REPOSITORY //------------------------------------ case "switch_repository": if (!isset($repository_id)) { break; } $dirList = ConfService::getRepositoriesList(); /** @var $repository_id string */ if (!isset($dirList[$repository_id])) { $errorMessage = "Trying to switch to an unkown repository!"; break; } ConfService::switchRootDir($repository_id); // Load try to init the driver now, to trigger an exception // if it's not loading right. ConfService::loadRepositoryDriver(); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $user = AuthService::getLoggedUser(); $activeRepId = ConfService::getCurrentRepositoryId(); $user->setArrayPref("history", "last_repository", $activeRepId); $user->save("user"); } //$logMessage = "Successfully Switched!"; $this->logInfo("Switch Repository", array("rep. id" => $repository_id)); break; //------------------------------------ // SEND XML REGISTRY //------------------------------------ //------------------------------------ // SEND XML REGISTRY //------------------------------------ case "get_xml_registry": case "state": $regDoc = AJXP_PluginsService::getXmlRegistry(); $changes = AJXP_Controller::filterRegistryFromRole($regDoc); if ($changes) { AJXP_PluginsService::updateXmlRegistry($regDoc); } $clone = $regDoc->cloneNode(true); $clonePath = new DOMXPath($clone); $serverCallbacks = $clonePath->query("//serverCallback|hooks"); foreach ($serverCallbacks as $callback) { $callback->parentNode->removeChild($callback); } $xPath = ''; if (isset($httpVars["xPath"])) { $xPath = ltrim(AJXP_Utils::securePath($httpVars["xPath"]), "/"); } if (!empty($xPath)) { $nodes = $clonePath->query($xPath); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($nodes->item(0)); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $xPath)); if ($nodes->length) { print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML($nodes->item(0))); } AJXP_XMLWriter::close("ajxp_registry_part"); } } else { AJXP_Utils::safeIniSet("zlib.output_compression", "4096"); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($clone); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { header('Content-Type: application/xml; charset=UTF-8'); print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML()); } } break; //------------------------------------ // BOOKMARK BAR //------------------------------------ //------------------------------------ // BOOKMARK BAR //------------------------------------ case "get_bookmarks": $bmUser = null; if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser = AuthService::getLoggedUser(); } else { if (!AuthService::usersEnabled()) { $confStorage = ConfService::getConfStorageImpl(); $bmUser = $confStorage->createUserObject("shared"); } } if ($bmUser == null) { AJXP_XMLWriter::header(); AJXP_XMLWriter::close(); } $driver = ConfService::loadRepositoryDriver(); if (!is_a($driver, "AjxpWrapperProvider")) { $driver = false; } if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) { $bmPath = AJXP_Utils::decodeSecureMagic($httpVars["bm_path"]); if ($httpVars["bm_action"] == "add_bookmark") { $title = ""; if (isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); } if ($title == "" && $bmPath == "/") { $title = ConfService::getCurrentRootDirDisplay(); } $bmUser->addBookMark($bmPath, $title); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->setMetadata("ajxp_bookmarked", array("ajxp_bookmarked" => "true"), true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "delete_bookmark") { $bmUser->removeBookmark($bmPath); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->removeMetadata("ajxp_bookmarked", true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); $bmUser->renameBookmark($bmPath, $title); } } } AJXP_Controller::applyHook("msg.instant", array("<reload_bookmarks/>", ConfService::getRepository()->getId())); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser->save("user"); AuthService::updateUser($bmUser); } else { if (!AuthService::usersEnabled()) { $bmUser->save("user"); } } } AJXP_XMLWriter::header(); AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks(), true, isset($httpVars["format"]) ? $httpVars["format"] : "legacy"); AJXP_XMLWriter::close(); break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "save_user_pref": $userObject = AuthService::getLoggedUser(); $i = 0; while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) { $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM); $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i])); if ($prefName == "password") { continue; } if ($prefName != "pending_folder" && $userObject == null) { $i++; continue; } $userObject->setPref($prefName, $prefValue); $userObject->save("user"); AuthService::updateUser($userObject); //setcookie("AJXP_$prefName", $prefValue); $i++; } header("Content-Type:text/plain"); print "SUCCESS"; break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "custom_data_edit": case "user_create_user": $data = array(); if ($action == "user_create_user" && isset($httpVars["NEW_new_user_id"])) { $updating = false; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $original_id = AJXP_Utils::decodeSecureMagic($data["new_user_id"]); $data["new_user_id"] = AJXP_Utils::decodeSecureMagic($data["new_user_id"], AJXP_SANITIZE_EMAILCHARS); if ($original_id != $data["new_user_id"]) { throw new Exception(str_replace("%s", $data["new_user_id"], $mess["ajxp_conf.127"])); } if (AuthService::userExists($data["new_user_id"], "w")) { throw new Exception($mess["ajxp_conf.43"]); } $loggedUser = AuthService::getLoggedUser(); $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, ""); if (!empty($limit) && intval($limit) > 0) { $count = count($this->getUserChildren($loggedUser->getId())); if ($count >= $limit) { throw new Exception($mess['483']); } } AuthService::createUser($data["new_user_id"], $data["new_password"]); $userObject = ConfService::getConfStorageImpl()->createUserObject($data["new_user_id"]); $userObject->setParent($loggedUser->getId()); $userObject->save('superuser'); $userObject->personalRole->clearAcls(); $userObject->setGroupPath($loggedUser->getGroupPath()); $userObject->setProfile("shared"); } else { if ($action == "user_create_user" && isset($httpVars["NEW_existing_user_id"])) { $updating = true; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $userId = $data["existing_user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } if (!empty($data["new_password"])) { AuthService::updatePassword($userId, $data["new_password"]); } } else { $updating = false; $userObject = AuthService::getLoggedUser(); AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "PREFERENCES_"); } } $paramNodes = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'user') and @expose='true']", "node", false, false, true); $rChanges = false; if (is_array($paramNodes) && count($paramNodes)) { foreach ($paramNodes as $xmlNode) { if ($xmlNode->getAttribute("expose") == "true") { $parentNode = $xmlNode->parentNode->parentNode; $pluginId = $parentNode->getAttribute("id"); if (empty($pluginId)) { $pluginId = $parentNode->nodeName . "." . $parentNode->getAttribute("name"); } $name = $xmlNode->getAttribute("name"); if (isset($data[$name]) || $data[$name] === "") { if ($data[$name] == "__AJXP_VALUE_SET__") { continue; } if ($data[$name] === "" || $userObject->parentRole == null || $userObject->parentRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name] || $userObject->personalRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name]) { $userObject->personalRole->setParameterValue($pluginId, $name, $data[$name]); $rChanges = true; } } } } } if ($rChanges) { AuthService::updateRole($userObject->personalRole, $userObject); $userObject->recomputeMergedRole(); if ($action == "custom_data_edit") { AuthService::updateUser($userObject); } } if ($action == "user_create_user") { AJXP_Controller::applyHook($updating ? "user.after_update" : "user.after_create", array($userObject)); if (isset($data["send_email"]) && $data["send_email"] == true && !empty($data["email"])) { $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer"); if ($mailer !== false) { $mess = ConfService::getMessages(); $link = AJXP_Utils::detectServerURL(); $apptitle = ConfService::getCoreConf("APPLICATION_TITLE"); $subject = str_replace("%s", $apptitle, $mess["507"]); $body = str_replace(array("%s", "%link", "%user", "%pass"), array($apptitle, $link, $data["new_user_id"], $data["new_password"]), $mess["508"]); $mailer->sendMail(array($data["email"]), $subject, $body); } } echo "SUCCESS"; } else { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["241"], null); AJXP_XMLWriter::close(); } break; case "user_update_user": if (!isset($httpVars["user_id"])) { throw new Exception("invalid arguments"); } $userId = $httpVars["user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } $paramsString = ConfService::getCoreConf("NEWUSERS_EDIT_PARAMETERS", "conf"); $result = array(); $params = explode(",", $paramsString); foreach ($params as $p) { $result[$p] = $userObject->personalRole->filterParameterValue("core.conf", $p, AJXP_REPO_SCOPE_ALL, ""); } HTMLWriter::charsetHeader("application/json"); echo json_encode($result); break; //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ case "webdav_preferences": $userObject = AuthService::getLoggedUser(); $webdavActive = false; $passSet = false; $digestSet = false; // Detect http/https and host if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") { $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST"); } else { $baseURL = AJXP_Utils::detectServerURL(); } $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/"; $davData = $userObject->getPref("AJXP_WEBDAV_DATA"); $digestSet = isset($davData["HA1"]); if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) { if (!empty($httpVars["activate"])) { $activate = $httpVars["activate"] == "true" ? true : false; if (empty($davData)) { $davData = array(); } $davData["ACTIVE"] = $activate; } if (!empty($httpVars["webdav_pass"])) { $password = $httpVars["webdav_pass"]; if (function_exists('mcrypt_encrypt')) { $user = $userObject->getId(); $secret = defined("AJXP_SAFE_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#"; $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB)); } $davData["PASS"] = $password; } $userObject->setPref("AJXP_WEBDAV_DATA", $davData); $userObject->save("user"); } if (!empty($davData)) { $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true; $passSet = isset($davData["PASS"]); } $repoList = ConfService::getRepositoriesList(); $davRepos = array(); $loggedUser = AuthService::getLoggedUser(); foreach ($repoList as $repoIndex => $repoObject) { $accessType = $repoObject->getAccessType(); $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType); if (is_a($driver, "AjxpWrapperProvider") && !$repoObject->getOption("AJXP_WEBDAV_DISABLED") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) { $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug()); } } $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "digest_set" => $digestSet, "webdav_force_basic" => ConfService::getCoreConf("WEBDAV_FORCE_BASIC") === true, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos); HTMLWriter::charsetHeader("application/json"); print json_encode($prefs); break; case "get_user_template_logo": $tplId = $httpVars["template_id"]; $iconFormat = $httpVars["icon_format"]; $repo = ConfService::getRepositoryById($tplId); $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat)); if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) { header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)); header('Pragma:'); header('Cache-Control: public'); 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"); readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo); } else { $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png"; header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo)); header('Pragma:'); header('Cache-Control: public'); 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"); readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo); } break; case "get_user_templates_definition": AJXP_XMLWriter::header("repository_templates"); $count = 0; $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => 1), $count); $pServ = AJXP_PluginsService::getInstance(); foreach ($repositories as $repo) { if (!$repo->isTemplate) { continue; } if (!$repo->getOption("TPL_USER_CAN_CREATE")) { continue; } $repoId = $repo->getId(); $repoLabel = $repo->getDisplay(); $repoType = $repo->getAccessType(); print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">"; $driverPlug = $pServ->getPluginByTypeName("access", $repoType); $params = $driverPlug->getManifestRawContent("//param", "node"); $tplDefined = $repo->getOptionsDefined(); $defaultLabel = ''; foreach ($params as $paramNode) { $name = $paramNode->getAttribute("name"); if (strpos($name, "TPL_") === 0) { if ($name == "TPL_DEFAULT_LABEL") { $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name)); } continue; } if (in_array($paramNode->getAttribute("name"), $tplDefined)) { continue; } if ($paramNode->getAttribute('no_templates') == 'true') { continue; } print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode)); } // ADD LABEL echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>'; print "</template>"; } AJXP_XMLWriter::close("repository_templates"); break; case "user_create_repository": $tplId = $httpVars["template_id"]; $tplRepo = ConfService::getRepositoryById($tplId); $options = array(); AJXP_Utils::parseStandardFormParameters($httpVars, $options); $loggedUser = AuthService::getLoggedUser(); $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, $loggedUser->getId()); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath)) { $newRep->setGroupPath($gPath); } $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[426]); } else { // Make sure we do not overwrite otherwise loaded rights. $loggedUser->load(); $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw"); $loggedUser->save("superuser"); $loggedUser->recomputeMergedRole(); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[425], null); AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId()); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_repository": $repoId = $httpVars["repository_id"]; $repository = ConfService::getRepositoryById($repoId); if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to perform this operation!"); } $res = ConfService::deleteRepository($repoId); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[427]); } else { $loggedUser = AuthService::getLoggedUser(); // Make sure we do not override remotely set rights $loggedUser->load(); $loggedUser->personalRole->setAcl($repoId, ""); $loggedUser->save("superuser"); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[428], null); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_user": $userId = $httpVars["user_id"]; $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject == null || !$userObject->hasParent() || $userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to edit this user"); } AuthService::deleteUser($userId); echo "SUCCESS"; break; case "user_list_authorized_users": $defaultFormat = "html"; HTMLWriter::charsetHeader(); if (!ConfService::getAuthDriverImpl()->usersEditable()) { break; } $loggedUser = AuthService::getLoggedUser(); $crtValue = $httpVars["value"]; $usersOnly = isset($httpVars["users_only"]) && $httpVars["users_only"] == "true"; $existingOnly = isset($httpVars["existing_only"]) && $httpVars["existing_only"] == "true"; if (!empty($crtValue)) { $regexp = '^' . $crtValue; } else { $regexp = null; } $skipDisplayWithoutRegexp = ConfService::getCoreConf("USERS_LIST_REGEXP_MANDATORY", "conf"); if ($skipDisplayWithoutRegexp && $regexp == null) { print "<ul></ul>"; break; } $limit = intval(ConfService::getCoreConf("USERS_LIST_COMPLETE_LIMIT", "conf")); $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf"); $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf"); $baseGroup = "/"; if ($regexp == null && !$displayAll || $regexp != null && !$searchAll) { $baseGroup = AuthService::filterBaseGroup("/"); } AuthService::setGroupFiltering(false); $allUsers = AuthService::listUsers($baseGroup, $regexp, 0, $limit, false); if (!$usersOnly) { $allGroups = array(); $roleOrGroup = ConfService::getCoreConf("GROUP_OR_ROLE", "conf"); $rolePrefix = $excludeString = $includeString = null; if (!is_array($roleOrGroup)) { $roleOrGroup = array("group_switch_value" => $roleOrGroup); } $listRoleType = false; if (isset($roleOrGroup["PREFIX"])) { $rolePrefix = $loggedUser->mergedRole->filterParameterValue("core.conf", "PREFIX", null, $roleOrGroup["PREFIX"]); $excludeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "EXCLUDED", null, $roleOrGroup["EXCLUDED"]); $includeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "INCLUDED", null, $roleOrGroup["INCLUDED"]); $listUserRolesOnly = $loggedUser->mergedRole->filterParameterValue("core.conf", "LIST_ROLE_BY", null, $roleOrGroup["LIST_ROLE_BY"]); if (is_array($listUserRolesOnly) && isset($listUserRolesOnly["group_switch_value"])) { switch ($listUserRolesOnly["group_switch_value"]) { case "userroles": $listRoleType = true; break; case "allroles": $listRoleType = false; break; default: break; } } } switch (strtolower($roleOrGroup["group_switch_value"])) { case 'user': // donothing break; case 'group': $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $allGroups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } break; case 'role': $allGroups = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); break; case 'rolegroup': $groups = array(); $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $groups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } $roles = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); empty($groups) ? $allGroups = $roles : (empty($roles) ? $allGroups = $groups : ($allGroups = array_merge($groups, $roles))); //$allGroups = array_merge($groups, $roles); break; default: break; } } $users = ""; $index = 0; if ($regexp != null && (!count($allUsers) || !empty($crtValue) && !array_key_exists(strtolower($crtValue), $allUsers)) && ConfService::getCoreConf("USER_CREATE_USERS", "conf") && !$existingOnly) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}'><span class='user_entry_label'>{$crtValue} (" . $mess["448"] . ")</span></li>"; } else { if ($existingOnly && !empty($crtValue)) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}' data-entry_id='{$crtValue}'><span class='user_entry_label'>{$crtValue}</span></li>"; } } $mess = ConfService::getMessages(); if ($regexp == null && !$usersOnly) { $users .= "<li class='complete_group_entry' data-group='AJXP_GRP_/' data-label='" . $mess["447"] . "'><span class='user_entry_label'>" . $mess["447"] . "</span></li>"; } $indexGroup = 0; if (!$usersOnly && is_array($allGroups)) { foreach ($allGroups as $groupId => $groupLabel) { if ($regexp == null || preg_match("/{$regexp}/i", $groupLabel)) { $users .= "<li class='complete_group_entry' data-group='{$groupId}' data-label='{$groupLabel}' data-entry_id='{$groupId}'><span class='user_entry_label'>" . $groupLabel . "</span></li>"; $indexGroup++; } if ($indexGroup == $limit) { break; } } } if ($regexp == null && method_exists($this, "listUserTeams")) { $teams = $this->listUserTeams(); foreach ($teams as $tId => $tData) { $users .= "<li class='complete_group_entry' data-group='/AJXP_TEAM/{$tId}' data-label='[team] " . $tData["LABEL"] . "'><span class='user_entry_label'>[team] " . $tData["LABEL"] . "</span></li>"; } } foreach ($allUsers as $userId => $userObject) { if ($userObject->getId() == $loggedUser->getId()) { continue; } if (!$userObject->hasParent() && ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") || $userObject->getParent() == $loggedUser->getId()) { $userLabel = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId); //if($regexp != null && ! (preg_match("/$regexp/i", $userId) || preg_match("/$regexp/i", $userLabel)) ) continue; if (empty($userLabel)) { $userLabel = $userId; } $userDisplay = $userLabel == $userId ? $userId : $userLabel . " ({$userId})"; if (ConfService::getCoreConf("USERS_LIST_HIDE_LOGIN", "conf") == true && $userLabel != $userId) { $userDisplay = $userLabel; } $users .= "<li class='complete_user_entry' data-label='{$userLabel}' data-entry_id='{$userId}'><span class='user_entry_label'>" . $userDisplay . "</span></li>"; $index++; } if ($index == $limit) { break; } } if (strlen($users)) { print "<ul>" . $users . "</ul>"; } AuthService::setGroupFiltering(true); break; case "load_repository_info": $data = array(); $repo = ConfService::getRepository(); if ($repo != null) { $users = AuthService::countUsersForRepository(ConfService::getRepository()->getId(), true); $data["core.users"] = $users; if (isset($httpVars["collect"]) && $httpVars["collect"] == "true") { AJXP_Controller::applyHook("repository.load_info", array(&$data)); } } HTMLWriter::charsetHeader("application/json"); echo json_encode($data); break; case "get_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { if (isset($httpVars["user_id"]) && AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->isAdmin()) { $context = array("USER" => $httpVars["user_id"]); } else { $context = array("USER" => AuthService::getLoggedUser()->getId()); } $this->loadBinary($context, $httpVars["binary_id"]); } } break; case "get_global_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { $this->loadBinary(array(), $httpVars["binary_id"]); } } break; case "store_binary_temp": if (count($fileVars)) { $keys = array_keys($fileVars); $boxData = $fileVars[$keys[0]]; $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { } else { $rand = substr(md5(time()), 0, 6); $tmp = $rand . "-" . $boxData["name"]; @move_uploaded_file($boxData["tmp_name"], AJXP_Utils::getAjxpTmpDir() . "/" . $tmp); } } if (isset($tmp) && file_exists(AJXP_Utils::getAjxpTmpDir() . "/" . $tmp)) { print '<script type="text/javascript">'; print 'parent.formManagerHiddenIFrameSubmission("' . $tmp . '");'; print '</script>'; } break; default: break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } return $xmlBuffer; }
/** * @param AJXP_Node $oldNode * @param AJXP_Node $newNode * @param bool $copy */ public function updateNodesIndex($oldNode = null, $newNode = null, $copy = false) { if (!dibi::isConnected()) { dibi::connect($this->sqlDriver); } //$this->logInfo("Syncable index", array($oldNode == null?'null':$oldNode->getUrl(), $newNode == null?'null':$newNode->getUrl())); try { if ($newNode != null && $this->excludeNode($newNode)) { // CREATE if ($oldNode == null) { AJXP_Logger::debug("Ignoring " . $newNode->getUrl() . " for indexation"); return; } else { AJXP_Logger::debug("Target node is excluded, see it as a deletion: " . $newNode->getUrl()); $newNode = null; } } if ($newNode == null) { $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser()); // DELETE $this->logDebug('DELETE', $oldNode->getUrl()); dibi::query("DELETE FROM [ajxp_index] WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); } else { if ($oldNode == null || $copy) { // CREATE $stat = stat($newNode->getUrl()); $newNode->setLeaf(!($stat['mode'] & 040000)); $this->logDebug('INSERT', $newNode->getUrl()); dibi::query("INSERT INTO [ajxp_index]", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath()), "bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => $newNode->isLeaf() ? md5_file($newNode->getUrl()) : "directory", "repository_identifier" => $repoId = $this->computeIdentifier($newNode->getRepository(), $newNode->getUser()))); } else { $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser()); if ($oldNode->getPath() == $newNode->getPath()) { // CONTENT CHANGE clearstatcache(); $stat = stat($newNode->getUrl()); $this->logDebug("Content changed", "current stat size is : " . $stat["size"]); $this->logDebug('UPDATE CONTENT', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET ", array("bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => md5_file($newNode->getUrl())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!"); $this->updateNodesIndex(null, $newNode, false); } } catch (Exception $e) { } } else { // PATH CHANGE ONLY $newNode->loadNodeInfo(); if ($newNode->isLeaf()) { $this->logDebug('UPDATE LEAF PATH', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET ", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!"); $this->updateNodesIndex(null, $newNode, false); } } catch (Exception $e) { } } else { $this->logDebug('UPDATE FOLDER PATH', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET [node_path]=REPLACE( REPLACE(CONCAT('\$\$\$',[node_path]), CONCAT('\$\$\$', %s), CONCAT('\$\$\$', %s)) , '\$\$\$', '') ", $oldNode->getPath(), $newNode->getPath(), "WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed folder (" . $newNode->getPath() . "), relaunching a recursive indexation!"); AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array()); } } catch (Exception $e) { } } } } } } catch (Exception $e) { AJXP_Logger::error("[meta.syncable]", "Exception", $e->getTraceAsString()); AJXP_Logger::error("[meta.syncable]", "Indexation", $e->getMessage()); } }
/** * @param String $action * @param Array $httpVars * @param Array $fileVars * @throws Exception */ public function receiveAction($action, $httpVars, $fileVars) { //VAR CREATION OUTSIDE OF ALL CONDITIONS, THEY ARE "MUST HAVE" VAR !! $messages = ConfService::getMessages(); $repository = ConfService::getRepository(); $userSelection = new UserSelection($repository, $httpVars); $nodes = $userSelection->buildNodes(); $currentDirPath = AJXP_Utils::safeDirname($userSelection->getUniqueNode()->getPath()); $currentDirPath = rtrim($currentDirPath, "/") . "/"; $currentDirUrl = $userSelection->currentBaseUrl() . $currentDirPath; if (empty($httpVars["compression_id"])) { $compressionId = sha1(rand()); $httpVars["compression_id"] = $compressionId; } else { $compressionId = $httpVars["compression_id"]; } $progressCompressionFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressCompressionID-" . $compressionId . ".txt"; if (empty($httpVars["extraction_id"])) { $extractId = sha1(rand()); $httpVars["extraction_id"] = $extractId; } else { $extractId = $httpVars["extraction_id"]; } $progressExtractFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressExtractID-" . $extractId . ".txt"; if ($action == "compression") { $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); $archiveFormat = $httpVars["type_archive"]; $tabTypeArchive = array(".tar", ".tar.gz", ".tar.bz2"); $acceptedExtension = false; foreach ($tabTypeArchive as $extensionArchive) { if ($extensionArchive == $archiveFormat) { $acceptedExtension = true; break; } } if ($acceptedExtension == false) { file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.16"]); throw new AJXP_Exception($messages["compression.16"]); } $typeArchive = $httpVars["type_archive"]; //if we can run in background we do it if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { $archivePath = $currentDirPath . $archiveName; file_put_contents($progressCompressionFileName, $messages["compression.5"]); AJXP_Controller::applyActionInBackground($repository->getId(), "compression", $httpVars); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $messages["compression.5"], true, 2); AJXP_XMLWriter::close(); return null; } else { $maxAuthorizedSize = 4294967296; $currentDirUrlLength = strlen($currentDirUrl); $tabFolders = array(); $tabAllRecursiveFiles = array(); $tabFilesNames = array(); foreach ($nodes as $node) { $nodeUrl = $node->getUrl(); if (is_file($nodeUrl) && filesize($nodeUrl) < $maxAuthorizedSize) { array_push($tabAllRecursiveFiles, $nodeUrl); array_push($tabFilesNames, substr($nodeUrl, $currentDirUrlLength)); } if (is_dir($nodeUrl)) { array_push($tabFolders, $nodeUrl); } } //DO A FOREACH OR IT'S GONNA HAVE SOME SAMES FILES NAMES foreach ($tabFolders as $value) { $dossiers = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($value)); foreach ($dossiers as $file) { if ($file->isDir()) { continue; } array_push($tabAllRecursiveFiles, $file->getPathname()); array_push($tabFilesNames, substr($file->getPathname(), $currentDirUrlLength)); } } //WE STOP IF IT'S JUST AN EMPTY FOLDER OR NO FILES if (empty($tabFilesNames)) { file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.17"]); throw new AJXP_Exception($messages["compression.17"]); } try { $tmpArchiveName = tempnam(AJXP_Utils::getAjxpTmpDir(), "tar-compression") . ".tar"; $archive = new PharData($tmpArchiveName); } catch (Exception $e) { file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage()); throw $e; } $counterCompression = 0; //THE TWO ARRAY ARE MERGED FOR THE FOREACH LOOP $tabAllFiles = array_combine($tabAllRecursiveFiles, $tabFilesNames); foreach ($tabAllFiles as $fullPath => $fileName) { try { $archive->addFile(AJXP_MetaStreamWrapper::getRealFSReference($fullPath), $fileName); $counterCompression++; file_put_contents($progressCompressionFileName, sprintf($messages["compression.6"], round($counterCompression / count($tabAllFiles) * 100, 0, PHP_ROUND_HALF_DOWN) . " %")); } catch (Exception $e) { unlink($tmpArchiveName); file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage()); throw $e; } } $finalArchive = $tmpArchiveName; if ($typeArchive != ".tar") { $archiveTypeCompress = substr(strrchr($typeArchive, "."), 1); file_put_contents($progressCompressionFileName, sprintf($messages["compression.7"], strtoupper($archiveTypeCompress))); if ($archiveTypeCompress == "gz") { $archive->compress(Phar::GZ); } elseif ($archiveTypeCompress == "bz2") { $archive->compress(Phar::BZ2); } $finalArchive = $tmpArchiveName . "." . $archiveTypeCompress; } $destArchive = AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $archiveName); rename($finalArchive, $destArchive); AJXP_Controller::applyHook("node.before_create", array($destArchive, filesize($destArchive))); if (file_exists($tmpArchiveName)) { unlink($tmpArchiveName); unlink(substr($tmpArchiveName, 0, -4)); } $newNode = new AJXP_Node($currentDirUrl . $archiveName); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); file_put_contents($progressCompressionFileName, "SUCCESS"); } } elseif ($action == "check_compression_status") { $archivePath = AJXP_Utils::decodeSecureMagic($httpVars["archive_path"]); $progressCompression = file_get_contents($progressCompressionFileName); $substrProgressCompression = substr($progressCompression, 0, 5); if ($progressCompression != "SUCCESS" && $substrProgressCompression != "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $progressCompression, true, 5); AJXP_XMLWriter::close(); } elseif ($progressCompression == "SUCCESS") { $newNode = new AJXP_Node($userSelection->currentBaseUrl() . $archivePath); $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array()); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($messages["compression.8"], null); AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true); AJXP_XMLWriter::close(); if (file_exists($progressCompressionFileName)) { unlink($progressCompressionFileName); } } elseif ($substrProgressCompression == "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $progressCompression); AJXP_XMLWriter::close(); if (file_exists($progressCompressionFileName)) { unlink($progressCompressionFileName); } } } elseif ($action == "extraction") { $fileArchive = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["file"]), AJXP_SANITIZE_DIRNAME); $fileArchive = substr(strrchr($fileArchive, DIRECTORY_SEPARATOR), 1); $authorizedExtension = array("tar" => 4, "gz" => 7, "bz2" => 8); $acceptedArchive = false; $extensionLength = 0; $counterExtract = 0; $currentAllPydioPath = $currentDirUrl . $fileArchive; $pharCurrentAllPydioPath = "phar://" . AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath); $pathInfoCurrentAllPydioPath = pathinfo($currentAllPydioPath, PATHINFO_EXTENSION); //WE TAKE ONLY TAR, TAR.GZ AND TAR.BZ2 ARCHIVES foreach ($authorizedExtension as $extension => $strlenExtension) { if ($pathInfoCurrentAllPydioPath == $extension) { $acceptedArchive = true; $extensionLength = $strlenExtension; break; } } if ($acceptedArchive == false) { file_put_contents($progressExtractFileName, "Error : " . $messages["compression.15"]); throw new AJXP_Exception($messages["compression.15"]); } $onlyFileName = substr($fileArchive, 0, -$extensionLength); $lastPosOnlyFileName = strrpos($onlyFileName, "-"); $tmpOnlyFileName = substr($onlyFileName, 0, $lastPosOnlyFileName); $counterDuplicate = substr($onlyFileName, $lastPosOnlyFileName + 1); if (!is_int($lastPosOnlyFileName) || !is_int($counterDuplicate)) { $tmpOnlyFileName = $onlyFileName; $counterDuplicate = 1; } while (file_exists($currentDirUrl . $onlyFileName)) { $onlyFileName = $tmpOnlyFileName . "-" . $counterDuplicate; $counterDuplicate++; } if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { file_put_contents($progressExtractFileName, $messages["compression.12"]); AJXP_Controller::applyActionInBackground($repository->getId(), "extraction", $httpVars); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $messages["compression.12"], true, 2); AJXP_XMLWriter::close(); return null; } mkdir($currentDirUrl . $onlyFileName, 0777, true); chmod(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), 0777); try { $archive = new PharData(AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath)); $fichiersArchive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharCurrentAllPydioPath)); foreach ($fichiersArchive as $file) { $fileGetPathName = $file->getPathname(); if ($file->isDir()) { continue; } $fileNameInArchive = substr(strstr($fileGetPathName, $fileArchive), strlen($fileArchive) + 1); try { $archive->extractTo(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), $fileNameInArchive, false); } catch (Exception $e) { file_put_contents($progressExtractFileName, "Error : " . $e->getMessage()); throw new AJXP_Exception($e); } $counterExtract++; file_put_contents($progressExtractFileName, sprintf($messages["compression.13"], round($counterExtract / $archive->count() * 100, 0, PHP_ROUND_HALF_DOWN) . " %")); } } catch (Exception $e) { file_put_contents($progressExtractFileName, "Error : " . $e->getMessage()); throw new AJXP_Exception($e); } file_put_contents($progressExtractFileName, "SUCCESS"); $newNode = new AJXP_Node($currentDirUrl . $onlyFileName); AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array()); } elseif ($action == "check_extraction_status") { $currentDirUrl = $httpVars["currentDirUrl"]; $onlyFileName = $httpVars["onlyFileName"]; $progressExtract = file_get_contents($progressExtractFileName); $substrProgressExtract = substr($progressExtract, 0, 5); if ($progressExtract != "SUCCESS" && $progressExtract != "INDEX" && $substrProgressExtract != "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $progressExtract, true, 4); AJXP_XMLWriter::close(); } elseif ($progressExtract == "SUCCESS") { $newNode = new AJXP_Node($currentDirUrl . $onlyFileName); $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array()); AJXP_Controller::applyHook("node.change", array(null, $newNode, false)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(sprintf($messages["compression.14"], $onlyFileName), null); AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $newNode->getRepositoryId()), "starting indexation", true, 5); AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true); AJXP_XMLWriter::close(); if (file_exists($progressExtractFileName)) { unlink($progressExtractFileName); } } elseif ($substrProgressExtract == "Error") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $progressExtract); AJXP_XMLWriter::close(); if (file_exists($progressExtractFileName)) { unlink($progressExtractFileName); } } } }
public function switchAction($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; }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); 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"; $selection = new UserSelection($repository, $httpVars); // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); } else { $file = $selection->getUniqueFile(); } $target = base64_decode($httpVars["parent_url"]); $tmp = call_user_func(array($streamData["classname"], "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'); $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->getId())) { $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()); } 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->getId()), '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->getId())) { $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()) . "?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()); AJXP_Controller::applyHook("node.change", array(null, &$node)); } } }