function buildPublicHtaccessContent() { $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); $dlURL = ConfService::getCoreConf("PUBLIC_DOWNLOAD_URL"); if ($dlURL != "") { $url = rtrim($dlURL, "/"); } else { $fullUrl = AJXP_Utils::detectServerURL(true); $url = str_replace("\\", "/", rtrim($fullUrl, "/") . rtrim(str_replace(AJXP_INSTALL_PATH, "", $downloadFolder), "/")); } $htaccessContent = "Order Deny,Allow\nAllow from all\n"; $htaccessContent .= "\n<Files \".ajxp_*\">\ndeny from all\n</Files>\n"; $path = parse_url($url, PHP_URL_PATH); $htaccessContent .= ' <IfModule mod_rewrite.c> RewriteEngine on RewriteBase ' . $path . ' RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9_-]+)\\.php$ share.php?hash=$1 [QSA] RewriteRule ^([a-zA-Z0-9_-]+)--([a-z]+)$ share.php?hash=$1&lang=$2 [QSA] RewriteRule ^([a-zA-Z0-9_-]+)$ share.php?hash=$1 [QSA] </IfModule> '; return $htaccessContent; }
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 listSharedFiles() { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"> <column messageId="ajxp_shared.4" attributeName="ajxp_label" sortType="String" width="20%"/> <column messageId="ajxp_shared.17" attributeName="download_url" sortType="String" width="20%"/> <column messageId="ajxp_shared.20" attributeName="download_count" sortType="String" width="2%"/> <column messageId="share_center.22" attributeName="download_limit" sortType="String" width="2%"/> <column messageId="ajxp_shared.6" attributeName="password" sortType="String" width="5%"/> <column messageId="ajxp_shared.7" attributeName="expiration" sortType="String" width="5%"/> </columns>'); $dlFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); if (!is_dir($dlFolder)) { return; } $files = glob($dlFolder . "/*.php"); if (!is_array($files)) { return; } $mess = ConfService::getMessages(); $loggedUser = AuthService::getLoggedUser(); $userId = $loggedUser->getId(); $dlURL = ConfService::getCoreConf("PUBLIC_DOWNLOAD_URL"); if ($dlURL != "") { $downloadBase = rtrim($dlURL, "/"); } else { $fullUrl = AJXP_Utils::detectServerURL() . dirname($_SERVER['REQUEST_URI']); $downloadBase = str_replace("\\", "/", $fullUrl . rtrim(str_replace(AJXP_INSTALL_PATH, "", $dlFolder), "/")); } foreach ($files as $file) { $ar = explode(".", basename($file)); $id = array_shift($ar); if ($ar[0] != "php") { continue; } //if(strlen($id) != 32) continue; $publicletData = ShareCenter::loadPublicletData($id); if (isset($publicletData["OWNER_ID"]) && $publicletData["OWNER_ID"] != $userId) { continue; } $expired = $publicletData["EXPIRE_TIME"] != 0 ? $publicletData["EXPIRE_TIME"] < time() ? true : false : false; if (!is_a($publicletData["REPOSITORY"], "Repository")) { continue; } AJXP_XMLWriter::renderNode(str_replace(".php", "", basename($file)), "" . SystemTextEncoding::toUTF8($publicletData["REPOSITORY"]->getDisplay()) . ":/" . SystemTextEncoding::toUTF8($publicletData["FILE_PATH"]), true, array("icon" => "html.png", "password" => $publicletData["PASSWORD"] != "" ? $publicletData["PASSWORD"] : "******", "expiration" => $publicletData["EXPIRE_TIME"] != 0 ? ($expired ? "[!]" : "") . date($mess["date_format"], $publicletData["EXPIRE_TIME"]) : "-", "download_count" => $publicletData["DOWNLOAD_COUNT"], "download_limit" => $publicletData["DOWNLOAD_LIMIT"] == 0 ? "-" : $publicletData["DOWNLOAD_LIMIT"], "integrity" => !$publicletData["SECURITY_MODIFIED"] ? $mess["ajxp_shared.15"] : $mess["ajxp_shared.16"], "download_url" => $downloadBase . "/" . basename($file), "ajxp_mime" => "shared_file")); } }
/** * @param $httpVars * @param $repository * @param $accessDriver * @return array An array containing the hash (0) and the generated url (1) */ public function createSharedMinisite($httpVars, $repository, $accessDriver) { $uniqueUser = null; if (isset($httpVars["create_guest_user"])) { // Create a guest user $userId = substr(md5(time()), 0, 12); $pref = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId()); if (!empty($pref)) { $userId = $pref . $userId; } $userPass = substr(md5(time()), 13, 24); $httpVars["user_0"] = $userId; $httpVars["user_pass_0"] = $httpVars["shared_pass"] = $userPass; $httpVars["entry_type_0"] = "user"; $httpVars["right_read_0"] = isset($httpVars["simple_right_read"]) ? "true" : "false"; $httpVars["right_write_0"] = isset($httpVars["simple_right_write"]) ? "true" : "false"; $httpVars["right_watch_0"] = "false"; $httpVars["disable_download"] = isset($httpVars["simple_right_download"]) ? false : true; if ($httpVars["right_write_0"] == "false" && $httpVars["right_read_0"] == "false") { return "share_center.58"; } if ($httpVars["right_read_0"] == "false" && !$httpVars["disable_download"]) { $httpVars["right_read_0"] = "true"; } $uniqueUser = $userId; } $httpVars["minisite"] = true; $newRepo = $this->createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser); if (!is_a($newRepo, "Repository")) { return $newRepo; } $newId = $newRepo->getId(); $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); $this->initPublicFolder($downloadFolder); $data = array("REPOSITORY" => $newId, "PRELOG_USER" => $userId); if ($httpVars["disable_download"]) { $data["DOWNLOAD_DISABLED"] = true; } //$data["TRAVEL_PATH_TO_ROOT"] = $this->computeMinisiteToServerURL(); $data["AJXP_APPLICATION_BASE"] = AJXP_Utils::detectServerURL(true); $outputData = serialize($data); $hash = self::computeHash($outputData, $downloadFolder); $outputData = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $hash, $outputData, MCRYPT_MODE_ECB)); $fileData = "<" . "?" . "php \n" . ' require_once("' . str_replace("\\", "/", AJXP_INSTALL_PATH) . '/publicLet.inc.php"); ' . "\n" . ' $id = str_replace(".php", "", basename(__FILE__)); ' . "\n" . ' $cypheredData = base64_decode("' . $outputData . '"); ' . "\n" . ' $inputData = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $id, $cypheredData, MCRYPT_MODE_ECB), "\\0"); ' . "\n" . ' if (!ShareCenter::checkHash($inputData, $id)) { header("HTTP/1.0 401 Not allowed, script was modified"); exit(); } ' . "\n" . ' // Ok extract the data ' . "\n" . ' $data = unserialize($inputData); ShareCenter::loadMinisite($data); '; if (@file_put_contents($downloadFolder . "/" . $hash . ".php", $fileData) === FALSE) { return "Can't write to PUBLIC URL"; } @chmod($downloadFolder . "/" . $hash . ".php", 0755); $url = $this->buildPublicletLink($hash); AJXP_Controller::applyHook("node.share.create", array('type' => 'minisite', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url, 'new_repository' => &$newRepo)); return array($hash, $url); }
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $selectedNode = $selection->getUniqueNode(); $selectedNodeUrl = $selectedNode->getUrl(); if ($action == "post_to_server") { if (!is_writeable($selectedNodeUrl)) { header("Location:" . AJXP_Utils::detectServerURL(true) . "/plugins/editor.pixlr/fake_error_pixlr.php"); return false; } // 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)) { $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; } } } if (isset($header) && isset($header["location"])) { header("Location: {$header['location']}"); //$response"); } else { header("Location:" . AJXP_Utils::detectServerURL(true) . "/plugins/editor.pixlr/fake_error_pixlr.php"); } } else { if ($action == "retrieve_pixlr_image") { $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]); $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $file); $selectedNode->loadNodeInfo(); if (!is_writeable($selectedNode->getUrl())) { $this->logError("Pixlr Editor", "Trying to edit an unauthorized file " . $selectedNode->getUrl()); return false; } $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)) { $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 listSharedFiles() { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist" template_name="ajxp_conf.shared"> <column messageId="ajxp_shared.4" attributeName="ajxp_label" sortType="String" defaultWidth="30%"/> <column messageId="ajxp_shared.27" attributeName="owner" sortType="String" defaultWidth="10%"/> <column messageId="ajxp_shared.17" attributeName="download_url" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_shared.6" attributeName="password" sortType="String" defaultWidth="4%"/> <column messageId="ajxp_shared.7" attributeName="expiration" sortType="String" defaultWidth="4%"/> <column messageId="ajxp_shared.20" attributeName="expired" sortType="String" defaultWidth="4%"/> <column messageId="ajxp_shared.14" attributeName="integrity" sortType="String" defaultWidth="4%" hidden="true"/> </columns>'); $dlFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); if (!is_dir($dlFolder)) { return; } $files = glob($dlFolder . "/*.php"); if ($files === false) { return; } $mess = ConfService::getMessages(); $loggedUser = AuthService::getLoggedUser(); $userId = $loggedUser->getId(); $dlURL = ConfService::getCoreConf("PUBLIC_DOWNLOAD_URL"); if ($dlURL != "") { $downloadBase = rtrim($dlURL, "/"); } else { $fullUrl = AJXP_Utils::detectServerURL() . dirname($_SERVER['REQUEST_URI']); $downloadBase = str_replace("\\", "/", $fullUrl . rtrim(str_replace(AJXP_INSTALL_PATH, "", $dlFolder), "/")); } foreach ($files as $file) { $publicletData = $this->loadPublicletData($file); AJXP_XMLWriter::renderNode(str_replace(".php", "", basename($file)), "" . SystemTextEncoding::toUTF8($publicletData["REPOSITORY"]->getDisplay()) . ":/" . SystemTextEncoding::toUTF8($publicletData["FILE_PATH"]), true, array("icon" => "html.png", "password" => $publicletData["PASSWORD"] != "" ? $publicletData["PASSWORD"] : "******", "expiration" => $publicletData["EXPIRE_TIME"] != 0 ? date($mess["date_format"], $publicletData["EXPIRE_TIME"]) : "-", "expired" => $publicletData["EXPIRE_TIME"] != 0 ? $publicletData["EXPIRE_TIME"] < time() ? $mess["ajxp_shared.21"] : $mess["ajxp_shared.22"] : "-", "integrity" => !$publicletData["SECURITY_MODIFIED"] ? $mess["ajxp_shared.15"] : $mess["ajxp_shared.16"], "download_url" => $downloadBase . "/" . basename($file), "owner" => isset($publicletData["OWNER_ID"]) ? $publicletData["OWNER_ID"] : "-", "ajxp_mime" => "shared_file")); } }
/** * @return string */ public function getMainLink() { $repoId = $this->getNode()->getRepositoryId(); if (isset($_SESSION["CURRENT_MINISITE"])) { $hash = $_SESSION["CURRENT_MINISITE"]; $shareCenter = ShareCenter::getShareCenter(); if (!empty($shareCenter)) { return $shareCenter->buildPublicletLink($hash); } } return trim(AJXP_Utils::detectServerURL(true), "/") . "/?goto=" . $repoId . $this->node->getPath(); }
function buildPublicDlURL() { $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); $dlURL = ConfService::getCoreConf("PUBLIC_DOWNLOAD_URL"); $langSuffix = "?lang=" . ConfService::getLanguage(); if ($dlURL != "") { return rtrim($dlURL, "/"); } else { $fullUrl = AJXP_Utils::detectServerURL() . dirname($_SERVER['REQUEST_URI']); return str_replace("\\", "/", $fullUrl . rtrim(str_replace(AJXP_INSTALL_PATH, "", $downloadFolder), "/")); } }
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::getCurrentRootDirIndex(); $user->setArrayPref("history", "last_repository", $activeRepId); $user->save("user"); } //$logMessage = "Successfully Switched!"; AJXP_Logger::logAction("Switch Repository", array("rep. id" => $repository_id)); 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) { exit(1); } if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) { if ($httpVars["bm_action"] == "add_bookmark") { $title = ""; if (isset($httpVars["bm_title"])) { $title = $httpVars["bm_title"]; } if ($title == "" && $httpVars["bm_path"] == "/") { $title = ConfService::getCurrentRootDirDisplay(); } $bmUser->addBookMark(SystemTextEncoding::magicDequote($httpVars["bm_path"]), SystemTextEncoding::magicDequote($title)); } else { if ($httpVars["bm_action"] == "delete_bookmark") { $bmUser->removeBookmark($httpVars["bm_path"]); } else { if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) { $bmUser->renameBookmark($httpVars["bm_path"], $httpVars["bm_title"]); } } } } 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()); AJXP_XMLWriter::close(); exit(1); 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"; exit(1); break; //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ case "webdav_preferences": $userObject = AuthService::getLoggedUser(); $webdavActive = false; $passSet = 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") . "/"; if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) { $davData = $userObject->getPref("AJXP_WEBDAV_DATA"); 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_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#"; $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB, $iv)); } $davData["PASS"] = $password; } $userObject->setPref("AJXP_WEBDAV_DATA", $davData); $userObject->save("user"); } $davData = $userObject->getPref("AJXP_WEBDAV_DATA"); 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, "AjxpWebdavProvider") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) { $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug()); } } $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "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"); $repositories = ConfService::getRepositoriesList(); $pServ = AJXP_PluginsService::getInstance(); foreach ($repositories as $repo) { if (!$repo->isTemplate) { continue; } if (!$repo->getOption("TPL_USER_CAN_CREATE")) { continue; } $repoId = $repo->getUniqueId(); $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(); self::parseParameters($httpVars, $options); $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, AuthService::getLoggedUser()->getId()); $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[426]); } else { $loggedUser = AuthService::getLoggedUser(); // Make sure we do not overwrite otherwise loaded rights. $loggedUser->load(); $loggedUser->setRight($newRep->getUniqueId(), "rw"); $loggedUser->save("superuser"); 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->removeRights($repoId); $loggedUser->save("superuser"); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[428], null); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); 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; }
/** * Update some internal configs from httpVars * @param $httpVars * @throws Exception */ public function parseHttpVars($httpVars) { $data =& $this->internal; $data["DOWNLOAD_DISABLED"] = isset($httpVars["simple_right_download"]) ? false : true; $data["AJXP_APPLICATION_BASE"] = AJXP_Utils::detectServerURL(true); if (isset($httpVars["minisite_layout"])) { $data["AJXP_TEMPLATE_NAME"] = $httpVars["minisite_layout"]; } if (isset($httpVars["expiration"])) { if (intval($httpVars["expiration"]) > 0) { $data["EXPIRE_TIME"] = time() + intval($httpVars["expiration"]) * 86400; } else { if (isset($data["EXPIRE_TIME"])) { unset($data["EXPIRE_TIME"]); } } } if (isset($httpVars["downloadlimit"])) { if (intval($httpVars["downloadlimit"]) > 0) { $data["DOWNLOAD_LIMIT"] = intval($httpVars["downloadlimit"]); } else { if (isset($data["DOWNLOAD_LIMIT"])) { unset($data["DOWNLOAD_LIMIT"]); } } } if (isset($httpVars["custom_handle"]) && !empty($httpVars["custom_handle"]) && (!isset($this->hash) || $httpVars["custom_handle"] != $this->hash)) { // Existing already $value = AJXP_Utils::sanitize($httpVars["custom_handle"], AJXP_SANITIZE_ALPHANUM); $value = strtolower($value); if (strlen($value) < $this->store->hashMinLength) { $mess = ConfService::getMessages(); throw new Exception(str_replace("%s", $this->store->hashMinLength, $mess["share_center.223"])); } $test = $this->store->loadShare($value); $mess = ConfService::getMessages(); if (!empty($test)) { throw new Exception($mess["share_center.172"]); } if (!isset($this->hash)) { $this->hash = $value; } else { $this->newHash = $value; } } }
/** * @return string */ public function getMainLink() { $repoId = $this->getNode()->getRepositoryId(); return AJXP_Utils::detectServerURL(true) . "/?goto=" . $repoId . $this->node->getPath(); }
public static function loadMinisite($data, $hash = '', $error = null) { if (isset($data["SECURITY_MODIFIED"]) && $data["SECURITY_MODIFIED"] === true) { $mess = ConfService::getMessages(); $error = $mess['share_center.164']; } $repository = $data["REPOSITORY"]; AJXP_PluginsService::getInstance()->initActivePlugins(); $shareCenter = AJXP_PluginsService::findPlugin("action", "share"); $confs = $shareCenter->getConfigs(); $minisiteLogo = "plugins/gui.ajax/PydioLogo250.png"; if (!empty($confs["CUSTOM_MINISITE_LOGO"])) { $logoPath = $confs["CUSTOM_MINISITE_LOGO"]; if (strpos($logoPath, "plugins/") === 0 && is_file(AJXP_INSTALL_PATH . "/" . $logoPath)) { $minisiteLogo = $logoPath; } else { $minisiteLogo = "index_shared.php?get_action=get_global_binary_param&binary_id=" . $logoPath; } } // Default value if (isset($data["AJXP_TEMPLATE_NAME"])) { $templateName = $data["AJXP_TEMPLATE_NAME"]; if ($templateName == "ajxp_film_strip" && AJXP_Utils::userAgentIsMobile()) { $templateName = "ajxp_shared_folder"; } } if (isset($repository)) { $repoObject = ConfService::getRepositoryById($repository); if (!is_object($repoObject)) { $mess = ConfService::getMessages(); $error = $mess["share_center.166"]; $templateName = "ajxp_unique_strip"; $repoObject = null; } } if (!isset($templateName) && isset($repoObject)) { $filter = $repoObject->getContentFilter(); if (!empty($filter) && count($filter->virtualPaths) == 1) { $templateName = "ajxp_unique_strip"; } else { $templateName = "ajxp_shared_folder"; } } if (!isset($templateName) && isset($error)) { $templateName = "ajxp_unique_strip"; } // UPDATE TEMPLATE $html = file_get_contents(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/action.share/res/minisite.php"); AJXP_Controller::applyHook("tpl.filter_html", array(&$html)); $html = AJXP_XMLWriter::replaceAjxpXmlKeywords($html); $html = str_replace("AJXP_MINISITE_LOGO", $minisiteLogo, $html); $html = str_replace("AJXP_APPLICATION_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $html); $html = str_replace("PYDIO_APP_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $html); if (isset($repository) && isset($repoObject)) { $html = str_replace("AJXP_START_REPOSITORY", $repository, $html); $html = str_replace("AJXP_REPOSITORY_LABEL", ConfService::getRepositoryById($repository)->getDisplay(), $html); } $html = str_replace('AJXP_HASH_LOAD_ERROR', isset($error) ? $error : '', $html); $html = str_replace("AJXP_TEMPLATE_NAME", $templateName, $html); $html = str_replace("AJXP_LINK_HASH", $hash, $html); $guiConfigs = AJXP_PluginsService::findPluginById("gui.ajax")->getConfigs(); $html = str_replace("AJXP_THEME", $guiConfigs["GUI_THEME"], $html); if (isset($_GET["dl"]) && isset($_GET["file"])) { AuthService::$useSession = false; } else { session_name("AjaXplorer_Shared" . str_replace(".", "_", $hash)); session_start(); AuthService::disconnect(); } if (!empty($data["PRELOG_USER"])) { AuthService::logUser($data["PRELOG_USER"], "", true); $html = str_replace("AJXP_PRELOGED_USER", "ajxp_preloged_user", $html); } else { if (isset($data["PRESET_LOGIN"])) { $_SESSION["PENDING_REPOSITORY_ID"] = $repository; $_SESSION["PENDING_FOLDER"] = "/"; $html = str_replace("AJXP_PRELOGED_USER", $data["PRESET_LOGIN"], $html); } else { $html = str_replace("AJXP_PRELOGED_USER", "ajxp_legacy_minisite", $html); } } if (isset($hash)) { $_SESSION["CURRENT_MINISITE"] = $hash; } if (isset($_GET["dl"]) && isset($_GET["file"]) && (!isset($data["DOWNLOAD_DISABLED"]) || $data["DOWNLOAD_DISABLED"] === false)) { ConfService::switchRootDir($repository); ConfService::loadRepositoryDriver(); AJXP_PluginsService::deferBuildingRegistry(); AJXP_PluginsService::getInstance()->initActivePlugins(); AJXP_PluginsService::flushDeferredRegistryBuilding(); $errMessage = null; try { $params = $_GET; $ACTION = "download"; if (isset($_GET["ct"])) { $mime = pathinfo($params["file"], PATHINFO_EXTENSION); $editors = AJXP_PluginsService::searchAllManifests("//editor[contains(@mimes,'{$mime}') and @previewProvider='true']", "node", true, true, false); if (count($editors)) { foreach ($editors as $editor) { $xPath = new DOMXPath($editor->ownerDocument); $callbacks = $xPath->query("//action[@contentTypedProvider]", $editor); if ($callbacks->length) { $ACTION = $callbacks->item(0)->getAttribute("name"); if ($ACTION == "audio_proxy") { $params["file"] = "base64encoded:" . base64_encode($params["file"]); } break; } } } } AJXP_Controller::registryReset(); AJXP_Controller::findActionAndApply($ACTION, $params, null); } catch (Exception $e) { $errMessage = $e->getMessage(); } if ($errMessage == null) { return; } $html = str_replace('AJXP_HASH_LOAD_ERROR', $errMessage, $html); } if (isset($_GET["lang"])) { $loggedUser =& AuthService::getLoggedUser(); if ($loggedUser != null) { $loggedUser->setPref("lang", $_GET["lang"]); } else { setcookie("AJXP_lang", $_GET["lang"]); } } if (!empty($data["AJXP_APPLICATION_BASE"])) { $tPath = $data["AJXP_APPLICATION_BASE"]; } else { $tPath = !empty($data["TRAVEL_PATH_TO_ROOT"]) ? $data["TRAVEL_PATH_TO_ROOT"] : "../.."; } $serverBaseUrl = AJXP_Utils::detectServerURL(true); // Update Host dynamically if it differ from registered one. $registeredHost = parse_url($tPath, PHP_URL_HOST); $currentHost = parse_url($serverBaseUrl, PHP_URL_HOST); if ($registeredHost != $currentHost) { $tPath = str_replace($registeredHost, $currentHost, $tPath); } // Update scheme dynamically if it differ from registered one. $registeredScheme = parse_url($tPath, PHP_URL_SCHEME); $currentScheme = parse_url($serverBaseUrl, PHP_URL_SCHEME); if ($registeredScheme != $currentScheme) { $tPath = str_replace($registeredScheme . "://", $currentScheme . "://", $tPath); } $html = str_replace("AJXP_PATH_TO_ROOT", rtrim($tPath, "/") . "/", $html); HTMLWriter::internetExplorerMainDocumentHeader(); HTMLWriter::charsetHeader(); echo $html; }
private function initCacheWithNamespace($namespace) { $cacheDriver = null; $driverOptions = $this->getFilteredOption("DRIVER"); $cachePrefix = $this->getFilteredOption("CACHE_PREFIX"); if (!is_array($driverOptions) || !isset($driverOptions['driver'])) { return null; } switch ($driverOptions['driver']) { case "apc": $cacheDriver = $this->_apc_init($driverOptions); break; case "memcache": $cacheDriver = $this->_memcache_init($driverOptions); break; case "memcached": $cacheDriver = $this->_memcached_init($driverOptions); break; case "redis": $cacheDriver = $this->_redis_init($driverOptions); break; case "xcache": $cacheDriver = $this->_xcache_init($driverOptions); break; default: break; } if (empty($cacheDriver)) { return null; } if (empty($cachePrefix)) { $cachePrefix = AJXP_Utils::slugify(AJXP_Utils::detectServerURL(true)); } $cachePrefix .= "_" . $namespace . "_"; $cacheDriver->setNamespace($cachePrefix); return $cacheDriver; }
/** * Build download folder URL from configuration and current URL * @return string|null */ public function getPublicDownloadUrl() { $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); $dlURL = ConfService::getCoreConf("PUBLIC_DOWNLOAD_URL"); if (!empty($dlURL)) { $parts = parse_url($dlURL); if ($parts['scheme']) { return rtrim($dlURL, "/"); } else { $host = AJXP_Utils::detectServerURL(); return rtrim($host, "/") . "/" . trim($dlURL, "/"); } } else { $fullUrl = AJXP_Utils::detectServerURL(true); return str_replace("\\", "/", rtrim($fullUrl, "/") . rtrim(str_replace(AJXP_INSTALL_PATH, "", $downloadFolder), "/")); } }
/** * @param string $className * @return void */ function AJXP_Sabre_autoload($className) { if (strpos($className, 'AJXP_Sabre_') === 0) { include AJXP_BIN_FOLDER . '/sabredav/ajaxplorer/class.' . $className . '.php'; } } spl_autoload_register('AJXP_Sabre_autoload'); include 'core/classes/sabredav/lib/Sabre/autoload.php'; if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") { $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST"); } else { $baseURL = AJXP_Utils::detectServerURL(); } $baseURI = ConfService::getCoreConf("WEBDAV_BASEURI"); $requestUri = $_SERVER["REQUEST_URI"]; $end = trim(substr($requestUri, strlen($baseURI . "/"))); $rId = null; if ((!empty($end) || $end === "0") && $end[0] != "?") { $parts = explode("/", $end); $pathBase = $parts[0]; $repositoryId = $pathBase; $repository = ConfService::getRepositoryById($repositoryId); if ($repository == null) { $repository = ConfService::getRepositoryByAlias($repositoryId); if ($repository != null) { $repositoryId = $repository->getId(); }
/** * @param String $shareId * @param Array $shareData * @param AJXP_Node $node * @throws Exception * @return array|bool */ public function shareToJson($shareId, $shareData, $node = null) { $messages = ConfService::getMessages(); $jsonData = array(); $elementWatch = false; if ($shareData["type"] == "file") { $pData = $this->getShareStore()->loadShare($shareId); if (!count($pData)) { return false; } foreach ($this->getShareStore()->modifiableShareKeys as $key) { if (isset($pData[$key])) { $shareData[$key] = $pData[$key]; } } if ($pData["OWNER_ID"] != AuthService::getLoggedUser()->getId() && !AuthService::getLoggedUser()->isAdmin()) { throw new Exception($messages["share_center.48"]); } if (isset($shareData["short_form_url"])) { $link = $shareData["short_form_url"]; } else { $link = $this->buildPublicletLink($shareId); } if ($this->watcher != false && $node != null) { $result = array(); $elementWatch = $this->watcher->hasWatchOnNode($node, AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_USERS_NAMESPACE, $result); if ($elementWatch && !in_array($shareId, $result)) { $elementWatch = false; } } $jsonData = array_merge(array("element_id" => $shareId, "publiclet_link" => $link, "download_counter" => $this->getShareStore()->getCurrentDownloadCounter($shareId), "download_limit" => $pData["DOWNLOAD_LIMIT"], "expire_time" => $pData["EXPIRE_TIME"] != 0 ? date($messages["date_format"], $pData["EXPIRE_TIME"]) : 0, "has_password" => !empty($pData["PASSWORD"]), "element_watch" => $elementWatch, "is_expired" => $this->shareStore->isShareExpired($shareId, $pData)), $shareData); } else { if ($shareData["type"] == "minisite" || $shareData["type"] == "repository") { $repoId = $shareId; if (strpos($repoId, "repo-") === 0) { // Legacy $repoId = str_replace("repo-", "", $repoId); $shareData["type"] = "repository"; } $minisite = $shareData["type"] == "minisite"; $minisiteIsPublic = false; $dlDisabled = false; $minisiteLink = ''; if ($minisite) { $minisiteData = $this->getShareStore()->loadShare($shareId); $repoId = $minisiteData["REPOSITORY"]; $minisiteIsPublic = isset($minisiteData["PRELOG_USER"]); $dlDisabled = isset($minisiteData["DOWNLOAD_DISABLED"]) && $minisiteData["DOWNLOAD_DISABLED"] === true; if (isset($shareData["short_form_url"])) { $minisiteLink = $shareData["short_form_url"]; } else { $minisiteLink = $this->buildPublicletLink($shareId); } } $notExistsData = array("error" => true, "repositoryId" => $repoId, "users_number" => 0, "label" => "Error - Cannot find shared data", "description" => "Cannot find repository", "entries" => array(), "element_watch" => false, "repository_url" => ""); $repo = ConfService::getRepositoryById($repoId); if ($repoId == null || $repo == null && $node != null) { if ($minisite) { $this->removeShareFromMeta($node, $shareId); } return $notExistsData; } else { if (!AuthService::getLoggedUser()->isAdmin() && $repo->getOwner() != AuthService::getLoggedUser()->getId()) { return $notExistsData; } } if ($this->watcher != false && $node != null) { $elementWatch = $this->watcher->hasWatchOnNode(new AJXP_Node($this->baseProtocol . "://" . $repoId . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_NAMESPACE); } if ($node != null) { $sharedEntries = $this->computeSharedRepositoryAccessRights($repoId, true, $node->getUrl()); } else { $sharedEntries = $this->computeSharedRepositoryAccessRights($repoId, true, null); } $cFilter = $repo->getContentFilter(); if (!empty($cFilter)) { $cFilter = $cFilter->toArray(); } $jsonData = array("repositoryId" => $repoId, "users_number" => AuthService::countUsersForRepository($repoId), "label" => $repo->getDisplay(), "description" => $repo->getDescription(), "entries" => $sharedEntries, "element_watch" => $elementWatch, "repository_url" => AJXP_Utils::detectServerURL(true) . "?goto=" . $repo->getSlug() . "/", "content_filter" => $cFilter); if (isset($minisiteData)) { if (!empty($minisiteData["DOWNLOAD_LIMIT"]) && !$dlDisabled) { $jsonData["download_counter"] = $this->getShareStore()->getCurrentDownloadCounter($shareId); $jsonData["download_limit"] = $minisiteData["DOWNLOAD_LIMIT"]; } if (!empty($minisiteData["EXPIRE_TIME"])) { $delta = $minisiteData["EXPIRE_TIME"] - time(); $days = round($delta / (60 * 60 * 24)); $jsonData["expire_time"] = date($messages["date_format"], $minisiteData["EXPIRE_TIME"]); $jsonData["expire_after"] = $days; } else { $jsonData["expire_after"] = 0; } $jsonData["is_expired"] = $this->shareStore->isShareExpired($shareId, $minisiteData); if (isset($minisiteData["AJXP_TEMPLATE_NAME"])) { $jsonData["minisite_layout"] = $minisiteData["AJXP_TEMPLATE_NAME"]; } if (!$minisiteIsPublic) { $jsonData["has_password"] = true; } $jsonData["minisite"] = array("public" => $minisiteIsPublic ? "true" : "false", "public_link" => $minisiteLink, "disable_download" => $dlDisabled, "hash" => $shareId, "hash_is_shorten" => isset($shareData["short_form_url"])); foreach ($this->getShareStore()->modifiableShareKeys as $key) { if (isset($minisiteData[$key])) { $jsonData[$key] = $minisiteData[$key]; } } } } } return $jsonData; }
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 $httpVars * @param Repository $repository * @param AbstractAccessDriver $accessDriver * @return mixed An array containing the hash (0) and the generated url (1) */ public function createSharedMinisite($httpVars, $repository, $accessDriver) { $uniqueUser = null; if (isset($httpVars["repository_id"]) && isset($httpVars["guest_user_id"])) { $existingData = $this->getShareStore()->loadShare($httpVars["hash"]); $existingU = ""; if (isset($existingData["PRELOG_USER"])) { $existingU = $existingData["PRELOG_USER"]; } else { if (isset($existingData["PRESET_LOGIN"])) { $existingU = $existingData["PRESET_LOGIN"]; } } $uniqueUser = $httpVars["guest_user_id"]; if (isset($httpVars["guest_user_pass"]) && strlen($httpVars["guest_user_pass"]) && $uniqueUser == $existingU) { //$userPass = $httpVars["guest_user_pass"]; // UPDATE GUEST USER PASS HERE AuthService::updatePassword($uniqueUser, $httpVars["guest_user_pass"]); } else { if (isset($httpVars["guest_user_pass"]) && $httpVars["guest_user_pass"] == "") { } else { if (isset($existingData["PRESET_LOGIN"])) { $httpVars["KEEP_PRESET_LOGIN"] = true; } } } } else { if (isset($httpVars["create_guest_user"])) { // Create a guest user $userId = substr(md5(time()), 0, 12); $pref = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository); if (!empty($pref)) { $userId = $pref . $userId; } if (!empty($httpVars["guest_user_pass"])) { $userPass = $httpVars["guest_user_pass"]; } else { $userPass = substr(md5(time()), 13, 24); } $uniqueUser = $userId; } } if (isset($uniqueUser)) { if (isset($userPass)) { $httpVars["user_pass_0"] = $httpVars["shared_pass"] = $userPass; } $httpVars["user_0"] = $uniqueUser; $httpVars["entry_type_0"] = "user"; $httpVars["right_read_0"] = isset($httpVars["simple_right_read"]) ? "true" : "false"; $httpVars["right_write_0"] = isset($httpVars["simple_right_write"]) ? "true" : "false"; $httpVars["right_watch_0"] = "false"; $httpVars["disable_download"] = isset($httpVars["simple_right_download"]) ? false : true; if ($httpVars["right_read_0"] == "false" && !$httpVars["disable_download"]) { $httpVars["right_read_0"] = "true"; } if ($httpVars["right_write_0"] == "false" && $httpVars["right_read_0"] == "false") { return "share_center.58"; } } $httpVars["minisite"] = true; $httpVars["selection"] = true; if (!isset($userSelection)) { $userSelection = new UserSelection($repository, $httpVars); $setFilter = false; if ($userSelection->isUnique()) { $node = $userSelection->getUniqueNode(); $node->loadNodeInfo(); if ($node->isLeaf()) { $setFilter = true; $httpVars["file"] = "/"; $httpVars["nodes"] = array("/"); } } else { $setFilter = true; } $nodes = $userSelection->buildNodes(); $hasDir = false; $hasFile = false; foreach ($nodes as $n) { $n->loadNodeInfo(); if ($n->isLeaf()) { $hasFile = true; } else { $hasDir = true; } } if ($hasDir && !$this->getAuthorization("folder", "minisite") || $hasFile && !$this->getAuthorization("file")) { return 103; } if ($setFilter) { // Either it's a file, or many nodes are shared $httpVars["filter_nodes"] = $nodes; } if (!isset($httpVars["repo_label"])) { $first = $userSelection->getUniqueNode(); $httpVars["repo_label"] = SystemTextEncoding::toUTF8($first->getLabel()); } } $newRepo = $this->createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser); if (!is_a($newRepo, "Repository")) { return $newRepo; } $newId = $newRepo->getId(); $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); $this->initPublicFolder($downloadFolder); if (isset($existingData)) { $repo = ConfService::getRepositoryById($existingData["REPOSITORY"]); if ($repo == null) { throw new Exception("Oups, something went wrong"); } $this->getShareStore()->testUserCanEditShare($repo->getOwner()); $data = $existingData; } else { $data = array("REPOSITORY" => $newId); } if (isset($data["PRELOG_USER"])) { unset($data["PRELOG_USER"]); } if (isset($data["PRESET_LOGIN"])) { unset($data["PRESET_LOGIN"]); } if (isset($httpVars["create_guest_user"]) && isset($userId) || isset($httpVars["guest_user_id"])) { if (!isset($userId)) { $userId = $httpVars["guest_user_id"]; } if (empty($httpVars["guest_user_pass"]) && !isset($httpVars["KEEP_PRESET_LOGIN"])) { $data["PRELOG_USER"] = $userId; } else { $data["PRESET_LOGIN"] = $userId; } } $data["DOWNLOAD_DISABLED"] = $httpVars["disable_download"]; $data["AJXP_APPLICATION_BASE"] = AJXP_Utils::detectServerURL(true); if (isset($httpVars["minisite_layout"])) { $data["AJXP_TEMPLATE_NAME"] = $httpVars["minisite_layout"]; } if (isset($httpVars["expiration"])) { if (intval($httpVars["expiration"]) > 0) { $data["EXPIRE_TIME"] = time() + intval($httpVars["expiration"]) * 86400; } else { if (isset($data["EXPIRE_TIME"])) { unset($data["EXPIRE_TIME"]); } } } if (isset($httpVars["downloadlimit"])) { if (intval($httpVars["downloadlimit"]) > 0) { $data["DOWNLOAD_LIMIT"] = intval($httpVars["downloadlimit"]); } else { if (isset($data["DOWNLOAD_LIMIT"])) { unset($data["DOWNLOAD_LIMIT"]); } } } if (AuthService::usersEnabled()) { $data["OWNER_ID"] = AuthService::getLoggedUser()->getId(); } if (!isset($httpVars["repository_id"])) { try { $forceHash = null; if (isset($httpVars["custom_handle"]) && !empty($httpVars["custom_handle"])) { // Existing already $value = AJXP_Utils::sanitize($httpVars["custom_handle"], AJXP_SANITIZE_ALPHANUM); $value = strtolower($value); $test = $this->getShareStore()->loadShare($value); $mess = ConfService::getMessages(); if (!empty($test)) { throw new Exception($mess["share_center.172"]); } $forceHash = $value; } $hash = $this->getShareStore()->storeShare($repository->getId(), $data, "minisite", $forceHash); } catch (Exception $e) { return $e->getMessage(); } $url = $this->buildPublicletLink($hash); $files = $userSelection->getFiles(); $this->logInfo("New Share", array("file" => "'" . $httpVars['file'] . "'", "files" => $files, "url" => $url, "expiration" => $data['EXPIRE_TIME'], "limit" => $data['DOWNLOAD_LIMIT'], "repo_uuid" => $repository->uuid)); AJXP_Controller::applyHook("node.share.create", array('type' => 'minisite', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url, 'new_repository' => &$newRepo)); } else { try { $hash = $httpVars["hash"]; $updateHash = null; if (isset($httpVars["custom_handle"]) && !empty($httpVars["custom_handle"]) && $httpVars["custom_handle"] != $httpVars["hash"]) { // Existing already $value = AJXP_Utils::sanitize($httpVars["custom_handle"], AJXP_SANITIZE_ALPHANUM); $value = strtolower($value); $test = $this->getShareStore()->loadShare($value); if (!empty($test)) { throw new Exception("Sorry hash already exists"); } $updateHash = $value; } $hash = $this->getShareStore()->storeShare($repository->getId(), $data, "minisite", $hash, $updateHash); } catch (Exception $e) { return $e->getMessage(); } $url = $this->buildPublicletLink($hash); $this->logInfo("Update Share", array("file" => "'" . $httpVars['file'] . "'", "files" => "'" . $httpVars['file'] . "'", "url" => $url, "expiration" => $data['EXPIRE_TIME'], "limit" => $data['DOWNLOAD_LIMIT'], "repo_uuid" => $repository->uuid)); AJXP_Controller::applyHook("node.share.update", array('type' => 'minisite', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url, 'new_repository' => &$newRepo)); } return array($hash, $url); }