function initFromArray($array) { if (!is_array($array)) { return; } if (isset($array[$this->varPrefix]) && $array[$this->varPrefix] != "") { $this->files[] = AJXP_Utils::securePath(SystemTextEncoding::fromPostedFileName($array[$this->varPrefix])); $this->isUnique = true; //return ; } if (isset($array[$this->varPrefix . "_0"])) { $index = 0; while (isset($array[$this->varPrefix . "_" . $index])) { $this->files[] = AJXP_Utils::securePath(SystemTextEncoding::fromPostedFileName($array[$this->varPrefix . "_" . $index])); $index++; } $this->isUnique = false; if (count($this->files) == 1) { $this->isUnique = true; } //return ; } if (isset($array[$this->dirPrefix])) { $this->dir = AJXP_Utils::securePath($array[$this->dirPrefix]); if ($test = $this->detectZip($this->dir)) { $this->inZip = true; $this->zipFile = $test[0]; $this->localZipPath = $test[1]; } } }
/** * Initialize the stream from the given path. */ protected static function initPath($path, $streamType = '', $storeOpenContext = false, $skipZip = true) { $url = AJXP_Utils::safeParseUrl($path); $repoId = $url["host"]; $path = $url["path"]; $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { throw new Exception("Cannot find repository with id " . $repoId); } $basePath = $repoObject->getOption("PATH"); $host = $repoObject->getOption("SFTP_HOST"); $port = $repoObject->getOption("SFTP_PORT"); $credentials = AJXP_Safe::tryLoadingCredentialsFromSources($url, $repoObject); $user = $credentials["user"]; $pass = $credentials["password"]; if ($basePath[strlen($basePath) - 1] == "/") { $basePath = substr($basePath, 0, -1); } if ($basePath[0] != "/") { $basePath = "/{$basePath}"; } $path = AJXP_Utils::securePath($path); if ($path[0] == "/") { $path = substr($path, 1); } return "sftp://" . $user . ':' . $pass . '@' . $host . ':' . $port . $basePath . "/" . $path; // http://username:password@hostname:port/path/file.ext }
/** * Initialize the stream from the given path. * Concretely, transform ajxp.webdav:// into webdav:// * * @param string $path * @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path */ protected static function initPath($path, $streamType, $storeOpenContext = false, $skipZip = false) { $url = parse_url($path); $repoId = $url["host"]; $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { throw new Exception("Cannot find repository with id " . $repoId); } $path = $url["path"]; $host = $repoObject->getOption("HOST"); $host = str_replace(array("http", "https"), array("webdav", "webdavs"), $host); // MAKE SURE THERE ARE NO // OR PROBLEMS LIKE THAT... $basePath = $repoObject->getOption("PATH"); if ($basePath[strlen($basePath) - 1] == "/") { $basePath = substr($basePath, 0, -1); } if ($basePath[0] != "/") { $basePath = "/{$basePath}"; } $path = AJXP_Utils::securePath($path); if ($path[0] == "/") { $path = substr($path, 1); } // SHOULD RETURN webdav://host_server/uri/to/webdav/folder return $host . $basePath . "/" . $path; }
/** * Initialize an empty mask, or from a serializedForm. * @param array|null $serializedForm */ function __construct($serializedForm = null) { if ($serializedForm != null) { foreach ($serializedForm as $path => $permissionValue) { $path = AJXP_Utils::sanitize(AJXP_Utils::securePath($path), AJXP_SANITIZE_DIRNAME); if (!is_array($permissionValue) || $permissionValue["children"]) { continue; } $perm = new AJXP_Permission(); if ($permissionValue["read"]) { $perm->setRead(); } if ($permissionValue["write"]) { $perm->setWrite(); } if ($permissionValue["deny"]) { $perm->setDeny(); } if ($perm->isEmpty()) { continue; } $this->updateBranch($path, $perm); } } }
public function init($options) { // Migrate new version of the options if (isset($options["CMS_TYPE"])) { // Transform MASTER_URL + LOGIN_URI to MASTER_HOST, MASTER_URI, LOGIN_URL, LOGOUT_URI $options["SLAVE_MODE"] = "false"; $cmsOpts = $options["CMS_TYPE"]; if ($cmsOpts["cms"] != "custom") { $loginURI = $cmsOpts["LOGIN_URI"]; if (strpos($cmsOpts["MASTER_URL"], "http") === 0) { $parse = parse_url($cmsOpts["MASTER_URL"]); $rootHost = $parse["host"]; $rootURI = $parse["path"]; } else { $rootHost = ""; $rootURI = $cmsOpts["MASTER_URL"]; } $cmsOpts["MASTER_HOST"] = $rootHost; $cmsOpts["LOGIN_URL"] = $cmsOpts["MASTER_URI"] = AJXP_Utils::securePath("/" . $rootURI . "/" . $loginURI); $logoutAction = $cmsOpts["LOGOUT_ACTION"]; switch ($cmsOpts["cms"]) { case "wp": $cmsOpts["LOGOUT_URL"] = $logoutAction == "back" ? $cmsOpts["MASTER_URL"] : $cmsOpts["MASTER_URL"] . "/wp-login.php?action=logout"; break; case "joomla": $cmsOpts["LOGOUT_URL"] = $cmsOpts["LOGIN_URL"]; break; case "drupal": $cmsOpts["LOGOUT_URL"] = $logoutAction == "back" ? $cmsOpts["LOGIN_URL"] : $cmsOpts["MASTER_URL"] . "/user/logout"; break; default: break; } } $options = array_merge($options, $cmsOpts); } $this->slaveMode = $options["SLAVE_MODE"] == "true"; if ($this->slaveMode && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) { $contribs = $this->xPath->query("registry_contributions/external_file"); foreach ($contribs as $contribNode) { if ($contribNode->getAttribute('filename') == 'plugins/core.auth/standard_auth_actions.xml') { $contribNode->parentNode->removeChild($contribNode); } } } parent::init($options); $options = $this->options; $this->usersSerFile = $options["USERS_FILEPATH"]; $this->secret = $options["SECRET"]; $this->urls = array($options["LOGIN_URL"], $options["LOGOUT_URL"]); }
/** * Initialize the stream from the given path. * Concretely, transform ajxp.webdav:// into webdav:// * * @param string $path * @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path */ protected static function initPath($path, $streamType, $storeOpenContext = false, $skipZip = false) { $url = AJXP_Utils::safeParseUrl($path); $repoId = $url["host"]; $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { $e = new Exception("Cannot find repository with id " . $repoId); self::$lastException = $e; throw $e; } $path = $url["path"]; $host = $repoObject->getOption("HOST"); $hostParts = parse_url($host); if ($hostParts["scheme"] == "https" && !extension_loaded("openssl")) { $e = new Exception("Warning you must have the openssl PHP extension loaded to connect an https server!"); self::$lastException = $e; throw $e; } $credentials = AJXP_Safe::tryLoadingCredentialsFromSources($hostParts, $repoObject); $user = $credentials["user"]; $password = $credentials["password"]; if ($user != null && $password != null) { $host = ($hostParts["scheme"] == "https" ? "webdavs" : "webdav") . "://{$user}:{$password}@" . $hostParts["host"]; if (isset($hostParts["port"])) { $host .= ":" . $hostParts["port"]; } } else { $host = str_replace(array("http", "https"), array("webdav", "webdavs"), $host); } // MAKE SURE THERE ARE NO // OR PROBLEMS LIKE THAT... $basePath = $repoObject->getOption("PATH"); if ($basePath[strlen($basePath) - 1] == "/") { $basePath = substr($basePath, 0, -1); } if ($basePath[0] != "/") { $basePath = "/{$basePath}"; } $path = AJXP_Utils::securePath($path); if ($path[0] == "/") { $path = substr($path, 1); } // SHOULD RETURN webdav://host_server/uri/to/webdav/folder AJXP_Logger::debug(__CLASS__, __FUNCTION__, $host . $basePath . "/" . $path); return $host . $basePath . "/" . $path; }
public function makeZip($src, $dest, $basedir) { @set_time_limit(0); require_once AJXP_BIN_FOLDER . "/pclzip.lib.php"; $filePaths = array(); foreach ($src as $item) { $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . ($item[0] == "/" ? "" : "/") . AJXP_Utils::securePath($item)); $basedir = trim(dirname($realFile)) . "/"; $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $realFile, PCLZIP_ATT_FILE_NEW_SHORT_NAME => basename($item)); } $this->logDebug("Pathes", $filePaths); $this->logDebug("Basedir", array($basedir)); self::$filteringDriverInstance = $this; $archive = new PclZip($dest); $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_PATH, $basedir, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_ADD_TEMP_FILE_ON); if (!$vList) { throw new Exception("Zip creation error : ({$dest}) " . $archive->errorInfo(true)); } self::$filteringDriverInstance = null; return $vList; }
/** * Initialize the stream from the given path. * Concretely, transform ajxp.webdav:// into webdav:// * * @param string $path * @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path */ protected static function initPath($path, $streamType = "", $sftpResource = false, $skipZip = false) { $url = parse_url($path); $repoId = $url["host"]; $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { throw new Exception("Cannot find repository with id " . $repoId); } $path = $url["path"]; // MAKE SURE THERE ARE NO // OR PROBLEMS LIKE THAT... $basePath = $repoObject->getOption("PATH"); if ($basePath[strlen($basePath) - 1] == "/") { $basePath = substr($basePath, 0, -1); } if ($basePath[0] != "/") { $basePath = "/{$basePath}"; } $path = AJXP_Utils::securePath($path); if ($path[0] == "/") { $path = substr($path, 1); } // SHOULD RETURN ssh2.sftp://Resource #23/server/path/folder/path return "ssh2.sftp://" . self::getSftpResource($repoObject) . $basePath . "/" . $path; }
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; }
/** * Opens the strem * * @param String $path Maybe in the form "ajxp.fs://repositoryId/pathToFile" * @param String $mode * @param string $options * @param resource $context * @return bool */ public function stream_open($path, $mode, $options, &$context) { try { $this->realPath = AJXP_Utils::securePath(self::initPath($path, "file")); } catch (Exception $e) { AJXP_Logger::error(__CLASS__, "stream_open", "Error while opening stream {$path} (" . $e->getMessage() . ")"); return false; } if ($this->realPath == -1) { $this->fp = -1; return true; } else { $this->fp = fopen($this->realPath, $mode, $options); return $this->fp !== false; } }
public function unifyChunks($action, &$httpVars, &$fileVars) { $filename = AJXP_Utils::decodeSecureMagic($httpVars["name"]); $tmpName = $fileVars["file"]["tmp_name"]; $chunk = $httpVars["chunk"]; $chunks = $httpVars["chunks"]; //error_log("currentChunk:".$chunk." chunks: ".$chunks); $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $wrapperName = $streamData["classname"]; $dir = AJXP_Utils::securePath($httpVars["dir"]); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/"; $driver = ConfService::loadDriverForRepository($repository); $remote = false; if (method_exists($driver, "storeFileToCopy")) { $remote = true; $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($repository->getOption("TMP_UPLOAD")); // Make tmp folder a bit more unique using secure_token $tmpFolder = $destCopy . "/" . $httpVars["secure_token"]; if (!is_dir($tmpFolder)) { @mkdir($tmpFolder, 0700, true); } $target = $tmpFolder . '/' . $filename; $fileVars["file"]["destination"] = base64_encode($dir); } else { if (call_user_func(array($wrapperName, "isRemote"))) { $remote = true; $tmpFolder = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["secure_token"]; if (!is_dir($tmpFolder)) { @mkdir($tmpFolder, 0700, true); } $target = $tmpFolder . '/' . $filename; } else { $target = $destStreamURL . $filename; } } //error_log("Directory: ".$dir); // Clean the fileName for security reasons //$filename = preg_replace('/[^\w\._]+/', '', $filename); // Look for the content type header if (isset($_SERVER["HTTP_CONTENT_TYPE"])) { $contentType = $_SERVER["HTTP_CONTENT_TYPE"]; } if (isset($_SERVER["CONTENT_TYPE"])) { $contentType = $_SERVER["CONTENT_TYPE"]; } // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5 if (strpos($contentType, "multipart") !== false) { if (isset($tmpName) && is_uploaded_file($tmpName)) { //error_log("tmpName: ".$tmpName); // Open temp file $out = fopen($target, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen($tmpName, "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); @unlink($tmpName); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } } else { // Open temp file $out = fopen($target, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } /* we apply the hook if we are uploading the last chunk */ if ($chunk == $chunks - 1) { if (!$remote) { AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($destStreamURL . $filename), false)); } else { if (method_exists($driver, "storeFileToCopy")) { $fileVars["file"]["tmp_name"] = $target; $fileVars["file"]["name"] = $filename; $driver->storeFileToCopy($fileVars["file"]); AJXP_Controller::findActionAndApply("next_to_remote", array(), array()); } else { // Remote Driver case: copy temp file to destination $node = new AJXP_Node($destStreamURL . $filename); AJXP_Controller::applyHook("node.before_create", array($node, filesize($target))); AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destStreamURL))); $res = copy($target, $destStreamURL . $filename); if ($res) { @unlink($target); } AJXP_Controller::applyHook("node.change", array(null, $node, false)); } } } // Return JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); }
/** * @return zipfile */ function makeZip($src, $dest, $basedir) { @set_time_limit(60); require_once SERVER_RESOURCES_FOLDER . "/pclzip.lib.php"; $filePaths = array(); foreach ($src as $item) { $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . "/" . $item); $realFile = AJXP_Utils::securePath($realFile); $basedir = trim(dirname($realFile)); $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $realFile, PCLZIP_ATT_FILE_NEW_SHORT_NAME => basename($item)); } AJXP_Logger::debug("Pathes", $filePaths); AJXP_Logger::debug("Basedir", array($basedir)); $archive = new PclZip($dest); $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_PATH, $basedir, PCLZIP_OPT_NO_COMPRESSION); if (!$vList) { throw new Exception("Zip creation error : ({$dest}) " . $archive->errorInfo(true)); } return $vList; }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } if (isset($dir) && $action != "upload") { $dir = SystemTextEncoding::fromUTF8($dir); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // SWITCH THE ROOT REPOSITORY //------------------------------------ case "switch_repository": if (!isset($repository_id)) { break; } $dirList = ConfService::getRepositoriesList(); /** @var $repository_id string */ if (!isset($dirList[$repository_id])) { $errorMessage = "Trying to switch to an unkown repository!"; break; } ConfService::switchRootDir($repository_id); // Load try to init the driver now, to trigger an exception // if it's not loading right. ConfService::loadRepositoryDriver(); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $user = AuthService::getLoggedUser(); $activeRepId = ConfService::getCurrentRepositoryId(); $user->setArrayPref("history", "last_repository", $activeRepId); $user->save("user"); } //$logMessage = "Successfully Switched!"; $this->logInfo("Switch Repository", array("rep. id" => $repository_id)); break; //------------------------------------ // SEND XML REGISTRY //------------------------------------ //------------------------------------ // SEND XML REGISTRY //------------------------------------ case "get_xml_registry": case "state": $regDoc = AJXP_PluginsService::getXmlRegistry(); $changes = AJXP_Controller::filterRegistryFromRole($regDoc); if ($changes) { AJXP_PluginsService::updateXmlRegistry($regDoc); } $clone = $regDoc->cloneNode(true); $clonePath = new DOMXPath($clone); $serverCallbacks = $clonePath->query("//serverCallback|hooks"); foreach ($serverCallbacks as $callback) { $callback->parentNode->removeChild($callback); } $xPath = ''; if (isset($httpVars["xPath"])) { $xPath = ltrim(AJXP_Utils::securePath($httpVars["xPath"]), "/"); } if (!empty($xPath)) { $nodes = $clonePath->query($xPath); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($nodes->item(0)); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $xPath)); if ($nodes->length) { print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML($nodes->item(0))); } AJXP_XMLWriter::close("ajxp_registry_part"); } } else { AJXP_Utils::safeIniSet("zlib.output_compression", "4096"); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($clone); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { header('Content-Type: application/xml; charset=UTF-8'); print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML()); } } break; //------------------------------------ // BOOKMARK BAR //------------------------------------ //------------------------------------ // BOOKMARK BAR //------------------------------------ case "get_bookmarks": $bmUser = null; if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser = AuthService::getLoggedUser(); } else { if (!AuthService::usersEnabled()) { $confStorage = ConfService::getConfStorageImpl(); $bmUser = $confStorage->createUserObject("shared"); } } if ($bmUser == null) { AJXP_XMLWriter::header(); AJXP_XMLWriter::close(); } $driver = ConfService::loadRepositoryDriver(); if (!is_a($driver, "AjxpWrapperProvider")) { $driver = false; } if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) { $bmPath = AJXP_Utils::decodeSecureMagic($httpVars["bm_path"]); if ($httpVars["bm_action"] == "add_bookmark") { $title = ""; if (isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); } if ($title == "" && $bmPath == "/") { $title = ConfService::getCurrentRootDirDisplay(); } $bmUser->addBookMark($bmPath, $title); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->setMetadata("ajxp_bookmarked", array("ajxp_bookmarked" => "true"), true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "delete_bookmark") { $bmUser->removeBookmark($bmPath); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->removeMetadata("ajxp_bookmarked", true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); $bmUser->renameBookmark($bmPath, $title); } } } AJXP_Controller::applyHook("msg.instant", array("<reload_bookmarks/>", ConfService::getRepository()->getId())); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser->save("user"); AuthService::updateUser($bmUser); } else { if (!AuthService::usersEnabled()) { $bmUser->save("user"); } } } AJXP_XMLWriter::header(); AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks(), true, isset($httpVars["format"]) ? $httpVars["format"] : "legacy"); AJXP_XMLWriter::close(); break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "save_user_pref": $userObject = AuthService::getLoggedUser(); $i = 0; while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) { $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM); $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i])); if ($prefName == "password") { continue; } if ($prefName != "pending_folder" && $userObject == null) { $i++; continue; } $userObject->setPref($prefName, $prefValue); $userObject->save("user"); AuthService::updateUser($userObject); //setcookie("AJXP_$prefName", $prefValue); $i++; } header("Content-Type:text/plain"); print "SUCCESS"; break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "custom_data_edit": case "user_create_user": $data = array(); if ($action == "user_create_user" && isset($httpVars["NEW_new_user_id"])) { $updating = false; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $original_id = AJXP_Utils::decodeSecureMagic($data["new_user_id"]); $data["new_user_id"] = AJXP_Utils::decodeSecureMagic($data["new_user_id"], AJXP_SANITIZE_EMAILCHARS); if ($original_id != $data["new_user_id"]) { throw new Exception(str_replace("%s", $data["new_user_id"], $mess["ajxp_conf.127"])); } if (AuthService::userExists($data["new_user_id"], "w")) { throw new Exception($mess["ajxp_conf.43"]); } $loggedUser = AuthService::getLoggedUser(); $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, ""); if (!empty($limit) && intval($limit) > 0) { $count = count($this->getUserChildren($loggedUser->getId())); if ($count >= $limit) { throw new Exception($mess['483']); } } AuthService::createUser($data["new_user_id"], $data["new_password"]); $userObject = ConfService::getConfStorageImpl()->createUserObject($data["new_user_id"]); $userObject->setParent($loggedUser->getId()); $userObject->save('superuser'); $userObject->personalRole->clearAcls(); $userObject->setGroupPath($loggedUser->getGroupPath()); $userObject->setProfile("shared"); } else { if ($action == "user_create_user" && isset($httpVars["NEW_existing_user_id"])) { $updating = true; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $userId = $data["existing_user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } if (!empty($data["new_password"])) { AuthService::updatePassword($userId, $data["new_password"]); } } else { $updating = false; $userObject = AuthService::getLoggedUser(); AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "PREFERENCES_"); } } $paramNodes = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'user') and @expose='true']", "node", false, false, true); $rChanges = false; if (is_array($paramNodes) && count($paramNodes)) { foreach ($paramNodes as $xmlNode) { if ($xmlNode->getAttribute("expose") == "true") { $parentNode = $xmlNode->parentNode->parentNode; $pluginId = $parentNode->getAttribute("id"); if (empty($pluginId)) { $pluginId = $parentNode->nodeName . "." . $parentNode->getAttribute("name"); } $name = $xmlNode->getAttribute("name"); if (isset($data[$name]) || $data[$name] === "") { if ($data[$name] == "__AJXP_VALUE_SET__") { continue; } if ($data[$name] === "" || $userObject->parentRole == null || $userObject->parentRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name] || $userObject->personalRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name]) { $userObject->personalRole->setParameterValue($pluginId, $name, $data[$name]); $rChanges = true; } } } } } if ($rChanges) { AuthService::updateRole($userObject->personalRole, $userObject); $userObject->recomputeMergedRole(); if ($action == "custom_data_edit") { AuthService::updateUser($userObject); } } if ($action == "user_create_user") { AJXP_Controller::applyHook($updating ? "user.after_update" : "user.after_create", array($userObject)); if (isset($data["send_email"]) && $data["send_email"] == true && !empty($data["email"])) { $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer"); if ($mailer !== false) { $mess = ConfService::getMessages(); $link = AJXP_Utils::detectServerURL(); $apptitle = ConfService::getCoreConf("APPLICATION_TITLE"); $subject = str_replace("%s", $apptitle, $mess["507"]); $body = str_replace(array("%s", "%link", "%user", "%pass"), array($apptitle, $link, $data["new_user_id"], $data["new_password"]), $mess["508"]); $mailer->sendMail(array($data["email"]), $subject, $body); } } echo "SUCCESS"; } else { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["241"], null); AJXP_XMLWriter::close(); } break; case "user_update_user": if (!isset($httpVars["user_id"])) { throw new Exception("invalid arguments"); } $userId = $httpVars["user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } $paramsString = ConfService::getCoreConf("NEWUSERS_EDIT_PARAMETERS", "conf"); $result = array(); $params = explode(",", $paramsString); foreach ($params as $p) { $result[$p] = $userObject->personalRole->filterParameterValue("core.conf", $p, AJXP_REPO_SCOPE_ALL, ""); } HTMLWriter::charsetHeader("application/json"); echo json_encode($result); break; //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ case "webdav_preferences": $userObject = AuthService::getLoggedUser(); $webdavActive = false; $passSet = false; $digestSet = false; // Detect http/https and host if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") { $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST"); } else { $baseURL = AJXP_Utils::detectServerURL(); } $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/"; $davData = $userObject->getPref("AJXP_WEBDAV_DATA"); $digestSet = isset($davData["HA1"]); if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) { if (!empty($httpVars["activate"])) { $activate = $httpVars["activate"] == "true" ? true : false; if (empty($davData)) { $davData = array(); } $davData["ACTIVE"] = $activate; } if (!empty($httpVars["webdav_pass"])) { $password = $httpVars["webdav_pass"]; if (function_exists('mcrypt_encrypt')) { $user = $userObject->getId(); $secret = defined("AJXP_SAFE_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#"; $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB)); } $davData["PASS"] = $password; } $userObject->setPref("AJXP_WEBDAV_DATA", $davData); $userObject->save("user"); } if (!empty($davData)) { $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true; $passSet = isset($davData["PASS"]); } $repoList = ConfService::getRepositoriesList(); $davRepos = array(); $loggedUser = AuthService::getLoggedUser(); foreach ($repoList as $repoIndex => $repoObject) { $accessType = $repoObject->getAccessType(); $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType); if (is_a($driver, "AjxpWrapperProvider") && !$repoObject->getOption("AJXP_WEBDAV_DISABLED") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) { $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug()); } } $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "digest_set" => $digestSet, "webdav_force_basic" => ConfService::getCoreConf("WEBDAV_FORCE_BASIC") === true, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos); HTMLWriter::charsetHeader("application/json"); print json_encode($prefs); break; case "get_user_template_logo": $tplId = $httpVars["template_id"]; $iconFormat = $httpVars["icon_format"]; $repo = ConfService::getRepositoryById($tplId); $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat)); if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) { header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)); header('Pragma:'); header('Cache-Control: public'); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo); } else { $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png"; header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo)); header('Pragma:'); header('Cache-Control: public'); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo); } break; case "get_user_templates_definition": AJXP_XMLWriter::header("repository_templates"); $count = 0; $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => 1), $count); $pServ = AJXP_PluginsService::getInstance(); foreach ($repositories as $repo) { if (!$repo->isTemplate) { continue; } if (!$repo->getOption("TPL_USER_CAN_CREATE")) { continue; } $repoId = $repo->getId(); $repoLabel = $repo->getDisplay(); $repoType = $repo->getAccessType(); print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">"; $driverPlug = $pServ->getPluginByTypeName("access", $repoType); $params = $driverPlug->getManifestRawContent("//param", "node"); $tplDefined = $repo->getOptionsDefined(); $defaultLabel = ''; foreach ($params as $paramNode) { $name = $paramNode->getAttribute("name"); if (strpos($name, "TPL_") === 0) { if ($name == "TPL_DEFAULT_LABEL") { $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name)); } continue; } if (in_array($paramNode->getAttribute("name"), $tplDefined)) { continue; } if ($paramNode->getAttribute('no_templates') == 'true') { continue; } print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode)); } // ADD LABEL echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>'; print "</template>"; } AJXP_XMLWriter::close("repository_templates"); break; case "user_create_repository": $tplId = $httpVars["template_id"]; $tplRepo = ConfService::getRepositoryById($tplId); $options = array(); AJXP_Utils::parseStandardFormParameters($httpVars, $options); $loggedUser = AuthService::getLoggedUser(); $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, $loggedUser->getId()); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath)) { $newRep->setGroupPath($gPath); } $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[426]); } else { // Make sure we do not overwrite otherwise loaded rights. $loggedUser->load(); $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw"); $loggedUser->save("superuser"); $loggedUser->recomputeMergedRole(); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[425], null); AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId()); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_repository": $repoId = $httpVars["repository_id"]; $repository = ConfService::getRepositoryById($repoId); if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to perform this operation!"); } $res = ConfService::deleteRepository($repoId); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[427]); } else { $loggedUser = AuthService::getLoggedUser(); // Make sure we do not override remotely set rights $loggedUser->load(); $loggedUser->personalRole->setAcl($repoId, ""); $loggedUser->save("superuser"); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[428], null); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_user": $userId = $httpVars["user_id"]; $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject == null || !$userObject->hasParent() || $userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to edit this user"); } AuthService::deleteUser($userId); echo "SUCCESS"; break; case "user_list_authorized_users": $defaultFormat = "html"; HTMLWriter::charsetHeader(); if (!ConfService::getAuthDriverImpl()->usersEditable()) { break; } $loggedUser = AuthService::getLoggedUser(); $crtValue = $httpVars["value"]; $usersOnly = isset($httpVars["users_only"]) && $httpVars["users_only"] == "true"; $existingOnly = isset($httpVars["existing_only"]) && $httpVars["existing_only"] == "true"; if (!empty($crtValue)) { $regexp = '^' . $crtValue; } else { $regexp = null; } $skipDisplayWithoutRegexp = ConfService::getCoreConf("USERS_LIST_REGEXP_MANDATORY", "conf"); if ($skipDisplayWithoutRegexp && $regexp == null) { print "<ul></ul>"; break; } $limit = intval(ConfService::getCoreConf("USERS_LIST_COMPLETE_LIMIT", "conf")); $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf"); $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf"); $baseGroup = "/"; if ($regexp == null && !$displayAll || $regexp != null && !$searchAll) { $baseGroup = AuthService::filterBaseGroup("/"); } AuthService::setGroupFiltering(false); $allUsers = AuthService::listUsers($baseGroup, $regexp, 0, $limit, false); if (!$usersOnly) { $allGroups = array(); $roleOrGroup = ConfService::getCoreConf("GROUP_OR_ROLE", "conf"); $rolePrefix = $excludeString = $includeString = null; if (!is_array($roleOrGroup)) { $roleOrGroup = array("group_switch_value" => $roleOrGroup); } $listRoleType = false; if (isset($roleOrGroup["PREFIX"])) { $rolePrefix = $loggedUser->mergedRole->filterParameterValue("core.conf", "PREFIX", null, $roleOrGroup["PREFIX"]); $excludeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "EXCLUDED", null, $roleOrGroup["EXCLUDED"]); $includeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "INCLUDED", null, $roleOrGroup["INCLUDED"]); $listUserRolesOnly = $loggedUser->mergedRole->filterParameterValue("core.conf", "LIST_ROLE_BY", null, $roleOrGroup["LIST_ROLE_BY"]); if (is_array($listUserRolesOnly) && isset($listUserRolesOnly["group_switch_value"])) { switch ($listUserRolesOnly["group_switch_value"]) { case "userroles": $listRoleType = true; break; case "allroles": $listRoleType = false; break; default: break; } } } switch (strtolower($roleOrGroup["group_switch_value"])) { case 'user': // donothing break; case 'group': $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $allGroups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } break; case 'role': $allGroups = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); break; case 'rolegroup': $groups = array(); $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $groups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } $roles = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); empty($groups) ? $allGroups = $roles : (empty($roles) ? $allGroups = $groups : ($allGroups = array_merge($groups, $roles))); //$allGroups = array_merge($groups, $roles); break; default: break; } } $users = ""; $index = 0; if ($regexp != null && (!count($allUsers) || !empty($crtValue) && !array_key_exists(strtolower($crtValue), $allUsers)) && ConfService::getCoreConf("USER_CREATE_USERS", "conf") && !$existingOnly) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}'><span class='user_entry_label'>{$crtValue} (" . $mess["448"] . ")</span></li>"; } else { if ($existingOnly && !empty($crtValue)) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}' data-entry_id='{$crtValue}'><span class='user_entry_label'>{$crtValue}</span></li>"; } } $mess = ConfService::getMessages(); if ($regexp == null && !$usersOnly) { $users .= "<li class='complete_group_entry' data-group='AJXP_GRP_/' data-label='" . $mess["447"] . "'><span class='user_entry_label'>" . $mess["447"] . "</span></li>"; } $indexGroup = 0; if (!$usersOnly && is_array($allGroups)) { foreach ($allGroups as $groupId => $groupLabel) { if ($regexp == null || preg_match("/{$regexp}/i", $groupLabel)) { $users .= "<li class='complete_group_entry' data-group='{$groupId}' data-label='{$groupLabel}' data-entry_id='{$groupId}'><span class='user_entry_label'>" . $groupLabel . "</span></li>"; $indexGroup++; } if ($indexGroup == $limit) { break; } } } if ($regexp == null && method_exists($this, "listUserTeams")) { $teams = $this->listUserTeams(); foreach ($teams as $tId => $tData) { $users .= "<li class='complete_group_entry' data-group='/AJXP_TEAM/{$tId}' data-label='[team] " . $tData["LABEL"] . "'><span class='user_entry_label'>[team] " . $tData["LABEL"] . "</span></li>"; } } foreach ($allUsers as $userId => $userObject) { if ($userObject->getId() == $loggedUser->getId()) { continue; } if (!$userObject->hasParent() && ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") || $userObject->getParent() == $loggedUser->getId()) { $userLabel = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId); //if($regexp != null && ! (preg_match("/$regexp/i", $userId) || preg_match("/$regexp/i", $userLabel)) ) continue; if (empty($userLabel)) { $userLabel = $userId; } $userDisplay = $userLabel == $userId ? $userId : $userLabel . " ({$userId})"; if (ConfService::getCoreConf("USERS_LIST_HIDE_LOGIN", "conf") == true && $userLabel != $userId) { $userDisplay = $userLabel; } $users .= "<li class='complete_user_entry' data-label='{$userLabel}' data-entry_id='{$userId}'><span class='user_entry_label'>" . $userDisplay . "</span></li>"; $index++; } if ($index == $limit) { break; } } if (strlen($users)) { print "<ul>" . $users . "</ul>"; } AuthService::setGroupFiltering(true); break; case "load_repository_info": $data = array(); $repo = ConfService::getRepository(); if ($repo != null) { $users = AuthService::countUsersForRepository(ConfService::getRepository()->getId(), true); $data["core.users"] = $users; if (isset($httpVars["collect"]) && $httpVars["collect"] == "true") { AJXP_Controller::applyHook("repository.load_info", array(&$data)); } } HTMLWriter::charsetHeader("application/json"); echo json_encode($data); break; case "get_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { if (isset($httpVars["user_id"]) && AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->isAdmin()) { $context = array("USER" => $httpVars["user_id"]); } else { $context = array("USER" => AuthService::getLoggedUser()->getId()); } $this->loadBinary($context, $httpVars["binary_id"]); } } break; case "get_global_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { $this->loadBinary(array(), $httpVars["binary_id"]); } } break; case "store_binary_temp": if (count($fileVars)) { $keys = array_keys($fileVars); $boxData = $fileVars[$keys[0]]; $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { } else { $rand = substr(md5(time()), 0, 6); $tmp = $rand . "-" . $boxData["name"]; @move_uploaded_file($boxData["tmp_name"], AJXP_Utils::getAjxpTmpDir() . "/" . $tmp); } } if (isset($tmp) && file_exists(AJXP_Utils::getAjxpTmpDir() . "/" . $tmp)) { print '<script type="text/javascript">'; print 'parent.formManagerHiddenIFrameSubmission("' . $tmp . '");'; print '</script>'; } break; default: break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } return $xmlBuffer; }
/** * Perform standard urldecode, sanitization and securepath * @static * @param $data * @param int $sanitizeLevel * @return string */ public static function decodeSecureMagic($data, $sanitizeLevel = AJXP_SANITIZE_HTML) { return SystemTextEncoding::fromUTF8(AJXP_Utils::sanitize(AJXP_Utils::securePath($data), $sanitizeLevel)); }
/** This method retrieves the FTP server features as described in RFC2389 * A decent FTP server support MLST command to list file using UTF-8 encoding * @return an array of features (see code) */ protected function getServerFeatures() { $link = $this->createFTPLink(); if (ConfService::getRepositoryById($this->repositoryId)->getOption("CREATE") == true) { // Test if root exists and create it otherwise $serverPath = AJXP_Utils::securePath($this->path . "/"); $testCd = @ftp_chdir($link, $serverPath); if ($testCd !== true) { $res = @ftp_mkdir($link, $serverPath); if (!$res) { throw new Exception("Cannot create path on remote server!"); } } } $features = @ftp_raw($link, "FEAT"); // Check the answer code if (isset($features[0]) && $features[0][0] != "2") { //ftp_close($link); return array("list" => "LIST", "charset" => $this->repoCharset); } $retArray = array("list" => "LIST", "charset" => $this->repoCharset); // Ok, find out the encoding used foreach ($features as $feature) { if (strstr($feature, "UTF8") !== FALSE) { // See http://wiki.filezilla-project.org/Character_Set for an explaination @ftp_raw($link, "OPTS UTF-8 ON"); $retArray['charset'] = "UTF-8"; //ftp_close($link); return $retArray; } } // In the future version, we should also use MLST as it standardize the listing format return $retArray; }
/** * Get the repository options, filtered in various maners * @param string $oName * @param bool $safe Do not filter * @param AbstractAjxpUser $resolveUser * @return mixed|string */ public function getOption($oName, $safe = false, $resolveUser = null) { if (!$safe && $this->inferOptionsFromParent) { if (!isset($this->parentTemplateObject)) { $this->parentTemplateObject = ConfService::getRepositoryById($this->parentId); } if (isset($this->parentTemplateObject)) { $value = $this->parentTemplateObject->getOption($oName, $safe); if (is_string($value) && strstr($value, "AJXP_ALLOW_SUB_PATH") !== false) { $val = rtrim(str_replace("AJXP_ALLOW_SUB_PATH", "", $value), "/") . "/" . $this->options[$oName]; return AJXP_Utils::securePath($val); } } } if (isset($this->options[$oName])) { $value = $this->options[$oName]; if (!$safe) { $value = AJXP_VarsFilter::filter($value, $resolveUser); } return $value; } if ($this->inferOptionsFromParent) { if (!isset($this->parentTemplateObject)) { $this->parentTemplateObject = ConfService::getRepositoryById($this->parentId); } if (isset($this->parentTemplateObject)) { return $this->parentTemplateObject->getOption($oName, $safe); } } return ""; }
<?php define("AJXP_EXEC", true); require_once "/home/utsmaedu/public_html/sgc/core/classes/class.AJXP_Utils.php"; $hash = AJXP_Utils::securePath(AJXP_Utils::sanitize($_GET["hash"], AJXP_SANITIZE_ALPHANUM)); if (file_exists($hash . ".php")) { require_once $hash . ".php"; } else { require_once "/home/utsmaedu/public_html/sgc/publicLet.inc.php"; ShareCenter::loadShareByHash($hash); }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_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 "put_content": AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file))); $code = stripslashes($code); $code = str_replace("<", "<", $content); $this->SSHOperation->setRemoteContent($this->makeName($file), $code); echo $mess[115]; exit(0); break; case "get_content": $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)); } $reloadContextNode = true; $reloadDataNode = SystemTextEncoding::fromUTF8($dest); 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()))); $reloadContextNode = true; } 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)); $reloadContextNode = 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); $reloadContextNode = true; $pendingSelection = SystemTextEncoding::fromUTF8($filename_new); AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; $dirname = AJXP_Utils::processFileName($dirname); $error = $this->SSHOperation->createRemoteDirectory($this->makeName($dir . "/" . $dirname)); if (isset($error)) { $errorMessage = $error; break; } $pendingSelection = $dir . "/" . $dirname; $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reloadContextNode = true; AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; $filename = AJXP_Utils::processFileName($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; $pendingSelection = $filename; $reloadContextNode = true; 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 = AJXP_Utils::parseFileDataErrors($boxData, $fancyLoader); if ($err != null) { $errorMessage = $err; break; } $userfile_name = $boxData["name"]; $userfile_name = AJXP_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": // BACKWARD COMPATIBILTY if (isset($httpVars["options"])) { if ($httpVars["options"] == "al") { $mode = "file_list"; } else { if ($httpVars["options"] == "a") { $mode = "search"; } else { if ($httpVars["options"] == "d") { $skipZip = "true"; } } } // skip "complete" mode that was in fact quite the same as standard tree listing (dz) } 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); $metaData = array(); if (RecycleBinManager::recycleEnabled() && RecycleBinManager::currentLocationIsRecycle($dir)) { $metaData["ajxp_mime"] = "ajxp_recycle"; } AJXP_XMLWriter::renderHeaderNode(AJXP_Utils::xmlEntities($dir, true), AJXP_Utils::xmlEntities(basename($dir), true), false, $metaData); foreach ($result as $file) { $attributes = ""; $fileName = SystemTextEncoding::toUTF8($file["name"]); $icon = AJXP_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=\"" . AJXP_Utils::is_image($fileName) . "\""; $atts[] = "mimestring=\"" . AJXP_Utils::mimetype($fileName, "type", $file["isDir"] == 1) . "\""; $atts[] = "ajxp_modiftime=\"" . $this->dateModif($file["time"]) . "\""; $atts[] = "filesize=\"" . AJXP_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 = "folder.png"; $openicon = "folder_open.png"; if (preg_match("/\\.zip\$/", $file["name"])) { $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/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($reloadContextNode)) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", 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; }
/** * @param $src * @param $dest * @param $basedir * @throws Exception * @return zipfile */ public function makeZip($src, $dest, $basedir) { $zipEncoding = ConfService::getCoreConf("ZIP_ENCODING"); @set_time_limit(0); require_once AJXP_BIN_FOLDER . "/pclzip.lib.php"; $filePaths = array(); foreach ($src as $item) { $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . "/" . $item); $realFile = AJXP_Utils::securePath($realFile); if (basename($item) == "") { $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $realFile); } else { $shortName = basename($item); if (!empty($zipEncoding)) { $test = iconv(SystemTextEncoding::getEncoding(), $zipEncoding, $shortName); if ($test !== false) { $shortName = $test; } } $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $realFile, PCLZIP_ATT_FILE_NEW_SHORT_NAME => $shortName); } } $this->logDebug("Pathes", $filePaths); self::$filteringDriverInstance = $this; $archive = new PclZip($dest); if ($basedir == "__AJXP_ZIP_FLAT__/") { $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_ADD_TEMP_FILE_ON, PCLZIP_CB_PRE_ADD, 'zipPreAddCallback'); } else { $basedir = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase) . trim($basedir); $this->logDebug("Basedir", array($basedir)); $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_PATH, $basedir, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_ADD_TEMP_FILE_ON, PCLZIP_CB_PRE_ADD, 'zipPreAddCallback'); } if (!$vList) { throw new Exception("Zip creation error : ({$dest}) " . $archive->errorInfo(true)); } self::$filteringDriverInstance = null; return $vList; }
public function uploadActions($action, $httpVars, $filesVars) { switch ($action) { case "trigger_remote_copy": if (!$this->hasFilesToCopy()) { break; } $toCopy = $this->getFileNameToCopy(); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . $toCopy . " to ftp server"); AJXP_XMLWriter::close(); exit(1); break; case "next_to_remote": if (!$this->hasFilesToCopy()) { break; } $fData = $this->getNextFileToCopy(); $nextFile = ''; if ($this->hasFilesToCopy()) { $nextFile = $this->getFileNameToCopy(); } $this->logDebug("Base64 : ", array("from" => $fData["destination"], "to" => base64_decode($fData['destination']))); $destPath = $this->urlBase . base64_decode($fData['destination']) . "/" . $fData['name']; //$destPath = AJXP_Utils::decodeSecureMagic($destPath); // DO NOT "SANITIZE", THE URL IS ALREADY IN THE FORM ajxp.ftp://repoId/filename $destPath = SystemTextEncoding::fromPostedFileName($destPath); $node = new AJXP_Node($destPath); $this->logDebug("Copying file to server", array("from" => $fData["tmp_name"], "to" => $destPath, "name" => $fData["name"])); try { AJXP_Controller::applyHook("node.before_create", array(&$node)); $fp = fopen($destPath, "w"); $fSource = fopen($fData["tmp_name"], "r"); while (!feof($fSource)) { fwrite($fp, fread($fSource, 4096)); } fclose($fSource); $this->logDebug("Closing target : begin ftp copy"); // Make sur the script does not time out! @set_time_limit(240); fclose($fp); $this->logDebug("FTP Upload : end of ftp copy"); @unlink($fData["tmp_name"]); AJXP_Controller::applyHook("node.change", array(null, &$node)); } catch (Exception $e) { $this->logDebug("Error during ftp copy", array($e->getMessage(), $e->getTrace())); } $this->logDebug("FTP Upload : shoud trigger next or reload nextFile={$nextFile}"); AJXP_XMLWriter::header(); if ($nextFile != '') { AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . SystemTextEncoding::toUTF8($nextFile) . " to remote server"); } else { AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Upload done, reloading client."); } AJXP_XMLWriter::close(); exit(1); break; case "upload": $rep_source = AJXP_Utils::securePath("/" . $httpVars['dir']); $this->logDebug("Upload : rep_source ", array($rep_source)); $logMessage = ""; foreach ($filesVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $this->logDebug("Upload : rep_source ", array($rep_source)); $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } if (isset($httpVars["auto_rename"])) { $destination = $this->urlBase . $rep_source; $boxData["name"] = fsAccessDriver::autoRenameForDest($destination, $boxData["name"]); } $boxData["destination"] = base64_encode($rep_source); $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($this->repository->getOption("TMP_UPLOAD")); $this->logDebug("Upload : tmp upload folder", array($destCopy)); if (!is_dir($destCopy)) { if (!@mkdir($destCopy)) { $this->logDebug("Upload error : cannot create temporary folder", array($destCopy)); $errorCode = 413; $errorMessage = "Warning, cannot create folder for temporary copy."; break; } } if (!$this->isWriteable($destCopy)) { $this->logDebug("Upload error: cannot write into temporary folder"); $errorCode = 414; $errorMessage = "Warning, cannot write into temporary folder."; break; } $this->logDebug("Upload : tmp upload folder", array($destCopy)); if (isset($boxData["input_upload"])) { try { $destName = tempnam($destCopy, ""); $this->logDebug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen($destName, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); $boxData["tmp_name"] = $destName; $this->storeFileToCopy($boxData); $this->logDebug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { $destName = $destCopy . "/" . basename($boxData["tmp_name"]); if ($destName == $boxData["tmp_name"]) { $destName .= "1"; } if (move_uploaded_file($boxData["tmp_name"], $destName)) { $boxData["tmp_name"] = $destName; $this->storeFileToCopy($boxData); } else { $mess = ConfService::getMessages(); $errorCode = 411; $errorMessage = "{$mess['33']} " . $boxData["name"]; break; } } } if (isset($errorMessage)) { $this->logDebug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { $this->logDebug("Return success"); return array("SUCCESS" => true, "PREVENT_NOTIF" => true); } break; default: break; } session_write_close(); exit; }
/** * Opens the strem * * @param String $path Maybe in the form "ajxp.fs://repositoryId/pathToFile" * @param String $mode * @param unknown_type $options * @param unknown_type $context * @return unknown */ public function stream_open($path, $mode, $options, &$context) { try { $this->realPath = AJXP_Utils::securePath(self::initPath($path, "file")); } catch (Exception $e) { AJXP_Logger::logAction("error", array("message" => "Error while opening stream {$path}")); return false; } if ($this->realPath == -1) { $this->fp = -1; return true; } else { $this->fp = fopen($this->realPath, $mode, $options); return $this->fp !== false; } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) { // Force legacy theme for the moment $this->pluginConf["GUI_THEME"] = "oxygen"; } if (!defined("AJXP_THEME_FOLDER")) { define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res"); define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]); } foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } if (isset($dir) && $action != "upload") { $dir = SystemTextEncoding::fromUTF8($dir); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // GET AN HTML TEMPLATE //------------------------------------ case "get_template": HTMLWriter::charsetHeader(); $folder = CLIENT_RESOURCES_FOLDER . "/html"; if (isset($httpVars["pluginName"])) { $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]); if (isset($httpVars["pluginPath"])) { $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]); } } $crtTheme = $this->pluginConf["GUI_THEME"]; $thFolder = AJXP_THEME_FOLDER . "/html"; if (isset($template_name)) { if (is_file($thFolder . "/" . $template_name)) { include $thFolder . "/" . $template_name; } else { if (is_file($folder . "/" . $template_name)) { include $folder . "/" . $template_name; } } } break; //------------------------------------ // GET I18N MESSAGES //------------------------------------ //------------------------------------ // GET I18N MESSAGES //------------------------------------ case "get_i18n_messages": $refresh = false; if (isset($httpVars["lang"])) { ConfService::setLanguage($httpVars["lang"]); $refresh = true; } HTMLWriter::charsetHeader('text/javascript'); HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh)); break; //------------------------------------ // SEND XML REGISTRY //------------------------------------ //------------------------------------ // SEND XML REGISTRY //------------------------------------ case "get_xml_registry": $regDoc = AJXP_PluginsService::getXmlRegistry(); $changes = AJXP_Controller::filterActionsRegistry($regDoc); if ($changes) { AJXP_PluginsService::updateXmlRegistry($regDoc); } if (isset($_GET["xPath"])) { $regPath = new DOMXPath($regDoc); $nodes = $regPath->query($_GET["xPath"]); AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $_GET["xPath"])); if ($nodes->length) { print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML($nodes->item(0))); } AJXP_XMLWriter::close("ajxp_registry_part"); } else { AJXP_Utils::safeIniSet("zlib.output_compression", "4096"); header('Content-Type: application/xml; charset=UTF-8'); print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML()); } break; //------------------------------------ // DISPLAY DOC //------------------------------------ //------------------------------------ // DISPLAY DOC //------------------------------------ case "display_doc": HTMLWriter::charsetHeader(); echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($_GET["doc_file"]))); break; //------------------------------------ // GET BOOT GUI //------------------------------------ //------------------------------------ // GET BOOT GUI //------------------------------------ case "get_boot_gui": header("X-UA-Compatible: chrome=1"); HTMLWriter::charsetHeader(); if (!is_file(TESTS_RESULT_FILE)) { $outputArray = array(); $testedParams = array(); $passed = AJXP_Utils::runTests($outputArray, $testedParams); if (!$passed && !isset($_GET["ignore_tests"])) { die(AJXP_Utils::testResultsToTable($outputArray, $testedParams)); } else { AJXP_Utils::testResultsToFile($outputArray, $testedParams); } } $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop"); if (AuthService::usersEnabled()) { AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : ""); AuthService::bootSequence($START_PARAMETERS); if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) { if (AuthService::getDefaultRootId() == -1) { AuthService::disconnect(); } else { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canRead(ConfService::getCurrentRootDirIndex()) && AuthService::getDefaultRootId() != ConfService::getCurrentRootDirIndex()) { ConfService::switchRootDir(AuthService::getDefaultRootId()); } } } } AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION); $confErrors = ConfService::getErrors(); if (count($confErrors)) { $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors)); } $JSON_START_PARAMETERS = json_encode($START_PARAMETERS); $crtTheme = $this->pluginConf["GUI_THEME"]; if (ConfService::getConf("JS_DEBUG")) { if (!isset($mess)) { $mess = ConfService::getMessages(); } if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) { include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html"; } else { include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html"; } } else { if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) { $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html"); } else { $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html"); } if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) { $content = str_replace("ajaxplorer_boot.js", "ajaxplorer_boot_protolegacy.js", $content); } $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false); if ($JSON_START_PARAMETERS) { $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content); } print $content; } break; //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ case "get_boot_conf": if (isset($_GET["server_prefix_uri"])) { $_SESSION["AJXP_SERVER_PREFIX_URI"] = $_GET["server_prefix_uri"]; } $config = array(); $config["ajxpResourcesFolder"] = "plugins/gui.ajax/res"; $config["ajxpServerAccess"] = AJXP_SERVER_ACCESS; $config["zipEnabled"] = ConfService::zipEnabled(); $config["multipleFilesDownloadEnabled"] = ConfService::getCoreConf("ZIP_CREATION"); $config["customWording"] = array("welcomeMessage" => $this->pluginConf["CUSTOM_WELCOME_MESSAGE"], "title" => ConfService::getCoreConf("APPLICATION_TITLE"), "icon" => $this->pluginConf["CUSTOM_ICON"], "iconWidth" => $this->pluginConf["CUSTOM_ICON_WIDTH"], "iconHeight" => $this->pluginConf["CUSTOM_ICON_HEIGHT"], "iconOnly" => $this->pluginConf["CUSTOM_ICON_ONLY"], "titleFontSize" => $this->pluginConf["CUSTOM_FONT_SIZE"]); $config["usersEnabled"] = AuthService::usersEnabled(); $config["loggedUser"] = AuthService::getLoggedUser() != null; $config["currentLanguage"] = ConfService::getLanguage(); $config["session_timeout"] = intval(ini_get("session.gc_maxlifetime")); if (!isset($this->pluginConf["CLIENT_TIMEOUT_TIME"]) || $this->pluginConf["CLIENT_TIMEOUT_TIME"] == "") { $to = $config["session_timeout"]; } else { $to = $this->pluginConf["CLIENT_TIMEOUT_TIME"]; } $config["client_timeout"] = $to; $config["client_timeout_warning"] = $this->pluginConf["CLIENT_TIMEOUT_WARN"]; $config["availableLanguages"] = ConfService::getConf("AVAILABLE_LANG"); $config["usersEditable"] = ConfService::getAuthDriverImpl()->usersEditable(); $config["ajxpVersion"] = AJXP_VERSION; $config["ajxpVersionDate"] = AJXP_VERSION_DATE; if (stristr($_SERVER["HTTP_USER_AGENT"], "msie 6")) { $config["cssResources"] = array("css/pngHack/pngHack.css"); } if (!empty($this->pluginConf['GOOGLE_ANALYTICS_ID'])) { $config["googleAnalyticsData"] = array("id" => $this->pluginConf['GOOGLE_ANALYTICS_ID'], "domain" => $this->pluginConf['GOOGLE_ANALYTICS_DOMAIN'], "event" => $this->pluginConf['GOOGLE_ANALYTICS_EVENT']); } $config["i18nMessages"] = ConfService::getMessages(); $config["password_min_length"] = ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth"); $config["SECURE_TOKEN"] = AuthService::generateSecureToken(); $config["streaming_supported"] = "true"; $config["theme"] = $this->pluginConf["GUI_THEME"]; header("Content-type:application/json;charset=UTF-8"); print json_encode($config); break; default: break; } return false; }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); if ($action == "post_to_zohoserver") { $sheetExt = explode(",", "xls,xlsx,ods,sxc,csv,tsv"); $presExt = explode(",", "ppt,pps,odp,sxi"); $docExt = explode(",", "doc,docx,rtf,odt,sxw"); require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; $file = base64_decode($httpVars["file"]); $file = AJXP_Utils::securePath($file); $target = base64_decode($httpVars["parent_url"]); $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file); $tmp = SystemTextEncoding::fromUTF8($tmp); $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); $extension = strtolower(pathinfo(urlencode(basename($file)), PATHINFO_EXTENSION)); $httpClient = new http_class(); $httpClient->request_method = "POST"; $secureToken = $httpVars["secure_token"]; $_SESSION["ZOHO_CURRENT_EDITED"] = $destStreamURL . $file; $_SESSION["ZOHO_CURRENT_UUID"] = md5(rand() . "-" . microtime()); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) { $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()); } else { $saveUrl = $target . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/save_zoho.php"; } $b64Sig = $this->signID($_SESSION["ZOHO_CURRENT_UUID"]); $params = array('id' => $_SESSION["ZOHO_CURRENT_UUID"], 'apikey' => $this->getFilteredOption("ZOHO_API_KEY", $repository->getId()), 'output' => 'url', 'lang' => "en", 'filename' => urlencode(basename($file)), 'persistence' => 'false', 'format' => $extension, 'mode' => 'normaledit', 'saveurl' => $saveUrl . "?signature=" . $b64Sig); $service = "exportwriter"; if (in_array($extension, $sheetExt)) { $service = "sheet"; } else { if (in_array($extension, $presExt)) { $service = "show"; } else { if (in_array($extension, $docExt)) { $service = "exportwriter"; } } } $arguments = array(); $httpClient->GetRequestArguments("https://" . $service . ".zoho.com/remotedoc.im", $arguments); $arguments["PostValues"] = $params; $arguments["PostFiles"] = array("content" => array("FileName" => $tmp, "Content-Type" => "automatic/name")); $err = $httpClient->Open($arguments); if (empty($err)) { $err = $httpClient->SendRequest($arguments); if (empty($err)) { $response = ""; while (true) { $body = ""; $error = $httpClient->ReadReplyBody($body, 1000); if ($error != "" || strlen($body) == 0) { break; } $response .= $body; } $result = trim($response); $matchlines = explode("\n", $result); $resultValues = array(); foreach ($matchlines as $line) { list($key, $val) = explode("=", $line, 2); $resultValues[$key] = $val; } if ($resultValues["RESULT"] == "TRUE" && isset($resultValues["URL"])) { header("Location: " . $resultValues["URL"]); } else { echo "Zoho API Error " . $resultValues["ERROR_CODE"] . " : " . $resultValues["WARNING"]; echo "<script>window.parent.setTimeout(function(){parent.hideLightBox();}, 2000);</script>"; } } $httpClient->Close(); } } else { if ($action == "retrieve_from_zohoagent") { $targetFile = $_SESSION["ZOHO_CURRENT_EDITED"]; $id = $_SESSION["ZOHO_CURRENT_UUID"]; $ext = pathinfo($targetFile, PATHINFO_EXTENSION); $node = new AJXP_Node($targetFile); $node->loadNodeInfo(); AJXP_Controller::applyHook("node.before_change", array(&$node)); $b64Sig = $this->signID($id); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) { $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()) . "?ajxp_action=get_file&name=" . $id . "&ext=" . $ext . "&signature=" . $b64Sig; $data = AJXP_Utils::getRemoteContent($url); if (strlen($data)) { file_put_contents($targetFile, $data); echo "MODIFIED"; } } else { if (is_file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id)) { copy(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id, $targetFile); unlink(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id); echo "MODIFIED"; } } AJXP_Controller::applyHook("node.change", array(null, &$node)); } } }
protected function buildRealUrl($url) { if (!isset($this->user)) { $parts = $this->parseUrl($url); } else { // parseUrl already called before (rename case). $parts = parse_url($url); } $serverPath = AJXP_Utils::securePath("/{$this->path}/" . $parts["path"]); return "ftp" . ($this->secure ? "s" : "") . "://{$this->user}:{$this->password}@{$this->host}:{$this->port}" . $serverPath; }
public function url_stat($path, $flags) { $parts = $this->parseUrl($path); $client = $this->createHttpClient(); $client->get($this->path . "?get_action=stat&file=" . AJXP_Utils::securePath($parts["path"])); $json = $client->getContent(); $decode = json_decode($json, true); return $decode; }
function parseParameters(&$repDef, &$options, $userId = null) { $replicationGroups = array(); foreach ($repDef as $key => $value) { $value = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($value)); if (strpos($key, "DRIVER_OPTION_") !== false && strpos($key, "DRIVER_OPTION_") == 0 && strpos($key, "ajxptype") === false && strpos($key, "_replication") === false && strpos($key, "_checkbox") === false) { if (isset($repDef[$key . "_ajxptype"])) { $type = $repDef[$key . "_ajxptype"]; if ($type == "boolean") { $value = $value == "true" ? true : false; } else { if ($type == "integer") { $value = intval($value); } else { if ($type == "array") { $value = explode(",", $value); } else { if ($type == "password" && $userId != null) { if (trim($value != "") && function_exists('mcrypt_encrypt')) { // The initialisation vector is only required to avoid a warning, as ECB ignore IV $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); // We encode as base64 so if we need to store the result in a database, it can be stored in text column $value = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($userId . "CDAFx¨op#"), $value, MCRYPT_MODE_ECB, $iv)); } } } } } unset($repDef[$key . "_ajxptype"]); } if (isset($repDef[$key . "_checkbox"])) { $checked = $repDef[$key . "_checkbox"] == "checked"; unset($repDef[$key . "_checkbox"]); if (!$checked) { continue; } } if (isset($repDef[$key . "_replication"])) { $repKey = $repDef[$key . "_replication"]; if (!is_array($replicationGroups[$repKey])) { $replicationGroups[$repKey] = array(); } $replicationGroups[$repKey][] = $key; } $options[substr($key, strlen("DRIVER_OPTION_"))] = $value; unset($repDef[$key]); } else { if ($key == "DISPLAY") { $value = SystemTextEncoding::fromUTF8(AJXP_Utils::securePath($value)); } $repDef[$key] = $value; } } // DO SOMETHING WITH REPLICATED PARAMETERS? if (count($replicationGroups)) { } }
public function uploadActions($action, $httpVars, $filesVars) { switch ($action) { case "trigger_remote_copy": if (!$this->hasFilesToCopy()) { break; } $toCopy = $this->getFileNameToCopy(); $this->logDebug("trigger_remote", $toCopy); AJXP_XMLWriter::header(); AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . $toCopy . " to remote server"); AJXP_XMLWriter::close(); exit(1); break; case "next_to_remote": if (!$this->hasFilesToCopy()) { break; } $fData = $this->getNextFileToCopy(); $nextFile = ''; if ($this->hasFilesToCopy()) { $nextFile = $this->getFileNameToCopy(); } $crtRep = ConfService::getRepository(); session_write_close(); $secureToken = ""; $httpClient = $this->getRemoteConnexion($secureToken); //$httpClient->setDebug(true); $postData = array("get_action" => "upload", "dir" => base64_encode($fData["destination"]), "secure_token" => $secureToken); $httpClient->postFile($crtRep->getOption("URI") . "?", $postData, "Filedata", $fData); if (strpos($httpClient->getHeader("content-type"), "text/xml") !== false && strpos($httpClient->getContent(), "require_auth") != false) { $httpClient = $this->getRemoteConnexion($secureToken, true); $postData["secure_token"] = $secureToken; $httpClient->postFile($crtRep->getOption("URI"), $postData, "Filedata", $fData); } unlink($fData["tmp_name"]); $response = $httpClient->getContent(); AJXP_XMLWriter::header(); $this->logDebug("next_to_remote", $nextFile); if (intval($response) >= 400) { AJXP_XMLWriter::sendMessage(null, "Error : " . intval($response)); } else { if ($nextFile != '') { AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . SystemTextEncoding::toUTF8($nextFile) . " to remote server"); } else { AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Upload done, reloading client."); } } AJXP_XMLWriter::close(); exit(1); break; case "upload": $rep_source = AJXP_Utils::securePath("/" . $httpVars['dir']); $this->logDebug("Upload : rep_source ", array($rep_source)); $logMessage = ""; foreach ($filesVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $this->logDebug("Upload : rep_source ", array($rep_source)); $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } $boxData["destination"] = $rep_source; $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($this->repository->getOption("TMP_UPLOAD")); $this->logDebug("Upload : tmp upload folder", array($destCopy)); if (!is_dir($destCopy)) { if (!@mkdir($destCopy)) { $this->logDebug("Upload error : cannot create temporary folder", array($destCopy)); $errorCode = 413; $errorMessage = "Warning, cannot create folder for temporary copy."; break; } } if (!is_writeable($destCopy)) { $this->logDebug("Upload error: cannot write into temporary folder"); $errorCode = 414; $errorMessage = "Warning, cannot write into temporary folder."; break; } $this->logDebug("Upload : tmp upload folder", array($destCopy)); if (isset($boxData["input_upload"])) { try { $destName = tempnam($destCopy, ""); $this->logDebug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen($destName, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); $boxData["tmp_name"] = $destName; $this->storeFileToCopy($boxData); $this->logDebug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { $destName = $destCopy . "/" . basename($boxData["tmp_name"]); if ($destName == $boxData["tmp_name"]) { $destName .= "1"; } if (move_uploaded_file($boxData["tmp_name"], $destName)) { $boxData["tmp_name"] = $destName; $this->storeFileToCopy($boxData); } else { $mess = ConfService::getMessages(); $errorCode = 411; $errorMessage = "{$mess['33']} " . $boxData["name"]; break; } } } if (isset($errorMessage)) { $this->logDebug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { $this->logDebug("Return success"); return array("SUCCESS" => true); } session_write_close(); break; default: break; } }
/** * @param array $httpVars * @param bool $update * @return Repository * @throws Exception */ protected function createOrLoadSharedRepository($httpVars, &$update) { if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") { $mess = ConfService::getMessages(); throw new Exception($mess["349"]); } if (isset($httpVars["repository_id"])) { $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]); $update = true; } // CHECK REPO DOES NOT ALREADY EXISTS WITH SAME LABEL $label = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_label"]), AJXP_SANITIZE_HTML); $description = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_description"]), AJXP_SANITIZE_HTML); $exists = $this->checkRepoWithSameLabel($label, isset($editingRepo) ? $editingRepo : null); if ($exists) { $mess = ConfService::getMessages(); throw new Exception($mess["share_center.352"]); } $loggedUser = AuthService::getLoggedUser(); if (isset($editingRepo)) { $this->getShareStore()->testUserCanEditShare($editingRepo->getOwner(), $editingRepo->options); $newRepo = $editingRepo; $replace = false; if ($editingRepo->getDisplay() != $label) { $newRepo->setDisplay($label); $replace = true; } if ($editingRepo->getDescription() != $description) { $newRepo->setDescription($description); $replace = true; } $newScope = isset($httpVars["share_scope"]) && $httpVars["share_scope"] == "public" ? "public" : "private"; $oldScope = $editingRepo->getOption("SHARE_ACCESS"); $currentOwner = $editingRepo->getOwner(); if ($newScope != $oldScope && $currentOwner != AuthService::getLoggedUser()->getId()) { $mess = ConfService::getMessages(); throw new Exception($mess["share_center.224"]); } if ($newScope !== $oldScope) { $editingRepo->addOption("SHARE_ACCESS", $newScope); $replace = true; } if (isset($httpVars["transfer_owner"])) { $newOwner = $httpVars["transfer_owner"]; if ($newOwner != $currentOwner && $currentOwner != AuthService::getLoggedUser()->getId()) { $mess = ConfService::getMessages(); throw new Exception($mess["share_center.224"]); } $editingRepo->setOwnerData($editingRepo->getParentId(), $newOwner, $editingRepo->getUniqueUser()); $replace = true; } if ($replace) { ConfService::replaceRepository($newRepo->getId(), $newRepo); } } else { $options = $this->accessDriver->makeSharedRepositoryOptions($httpVars, $this->repository); // TMP TESTS $options["SHARE_ACCESS"] = $httpVars["share_scope"]; $newRepo = $this->repository->createSharedChild($label, $options, $this->repository->getId(), $loggedUser->getId(), null); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) { $newRepo->setGroupPath($gPath); } $newRepo->setDescription($description); // Smells like dirty hack! $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]); if (isset($httpVars["filter_nodes"])) { $newRepo->setContentFilter(new ContentFilter($httpVars["filter_nodes"])); } ConfService::addRepository($newRepo); } return $newRepo; }
<?php define('AJXP_EXEC', true); require_once '../../core/classes/class.AJXP_Utils.php'; $AJXP_FILE_URL = AJXP_Utils::securePath(AJXP_Utils::sanitize($_GET["file"], 5)); $parts = explode("/", AJXP_Utils::securePath($_GET["file"])); foreach ($parts as $i => $part) { $parts[$i] = AJXP_Utils::sanitize($part, AJXP_SANITIZE_FILENAME); } $AJXP_FILE_URL = implode("/", $parts); ?> <html> <head> <script src="webodf/webodf.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> function init() { var odfelement = document.getElementById("odf"); window.odfcanvas = new odf.OdfCanvas(odfelement); window.odfcanvas.load("../../" + window.parent.ajxpServerAccessPath + "&get_action=download&file=<?php echo $AJXP_FILE_URL; ?> "); //window.odfcanvas.setEditable(true); /* odfcanvas.odfContainer().save(function(err){ console.log(err); }); */ } window.setTimeout(init, 0);
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; } }