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;
 }
 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 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;
 }
 public function checkPassword($login, $password, $seed)
 {
     //Our default value.
     $passwordVerified = false;
     try {
         //Send the request.
         $result = $this->apiCall('POST', 'session', array("login" => $login, "password" => $password));
         //Check the returned status.
         switch ($result->status) {
             //Proper login.
             case 201:
                 //Check the user is not blocked.
                 if ($result->body->state !== 'active') {
                     AJXP_Logger::warning(__CLASS__ . '.checkPassword.201', 'Blocked user attempted login [' . $login . ']', "");
                 } else {
                     $passwordVerified = true;
                     AJXP_Safe::storeCredentials($login, $result->body->private_token);
                     $_SESSION['Auth.GitLab.RemoteAdmin'] = $result->body->is_admin === true;
                 }
                 break;
                 //Proper failure.
             //Proper failure.
             case 401:
                 AJXP_Logger::info(__CLASS__ . '.checkPassword.401', 'Not authorized for login [' . $login . ']', "");
                 break;
                 //We're not sure.
             //We're not sure.
             default:
                 AJXP_Logger::info(__CLASS__ . '.checkPassword.###', 'Unknown status code. ' . var_export($result, true), "");
                 break;
         }
     } catch (Exception $e) {
         AJXP_Logger::error(__CLASS__ . '.checkPassword.ex', $e->getMessage(), "");
     }
     return $passwordVerified;
 }
 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;
 }
 /**
  * @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());
     }
 }
 /**
  * Log the user from its credentials
  * @static
  * @param string $user_id The user id
  * @param string $pwd The password
  * @param bool $bypass_pwd Ignore password or not
  * @param bool $cookieLogin Is it a logging from the remember me cookie?
  * @param string $returnSeed The unique seed
  * @return int
  */
 static function logUser($user_id, $pwd, $bypass_pwd = false, $cookieLogin = false, $returnSeed = "")
 {
     $user_id = self::filterUserSensitivity($user_id);
     if ($cookieLogin && !isset($_COOKIE["AjaXplorer-remember"])) {
         return -5;
         // SILENT IGNORE
     }
     if ($cookieLogin) {
         list($user_id, $pwd) = explode(":", $_COOKIE["AjaXplorer-remember"]);
     }
     $confDriver = ConfService::getConfStorageImpl();
     if ($user_id == null) {
         if (isset($_SESSION["AJXP_USER"]) && is_object($_SESSION["AJXP_USER"])) {
             return 1;
         }
         if (ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
             $authDriver = ConfService::getAuthDriverImpl();
             if (!$authDriver->userExists("guest")) {
                 AuthService::createUser("guest", "");
                 $guest = $confDriver->createUserObject("guest");
                 $guest->save("superuser");
             }
             AuthService::logUser("guest", null);
             return 1;
         }
         return 0;
     }
     $authDriver = ConfService::getAuthDriverImpl();
     // CHECK USER PASSWORD HERE!
     $loginAttempt = AuthService::getBruteForceLoginArray();
     $bruteForceLogin = AuthService::checkBruteForceLogin($loginAttempt);
     AuthService::setBruteForceLoginArray($loginAttempt);
     if (!$authDriver->userExists($user_id)) {
         if ($bruteForceLogin === FALSE) {
             return -4;
         } else {
             return 0;
         }
     }
     if (!$bypass_pwd) {
         if (!AuthService::checkPassword($user_id, $pwd, $cookieLogin, $returnSeed)) {
             if ($bruteForceLogin === FALSE) {
                 return -4;
             } else {
                 if ($cookieLogin) {
                     return -5;
                 }
                 return -1;
             }
         }
     }
     // Successful login attempt
     unset($loginAttempt[$_SERVER["REMOTE_ADDR"]]);
     AuthService::setBruteForceLoginArray($loginAttempt);
     // Setting session credentials if asked in config
     if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) {
         list($authId, $authPwd) = $authDriver->filterCredentials($user_id, $pwd);
         AJXP_Safe::storeCredentials($authId, $authPwd);
     }
     $user = $confDriver->createUserObject($user_id);
     if ($authDriver->isAjxpAdmin($user_id)) {
         $user->setAdmin(true);
     }
     if ($user->isAdmin()) {
         $user = AuthService::updateAdminRights($user);
     } else {
         if (!$user->hasParent() && $user_id != "guest") {
             //$user->setRight("ajxp_shared", "rw");
         }
     }
     $_SESSION["AJXP_USER"] = $user;
     if ($authDriver->autoCreateUser() && !$user->storageExists()) {
         $user->save("superuser");
         // make sure update rights now
     }
     AJXP_Logger::logAction("Log In");
     return 1;
 }
 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;
 }
 /**
  * Log the user from its credentials
  * @static
  * @param string $user_id The user id
  * @param string $pwd The password
  * @param bool $bypass_pwd Ignore password or not
  * @param bool $cookieLogin Is it a logging from the remember me cookie?
  * @param string $returnSeed The unique seed
  * @return int
  */
 public static function logUser($user_id, $pwd, $bypass_pwd = false, $cookieLogin = false, $returnSeed = "")
 {
     $user_id = self::filterUserSensitivity($user_id);
     if ($cookieLogin && !isset($_COOKIE["AjaXplorer-remember"])) {
         return -5;
         // SILENT IGNORE
     }
     if ($cookieLogin) {
         list($user_id, $pwd) = explode(":", $_COOKIE["AjaXplorer-remember"]);
     }
     $confDriver = ConfService::getConfStorageImpl();
     if ($user_id == null) {
         if (self::$useSession) {
             if (isset($_SESSION["AJXP_USER"]) && is_object($_SESSION["AJXP_USER"])) {
                 /**
                  * @var AbstractAjxpUser $u
                  */
                 $u = $_SESSION["AJXP_USER"];
                 if ($u->reloadRolesIfRequired()) {
                     ConfService::getInstance()->invalidateLoadedRepositories();
                     self::$bufferedMessage = AJXP_XMLWriter::reloadRepositoryList(false);
                     $_SESSION["AJXP_USER"] = $u;
                 }
                 return 1;
             }
         } else {
             if (isset(self::$currentUser) && is_object(self::$currentUser)) {
                 return 1;
             }
         }
         if (ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") && !isset($_SESSION["CURRENT_MINISITE"])) {
             $authDriver = ConfService::getAuthDriverImpl();
             if (!$authDriver->userExists("guest")) {
                 self::createUser("guest", "");
                 $guest = $confDriver->createUserObject("guest");
                 $guest->save("superuser");
             }
             self::logUser("guest", null);
             return 1;
         }
         return -1;
     }
     $authDriver = ConfService::getAuthDriverImpl();
     // CHECK USER PASSWORD HERE!
     $loginAttempt = self::getBruteForceLoginArray();
     $bruteForceLogin = self::checkBruteForceLogin($loginAttempt);
     self::setBruteForceLoginArray($loginAttempt);
     if (!$authDriver->userExists($user_id)) {
         AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => AJXP_Utils::sanitize($user_id, AJXP_SANITIZE_EMAILCHARS), "error" => "Invalid user"));
         if ($bruteForceLogin === FALSE) {
             return -4;
         } else {
             return -1;
         }
     }
     if (!$bypass_pwd) {
         if (!self::checkPassword($user_id, $pwd, $cookieLogin, $returnSeed)) {
             AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => AJXP_Utils::sanitize($user_id, AJXP_SANITIZE_EMAILCHARS), "error" => "Invalid password"));
             if ($bruteForceLogin === FALSE) {
                 return -4;
             } else {
                 if ($cookieLogin) {
                     return -5;
                 }
                 return -1;
             }
         }
     }
     // Successful login attempt
     unset($loginAttempt[$_SERVER["REMOTE_ADDR"]]);
     self::setBruteForceLoginArray($loginAttempt);
     // Setting session credentials if asked in config
     if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) {
         list($authId, $authPwd) = $authDriver->filterCredentials($user_id, $pwd);
         AJXP_Safe::storeCredentials($authId, $authPwd);
     }
     $user = $confDriver->createUserObject($user_id);
     if ($user->getLock() == "logout") {
         AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => AJXP_Utils::sanitize($user_id, AJXP_SANITIZE_EMAILCHARS), "error" => "Locked user"));
         return -1;
     }
     if (AuthService::$useSession && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
         ConfService::getInstance()->invalidateLoadedRepositories();
     }
     if ($authDriver->isAjxpAdmin($user_id)) {
         $user->setAdmin(true);
     }
     if (self::$useSession) {
         $_SESSION["AJXP_USER"] = $user;
     } else {
         self::$currentUser = $user;
     }
     if ($user->isAdmin()) {
         $user = self::updateAdminRights($user);
         self::updateUser($user);
     }
     if ($authDriver->autoCreateUser() && !$user->storageExists()) {
         $user->save("superuser");
         // make sure update rights now
     }
     AJXP_Logger::info(__CLASS__, "Log In", array("context" => self::$useSession ? "WebUI" : "API"));
     return 1;
 }
 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;
 }
 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;
 }
 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;
     }
 }
 /**
  * @static
  * @param Array $data
  * @return void
  */
 static function loadPubliclet($data)
 {
     // create driver from $data
     $className = $data["DRIVER"] . "AccessDriver";
     $hash = md5(serialize($data));
     if ($data["EXPIRE_TIME"] && time() > $data["EXPIRE_TIME"] || $data["DOWNLOAD_LIMIT"] && $data["DOWNLOAD_LIMIT"] > 0 && $data["DOWNLOAD_LIMIT"] <= PublicletCounter::getCount($hash)) {
         // Remove the publiclet, it's done
         if (strstr(realpath($_SERVER["SCRIPT_FILENAME"]), realpath(ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"))) !== FALSE) {
             PublicletCounter::delete($hash);
             unlink($_SERVER["SCRIPT_FILENAME"]);
         }
         echo "Link is expired, sorry.";
         exit;
     }
     // Load language messages
     $language = "en";
     if (isset($_GET["lang"])) {
         $language = $_GET["lang"];
     }
     $messages = array();
     if (is_file(dirname(__FILE__) . "/res/i18n/" . $language . ".php")) {
         include dirname(__FILE__) . "/res/i18n/" . $language . ".php";
         $messages = $mess;
     } else {
         include dirname(__FILE__) . "/res/i18n/en.php";
     }
     $AJXP_LINK_HAS_PASSWORD = false;
     $AJXP_LINK_BASENAME = SystemTextEncoding::toUTF8(basename($data["FILE_PATH"]));
     // 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";
             return;
         }
     } else {
         if (!isset($_GET["dl"])) {
             include AJXP_INSTALL_PATH . "/plugins/action.share/res/public_links.php";
             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));
     PublicletCounter::increment($hash);
     AuthService::logUser($data["OWNER_ID"], "", true);
     if ($driver->hasMixin("credentials_consumer") && 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();
     ConfService::initActivePlugins();
     try {
         $params = array("file" => SystemTextEncoding::toUTF8($data["FILE_PATH"]));
         if (isset($data["PLUGINS_DATA"])) {
             $params["PLUGINS_DATA"] = $data["PLUGINS_DATA"];
         }
         AJXP_Controller::findActionAndApply($data["ACTION"], $params, null);
     } catch (Exception $e) {
         die($e->getMessage());
     }
 }