public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; if ($this->wrapperClassName == "fsAccessWrapper") { $dir = fsAccessWrapper::patchPathForBaseDir($dir); } $dir = AJXP_Utils::securePath($dir); if ($action != "upload") { $dir = AJXP_Utils::decodeSecureMagic($dir); } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { $this->filterUserSelectionToHidden($selection->getFiles()); } $mess = ConfService::getMessages(); $newArgs = RecycleBinManager::filterActions($action, $selection, $dir, $httpVars); if (isset($newArgs["action"])) { $action = $newArgs["action"]; } if (isset($newArgs["dest"])) { $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]); } //Re-encode! // FILTER DIR PAGINATION ANCHOR $page = null; if (isset($dir) && strstr($dir, "%23") !== false) { $parts = explode("%23", $dir); $dir = $parts[0]; $page = $parts[1]; } $pendingSelection = ""; $logMessage = null; $reloadContextNode = false; switch ($action) { //------------------------------------ // DOWNLOAD //------------------------------------ case "download": $this->logInfo("Download", array("files" => $this->addSlugToPath($selection))); @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE); @register_shutdown_function("restore_error_handler"); $zip = false; if ($selection->isUnique()) { if (is_dir($this->urlBase . $selection->getUniqueFile())) { $zip = true; $base = basename($selection->getUniqueFile()); $uniqDir = dirname($selection->getUniqueFile()); if (!empty($uniqDir) && $uniqDir != "/") { $dir = dirname($selection->getUniqueFile()); } } else { if (!file_exists($this->urlBase . $selection->getUniqueFile())) { throw new Exception("Cannot find file!"); } } $node = $selection->getUniqueNode($this); } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpDownload.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, empty($dir) ? "/" : $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing"); } if (!$this->getFilteredOption("USE_XSENDFILE", $this->repository->getId()) && !$this->getFilteredOption("USE_XACCELREDIRECT", $this->repository->getId())) { register_shutdown_function("unlink", $file); } $localName = ($base == "" ? "Files" : $base) . ".zip"; if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); } $this->readFile($file, "force-download", $localName, false, false, true); } else { $localName = ""; AJXP_Controller::applyHook("dl.localname", array($this->urlBase . $selection->getUniqueFile(), &$localName, $this->wrapperClassName)); $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download", $localName); } if (isset($node)) { AJXP_Controller::applyHook("node.read", array(&$node)); } break; case "prepare_chunk_dl": $chunkCount = intval($httpVars["chunk_count"]); $fileId = $this->urlBase . $selection->getUniqueFile(); $sessionKey = "chunk_file_" . md5($fileId . time()); $totalSize = $this->filesystemFileSize($fileId); $chunkSize = intval($totalSize / $chunkCount); $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $fileId, true); $chunkData = array("localname" => basename($fileId), "chunk_count" => $chunkCount, "chunk_size" => $chunkSize, "total_size" => $totalSize, "file_id" => $sessionKey); $_SESSION[$sessionKey] = array_merge($chunkData, array("file" => $realFile)); HTMLWriter::charsetHeader("application/json"); print json_encode($chunkData); $node = $selection->getUniqueNode($this); AJXP_Controller::applyHook("node.read", array(&$node)); break; case "download_chunk": $chunkIndex = intval($httpVars["chunk_index"]); $chunkKey = $httpVars["file_id"]; $sessData = $_SESSION[$chunkKey]; $realFile = $sessData["file"]; $chunkSize = $sessData["chunk_size"]; $offset = $chunkSize * $chunkIndex; if ($chunkIndex == $sessData["chunk_count"] - 1) { // Compute the last chunk real length $chunkSize = $sessData["total_size"] - $chunkSize * ($sessData["chunk_count"] - 1); if (call_user_func(array($this->wrapperClassName, "isRemote"))) { register_shutdown_function("unlink", $realFile); } } $this->readFile($realFile, "force-download", $sessData["localname"] . "." . sprintf("%03d", $chunkIndex + 1), false, false, true, $offset, $chunkSize); break; case "compress": // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); $this->filterUserSelectionToHidden(array($localName)); } else { $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip"; } $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpCompression.zip"; if (isset($httpVars["compress_flat"])) { $baseDir = "__AJXP_ZIP_FLAT__/"; } else { $baseDir = $dir; } $zipFile = $this->makeZip($selection->getFiles(), $file, $baseDir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing file {$localName}"); } register_shutdown_function("unlink", $file); $tmpFNAME = $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName); copy($file, $tmpFNAME); try { AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($tmpFNAME), filesize($tmpFNAME))); } catch (Exception $e) { @unlink($tmpFNAME); throw $e; } @rename($tmpFNAME, $this->urlBase . $dir . "/" . $localName); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($this->urlBase . $dir . "/" . $localName), false)); //$reloadContextNode = true; //$pendingSelection = $localName; $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $localName); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["ADD"][] = $newNode; break; case "stat": clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $stat = @stat($this->urlBase . $selection->getUniqueFile()); if (!$stat) { print '{}'; } else { print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $stat = @stat($this->urlBase . $path); if (!$stat) { $stat = '{}'; } else { $stat = json_encode($stat); } print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "get_content": $dlFile = $this->urlBase . $selection->getUniqueFile(); $this->logInfo("Get_content", array("files" => $this->addSlugToPath($selection))); if (AJXP_Utils::getStreamingMimeType(basename($dlFile)) !== false) { $this->readFile($this->urlBase . $selection->getUniqueFile(), "stream_content"); } else { $this->readFile($this->urlBase . $selection->getUniqueFile(), "plain"); } $node = $selection->getUniqueNode($this); AJXP_Controller::applyHook("node.read", array(&$node)); break; case "put_content": if (!isset($httpVars["content"])) { break; } // Load "code" variable directly from POST array, do not "securePath" or "sanitize"... $code = $httpVars["content"]; $file = $selection->getUniqueFile(); $this->logInfo("Online Edition", array("file" => $this->addSlugToPath($file))); if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") { $code = base64_decode($code); } else { $code = str_replace("<", "<", SystemTextEncoding::magicDequote($code)); } $fileName = $this->urlBase . $file; $currentNode = new AJXP_Node($fileName); try { AJXP_Controller::applyHook("node.before_change", array(&$currentNode, strlen($code))); } catch (Exception $e) { header("Content-Type:text/plain"); print $e->getMessage(); return; } if (!is_file($fileName) || !$this->isWriteable($fileName, "file")) { header("Content-Type:text/plain"); print !$this->isWriteable($fileName, "file") ? "1001" : "1002"; return; } $fp = fopen($fileName, "w"); fputs($fp, $code); fclose($fp); clearstatcache(true, $fileName); AJXP_Controller::applyHook("node.change", array($currentNode, $currentNode, false)); header("Content-Type:text/plain"); print $mess[115]; break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": //throw new AJXP_Exception("", 113); if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && !$loggedUser->canWrite(ConfService::getCurrentRepositoryId())) { throw new AJXP_Exception("You are not allowed to write", 207); } $success = $error = array(); $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $this->filterUserSelectionToHidden(array($httpVars["dest"])); if ($selection->inZip()) { // Set action to copy anycase (cannot move from the zip). $action = "copy"; $this->extractArchive($dest, $selection, $error, $success); } else { $move = $action == "move" ? true : false; if ($move && isset($httpVars["force_copy_delete"])) { $move = false; } $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $move); } if (count($error)) { throw new AJXP_Exception(SystemTextEncoding::toUTF8(join("\n", $error))); } else { if (isset($httpVars["force_copy_delete"])) { $errorMessage = $this->delete($selection->getFiles(), $logMessages); if ($errorMessage) { throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage)); } $this->logInfo("Copy/Delete", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest))); } else { $this->logInfo($action == "move" ? "Move" : "Copy", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest))); } $logMessage = join("\n", $success); } if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } // Assume new nodes are correctly created $selectedItems = $selection->getFiles(); foreach ($selectedItems as $selectedPath) { $newPath = $this->urlBase . $dest . "/" . basename($selectedPath); $newNode = new AJXP_Node($newPath); $nodesDiffs["ADD"][] = $newNode; if ($action == "move") { $nodesDiffs["REMOVE"][] = $selectedPath; } } if (!(RecycleBinManager::getRelativeRecycle() == $dest && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) == true)) { //$reloadDataNode = $dest; } break; //------------------------------------ // DELETE //------------------------------------ //------------------------------------ // DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $logMessages = array(); $errorMessage = $this->delete($selection->getFiles(), $logMessages); if (count($logMessages)) { $logMessage = join("\n", $logMessages); } if ($errorMessage) { throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage)); } $this->logInfo("Delete", array("files" => $this->addSlugToPath($selection))); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["REMOVE"] = array_merge($nodesDiffs["REMOVE"], $selection->getFiles()); break; case "purge": $hardPurgeTime = intval($this->repository->getOption("PURGE_AFTER")) * 3600 * 24; $softPurgeTime = intval($this->repository->getOption("PURGE_AFTER_SOFT")) * 3600 * 24; $shareCenter = AJXP_PluginsService::findPluginById('action.share'); if (!($shareCenter && $shareCenter->isEnabled())) { //action.share is disabled, don't look at the softPurgeTime $softPurgeTime = 0; } if ($hardPurgeTime > 0 || $softPurgeTime > 0) { $this->recursivePurge($this->urlBase, $hardPurgeTime, $softPurgeTime); } break; //------------------------------------ // RENAME //------------------------------------ //------------------------------------ // RENAME //------------------------------------ case "rename": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]); $dest = null; if (isset($httpVars["dest"])) { $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $filename_new = ""; } $this->filterUserSelectionToHidden(array($filename_new)); $this->rename($file, $filename_new, $dest); $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); //$reloadContextNode = true; //$pendingSelection = $filename_new; if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } if ($dest == null) { $dest = AJXP_Utils::safeDirname($file); } $nodesDiffs["UPDATE"][$file] = new AJXP_Node($this->urlBase . $dest . "/" . $filename_new); $this->logInfo("Rename", array("original" => $this->addSlugToPath($file), "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; if (!isset($httpVars["dirname"])) { $uniq = $selection->getUniqueFile(); $dir = AJXP_Utils::safeDirname($uniq); $dirname = AJXP_Utils::safeBasename($uniq); } else { $dirname = AJXP_Utils::decodeSecureMagic($httpVars["dirname"], AJXP_SANITIZE_FILENAME); } $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); $this->filterUserSelectionToHidden(array($dirname)); AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($dir . "/" . $dirname), -2)); $error = $this->mkDir($dir, $dirname, isset($httpVars["ignore_exists"]) ? true : false); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; //$pendingSelection = $dirname; //$reloadContextNode = true; $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $dirname); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } array_push($nodesDiffs["ADD"], $newNode); $this->logInfo("Create Dir", array("dir" => $this->addSlugToPath($dir) . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; if (empty($httpVars["filename"]) && isset($httpVars["node"])) { $filename = AJXP_Utils::decodeSecureMagic($httpVars["node"], AJXP_SANITIZE_FILENAME); } else { $filename = AJXP_Utils::decodeSecureMagic($httpVars["filename"], AJXP_SANITIZE_FILENAME); } $filename = substr($filename, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); $this->filterUserSelectionToHidden(array($filename)); $content = ""; if (isset($httpVars["content"])) { $content = $httpVars["content"]; } $error = $this->createEmptyFile($dir, $filename, $content); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; //$reloadContextNode = true; //$pendingSelection = $dir."/".$filename; $this->logInfo("Create File", array("file" => $this->addSlugToPath($dir) . "/" . $filename)); $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $filename); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } array_push($nodesDiffs["ADD"], $newNode); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $files = $selection->getFiles(); $changedFiles = array(); $chmod_value = $httpVars["chmod_value"]; $recursive = $httpVars["recursive"]; $recur_apply_to = $httpVars["recur_apply_to"]; foreach ($files as $fileName) { $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles); } $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders"; $this->logInfo("Chmod", array("dir" => $this->addSlugToPath($dir), "filesCount" => count($changedFiles))); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["UPDATE"] = array_merge($nodesDiffs["UPDATE"], $selection->buildNodes($this)); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": $repoData = array('base_url' => $this->urlBase, 'wrapper_name' => $this->wrapperClassName, 'chmod' => $this->repository->getOption('CHMOD_VALUE'), 'recycle' => $this->repository->getOption('RECYCLE_BIN')); $this->logDebug("Upload Files Data", $fileVars); $destination = $this->urlBase . AJXP_Utils::decodeSecureMagic($dir); $this->logDebug("Upload inside", array("destination" => $this->addSlugToPath($destination))); if (!$this->isWriteable($destination)) { $errorCode = 412; $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}."; $this->logDebug("Upload error 412", array("destination" => $this->addSlugToPath($destination))); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } foreach ($fileVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } $userfile_name = $boxData["name"]; try { $this->filterUserSelectionToHidden(array($userfile_name)); } catch (Exception $e) { return array("ERROR" => array("CODE" => 411, "MESSAGE" => "Forbidden")); } $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromPostedFileName($userfile_name), AJXP_SANITIZE_FILENAME); if (isset($httpVars["urlencoded_filename"])) { $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["urlencoded_filename"])), AJXP_SANITIZE_FILENAME); } $this->logDebug("User filename " . $userfile_name); $userfile_name = substr($userfile_name, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); if (isset($httpVars["auto_rename"])) { $userfile_name = self::autoRenameForDest($destination, $userfile_name); } $already_existed = false; try { if (file_exists($destination . "/" . $userfile_name)) { $already_existed = true; AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"])); } else { AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"])); } AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination))); } catch (Exception $e) { $errorCode = 507; $errorMessage = $e->getMessage(); break; } if (isset($boxData["input_upload"])) { try { $this->logDebug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen("{$destination}/" . $userfile_name, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); $this->logDebug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { $result = @move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name); if (!$result) { $realPath = call_user_func(array($this->wrapperClassName, "getRealFSReference"), "{$destination}/" . $userfile_name); $result = move_uploaded_file($boxData["tmp_name"], $realPath); } if (!$result) { $errorCode = 411; $errorMessage = "{$mess['33']} " . $userfile_name; break; } } if (isset($httpVars["appendto_urlencoded_part"])) { $appendTo = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["appendto_urlencoded_part"])), AJXP_SANITIZE_FILENAME); if (file_exists($destination . "/" . $appendTo)) { $this->logDebug("Should copy stream from {$userfile_name} to {$appendTo}"); $partO = fopen($destination . "/" . $userfile_name, "r"); $appendF = fopen($destination . "/" . $appendTo, "a+"); while (!feof($partO)) { $buf = fread($partO, 1024); fwrite($appendF, $buf, strlen($buf)); } fclose($partO); fclose($appendF); $this->logDebug("Done, closing streams!"); } @unlink($destination . "/" . $userfile_name); $userfile_name = $appendTo; } $this->changeMode($destination . "/" . $userfile_name, $repoData); $createdNode = new AJXP_Node($destination . "/" . $userfile_name); //AJXP_Controller::applyHook("node.change", array(null, $createdNode, false)); $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; $this->logInfo("Upload File", array("file" => $this->addSlugToPath(SystemTextEncoding::fromUTF8($dir)) . "/" . $userfile_name)); } if (isset($errorMessage)) { $this->logDebug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { $this->logDebug("Return success"); if ($already_existed) { return array("SUCCESS" => true, "UPDATED_NODE" => $createdNode); } else { return array("SUCCESS" => true, "CREATED_NODE" => $createdNode); } } return; break; case "lsync": if (!ConfService::currentContextIsCommandLine()) { die("This command must be accessed via CLI only."); } $fromNode = null; $toNode = null; $copyOrMove = false; if (isset($httpVars["from"])) { $fromNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["from"])); } if (isset($httpVars["to"])) { $toNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["to"])); } if (isset($httpVars["copy"]) && $httpVars["copy"] == "true") { $copyOrMove = true; } AJXP_Controller::applyHook("node.change", array($fromNode, $toNode, $copyOrMove)); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a"); $startTime = microtime(); if (isset($httpVars["file"])) { $uniqueFile = AJXP_Utils::decodeSecureMagic($httpVars["file"]); } $dir = AJXP_Utils::securePath($dir); $path = $this->urlBase . ($dir != "" ? ($dir[0] == "/" ? "" : "/") . $dir : ""); $nonPatchedPath = $path; if ($this->wrapperClassName == "fsAccessWrapper") { $nonPatchedPath = fsAccessWrapper::unPatchPathForBaseDir($path); } if ($this->getFilteredOption("REMOTE_SORTING")) { $orderDirection = isset($httpVars["order_direction"]) ? strtolower($httpVars["order_direction"]) : "asc"; $orderField = isset($httpVars["order_column"]) ? $httpVars["order_column"] : null; if ($orderField != null && !in_array($orderField, array("ajxp_label", "filesize", "ajxp_modiftime", "mimestring"))) { $orderField = "ajxp_label"; } } if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") { $max_depth = isset($httpVars["max_depth"]) ? intval($httpVars["max_depth"]) : 0; $max_nodes = isset($httpVars["max_nodes"]) ? intval($httpVars["max_nodes"]) : 0; $crt_depth = isset($httpVars["crt_depth"]) ? intval($httpVars["crt_depth"]) + 1 : 1; $crt_nodes = isset($httpVars["crt_nodes"]) ? intval($httpVars["crt_nodes"]) : 0; } else { $threshold = $this->repository->getOption("PAGINATION_THRESHOLD"); if (!isset($threshold) || intval($threshold) == 0) { $threshold = 500; } $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER"); if (!isset($limitPerPage) || intval($limitPerPage) == 0) { $limitPerPage = 200; } } $countFiles = $this->countFiles($path, !$lsOptions["f"]); if (isset($crt_nodes)) { $crt_nodes += $countFiles; } if (isset($threshold) && isset($limitPerPage) && $countFiles > $threshold) { if (isset($uniqueFile)) { $originalLimitPerPage = $limitPerPage; $offset = $limitPerPage = 0; } else { $offset = 0; $crtPage = 1; if (isset($page)) { $offset = (intval($page) - 1) * $limitPerPage; $crtPage = $page; } $totalPages = floor($countFiles / $limitPerPage) + 1; } } else { $offset = $limitPerPage = 0; } $metaData = array(); if (RecycleBinManager::recycleEnabled() && $dir == "") { $metaData["repo_has_recycle"] = "true"; } $parentAjxpNode = new AJXP_Node($nonPatchedPath, $metaData); $parentAjxpNode->loadNodeInfo(false, true, $lsOptions["l"] ? "all" : "minimal"); AJXP_Controller::applyHook("node.read", array(&$parentAjxpNode)); if (AJXP_XMLWriter::$headerSent == "tree") { AJXP_XMLWriter::renderAjxpNode($parentAjxpNode, false); } else { AJXP_XMLWriter::renderAjxpHeaderNode($parentAjxpNode); } if (isset($totalPages) && isset($crtPage)) { $remoteOptions = null; if ($this->getFilteredOption("REMOTE_SORTING")) { $remoteOptions = array("remote_order" => "true", "currentOrderCol" => isset($orderField) ? $orderField : "ajxp_label", "currentOrderDir" => isset($orderDirection) ? $orderDirection : "asc"); } AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages, $this->countFiles($path, TRUE), $remoteOptions); if (!$lsOptions["f"]) { AJXP_XMLWriter::close(); exit(1); } } $cursor = 0; $handle = opendir($path); if (!$handle) { throw new AJXP_Exception("Cannot open dir " . $nonPatchedPath); } closedir($handle); $fullList = array("d" => array(), "z" => array(), "f" => array()); if (isset($orderField) && isset($orderDirection) && $orderField == "ajxp_label" && $orderDirection == "desc") { $nodes = scandir($path, 1); } else { $nodes = scandir($path); } if (!empty($this->driverConf["SCANDIR_RESULT_SORTFONC"])) { usort($nodes, $this->driverConf["SCANDIR_RESULT_SORTFONC"]); } if (isset($orderField) && isset($orderDirection) && $orderField != "ajxp_label") { $toSort = array(); foreach ($nodes as $node) { if ($orderField == "filesize") { $toSort[$node] = is_file($nonPatchedPath . "/" . $node) ? $this->filesystemFileSize($nonPatchedPath . "/" . $node) : 0; } else { if ($orderField == "ajxp_modiftime") { $toSort[$node] = filemtime($nonPatchedPath . "/" . $node); } else { if ($orderField == "mimestring") { $toSort[$node] = pathinfo($node, PATHINFO_EXTENSION); } } } } if ($orderDirection == "asc") { asort($toSort); } else { arsort($toSort); } $nodes = array_keys($toSort); } //while (strlen($nodeName = readdir($handle)) > 0) { foreach ($nodes as $nodeName) { if ($nodeName == "." || $nodeName == "..") { continue; } if (isset($uniqueFile) && $nodeName != $uniqueFile) { $cursor++; continue; } if ($offset > 0 && $cursor < $offset) { $cursor++; continue; } $isLeaf = ""; if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) { continue; } if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) { continue; } if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) { break; } $currentFile = $nonPatchedPath . "/" . $nodeName; $meta = array(); if ($isLeaf != "") { $meta = array("is_file" => $isLeaf ? "1" : "0"); } $node = new AJXP_Node($currentFile, $meta); $node->setLabel($nodeName); $node->loadNodeInfo(false, false, $lsOptions["l"] ? "all" : "minimal"); if (!empty($node->metaData["nodeName"]) && $node->metaData["nodeName"] != $nodeName) { $node->setUrl($nonPatchedPath . "/" . $node->metaData["nodeName"]); } if (!empty($node->metaData["hidden"]) && $node->metaData["hidden"] === true) { continue; } if (!empty($node->metaData["mimestring_id"]) && array_key_exists($node->metaData["mimestring_id"], $mess)) { $node->mergeMetadata(array("mimestring" => $mess[$node->metaData["mimestring_id"]])); } if (isset($originalLimitPerPage) && $cursor > $originalLimitPerPage) { $node->mergeMetadata(array("page_position" => floor($cursor / $originalLimitPerPage) + 1)); } $nodeType = "d"; if ($node->isLeaf()) { if (AJXP_Utils::isBrowsableArchive($nodeName)) { if ($lsOptions["f"] && $lsOptions["z"]) { $nodeType = "f"; } else { $nodeType = "z"; } } else { $nodeType = "f"; } } // There is a special sorting, cancel the reordering of files & folders. if (isset($orderField) && $orderField != "ajxp_label") { $nodeType = "f"; } $fullList[$nodeType][$nodeName] = $node; $cursor++; if (isset($uniqueFile) && $nodeName != $uniqueFile) { break; } } if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") { $breakNow = false; if (isset($max_depth) && $max_depth > 0 && $crt_depth >= $max_depth) { $breakNow = true; } if (isset($max_nodes) && $max_nodes > 0 && $crt_nodes >= $max_nodes) { $breakNow = true; } foreach ($fullList["d"] as &$nodeDir) { if ($breakNow) { $nodeDir->mergeMetadata(array("ajxp_has_children" => $this->countFiles($nodeDir->getUrl(), false, true) ? "true" : "false")); AJXP_XMLWriter::renderAjxpNode($nodeDir, true); continue; } $this->switchAction("ls", array("dir" => SystemTextEncoding::toUTF8($nodeDir->getPath()), "options" => $httpVars["options"], "recursive" => "true", "max_depth" => $max_depth, "max_nodes" => $max_nodes, "crt_depth" => $crt_depth, "crt_nodes" => $crt_nodes), array()); } } else { array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["d"]); } array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["z"]); array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["f"]); // ADD RECYCLE BIN TO THE LIST if ($dir == "" && !$uniqueFile && RecycleBinManager::recycleEnabled() && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) !== true) { $recycleBinOption = RecycleBinManager::getRelativeRecycle(); if (file_exists($this->urlBase . $recycleBinOption)) { $recycleNode = new AJXP_Node($this->urlBase . $recycleBinOption); $recycleNode->loadNodeInfo(); AJXP_XMLWriter::renderAjxpNode($recycleNode); } } $this->logDebug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms"); AJXP_XMLWriter::close(); break; } $xmlBuffer = ""; if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if ($reloadContextNode) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false); } if (isset($nodesDiffs)) { $xmlBuffer .= AJXP_XMLWriter::writeNodesDiff($nodesDiffs, false); } return $xmlBuffer; }
public function listRepositories($root, $child, $hashValue = null, $returnNodes = false) { $REPOS_PER_PAGE = 50; $allNodes = array(); if ($hashValue == null) { $hashValue = 1; } $offset = ($hashValue - 1) * $REPOS_PER_PAGE; $count = null; // Load all repositories = normal, templates, and templates children $currentUserIsGroupAdmin = AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/"; if ($currentUserIsGroupAdmin) { $repos = ConfService::listRepositoriesWithCriteria(array("owner_user_id" => AJXP_FILTER_EMPTY, "groupPath" => "regexp:/^" . str_replace("/", "\\/", AuthService::getLoggedUser()->getGroupPath()) . '/', "ORDERBY" => array("KEY" => "display", "DIR" => "ASC"), "CURSOR" => array("OFFSET" => $offset, "LIMIT" => $REPOS_PER_PAGE)), $count); } else { $repos = ConfService::listRepositoriesWithCriteria(array("parent_uuid" => AJXP_FILTER_EMPTY, "ORDERBY" => array("KEY" => "display", "DIR" => "ASC"), "CURSOR" => array("OFFSET" => $offset, "LIMIT" => $REPOS_PER_PAGE)), $count); } if (!$returnNodes) { var_dump($count); AJXP_XMLWriter::renderPaginationData($count, $hashValue, ceil($count / $REPOS_PER_PAGE)); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.repositories"> <column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/> <column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/> <column messageId="ajxp_conf.125" attributeName="slug" sortType="String"/> </columns>'); } foreach ($repos as $repoIndex => $repoObject) { if ($repoObject->getAccessType() == "ajxp_conf" || $repoObject->getAccessType() == "ajxp_shared") { continue; } if (!AuthService::canAdministrate($repoObject)) { continue; } if (is_numeric($repoIndex)) { $repoIndex = "" . $repoIndex; } $icon = "hdd_external_unmount.png"; $editable = $repoObject->isWriteable(); if ($repoObject->isTemplate) { $icon = "hdd_external_mount.png"; if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/") { $editable = false; } } $meta = array("repository_id" => $repoIndex, "accessType" => ($repoObject->isTemplate ? "Template for " : "") . $repoObject->getAccessType(), "icon" => $icon, "owner" => $repoObject->hasOwner() ? $repoObject->getOwner() : "", "openicon" => $icon, "slug" => $repoObject->getSlug(), "parentname" => "/repositories", "ajxp_mime" => "repository" . ($editable ? "_editable" : "")); $nodeKey = "/data/repositories/{$repoIndex}"; if (in_array($nodeKey, $this->currentBookmarks)) { $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png")); } $xml = AJXP_XMLWriter::renderNode($nodeKey, AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay())), true, $meta, true, false); if ($returnNodes) { $allNodes[$nodeKey] = $xml; } else { print $xml; } if ($repoObject->isTemplate) { // Now Load children for template repositories $children = ConfService::listRepositoriesWithCriteria(array("parent_uuid" => $repoIndex . ""), $count); foreach ($children as $childId => $childObject) { if (!AuthService::canAdministrate($childObject)) { continue; } if (is_numeric($childId)) { $childId = "" . $childId; } $meta = array("repository_id" => $childId, "accessType" => $childObject->getAccessType(), "icon" => "repo_child.png", "owner" => $childObject->hasOwner() ? $childObject->getOwner() : "", "openicon" => "repo_child.png", "parentname" => "/repositories", "ajxp_mime" => "repository_editable"); $cNodeKey = "/data/repositories/{$childId}"; if (in_array($cNodeKey, $this->currentBookmarks)) { $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png")); } $xml = AJXP_XMLWriter::renderNode($cNodeKey, AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($childObject->getDisplay())), true, $meta, true, false); if ($returnNodes) { $allNodes[$cNodeKey] = $xml; } else { print $xml; } } } } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::securePath($dir); if ($action != "upload") { $dir = SystemTextEncoding::fromPostedFileName($dir); } $selection->initFromHttpVars($httpVars); $mess = ConfService::getMessages(); $newArgs = RecycleBinManager::filterActions($action, $selection, $dir); if (isset($newArgs["action"])) { $action = $newArgs["action"]; } if (isset($newArgs["dest"])) { $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]); } //Re-encode! // FILTER DIR PAGINATION ANCHOR $page = null; if (isset($dir) && strstr($dir, "#") !== false) { $parts = explode("#", $dir); $dir = $parts[0]; $page = $parts[1]; } $pendingSelection = ""; $logMessage = null; $reloadContextNode = false; switch ($action) { //------------------------------------ // DOWNLOAD //------------------------------------ case "download": AJXP_Logger::logAction("Download", array("files" => $selection)); @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE); @register_shutdown_function("restore_error_handler"); $zip = false; if ($selection->isUnique()) { if (is_dir($this->urlBase . $selection->getUniqueFile())) { $zip = true; $base = basename($selection->getUniqueFile()); $dir .= "/" . dirname($selection->getUniqueFile()); } } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpDownload.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing"); } register_shutdown_function("unlink", $file); $localName = ($base == "" ? "Files" : $base) . ".zip"; $this->readFile($file, "force-download", $localName, false, false, true); } else { $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download"); } exit(0); break; case "compress": // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); } else { $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip"; } $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpCompression.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing file {$localName}"); } register_shutdown_function("unlink", $file); copy($file, $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName)); @rename($this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName), $this->urlBase . $dir . "/" . $localName); $reloadContextNode = true; $pendingSelection = $localName; break; case "stat": clearstatcache(); $stat = @stat($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["file"])); header("Content-type:application/json"); if (!$stat) { print '{}'; } else { print json_encode($stat); } exit(1); break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "get_content": $this->readFile($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["file"]), "plain"); exit(0); break; case "put_content": if (!isset($httpVars["content"])) { break; } // Reload "code" variable directly from POST array, do not "securePath"... $code = $httpVars["content"]; $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); AJXP_Logger::logAction("Online Edition", array("file" => $file)); if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") { $code = base64_decode($code); } else { $code = stripslashes($code); $code = str_replace("<", "<", $code); } $fileName = $this->urlBase . $file; if (!is_file($fileName) || !is_writable($fileName)) { header("Content-Type:text/plain"); print !is_writable($fileName) ? "1001" : "1002"; exit(1); } $fp = fopen($fileName, "w"); fputs($fp, $code); fclose($fp); header("Content-Type:text/plain"); print $mess[115]; exit(0); break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $success = $error = array(); $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); if ($selection->inZip()) { // Set action to copy anycase (cannot move from the zip). $action = "copy"; } $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false); if (count($error)) { throw new AJXP_Exception(join("\n", $error)); } else { $logMessage = join("\n", $success); AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest)); } $reloadContextNode = true; $reloadDataNode = $dest; break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $logMessages = array(); $errorMessage = $this->delete($selection->getFiles(), $logMessages); if (count($logMessages)) { $logMessage = join("\n", $logMessages); } if ($errorMessage) { throw new AJXP_Exception($errorMessage); } AJXP_Logger::logAction("Delete", array("files" => $selection)); $reloadContextNode = true; break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "rename": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]); $this->rename($file, $filename_new); $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); $reloadContextNode = true; $pendingSelection = $filename_new; AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; $dirname = AJXP_Utils::processFileName(SystemTextEncoding::fromUTF8($httpVars["dirname"])); $error = $this->mkDir($dir, $dirname); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $pendingSelection = $dirname; $reloadContextNode = true; AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; $filename = AJXP_Utils::processFileName(SystemTextEncoding::fromUTF8($httpVars["filename"])); $error = $this->createEmptyFile($dir, $filename); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reloadContextNode = true; $pendingSelection = $dir . "/" . $filename; AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename)); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $messtmp = ""; $files = $selection->getFiles(); $changedFiles = array(); $chmod_value = $httpVars["chmod_value"]; $recursive = $httpVars["recursive"]; $recur_apply_to = $httpVars["recur_apply_to"]; foreach ($files as $fileName) { $error = $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles); } if (isset($error)) { throw new AJXP_Exception($error); } //$messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] "; $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders"; $reloadContextNode = true; AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($changedFiles))); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": AJXP_Logger::debug("Upload Files Data", $fileVars); $destination = $this->urlBase . SystemTextEncoding::fromPostedFileName($dir); AJXP_Logger::debug("Upload inside", array("destination" => $destination)); if (!$this->isWriteable($destination)) { $errorCode = 412; $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}."; AJXP_Logger::debug("Upload error 412", array("destination" => $destination)); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } foreach ($fileVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } $userfile_name = $boxData["name"]; $userfile_name = AJXP_Utils::processFileName($userfile_name); if (isset($httpVars["auto_rename"])) { $userfile_name = self::autoRenameForDest($destination, $userfile_name); } if (isset($boxData["input_upload"])) { try { AJXP_Logger::debug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen("{$destination}/" . $userfile_name, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); AJXP_Logger::debug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { if (!move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name)) { $errorCode = 411; $errorMessage = "{$mess['33']} " . $userfile_name; break; } } $this->changeMode($destination . "/" . $userfile_name); $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; AJXP_Logger::logAction("Upload File", array("file" => SystemTextEncoding::fromUTF8($dir) . "/" . $userfile_name)); } if (isset($errorMessage)) { AJXP_Logger::debug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { AJXP_Logger::debug("Return success"); return array("SUCCESS" => true); } return; break; //------------------------------------ // Public URL //------------------------------------ //------------------------------------ // Public URL //------------------------------------ case "public_url": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $url = $this->makePubliclet($file, $httpVars["password"], $httpVars["expiration"]); header("Content-type:text/plain"); echo $url; exit(1); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a"); $startTime = microtime(); $dir = AJXP_Utils::securePath(SystemTextEncoding::magicDequote($dir)); $path = $this->urlBase . ($dir != "" ? "/" . $dir : ""); $threshold = $this->repository->getOption("PAGINATION_THRESHOLD"); if (!isset($threshold) || intval($threshold) == 0) { $threshold = 500; } $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER"); if (!isset($limitPerPage) || intval($limitPerPage) == 0) { $limitPerPage = 200; } $countFiles = $this->countFiles($path, !$lsOptions["f"]); if ($countFiles > $threshold) { $offset = 0; $crtPage = 1; if (isset($page)) { $offset = (intval($page) - 1) * $limitPerPage; $crtPage = $page; } $totalPages = floor($countFiles / $limitPerPage) + 1; } else { $offset = $limitPerPage = 0; } $metaData = array(); $crtLabel = AJXP_Utils::xmlEntities(basename($dir), true); if (RecycleBinManager::recycleEnabled()) { if (RecycleBinManager::currentLocationIsRecycle($dir)) { $metaData["ajxp_mime"] = "ajxp_recycle"; $crtLabel = AJXP_Utils::xmlEntities($mess[122]); } else { if ($dir == "") { $metaData["repo_has_recycle"] = "true"; } } } AJXP_XMLWriter::renderHeaderNode(AJXP_Utils::xmlEntities($dir, true), $crtLabel, false, $metaData); if (isset($totalPages) && isset($crtPage)) { AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages); if (!$lsOptions["f"]) { AJXP_XMLWriter::close(); exit(1); } } $cursor = 0; $handle = opendir($path); if (!$handle) { throw new AJXP_Exception("Cannot open dir " . $path); } $fullList = array("d" => array(), "z" => array(), "f" => array()); while (strlen($nodeName = readdir($handle)) > 0) { if ($nodeName == "." || $nodeName == "..") { continue; } $isLeaf = is_file($path . "/" . $nodeName) || AJXP_Utils::isBrowsableArchive($nodeName); if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) { continue; } if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) { continue; } $nodeType = "d"; if ($isLeaf) { if (AJXP_Utils::isBrowsableArchive($nodeName)) { if ($lsOptions["f"] && $lsOptions["z"]) { // See archives as files $nodeType = "f"; } else { $nodeType = "z"; } } else { $nodeType = "f"; } } if ($offset > 0 && $cursor < $offset) { $cursor++; continue; } if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) { break; } $metaData = array(); $currentFile = $path . "/" . $nodeName; $metaData["is_file"] = $isLeaf ? "1" : "0"; $metaData["filename"] = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($dir . "/" . $nodeName)); $metaData["icon"] = AJXP_Utils::mimetype($nodeName, "image", !$isLeaf); if ($metaData["icon"] == "folder.png") { $metaData["openicon"] = "folder_open.png"; } if (!is_file($currentFile) || AJXP_Utils::isBrowsableArchive($nodeName)) { $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?get_action=ls&options=dz&dir=" . $dir . "/" . $nodeName); $link = urlencode($link); $metaData["src"] = $link; } if ($lsOptions["l"]) { $metaData["file_group"] = @filegroup($currentFile) || "unknown"; $metaData["file_owner"] = @fileowner($currentFile) || "unknown"; $fPerms = @fileperms($currentFile); if ($fPerms !== false) { $fPerms = substr(decoct($fPerms), $isLeaf ? 2 : 1); } else { $fPerms = '0000'; } $metaData["file_perms"] = $fPerms; $metaData["mimestring"] = AJXP_Utils::mimetype($currentFile, "type", !$isLeaf); $datemodif = $this->date_modif($currentFile); $metaData["ajxp_modiftime"] = $datemodif ? $datemodif : "0"; $metaData["bytesize"] = 0; if ($isLeaf) { $metaData["bytesize"] = filesize($currentFile); } $metaData["filesize"] = AJXP_Utils::roundSize($metaData["bytesize"]); if (AJXP_Utils::isBrowsableArchive($nodeName)) { $metaData["ajxp_mime"] = "ajxp_browsable_archive"; } $realFile = null; // A reference to the real file. AJXP_Controller::applyHook("ls.metadata", array($currentFile, &$metaData, $this->wrapperClassName, &$realFile)); } $attributes = ""; foreach ($metaData as $key => $value) { $attributes .= "{$key}=\"{$value}\" "; } $renderNodeData = array(AJXP_Utils::xmlEntities($dir . "/" . $nodeName, true), AJXP_Utils::xmlEntities($nodeName, true), $isLeaf, $metaData); $fullList[$nodeType][$nodeName] = $renderNodeData; $cursor++; } foreach ($fullList as $key => $list) { uksort($list, 'strnatcasecmp'); $fullList[$key] = $list; } $allNodes = array_merge($fullList["d"], $fullList["z"], $fullList["f"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["d"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["z"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["f"]); // ADD RECYCLE BIN TO THE LIST if ($dir == "" && RecycleBinManager::recycleEnabled()) { $recycleBinOption = RecycleBinManager::getRelativeRecycle(); if (file_exists($this->urlBase . $recycleBinOption)) { $recycleIcon = $this->countFiles($this->urlBase . $recycleBinOption, false, true) > 0 ? "trashcan_full.png" : "trashcan.png"; AJXP_XMLWriter::renderNode($recycleBinOption, AJXP_Utils::xmlEntities($mess[122]), false, array("ajxp_modiftime" => $this->date_modif($this->urlBase . $recycleBinOption), "mimestring" => AJXP_Utils::xmlEntities($mess[122]), "icon" => "{$recycleIcon}", "filesize" => "-", "ajxp_mime" => "ajxp_recycle")); } } AJXP_Logger::debug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms"); AJXP_XMLWriter::close(); return; break; } $xmlBuffer = ""; if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if ($reloadContextNode) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false); } return $xmlBuffer; }
function listUsers($root, $child, $hashValue = null) { $columns = '<columns switchGridMode="filelist" template_name="ajxp_conf.users"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="10%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; if (AuthService::driverSupportsAuthSchemes()) { $columns = '<columns switchGridMode="filelist" template_name="ajxp_conf.users"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.115" attributeName="auth_scheme" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; } AJXP_XMLWriter::sendFilesListComponentConfig($columns); if (!AuthService::usersEnabled()) { return; } $count = AuthService::authCountUsers(); $USER_PER_PAGE = 50; if (empty($hashValue)) { $hashValue = 1; } if (AuthService::authSupportsPagination() && $count > $USER_PER_PAGE) { $offset = ($hashValue - 1) * $USER_PER_PAGE; AJXP_XMLWriter::renderPaginationData($count, $hashValue, ceil($count / $USER_PER_PAGE)); $users = AuthService::listUsers("", $offset, $USER_PER_PAGE); } else { $users = AuthService::listUsers(); } $mess = ConfService::getMessages(); $repos = ConfService::getRepositoriesList(); $loggedUser = AuthService::getLoggedUser(); $userArray = array(); foreach ($users as $userIndex => $userObject) { $label = $userObject->getId(); if ($userObject->hasParent()) { $label = $userObject->getParent() . "000" . $label; } $userArray[$label] = $userObject; } ksort($userArray); foreach ($userArray as $userObject) { $isAdmin = $userObject->isAdmin(); $userId = $userObject->getId(); $icon = "user" . ($userId == "guest" ? "_guest" : ($isAdmin ? "_admin" : "")); if ($userObject->hasParent()) { $icon = "user_child"; } $rightsString = ""; if ($isAdmin) { $rightsString = $mess["ajxp_conf.63"]; } else { $r = array(); foreach ($repos as $repoId => $repository) { if ($repository->getAccessType() == "ajxp_shared") { continue; } if (!$userObject->canRead($repoId) && !$userObject->canWrite($repoId)) { continue; } $rs = $userObject->canRead($repoId) ? "r" : ""; $rs .= $userObject->canWrite($repoId) ? "w" : ""; $r[] = $repository->getDisplay() . " (" . $rs . ")"; } $rightsString = implode(", ", $r); } $nodeLabel = $userId; $scheme = AuthService::getAuthScheme($userId); AJXP_XMLWriter::renderNode("/users/" . $userId, $nodeLabel, true, array("isAdmin" => $mess[$isAdmin ? "ajxp_conf.14" : "ajxp_conf.15"], "icon" => $icon . ".png", "auth_scheme" => $scheme != null ? $scheme : "", "rights_summary" => $rightsString, "ajxp_roles" => implode(", ", array_keys($userObject->getRoles())), "ajxp_mime" => "user" . ($userId != "guest" && $userId != $loggedUser->getId() ? "_editable" : ""))); } }
public function switchAction($action, $httpVars, $fileVars) { $repo = ConfService::getRepository(); if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); if (isset($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); } // FILTER DIR PAGINATION ANCHOR if (isset($dir) && strstr($dir, "%23") !== false) { $parts = explode("%23", $dir); $dir = $parts[0]; $page = $parts[1]; } if (isset($dest)) { $dest = SystemTextEncoding::fromUTF8($dest); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // ONLINE EDIT //------------------------------------ case "edit_record": $isNew = false; if (isset($record_is_new) && $record_is_new == "true") { $isNew = true; } $tableName = $_POST["table_name"]; $pkName = $_POST["pk_name"]; $query = ""; $arrValues = array(); foreach ($_POST as $key => $value) { if (substr($key, 0, strlen("ajxp_mysql_")) == "ajxp_mysql_") { $newKey = substr($key, strlen("ajxp_mysql_")); $arrValues[$newKey] = $value; } } if ($isNew) { $string = ""; $index = 0; foreach ($arrValues as $k => $v) { // CHECK IF AUTO KEY!!! $string .= "'" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'"; if ($index < count($arrValues) - 1) { $string .= ","; } $index++; } $query = "INSERT INTO {$tableName} VALUES ({$string})"; } else { $string = ""; $index = 0; foreach ($arrValues as $k => $v) { if ($k == $pkName) { $pkValue = $v; } else { $string .= $k . "='" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'"; if ($index < count($arrValues) - 1) { $string .= ","; } } $index++; } $query = "UPDATE {$tableName} SET {$string} WHERE {$pkName}='{$pkValue}'"; } $link = $this->createDbLink(); $res = $this->execQuery($query); $this->closeDbLink($link); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } break; //------------------------------------ // CHANGE COLUMNS OR CREATE TABLE //------------------------------------ //------------------------------------ // CHANGE COLUMNS OR CREATE TABLE //------------------------------------ case "edit_table": $link = $this->createDbLink(); if (isset($httpVars["current_table"])) { if (isset($httpVars["delete_column"])) { $query = "ALTER TABLE " . $httpVars["current_table"] . " DROP COLUMN " . $httpVars["delete_column"]; $res = $this->execQuery($query); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; } if (isset($httpVars["add_column"])) { $defString = $this->makeColumnDef($httpVars, "add_field_"); $query = "ALTER TABLE " . $httpVars["current_table"] . " ADD COLUMN ({$defString})"; if (isset($httpVars["add_field_pk"]) && $httpVars["add_field_pk"] == "1") { $query .= ", ADD PRIMARY KEY (" . $httpVars["add_field_name"] . ")"; } if (isset($httpVars["add_field_index"]) && $httpVars["add_field_index"] == "1") { $query .= ", ADD INDEX (" . $httpVars["add_field_name"] . ")"; } if (isset($httpVars["add_field_uniq"]) && $httpVars["add_field_uniq"] == "1") { $query .= ", ADD UNIQUE (" . $httpVars["add_field_name"] . ")"; } $res = $this->execQuery($query); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; } } $fields = array("origname", "name", "default", "null", "size", "type", "flags", "pk", "index", "uniq"); $rows = array(); foreach ($httpVars as $k => $val) { $split = explode("_", $k); if (count($split) == 3 && $split[0] == "field" && is_numeric($split[2]) && in_array($split[1], $fields)) { if (!isset($rows[intval($split[2])])) { $rows[intval($split[2])] = array(); } $rows[intval($split[2])][$split[1]] = $val; } else { if (count($split) == 2 && $split[0] == "field" && in_array($split[1], $fields)) { if (!isset($rows[0])) { $rows[0] = array(); } $rows[0][$split[1]] = $val; } } } if (isset($current_table)) { $qMessage = ''; foreach ($rows as $row) { $sizeString = $row["size"] != "" ? "(" . $row["size"] . ")" : ""; $defString = $row["default"] != "" ? " DEFAULT " . $row["default"] . "" : ""; $query = "ALTER TABLE {$current_table} CHANGE " . $row["origname"] . " " . $row["name"] . " " . $row["type"] . $sizeString . $defString . " " . $row["null"]; $res = $this->execQuery(trim($query)); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; $this->closeDbLink($link); break; } else { $qMessage .= $query; $reload_file_list = true; } } $logMessage = $qMessage; } else { if (isset($new_table)) { $fieldsDef = array(); $pks = array(); $indexes = array(); $uniqs = array(); foreach ($rows as $index => $row) { $fieldsDef[] = $this->makeColumnDef($row); // Analyse keys if ($row["pk"] == "1") { $pks[] = $row["name"]; } if ($row["index"] == "1") { $indexes[] = $row["name"]; } if ($row["uniq"] == "1") { $uniqs[] = $row["name"]; } } $fieldsDef = implode(",", $fieldsDef); if (count($pks)) { $fieldsDef .= ",PRIMARY KEY (" . implode(",", $pks) . ")"; } if (count($indexes)) { $fieldsDef .= ",INDEX (" . implode(",", $indexes) . ")"; } if (count($uniqs)) { $fieldsDef .= ",UNIQUE (" . implode(",", $uniqs) . ")"; } $query = "CREATE TABLE {$new_table} ({$fieldsDef})"; $res = $this->execQuery(trim($query)); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; $reload_current_node = true; } } } $this->closeDbLink($link); break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete_table": case "delete_record": $dir = basename($dir); $link = $this->createDbLink(); if (trim($dir) == "") { // ROOT NODE => DROP TABLES $tables = $selection->getFiles(); $query = "DROP TABLE"; foreach ($tables as $index => $tableName) { $tables[$index] = basename($tableName); } $query .= " " . implode(",", $tables); $res = $this->execQuery($query); $reload_current_node = true; } else { // TABLE NODE => DELETE RECORDS $tableName = $dir; $pks = $selection->getFiles(); foreach ($pks as $key => $pkString) { $parts = explode(".", $pkString); array_pop($parts); // remove .pk extension array_shift($parts); // remove record prefix foreach ($parts as $index => $pkPart) { $parts[$index] = str_replace("__", "='", $pkPart) . "'"; } $pks[$key] = "(" . implode(" AND ", $parts) . ")"; } $query = "DELETE FROM {$tableName} WHERE " . implode(" OR ", $pks); $res = $this->execQuery($query); } //AJXP_Exception::errorToXml($res); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "set_query": $query = $httpVars["query"]; $_SESSION["LAST_SQL_QUERY"] = $query; print "<tree store=\"true\"></tree>"; break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $searchMode = $fileListMode = $completeMode = false; if (isset($mode)) { if ($mode == "search") { $searchMode = true; } else { if ($mode == "file_list") { $fileListMode = true; } else { if ($mode == "complete") { $completeMode = true; } } } } $link = $this->createDbLink(); //AJXP_Exception::errorToXml($link); if ($dir == "") { AJXP_XMLWriter::header(); $tables = $this->listTables(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist"><column messageString="Table Name" attributeName="ajxp_label" sortType="String"/><column messageString="Byte Size" attributeName="bytesize" sortType="NumberKo"/><column messageString="Count" attributeName="count" sortType="Number"/></columns>'); $icon = $mode == "file_list" ? "sql_images/mimes/ICON_SIZE/table_empty.png" : "sql_images/mimes/ICON_SIZE/table_empty_tree.png"; foreach ($tables as $tableName) { $size = $this->getSize($tableName); $count = $this->getCount($tableName); print "<tree is_file=\"0\" text=\"{$tableName}\" filename=\"/{$tableName}\" bytesize=\"{$size}\" count=\"{$count}\" icon=\"{$icon}\" ajxp_mime=\"table\" />"; } print "<tree is_file=\"0\" text=\"Search Results\" ajxp_node=\"true\" filename=\"/ajxpmysqldriver_searchresults\" bytesize=\"-\" count=\"-\" icon=\"search.png\"/>"; AJXP_XMLWriter::close(); } else { $tableName = basename($dir); if (isset($page)) { $currentPage = $page; } else { $currentPage = 1; } $query = "SELECT * FROM {$tableName}"; $searchQuery = false; if ($tableName == "ajxpmysqldriver_searchresults") { if (isset($_SESSION["LAST_SQL_QUERY"])) { $query = $_SESSION["LAST_SQL_QUERY"]; $matches = array(); if (preg_match("/SELECT [\\S, ]* FROM (\\S*).*/i", $query, $matches) !== false) { $tableName = $matches[1]; $searchQuery = true; } else { break; } } else { break; } } if (isset($order_column)) { $query .= " ORDER BY {$order_column} " . strtoupper($order_direction); if (!isset($_SESSION["AJXP_ORDER_DATA"])) { $_SESSION["AJXP_ORDER_DATA"] = array(); } $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName] = array("column" => $order_column, "dir" => $order_direction); } else { if (isset($_SESSION["AJXP_ORDER_DATA"])) { if (isset($_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName])) { $order_column = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["column"]; $order_direction = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["dir"]; $query .= " ORDER BY {$order_column} " . strtoupper($order_direction); } } } try { $result = $this->showRecords($query, $tableName, $currentPage); } catch (AJXP_Exception $ex) { unset($_SESSION["LAST_SQL_QUERY"]); throw $ex; } AJXP_XMLWriter::header(); $blobCols = array(); $columnsString = '<columns switchDisplayMode="list" switchGridMode="grid">'; foreach ($result["COLUMNS"] as $col) { $columnsString .= "<column messageString=\"" . $col["NAME"] . "\" attributeName=\"" . $col["NAME"] . "\" field_name=\"" . $col["NAME"] . "\" field_type=\"" . $col["TYPE"] . "\" field_size=\"" . $col["LENGTH"] . "\" field_flags=\"" . $this->cleanFlagString($col["FLAGS"]) . "\" field_pk=\"" . (preg_match("/primary/", $col["FLAGS"]) ? "1" : "0") . "\" field_null=\"" . (preg_match("/not_null/", $col["FLAGS"]) ? "NOT_NULL" : "NULL") . "\" sortType=\"" . $this->sqlTypeToSortType($col["TYPE"]) . "\" field_default=\"" . $col["DEFAULT"] . "\"/>"; if (stristr($col["TYPE"], "blob") !== false && ($col["FLAGS"] != "" && stristr($col["FLAGS"], "binary"))) { $blobCols[] = $col["NAME"]; } } $columnsString .= '</columns>'; AJXP_XMLWriter::sendFilesListComponentConfig($columnsString); //print '<pagination total="'.$result["TOTAL_PAGES"].'" current="'.$currentPage.'" remote_order="true" currentOrderCol="'.$order_column.'" currentOrderDir="'.$order_direction.'"/>'; if ($result["TOTAL_PAGES"] > 1) { AJXP_XMLWriter::renderPaginationData($count, $currentPage, $result["TOTAL_PAGES"]); } foreach ($result["ROWS"] as $arbitIndex => $row) { print '<tree '; $pkString = ""; foreach ($row as $key => $value) { if (in_array($key, $blobCols)) { $sizeStr = " - NULL"; if (strlen($value)) { $sizeStr = " - " . AJXP_Utils::roundSize(strlen($value)); } print "{$key}=\"BLOB{$sizeStr}\" "; } else { $value = str_replace("\"", "", $value); $value = AJXP_Utils::xmlEntities($value); print $key . '="' . SystemTextEncoding::toUTF8($value) . '" '; if ($result["HAS_PK"] > 0) { if (in_array($key, $result["PK_FIELDS"])) { $pkString .= $key . "__" . $value . "."; } } } } if ($result["HAS_PK"] > 0) { print 'filename="record.' . $pkString . 'pk" '; print 'is_file="1" ajxp_mime="pk"/>'; } else { print 'filename="record_' . $arbitIndex . '.no_pk" '; print 'is_file="1" ajxp_mime="row"/>'; } } AJXP_XMLWriter::close(); } $this->closeDbLink($link); exit(1); 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); } if (isset($reload_current_node) && $reload_current_node == "true" || isset($reload_file_list)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", "", false); } return $xmlBuffer; }
public function applyAction($actionName, $httpVars, $fileVars) { $messages = ConfService::getMessages(); $repoId = $this->accessDriver->repository->getId(); if ($actionName == "search") { // TMP if (strpos($httpVars["query"], "keyword:") === 0) { $parts = explode(":", $httpVars["query"]); $this->applyAction("search_by_keyword", array("field" => $parts[1]), array()); return null; } require_once "Zend/Search/Lucene.php"; try { $index = $this->loadIndex($repoId, false); } catch (Exception $ex) { AJXP_XMLWriter::header(); if ($this->seemsCurrentlyIndexing($repoId, 3)) { AJXP_XMLWriter::sendMessage($messages["index.lucene.11"], null); } else { if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { AJXP_Controller::applyActionInBackground($repoId, "index", array()); sleep(2); AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $repoId), sprintf($messages["index.lucene.8"], "/"), true, 5); AJXP_XMLWriter::sendMessage($messages["index.lucene.7"], null); } else { AJXP_XMLWriter::sendMessage($messages["index.lucene.12"], null); } } AJXP_XMLWriter::close(); return null; } $textQuery = $httpVars["query"]; if ($this->getFilteredOption("AUTO_WILDCARD") === true && strlen($textQuery) > 0 && ctype_alnum($textQuery)) { if ($textQuery[0] == '"' && $textQuery[strlen($textQuery) - 1] == '"') { $textQuery = substr($textQuery, 1, -1); } else { if ($textQuery[strlen($textQuery) - 1] != "*") { $textQuery .= "*"; } } } if (strpos($textQuery, ":") !== false) { $textQuery = str_replace("ajxp_meta_ajxp_document_content:", "body:", $textQuery); $textQuery = $this->filterSearchRangesKeywords($textQuery); $query = "ajxp_scope:shared AND ({$textQuery})"; } else { if ((isset($this->metaFields) || $this->indexContent) && isset($httpVars["fields"])) { $sParts = array(); foreach (explode(",", $httpVars["fields"]) as $searchField) { if ($searchField == "filename") { $sParts[] = "basename:" . $textQuery; } else { if ($searchField == "ajxp_document_content") { $sParts[] = $textQuery; } else { if (in_array($searchField, $this->metaFields)) { $sParts[] = "ajxp_meta_" . $searchField . ":" . $textQuery; } else { if ($searchField == "ajxp_document_content") { $sParts[] = "title:" . $textQuery; $sParts[] = "body:" . $textQuery; $sParts[] = "keywords:" . $textQuery; } } } } } $query = implode(" OR ", $sParts); $query = "ajxp_scope:shared AND ({$query})"; $this->logDebug("Query : {$query}"); } else { $index->setDefaultSearchField("basename"); $query = $this->filterSearchRangesKeywords($textQuery); } } $this->setDefaultAnalyzer(); if ($query == "*") { $index->setDefaultSearchField("ajxp_node"); $query = "yes"; $hits = $index->find($query, "node_url", SORT_STRING); } else { $hits = $index->find($query); } $commitIndex = false; if (isset($httpVars['return_selection'])) { $returnNodes = array(); } else { AJXP_XMLWriter::header(); } $cursor = 0; if (isset($httpVars['limit'])) { $limit = intval($httpVars['limit']); } if (!isset($returnNodes) && !empty($limit) && count($hits) > $limit) { AJXP_XMLWriter::renderPaginationData(count($hits), 1, 1); } foreach ($hits as $hit) { // Backward compatibility $hit->node_url = preg_replace("#ajxp\\.[a-z_]+://#", "pydio://", $hit->node_url); if ($hit->serialized_metadata != null) { $meta = unserialize(base64_decode($hit->serialized_metadata)); if (isset($meta["ajxp_modiftime"])) { $meta["ajxp_relativetime"] = $meta["ajxp_description"] = $messages[4] . " " . AJXP_Utils::relativeDate($meta["ajxp_modiftime"], $messages); } $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), $meta); } else { $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), array()); $tmpNode->loadNodeInfo(); } if ($tmpNode->getRepositoryId() != $repoId) { $this->logDebug(__CLASS__, "Strange case, search retrieves a node from wrong repository!"); $index->delete($hit->id); $commitIndex = true; continue; } if (!file_exists($tmpNode->getUrl())) { $index->delete($hit->id); $commitIndex = true; continue; } if (!is_readable($tmpNode->getUrl())) { continue; } $basename = basename($tmpNode->getPath()); $isLeaf = $tmpNode->isLeaf(); if (!$this->accessDriver->filterNodeName($tmpNode->getPath(), $basename, $isLeaf, array("d" => true, "f" => true))) { continue; } $tmpNode->search_score = sprintf("%0.2f", $hit->score); if (isset($returnNodes)) { $returnNodes[] = $tmpNode; } else { AJXP_XMLWriter::renderAjxpNode($tmpNode); } $cursor++; if (isset($limit) && $cursor >= $limit) { break; } } if (!isset($returnNodes)) { AJXP_XMLWriter::close(); } if ($commitIndex) { $index->commit(); } } else { if ($actionName == "search_by_keyword") { require_once "Zend/Search/Lucene.php"; $scope = "user"; try { $index = $this->loadIndex($repoId, false); } catch (Exception $ex) { AJXP_XMLWriter::header(); if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) { AJXP_Controller::applyActionInBackground($repoId, "index", array()); AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $repoId), sprintf($messages["index.lucene.8"], "/"), true, 2); } AJXP_XMLWriter::sendMessage($messages["index.lucene.7"], null); AJXP_XMLWriter::close(); return null; } $sParts = array(); $searchField = $httpVars["field"]; if ($searchField == "ajxp_node") { $sParts[] = "{$searchField}:yes"; } else { $sParts[] = "{$searchField}:true"; } if ($scope == "user" && AuthService::usersEnabled()) { if (AuthService::getLoggedUser() == null) { throw new Exception("Cannot find current user"); } $sParts[] = "ajxp_scope:user"; $sParts[] = "ajxp_user:"******"ajxp_scope:shared"; } $query = implode(" AND ", $sParts); $this->logDebug("Query : {$query}"); $hits = $index->find($query); $commitIndex = false; if (isset($httpVars['return_selection'])) { $returnNodes = array(); } else { AJXP_XMLWriter::header(); } foreach ($hits as $hit) { // Backward compat with old protocols $hit->node_url = preg_replace("#ajxp\\.[a-z_]+://#", "pydio://", $hit->node_url); if ($hit->serialized_metadata != null) { $meta = unserialize(base64_decode($hit->serialized_metadata)); $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), $meta); } else { $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), array()); $tmpNode->loadNodeInfo(); } if (!file_exists($tmpNode->getUrl())) { $index->delete($hit->id); $commitIndex = true; continue; } if (!is_readable($tmpNode->getUrl())) { continue; } $basename = basename($tmpNode->getPath()); $isLeaf = $tmpNode->isLeaf(); if (!$this->accessDriver->filterNodeName($tmpNode->getPath(), $basename, $isLeaf, array("d" => true, "f" => true))) { continue; } $tmpNode->search_score = sprintf("%0.2f", $hit->score); if (isset($returnNodes)) { $returnNodes[] = $tmpNode; } else { AJXP_XMLWriter::renderAjxpNode($tmpNode); } } if (!isset($returnNodes)) { AJXP_XMLWriter::close(); } if ($commitIndex) { $index->commit(); } } } if (isset($returnNodes)) { return $returnNodes; } else { return null; } }
public function listUsers($root, $child, $hashValue = null, $returnNodes = false, $findNodePosition = null) { $USER_PER_PAGE = 50; if ($root == "users") { $baseGroup = "/"; } else { $baseGroup = substr($root, strlen("users")); } if ($findNodePosition != null && $hashValue == null) { // Loop on each page to find the correct page. $count = AuthService::authCountUsers($baseGroup); $pages = ceil($count / $USER_PER_PAGE); for ($i = 0; $i < $pages; $i++) { $tests = $this->listUsers($root, $child, $i + 1, true, $findNodePosition); if (is_array($tests) && isset($tests["/data/" . $root . "/" . $findNodePosition])) { return array("/data/" . $root . "/" . $findNodePosition => str_replace("ajxp_mime", "page_position='" . ($i + 1) . "' ajxp_mime", $tests["/data/" . $root . "/" . $findNodePosition])); } } return array(); } $allNodes = array(); $columns = '<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.users"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="10%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; if (AuthService::driverSupportsAuthSchemes()) { $columns = '<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.users_authscheme"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.115" attributeName="auth_scheme" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; } if (!$returnNodes) { AJXP_XMLWriter::sendFilesListComponentConfig($columns); } if (!AuthService::usersEnabled()) { return; } if (empty($hashValue)) { $hashValue = 1; } $count = AuthService::authCountUsers($baseGroup); if (AuthService::authSupportsPagination() && $count >= $USER_PER_PAGE) { $offset = ($hashValue - 1) * $USER_PER_PAGE; if (!$returnNodes) { AJXP_XMLWriter::renderPaginationData($count, $hashValue, ceil($count / $USER_PER_PAGE)); } $users = AuthService::listUsers($baseGroup, "", $offset, $USER_PER_PAGE); if ($hashValue == 1) { $groups = AuthService::listChildrenGroups($baseGroup); } else { $groups = array(); } } else { $users = AuthService::listUsers($baseGroup); $groups = AuthService::listChildrenGroups($baseGroup); } foreach ($groups as $groupId => $groupLabel) { $nodeKey = "/data/" . $root . "/" . ltrim($groupId, "/"); $meta = array("icon" => "users-folder.png", "ajxp_mime" => "group"); if (in_array($nodeKey, $this->currentBookmarks)) { $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png")); } $xml = AJXP_XMLWriter::renderNode($nodeKey, $groupLabel, false, $meta, true, false); if (!$returnNodes) { print $xml; } else { $allNodes[$nodeKey] = $xml; } } $mess = ConfService::getMessages(); $repos = ConfService::getRepositoriesList("all"); $loggedUser = AuthService::getLoggedUser(); $userArray = array(); foreach ($users as $userIndex => $userObject) { $label = $userObject->getId(); if ($userObject->hasParent()) { $label = $userObject->getParent() . "000" . $label; } else { $children = ConfService::getConfStorageImpl()->getUserChildren($label); foreach ($children as $addChild) { $userArray[$label . "000" . $addChild->getId()] = $addChild; } } $userArray[$label] = $userObject; } ksort($userArray); foreach ($userArray as $userObject) { $isAdmin = $userObject->isAdmin(); $userId = $userObject->getId(); $icon = "user" . ($userId == "guest" ? "_guest" : ($isAdmin ? "_admin" : "")); if ($userObject->hasParent()) { $icon = "user_child"; } $rightsString = ""; if ($isAdmin) { $rightsString = $mess["ajxp_conf.63"]; } else { $r = array(); foreach ($repos as $repoId => $repository) { if ($repository->getAccessType() == "ajxp_shared") { continue; } if (!$userObject->canRead($repoId) && !$userObject->canWrite($repoId)) { continue; } $rs = $userObject->canRead($repoId) ? "r" : ""; $rs .= $userObject->canWrite($repoId) ? "w" : ""; $r[] = $repository->getDisplay() . " (" . $rs . ")"; } $rightsString = implode(", ", $r); } $nodeLabel = $userId; $test = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, ""); if (!empty($test)) { $nodeLabel = $test; } $scheme = AuthService::getAuthScheme($userId); $nodeKey = "/data/{$root}/" . $userId; $roles = array_filter(array_keys($userObject->getRoles()), array($this, "filterReservedRoles")); $meta = array("isAdmin" => $mess[$isAdmin ? "ajxp_conf.14" : "ajxp_conf.15"], "icon" => $icon . ".png", "auth_scheme" => $scheme != null ? $scheme : "", "rights_summary" => $rightsString, "ajxp_roles" => implode(", ", $roles), "ajxp_mime" => "user" . ($userId != "guest" && $userId != $loggedUser->getId() ? "_editable" : "")); if (in_array($nodeKey, $this->currentBookmarks)) { $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png")); } $xml = AJXP_XMLWriter::renderNode($nodeKey, $nodeLabel, true, $meta, true, false); if (!$returnNodes) { print $xml; } else { $allNodes[$nodeKey] = $xml; } } return $allNodes; }