public function authenticate(Sabre\DAV\Server $server, $realm) { //AJXP_Logger::debug("Try authentication on $realm", $server); try { $success = parent::authenticate($server, $realm); } catch (Exception $e) { $success = 0; $errmsg = $e->getMessage(); if ($errmsg != "No digest authentication headers were found") { $success = false; } } if ($success) { $res = AuthService::logUser($this->currentUser, null, true); if ($res < 1) { throw new Sabre\DAV\Exception\NotAuthenticated(); } $this->updateCurrentUserRights(AuthService::getLoggedUser()); if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { $webdavData = AuthService::getLoggedUser()->getPref("AJXP_WEBDAV_DATA"); AJXP_Safe::storeCredentials($this->currentUser, $this->_decodePassword($webdavData["PASS"], $this->currentUser)); } } else { if ($success === false) { AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => $this->currentUser, "error" => "Invalid WebDAV user or password")); } throw new Sabre\DAV\Exception\NotAuthenticated($errmsg); } ConfService::switchRootDir($this->repositoryId); return true; }
public function checkPassword($login, $pass, $seed) { require_once AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/access.smb/smb.php"; $_SESSION["AJXP_SESSION_REMOTE_PASS"] = $pass; $repoId = $this->options["REPOSITORY_ID"]; $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { throw new Exception("Cannot find repository with id " . $repoId); } $path = ""; $basePath = $repoObject->getOption("PATH", true); $basePath = str_replace("AJXP_USER", $login, $basePath); $host = $repoObject->getOption("HOST"); $url = "smb://{$login}:{$pass}@" . $host . "/" . $basePath . "/"; try { if (!is_dir($url)) { $this->logDebug("SMB Login failure"); $_SESSION["AJXP_SESSION_REMOTE_PASS"] = ''; unset($_SESSION["COUNT"]); unset($_SESSION["disk"]); return false; } AJXP_Safe::storeCredentials($login, $pass); } catch (Exception $e) { return false; } return true; }
/** * Initialize the stream from the given path. * Concretely, transform ajxp.smb:// into smb:// * * @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"]; // Fix if the host is defined as //MY_HOST/path/to/folder $host = str_replace("//", "", $repoObject->getOption("HOST")); $credentials = ""; $safeCreds = AJXP_Safe::tryLoadingCredentialsFromSources($url, $repoObject); if ($safeCreds["user"] != "" && $safeCreds["password"] != "") { $login = $safeCreds["user"]; $pass = $safeCreds["password"]; $_SESSION["AJXP_SESSION_REMOTE_PASS"] = $pass; $credentials = "{$login}:{$pass}@"; $domain = $repoObject->getOption("DOMAIN"); if ($domain != "") { $credentials = $domain . "/" . $credentials; } } $basePath = $repoObject->getOption("PATH"); $fullPath = "smb://" . $credentials . $host . "/"; //.$basePath."/".$path; if ($basePath != "") { $fullPath .= trim($basePath, "/\\"); } if ($path != "") { $fullPath .= ($path[0] == "/" ? "" : "/") . $path; } return $fullPath; }
public function logoutCallback($actionName, $httpVars, $fileVars) { AJXP_Safe::clearCredentials(); $adminUser = $this->options["AJXP_ADMIN_LOGIN"]; AuthService::disconnect(); session_write_close(); AJXP_XMLWriter::header(); AJXP_XMLWriter::loggingResult(2); AJXP_XMLWriter::close(); }
/** * 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; }
protected function getCredentials() { // 1. Try from plugin config $user = $this->options["USER"]; $password = $this->options["PASS"]; // 1BIS : encoded? if ($user == "" && isset($this->options["ENCODED_CREDENTIALS"])) { list($user, $password) = AJXP_Safe::getCredentialsFromEncodedString($this->options["ENCODED_CREDENTIALS"]); } // 2. Try from session if ($user == "" && isset($this->options["USE_SESSION_CREDENTIALS"])) { $safeCred = AJXP_Safe::loadCredentials(); if ($safeCred !== false) { $user = $safeCred["user"]; $password = $safeCred["password"]; } } return array($user, $password); }
public function authenticate(Sabre\DAV\Server $server, $realm) { //AJXP_Logger::debug("Try authentication on $realm", $server); $success = parent::authenticate($server, $realm); if ($success) { $res = AuthService::logUser($this->currentUser, null, true); if ($res < 1) { throw new Sabre\DAV\Exception\NotAuthenticated(); } $this->updateCurrentUserRights(AuthService::getLoggedUser()); if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { $webdavData = AuthService::getLoggedUser()->getPref("AJXP_WEBDAV_DATA"); AJXP_Safe::storeCredentials($this->currentUser, $this->_decodePassword($webdavData["PASS"], $this->currentUser)); } } if ($success === false) { throw new Sabre\DAV\Exception\NotAuthenticated(); } ConfService::switchRootDir($this->repositoryId); return true; }
protected function getCredentials() { // 1. Try from plugin config $user = $this->options["USER"]; $password = $this->options["PASS"]; // 1BIS : encoded? if ($user == "" && isset($this->options["ENCODED_CREDENTIALS"])) { list($user, $password) = AJXP_Safe::getCredentialsFromEncodedString($this->options["ENCODED_CREDENTIALS"]); } // 2. Try from session if ($user == "" && isset($this->options["USE_SESSION_CREDENTIALS"])) { $safeCred = AJXP_Safe::loadCredentials(); if ($safeCred !== false) { $user = $safeCred["user"]; $password = $safeCred["password"]; } else { throw new Exception("Session credential are empty! Did you forget to check the Set Session Credential in the Authentication configuration panel?"); } } return array($user, $password); }
/** * Clear the session * @static * @return void */ public static function disconnect() { if (isset($_SESSION["AJXP_USER"]) || isset(self::$currentUser)) { $user = isset($_SESSION["AJXP_USER"]) ? $_SESSION["AJXP_USER"] : self::$currentUser; $userId = $user->id; AJXP_Controller::applyHook("user.before_disconnect", array($user)); AuthService::clearRememberCookie(); AJXP_Logger::info(__CLASS__, "Log Out", ""); unset($_SESSION["AJXP_USER"]); if (isset(self::$currentUser)) { unset(self::$currentUser); } if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { AJXP_Safe::clearCredentials(); } AJXP_Controller::applyHook("user.after_disconnect", array($userId)); } }
/** * Launch a command-line version of the framework by passing the actionName & parameters as arguments. * @static * @param String $currentRepositoryId * @param String $actionName * @param Array $parameters * @param string $user * @param string $statusFile * @return null|UnixProcess */ public static function applyActionInBackground($currentRepositoryId, $actionName, $parameters, $user = "", $statusFile = "") { $token = md5(time()); $logDir = AJXP_CACHE_DIR . "/cmd_outputs"; if (!is_dir($logDir)) { mkdir($logDir, 0755); } $logFile = $logDir . "/" . $token . ".out"; if (empty($user)) { if (AuthService::usersEnabled() && AuthService::getLoggedUser() !== null) { $user = AuthService::getLoggedUser()->getId(); } else { $user = "******"; } } if (AuthService::usersEnabled()) { $cKey = ConfService::getCoreConf("AJXP_CLI_SECRET_KEY", "conf"); if (empty($cKey)) { $cKey = "CDAFx¨op#"; } $user = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($token . $cKey), $user, MCRYPT_MODE_ECB)); } $robustInstallPath = str_replace("/", DIRECTORY_SEPARATOR, AJXP_INSTALL_PATH); $cmd = ConfService::getCoreConf("CLI_PHP") . " " . $robustInstallPath . DIRECTORY_SEPARATOR . "cmd.php -u={$user} -t={$token} -a={$actionName} -r={$currentRepositoryId}"; /* Inserted next 3 lines to quote the command if in windows - rmeske*/ if (PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows") { $cmd = ConfService::getCoreConf("CLI_PHP") . " " . chr(34) . $robustInstallPath . DIRECTORY_SEPARATOR . "cmd.php" . chr(34) . " -u={$user} -t={$token} -a={$actionName} -r={$currentRepositoryId}"; } if ($statusFile != "") { $cmd .= " -s=" . $statusFile; } foreach ($parameters as $key => $value) { if ($key == "action" || $key == "get_action") { continue; } if (is_array($value)) { $index = 0; foreach ($value as $v) { $cmd .= " --file_" . $index . "=" . escapeshellarg($v); $index++; } } else { $cmd .= " --{$key}=" . escapeshellarg($value); } } $repoObject = ConfService::getRepository(); $clearEnv = false; if ($repoObject->getOption("USE_SESSION_CREDENTIALS")) { $encodedCreds = AJXP_Safe::getEncodedCredentialString(); if (!empty($encodedCreds)) { putenv("AJXP_SAFE_CREDENTIALS=" . $encodedCreds); $clearEnv = "AJXP_SAFE_CREDENTIALS"; } } $res = self::runCommandInBackground($cmd, $logFile); if (!empty($clearEnv)) { putenv($clearEnv); } return $res; }
protected function parseUrl($url, $forceLogin = false) { // URL MAY BE ajxp.ftp://username:password@host/path $urlParts = AJXP_Utils::safeParseUrl($url); $this->repositoryId = $urlParts["host"]; $repository = ConfService::getRepositoryById($this->repositoryId); if ($repository == null) { throw new Exception("Cannot find repository for dynamic ftp authentification."); } $credentials = AJXP_Safe::tryLoadingCredentialsFromSources($urlParts, $repository); $this->user = $credentials["user"]; $this->password = $credentials["password"]; if ($this->user == "") { throw new AJXP_Exception("Cannot find user/pass for FTP access!"); } if ($repository->getOption("DYNAMIC_FTP") == "TRUE" && isset($_SESSION["AJXP_DYNAMIC_FTP_DATA"])) { $data = $_SESSION["AJXP_DYNAMIC_FTP_DATA"]; $this->host = $data["FTP_HOST"]; $this->path = $data["PATH"]; $this->secure = $data["FTP_SECURE"] == "TRUE" ? true : false; $this->port = $data["FTP_PORT"] != "" ? intval($data["FTP_PORT"]) : ($this->secure ? 22 : 21); $this->ftpActive = $data["FTP_DIRECT"] == "TRUE" ? true : false; $this->repoCharset = $data["CHARSET"]; } else { $this->host = $repository->getOption("FTP_HOST"); $this->path = $repository->getOption("PATH"); $this->secure = $repository->getOption("FTP_SECURE") == "TRUE" ? true : false; $this->port = $repository->getOption("FTP_PORT") != "" ? intval($repository->getOption("FTP_PORT")) : ($this->secure ? 22 : 21); $this->ftpActive = $repository->getOption("FTP_DIRECT") == "TRUE" ? true : false; $this->repoCharset = $repository->getOption("CHARSET"); } // Test Connexion and server features global $_SESSION; $cacheKey = $repository->getId() . "_ftpCharset"; if (!isset($_SESSION[$cacheKey]) || !strlen($_SESSION[$cacheKey]) || $forceLogin) { $features = $this->getServerFeatures(); $ctxCharset = ConfService::getContextCharset(); if (empty($ctxCharset)) { ConfService::setContextCharset($features["charset"]); $_SESSION[$cacheKey] = $features["charset"]; } else { $_SESSION[$cacheKey] = $ctxCharset; } } return $urlParts; }
function tryToLogUser(&$httpVars, $isLast = false) { if (isset($_SESSION["CURRENT_MINISITE"])) { return false; } $this->loadConfig(); if (isset($_SESSION['AUTHENTICATE_BY_CAS'])) { $flag = $_SESSION['AUTHENTICATE_BY_CAS']; } else { $flag = 0; } $pgtIou = !empty($httpVars['pgtIou']); $logged = isset($_SESSION['LOGGED_IN_BY_CAS']); $enre = !empty($httpVars['put_action_enable_redirect']); $ticket = !empty($httpVars['ticket']); $pgt = !empty($_SESSION['phpCAS']['pgt']); $clientModeTicketPendding = isset($_SESSION['AUTHENTICATE_BY_CAS_CLIENT_MOD_TICKET_PENDDING']); if ($this->cas_modify_login_page) { if ($flag == 0 && $enre && !$logged && !$pgtIou) { $_SESSION['AUTHENTICATE_BY_CAS'] = 1; } elseif ($flag == 1 && !$enre && !$logged && !$pgtIou && !$ticket && !$pgt) { $_SESSION['AUTHENTICATE_BY_CAS'] = 0; } elseif ($flag == 1 && $enre && !$logged && !$pgtIou) { $_SESSION['AUTHENTICATE_BY_CAS'] = 1; } elseif ($pgtIou || $pgt) { $_SESSION['AUTHENTICATE_BY_CAS'] = 1; } elseif ($ticket) { $_SESSION['AUTHENTICATE_BY_CAS'] = 1; $_SESSION['AUTHENTICATE_BY_CAS_CLIENT_MOD_TICKET_PENDDING'] = 1; } elseif ($logged && $pgtIou) { $_SESSION['AUTHENTICATE_BY_CAS'] = 2; } else { $_SESSION['AUTHENTICATE_BY_CAS'] = 0; } if ($_SESSION['AUTHENTICATE_BY_CAS'] < 1) { if ($clientModeTicketPendding) { unset($_SESSION['AUTHENTICATE_BY_CAS_CLIENT_MOD_TICKET_PENDDING']); } else { return false; } } } /** * Depend on phpCAS mode configuration */ switch ($this->cas_mode) { case PHPCAS_MODE_CLIENT: if ($this->checkConfigurationForClientMode()) { AJXP_Logger::info(__FUNCTION__, "Start phpCAS mode Client: ", "sucessfully"); phpCAS::client(CAS_VERSION_2_0, $this->cas_server, $this->cas_port, $this->cas_uri, false); if (!empty($this->cas_certificate_path)) { phpCAS::setCasServerCACert($this->cas_certificate_path); } else { phpCAS::setNoCasServerValidation(); } /** * Debug */ if ($this->cas_debug_mode) { // logfile name by date: $today = getdate(); $file_path = AJXP_DATA_PATH . '/logs/phpcas_' . $today['year'] . '-' . $today['month'] . '-' . $today['mday'] . '.txt'; empty($this->cas_debug_file) ? $file_path : ($file_path = $this->cas_debug_file); phpCAS::setDebug($file_path); } phpCAS::forceAuthentication(); } else { AJXP_Logger::error(__FUNCTION__, "Could not start phpCAS mode CLIENT, please verify the configuration", ""); return false; } break; case PHPCAS_MODE_PROXY: /** * If in login page, user click on login via CAS, the page will be reload with manuallyredirectocas is set. * Or force redirect to cas login page even the force redirect is set in configuration of this module * */ if ($this->checkConfigurationForProxyMode()) { AJXP_Logger::info(__FUNCTION__, "Start phpCAS mode Proxy: ", "sucessfully"); /** * init phpCAS in mode proxy */ phpCAS::proxy(CAS_VERSION_2_0, $this->cas_server, $this->cas_port, $this->cas_uri, false); if (!empty($this->cas_certificate_path)) { phpCAS::setCasServerCACert($this->cas_certificate_path); } else { phpCAS::setNoCasServerValidation(); } /** * Debug */ if ($this->cas_debug_mode) { // logfile name by date: $today = getdate(); $file_path = AJXP_DATA_PATH . '/logs/phpcas_' . $today['year'] . '-' . $today['month'] . '-' . $today['mday'] . '.txt'; empty($this->cas_debug_file) ? $file_path : ($file_path = $this->cas_debug_file); phpCAS::setDebug($file_path); } if (!empty($this->cas_setFixedCallbackURL)) { phpCAS::setFixedCallbackURL($this->cas_setFixedCallbackURL); } // /** * PTG storage */ $this->setPTGStorage(); phpCAS::forceAuthentication(); /** * Get proxy ticket (PT) for SAMBA to authentication at CAS via pam_cas * In fact, we can use any other service. Of course, it should be enabled in CAS * */ $err_code = null; $serviceURL = $this->cas_proxied_service; AJXP_Logger::debug(__FUNCTION__, "Try to get proxy ticket for service: ", $serviceURL); $res = phpCAS::serviceSMB($serviceURL, $err_code); if (!empty($res)) { $_SESSION['PROXYTICKET'] = $res; AJXP_Logger::info(__FUNCTION__, "Get Proxy ticket successfully ", ""); } else { AJXP_Logger::info(__FUNCTION__, "Could not get Proxy ticket. ", ""); } break; } else { AJXP_Logger::error(__FUNCTION__, "Could not start phpCAS mode PROXY, please verify the configuration", ""); return false; } default: return false; break; } AJXP_Logger::debug(__FUNCTION__, "Call phpCAS::getUser() after forceAuthentication ", ""); $cas_user = phpCAS::getUser(); if (!AuthService::userExists($cas_user) && $this->is_AutoCreateUser) { AuthService::createUser($cas_user, openssl_random_pseudo_bytes(20)); } if (AuthService::userExists($cas_user)) { $res = AuthService::logUser($cas_user, "", true); if ($res > 0) { AJXP_Safe::storeCredentials($cas_user, $_SESSION['PROXYTICKET']); $_SESSION['LOGGED_IN_BY_CAS'] = true; if (!empty($this->cas_additional_role)) { $userObj = ConfService::getConfStorageImpl()->createUserObject($cas_user); $roles = $userObj->getRoles(); $cas_RoleID = $this->cas_additional_role; $userObj->addRole(AuthService::getRole($cas_RoleID, true)); AuthService::updateUser($userObj); } return true; } } return false; }
public function detectRemoteUserId($repoObject) { $host = $repoObject->getOption("SFTP_HOST"); $port = $repoObject->getOption("SFTP_PORT"); $credentials = AJXP_Safe::tryLoadingCredentialsFromSources(NULL, $repoObject); $user = $credentials["user"]; $pass = $credentials["password"]; $ssh2 = new Net_SSH2($host, $port); if ($ssh2->login($user, $pass)) { $output = $ssh2->exec('id'); $ssh2->disconnect(); if (trim($output != "")) { $res = sscanf($output, "uid=%i(%s) gid=%i(%s) groups=%i(%s)"); preg_match_all("/(\\w*)=(\\w*)\\((\\w*)\\)/", $output, $matches); if (count($matches[0]) == 3) { $uid = $matches[2][0]; $gid = $matches[2][1]; return array($uid, $gid); } } } unset($ssh2); return array(null, null); }
public function checkPassword($login, $pass, $seed) { if (!defined('SMB4PHP_SMBCLIENT')) { define('SMB4PHP_SMBCLIENT', $this->options["SMBCLIENT"]); } require_once AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/access.smb/smb.php"; $_SESSION["AJXP_SESSION_REMOTE_PASS"] = $pass; $repoId = $this->options["REPOSITORY_ID"]; $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { throw new Exception("Cannot find repository with id " . $repoId); } $path = ""; $basePath = $repoObject->getOption("PATH", true); $basePath = str_replace("AJXP_USER", $login, $basePath); $host = $repoObject->getOption("HOST"); $domain = $repoObject->getOption("DOMAIN", true); $smbPath = $repoObject->getOption("PATH", true); if (!empty($domain)) { $login = $domain . $login; } $strTmp = "{$login}:{$pass}@" . $host . "/" . $basePath . "/"; $strTmp = str_replace("//", "/", $strTmp); $url = "smbclient://" . $strTmp; try { if (!is_dir($url)) { $this->logDebug("SMB Login failure"); $_SESSION["AJXP_SESSION_REMOTE_PASS"] = ''; foreach ($_SESSION as $key => $val) { if (substr($key, -4) === "disk" && substr($key, 0, 4) == "smb_") { unset($_SESSION[$key]); } } return false; } AJXP_Safe::storeCredentials($login, $pass); } catch (Exception $e) { return false; } return true; }
function createSharedRepository($httpVars, $repository, $accessDriver) { // ERRORS // 100 : missing args // 101 : repository label already exists // 102 : user already exists // 103 : current user is not allowed to share // SUCCESS // 200 if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "" || !isset($httpVars["repo_rights"]) || $httpVars["repo_rights"] == "") { return 100; } $loggedUser = AuthService::getLoggedUser(); $actRights = $loggedUser->getSpecificActionsRights($repository->id); if (isset($actRights["share"]) && $actRights["share"] === false) { return 103; } $users = array(); if (isset($httpVars["shared_user"]) && !empty($httpVars["shared_user"])) { $users = array_filter(array_map("trim", explode(",", str_replace("\n", ",", $httpVars["shared_user"]))), array("AuthService", "userExists")); } if (isset($httpVars["new_shared_user"]) && !empty($httpVars["new_shared_user"])) { $newshareduser = AJXP_Utils::decodeSecureMagic($httpVars["new_shared_user"], AJXP_SANITIZE_ALPHANUM); if (!empty($this->pluginConf["SHARED_USERS_TMP_PREFIX"]) && strpos($newshareduser, $this->pluginConf["SHARED_USERS_TMP_PREFIX"]) !== 0) { $newshareduser = $this->pluginConf["SHARED_USERS_TMP_PREFIX"] . $newshareduser; } if (!AuthService::userExists($newshareduser)) { array_push($users, $newshareduser); } else { throw new Exception("User already exists, please choose another name."); } } //$userName = AJXP_Utils::decodeSecureMagic($httpVars["shared_user"], AJXP_SANITIZE_ALPHANUM); $label = AJXP_Utils::decodeSecureMagic($httpVars["repo_label"]); $rights = $httpVars["repo_rights"]; if ($rights != "r" && $rights != "w" && $rights != "rw") { return 100; } if (isset($httpVars["repository_id"])) { $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]); } // CHECK USER & REPO DOES NOT ALREADY EXISTS $repos = ConfService::getRepositoriesList(); foreach ($repos as $obj) { if ($obj->getDisplay() == $label && (!isset($editingRepo) || $editingRepo != $obj)) { return 101; } } $confDriver = ConfService::getConfStorageImpl(); foreach ($users as $userName) { if (AuthService::userExists($userName)) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) { return 102; } } else { if (AuthService::isReservedUserId($userName)) { return 102; } if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") { return 100; } } } // CREATE SHARED OPTIONS $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository); $customData = array(); foreach ($httpVars as $key => $value) { if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") { $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value; } } if (count($customData)) { $options["PLUGINS_DATA"] = $customData; } if (isset($editingRepo)) { $newRepo = $editingRepo; $newRepo->setDisplay($label); $newRepo->options = array_merge($newRepo->options, $options); ConfService::replaceRepository($httpVars["repository_id"], $newRepo); } else { if ($repository->getOption("META_SOURCES")) { $options["META_SOURCES"] = $repository->getOption("META_SOURCES"); foreach ($options["META_SOURCES"] as $index => $data) { if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) { $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString(); } } } $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null); ConfService::addRepository($newRepo); } if (isset($httpVars["original_users"])) { $originalUsers = explode(",", $httpVars["original_users"]); $removeUsers = array_diff($originalUsers, $users); if (count($removeUsers)) { foreach ($removeUsers as $user) { if (AuthService::userExists($user)) { $userObject = $confDriver->createUserObject($user); $userObject->removeRights($newRepo->getUniqueId()); $userObject->save("superuser"); } } } } foreach ($users as $userName) { if (AuthService::userExists($userName)) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); } else { if (ConfService::getAuthDriverImpl()->getOption("TRANSMIT_CLEAR_PASS")) { $pass = $httpVars["shared_pass"]; } else { $pass = md5($httpVars["shared_pass"]); } AuthService::createUser($userName, $pass); $userObject = $confDriver->createUserObject($userName); $userObject->clearRights(); $userObject->setParent($loggedUser->id); } // CREATE USER WITH NEW REPO RIGHTS $userObject->setRight($newRepo->getUniqueId(), $rights); $userObject->setSpecificActionRight($newRepo->getUniqueId(), "share", false); $userObject->save("superuser"); } // METADATA if (!isset($editingRepo) && $this->metaStore != null) { $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $this->metaStore->setMetadata(new AJXP_Node($this->urlBase . $file), "ajxp_shared", array("element" => $newRepo->getUniqueId()), true, AJXP_METADATA_SCOPE_REPOSITORY); } return 200; }
public function makeSharedRepositoryOptions($httpVars, $repository) { $newOptions = array("PATH" => SystemTextEncoding::toStorageEncoding($repository->getOption("PATH")) . AJXP_Utils::decodeSecureMagic($httpVars["file"]), "CREATE" => $repository->getOption("CREATE"), "RECYCLE_BIN" => isset($httpVars["inherit_recycle"]) ? $repository->getOption("RECYCLE_BIN") : "", "DEFAULT_RIGHTS" => "", "DATA_TEMPLATE" => ""); if ($repository->getOption("USE_SESSION_CREDENTIALS") === true) { $newOptions["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString(); } $customData = array(); foreach ($httpVars as $key => $value) { if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") { $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value; } } if (count($customData)) { $newOptions["PLUGINS_DATA"] = $customData; } if ($repository->getOption("META_SOURCES")) { $newOptions["META_SOURCES"] = $repository->getOption("META_SOURCES"); foreach ($newOptions["META_SOURCES"] as $index => &$data) { if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) { $newOptions["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString(); } } AJXP_Controller::applyHook("workspace.share_metasources", array(&$newOptions["META_SOURCES"])); } return $newOptions; }
/** * If the auth driver implementatino has a logout redirect URL, clear session and return it. * @static * @param bool $logUserOut * @return bool */ static function getLogoutAddress($logUserOut = true) { $authDriver = ConfService::getAuthDriverImpl(); $logout = $authDriver->getLogoutRedirect(); if ($logUserOut && isset($_SESSION["AJXP_USER"])) { AJXP_Logger::logAction("Log Out"); unset($_SESSION["AJXP_USER"]); if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { AJXP_Safe::clearCredentials(); } } return $logout; }
protected function _performAuthentication($data, $method = "BASIC") { if (!AuthService::userExists($data->username)) { AJXP_Logger::debug("not exists! " . $data->username); return false; } $confDriver = ConfService::getConfStorageImpl(); $user = $confDriver->createUserObject($data->username); $webdavData = $user->getPref("AJXP_WEBDAV_DATA"); if (empty($webdavData) || !isset($webdavData["ACTIVE"]) || $webdavData["ACTIVE"] !== true || !isset($webdavData["PASS"])) { return false; } //$webdavData = array("PASS" => $this->_encodePassword("admin", "admin")); $passCheck = false; if ($method == "BASIC") { if ($this->_decodePassword($webdavData["PASS"], $data->username) == $data->password) { $passCheck = true; } } else { if ($method == "DIGEST") { $passCheck = $this->checkDigest($data, $this->_decodePassword($webdavData["PASS"], $data->username)); } } if ($passCheck) { AuthService::logUser($data->username, null, true); $res = $this->updateCurrentUserRights(AuthService::getLoggedUser()); if ($res === false) { return false; } if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { AJXP_Safe::storeCredentials($data->username, $this->_decodePassword($webdavData["PASS"], $data->username)); } return true; } else { return false; } }
/** * Will try to get the credentials for a given repository as follow : * + Try to get the credentials from the url parsing * + Try to get them from the user "Wallet" (personal data) * + Try to get them from the repository configuration * + Try to get them from the AJXP_Safe. * * @param array $parsedUrl * @param Repository $repository * @return array */ public static function tryLoadingCredentialsFromSources($parsedUrl, $repository) { $user = $password = ""; $optionsPrefix = ""; if ($repository->getAccessType() == "ftp") { $optionsPrefix = "FTP_"; } // Get USER/PASS // 1. Try from URL if (isset($parsedUrl["user"]) && isset($parsedUrl["pass"])) { $user = rawurldecode($parsedUrl["user"]); $password = rawurldecode($parsedUrl["pass"]); } // 2. Try from user wallet if ($user == "") { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { $wallet = $loggedUser->getPref("AJXP_WALLET"); if (is_array($wallet) && isset($wallet[$repository->getId()][$optionsPrefix . "USER"])) { $user = $wallet[$repository->getId()][$optionsPrefix . "USER"]; $password = $loggedUser->decodeUserPassword($wallet[$repository->getId()][$optionsPrefix . "PASS"]); } } } // 2bis. Wallet is now a custom parameter if ($user == "") { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { $u = $loggedUser->mergedRole->filterParameterValue("access." . $repository->getAccessType(), $optionsPrefix . "USER", $repository->getId(), ""); $p = $loggedUser->mergedRole->filterParameterValue("access." . $repository->getAccessType(), $optionsPrefix . "PASS", $repository->getId(), ""); if (!empty($u) && !empty($p)) { $user = $u; $password = $loggedUser->decodeUserPassword($p); } } } // 3. Try from repository config if ($user == "") { $user = $repository->getOption($optionsPrefix . "USER"); $password = $repository->getOption($optionsPrefix . "PASS"); } // 4. Test if there are encoded credentials available if ($user == "" && $repository->getOption("ENCODED_CREDENTIALS") != "") { list($user, $password) = AJXP_Safe::getCredentialsFromEncodedString($repository->getOption("ENCODED_CREDENTIALS")); } // 5. Try from session $storeCreds = false; if ($repository->getOption("META_SOURCES")) { $options["META_SOURCES"] = $repository->getOption("META_SOURCES"); foreach ($options["META_SOURCES"] as $metaSource) { if (isset($metaSource["USE_SESSION_CREDENTIALS"]) && $metaSource["USE_SESSION_CREDENTIALS"] === true) { $storeCreds = true; break; } } } if ($user == "" && ($repository->getOption("USE_SESSION_CREDENTIALS") || $storeCreds || self::getInstance()->forceSessionCredentials)) { $safeCred = AJXP_Safe::loadCredentials(); if ($safeCred !== false) { $user = $safeCred["user"]; $password = $safeCred["password"]; } } return array("user" => $user, "password" => $password); }
public static function getSshConnection($path, $repoObject = null) { if ($repoObject != null) { $url = array(); } else { $url = AJXP_Utils::safeParseUrl($path); $repoId = $url["host"]; $repoObject = ConfService::getRepositoryById($repoId); } $remote_serv = $repoObject->getOption("SERV"); $remote_port = $repoObject->getOption("PORT"); $credentials = AJXP_Safe::tryLoadingCredentialsFromSources($url, $repoObject); $remote_user = $credentials["user"]; $remote_pass = $credentials["password"]; $remote_base_path = $repoObject->getOption("PATH"); $callbacks = array('disconnect' => "disconnectedSftp", 'ignore' => "ignoreSftp", 'debug' => "debugSftp", 'macerror' => "macerrorSftp"); $connection = ssh2_connect($remote_serv, intval($remote_port), array(), $callbacks); ssh2_auth_password($connection, $remote_user, $remote_pass); return array($connection, $remote_base_path); }
protected function apiCall($method, $endpoint, $data = null) { //I think this is prettier. $method = strtoupper($method); //Get our token. If we have one. $token = AJXP_Safe::loadCredentials(); $query = ''; if ($token) { $query = '?private_token=' . $token['password']; } //Prepare the CURL call. $handle = curl_init(); $options = array(CURLOPT_TIMEOUT => 2, CURLOPT_CONNECTTIMEOUT => 1, CURLOPT_FOLLOWLOCATION => false, CURLOPT_MAXREDIRS => 0, CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => 'Pydio GitLab Auth Driver v1', CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_URL => $this->url . $this->path . $endpoint . $query); switch ($method) { case 'GET': break; case 'POST': $options[CURLOPT_CUSTOMREQUEST] = $method; $dataString = json_encode($data); $options[CURLOPT_POSTFIELDS] = $dataString; $options[CURLOPT_HTTPHEADER] = array('Content-Type: application/json; charset=UTF-8', 'Content-Length: ' . strlen($dataString)); break; default: throw new Exception("Unknown API method '" . $method . "'."); } curl_setopt_array($handle, $options); //Perform the post. $user_data = curl_exec($handle); $error = curl_error($handle); $status = curl_getinfo($handle, CURLINFO_HTTP_CODE); //Done with CURL now. curl_close($handle); return (object) array('body' => json_decode($user_data), 'status' => $status, 'error' => $error); }
/** * @param array $data * @param AbstractAccessDriver $accessDriver * @param Repository $repository */ public function storeSafeCredentialsIfNeeded(&$data, $accessDriver, $repository) { $storeCreds = false; if ($repository->getOption("META_SOURCES")) { $options["META_SOURCES"] = $repository->getOption("META_SOURCES"); foreach ($options["META_SOURCES"] as $metaSource) { if (isset($metaSource["USE_SESSION_CREDENTIALS"]) && $metaSource["USE_SESSION_CREDENTIALS"] === true) { $storeCreds = true; break; } } } if ($storeCreds || $accessDriver->hasMixin("credentials_consumer")) { $cred = AJXP_Safe::tryLoadingCredentialsFromSources(array(), $repository); if (isset($cred["user"]) && isset($cred["password"])) { $data["SAFE_USER"] = $cred["user"]; $data["SAFE_PASS"] = $cred["password"]; } } }
} $optUser = $options["u"]; if (!empty($optUser)) { if (isset($options["p"])) { $optPass = $options["p"]; } else { // Consider "u" is a crypted version of u:p $optToken = $options["t"]; $cKey = ConfService::getCoreConf("AJXP_CLI_SECRET_KEY", "conf"); if (empty($cKey)) { $cKey = "CDAFx¨op#"; } $optUser = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($optToken . $cKey), base64_decode($optUser), MCRYPT_MODE_ECB), ""); $env = getenv("AJXP_SAFE_CREDENTIALS"); if (!empty($env)) { $array = AJXP_Safe::getCredentialsFromEncodedString($env); if (isset($array["user"]) && $array["user"] == $optUser) { unset($optToken); $optPass = $array["password"]; } } } if (strpos($optUser, ",") !== false) { $originalOptUser = $optUser; $nextUsers = explode(",", $optUser); $optUser = array_shift($nextUsers); $nextUsers = implode(",", $nextUsers); } else { if (strpos($optUser, "queue:") === 0) { $optUserQueue = substr($optUser, strlen("queue:")); $optUser = false;
/** * @param Array $httpVars * @param Repository $repository * @param AbstractAccessDriver $accessDriver * @param null $uniqueUser * @throws Exception * @return int|Repository */ public function createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser = null) { // ERRORS // 100 : missing args // 101 : repository label already exists // 102 : user already exists // 103 : current user is not allowed to share // SUCCESS // 200 if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") { return 100; } /* // FILE IS ALWAYS THE PARENT FOLDER SO WE NOW CHECK FOLDER_SHARING AT A HIGHER LEVEL $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $foldersharing = $this->getFilteredOption("ENABLE_FOLDER_SHARING", $this->repository->getId()); $foldersharingDisabled = isset($foldersharing) && ($foldersharing === false || (is_string($foldersharing) && $foldersharing == "disable")); if (is_dir($this->urlBase.$file) && $foldersharingDisabled) { return 103; } */ $loggedUser = AuthService::getLoggedUser(); $actRights = $loggedUser->mergedRole->listActionsStatesFor($repository); if (isset($actRights["share"]) && $actRights["share"] === false) { return 103; } $users = array(); $uRights = array(); $uPasses = array(); $groups = array(); $uWatches = array(); $index = 0; $prefix = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId()); while (isset($httpVars["user_" . $index])) { $eType = $httpVars["entry_type_" . $index]; $uWatch = false; $rightString = ($httpVars["right_read_" . $index] == "true" ? "r" : "") . ($httpVars["right_write_" . $index] == "true" ? "w" : ""); if ($this->watcher !== false) { $uWatch = $httpVars["right_watch_" . $index] == "true" ? true : false; } if (empty($rightString)) { $index++; continue; } if ($eType == "user") { $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index], AJXP_SANITIZE_EMAILCHARS); if (!AuthService::userExists($u) && !isset($httpVars["user_pass_" . $index])) { $index++; continue; } else { if (AuthService::userExists($u, "w") && isset($httpVars["user_pass_" . $index])) { throw new Exception("User {$u} already exists, please choose another name."); } } if (!AuthService::userExists($u, "r") && !empty($prefix) && strpos($u, $prefix) !== 0) { $u = $prefix . $u; } $users[] = $u; } else { $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index]); if (strpos($u, "/AJXP_TEAM/") === 0) { $confDriver = ConfService::getConfStorageImpl(); if (method_exists($confDriver, "teamIdToUsers")) { $teamUsers = $confDriver->teamIdToUsers(str_replace("/AJXP_TEAM/", "", $u)); foreach ($teamUsers as $userId) { $users[] = $userId; $uRights[$userId] = $rightString; if ($this->watcher !== false) { $uWatches[$userId] = $uWatch; } } } $index++; continue; } else { $groups[] = $u; } } $uRights[$u] = $rightString; $uPasses[$u] = isset($httpVars["user_pass_" . $index]) ? $httpVars["user_pass_" . $index] : ""; if ($this->watcher !== false) { $uWatches[$u] = $uWatch; } $index++; } $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); if (isset($httpVars["repository_id"])) { $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]); } // CHECK USER & REPO DOES NOT ALREADY EXISTS if ($this->getFilteredOption("AVOID_SHARED_FOLDER_SAME_LABEL", $this->repository->getId()) == true) { $count = 0; $similarLabelRepos = ConfService::listRepositoriesWithCriteria(array("display" => $label), $count); if ($count && !isset($editingRepo)) { return 101; } if ($count && isset($editingRepo)) { foreach ($similarLabelRepos as $slr) { if ($slr->getUniqueId() != $editingRepo->getUniqueId()) { return 101; } } } /* $repos = ConfService::getRepositoriesList(); foreach ($repos as $obj) { if ($obj->getDisplay() == $label && (!isSet($editingRepo) || $editingRepo != $obj)) { } } */ } $confDriver = ConfService::getConfStorageImpl(); foreach ($users as $userName) { if (AuthService::userExists($userName)) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) { return 102; } } else { if ($httpVars["create_guest_user"] != "true" && !ConfService::getCoreConf("USER_CREATE_USERS", "conf") || AuthService::isReservedUserId($userName)) { return 102; } if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") { return 100; } } } // CREATE SHARED OPTIONS $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository); $customData = array(); foreach ($httpVars as $key => $value) { if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") { $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value; } } if (count($customData)) { $options["PLUGINS_DATA"] = $customData; } if (isset($editingRepo)) { $this->getShareStore()->testUserCanEditShare($editingRepo->getOwner()); $newRepo = $editingRepo; $replace = false; if ($editingRepo->getDisplay() != $label) { $newRepo->setDisplay($label); $replace = true; } if ($editingRepo->getDescription() != $description) { $newRepo->setDescription($description); $replace = true; } if ($replace) { ConfService::replaceRepository($httpVars["repository_id"], $newRepo); } } else { if ($repository->getOption("META_SOURCES")) { $options["META_SOURCES"] = $repository->getOption("META_SOURCES"); foreach ($options["META_SOURCES"] as $index => &$data) { if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) { $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString(); } if ($index == "meta.syncable" && (!isset($data["REPO_SYNCABLE"]) || $data["REPO_SYNCABLE"] === true)) { $data["REQUIRES_INDEXATION"] = true; } } } $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) { $newRepo->setGroupPath($gPath); } $newRepo->setDescription($description); $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]); if (isset($httpVars["filter_nodes"])) { $newRepo->setContentFilter(new ContentFilter($httpVars["filter_nodes"])); } ConfService::addRepository($newRepo); if (!isset($httpVars["minisite"])) { $this->getShareStore()->storeShare($repository->getId(), array("REPOSITORY" => $newRepo->getUniqueId(), "OWNER_ID" => $loggedUser->getId()), "repository"); } } $sel = new UserSelection($this->repository, $httpVars); $file = $sel->getUniqueFile(); $newRepoUniqueId = $newRepo->getUniqueId(); if (isset($editingRepo)) { $currentRights = $this->computeSharedRepositoryAccessRights($httpVars["repository_id"], false, $this->urlBase . $file); $originalUsers = array_keys($currentRights["USERS"]); $removeUsers = array_diff($originalUsers, $users); if (count($removeUsers)) { foreach ($removeUsers as $user) { if (AuthService::userExists($user)) { $userObject = $confDriver->createUserObject($user); $userObject->personalRole->setAcl($newRepoUniqueId, ""); $userObject->save("superuser"); } if ($this->watcher !== false) { $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $user, true); } } } $originalGroups = array_keys($currentRights["GROUPS"]); $removeGroups = array_diff($originalGroups, $groups); if (count($removeGroups)) { foreach ($removeGroups as $groupId) { $role = AuthService::getRole($groupId); if ($role !== false) { $role->setAcl($newRepoUniqueId, ""); AuthService::updateRole($role); } } } } foreach ($users as $userName) { if (AuthService::userExists($userName, "r")) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); } else { if (ConfService::getAuthDriverImpl()->getOptionAsBool("TRANSMIT_CLEAR_PASS")) { $pass = $uPasses[$userName]; } else { $pass = md5($uPasses[$userName]); } if (!isset($httpVars["minisite"])) { // This is an explicit user creation - check possible limits AJXP_Controller::applyHook("user.before_create", array($userName, null, false, false)); $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, ""); if (!empty($limit) && intval($limit) > 0) { $count = count(ConfService::getConfStorageImpl()->getUserChildren($loggedUser->getId())); if ($count >= $limit) { $mess = ConfService::getMessages(); throw new Exception($mess['483']); } } } AuthService::createUser($userName, $pass, false, isset($httpVars["minisite"])); $userObject = $confDriver->createUserObject($userName); $userObject->personalRole->clearAcls(); $userObject->setParent($loggedUser->id); $userObject->setGroupPath($loggedUser->getGroupPath()); $userObject->setProfile("shared"); if (isset($httpVars["minisite"])) { $mess = ConfService::getMessages(); $userObject->setHidden(true); $userObject->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", "[" . $mess["share_center.109"] . "] " . AJXP_Utils::sanitize($newRepo->getDisplay(), AJXP_SANITIZE_EMAILCHARS)); } AJXP_Controller::applyHook("user.after_create", array($userObject)); } // CREATE USER WITH NEW REPO RIGHTS $userObject->personalRole->setAcl($newRepoUniqueId, $uRights[$userName]); // FORK MASK IF THERE IS ANY if ($file != "/" && $loggedUser->mergedRole->hasMask($repository->getId())) { $parentTree = $loggedUser->mergedRole->getMask($repository->getId())->getTree(); // Try to find a branch on the current selection $parts = explode("/", trim($file, "/")); while (($next = array_shift($parts)) !== null) { if (isset($parentTree[$next])) { $parentTree = $parentTree[$next]; } else { $parentTree = null; break; } } if ($parentTree != null) { $newMask = new AJXP_PermissionMask(); $newMask->updateTree($parentTree); } if (isset($newMask)) { $userObject->personalRole->setMask($newRepoUniqueId, $newMask); } } if (isset($httpVars["minisite"])) { if (isset($editingRepo)) { try { AuthService::deleteRole("AJXP_SHARED-" . $newRepoUniqueId); } catch (Exception $e) { } } $newRole = new AJXP_Role("AJXP_SHARED-" . $newRepoUniqueId); $r = AuthService::getRole("MINISITE"); if (is_a($r, "AJXP_Role")) { if ($httpVars["disable_download"]) { $f = AuthService::getRole("MINISITE_NODOWNLOAD"); if (is_a($f, "AJXP_Role")) { $r = $f->override($r); } } $allData = $r->getDataArray(); $newData = $newRole->getDataArray(); if (isset($allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED])) { $newData["ACTIONS"][$newRepoUniqueId] = $allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED]; } if (isset($allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED])) { $newData["PARAMETERS"][$newRepoUniqueId] = $allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED]; } $newRole->bunchUpdate($newData); AuthService::updateRole($newRole); $userObject->addRole($newRole); } } $userObject->save("superuser"); if ($this->watcher !== false) { // Register a watch on the current folder for shared user if ($uWatches[$userName]) { $this->watcher->setWatchOnFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), $userName, MetaWatchRegister::$META_WATCH_USERS_CHANGE, array(AuthService::getLoggedUser()->getId())); } else { $this->watcher->removeWatchFromFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), $userName, true); } } } if ($this->watcher !== false) { // Register a watch on the new repository root for current user if ($httpVars["self_watch_folder"] == "true") { $this->watcher->setWatchOnFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH); } else { $this->watcher->removeWatchFromFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), AuthService::getLoggedUser()->getId()); } } foreach ($groups as $group) { $r = $uRights[$group]; /*if($group == "AJXP_GRP_/") { $group = "ROOT_ROLE"; }*/ $grRole = AuthService::getRole($group, true); $grRole->setAcl($newRepoUniqueId, $r); AuthService::updateRole($grRole); } if (array_key_exists("minisite", $httpVars) && $httpVars["minisite"] != true) { AJXP_Controller::applyHook(isset($editingRepo) ? "node.share.update" : "node.share.create", array('type' => 'repository', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'new_repository' => &$newRepo)); } return $newRepo; }
/** * @param Array $httpVars * @param Repository $repository * @param AbstractAccessDriver $accessDriver * @param null $uniqueUser * @throws Exception * @return int|Repository */ public function createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser = null) { // ERRORS // 100 : missing args // 101 : repository label already exists // 102 : user already exists // 103 : current user is not allowed to share // SUCCESS // 200 if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") { return 100; } $foldersharing = $this->getFilteredOption("ENABLE_FOLDER_SHARING", $this->repository->getId()); if (isset($foldersharing) && $foldersharing === false) { return 103; } $loggedUser = AuthService::getLoggedUser(); $actRights = $loggedUser->mergedRole->listActionsStatesFor($repository); if (isset($actRights["share"]) && $actRights["share"] === false) { return 103; } $users = array(); $uRights = array(); $uPasses = array(); $groups = array(); $index = 0; $prefix = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId()); while (isset($httpVars["user_" . $index])) { $eType = $httpVars["entry_type_" . $index]; $rightString = ($httpVars["right_read_" . $index] == "true" ? "r" : "") . ($httpVars["right_write_" . $index] == "true" ? "w" : ""); if ($this->watcher !== false) { $uWatch = $httpVars["right_watch_" . $index] == "true" ? true : false; } if (empty($rightString)) { $index++; continue; } if ($eType == "user") { $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index], AJXP_SANITIZE_EMAILCHARS); if (!AuthService::userExists($u) && !isset($httpVars["user_pass_" . $index])) { $index++; continue; } else { if (AuthService::userExists($u) && isset($httpVars["user_pass_" . $index])) { throw new Exception("User {$u} already exists, please choose another name."); } } if (!AuthService::userExists($u, "r") && !empty($prefix) && strpos($u, $prefix) !== 0) { $u = $prefix . $u; } $users[] = $u; } else { $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index]); if (strpos($u, "/AJXP_TEAM/") === 0) { $confDriver = ConfService::getConfStorageImpl(); if (method_exists($confDriver, "teamIdToUsers")) { $teamUsers = $confDriver->teamIdToUsers(str_replace("/AJXP_TEAM/", "", $u)); foreach ($teamUsers as $userId) { $users[] = $userId; $uRights[$userId] = $rightString; if ($this->watcher !== false) { $uWatches[$userId] = $uWatch; } } } $index++; continue; } else { $groups[] = $u; } } $uRights[$u] = $rightString; $uPasses[$u] = isset($httpVars["user_pass_" . $index]) ? $httpVars["user_pass_" . $index] : ""; if ($this->watcher !== false) { $uWatches[$u] = $uWatch; } $index++; } $label = AJXP_Utils::decodeSecureMagic($httpVars["repo_label"]); $description = AJXP_Utils::decodeSecureMagic($httpVars["repo_description"]); if (isset($httpVars["repository_id"])) { $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]); } // CHECK USER & REPO DOES NOT ALREADY EXISTS if ($this->getFilteredOption("AVOID_SHARED_FOLDER_SAME_LABEL", $this->repository->getId()) == true) { $repos = ConfService::getRepositoriesList(); foreach ($repos as $obj) { if ($obj->getDisplay() == $label && (!isset($editingRepo) || $editingRepo != $obj)) { return 101; } } } $confDriver = ConfService::getConfStorageImpl(); foreach ($users as $userName) { if (AuthService::userExists($userName)) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) { return 102; } } else { if ($httpVars["create_guest_user"] != "true" && !ConfService::getCoreConf("USER_CREATE_USERS", "conf") || AuthService::isReservedUserId($userName)) { return 102; } if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") { return 100; } } } // CREATE SHARED OPTIONS $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository); $customData = array(); foreach ($httpVars as $key => $value) { if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") { $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value; } } if (count($customData)) { $options["PLUGINS_DATA"] = $customData; } if (isset($editingRepo)) { $newRepo = $editingRepo; if ($editingRepo->getDisplay() != $label) { $newRepo->setDisplay($label); ConfService::replaceRepository($httpVars["repository_id"], $newRepo); } $editingRepo->setDescription($description); } else { if ($repository->getOption("META_SOURCES")) { $options["META_SOURCES"] = $repository->getOption("META_SOURCES"); foreach ($options["META_SOURCES"] as $index => $data) { if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) { $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString(); } } } $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) { $newRepo->setGroupPath($gPath); } $newRepo->setDescription($description); ConfService::addRepository($newRepo); } $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (isset($editingRepo)) { $currentRights = $this->computeSharedRepositoryAccessRights($httpVars["repository_id"], false, $this->urlBase . $file); $originalUsers = array_keys($currentRights["USERS"]); $removeUsers = array_diff($originalUsers, $users); if (count($removeUsers)) { foreach ($removeUsers as $user) { if (AuthService::userExists($user)) { $userObject = $confDriver->createUserObject($user); $userObject->personalRole->setAcl($newRepo->getUniqueId(), ""); $userObject->save("superuser"); } } } $originalGroups = array_keys($currentRights["GROUPS"]); $removeGroups = array_diff($originalGroups, $groups); if (count($removeGroups)) { foreach ($removeGroups as $groupId) { $role = AuthService::getRole("AJXP_GRP_" . AuthService::filterBaseGroup($groupId)); if ($role !== false) { $role->setAcl($newRepo->getUniqueId(), ""); AuthService::updateRole($role); } } } } foreach ($users as $userName) { if (AuthService::userExists($userName, "r")) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); } else { if (ConfService::getAuthDriverImpl()->getOption("TRANSMIT_CLEAR_PASS")) { $pass = $uPasses[$userName]; } else { $pass = md5($uPasses[$userName]); } $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, ""); if (!empty($limit) && intval($limit) > 0) { $count = count(ConfService::getConfStorageImpl()->getUserChildren($loggedUser->getId())); if ($count >= $limit) { $mess = ConfService::getMessages(); throw new Exception($mess['483']); } } AuthService::createUser($userName, $pass); $userObject = $confDriver->createUserObject($userName); $userObject->personalRole->clearAcls(); $userObject->setParent($loggedUser->id); $userObject->setGroupPath($loggedUser->getGroupPath()); $userObject->setProfile("shared"); if (isset($httpVars["minisite"])) { $mess = ConfService::getMessages(); $userObject->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", "[" . $mess["share_center.109"] . "] " . $newRepo->getDisplay()); } AJXP_Controller::applyHook("user.after_create", array($userObject)); } // CREATE USER WITH NEW REPO RIGHTS $userObject->personalRole->setAcl($newRepo->getUniqueId(), $uRights[$userName]); if (isset($httpVars["minisite"])) { $newRole = new AJXP_Role("AJXP_SHARED-" . $newRepo->getUniqueId()); $r = AuthService::getRole("MINISITE"); if (is_a($r, "AJXP_Role")) { if ($httpVars["disable_download"]) { $f = AuthService::getRole("MINISITE_NODOWNLOAD"); if (is_a($f, "AJXP_Role")) { $r = $f->override($r); } } $allData = $r->getDataArray(); $newData = $newRole->getDataArray(); if (isset($allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED])) { $newData["ACTIONS"][$newRepo->getUniqueId()] = $allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED]; } if (isset($allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED])) { $newData["PARAMETERS"][$newRepo->getUniqueId()] = $allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED]; } $newRole->bunchUpdate($newData); AuthService::updateRole($newRole); $userObject->addRole($newRole); } } $userObject->save("superuser"); if ($this->watcher !== false) { // Register a watch on the current folder for shared user if ($uWatches[$userName] == "true") { $this->watcher->setWatchOnFolder(new AJXP_Node($this->urlBase . $file), $userName, MetaWatchRegister::$META_WATCH_USERS_CHANGE, array(AuthService::getLoggedUser()->getId())); } else { $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $userName, true); } } } if ($this->watcher !== false) { // Register a watch on the new repository root for current user if ($httpVars["self_watch_folder"] == "true") { $this->watcher->setWatchOnFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH); } else { $this->watcher->removeWatchFromFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId()); } } foreach ($groups as $group) { $grRole = AuthService::getRole("AJXP_GRP_" . AuthService::filterBaseGroup($group), true); $grRole->setAcl($newRepo->getUniqueId(), $uRights[$group]); AuthService::updateRole($grRole); } if (array_key_exists("minisite", $httpVars) && $httpVars["minisite"] != true) { AJXP_Controller::applyHook("node.share.create", array('type' => 'repository', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'new_repository' => &$newRepo)); } return $newRepo; }
public function authenticate(Sabre\DAV\Server $server, $realm) { $auth = new Sabre\HTTP\BasicAuth(); $auth->setHTTPRequest($server->httpRequest); $auth->setHTTPResponse($server->httpResponse); $auth->setRealm($realm); $userpass = $auth->getUserPass(); if (!$userpass) { $auth->requireLogin(); throw new Sabre\DAV\Exception\NotAuthenticated('No basic authentication headers were found'); } // Authenticates the user //AJXP_Logger::info(__CLASS__,"authenticate",$userpass[0]); $confDriver = ConfService::getConfStorageImpl(); $userObject = $confDriver->createUserObject($userpass[0]); $webdavData = $userObject->getPref("AJXP_WEBDAV_DATA"); if (empty($webdavData) || !isset($webdavData["ACTIVE"]) || $webdavData["ACTIVE"] !== true) { AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => $userpass[0], "error" => "WebDAV user not found or disabled")); throw new Sabre\DAV\Exception\NotAuthenticated(); } // check if there are cached credentials. prevents excessive authentication calls to external // auth mechanism. $cachedPasswordValid = 0; $secret = defined("AJXP_SECRET_KEY") ? AJXP_SECRET_KEY : "CDAFx¨op#"; $encryptedPass = md5($userpass[1] . $secret . date('YmdHi')); if (isset($webdavData["TMP_PASS"]) && $encryptedPass == $webdavData["TMP_PASS"]) { $cachedPasswordValid = true; //AJXP_Logger::debug("Using Cached Password"); } if (!$cachedPasswordValid && !$this->validateUserPass($userpass[0], $userpass[1])) { AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => $userpass[0], "error" => "Invalid WebDAV user or password")); $auth->requireLogin(); throw new Sabre\DAV\Exception\NotAuthenticated('Username or password does not match'); } $this->currentUser = $userpass[0]; $res = AuthService::logUser($this->currentUser, $userpass[1], true); if ($res < 1) { throw new Sabre\DAV\Exception\NotAuthenticated(); } $this->updateCurrentUserRights(AuthService::getLoggedUser()); if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { AJXP_Safe::storeCredentials($this->currentUser, $userpass[1]); } if (isset($this->repositoryId) && ConfService::getRepositoryById($this->repositoryId)->getOption("AJXP_WEBDAV_DISABLED") === true) { throw new Sabre\DAV\Exception\NotAuthenticated('You are not allowed to access this workspace'); } ConfService::switchRootDir($this->repositoryId); // the method used here will invalidate the cached password every minute on the minute if (!$cachedPasswordValid) { $webdavData["TMP_PASS"] = $encryptedPass; $userObject->setPref("AJXP_WEBDAV_DATA", $webdavData); $userObject->save("user"); AuthService::updateUser($userObject); } return true; }
/** * @param array $data * @param array $options * @param ShareStore $shareStore */ public static function render($data, $options, $shareStore) { if (isset($data["SECURITY_MODIFIED"]) && $data["SECURITY_MODIFIED"] === true) { self::renderError($data, "false"); return; } // create driver from $data $className = $data["DRIVER"] . "AccessDriver"; $u = parse_url($_SERVER["REQUEST_URI"]); $shortHash = pathinfo(basename($u["path"]), PATHINFO_FILENAME); // Load language messages $language = ConfService::getLanguage(); if (isset($_GET["lang"])) { $language = basename($_GET["lang"]); } $messages = array(); if (is_file(dirname(__FILE__) . "/res/i18n/" . $language . ".php")) { include dirname(__FILE__) . "/res/i18n/" . $language . ".php"; } else { include dirname(__FILE__) . "/res/i18n/en.php"; } if (isset($mess)) { $messages = $mess; } $AJXP_LINK_HAS_PASSWORD = false; $AJXP_LINK_BASENAME = SystemTextEncoding::toUTF8(basename($data["FILE_PATH"])); AJXP_PluginsService::getInstance()->initActivePlugins(); ConfService::setLanguage($language); $mess = ConfService::getMessages(); if ($shareStore->isShareExpired($shortHash, $data)) { self::renderError(array(), $shortHash, $mess["share_center.165"]); return; } $customs = array("title", "legend", "legend_pass", "background_attributes_1", "text_color", "background_color", "textshadow_color"); $images = array("button", "background_1"); $confs = $options; $confs["CUSTOM_SHAREPAGE_BACKGROUND_ATTRIBUTES_1"] = "background-repeat:repeat;background-position:50% 50%;"; $confs["CUSTOM_SHAREPAGE_BACKGROUND_1"] = "plugins/action.share/res/hi-res/02.jpg"; $confs["CUSTOM_SHAREPAGE_TEXT_COLOR"] = "#ffffff"; $confs["CUSTOM_SHAREPAGE_TEXTSHADOW_COLOR"] = "rgba(0,0,0,5)"; foreach ($customs as $custom) { $varName = "CUSTOM_SHAREPAGE_" . strtoupper($custom); ${$varName} = $confs[$varName]; } $dlFolder = realpath(ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER")); foreach ($images as $custom) { $varName = "CUSTOM_SHAREPAGE_" . strtoupper($custom); if (!empty($confs[$varName])) { if (strpos($confs[$varName], "plugins/") === 0 && is_file(AJXP_INSTALL_PATH . "/" . $confs[$varName])) { $realFile = AJXP_INSTALL_PATH . "/" . $confs[$varName]; copy($realFile, $dlFolder . "/binary-" . basename($realFile)); ${$varName} = "binary-" . basename($realFile); } else { ${$varName} = "binary-" . $confs[$varName]; if (is_file($dlFolder . "/binary-" . $confs[$varName])) { continue; } $copiedImageName = $dlFolder . "/binary-" . $confs[$varName]; $imgFile = fopen($copiedImageName, "wb"); ConfService::getConfStorageImpl()->loadBinary(array(), $confs[$varName], $imgFile); fclose($imgFile); } } } HTMLWriter::charsetHeader(); // Check password if (strlen($data["PASSWORD"])) { if (!isset($_POST['password']) || $_POST['password'] != $data["PASSWORD"]) { $AJXP_LINK_HAS_PASSWORD = true; $AJXP_LINK_WRONG_PASSWORD = isset($_POST['password']) && $_POST['password'] != $data["PASSWORD"]; include AJXP_INSTALL_PATH . "/plugins/action.share/res/public_links.php"; $res = '<div style="position: absolute;z-index: 10000; bottom: 0; right: 0; color: #666;font-family: HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size: 13px;text-align: right;padding: 6px; line-height: 20px;text-shadow: 0px 1px 0px white;" class="no_select_bg"><br>Build your own box with Pydio : <a style="color: #000000;" target="_blank" href="http://pyd.io/">http://pyd.io/</a><br/>Community - Free non supported version © C. du Jeu 2008-2014 </div>'; AJXP_Controller::applyHook("tpl.filter_html", array(&$res)); echo $res; return; } } else { if (!isset($_GET["dl"])) { include AJXP_INSTALL_PATH . "/plugins/action.share/res/public_links.php"; $res = '<div style="position: absolute;z-index: 10000; bottom: 0; right: 0; color: #666;font-family: HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size: 13px;text-align: right;padding: 6px; line-height: 20px;text-shadow: 0px 1px 0px white;" class="no_select_bg"><br>Build your own box with Pydio : <a style="color: #000000;" target="_blank" href="http://pyd.io/">http://pyd.io/</a><br/>Community - Free non supported version © C. du Jeu 2008-2014 </div>'; AJXP_Controller::applyHook("tpl.filter_html", array(&$res)); echo $res; return; } } $filePath = AJXP_INSTALL_PATH . "/plugins/access." . $data["DRIVER"] . "/class." . $className . ".php"; if (!is_file($filePath)) { die("Warning, cannot find driver for conf storage! ({$className}, {$filePath})"); } require_once $filePath; $driver = new $className($data["PLUGIN_ID"], $data["BASE_DIR"]); $driver->loadManifest(); //$hash = md5(serialize($data)); $shareStore->incrementDownloadCounter($shortHash); //AuthService::logUser($data["OWNER_ID"], "", true); AuthService::logTemporaryUser($data["OWNER_ID"], $shortHash); if (isset($data["SAFE_USER"]) && isset($data["SAFE_PASS"])) { // FORCE SESSION MODE AJXP_Safe::getInstance()->forceSessionCredentialsUsage(); AJXP_Safe::storeCredentials($data["SAFE_USER"], $data["SAFE_PASS"]); } $repoObject = $data["REPOSITORY"]; ConfService::switchRootDir($repoObject->getId()); ConfService::loadRepositoryDriver(); AJXP_PluginsService::getInstance()->initActivePlugins(); try { $params = array("file" => SystemTextEncoding::toUTF8($data["FILE_PATH"])); if (isset($data["PLUGINS_DATA"])) { $params["PLUGINS_DATA"] = $data["PLUGINS_DATA"]; } if (isset($_GET["ct"]) && $_GET["ct"] == "true") { $mime = pathinfo($params["file"], PATHINFO_EXTENSION); $editors = AJXP_PluginsService::searchAllManifests("//editor[contains(@mimes,'{$mime}') and @previewProvider='true']", "node", true, true, false); if (count($editors)) { foreach ($editors as $editor) { $xPath = new DOMXPath($editor->ownerDocument); $callbacks = $xPath->query("//action[@contentTypedProvider]", $editor); if ($callbacks->length) { $data["ACTION"] = $callbacks->item(0)->getAttribute("name"); if ($data["ACTION"] == "audio_proxy") { $params["file"] = base64_encode($params["file"]); } break; } } } } AJXP_Controller::findActionAndApply($data["ACTION"], $params, null); register_shutdown_function(array("AuthService", "clearTemporaryUser"), $shortHash); } catch (Exception $e) { AuthService::clearTemporaryUser($shortHash); die($e->getMessage()); } }
public function makeSharedRepositoryOptions($httpVars, $repository) { $newOptions = array("PATH" => $repository->getOption("PATH") . AJXP_Utils::decodeSecureMagic($httpVars["file"]), "CREATE" => isset($httpVars["inherit_recycle"]) ? $repository->getOption("CREATE") : false, "RECYCLE_BIN" => isset($httpVars["inherit_recycle"]) ? $repository->getOption("RECYCLE_BIN") : "", "DEFAULT_RIGHTS" => ""); if ($repository->getOption("USE_SESSION_CREDENTIALS") === true) { $newOptions["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString(); } return $newOptions; }
public function checkPassword($login, $pass, $seed) { $wrapper = new ftpSonWrapper(); $repoId = $this->options["REPOSITORY_ID"]; try { $wrapper->initUrl("ajxp.ftp://" . rawurlencode($login) . ":" . rawurlencode($pass) . "@{$repoId}/"); AJXP_Safe::storeCredentials($login, $pass); } catch (Exception $e) { return false; } return true; }
/** * Will try to get the credentials for a given repository as follow : * + Try to get the credentials from the url parsing * + Try to get them from the user "Wallet" (personal data) * + Try to get them from the repository configuration * + Try to get them from the AJXP_Safe. * * @param array $parsedUrl * @param Repository $repository * @return array */ public static function tryLoadingCredentialsFromSources($parsedUrl, $repository) { $user = $password = ""; $optionsPrefix = ""; if ($repository->getAccessType() == "ftp") { $optionsPrefix = "FTP_"; } // Get USER/PASS // 1. Try from URL if (isset($parsedUrl["user"]) && isset($parsedUrl["pass"])) { $user = rawurldecode($parsedUrl["user"]); $password = rawurldecode($parsedUrl["pass"]); } // 2. Try from user wallet if ($user == "") { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { $wallet = $loggedUser->getPref("AJXP_WALLET"); if (is_array($wallet) && isset($wallet[$repository->getId()][$optionsPrefix . "USER"])) { $user = $wallet[$repository->getId()][$optionsPrefix . "USER"]; $password = $loggedUser->decodeUserPassword($wallet[$repository->getId()][$optionsPrefix . "PASS"]); } } } // 3. Try from repository config if ($user == "") { $user = $repository->getOption($optionsPrefix . "USER"); $password = $repository->getOption($optionsPrefix . "PASS"); } // 4. Test if there are encoded credentials available if ($user == "" && $repository->getOption("ENCODED_CREDENTIALS") != "") { list($user, $password) = AJXP_Safe::getCredentialsFromEncodedString($repository->getOption("ENCODED_CREDENTIALS")); } // 5. Try from session if ($user == "" && ($repository->getOption("USE_SESSION_CREDENTIALS") || self::getInstance()->forceSessionCredentials)) { $safeCred = AJXP_Safe::loadCredentials(); if ($safeCred !== false) { $user = $safeCred["user"]; $password = $safeCred["password"]; } } return array("user" => $user, "password" => $password); }