/** * @param UserSelection $userSelection */ function filterUserSelection(&$userSelection) { if ($userSelection->isEmpty()) { foreach ($this->filters as $path => $virtual) { $userSelection->addFile($path); } } else { $newFiles = array(); foreach ($userSelection->getFiles() as $f) { if (isset($this->virtualPaths[$f])) { $newFiles[] = $this->virtualPaths[$f]; } else { $testB = base64_decode($f); if (isset($this->virtualPaths[$testB])) { $newFiles[] = $this->virtualPaths[$testB]; } } } $userSelection->setFiles($newFiles); } }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $loggedUser = AuthService::getLoggedUser(); if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) { return; } if (AuthService::usersEnabled()) { $currentBookmarks = AuthService::getLoggedUser()->getBookmarks(); // FLATTEN foreach ($currentBookmarks as $bm) { $this->currentBookmarks[] = $bm["PATH"]; } } if ($action == "edit") { if (isset($httpVars["sub_action"])) { $action = $httpVars["sub_action"]; } } $mess = ConfService::getMessages(); $currentUserIsGroupAdmin = AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/"; if ($currentUserIsGroupAdmin && ConfService::getAuthDriverImpl()->isAjxpAdmin(AuthService::getLoggedUser()->getId())) { $currentUserIsGroupAdmin = false; } switch ($action) { //------------------------------------ // BASIC LISTING //------------------------------------ case "ls": $rootNodes = array("data" => array("LABEL" => $mess["ajxp_conf.110"], "ICON" => "user.png", "DESCRIPTION" => $mess["ajxp_conf.137"], "CHILDREN" => array("repositories" => array("AJXP_MIME" => "workspaces_zone", "LABEL" => $mess["ajxp_conf.3"], "DESCRIPTION" => $mess["ajxp_conf.138"], "ICON" => "hdd_external_unmount.png", "LIST" => "listRepositories"), "users" => array("AJXP_MIME" => "users_zone", "LABEL" => $mess["ajxp_conf.2"], "DESCRIPTION" => $mess["ajxp_conf.139"], "ICON" => "users-folder.png", "LIST" => "listUsers"), "roles" => array("AJXP_MIME" => "roles_zone", "LABEL" => $mess["ajxp_conf.69"], "DESCRIPTION" => $mess["ajxp_conf.140"], "ICON" => "user-acl.png", "LIST" => "listRoles"))), "config" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.109"], "ICON" => "preferences_desktop.png", "DESCRIPTION" => $mess["ajxp_conf.136"], "CHILDREN" => array("core" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.98"], "DESCRIPTION" => $mess["ajxp_conf.133"], "ICON" => "preferences_desktop.png", "LIST" => "listPlugins"), "plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.99"], "DESCRIPTION" => $mess["ajxp_conf.134"], "ICON" => "folder_development.png", "LIST" => "listPlugins"), "core_plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.123"], "DESCRIPTION" => $mess["ajxp_conf.135"], "ICON" => "folder_development.png", "LIST" => "listPlugins"))), "admin" => array("LABEL" => $mess["ajxp_conf.111"], "ICON" => "toggle_log.png", "DESCRIPTION" => $mess["ajxp_conf.141"], "CHILDREN" => array("logs" => array("LABEL" => $mess["ajxp_conf.4"], "DESCRIPTION" => $mess["ajxp_conf.142"], "ICON" => "toggle_log.png", "LIST" => "listLogFiles"), "diagnostic" => array("LABEL" => $mess["ajxp_conf.5"], "DESCRIPTION" => $mess["ajxp_conf.143"], "ICON" => "susehelpcenter.png", "LIST" => "printDiagnostic"))), "developer" => array("LABEL" => $mess["ajxp_conf.144"], "ICON" => "applications_engineering.png", "DESCRIPTION" => $mess["ajxp_conf.145"], "CHILDREN" => array("actions" => array("LABEL" => $mess["ajxp_conf.146"], "DESCRIPTION" => $mess["ajxp_conf.147"], "ICON" => "book.png", "LIST" => "listActions"), "hooks" => array("LABEL" => $mess["ajxp_conf.148"], "DESCRIPTION" => $mess["ajxp_conf.149"], "ICON" => "book.png", "LIST" => "listHooks")))); if ($currentUserIsGroupAdmin) { unset($rootNodes["config"]); unset($rootNodes["admin"]); unset($rootNodes["developer"]); } AJXP_Controller::applyHook("ajxp_conf.list_config_nodes", array(&$rootNodes)); $parentName = ""; $dir = trim(AJXP_Utils::decodeSecureMagic(isset($httpVars["dir"]) ? $httpVars["dir"] : ""), " /"); if ($dir != "") { $hash = null; if (strstr(urldecode($dir), "#") !== false) { list($dir, $hash) = explode("#", urldecode($dir)); } $splits = explode("/", $dir); $root = array_shift($splits); if (count($splits)) { $returnNodes = false; if (isset($httpVars["file"])) { $returnNodes = true; } $child = $splits[0]; if (isset($rootNodes[$root]["CHILDREN"][$child])) { $atts = array(); if ($child == "users") { $atts["remote_indexation"] = "admin_search"; } $callback = $rootNodes[$root]["CHILDREN"][$child]["LIST"]; if (is_string($callback) && method_exists($this, $callback)) { if (!$returnNodes) { AJXP_XMLWriter::header("tree", $atts); } $res = call_user_func(array($this, $callback), implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : ''); if (!$returnNodes) { AJXP_XMLWriter::close(); } } else { if (is_array($callback)) { $res = call_user_func($callback, implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : ''); } } if ($returnNodes) { AJXP_XMLWriter::header("tree", $atts); if (isset($res["/" . $dir . "/" . $httpVars["file"]])) { print $res["/" . $dir . "/" . $httpVars["file"]]; } AJXP_XMLWriter::close(); } return; } } else { $parentName = "/" . $root . "/"; $nodes = $rootNodes[$root]["CHILDREN"]; } } else { $parentName = "/"; $nodes = $rootNodes; } if (isset($httpVars["file"])) { $parentName = $httpVars["dir"] . "/"; $nodes = array(basename($httpVars["file"]) => array("LABEL" => basename($httpVars["file"]))); } if (isset($nodes)) { AJXP_XMLWriter::header(); if (!isset($httpVars["file"])) { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="detail"><column messageId="ajxp_conf.1" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.102" attributeName="description" sortType="String"/></columns>'); } foreach ($nodes as $key => $data) { $bmString = ''; if (in_array($parentName . $key, $this->currentBookmarks)) { $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" '; } if ($key == "users") { $bmString .= ' remote_indexation="admin_search"'; } if (isset($data["AJXP_MIME"])) { $bmString .= ' ajxp_mime="' . $data["AJXP_MIME"] . '"'; } if (empty($data["CHILDREN"])) { print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '/>'; } else { print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '>'; foreach ($data["CHILDREN"] as $cKey => $cData) { $bmString = ''; if (in_array($parentName . $key . "/" . $cKey, $this->currentBookmarks)) { $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" '; } if ($cKey == "users") { $bmString .= ' remote_indexation="admin_search"'; } if (isset($cData["AJXP_MIME"])) { $bmString .= ' ajxp_mime="' . $cData["AJXP_MIME"] . '"'; } print '<tree text="' . AJXP_Utils::xmlEntities($cData["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($cData["DESCRIPTION"]) . '" icon="' . $cData["ICON"] . '" filename="' . $parentName . $key . '/' . $cKey . '" ' . $bmString . '/>'; } print '</tree>'; } } AJXP_XMLWriter::close(); } break; case "stat": header("Content-type:application/json"); print '{"mode":true}'; return; break; case "clear_plugins_cache": AJXP_XMLWriter::header(); // Clear plugins cache if they exist AJXP_PluginsService::clearPluginsCache(); ConfService::clearMessagesCache(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . (AJXP_SKIP_CACHE ? "132" : "131")], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; case "create_group": if (isset($httpVars["group_path"])) { $basePath = AJXP_Utils::forwardSlashDirname($httpVars["group_path"]); if (empty($basePath)) { $basePath = "/"; } $gName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic(basename($httpVars["group_path"])), AJXP_SANITIZE_ALPHANUM); } else { $basePath = substr($httpVars["dir"], strlen("/data/users")); $gName = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["group_name"]), AJXP_SANITIZE_ALPHANUM); } $gLabel = AJXP_Utils::decodeSecureMagic($httpVars["group_label"]); AuthService::createGroup($basePath, $gName, $gLabel); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.124"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; case "create_role": $roleId = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["role_id"]), AJXP_SANITIZE_HTML_STRICT); if (!strlen($roleId)) { throw new Exception($mess[349]); } if (AuthService::getRole($roleId) !== false) { throw new Exception($mess["ajxp_conf.65"]); } $r = new AJXP_Role($roleId); if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) { $r->setGroupPath(AuthService::getLoggedUser()->getGroupPath()); } AuthService::updateRole($r); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null); AJXP_XMLWriter::reloadDataNode("", $httpVars["role_id"]); AJXP_XMLWriter::close(); break; case "edit_role": $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]); $roleGroup = false; $userObject = null; $groupLabel = null; if (strpos($roleId, "AJXP_GRP_") === 0) { $groupPath = substr($roleId, strlen("AJXP_GRP_")); $filteredGroupPath = AuthService::filterBaseGroup($groupPath); $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath)); $key = "/" . basename($groupPath); if (!array_key_exists($key, $groups)) { throw new Exception("Cannot find group with this id!"); } $roleId = "AJXP_GRP_" . $filteredGroupPath; $groupLabel = $groups[$key]; $roleGroup = true; } if (strpos($roleId, "AJXP_USR_") === 0) { $usrId = str_replace("AJXP_USR_/", "", $roleId); $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId); if (!AuthService::canAdministrate($userObject)) { throw new Exception("Cant find user!"); } $role = $userObject->personalRole; } else { $role = AuthService::getRole($roleId, $roleGroup); } if ($role === false) { throw new Exception("Cant find role! "); } if (isset($httpVars["format"]) && $httpVars["format"] == "json") { HTMLWriter::charsetHeader("application/json"); $roleData = $role->getDataArray(true); $allReps = ConfService::getRepositoriesList("all", false); $repos = array(); if (!empty($userObject)) { // USER foreach ($allReps as $repositoryId => $repositoryObject) { if (!AuthService::canAssign($repositoryObject, $userObject) || $repositoryObject->isTemplate || $repositoryObject->getAccessType() == "ajxp_conf" && !$userObject->isAdmin() || $repositoryObject->getUniqueUser() != null && $repositoryObject->getUniqueUser() != $userObject->getId()) { continue; } $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay()); } } else { foreach ($allReps as $repositoryId => $repositoryObject) { if (!AuthService::canAdministrate($repositoryObject)) { continue; } $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay()); } } // Make sure it's utf8 $data = array("ROLE" => $roleData, "ALL" => array("REPOSITORIES" => $repos)); if (isset($userObject)) { $data["USER"] = array(); $data["USER"]["LOCK"] = $userObject->getLock(); $data["USER"]["PROFILE"] = $userObject->getProfile(); $data["ALL"]["PROFILES"] = array("standard|Standard", "admin|Administrator", "shared|Shared", "guest|Guest"); $data["USER"]["ROLES"] = array_keys($userObject->getRoles()); $data["ALL"]["ROLES"] = array_keys(AuthService::getRolesList(array(), true)); if (isset($userObject->parentRole)) { $data["PARENT_ROLE"] = $userObject->parentRole->getDataArray(); } } else { if (isset($groupPath)) { $data["GROUP"] = array("PATH" => $groupPath, "LABEL" => $groupLabel); } } $scope = "role"; if ($roleGroup) { $scope = "group"; } else { if (isset($userObject)) { $scope = "user"; } } $data["SCOPE_PARAMS"] = array(); $nodes = AJXP_PluginsService::getInstance()->searchAllManifests("//param[contains(@scope,'" . $scope . "')]|//global_param[contains(@scope,'" . $scope . "')]", "node", false, true, true); foreach ($nodes as $node) { $pId = $node->parentNode->parentNode->attributes->getNamedItem("id")->nodeValue; $origName = $node->attributes->getNamedItem("name")->nodeValue; $node->attributes->getNamedItem("name")->nodeValue = "AJXP_REPO_SCOPE_ALL/" . $pId . "/" . $origName; $nArr = array(); foreach ($node->attributes as $attrib) { $nArr[$attrib->nodeName] = AJXP_XMLWriter::replaceAjxpXmlKeywords($attrib->nodeValue); } $data["SCOPE_PARAMS"][] = $nArr; } echo json_encode($data); } break; case "post_json_role": $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]); $roleGroup = false; $userObject = $usrId = $filteredGroupPath = null; if (strpos($roleId, "AJXP_GRP_") === 0) { $groupPath = substr($roleId, strlen("AJXP_GRP_")); $filteredGroupPath = AuthService::filterBaseGroup($groupPath); $roleId = "AJXP_GRP_" . $filteredGroupPath; $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath)); $key = "/" . basename($groupPath); if (!array_key_exists($key, $groups)) { throw new Exception("Cannot find group with this id!"); } $groupLabel = $groups[$key]; $roleGroup = true; } if (strpos($roleId, "AJXP_USR_") === 0) { $usrId = str_replace("AJXP_USR_/", "", $roleId); $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId); if (!AuthService::canAdministrate($userObject)) { throw new Exception("Cannot post role for user " . $usrId); } $originalRole = $userObject->personalRole; } else { // second param = create if not exists. $originalRole = AuthService::getRole($roleId, $roleGroup); } if ($originalRole === false) { throw new Exception("Cant find role! "); } $jsonData = SystemTextEncoding::magicDequote($httpVars["json_data"]); $data = json_decode($jsonData, true); $roleData = $data["ROLE"]; $forms = $data["FORMS"]; $binariesContext = array(); if (isset($userObject)) { $binariesContext = array("USER" => $userObject->getId()); } foreach ($forms as $repoScope => $plugData) { foreach ($plugData as $plugId => $formsData) { $parsed = array(); AJXP_Utils::parseStandardFormParameters($formsData, $parsed, $userObject != null ? $usrId : null, "ROLE_PARAM_", $binariesContext, AJXP_Role::$cypheredPassPrefix); $roleData["PARAMETERS"][$repoScope][$plugId] = $parsed; } } $existingParameters = $originalRole->listParameters(true); $this->mergeExistingParameters($roleData["PARAMETERS"], $existingParameters); if (isset($userObject) && isset($data["USER"]) && isset($data["USER"]["PROFILE"])) { $userObject->setAdmin($data["USER"]["PROFILE"] == "admin"); $userObject->setProfile($data["USER"]["PROFILE"]); } if (isset($data["GROUP_LABEL"]) && isset($groupLabel) && $groupLabel != $data["GROUP_LABEL"]) { ConfService::getConfStorageImpl()->relabelGroup($filteredGroupPath, $data["GROUP_LABEL"]); } if ($currentUserIsGroupAdmin) { // FILTER DATA FOR GROUP ADMINS $params = $this->getEditableParameters(false); foreach ($roleData["PARAMETERS"] as $scope => &$plugsParameters) { foreach ($plugsParameters as $paramPlugin => &$parameters) { foreach ($parameters as $pName => $pValue) { if (!isset($params[$paramPlugin]) || !in_array($pName, $params[$paramPlugin])) { unset($parameters[$pName]); } } if (!count($parameters)) { unset($plugsParameters[$paramPlugin]); } } if (!count($plugsParameters)) { unset($roleData["PARAMETERS"][$scope]); } } // Remerge from parent $roleData["PARAMETERS"] = $originalRole->array_merge_recursive2($originalRole->listParameters(), $roleData["PARAMETERS"]); // Changing Actions is not allowed $roleData["ACTIONS"] = $originalRole->listActionsStates(); } try { $originalRole->bunchUpdate($roleData); if (isset($userObject)) { $userObject->personalRole = $originalRole; $userObject->save("superuser"); } else { AuthService::updateRole($originalRole); } $output = array("ROLE" => $originalRole->getDataArray(true), "SUCCESS" => true); } catch (Exception $e) { $output = array("ERROR" => $e->getMessage()); } HTMLWriter::charsetHeader("application/json"); echo json_encode($output); break; case "user_set_lock": $userId = AJXP_Utils::decodeSecureMagic($httpVars["user_id"]); $lock = $httpVars["lock"] == "true" ? true : false; $lockType = $httpVars["lock_type"]; if (AuthService::userExists($userId)) { $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if (!AuthService::canAdministrate($userObject)) { throw new Exception("Cannot update user data for " . $userId); } if ($lock) { $userObject->setLock($lockType); } else { $userObject->removeLock(); } $userObject->save("superuser"); } break; case "create_user": if (!isset($httpVars["new_user_login"]) || $httpVars["new_user_login"] == "" || !isset($httpVars["new_user_pwd"]) || $httpVars["new_user_pwd"] == "") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); return; } $original_login = SystemTextEncoding::magicDequote($httpVars["new_user_login"]); $new_user_login = AJXP_Utils::sanitize($original_login, AJXP_SANITIZE_EMAILCHARS); if ($original_login != $new_user_login) { throw new Exception(str_replace("%s", $new_user_login, $mess["ajxp_conf.127"])); } if (AuthService::userExists($new_user_login, "w") || AuthService::isReservedUserId($new_user_login)) { throw new Exception($mess["ajxp_conf.43"]); } AuthService::createUser($new_user_login, $httpVars["new_user_pwd"]); $confStorage = ConfService::getConfStorageImpl(); $newUser = $confStorage->createUserObject($new_user_login); $basePath = AuthService::getLoggedUser()->getGroupPath(); if (empty($basePath)) { $basePath = "/"; } if (!empty($httpVars["group_path"])) { $newUser->setGroupPath(rtrim($basePath, "/") . "/" . ltrim($httpVars["group_path"], "/")); } else { $newUser->setGroupPath($basePath); } $newUser->save("superuser"); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.44"], null); AJXP_XMLWriter::reloadDataNode("", $new_user_login); AJXP_XMLWriter::close(); break; case "change_admin_right": $userId = $httpVars["user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Invalid user id!"); } $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); if (!AuthService::canAdministrate($user)) { throw new Exception("Cannot update user with id " . $userId); } $user->setAdmin($httpVars["right_value"] == "1" ? true : false); $user->save("superuser"); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.45"] . $httpVars["user_id"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; case "role_update_right": if (!isset($httpVars["role_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); break; } $rId = AJXP_Utils::sanitize($httpVars["role_id"]); $role = AuthService::getRole($rId); if ($role === false) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"] . "(" . $rId . ")"); AJXP_XMLWriter::close(); break; } $role->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM)); AuthService::updateRole($role); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["role_id"], null); AJXP_XMLWriter::close(); break; case "user_update_right": if (!isset($httpVars["user_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"]) || !AuthService::userExists($httpVars["user_id"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>"; AJXP_XMLWriter::close(); return; } $confStorage = ConfService::getConfStorageImpl(); $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS); $user = $confStorage->createUserObject($userId); if (!AuthService::canAdministrate($user)) { throw new Exception("Cannot update user with id " . $userId); } $user->personalRole->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM)); $user->save(); $loggedUser = AuthService::getLoggedUser(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["user_id"], null); print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $user->canRead($httpVars["repository_id"]) . "\" write=\"" . $user->canWrite($httpVars["repository_id"]) . "\"/>"; AJXP_XMLWriter::reloadRepositoryList(); AJXP_XMLWriter::close(); return; break; case "user_update_group": $userSelection = new UserSelection(); $userSelection->initFromHttpVars($httpVars); $dir = $httpVars["dir"]; $dest = $httpVars["dest"]; if (isset($httpVars["group_path"])) { // API Case $groupPath = $httpVars["group_path"]; } else { if (strpos($dir, "/data/users", 0) !== 0 || strpos($dest, "/data/users", 0) !== 0) { break; } $groupPath = substr($dest, strlen("/data/users")); } $confStorage = ConfService::getConfStorageImpl(); $userId = null; $usersMoved = array(); $basePath = AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getGroupPath() : "/"; if (empty($basePath)) { $basePath = "/"; } if (!empty($groupPath)) { $targetPath = rtrim($basePath, "/") . "/" . ltrim($groupPath, "/"); } else { $targetPath = $basePath; } foreach ($userSelection->getFiles() as $selectedUser) { $userId = basename($selectedUser); if (!AuthService::userExists($userId)) { continue; } $user = $confStorage->createUserObject($userId); if (!AuthService::canAdministrate($user)) { continue; } $user->setGroupPath($targetPath, true); $user->save("superuser"); $usersMoved[] = $user->getId(); } AJXP_XMLWriter::header(); if (count($usersMoved)) { AJXP_XMLWriter::sendMessage(count($usersMoved) . " user(s) successfully moved to " . $targetPath, null); AJXP_XMLWriter::reloadDataNode($dest, $userId); AJXP_XMLWriter::reloadDataNode(); } else { AJXP_XMLWriter::sendMessage(null, "No users moved, there must have been something wrong."); } AJXP_XMLWriter::close(); break; case "user_add_role": case "user_delete_role": if (!isset($httpVars["user_id"]) || !isset($httpVars["role_id"]) || !AuthService::userExists($httpVars["user_id"]) || !AuthService::getRole($httpVars["role_id"])) { throw new Exception($mess["ajxp_conf.61"]); } if ($action == "user_add_role") { $act = "add"; $messId = "73"; } else { $act = "remove"; $messId = "74"; } $this->updateUserRole(AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS), $httpVars["role_id"], $act); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . $messId] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); return; break; case "user_update_role": $confStorage = ConfService::getConfStorageImpl(); $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); $detectedRoles = array(); $roleId = null; if (isset($httpVars["role_id"]) && isset($httpVars["update_role_action"])) { $update = $httpVars["update_role_action"]; $roleId = $httpVars["role_id"]; if (AuthService::getRole($roleId) === false) { throw new Exception("Invalid role id"); } } foreach ($files as $index => $file) { $userId = basename($file); if (isset($update)) { $userObject = $this->updateUserRole($userId, $roleId, $update); } else { $userObject = $confStorage->createUserObject($userId); if (!AuthService::canAdministrate($userObject)) { continue; } } if ($userObject->hasParent()) { unset($files[$index]); continue; } $userRoles = $userObject->getRoles(); foreach ($userRoles as $roleIndex => $bool) { if (!isset($detectedRoles[$roleIndex])) { $detectedRoles[$roleIndex] = 0; } if ($bool === true) { $detectedRoles[$roleIndex]++; } } } $count = count($files); AJXP_XMLWriter::header("admin_data"); print "<user><ajxp_roles>"; foreach ($detectedRoles as $roleId => $roleCount) { if ($roleCount < $count) { continue; } print "<role id=\"{$roleId}\"/>"; } print "</ajxp_roles></user>"; print "<ajxp_roles>"; foreach (AuthService::getRolesList(array(), !$this->listSpecialRoles) as $roleId => $roleObject) { print "<role id=\"{$roleId}\"/>"; } print "</ajxp_roles>"; AJXP_XMLWriter::close("admin_data"); break; case "save_custom_user_params": $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS); if ($userId == $loggedUser->getId()) { $user = $loggedUser; } else { $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); } if (!AuthService::canAdministrate($user)) { throw new Exception("Cannot update user with id " . $userId); } $custom = $user->getPref("CUSTOM_PARAMS"); if (!is_array($custom)) { $custom = array(); } $options = $custom; $this->parseParameters($httpVars, $options, $userId, false, $custom); $custom = $options; $user->setPref("CUSTOM_PARAMS", $custom); $user->save(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); break; case "save_repository_user_params": $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS); if ($userId == $loggedUser->getId()) { $user = $loggedUser; } else { $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); } if (!AuthService::canAdministrate($user)) { throw new Exception("Cannot update user with id " . $userId); } $wallet = $user->getPref("AJXP_WALLET"); if (!is_array($wallet)) { $wallet = array(); } $repoID = $httpVars["repository_id"]; if (!array_key_exists($repoID, $wallet)) { $wallet[$repoID] = array(); } $options = $wallet[$repoID]; $existing = $options; $this->parseParameters($httpVars, $options, $userId, false, $existing); $wallet[$repoID] = $options; $user->setPref("AJXP_WALLET", $wallet); $user->save(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); break; case "update_user_pwd": if (!isset($httpVars["user_id"]) || !isset($httpVars["user_pwd"]) || !AuthService::userExists($httpVars["user_id"]) || trim($httpVars["user_pwd"]) == "") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); return; } $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS); $user = ConfService::getConfStorageImpl()->createUserObject($userId); if (!AuthService::canAdministrate($user)) { throw new Exception("Cannot update user data for " . $userId); } $res = AuthService::updatePassword($userId, $httpVars["user_pwd"]); AJXP_XMLWriter::header(); if ($res === true) { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.48"] . $userId, null); } else { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.49"] . " : {$res}"); } AJXP_XMLWriter::close(); break; case "save_user_preference": if (!isset($httpVars["user_id"]) || !AuthService::userExists($httpVars["user_id"])) { throw new Exception($mess["ajxp_conf.61"]); } $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS); if ($userId == $loggedUser->getId()) { $userObject = $loggedUser; } else { $confStorage = ConfService::getConfStorageImpl(); $userObject = $confStorage->createUserObject($userId); } if (!AuthService::canAdministrate($userObject)) { throw new Exception("Cannot update user data for " . $userId); } $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"); $i++; } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage("Succesfully saved user preference", null); AJXP_XMLWriter::close(); break; case "get_drivers_definition": AJXP_XMLWriter::header("drivers", array("allowed" => $currentUserIsGroupAdmin ? "false" : "true")); print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("param", "", true)); AJXP_XMLWriter::close("drivers"); break; case "get_templates_definition": AJXP_XMLWriter::header("repository_templates"); $count = 0; $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => '1'), $count); foreach ($repositories as $repo) { if (!$repo->isTemplate) { continue; } $repoId = $repo->getUniqueId(); $repoLabel = SystemTextEncoding::toUTF8($repo->getDisplay()); $repoType = $repo->getAccessType(); print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">"; foreach ($repo->getOptionsDefined() as $optionName) { print "<option name=\"{$optionName}\"/>"; } print "</template>"; } AJXP_XMLWriter::close("repository_templates"); break; case "create_repository": $repDef = $httpVars; $isTemplate = isset($httpVars["sf_checkboxes_active"]); unset($repDef["get_action"]); unset($repDef["sf_checkboxes_active"]); if (isset($httpVars["json_data"])) { $repDef = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true); $options = $repDef["DRIVER_OPTIONS"]; } else { $options = array(); $this->parseParameters($repDef, $options, null, true); } if (count($options)) { $repDef["DRIVER_OPTIONS"] = $options; unset($repDef["DRIVER_OPTIONS"]["AJXP_GROUP_PATH_PARAMETER"]); } if (strstr($repDef["DRIVER"], "ajxp_template_") !== false) { $templateId = substr($repDef["DRIVER"], 14); $templateRepo = ConfService::getRepositoryById($templateId); $newRep = $templateRepo->createTemplateChild($repDef["DISPLAY"], $repDef["DRIVER_OPTIONS"]); if (isset($repDef["AJXP_SLUG"])) { $newRep->setSlug($repDef["AJXP_SLUG"]); } } else { if ($currentUserIsGroupAdmin) { throw new Exception("You are not allowed to create a workspace from a driver. Use a template instead."); } $pServ = AJXP_PluginsService::getInstance(); $driver = $pServ->getPluginByTypeName("access", $repDef["DRIVER"]); $newRep = ConfService::createRepositoryFromArray(0, $repDef); $testFile = $driver->getBaseDir() . "/test." . $newRep->getAccessType() . "Access.php"; if (!$isTemplate && is_file($testFile)) { //chdir(AJXP_TESTS_FOLDER."/plugins"); $className = $newRep->getAccessType() . "AccessTest"; if (!class_exists($className)) { include $testFile; } $class = new $className(); $result = $class->doRepositoryTest($newRep); if (!$result) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $class->failedInfo); AJXP_XMLWriter::close(); return; } } // Apply default metasource if any if ($driver != null && $driver->getConfigs() != null) { $confs = $driver->getConfigs(); if (!empty($confs["DEFAULT_METASOURCES"])) { $metaIds = AJXP_Utils::parseCSL($confs["DEFAULT_METASOURCES"]); $metaSourceOptions = array(); foreach ($metaIds as $metaID) { $metaPlug = $pServ->getPluginById($metaID); if ($metaPlug == null) { continue; } $pNodes = $metaPlug->getManifestRawContent("//param[@default]", "nodes"); $defaultParams = array(); foreach ($pNodes as $domNode) { $defaultParams[$domNode->getAttribute("name")] = $domNode->getAttribute("default"); } $metaSourceOptions[$metaID] = $defaultParams; } $newRep->addOption("META_SOURCES", $metaSourceOptions); } } } if ($this->repositoryExists($newRep->getDisplay())) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]); AJXP_XMLWriter::close(); return; } if ($isTemplate) { $newRep->isTemplate = true; } if ($currentUserIsGroupAdmin) { $newRep->setGroupPath(AuthService::getLoggedUser()->getGroupPath()); } else { if (!empty($options["AJXP_GROUP_PATH_PARAMETER"])) { $basePath = "/"; if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) { $basePath = AuthService::getLoggedUser()->getGroupPath(); } $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($options["AJXP_GROUP_PATH_PARAMETER"], "/")); $newRep->setGroupPath($value); } } $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]); } else { $loggedUser = AuthService::getLoggedUser(); $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw"); $loggedUser->recomputeMergedRole(); $loggedUser->save("superuser"); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.52"], null); AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId()); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "edit_repository": $repId = $httpVars["repository_id"]; $repository = ConfService::getRepositoryById($repId); if ($repository == null) { throw new Exception("Cannot find workspace with id {$repId}"); } if (!AuthService::canAdministrate($repository)) { throw new Exception("You are not allowed to edit this workspace!"); } $pServ = AJXP_PluginsService::getInstance(); $plug = $pServ->getPluginById("access." . $repository->accessType); if ($plug == null) { throw new Exception("Cannot find access driver (" . $repository->accessType . ") for workspace!"); } AJXP_XMLWriter::header("admin_data"); $slug = $repository->getSlug(); if ($slug == "" && $repository->isWriteable()) { $repository->setSlug(); ConfService::replaceRepository($repId, $repository); } if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) { $rgp = $repository->getGroupPath(); if ($rgp == null) { $rgp = "/"; } if (strlen($rgp) < strlen(AuthService::getLoggedUser()->getGroupPath())) { $repository->setWriteable(false); } } $nested = array(); $definitions = $plug->getConfigsDefinitions(); print "<repository index=\"{$repId}\""; foreach ($repository as $name => $option) { if (strstr($name, " ") > -1) { continue; } if (!is_array($option)) { if (is_bool($option)) { $option = $option ? "true" : "false"; } print " {$name}=\"" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($option)) . "\" "; } else { if (is_array($option)) { $nested[] = $option; } } } if (count($nested)) { print ">"; foreach ($nested as $option) { foreach ($option as $key => $optValue) { if (is_array($optValue) && count($optValue)) { print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>"; } else { if (is_object($optValue)) { print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>"; } else { if (is_bool($optValue)) { $optValue = $optValue ? "true" : "false"; } else { if (isset($definitions[$key]) && $definitions[$key]["type"] == "password" && !empty($optValue)) { $optValue = "__AJXP_VALUE_SET__"; } } $optValue = AJXP_Utils::xmlEntities($optValue, true); print "<param name=\"{$key}\" value=\"{$optValue}\"/>"; } } } } // Add SLUG if (!$repository->isTemplate) { print "<param name=\"AJXP_SLUG\" value=\"" . $repository->getSlug() . "\"/>"; } if ($repository->getGroupPath() != null) { $basePath = "/"; if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) { $basePath = AuthService::getLoggedUser()->getGroupPath(); } $groupPath = $repository->getGroupPath(); if ($basePath != "/") { $groupPath = substr($repository->getGroupPath(), strlen($basePath)); } print "<param name=\"AJXP_GROUP_PATH_PARAMETER\" value=\"" . $groupPath . "\"/>"; } print "</repository>"; } else { print "/>"; } if ($repository->hasParent()) { $parent = ConfService::getRepositoryById($repository->getParentId()); if (isset($parent) && $parent->isTemplate) { $parentLabel = $parent->getDisplay(); $parentType = $parent->getAccessType(); print "<template repository_id=\"" . $repository->getParentId() . "\" repository_label=\"{$parentLabel}\" repository_type=\"{$parentType}\">"; foreach ($parent->getOptionsDefined() as $parentOptionName) { print "<option name=\"{$parentOptionName}\"/>"; } print "</template>"; } } $manifest = $plug->getManifestRawContent("server_settings/param"); $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest); print "<ajxpdriver name=\"" . $repository->accessType . "\">{$manifest}</ajxpdriver>"; print "<metasources>"; $metas = $pServ->getPluginsByType("metastore"); $metas = array_merge($metas, $pServ->getPluginsByType("meta")); $metas = array_merge($metas, $pServ->getPluginsByType("index")); foreach ($metas as $metaPlug) { print "<meta id=\"" . $metaPlug->getId() . "\" label=\"" . AJXP_Utils::xmlEntities($metaPlug->getManifestLabel()) . "\">"; $manifest = $metaPlug->getManifestRawContent("server_settings/param"); $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest); print $manifest; print "</meta>"; } print "</metasources>"; AJXP_XMLWriter::close("admin_data"); return; break; case "edit_repository_label": case "edit_repository_data": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!$repo->isWriteable()) { throw new Exception("This workspace is not writeable. Please edit directly the conf/bootstrap_repositories.php file."); } $res = 0; if (isset($httpVars["newLabel"])) { $newLabel = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["newLabel"]), AJXP_SANITIZE_HTML); if ($this->repositoryExists($newLabel)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]); AJXP_XMLWriter::close(); return; } $repo->setDisplay($newLabel); $res = ConfService::replaceRepository($repId, $repo); } else { $options = array(); $existing = $repo->getOptionsDefined(); $existingValues = array(); foreach ($existing as $exK) { $existingValues[$exK] = $repo->getOption($exK, true); } $this->parseParameters($httpVars, $options, null, true, $existingValues); if (count($options)) { foreach ($options as $key => $value) { if ($key == "AJXP_SLUG") { $repo->setSlug($value); continue; } elseif ($key == "AJXP_GROUP_PATH_PARAMETER") { $basePath = "/"; if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) { $basePath = AuthService::getLoggedUser()->getGroupPath(); } $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($value, "/")); $repo->setGroupPath($value); continue; } $repo->addOption($key, $value); } } if ($repo->getOption("DEFAULT_RIGHTS")) { $gp = $repo->getGroupPath(); if (empty($gp) || $gp == "/") { $defRole = AuthService::getRole("ROOT_ROLE"); } else { $defRole = AuthService::getRole("AJXP_GRP_" . $gp, true); } if ($defRole !== false) { $defRole->setAcl($repId, $repo->getOption("DEFAULT_RIGHTS")); AuthService::updateRole($defRole); } } if (is_file(AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php")) { chdir(AJXP_TESTS_FOLDER . "/plugins"); include AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php"; $className = "ajxp_" . $repo->getAccessType(); $class = new $className(); $result = $class->doRepositoryTest($repo); if (!$result) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $class->failedInfo); AJXP_XMLWriter::close(); return; } } ConfService::replaceRepository($repId, $repo); } AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.53"]); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.54"], null); if (isset($httpVars["newLabel"])) { AJXP_XMLWriter::reloadDataNode("", $repId); } AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "meta_source_add": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!is_object($repo)) { throw new Exception("Invalid workspace id! {$repId}"); } $metaSourceType = AJXP_Utils::sanitize($httpVars["new_meta_source"], AJXP_SANITIZE_ALPHANUM); if (isset($httpVars["json_data"])) { $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true); } else { $options = array(); $this->parseParameters($httpVars, $options, null, true); } $repoOptions = $repo->getOption("META_SOURCES"); if (is_array($repoOptions) && isset($repoOptions[$metaSourceType])) { throw new Exception($mess["ajxp_conf.55"]); } if (!is_array($repoOptions)) { $repoOptions = array(); } $repoOptions[$metaSourceType] = $options; uksort($repoOptions, array($this, "metaSourceOrderingFunction")); $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.56"], null); AJXP_XMLWriter::close(); break; case "meta_source_delete": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!is_object($repo)) { throw new Exception("Invalid workspace id! {$repId}"); } $metaSourceId = $httpVars["plugId"]; $repoOptions = $repo->getOption("META_SOURCES"); if (is_array($repoOptions) && array_key_exists($metaSourceId, $repoOptions)) { unset($repoOptions[$metaSourceId]); uksort($repoOptions, array($this, "metaSourceOrderingFunction")); $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); } else { throw new Exception("Cannot find meta source " . $metaSourceId); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.57"], null); AJXP_XMLWriter::close(); break; case "meta_source_edit": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!is_object($repo)) { throw new Exception("Invalid workspace id! {$repId}"); } $metaSourceId = $httpVars["plugId"]; $repoOptions = $repo->getOption("META_SOURCES"); if (!is_array($repoOptions)) { $repoOptions = array(); } if (isset($httpVars["json_data"])) { $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true); } else { $options = array(); $this->parseParameters($httpVars, $options, null, true); } if (isset($repoOptions[$metaSourceId])) { $this->mergeExistingParameters($options, $repoOptions[$metaSourceId]); } $repoOptions[$metaSourceId] = $options; uksort($repoOptions, array($this, "metaSourceOrderingFunction")); $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.58"], null); AJXP_XMLWriter::close(); break; case "delete": // REST API mapping if (isset($httpVars["data_type"])) { switch ($httpVars["data_type"]) { case "repository": $httpVars["repository_id"] = basename($httpVars["data_id"]); break; case "role": $httpVars["role_id"] = basename($httpVars["data_id"]); break; case "user": $httpVars["user_id"] = basename($httpVars["data_id"]); break; case "group": $httpVars["group"] = "/data/users" . $httpVars["data_id"]; break; default: break; } unset($httpVars["data_type"]); unset($httpVars["data_id"]); } if (isset($httpVars["repository_id"])) { $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!is_object($repo)) { $res = -1; } else { $res = ConfService::deleteRepository($repId); } AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[427]); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); return; } else { if (isset($httpVars["role_id"])) { $roleId = $httpVars["role_id"]; if (AuthService::getRole($roleId) === false) { throw new Exception($mess["ajxp_conf.67"]); } AuthService::deleteRole($roleId); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.68"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } else { if (isset($httpVars["group"])) { $groupPath = $httpVars["group"]; $basePath = substr(AJXP_Utils::forwardSlashDirname($groupPath), strlen("/data/users")); $gName = basename($groupPath); AuthService::deleteGroup($basePath, $gName); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.128"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } else { if (!isset($httpVars["user_id"]) || $httpVars["user_id"] == "" || AuthService::isReservedUserId($httpVars["user_id"]) || $loggedUser->getId() == $httpVars["user_id"]) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); } AuthService::deleteUser($httpVars["user_id"]); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } } } break; case "get_plugin_manifest": $ajxpPlugin = AJXP_PluginsService::getInstance()->getPluginById($httpVars["plugin_id"]); AJXP_XMLWriter::header("admin_data"); $fullManifest = $ajxpPlugin->getManifestRawContent("", "xml"); $xPath = new DOMXPath($fullManifest->ownerDocument); $addParams = ""; $instancesDefinitions = array(); $pInstNodes = $xPath->query("server_settings/global_param[contains(@type, 'plugin_instance:')]"); foreach ($pInstNodes as $pInstNode) { $type = $pInstNode->getAttribute("type"); $instType = str_replace("plugin_instance:", "", $type); $fieldName = $pInstNode->getAttribute("name"); $pInstNode->setAttribute("type", "group_switch:" . $fieldName); $typePlugs = AJXP_PluginsService::getInstance()->getPluginsByType($instType); foreach ($typePlugs as $typePlug) { if ($typePlug->getId() == "auth.multi") { continue; } $checkErrorMessage = ""; try { $typePlug->performChecks(); } catch (Exception $e) { $checkErrorMessage = " (Warning : " . $e->getMessage() . ")"; } $tParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[not(@group_switch_name)]")); $addParams .= '<global_param group_switch_name="' . $fieldName . '" name="instance_name" group_switch_label="' . $typePlug->getManifestLabel() . $checkErrorMessage . '" group_switch_value="' . $typePlug->getId() . '" default="' . $typePlug->getId() . '" type="hidden"/>'; $addParams .= str_replace("<param", "<global_param group_switch_name=\"{$fieldName}\" group_switch_label=\"" . $typePlug->getManifestLabel() . $checkErrorMessage . "\" group_switch_value=\"" . $typePlug->getId() . "\" ", $tParams); $addParams .= str_replace("<param", "<global_param", AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[@group_switch_name]"))); $addParams .= AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/global_param")); $instancesDefs = $typePlug->getConfigsDefinitions(); if (!empty($instancesDefs) && is_array($instancesDefs)) { foreach ($instancesDefs as $defKey => $defData) { $instancesDefinitions[$fieldName . "/" . $defKey] = $defData; } } } } $allParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($fullManifest->ownerDocument->saveXML($fullManifest)); $allParams = str_replace('type="plugin_instance:', 'type="group_switch:', $allParams); $allParams = str_replace("</server_settings>", $addParams . "</server_settings>", $allParams); echo $allParams; $definitions = $instancesDefinitions; $configsDefs = $ajxpPlugin->getConfigsDefinitions(); if (is_array($configsDefs)) { $definitions = array_merge($configsDefs, $instancesDefinitions); } $values = $ajxpPlugin->getConfigs(); if (!is_array($values)) { $values = array(); } echo "<plugin_settings_values>"; // First flatten keys $flattenedKeys = array(); foreach ($values as $key => $value) { $type = $definitions[$key]["type"]; if ((strpos($type, "group_switch:") === 0 || strpos($type, "plugin_instance:") === 0) && is_array($value)) { $res = array(); $this->flattenKeyValues($res, $definitions, $value, $key); $flattenedKeys += $res; // Replace parent key by new flat value $values[$key] = $flattenedKeys[$key]; } } $values += $flattenedKeys; foreach ($values as $key => $value) { $attribute = true; $type = $definitions[$key]["type"]; if ($type == "array" && is_array($value)) { $value = implode(",", $value); } else { if ($type == "boolean") { $value = $value === true || $value === "true" || $value == 1 ? "true" : "false"; } else { if ($type == "textarea") { $attribute = false; } else { if ($type == "password" && !empty($value)) { $value = "__AJXP_VALUE_SET__"; } } } } if ($attribute) { echo "<param name=\"{$key}\" value=\"" . AJXP_Utils::xmlEntities($value) . "\"/>"; } else { echo "<param name=\"{$key}\" cdatavalue=\"true\"><![CDATA[" . $value . "]]></param>"; } } if ($ajxpPlugin->getType() != "core") { echo "<param name=\"AJXP_PLUGIN_ENABLED\" value=\"" . ($ajxpPlugin->isEnabled() ? "true" : "false") . "\"/>"; } echo "</plugin_settings_values>"; echo "<plugin_doc><![CDATA[<p>" . $ajxpPlugin->getPluginInformationHTML("Charles du Jeu", "http://pyd.io/plugins/") . "</p>"; if (file_exists($ajxpPlugin->getBaseDir() . "/plugin_doc.html")) { echo file_get_contents($ajxpPlugin->getBaseDir() . "/plugin_doc.html"); } echo "]]></plugin_doc>"; AJXP_XMLWriter::close("admin_data"); break; case "run_plugin_action": $options = array(); $this->parseParameters($httpVars, $options, null, true); $pluginId = $httpVars["action_plugin_id"]; if (isset($httpVars["button_key"])) { $options = $options[$httpVars["button_key"]]; } $plugin = AJXP_PluginsService::getInstance()->softLoad($pluginId, $options); if (method_exists($plugin, $httpVars["action_plugin_method"])) { try { $res = call_user_func(array($plugin, $httpVars["action_plugin_method"]), $options); } catch (Exception $e) { echo "ERROR:" . $e->getMessage(); break; } echo $res; } else { echo 'ERROR: Plugin ' . $httpVars["action_plugin_id"] . ' does not implement ' . $httpVars["action_plugin_method"] . ' method!'; } break; case "edit_plugin_options": $options = array(); $this->parseParameters($httpVars, $options, null, true); $confStorage = ConfService::getConfStorageImpl(); list($pType, $pName) = explode(".", $httpVars["plugin_id"]); $existing = $confStorage->loadPluginConfig($pType, $pName); $this->mergeExistingParameters($options, $existing); $confStorage->savePluginConfig($httpVars["plugin_id"], $options); AJXP_PluginsService::clearPluginsCache(); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.97"], null); AJXP_XMLWriter::close(); break; case "generate_api_docs": PydioSdkGenerator::analyzeRegistry(isset($httpVars["version"]) ? $httpVars["version"] : AJXP_VERSION); break; // Action for update all Pydio's user from ldap in CLI mode // Action for update all Pydio's user from ldap in CLI mode case "cli_update_user_list": if (php_sapi_name() == "cli") { $progressBar = new AJXP_ProgressBarCLI(); $countCallback = array($progressBar, "init"); $loopCallback = array($progressBar, "update"); AuthService::listUsers("/", null, -1, -1, true, true, $countCallback, $loopCallback); } break; default: break; } return; }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::securePath($dir); if ($dir == "/") { $dir = ""; } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { //$this->filterUserSelectionToHidden($selection->getFiles()); } $urlBase = "ajxp.fs://" . ConfService::getRepository()->getId(); $mess = ConfService::getMessages(); switch ($action) { case "monitor_compression": $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]); $percent = 0; if (is_file($percentFile)) { $percent = intval(file_get_contents($percentFile)); } if ($percent < 100) { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1); AJXP_XMLWriter::close(); } else { @unlink($percentFile); AJXP_XMLWriter::header(); if ($httpVars["on_end"] == "reload") { AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } else { $archiveName = $httpVars["archive_name"]; $jsCode = "\n \$('download_form').action = window.ajxpServerAccessPath;\n \$('download_form').secure_token.value = window.Connexion.SECURE_TOKEN;\n \$('download_form').select('input').each(function(input){\n if(input.name!='get_action' && input.name!='secure_token') input.remove();\n });\n \$('download_form').insert(new Element('input', {type:'hidden', name:'ope_id', value:'" . $httpVars["ope_id"] . "'}));\n \$('download_form').insert(new Element('input', {type:'hidden', name:'archive_name', value:'" . $archiveName . "'}));\n \$('download_form').insert(new Element('input', {type:'hidden', name:'get_action', value:'postcompress_download'}));\n \$('download_form').submit();\n "; AJXP_XMLWriter::triggerBgJsAction($jsCode, "powerfs.3", true); AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } AJXP_XMLWriter::close(); } break; case "postcompress_download": $archive = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["ope_id"] . "_" . $httpVars["archive_name"]; //$fsDriver = new fsAccessDriver("fake", ""); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true); break; case "compress": case "precompress": if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) { $opeId = substr(md5(time()), 0, 10); $httpVars["ope_id"] = $opeId; AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars); AJXP_XMLWriter::header(); $bgParameters = array("dir" => $dir, "archive_name" => $httpVars["archive_name"], "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId); AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true); AJXP_XMLWriter::close(); session_write_close(); exit; } $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir; $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"]; $compressLocally = $action == "compress" ? true : false; // List all files $todo = array(); $args = array(); $replaceSearch = array($rootDir, "\\"); $replaceReplace = array("", "/"); foreach ($selection->getFiles() as $selectionFile) { $args[] = '"' . substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1)) . '"'; $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile); $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/"); if (is_dir($selectionFile)) { $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST); foreach ($objects as $name => $object) { $todo[] = str_replace($replaceSearch, $replaceReplace, $name); } } } $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";"; $archiveName = $httpVars["archive_name"]; if (!$compressLocally) { $archiveName = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["ope_id"] . "_" . $archiveName; } chdir($rootDir); $cmd = "zip -r \"" . $archiveName . "\" " . implode(" ", $args); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $c = $fsDriver->getConfigs(); if (!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) { $cmd .= " -x .\\*"; } $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED"; $proc = popen($cmd, "r"); $toks = array(); $handled = array(); $finishedEchoed = false; while (!feof($proc)) { set_time_limit(20); $results = fgets($proc, 256); if (strlen($results) == 0) { } else { $tok = strtok($results, "\n"); while ($tok !== false) { $toks[] = $tok; if ($tok == "ZIP_FINISHED") { $finishedEchoed = true; } else { $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches); if ($test !== false) { $handled[] = $matches[2]; } } $tok = strtok("\n"); } if ($finishedEchoed) { $percent = 100; } else { $percent = min(round(count($handled) / count($todo) * 100), 100); } file_put_contents($percentFile, $percent); } // avoid a busy wait if ($percent < 100) { usleep(1); } } pclose($proc); file_put_contents($percentFile, 100); break; default: break; } }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $loggedUser = AuthService::getLoggedUser(); if (!AuthService::usersEnabled()) { return; } if ($action == "edit") { if (isset($httpVars["sub_action"])) { $action = $httpVars["sub_action"]; } } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // BASIC LISTING //------------------------------------ case "ls": $rootNodes = array("files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png", "DESCRIPTION" => $mess["ajxp_shared.28"]), "repositories" => array("LABEL" => $mess["ajxp_shared.2"], "ICON" => "document_open_remote.png", "DESCRIPTION" => $mess["ajxp_shared.29"]), "users" => array("LABEL" => $mess["ajxp_shared.1"], "ICON" => "user_shared.png", "DESCRIPTION" => $mess["ajxp_shared.30"])); $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : ""; $splits = explode("/", $dir); if (count($splits)) { if ($splits[0] == "") { array_shift($splits); } if (count($splits)) { $strippedDir = strtolower(urldecode($splits[0])); } else { $strippedDir = ""; } } if (array_key_exists($strippedDir, $rootNodes)) { AJXP_XMLWriter::header(); if ($strippedDir == "users") { $this->listUsers(); } else { if ($strippedDir == "repositories") { $this->listRepositories(); } else { if ($strippedDir == "files") { $this->listSharedFiles(); } } } AJXP_XMLWriter::close(); } else { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_shared.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_shared.31" attributeName="description" sortType="String"/></columns>'); foreach ($rootNodes as $key => $data) { print '<tree text="' . $data["LABEL"] . '" icon="' . $data["ICON"] . '" filename="/' . $key . '" parentname="/" description="' . $data["DESCRIPTION"] . '" />'; } AJXP_XMLWriter::close(); } break; case "stat": header("Content-type:application/json"); print '{"mode":true}'; break; case "delete": $mime = $httpVars["ajxp_mime"]; $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); AJXP_XMLWriter::header(); foreach ($files as $index => $element) { $element = basename($element); $ar = explode("shared_", $mime); $mime = array_pop($ar); ShareCenter::deleteSharedElement($mime, $element, $loggedUser); if ($mime == "repository") { $out = $mess["ajxp_conf.59"]; } else { if ($mime == "user") { $out = $mess["ajxp_conf.60"]; } else { if ($mime == "file") { $out = $mess["ajxp_shared.13"]; } } } } AJXP_XMLWriter::sendMessage($out, null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; case "clear_expired": $deleted = $this->clearExpiredFiles(); AJXP_XMLWriter::header(); if (count($deleted)) { AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null); AJXP_XMLWriter::reloadDataNode(); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null); } AJXP_XMLWriter::close(); break; case "reset_download_counter": $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $elements = $selection->getFiles(); foreach ($elements as $element) { PublicletCounter::reset(str_replace(".php", "", basename($element))); } AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; default: break; } return; }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = Utils::securePath(SystemTextEncoding::magicDequote($getValue)); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); if (isset($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); } if (isset($dest)) { $dest = SystemTextEncoding::fromUTF8($dest); } $mess = ConfService::getMessages(); $recycleBinOption = $this->repository->getOption("RECYCLE_BIN"); // FILTER ACTION FOR DELETE if ($recycleBinOption != "" && $action == "delete" && $dir != "/" . $recycleBinOption) { $action = "move"; $dest = "/" . $recycleBinOption; $dest_node = "AJAXPLORER_RECYCLE_NODE"; } // FILTER ACTION FOR RESTORE if ($recycleBinOption != "" && $action == "restore" && $dir == "/" . $recycleBinOption) { $originalRep = RecycleBinManager::getFileOrigin($selection->getUniqueFile()); if ($originalRep != "") { $action = "move"; $dest = $originalRep; } } switch ($action) { //------------------------------------ // DOWNLOAD, IMAGE & MP3 PROXYS //------------------------------------ case "download": AJXP_Logger::logAction("Download", array("files" => $selection)); $zip = false; if ($selection->isUnique()) { if (is_dir($this->getPath() . "/" . $selection->getUniqueFile())) { $zip = true; $dir .= "/" . basename($selection->getUniqueFile()); } } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $this->downFile($this->makeName($selection->getFiles()), "force-download", "archive.zip"); } else { $this->downFile($this->makeName($selection->getUniqueFile()), "force-download", $selection->getUniqueFile()); } exit(0); break; case "image_proxy": $this->downFile($this->makeName($file), "image", $file); exit(0); break; case "mp3_proxy": $this->downFile($this->makeName($file), "mp3", $file); exit(0); break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "edit": if (isset($save) && $save == 1) { AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file))); $code = stripslashes($code); $code = str_replace("<", "<", $code); $this->SSHOperation->setRemoteContent($this->makeName($file), $code); echo $mess[115]; } else { $this->sendFile($this->SSHOperation->getRemoteContent($this->makeName($file)), "plain", $file); } exit(0); break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } $result = ""; if ($action == "move") { $result = $this->SSHOperation->moveFile($this->makeName($selection->getFiles()), $this->makeName($dest)); } else { $result = $this->SSHOperation->copyFile($this->makeName($selection->getFiles()), $this->makeName($dest)); } $mess = ConfService::getMessages(); if (strlen($result)) { $errorMessage = $mess[114]; } else { foreach ($selection->getFiles() as $files) { $logMessage .= $mess[34] . " " . SystemTextEncoding::toUTF8(basename($file)) . " " . $mess[$action == "move" ? 74 : 73] . " " . SystemTextEncoding::toUTF8($dest) . "\n"; } AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest)); } $reload_current_node = true; if (isset($dest_node)) { $reload_dest_node = $dest_node; } $reload_file_list = true; break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $messtmp = ""; $changedFiles = array(); $value = "0" . decoct(octdec(ltrim($chmod_value, "0"))); // On error, the command will fail $result = $this->SSHOperation->chmodFile($this->makeName($selection->getFiles()), $chmod_value); $mess = ConfService::getMessages(); if (strlen($result)) { $errorMessage = $mess[114]; } else { $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($selection->getFiles()) . " files or folders"; AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($selection->getFiles()))); $reload_file_list = $dir; } break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } $logMessages = array(); $result = $this->SSHOperation->deleteFile($this->makeName($selection->getFiles())); if (strlen($result)) { $mess = ConfService::getMessages(); $errorMessage = $mess[120]; } else { $mess = ConfService::getMessages(); foreach ($selection->getFiles() as $file) { $logMessages[] = "{$mess['34']} " . SystemTextEncoding::toUTF8($file) . " {$mess['44']}."; } $logMessage = join("\n", $logMessages); } AJXP_Logger::logAction("Delete", array("files" => $selection)); $reload_current_node = true; $reload_file_list = true; break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "rename": $filename_new = $dir . "/" . $filename_new; $error = $this->SSHOperation->moveFile($this->makeName($file), $this->makeName($filename_new)); if ($error != null) { $errorMessage = $error; break; } $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); $reload_current_node = true; $reload_file_list = basename($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 = Utils::processFileName($dirname); $error = $this->SSHOperation->createRemoteDirectory($this->makeName($dir . "/" . $dirname)); if (isset($error)) { $errorMessage = $error; break; } $reload_file_list = $dirname; $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reload_current_node = 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 = Utils::processFileName($filename); $error = $this->SSHOperation->setRemoteContent($this->makeName($dir . "/" . $filename), ""); if (isset($error)) { $errorMessage = $error; break; } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reload_file_list = $filename; AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename)); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": $fancyLoader = false; if (isset($fileVars["Filedata"])) { $fancyLoader = true; if ($dir != "") { $dir = "/" . base64_decode($dir); } } if ($dir != "") { $rep_source = "/{$dir}"; } else { $rep_source = ""; } $destination = $rep_source; $logMessage = ""; //$fancyLoader = false; foreach ($fileVars as $boxName => $boxData) { if ($boxName != "Filedata" && substr($boxName, 0, 9) != "userfile_") { continue; } if ($boxName == "Filedata") { $fancyLoader = true; } $err = Utils::parseFileDataErrors($boxData, $fancyLoader); if ($err != null) { $errorMessage = $err; break; } $userfile_name = $boxData["name"]; $userfile_name = Utils::processFileName($userfile_name); if (!$this->SSHOperation->uploadFile($boxData["tmp_name"], $this->makeName($destination . "/" . $userfile_name))) { $errorMessage = ($fancyLoader ? "411 " : "") . "{$mess['33']} " . $userfile_name; break; } $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; AJXP_Logger::logAction("Upload File", array("file" => $dir . "/" . $userfile_name)); } if ($fancyLoader) { if (isset($errorMessage)) { header('HTTP/1.0 ' . $errorMessage); die('Error ' . $errorMessage); } else { header('HTTP/1.0 200 OK'); die("200 OK"); } } else { print "<html><script language=\"javascript\">\n"; if (isset($errorMessage)) { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');"; } else { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext();"; } print "</script></html>"; } exit; break; //------------------------------------ // Public URL //------------------------------------ //------------------------------------ // Public URL //------------------------------------ case "public_url": $file = SystemTextEncoding::fromUTF8($file); $url = $this->makePubliclet($file, $password, $expiration); header("Content-type:text/plain"); echo $url; exit(1); 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; } } } } $nom_rep = $dir; AJXP_Exception::errorToXml($nom_rep); $result = $this->SSHOperation->listFilesIn($nom_rep); AJXP_XMLWriter::header(); foreach ($result as $file) { $attributes = ""; $fileName = SystemTextEncoding::toUTF8($file["name"]); $icon = Utils::mimetype($fileName, "image", $file["isDir"] == 1); if ($searchMode) { if ($file["isDir"] == 0) { $attributes = "is_file=\"true\" icon=\"" . SystemTextEncoding::toUTF8($icon) . "\""; } } else { if ($fileListMode) { $atts = array(); $atts[] = "is_file=\"" . (1 - $file["isDir"]) . "\""; $atts[] = "is_image=\"" . Utils::is_image($fileName) . "\""; $atts[] = "mimestring=\"" . Utils::mimetype($fileName, "type", $file["isDir"] == 1) . "\""; $atts[] = "ajxp_modiftime=\"" . $this->dateModif($file["time"]) . "\""; $atts[] = "filesize=\"" . Utils::roundSize($file["size"]) . "\""; $atts[] = "bytesize=\"" . $file["size"] . "\""; $atts[] = "filename=\"" . str_replace("&", "&", $dir . "/" . $fileName) . "\""; $atts[] = "icon=\"" . ($file["isDir"] == 1 ? "folder.png" : SystemTextEncoding::toUTF8($icon)) . "\""; $attributes = join(" ", $atts); } else { if ($file["isDir"] == 1) { $link = SERVER_ACCESS . "?dir=" . $dir . "/" . $fileName; $link = urlencode($link); $folderBaseName = str_replace("&", "&", $fileName); $folderFullName = "{$dir}/" . $folderBaseName; $parentFolderName = $dir; if (!$completeMode) { $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png"; $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png"; if (preg_match("/\\.zip\$/", $file["name"])) { $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/crystal/actions/16/accessories-archiver.png"; } $attributes = "icon=\"{$icon}\" openicon=\"{$openicon}\" filename=\"" . $folderFullName . "\" src=\"{$link}\""; } } } } if (strlen($attributes) > 0) { print "<tree text=\"" . str_replace("&", "&", SystemTextEncoding::toUTF8($this->SSHOperation->unescapeFileName($file["name"]))) . "\" {$attributes}>"; print "</tree>"; } } AJXP_XMLWriter::close(); 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") { $xmlBuffer .= AJXP_XMLWriter::reloadCurrentNode(false); } if (isset($reload_dest_node) && $reload_dest_node != "") { $xmlBuffer .= AJXP_XMLWriter::reloadNode($reload_dest_node, false); } if (isset($reload_file_list)) { $xmlBuffer .= AJXP_XMLWriter::reloadFileList($reload_file_list, false); } return $xmlBuffer; }
public function switchAction($action, $httpVars, $fileVars) { $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::decodeSecureMagic($dir); if ($dir == "/") { $dir = ""; } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { //$this->filterUserSelectionToHidden($selection->getFiles()); } $urlBase = "pydio://" . ConfService::getRepository()->getId(); $mess = ConfService::getMessages(); switch ($action) { case "monitor_compression": $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]); $percent = 0; if (is_file($percentFile)) { $percent = intval(file_get_contents($percentFile)); } if ($percent < 100) { AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1); AJXP_XMLWriter::close(); } else { @unlink($percentFile); AJXP_XMLWriter::header(); if ($httpVars["on_end"] == "reload") { AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } else { $archiveName = AJXP_Utils::sanitize($httpVars["archive_name"], AJXP_SANITIZE_FILENAME); $archiveName = str_replace("'", "\\'", $archiveName); $jsCode = "\n PydioApi.getClient().downloadSelection(null, \$('download_form'), 'postcompress_download', {ope_id:'" . $httpVars["ope_id"] . "',archive_name:'" . $archiveName . "'});\n "; AJXP_XMLWriter::triggerBgJsAction($jsCode, $mess["powerfs.3"], true); AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2); } AJXP_XMLWriter::close(); } break; case "postcompress_download": $archive = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); if (is_file($archive)) { if (!$fsDriver->getFilteredOption("USE_XSENDFILE", ConfService::getRepository()) && !$fsDriver->getFilteredOption("USE_XACCELREDIRECT", ConfService::getRepository())) { register_shutdown_function("unlink", $archive); } $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true); } else { echo "<script>alert('Cannot find archive! Is ZIP correctly installed?');</script>"; } break; case "compress": case "precompress": $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME); if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) { $opeId = substr(md5(time()), 0, 10); $httpVars["ope_id"] = $opeId; AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars); AJXP_XMLWriter::header(); $bgParameters = array("dir" => SystemTextEncoding::toUTF8($dir), "archive_name" => SystemTextEncoding::toUTF8($archiveName), "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId); AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true); AJXP_XMLWriter::close(); session_write_close(); exit; } $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir; $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"]; $compressLocally = $action == "compress" ? true : false; // List all files $todo = array(); $args = array(); $replaceSearch = array($rootDir, "\\"); $replaceReplace = array("", "/"); foreach ($selection->getFiles() as $selectionFile) { $baseFile = $selectionFile; $args[] = escapeshellarg(substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1))); $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile); $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/"); if (is_dir($selectionFile)) { $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST); foreach ($objects as $name => $object) { $todo[] = str_replace($replaceSearch, $replaceReplace, $name); } } if (trim($baseFile, "/") == "") { // ROOT IS SELECTED, FIX IT $args = array(escapeshellarg(basename($rootDir))); $rootDir = dirname($rootDir); break; } } $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";"; if (!$compressLocally) { $archiveName = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . $archiveName; } chdir($rootDir); $cmd = $this->getFilteredOption("ZIP_PATH") . " -r " . escapeshellarg($archiveName) . " " . implode(" ", $args); $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access"); $c = $fsDriver->getConfigs(); if ((!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) && stripos(PHP_OS, "win") === false) { $cmd .= " -x .\\*"; } $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED"; $proc = popen($cmd, "r"); $toks = array(); $handled = array(); $finishedEchoed = false; while (!feof($proc)) { set_time_limit(20); $results = fgets($proc, 256); if (strlen($results) == 0) { } else { $tok = strtok($results, "\n"); while ($tok !== false) { $toks[] = $tok; if ($tok == "ZIP_FINISHED") { $finishedEchoed = true; } else { $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches); if ($test !== false) { $handled[] = $matches[2]; } } $tok = strtok("\n"); } if ($finishedEchoed) { $percent = 100; } else { $percent = min(round(count($handled) / count($todo) * 100), 100); } file_put_contents($percentFile, $percent); } // avoid a busy wait if ($percent < 100) { usleep(1); } } pclose($proc); file_put_contents($percentFile, 100); break; default: break; } }
public function switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $this->streamData = $streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); switch ($actionName) { case "filehasher_signature": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!file_exists($destStreamURL . $file)) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $destStreamURL . $file, array($this, "generateSignature")); $data = $cacheItem->getData(); header("Content-Type:application/octet-stream"); header("Content-Length", strlen($data)); echo $data; break; case "filehasher_delta": case "filehasher_patch": // HANDLE UPLOAD DATA $this->logDebug("Received signature file, should compute delta now"); if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) { throw new Exception("These action should find uploaded data"); } $uploadedData = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-sig"); move_uploaded_file($fileVars["userfile_0"]["tmp_name"], $uploadedData); $fileUrl = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]); $file = call_user_func(array($this->streamData["classname"], "getRealFSReference"), $fileUrl, true); if ($actionName == "filehasher_delta") { $signatureFile = $uploadedData; $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); $this->logDebug("Received signature file, should compute delta now"); rsync_generate_delta($signatureFile, $file, $deltaFile); $this->logDebug("Computed delta file, size is " . filesize($deltaFile)); header("Content-Type:application/octet-stream"); header("Content-Length:" . filesize($deltaFile)); readfile($deltaFile); unlink($signatureFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; $deltaFile = $uploadedData; rsync_patch_file($file, $deltaFile, $patched); rename($patched, $file); unlink($deltaFile); header("Content-Type:text/plain"); echo md5_file($file); } break; case "stat_hash": $selection = new UserSelection(); $selection->initFromArray($httpVars); clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $node = $selection->getUniqueNode($this->accessDriver); $stat = @stat($node->getUrl()); if (!$stat) { print '{}'; } else { if ($node->isLeaf()) { $hash = $this->getFileHash($selection->getUniqueNode($this->accessDriver)); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $node = new AJXP_Node($destStreamURL . $path); $stat = @stat($destStreamURL . $path); if (!$stat) { $stat = '{}'; } else { if (!is_dir($node->getUrl())) { $hash = $this->getFileHash($node); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; $stat = json_encode($stat); } print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; break; } }
public function preProcess($action, $httpVars, $fileVars) { if (!is_array($this->pluginConf)) { throw new Exception("Cannot find configuration for plugin notify.phpmail-lite! Make sur that you have filled the options in the GUI, or that the .inc file was dropped inside the /conf/ folder!"); } if ($action == "upload" && !isset($httpVars["dir"])) { return; } require "lib/class.phpmailer-lite.php"; // Parse options if (is_string($this->pluginConf["FROM"])) { $this->pluginConf["FROM"] = $this->parseStringOption($this->pluginConf["FROM"]); } if (is_string($this->pluginConf["TO"]) && $this->pluginConf["TO"] != "") { $froms = explode(",", $this->pluginConf["TO"]); $this->pluginConf["TO"] = array_map(array($this, "parseStringOption"), $froms); } $recipients = $this->pluginConf["TO"]; if ($this->pluginConf["SHARE"]) { if (isset($httpVars["PLUGINS_DATA"])) { $pData = $httpVars["PLUGINS_DATA"]; } else { $repo = ConfService::getRepository(); $pData = $repo->getOption("PLUGINS_DATA"); } if ($pData != null && isset($pData["SHARE_NOTIFICATION_ACTIVE"]) && isset($pData["SHARE_NOTIFICATION_EMAIL"]) && $pData["SHARE_NOTIFICATION_ACTIVE"] == "on") { $emails = array_map(array($this, "parseStringOption"), explode(",", $pData["SHARE_NOTIFICATION_EMAIL"])); if (is_array($recipients)) { $recipients = array_merge($recipients, $emails); } else { $recipients = $emails; } } } if ($recipients == "" || !count($recipients)) { return; } // NOW IF THERE ARE RECIPIENTS FOR ANY REASON, GO $mail = new PHPMailerLite(true); $mail->Mailer = $this->pluginConf["MAILER"]; $mail->SetFrom($this->pluginConf["FROM"]["address"], $this->pluginConf["FROM"]["name"]); foreach ($recipients as $address) { $mail->AddAddress($address["address"], $address["name"]); } $mail->WordWrap = 50; // set word wrap to 50 characters $mail->IsHTML(true); // set email format to HTML $userSelection = new UserSelection(); $userSelection->initFromHttpVars($httpVars); if ($action == "upload" && !isset($httpVars["simple_uploader"]) && !isset($httpVars["xhr_uploader"])) { // FLEX UPLOADER, BASE64 DECODE! if (isset($fileVars["userfile_0"])) { $file = $fileVars["userfile_0"]["name"]; } else { if (isset($httpVars["Filename"])) { $file = $httpVars["Filename"]; } } $folder = base64_decode($httpVars["dir"]); } else { $folder = $httpVars["dir"]; $file = ""; if (!$userSelection->isEmpty()) { $file = implode(",", array_map("basename", $userSelection->getFiles())); if ($folder == null) { $folder = dirname($userSelection->getUniqueFile()); } } if ($action == "upload" && isset($fileVars["userfile_0"])) { $file = $fileVars["userfile_0"]["name"]; } } $subject = array("%user", "AJXP_USER", "AJXP_FILE", "AJXP_FOLDER", "AJXP_ACTION", "AJXP_REPOSITORY"); $replace = array(AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getId(), $file, $folder, $action, ConfService::getRepository()->getDisplay()); $body = str_replace($subject, $replace, $this->pluginConf["BODY"]); $mail->Subject = str_replace($subject, $replace, $this->pluginConf["SUBJECT"]); $mail->Body = nl2br($body); $mail->AltBody = strip_tags($mail->Body); if (!$mail->Send()) { $message = "Message could not be sent. <p>"; $message .= "Mailer Error: " . $mail->ErrorInfo; throw new Exception($message); } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $loggedUser = AuthService::getLoggedUser(); if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) { return; } if ($action == "edit") { if (isset($httpVars["sub_action"])) { $action = $httpVars["sub_action"]; } } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // BASIC LISTING //------------------------------------ case "ls": $rootNodes = array("data" => array("LABEL" => $mess["ajxp_conf.110"], "ICON" => "user.png", "CHILDREN" => array("repositories" => array("LABEL" => $mess["ajxp_conf.3"], "ICON" => "hdd_external_unmount.png", "LIST" => "listRepositories"), "users" => array("LABEL" => $mess["ajxp_conf.2"], "ICON" => "user.png", "LIST" => "listUsers"), "roles" => array("LABEL" => $mess["ajxp_conf.69"], "ICON" => "yast_kuser.png", "LIST" => "listRoles"))), "config" => array("LABEL" => $mess["ajxp_conf.109"], "ICON" => "preferences_desktop.png", "CHILDREN" => array("core" => array("LABEL" => $mess["ajxp_conf.98"], "ICON" => "preferences_desktop.png", "LIST" => "listPlugins"), "plugins" => array("LABEL" => $mess["ajxp_conf.99"], "ICON" => "folder_development.png", "LIST" => "listPlugins"))), "admin" => array("LABEL" => $mess["ajxp_conf.111"], "ICON" => "toggle_log.png", "CHILDREN" => array("logs" => array("LABEL" => $mess["ajxp_conf.4"], "ICON" => "toggle_log.png", "LIST" => "listLogFiles"), "files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png", "LIST" => "listSharedFiles"), "diagnostic" => array("LABEL" => $mess["ajxp_conf.5"], "ICON" => "susehelpcenter.png", "LIST" => "printDiagnostic")))); AJXP_Controller::applyHook("ajxp_conf.list_config_nodes", array(&$rootNodes)); $dir = trim(AJXP_Utils::decodeSecureMagic(isset($httpVars["dir"]) ? $httpVars["dir"] : ""), " /"); if ($dir != "") { $splits = explode("/", $dir); $root = array_shift($splits); if (count($splits)) { $child = $splits[0]; if (strstr(urldecode($child), "#") !== false) { list($child, $hash) = explode("#", urldecode($child)); } if (isset($rootNodes[$root]["CHILDREN"][$child])) { $callback = $rootNodes[$root]["CHILDREN"][$child]["LIST"]; if (is_string($callback) && method_exists($this, $callback)) { AJXP_XMLWriter::header(); call_user_func(array($this, $callback), implode("/", $splits), $root, $hash); AJXP_XMLWriter::close(); } else { if (is_array($callback)) { call_user_func($callback, implode("/", $splits), $root, $hash); } } return; } } else { $parentName = "/" . $root . "/"; $nodes = $rootNodes[$root]["CHILDREN"]; } } else { $parentName = "/"; $nodes = $rootNodes; } if (isset($nodes)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.1" attributeName="ajxp_label" sortType="String"/></columns>'); foreach ($nodes as $key => $data) { print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '"/>'; } AJXP_XMLWriter::close(); } break; case "stat": header("Content-type:application/json"); print '{"mode":true}'; return; break; case "create_role": $roleId = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["role_id"]), AJXP_SANITIZE_HTML_STRICT); if (!strlen($roleId)) { throw new Exception($mess[349]); } if (AuthService::getRole($roleId) !== false) { throw new Exception($mess["ajxp_conf.65"]); } AuthService::updateRole(new AjxpRole($roleId)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null); AJXP_XMLWriter::reloadDataNode("", $httpVars["role_id"]); AJXP_XMLWriter::close(); break; case "edit_role": $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]); $role = AuthService::getRole($roleId); if ($role === false) { throw new Exception("Cant find role! "); } AJXP_XMLWriter::header("admin_data"); print AJXP_XMLWriter::writeRoleRepositoriesData($role); AJXP_XMLWriter::close("admin_data"); break; case "update_role_right": if (!isset($httpVars["role_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); print "<update_checkboxes user_id=\"" . $httpVars["role_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>"; AJXP_XMLWriter::close(); return; } $role = AuthService::getRole($httpVars["role_id"]); if ($role === false) { throw new Exception("Cant find role!"); } $role->setRight($httpVars["repository_id"], $httpVars["right"]); AuthService::updateRole($role); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.64"] . $httpVars["role_id"], null); print "<update_checkboxes user_id=\"" . $httpVars["role_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $role->canRead($httpVars["repository_id"]) . "\" write=\"" . $role->canWrite($httpVars["repository_id"]) . "\"/>"; //AJXP_XMLWriter::reloadRepositoryList(); AJXP_XMLWriter::close(); break; case "update_role_actions": if (!isset($httpVars["role_id"]) || !isset($httpVars["disabled_actions"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); return; } $role = AuthService::getRole($httpVars["role_id"]); if ($role === false) { throw new Exception("Cant find role!"); } $actions = explode(",", $httpVars["disabled_actions"]); // Clear and reload actions foreach ($role->getSpecificActionsRights("ajxp.all") as $actName => $actValue) { $role->setSpecificActionRight("ajxp.all", $actName, true); } foreach ($actions as $action) { if (($action = AJXP_Utils::sanitize($action, AJXP_SANITIZE_ALPHANUM)) == "") { continue; } $role->setSpecificActionRight("ajxp.all", $action, false); } AuthService::updateRole($role); AJXP_XMLWriter::header("admin_data"); print AJXP_XMLWriter::writeRoleRepositoriesData($role); AJXP_XMLWriter::close("admin_data"); break; case "update_role_default": if (!isset($httpVars["role_id"]) || !isset($httpVars["default_value"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); return; } $role = AuthService::getRole($httpVars["role_id"]); if ($role === false) { throw new Exception("Cannot find role!"); } $role->setDefault($httpVars["default_value"] == "true"); AuthService::updateRole($role); AJXP_XMLWriter::header("admin_data"); print AJXP_XMLWriter::writeRoleRepositoriesData($role); AJXP_XMLWriter::close("admin_data"); break; case "get_custom_params": $confStorage = ConfService::getConfStorageImpl(); AJXP_XMLWriter::header("admin_data"); $confDriver = ConfService::getConfStorageImpl(); $customData = $confDriver->options['CUSTOM_DATA']; if (is_array($customData) && count($customData) > 0) { print "<custom_data>"; foreach ($customData as $custName => $custValue) { print "<param name=\"{$custName}\" type=\"string\" label=\"{$custValue}\" description=\"\" value=\"\"/>"; } print "</custom_data>"; } AJXP_XMLWriter::close("admin_data"); break; case "edit_user": $confStorage = ConfService::getConfStorageImpl(); $userId = $httpVars["user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Invalid user id!"); } $userObject = $confStorage->createUserObject($userId); //print_r($userObject); AJXP_XMLWriter::header("admin_data"); AJXP_XMLWriter::sendUserData($userObject, true); // Add CUSTOM USER DATA $confDriver = ConfService::getConfStorageImpl(); $customData = $confDriver->options['CUSTOM_DATA']; if (is_array($customData) && count($customData) > 0) { $userCustom = $userObject->getPref("CUSTOM_PARAMS"); print "<custom_data>"; foreach ($customData as $custName => $custValue) { $value = isset($userCustom[$custName]) ? $userCustom[$custName] : ''; print "<param name=\"{$custName}\" type=\"string\" label=\"{$custValue}\" description=\"\" value=\"{$value}\"/>"; } print "</custom_data>"; } // Add WALLET DATA : DEFINITIONS AND VALUES print "<drivers>"; print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("user_param")); print "</drivers>"; $wallet = $userObject->getPref("AJXP_WALLET"); if (is_array($wallet) && count($wallet) > 0) { print "<user_wallet>"; foreach ($wallet as $repoId => $options) { foreach ($options as $optName => $optValue) { print "<wallet_data repo_id=\"{$repoId}\" option_name=\"{$optName}\" option_value=\"{$optValue}\"/>"; } } print "</user_wallet>"; } $editPass = $userId != "guest" ? "1" : "0"; $authDriver = ConfService::getAuthDriverImpl(); if (!$authDriver->passwordsEditable()) { $editPass = "******"; } print "<edit_options edit_pass=\"" . $editPass . "\" edit_admin_right=\"" . ($userId != "guest" && $userId != $loggedUser->getId() ? "1" : "0") . "\" edit_delete=\"" . ($userId != "guest" && $userId != $loggedUser->getId() && $authDriver->usersEditable() ? "1" : "0") . "\"/>"; print "<ajxp_roles>"; foreach (AuthService::getRolesList() as $roleId => $roleObject) { print "<role id=\"" . AJXP_Utils::xmlEntities($roleId) . "\"/>"; } print "</ajxp_roles>"; AJXP_XMLWriter::close("admin_data"); break; case "create_user": if (!isset($httpVars["new_user_login"]) || $httpVars["new_user_login"] == "" || !isset($httpVars["new_user_pwd"]) || $httpVars["new_user_pwd"] == "") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); return; } $new_user_login = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["new_user_login"]), AJXP_SANITIZE_EMAILCHARS); if (AuthService::userExists($new_user_login) || AuthService::isReservedUserId($new_user_login)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.43"]); AJXP_XMLWriter::close(); return; } $confStorage = ConfService::getConfStorageImpl(); $newUser = $confStorage->createUserObject($new_user_login); $customData = array(); $this->parseParameters($httpVars, $customData); if (is_array($customData) && count($customData) > 0) { $newUser->setPref("CUSTOM_PARAMS", $customData); } $newUser->save("superuser"); AuthService::createUser($new_user_login, $httpVars["new_user_pwd"]); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.44"], null); AJXP_XMLWriter::reloadDataNode("", $new_user_login); AJXP_XMLWriter::close(); break; case "change_admin_right": $userId = $httpVars["user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Invalid user id!"); } $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); $user->setAdmin($httpVars["right_value"] == "1" ? true : false); $user->save("superuser"); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.45"] . $httpVars["user_id"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; case "update_user_right": if (!isset($httpVars["user_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"]) || !AuthService::userExists($httpVars["user_id"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>"; AJXP_XMLWriter::close(); return; } $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($httpVars["user_id"]); $user->setRight(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM)); $user->save(); $loggedUser = AuthService::getLoggedUser(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["user_id"], null); print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $user->canRead($httpVars["repository_id"]) . "\" write=\"" . $user->canWrite($httpVars["repository_id"]) . "\"/>"; AJXP_XMLWriter::reloadRepositoryList(); AJXP_XMLWriter::close(); return; break; case "user_add_role": case "user_delete_role": if (!isset($httpVars["user_id"]) || !isset($httpVars["role_id"]) || !AuthService::userExists($httpVars["user_id"]) || !AuthService::getRole($httpVars["role_id"])) { throw new Exception($mess["ajxp_conf.61"]); } if ($action == "user_add_role") { $act = "add"; $messId = "73"; } else { $act = "remove"; $messId = "74"; } $this->updateUserRole($httpVars["user_id"], $httpVars["role_id"], $act); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . $messId] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); return; break; case "batch_users_roles": $confStorage = ConfService::getConfStorageImpl(); $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); $detectedRoles = array(); if (isset($httpVars["role_id"]) && isset($httpVars["update_role_action"])) { $update = $httpVars["update_role_action"]; $roleId = $httpVars["role_id"]; if (AuthService::getRole($roleId) === false) { throw new Exception("Invalid role id"); } } foreach ($files as $index => $file) { $userId = basename($file); if (isset($update)) { $userObject = $this->updateUserRole($userId, $roleId, $update); } else { $userObject = $confStorage->createUserObject($userId); } if ($userObject->hasParent()) { unset($files[$index]); continue; } $userRoles = $userObject->getRoles(); foreach ($userRoles as $roleIndex => $bool) { if (!isset($detectedRoles[$roleIndex])) { $detectedRoles[$roleIndex] = 0; } if ($bool === true) { $detectedRoles[$roleIndex]++; } } } $count = count($files); AJXP_XMLWriter::header("admin_data"); print "<user><ajxp_roles>"; foreach ($detectedRoles as $roleId => $roleCount) { if ($roleCount < $count) { continue; } print "<role id=\"{$roleId}\"/>"; } print "</ajxp_roles></user>"; print "<ajxp_roles>"; foreach (AuthService::getRolesList() as $roleId => $roleObject) { print "<role id=\"{$roleId}\"/>"; } print "</ajxp_roles>"; AJXP_XMLWriter::close("admin_data"); break; case "save_custom_user_params": $userId = $httpVars["user_id"]; if ($userId == $loggedUser->getId()) { $user = $loggedUser; } else { $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); } $custom = $user->getPref("CUSTOM_PARAMS"); if (!is_array($custom)) { $custom = array(); } $options = $custom; $this->parseParameters($httpVars, $options, $userId); $custom = $options; $user->setPref("CUSTOM_PARAMS", $custom); $user->save(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); break; case "save_repository_user_params": $userId = $httpVars["user_id"]; if ($userId == $loggedUser->getId()) { $user = $loggedUser; } else { $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); } $wallet = $user->getPref("AJXP_WALLET"); if (!is_array($wallet)) { $wallet = array(); } $repoID = $httpVars["repository_id"]; if (!array_key_exists($repoID, $wallet)) { $wallet[$repoID] = array(); } $options = $wallet[$repoID]; $this->parseParameters($httpVars, $options, $userId); $wallet[$repoID] = $options; $user->setPref("AJXP_WALLET", $wallet); $user->save(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); break; case "update_user_pwd": if (!isset($httpVars["user_id"]) || !isset($httpVars["user_pwd"]) || !AuthService::userExists($httpVars["user_id"]) || trim($httpVars["user_pwd"]) == "") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); return; } $res = AuthService::updatePassword($httpVars["user_id"], $httpVars["user_pwd"]); AJXP_XMLWriter::header(); if ($res === true) { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.48"] . $httpVars["user_id"], null); } else { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.49"] . " : {$res}"); } AJXP_XMLWriter::close(); break; case "save_user_preference": if (!isset($httpVars["user_id"]) || !AuthService::userExists($httpVars["user_id"])) { throw new Exception($mess["ajxp_conf.61"]); } $userId = $httpVars["user_id"]; if ($userId == $loggedUser->getId()) { $userObject = $loggedUser; } else { $confStorage = ConfService::getConfStorageImpl(); $userObject = $confStorage->createUserObject($userId); } $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"); $i++; } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage("Succesfully saved user preference", null); AJXP_XMLWriter::close(); break; case "get_drivers_definition": AJXP_XMLWriter::header("drivers"); print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("param", "", true)); AJXP_XMLWriter::close("drivers"); break; case "get_templates_definition": AJXP_XMLWriter::header("repository_templates"); $repositories = ConfService::getRepositoriesList(); foreach ($repositories as $repo) { if (!$repo->isTemplate) { continue; } $repoId = $repo->getUniqueId(); $repoLabel = $repo->getDisplay(); $repoType = $repo->getAccessType(); print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">"; foreach ($repo->getOptionsDefined() as $optionName) { print "<option name=\"{$optionName}\"/>"; } print "</template>"; } AJXP_XMLWriter::close("repository_templates"); break; case "create_repository": $options = array(); $repDef = $httpVars; $isTemplate = isset($httpVars["sf_checkboxes_active"]); unset($repDef["get_action"]); unset($repDef["sf_checkboxes_active"]); $this->parseParameters($repDef, $options); if (count($options)) { $repDef["DRIVER_OPTIONS"] = $options; } if (strstr($repDef["DRIVER"], "ajxp_template_") !== false) { $templateId = substr($repDef["DRIVER"], 14); $templateRepo = ConfService::getRepositoryById($templateId); $newRep = $templateRepo->createTemplateChild($repDef["DISPLAY"], $repDef["DRIVER_OPTIONS"]); } else { $pServ = AJXP_PluginsService::getInstance(); $driver = $pServ->getPluginByTypeName("access", $repDef["DRIVER"]); $newRep = ConfService::createRepositoryFromArray(0, $repDef); $testFile = $driver->getBaseDir() . "/test." . $newRep->getAccessType() . "Access.php"; if (!$isTemplate && is_file($testFile)) { //chdir(AJXP_TESTS_FOLDER."/plugins"); include $testFile; $className = $newRep->getAccessType() . "AccessTest"; $class = new $className(); $result = $class->doRepositoryTest($newRep); if (!$result) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $class->failedInfo); AJXP_XMLWriter::close(); return; } } // Apply default metasource if any if ($driver != null && $driver->getConfigs() != null) { $confs = $driver->getConfigs(); if (!empty($confs["DEFAULT_METASOURCES"])) { $metaIds = AJXP_Utils::parseCSL($confs["DEFAULT_METASOURCES"]); $metaSourceOptions = array(); foreach ($metaIds as $metaID) { $metaPlug = $pServ->getPluginById($metaID); if ($metaPlug == null) { continue; } $pNodes = $metaPlug->getManifestRawContent("//param[@default]", "nodes"); $defaultParams = array(); foreach ($pNodes as $domNode) { $defaultParams[$domNode->getAttribute("name")] = $domNode->getAttribute("default"); } $metaSourceOptions[$metaID] = $defaultParams; } $newRep->addOption("META_SOURCES", $metaSourceOptions); } } } if ($this->repositoryExists($newRep->getDisplay())) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]); AJXP_XMLWriter::close(); return; } if ($isTemplate) { $newRep->isTemplate = true; } $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]); } else { $loggedUser = AuthService::getLoggedUser(); $loggedUser->setRight($newRep->getUniqueId(), "rw"); $loggedUser->save("superuser"); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.52"], null); AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId()); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "edit_repository": $repId = $httpVars["repository_id"]; $repList = ConfService::getRootDirsList(); //print_r($repList); if (!isset($repList[$repId])) { throw new Exception("Cannot find repository with id {$repId}"); } $repository = $repList[$repId]; $pServ = AJXP_PluginsService::getInstance(); $plug = $pServ->getPluginById("access." . $repository->accessType); if ($plug == null) { throw new Exception("Cannot find access driver (" . $repository->accessType . ") for repository!"); } AJXP_XMLWriter::header("admin_data"); $slug = $repository->getSlug(); if ($slug == "" && $repository->isWriteable()) { $repository->setSlug(); ConfService::replaceRepository($repId, $repository); } $nested = array(); print "<repository index=\"{$repId}\""; foreach ($repository as $name => $option) { if (strstr($name, " ") > -1) { continue; } if (!is_array($option)) { if (is_bool($option)) { $option = $option ? "true" : "false"; } print " {$name}=\"" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($option)) . "\" "; } else { if (is_array($option)) { $nested[] = $option; } } } if (count($nested)) { print ">"; foreach ($nested as $option) { foreach ($option as $key => $optValue) { if (is_array($optValue) && count($optValue)) { print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>"; } else { if (is_bool($optValue)) { $optValue = $optValue ? "true" : "false"; } print "<param name=\"{$key}\" value=\"{$optValue}\"/>"; } } } // Add SLUG if (!$repository->isTemplate) { print "<param name=\"AJXP_SLUG\" value=\"" . $repository->getSlug() . "\"/>"; } print "</repository>"; } else { print "/>"; } if ($repository->hasParent()) { $parent = ConfService::getRepositoryById($repository->getParentId()); if (isset($parent) && $parent->isTemplate) { $parentLabel = $parent->getDisplay(); $parentType = $parent->getAccessType(); print "<template repository_id=\"" . $repository->getParentId() . "\" repository_label=\"{$parentLabel}\" repository_type=\"{$parentType}\">"; foreach ($parent->getOptionsDefined() as $parentOptionName) { print "<option name=\"{$parentOptionName}\"/>"; } print "</template>"; } } $manifest = $plug->getManifestRawContent("server_settings/param"); $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest); print "<ajxpdriver name=\"" . $repository->accessType . "\">{$manifest}</ajxpdriver>"; print "<metasources>"; $metas = $pServ->getPluginsByType("metastore"); $metas = array_merge($metas, $pServ->getPluginsByType("meta")); $metas = array_merge($metas, $pServ->getPluginsByType("index")); foreach ($metas as $metaPlug) { print "<meta id=\"" . $metaPlug->getId() . "\" label=\"" . AJXP_Utils::xmlEntities($metaPlug->getManifestLabel()) . "\">"; $manifest = $metaPlug->getManifestRawContent("server_settings/param"); $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest); print $manifest; print "</meta>"; } print "</metasources>"; AJXP_XMLWriter::close("admin_data"); return; break; case "edit_repository_label": case "edit_repository_data": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); $res = 0; if (isset($httpVars["newLabel"])) { $newLabel = AJXP_Utils::decodeSecureMagic($httpVars["newLabel"]); if ($this->repositoryExists($newLabel)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]); AJXP_XMLWriter::close(); return; } $repo->setDisplay($newLabel); $res = ConfService::replaceRepository($repId, $repo); } else { $options = array(); $this->parseParameters($httpVars, $options); if (count($options)) { foreach ($options as $key => $value) { if ($key == "AJXP_SLUG") { $repo->setSlug($value); continue; } $repo->addOption($key, $value); } } if (is_file(AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php")) { chdir(AJXP_TESTS_FOLDER . "/plugins"); include AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php"; $className = "ajxp_" . $repo->getAccessType(); $class = new $className(); $result = $class->doRepositoryTest($repo); if (!$result) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $class->failedInfo); AJXP_XMLWriter::close(); return; } } ConfService::replaceRepository($repId, $repo); } AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.53"]); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.54"], null); AJXP_XMLWriter::reloadDataNode("", isset($httpVars["newLabel"]) ? $repId : false); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "add_meta_source": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!is_object($repo)) { throw new Exception("Invalid repository id! {$repId}"); } $metaSourceType = AJXP_Utils::sanitize($httpVars["new_meta_source"], AJXP_SANITIZE_ALPHANUM); $options = array(); $this->parseParameters($httpVars, $options); $repoOptions = $repo->getOption("META_SOURCES"); if (is_array($repoOptions) && isset($repoOptions[$metaSourceType])) { throw new Exception($mess["ajxp_conf.55"]); } if (!is_array($repoOptions)) { $repoOptions = array(); } $repoOptions[$metaSourceType] = $options; uksort($repoOptions, array($this, "metaSourceOrderingFunction")); $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.56"], null); AJXP_XMLWriter::close(); break; case "delete_meta_source": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!is_object($repo)) { throw new Exception("Invalid repository id! {$repId}"); } $metaSourceId = $httpVars["plugId"]; $repoOptions = $repo->getOption("META_SOURCES"); if (is_array($repoOptions) && array_key_exists($metaSourceId, $repoOptions)) { unset($repoOptions[$metaSourceId]); uksort($repoOptions, array($this, "metaSourceOrderingFunction")); $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.57"], null); AJXP_XMLWriter::close(); break; case "edit_meta_source": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); if (!is_object($repo)) { throw new Exception("Invalid repository id! {$repId}"); } $metaSourceId = $httpVars["plugId"]; $options = array(); $this->parseParameters($httpVars, $options); $repoOptions = $repo->getOption("META_SOURCES"); if (!is_array($repoOptions)) { $repoOptions = array(); } $repoOptions[$metaSourceId] = $options; uksort($repoOptions, array($this, "metaSourceOrderingFunction")); $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.58"], null); AJXP_XMLWriter::close(); break; case "delete": if (isset($httpVars["repository_id"])) { $repId = $httpVars["repository_id"]; $res = ConfService::deleteRepository($repId); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); return; } else { if (isset($httpVars["shared_file"])) { AJXP_XMLWriter::header(); $element = basename($httpVars["shared_file"]); $dlFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); $publicletData = $this->loadPublicletData($dlFolder . "/" . $element . ".php"); unlink($dlFolder . "/" . $element . ".php"); AJXP_XMLWriter::sendMessage($mess["ajxp_shared.13"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } else { if (isset($httpVars["role_id"])) { $roleId = $httpVars["role_id"]; if (AuthService::getRole($roleId) === false) { throw new Exception($mess["ajxp_conf.67"]); } AuthService::deleteRole($roleId); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } else { if (!isset($httpVars["user_id"]) || $httpVars["user_id"] == "" || AuthService::isReservedUserId($httpVars["user_id"]) || $loggedUser->getId() == $httpVars["user_id"]) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); } $res = AuthService::deleteUser($httpVars["user_id"]); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } } } break; case "clear_expired": $deleted = $this->clearExpiredFiles(); AJXP_XMLWriter::header(); if (count($deleted)) { AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null); AJXP_XMLWriter::reloadDataNode(); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null); } AJXP_XMLWriter::close(); break; case "get_plugin_manifest": $ajxpPlugin = AJXP_PluginsService::getInstance()->getPluginById($httpVars["plugin_id"]); AJXP_XMLWriter::header("admin_data"); echo AJXP_XMLWriter::replaceAjxpXmlKeywords($ajxpPlugin->getManifestRawContent()); $definitions = $ajxpPlugin->getConfigsDefinitions(); $values = $ajxpPlugin->getConfigs(); if (!is_array($values)) { $values = array(); } echo "<plugin_settings_values>"; foreach ($values as $key => $value) { if ($definitions[$key]["type"] == "array" && is_array($value)) { $value = implode(",", $value); } else { if ($definitions[$key]["type"] == "boolean") { $value = $value === true || $value === "true" || $value == 1 ? "true" : "false"; } else { if ($definitions[$key]["type"] == "textarea") { //$value = str_replace("\\n", "\n", $value); } } } echo "<param name=\"{$key}\" value=\"" . AJXP_Utils::xmlEntities($value) . "\"/>"; } if ($ajxpPlugin->getType() != "core") { echo "<param name=\"AJXP_PLUGIN_ENABLED\" value=\"" . ($ajxpPlugin->isEnabled() ? "true" : "false") . "\"/>"; } echo "</plugin_settings_values>"; echo "<plugin_doc><![CDATA[<p>" . $ajxpPlugin->getPluginInformationHTML("Charles du Jeu", "http://ajaxplorer.info/plugins/") . "</p>"; if (file_exists($ajxpPlugin->getBaseDir() . "/plugin_doc.html")) { echo file_get_contents($ajxpPlugin->getBaseDir() . "/plugin_doc.html"); } echo "]]></plugin_doc>"; AJXP_XMLWriter::close("admin_data"); break; case "edit_plugin_options": $options = array(); $this->parseParameters($httpVars, $options); $confStorage = ConfService::getConfStorageImpl(); $confStorage->savePluginConfig($httpVars["plugin_id"], $options); @unlink(AJXP_PLUGINS_CACHE_FILE); @unlink(AJXP_PLUGINS_REQUIRES_FILE); @unlink(AJXP_PLUGINS_MESSAGES_FILE); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.97"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; default: break; } return; }
public function switchAction($action, $httpVars, $fileVars) { parent::accessPreprocess($action, $httpVars, $fileVars); if (!AuthService::usersEnabled()) { return; } if ($action == "edit") { if (isset($httpVars["sub_action"])) { $action = $httpVars["sub_action"]; } } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // BASIC LISTING //------------------------------------ case "ls": $rootNodes = array("users" => array("LABEL" => $mess["user_dash.1"], "ICON" => "user_shared.png", "ICON-CLASS" => "icon-book", "DESCRIPTION" => $mess["user_dash.30"]), "files" => array("LABEL" => $mess["user_dash.34"], "ICON" => "user_shared.png", "ICON-CLASS" => "mdi mdi-share-variant", "DESCRIPTION" => $mess["user_dash.35"]), "settings" => array("LABEL" => $mess["user_dash.36"], "ICON" => "user_shared.png", "ICON-CLASS" => "icon-cog", "DESCRIPTION" => $mess["user_dash.37"]), "repositories" => array("LABEL" => $mess["user_dash.36"], "ICON" => "user_shared.png", "ICON-CLASS" => "icon-cog", "DESCRIPTION" => $mess["user_dash.37"]), "teams" => array("LABEL" => "Teams", "ICON" => "user_shared.png", "ICON-CLASS" => "icon-group", "DESCRIPTION" => "My Teams")); $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : ""; $splits = explode("/", $dir); if (count($splits)) { if ($splits[0] == "") { array_shift($splits); } if (count($splits)) { $strippedDir = strtolower(urldecode($splits[0])); } else { $strippedDir = ""; } } if (array_key_exists($strippedDir, $rootNodes)) { AJXP_XMLWriter::header(); if ($strippedDir == "users") { $this->listUsers(); } else { if ($strippedDir == "teams") { $this->listTeams(); } else { if ($strippedDir == "repositories") { $this->listRepositories(); } else { if ($strippedDir == "files") { $this->listSharedFiles("files"); } } } } AJXP_XMLWriter::close(); } else { AJXP_XMLWriter::header(); /* AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="user_dash.8" attributeName="ajxp_label" sortType="String"/><column messageId="user_dash.31" attributeName="description" sortType="String"/></columns>'); foreach ($rootNodes as $key => $data) { $l = $data["LABEL"]; print '<tree text="'.$l.'" icon="'.$data["ICON"].'" filename="/'.$key.'" parentname="/" description="'.$data["DESCRIPTION"].'" />'; } */ AJXP_XMLWriter::close(); } break; case "stat": header("Content-type:application/json"); print '{"mode":true}'; break; case "delete": $mime = $httpVars["ajxp_mime"]; $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); AJXP_XMLWriter::header(); $minisites = $this->listSharedFiles("minisites"); /** * @var ShareCenter $shareCenter */ $shareCenter = AJXP_PluginsService::findPluginById("action.share"); foreach ($files as $index => $element) { $element = basename($element); $ar = explode("shared_", $mime); $mime = array_pop($ar); if ($mime == "repository" && isset($minisites[$element])) { $mime = "minisite"; $element = $minisites[$element]; } $shareCenter->getShareStore()->deleteShare($mime, $element); if ($mime == "repository" || $mime == "minisite") { $out = $mess["ajxp_conf.59"]; } else { if ($mime == "user") { $out = $mess["ajxp_conf.60"]; } else { if ($mime == "file") { $out = $mess["user_dash.13"]; } } } } AJXP_XMLWriter::sendMessage($out, null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; case "clear_expired": /** * @var ShareCenter $shareCenter */ $shareCenter = AJXP_PluginsService::getInstance()->findPluginById("action.share"); $deleted = $shareCenter->getShareStore()->clearExpiredFiles(true); AJXP_XMLWriter::header(); if (count($deleted)) { AJXP_XMLWriter::sendMessage(sprintf($mess["user_dash.23"], count($deleted) . ""), null); AJXP_XMLWriter::reloadDataNode(); } else { AJXP_XMLWriter::sendMessage($mess["user_dash.24"], null); } AJXP_XMLWriter::close(); break; case "reset_download_counter": $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $elements = $selection->getFiles(); foreach ($elements as $element) { PublicletCounter::reset(str_replace(".php", "", basename($element))); } AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; default: break; } return; }
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; }
function crossRepositoryCopy($httpVars) { ConfService::detectRepositoryStreams(true); $mess = ConfService::getMessages(); $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); $accessType = $this->repository->getAccessType(); $repositoryId = $this->repository->getId(); $plugin = AJXP_PluginsService::findPlugin("access", $accessType); $origWrapperData = $plugin->detectStreamWrapper(true); $origStreamURL = $origWrapperData["protocol"] . "://{$repositoryId}"; $destRepoId = $httpVars["dest_repository_id"]; $destRepoObject = ConfService::getRepositoryById($destRepoId); $destRepoAccess = $destRepoObject->getAccessType(); $plugin = AJXP_PluginsService::findPlugin("access", $destRepoAccess); $destWrapperData = $plugin->detectStreamWrapper(true); $destStreamURL = $destWrapperData["protocol"] . "://{$destRepoId}"; // Check rights if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId) || isset($httpVars["moving_files"]) && !$loggedUser->canWrite($repositoryId)) { throw new Exception($mess[364]); } } $messages = array(); foreach ($files as $file) { $origFile = $origStreamURL . $file; $localName = ""; AJXP_Controller::applyHook("dl.localname", array($origFile, &$localName, $origWrapperData["classname"])); $bName = basename($file); if ($localName != "") { $bName = $localName; } $destFile = $destStreamURL . SystemTextEncoding::fromUTF8($httpVars["dest"]) . "/" . $bName; AJXP_Logger::debug("Copying {$origFile} to {$destFile}"); if (!is_file($origFile)) { throw new Exception("Cannot find {$origFile}"); } $origHandler = fopen($origFile, "r"); $destHandler = fopen($destFile, "w"); if ($origHandler === false || $destHandler === false) { $errorMessages[] = AJXP_XMLWriter::sendMessage(null, $mess[114] . " ({$origFile} to {$destFile})", false); continue; } while (!feof($origHandler)) { fwrite($destHandler, fread($origHandler, 4096)); } fflush($destHandler); fclose($origHandler); fclose($destHandler); $messages[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($origFile)) . " " . (isset($httpVars["moving_files"]) ? $mess[74] : $mess[73]) . " " . SystemTextEncoding::toUTF8($destFile); } AJXP_XMLWriter::header(); if (count($errorMessages)) { AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true); } AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true); AJXP_XMLWriter::close(); }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $loggedUser = AuthService::getLoggedUser(); if (ENABLE_USERS && !$loggedUser->isAdmin()) { return; } if ($action == "edit") { if (isset($httpVars["sub_action"])) { $action = $httpVars["sub_action"]; } } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // BASIC LISTING //------------------------------------ case "ls": $rootNodes = array("repositories" => array("LABEL" => $mess["ajxp_conf.3"], "ICON" => "folder_red.png"), "users" => array("LABEL" => $mess["ajxp_conf.2"], "ICON" => "yast_kuser.png"), "roles" => array("LABEL" => $mess["ajxp_conf.69"], "ICON" => "user_group_new.png"), "files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png"), "logs" => array("LABEL" => $mess["ajxp_conf.4"], "ICON" => "toggle_log.png"), "diagnostic" => array("LABEL" => $mess["ajxp_conf.5"], "ICON" => "susehelpcenter.png")); $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : ""; $splits = explode("/", $dir); if (count($splits)) { if ($splits[0] == "") { array_shift($splits); } if (count($splits)) { $strippedDir = strtolower(urldecode($splits[0])); } else { $strippedDir = ""; } } if (array_key_exists($strippedDir, $rootNodes)) { AJXP_XMLWriter::header(); if ($strippedDir == "users") { $this->listUsers(); } else { if ($strippedDir == "roles") { $this->listRoles(); } else { if ($strippedDir == "repositories") { $this->listRepositories(); } else { if ($strippedDir == "logs") { $this->listLogFiles($dir); } else { if ($strippedDir == "diagnostic") { $this->printDiagnostic(); } else { if ($strippedDir == "files") { $this->listSharedFiles(); } } } } } } AJXP_XMLWriter::close(); exit(1); } else { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.1" attributeName="ajxp_label" sortType="String"/></columns>'); foreach ($rootNodes as $key => $data) { $src = ''; if ($key == "logs") { $src = 'src="content.php?get_action=ls&dir=' . $key . '"'; } print '<tree text="' . $data["LABEL"] . '" icon="' . $data["ICON"] . '" filename="/' . $key . '" parentname="/" ' . $src . ' />'; } AJXP_XMLWriter::close(); exit(1); } break; case "stat": header("Content-type:application/json"); print '{"mode":true}'; exit(1); break; case "create_role": $roleId = $httpVars["role_id"]; if (AuthService::getRole($roleId) !== false) { throw new Exception($mess["ajxp_conf.65"]); } AuthService::updateRole(new AjxpRole($roleId)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null); AJXP_XMLWriter::reloadDataNode("", $httpVars["role_id"]); AJXP_XMLWriter::close(); break; case "edit_role": $roleId = $httpVars["role_id"]; $role = AuthService::getRole($roleId); AJXP_XMLWriter::header("admin_data"); print AJXP_XMLWriter::writeRoleRepositoriesData($role); AJXP_XMLWriter::close("admin_data"); break; case "update_role_right": if (!isset($httpVars["role_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); print "<update_checkboxes user_id=\"" . $httpVars["role_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>"; AJXP_XMLWriter::close(); return; //exit(1); } $role = AuthService::getRole($httpVars["role_id"]); $role->setRight($httpVars["repository_id"], $httpVars["right"]); AuthService::updateRole($role); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.64"] . $httpVars["role_id"], null); print "<update_checkboxes user_id=\"" . $httpVars["role_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $role->canRead($httpVars["repository_id"]) . "\" write=\"" . $role->canWrite($httpVars["repository_id"]) . "\"/>"; //AJXP_XMLWriter::reloadRepositoryList(); AJXP_XMLWriter::close(); //exit(1); break; case "update_role_actions": if (!isset($httpVars["role_id"]) || !isset($httpVars["disabled_actions"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); return; } $role = AuthService::getRole($httpVars["role_id"]); $actions = array_map("trim", explode(",", $httpVars["disabled_actions"])); // Clear and reload actions foreach ($role->getSpecificActionsRights("ajxp.all") as $actName => $actValue) { $role->setSpecificActionRight("ajxp.all", $actName, true); } foreach ($actions as $action) { if ($action == "") { continue; } $role->setSpecificActionRight("ajxp.all", $action, false); } AuthService::updateRole($role); AJXP_XMLWriter::header("admin_data"); print AJXP_XMLWriter::writeRoleRepositoriesData($role); AJXP_XMLWriter::close("admin_data"); break; case "edit_user": $confStorage = ConfService::getConfStorageImpl(); $userId = $httpVars["user_id"]; $userObject = $confStorage->createUserObject($userId); //print_r($userObject); AJXP_XMLWriter::header("admin_data"); AJXP_XMLWriter::sendUserData($userObject, true); // Add WALLET DATA : DEFINITIONS AND VALUES print "<drivers>"; print ConfService::availableDriversToXML("user_param"); print "</drivers>"; $wallet = $userObject->getPref("AJXP_WALLET"); if (is_array($wallet) && count($wallet) > 0) { print "<user_wallet>"; foreach ($wallet as $repoId => $options) { foreach ($options as $optName => $optValue) { print "<wallet_data repo_id=\"{$repoId}\" option_name=\"{$optName}\" option_value=\"{$optValue}\"/>"; } } print "</user_wallet>"; } $editPass = $userId != "guest" ? "1" : "0"; $authDriver = ConfService::getAuthDriverImpl(); if (!$authDriver->passwordsEditable()) { $editPass = "******"; } print "<edit_options edit_pass=\"" . $editPass . "\" edit_admin_right=\"" . ($userId != "guest" && $userId != $loggedUser->getId() ? "1" : "0") . "\" edit_delete=\"" . ($userId != "guest" && $userId != $loggedUser->getId() && $authDriver->usersEditable() ? "1" : "0") . "\"/>"; print "<ajxp_roles>"; foreach (AuthService::getRolesList() as $roleId => $roleObject) { print "<role id=\"{$roleId}\"/>"; } print "</ajxp_roles>"; AJXP_XMLWriter::close("admin_data"); exit(1); break; case "create_user": if (!isset($httpVars["new_user_login"]) || $httpVars["new_user_login"] == "" || !isset($httpVars["new_user_pwd"]) || $httpVars["new_user_pwd"] == "") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); exit(1); } $forbidden = array("guest", "share"); if (AuthService::userExists($httpVars["new_user_login"]) || in_array($httpVars["new_user_login"], $forbidden)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.43"]); AJXP_XMLWriter::close(); exit(1); } if (get_magic_quotes_gpc()) { $httpVars["new_user_login"] = stripslashes($httpVars["new_user_login"]); } $httpVars["new_user_login"] = str_replace("'", "", $httpVars["new_user_login"]); $confStorage = ConfService::getConfStorageImpl(); $newUser = $confStorage->createUserObject($httpVars["new_user_login"]); $newUser->save(); AuthService::createUser($httpVars["new_user_login"], $httpVars["new_user_pwd"]); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.44"], null); AJXP_XMLWriter::reloadFileList($httpVars["new_user_login"]); AJXP_XMLWriter::close(); exit(1); break; case "change_admin_right": $userId = $httpVars["user_id"]; $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); $user->setAdmin($httpVars["right_value"] == "1" ? true : false); $user->save(); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.45"] . $httpVars["user_id"], null); AJXP_XMLWriter::reloadFileList(false); AJXP_XMLWriter::close(); exit(1); break; case "update_user_right": if (!isset($httpVars["user_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"]) || !AuthService::userExists($httpVars["user_id"])) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>"; AJXP_XMLWriter::close(); exit(1); } $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($httpVars["user_id"]); $user->setRight($httpVars["repository_id"], $httpVars["right"]); $user->save(); $loggedUser = AuthService::getLoggedUser(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["user_id"], null); print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $user->canRead($httpVars["repository_id"]) . "\" write=\"" . $user->canWrite($httpVars["repository_id"]) . "\"/>"; AJXP_XMLWriter::reloadRepositoryList(); AJXP_XMLWriter::close(); return; break; case "user_add_role": case "user_delete_role": if (!isset($httpVars["user_id"]) || !isset($httpVars["role_id"]) || !AuthService::userExists($httpVars["user_id"])) { throw new Exception($mess["ajxp_conf.61"]); } if ($action == "user_add_role") { $act = "add"; $messId = "73"; } else { $act = "remove"; $messId = "74"; } $this->updateUserRole($httpVars["user_id"], $httpVars["role_id"], $act); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . $messId] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); return; break; case "batch_users_roles": $confStorage = ConfService::getConfStorageImpl(); $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); $detectedRoles = array(); if (isset($httpVars["role_id"]) && isset($httpVars["update_role_action"])) { $update = $httpVars["update_role_action"]; $roleId = $httpVars["role_id"]; } foreach ($files as $index => $file) { $userId = basename($file); if (isset($update)) { $userObject = $this->updateUserRole($userId, $roleId, $update); } else { $userObject = $confStorage->createUserObject($userId); } if ($userObject->hasParent()) { unset($files[$index]); continue; } $userRoles = $userObject->getRoles(); foreach ($userRoles as $roleIndex => $bool) { if (!isset($detectedRoles[$roleIndex])) { $detectedRoles[$roleIndex] = 0; } if ($bool === true) { $detectedRoles[$roleIndex]++; } } } $count = count($files); AJXP_XMLWriter::header("admin_data"); print "<user><ajxp_roles>"; foreach ($detectedRoles as $roleId => $roleCount) { if ($roleCount < $count) { continue; } print "<role id=\"{$roleId}\"/>"; } print "</ajxp_roles></user>"; print "<ajxp_roles>"; foreach (AuthService::getRolesList() as $roleId => $roleObject) { print "<role id=\"{$roleId}\"/>"; } print "</ajxp_roles>"; AJXP_XMLWriter::close("admin_data"); break; case "save_repository_user_params": $userId = $httpVars["user_id"]; if ($userId == $loggedUser->getId()) { $user = $loggedUser; } else { $confStorage = ConfService::getConfStorageImpl(); $user = $confStorage->createUserObject($userId); } $wallet = $user->getPref("AJXP_WALLET"); if (!is_array($wallet)) { $wallet = array(); } $repoID = $httpVars["repository_id"]; if (!array_key_exists($repoID, $wallet)) { $wallet[$repoID] = array(); } $options = $wallet[$repoID]; $this->parseParameters($httpVars, $options, $userId); $wallet[$repoID] = $options; $user->setPref("AJXP_WALLET", $wallet); $user->save(); if ($loggedUser->getId() == $user->getId()) { AuthService::updateUser($user); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null); AJXP_XMLWriter::close(); exit(1); break; case "update_user_pwd": if (!isset($httpVars["user_id"]) || !isset($httpVars["user_pwd"]) || !AuthService::userExists($httpVars["user_id"]) || trim($httpVars["user_pwd"]) == "") { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); exit(1); } $res = AuthService::updatePassword($httpVars["user_id"], $httpVars["user_pwd"]); AJXP_XMLWriter::header(); if ($res === true) { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.48"] . $httpVars["user_id"], null); } else { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.49"] . " : {$res}"); } AJXP_XMLWriter::close(); exit(1); break; case "get_drivers_definition": AJXP_XMLWriter::header("drivers"); print ConfService::availableDriversToXML("param"); AJXP_XMLWriter::close("drivers"); exit(1); break; case "create_repository": $options = array(); $repDef = $httpVars; unset($repDef["get_action"]); $this->parseParameters($repDef, $options); if (count($options)) { $repDef["DRIVER_OPTIONS"] = $options; } // NOW SAVE THIS REPOSITORY! $newRep = ConfService::createRepositoryFromArray(0, $repDef); if (is_file(INSTALL_PATH . "/server/tests/plugins/test.ajxp_" . $newRep->getAccessType() . ".php")) { chdir(INSTALL_PATH . "/server/tests/plugins"); include INSTALL_PATH . "/server/tests/plugins/test.ajxp_" . $newRep->getAccessType() . ".php"; $className = "ajxp_" . $newRep->getAccessType(); $class = new $className(); $result = $class->doRepositoryTest($newRep); if (!$result) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $class->failedInfo); AJXP_XMLWriter::close(); exit(1); } } if ($this->repositoryExists($newRep->getDisplay())) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]); AJXP_XMLWriter::close(); exit(1); } $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]); } else { $confStorage = ConfService::getConfStorageImpl(); $loggedUser = AuthService::getLoggedUser(); $loggedUser->setRight($newRep->getUniqueId(), "rw"); $loggedUser->save(); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.52"], null); AJXP_XMLWriter::reloadFileList($newRep->getDisplay()); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); exit(1); break; case "edit_repository": $repId = $httpVars["repository_id"]; $repList = ConfService::getRootDirsList(); //print_r($repList); AJXP_XMLWriter::header("admin_data"); if (!isset($repList[$repId])) { AJXP_XMLWriter::close("admin_data"); exit(1); } $repository = $repList[$repId]; $nested = array(); print "<repository index=\"{$repId}\""; foreach ($repository as $name => $option) { if (!is_array($option)) { if (is_bool($option)) { $option = $option ? "true" : "false"; } print " {$name}=\"" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($option)) . "\" "; } else { if (is_array($option)) { $nested[] = $option; } } } if (count($nested)) { print ">"; foreach ($nested as $option) { foreach ($option as $key => $optValue) { if (is_array($optValue) && count($optValue)) { print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>"; } else { if (is_bool($optValue)) { $optValue = $optValue ? "true" : "false"; } print "<param name=\"{$key}\" value=\"{$optValue}\"/>"; } } } print "</repository>"; } else { print "/>"; } $pServ = AJXP_PluginsService::getInstance(); $plug = $pServ->getPluginById("access." . $repository->accessType); $manifest = $plug->getManifestRawContent("server_settings/param"); print "<ajxpdriver name=\"" . $repository->accessType . "\">{$manifest}</ajxpdriver>"; print "<metasources>"; $metas = $pServ->getPluginsByType("meta"); foreach ($metas as $metaPlug) { print "<meta id=\"" . $metaPlug->getId() . "\">"; $manifest = $metaPlug->getManifestRawContent("server_settings/param"); print $manifest; print "</meta>"; } print "</metasources>"; AJXP_XMLWriter::close("admin_data"); exit(1); break; case "edit_repository_label": case "edit_repository_data": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); $res = 0; if (isset($httpVars["newLabel"])) { $newLabel = SystemTextEncoding::fromPostedFileName($httpVars["newLabel"]); if ($this->repositoryExists($newLabel)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]); AJXP_XMLWriter::close(); exit(1); } $repo->setDisplay($newLabel); $res = ConfService::replaceRepository($repId, $repo); } else { $options = array(); $this->parseParameters($httpVars, $options); if (count($options)) { foreach ($options as $key => $value) { $repo->addOption($key, $value); } } if (is_file(INSTALL_PATH . "/server/tests/plugins/test.ajxp_" . $repo->getAccessType() . ".php")) { chdir(INSTALL_PATH . "/server/tests/plugins"); include INSTALL_PATH . "/server/tests/plugins/test.ajxp_" . $repo->getAccessType() . ".php"; $className = "ajxp_" . $repo->getAccessType(); $class = new $className(); $result = $class->doRepositoryTest($repo); if (!$result) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $class->failedInfo); AJXP_XMLWriter::close(); exit(1); } } ConfService::replaceRepository($repId, $repo); } AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.53"]); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.54"], null); AJXP_XMLWriter::reloadDataNode("", isset($httpVars["newLabel"]) ? SystemTextEncoding::fromPostedFileName($httpVars["newLabel"]) : false); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); exit(1); case "add_meta_source": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); $metaSourceType = $httpVars["new_meta_source"]; $options = array(); $this->parseParameters($httpVars, $options); $repoOptions = $repo->getOption("META_SOURCES"); if (is_array($repoOptions) && isset($repoOptions[$metaSourceType])) { throw new Exception($mess["ajxp_conf.55"]); } if (!is_array($repoOptions)) { $repoOptions = array(); } $repoOptions[$metaSourceType] = $options; $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.56"], null); AJXP_XMLWriter::close(); break; case "delete_meta_source": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); $metaSourceId = $httpVars["plugId"]; $repoOptions = $repo->getOption("META_SOURCES"); if (is_array($repoOptions) && array_key_exists($metaSourceId, $repoOptions)) { unset($repoOptions[$metaSourceId]); $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); } AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.57"], null); AJXP_XMLWriter::close(); break; case "edit_meta_source": $repId = $httpVars["repository_id"]; $repo = ConfService::getRepositoryById($repId); $metaSourceId = $httpVars["plugId"]; $options = array(); $this->parseParameters($httpVars, $options); $repoOptions = $repo->getOption("META_SOURCES"); if (!is_array($repoOptions)) { $repoOptions = array(); } $repoOptions[$metaSourceId] = $options; $repo->addOption("META_SOURCES", $repoOptions); ConfService::replaceRepository($repId, $repo); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.58"], null); AJXP_XMLWriter::close(); break; case "delete": if (isset($httpVars["repository_id"])) { $repId = $httpVars["repository_id"]; //if(get_magic_quotes_gpc()) $repLabel = stripslashes($repLabel); $res = ConfService::deleteRepository($repId); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); exit(1); } else { if (isset($httpVars["shared_file"])) { AJXP_XMLWriter::header(); $element = basename($httpVars["shared_file"]); $publicletData = $this->loadPublicletData(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php"); unlink(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php"); AJXP_XMLWriter::sendMessage($mess["ajxp_shared.13"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } else { if (isset($httpVars["role_id"])) { $roleId = $httpVars["role_id"]; if (AuthService::getRole($roleId) === false) { throw new Exception($mess["ajxp_conf.67"]); } AuthService::deleteRole($roleId); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); } else { $forbidden = array("guest", "share"); if (!isset($httpVars["user_id"]) || $httpVars["user_id"] == "" || in_array($httpVars["user_id"], $forbidden) || $loggedUser->getId() == $httpVars["user_id"]) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]); AJXP_XMLWriter::close(); exit(1); } $res = AuthService::deleteUser($httpVars["user_id"]); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); exit(1); } } } break; case "clear_expired": $deleted = $this->clearExpiredFiles(); AJXP_XMLWriter::header(); if (count($deleted)) { AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null); AJXP_XMLWriter::reloadDataNode(); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null); } AJXP_XMLWriter::close(); break; default: break; } return; }
/** * Extract an archive directly inside the dest directory. * * @param string $destDir * @param UserSelection $selection * @param array $error * @param array $success */ function extractArchive($destDir, $selection, &$error, &$success) { require_once "server/classes/pclzip.lib.php"; $zipPath = $selection->getZipPath(true); $zipLocalPath = $selection->getZipLocalPath(true); if (strlen($zipLocalPath) > 1 && $zipLocalPath[0] == "/") { $zipLocalPath = substr($zipLocalPath, 1) . "/"; } $files = $selection->getFiles(); $realZipFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . $zipPath); $archive = new PclZip($realZipFile); $content = $archive->listContent(); foreach ($files as $key => $item) { // Remove path $item = substr($item, strlen($zipPath)); if ($item[0] == "/") { $item = substr($item, 1); } foreach ($content as $zipItem) { if ($zipItem["stored_filename"] == $item || $zipItem["stored_filename"] == $item . "/") { $files[$key] = $zipItem["stored_filename"]; break; } else { unset($files[$key]); } } } AJXP_Logger::debug("Archive", $files); $realDestination = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . $destDir); AJXP_Logger::debug("Extract", array($realDestination, $realZipFile, $files, $zipLocalPath)); $result = $archive->extract(PCLZIP_OPT_BY_NAME, $files, PCLZIP_OPT_PATH, $realDestination, PCLZIP_OPT_REMOVE_PATH, $zipLocalPath); if ($result <= 0) { $error[] = $archive->errorInfo(true); } else { $mess = ConfService::getMessages(); $success[] = sprintf($mess[368], basename($zipPath), $destDir); } }
function crossRepositoryCopy($httpVars) { ConfService::detectRepositoryStreams(true); $mess = ConfService::getMessages(); $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); $accessType = $this->repository->getAccessType(); $repositoryId = $this->repository->getId(); $origStreamURL = "ajxp.{$accessType}://{$repositoryId}"; $destRepoId = $httpVars["dest_repository_id"]; $destRepoObject = ConfService::getRepositoryById($destRepoId); $destRepoAccess = $destRepoObject->getAccessType(); $destStreamURL = "ajxp.{$destRepoAccess}://{$destRepoId}"; // Check rights if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, "You do not have the right to access one of the repositories!"); AJXP_XMLWriter::close(); exit(1); } } $messages = array(); foreach ($files as $file) { $origFile = $origStreamURL . $file; $destFile = $destStreamURL . $httpVars["dest"] . "/" . basename($file); $origHandler = fopen($origFile, "r"); $destHandler = fopen($destFile, "w"); if ($origHandler === false || $destHandler === false) { $errorMessages[] = AJXP_XMLWriter::sendMessage(null, $mess[114] . " ({$origFile} to {$destFile})", false); continue; } while (!feof($origHandler)) { fwrite($destHandler, fread($origHandler, 4096)); } fflush($destHandler); fclose($origHandler); fclose($destHandler); $messages[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($origFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destFile); } AJXP_XMLWriter::header(); if (count($errorMessages)) { AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true); } AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true); AJXP_XMLWriter::close(); exit(0); }
/** * Extract an archive directly inside the dest directory. * * @param string $destDir * @param UserSelection $selection * @param array $error * @param array $success */ public function extractArchive($destDir, $selection, &$error, &$success) { require_once AJXP_BIN_FOLDER . "/pclzip.lib.php"; $zipPath = $selection->getZipPath(true); $zipLocalPath = $selection->getZipLocalPath(true); if (strlen($zipLocalPath) > 1 && $zipLocalPath[0] == "/") { $zipLocalPath = substr($zipLocalPath, 1) . "/"; } $files = $selection->getFiles(); $realZipFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . $zipPath); $archive = new PclZip($realZipFile); $content = $archive->listContent(); foreach ($files as $key => $item) { // Remove path $item = substr($item, strlen($zipPath)); if ($item[0] == "/") { $item = substr($item, 1); } foreach ($content as $zipItem) { if ($zipItem["stored_filename"] == $item || $zipItem["stored_filename"] == $item . "/") { $files[$key] = $zipItem["stored_filename"]; break; } else { unset($files[$key]); } } } $this->logDebug("Archive", $this->addSlugToPath($files)); $realDestination = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . $destDir); $this->logDebug("Extract", array($realDestination, $realZipFile, $this->addSlugToPath($files), $zipLocalPath)); self::$currentZipOperationHandler =& $this; $result = $archive->extract(PCLZIP_OPT_BY_NAME, $files, PCLZIP_OPT_PATH, $realDestination, PCLZIP_OPT_REMOVE_PATH, $zipLocalPath, PCLZIP_CB_PRE_EXTRACT, "staticExtractArchiveItemPreCallback", PCLZIP_CB_POST_EXTRACT, "staticExtractArchiveItemPostCallback", PCLZIP_OPT_STOP_ON_ERROR); self::$currentZipOperationHandler = null; if ($result <= 0) { $error[] = $archive->errorInfo(true); } else { $mess = ConfService::getMessages(); $success[] = sprintf($mess[368], basename($zipPath), $destDir); } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $loggedUser = AuthService::getLoggedUser(); if (!ENABLE_USERS) { return; } if ($action == "edit") { if (isset($httpVars["sub_action"])) { $action = $httpVars["sub_action"]; } } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // BASIC LISTING //------------------------------------ case "ls": $rootNodes = array("files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png", "DESCRIPTION" => $mess["ajxp_shared.28"]), "repositories" => array("LABEL" => $mess["ajxp_shared.2"], "ICON" => "document_open_remote.png", "DESCRIPTION" => $mess["ajxp_shared.29"]), "users" => array("LABEL" => $mess["ajxp_shared.1"], "ICON" => "user_shared.png", "DESCRIPTION" => $mess["ajxp_shared.30"])); $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : ""; $splits = explode("/", $dir); if (count($splits)) { if ($splits[0] == "") { array_shift($splits); } if (count($splits)) { $strippedDir = strtolower(urldecode($splits[0])); } else { $strippedDir = ""; } } if (array_key_exists($strippedDir, $rootNodes)) { AJXP_XMLWriter::header(); if ($strippedDir == "users") { $this->listUsers(); } else { if ($strippedDir == "repositories") { $this->listRepositories(); } else { if ($strippedDir == "files") { $this->listSharedFiles(); } } } AJXP_XMLWriter::close(); exit(1); } else { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_shared.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_shared.31" attributeName="description" sortType="String"/></columns>'); foreach ($rootNodes as $key => $data) { print '<tree text="' . $data["LABEL"] . '" icon="' . $data["ICON"] . '" filename="/' . $key . '" parentname="/" description="' . $data["DESCRIPTION"] . '" />'; } AJXP_XMLWriter::close(); } break; case "stat": header("Content-type:application/json"); print '{"mode":true}'; break; case "delete": $mime = $httpVars["ajxp_mime"]; $selection = new UserSelection(); $selection->initFromHttpVars(); $files = $selection->getFiles(); AJXP_XMLWriter::header(); foreach ($files as $index => $element) { $element = basename($element); if ($mime == "shared_repository") { $repo = ConfService::getRepositoryById($element); if (!$repo->hasOwner() || $repo->getOwner() != $loggedUser->getId()) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]); break; } else { $res = ConfService::deleteRepository($element); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]); break; } else { if ($index == count($files) - 1) { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null); AJXP_XMLWriter::reloadDataNode(); } } } } else { if ($mime == "shared_user") { $confDriver = ConfService::getConfStorageImpl(); $object = $confDriver->createUserObject($element); if (!$object->hasParent() || $object->getParent() != $loggedUser->getId()) { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]); break; } else { $res = AuthService::deleteUser($element); if ($index == count($files) - 1) { AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null); AJXP_XMLWriter::reloadDataNode(); } } } else { if ($mime == "shared_file") { $publicletData = $this->loadPublicletData(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php"); if (isset($publicletData["OWNER_ID"]) && $publicletData["OWNER_ID"] == $loggedUser->getId()) { require_once INSTALL_PATH . "/server/classes/class.PublicletCounter.php"; PublicletCounter::delete($element); unlink(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php"); if ($index == count($files) - 1) { AJXP_XMLWriter::sendMessage($mess["ajxp_shared.13"], null); AJXP_XMLWriter::reloadDataNode(); } } else { AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]); break; } } } } } AJXP_XMLWriter::close(); break; case "clear_expired": $deleted = $this->clearExpiredFiles(); AJXP_XMLWriter::header(); if (count($deleted)) { AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null); AJXP_XMLWriter::reloadDataNode(); } else { AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null); } AJXP_XMLWriter::close(); break; case "reset_download_counter": $selection = new UserSelection(); $selection->initFromHttpVars(); $elements = $selection->getFiles(); require_once INSTALL_PATH . "/server/classes/class.PublicletCounter.php"; foreach ($elements as $element) { PublicletCounter::reset(str_replace(".php", "", basename($element))); } AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); break; default: break; } return; }
public function crossRepositoryCopy($httpVars) { ConfService::detectRepositoryStreams(true); $mess = ConfService::getMessages(); $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); $accessType = $this->repository->getAccessType(); $repositoryId = $this->repository->getId(); $plugin = AJXP_PluginsService::findPlugin("access", $accessType); $origWrapperData = $plugin->detectStreamWrapper(true); $origStreamURL = $origWrapperData["protocol"] . "://{$repositoryId}"; $destRepoId = $httpVars["dest_repository_id"]; $destRepoObject = ConfService::getRepositoryById($destRepoId); $destRepoAccess = $destRepoObject->getAccessType(); $plugin = AJXP_PluginsService::findPlugin("access", $destRepoAccess); $plugin->repository = $destRepoObject; $destWrapperData = $plugin->detectStreamWrapper(true); $destStreamURL = $destWrapperData["protocol"] . "://{$destRepoId}"; // Check rights if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId) || isset($httpVars["moving_files"]) && !$loggedUser->canWrite($repositoryId)) { throw new Exception($mess[364]); } } $srcRepoData = array('base_url' => $origStreamURL, 'wrapper_name' => $origWrapperData['classname'], 'recycle' => $this->repository->getOption("RECYCLE_BIN")); $destRepoData = array('base_url' => $destStreamURL, 'wrapper_name' => $destWrapperData['classname'], 'chmod' => $this->repository->getOption('CHMOD')); $messages = array(); $errorMessages = array(); foreach ($files as $file) { $this->copyOrMoveFile(AJXP_Utils::decodeSecureMagic($httpVars["dest"]), $file, $errorMessages, $messages, isset($httpVars["moving_files"]) ? true : false, $srcRepoData, $destRepoData); } AJXP_XMLWriter::header(); if (count($errorMessages)) { AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true); } AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true); AJXP_XMLWriter::close(); }
public function switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = $this->accessDriver->repository; if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); switch ($actionName) { case "filehasher_signature": $file = $selection->getUniqueNode(); if (!file_exists($file->getUrl())) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $file->getUrl(), array($this, "generateSignature")); $data = $cacheItem->getData(); header("Content-Type:application/octet-stream"); header("Content-Length", strlen($data)); echo $data; break; case "filehasher_delta": case "filehasher_patch": // HANDLE UPLOAD DATA $this->logDebug("Received signature file, should compute delta now"); if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) { throw new Exception("These action should find uploaded data"); } $signature_delta_file = $fileVars["userfile_0"]["tmp_name"]; $fileUrl = $selection->getUniqueNode()->getUrl(); $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true); if ($actionName == "filehasher_delta") { $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); $this->logDebug("Received signature file, should compute delta now"); rsync_generate_delta($signature_delta_file, $file, $deltaFile); $this->logDebug("Computed delta file, size is " . filesize($deltaFile)); header("Content-Type:application/octet-stream"); header("Content-Length:" . filesize($deltaFile)); readfile($deltaFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; rsync_patch_file($file, $signature_delta_file, $patched); rename($patched, $file); $node = $selection->getUniqueNode(); AJXP_Controller::applyHook("node.change", array($node, $node, false)); header("Content-Type:text/plain"); echo md5_file($file); } break; case "stat_hash": clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $node = $selection->getUniqueNode(); $stat = @stat($node->getUrl()); if (!$stat || !is_readable($node->getUrl())) { print '{}'; } else { if (is_file($node->getUrl())) { if (isset($_SERVER["HTTP_RANGE"])) { $fullSize = floatval($stat['size']); $ranges = explode('=', $_SERVER["HTTP_RANGE"]); $offsets = explode('-', $ranges[1]); $offset = floatval($offsets[0]); $length = floatval($offsets[1]) - $offset; if (!$length) { $length = $fullSize - $offset; } if ($length + $offset > $fullSize || $length < 0) { $length = $fullSize - $offset; } $hash = $this->getPartialHash($node, $offset, $length); } else { $hash = $this->getFileHash($selection->getUniqueNode()); } } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $node = new AJXP_Node($selection->currentBaseUrl() . $path); $stat = @stat($selection->currentBaseUrl() . $path); if (!$stat || !is_readable($node->getUrl())) { $stat = '{}'; } else { if (!is_dir($node->getUrl())) { $hash = $this->getFileHash($node); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; $stat = json_encode($stat); } print json_encode(SystemTextEncoding::toUTF8($path)) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; break; } }
/** * @param $httpVars * @param Repository $repository * @param AbstractAccessDriver $accessDriver * @return mixed An array containing the hash (0) and the generated url (1) */ public function createSharedMinisite($httpVars, $repository, $accessDriver) { $uniqueUser = null; if (isset($httpVars["repository_id"]) && isset($httpVars["guest_user_id"])) { $existingData = $this->getShareStore()->loadShare($httpVars["hash"]); $existingU = ""; if (isset($existingData["PRELOG_USER"])) { $existingU = $existingData["PRELOG_USER"]; } else { if (isset($existingData["PRESET_LOGIN"])) { $existingU = $existingData["PRESET_LOGIN"]; } } $uniqueUser = $httpVars["guest_user_id"]; if (isset($httpVars["guest_user_pass"]) && strlen($httpVars["guest_user_pass"]) && $uniqueUser == $existingU) { //$userPass = $httpVars["guest_user_pass"]; // UPDATE GUEST USER PASS HERE AuthService::updatePassword($uniqueUser, $httpVars["guest_user_pass"]); } else { if (isset($httpVars["guest_user_pass"]) && $httpVars["guest_user_pass"] == "") { } else { if (isset($existingData["PRESET_LOGIN"])) { $httpVars["KEEP_PRESET_LOGIN"] = true; } } } } else { if (isset($httpVars["create_guest_user"])) { // Create a guest user $userId = substr(md5(time()), 0, 12); $pref = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId()); if (!empty($pref)) { $userId = $pref . $userId; } if (!empty($httpVars["guest_user_pass"])) { $userPass = $httpVars["guest_user_pass"]; } else { $userPass = substr(md5(time()), 13, 24); } $uniqueUser = $userId; } } if (isset($uniqueUser)) { if (isset($userPass)) { $httpVars["user_pass_0"] = $httpVars["shared_pass"] = $userPass; } $httpVars["user_0"] = $uniqueUser; $httpVars["entry_type_0"] = "user"; $httpVars["right_read_0"] = isset($httpVars["simple_right_read"]) ? "true" : "false"; $httpVars["right_write_0"] = isset($httpVars["simple_right_write"]) ? "true" : "false"; $httpVars["right_watch_0"] = "false"; $httpVars["disable_download"] = isset($httpVars["simple_right_download"]) ? false : true; if ($httpVars["right_read_0"] == "false" && !$httpVars["disable_download"]) { $httpVars["right_read_0"] = "true"; } if ($httpVars["right_write_0"] == "false" && $httpVars["right_read_0"] == "false") { return "share_center.58"; } } $httpVars["minisite"] = true; $httpVars["selection"] = true; if (!isset($userSelection)) { $userSelection = new UserSelection($repository, $httpVars); $setFilter = false; if ($userSelection->isUnique()) { $node = $userSelection->getUniqueNode(); $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"]) && intval($httpVars["expiration"]) > 0) { $data["EXPIRE_TIME"] = time() + intval($httpVars["expiration"]) * 86400; } if (isset($httpVars["downloadlimit"]) && intval($httpVars["downloadlimit"]) > 0) { $data["DOWNLOAD_LIMIT"] = intval($httpVars["downloadlimit"]); } if (AuthService::usersEnabled()) { $data["OWNER_ID"] = AuthService::getLoggedUser()->getId(); } if (!isset($httpVars["repository_id"])) { try { $forceHash = null; if (isset($httpVars["custom_handle"]) && !empty($httpVars["custom_handle"])) { // Existing already $value = AJXP_Utils::sanitize($httpVars["custom_handle"], AJXP_SANITIZE_ALPHANUM); $value = strtolower($value); $test = $this->getShareStore()->loadShare($value); $mess = ConfService::getMessages(); if (!empty($test)) { throw new Exception($mess["share_center.172"]); } $forceHash = $value; } $hash = $this->getShareStore()->storeShare($repository->getId(), $data, "minisite", $forceHash); } catch (Exception $e) { return $e->getMessage(); } $url = $this->buildPublicletLink($hash); $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); }