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;
 }
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     if (!isset($httpVars["get_action"]) || $httpVars["get_action"] != "login") {
         return false;
     }
     $rememberLogin = "";
     $rememberPass = "";
     $secureToken = "";
     $loggedUser = null;
     include_once AJXP_BIN_FOLDER . "/class.CaptchaProvider.php";
     if (AuthService::suspectBruteForceLogin() && (!isset($httpVars["captcha_code"]) || !CaptchaProvider::checkCaptchaResult($httpVars["captcha_code"]))) {
         $loggingResult = -4;
     } else {
         $userId = isset($httpVars["userid"]) ? AJXP_Utils::sanitize($httpVars["userid"], AJXP_SANITIZE_EMAILCHARS) : null;
         $userPass = isset($httpVars["password"]) ? trim($httpVars["password"]) : null;
         $rememberMe = isset($httpVars["remember_me"]) && $httpVars["remember_me"] == "true" ? true : false;
         $cookieLogin = isset($httpVars["cookie_login"]) ? true : false;
         $loggingResult = AuthService::logUser($userId, $userPass, false, $cookieLogin, $httpVars["login_seed"]);
         if ($rememberMe && $loggingResult == 1) {
             $rememberLogin = "******";
             $rememberPass = "******";
         }
         if ($loggingResult == 1) {
             session_regenerate_id(true);
             $secureToken = AuthService::generateSecureToken();
         }
         if ($loggingResult < 1 && AuthService::suspectBruteForceLogin()) {
             $loggingResult = -4;
             // Force captcha reload
         }
     }
     $loggedUser = AuthService::getLoggedUser();
     if ($loggedUser != null) {
         $force = $loggedUser->mergedRole->filterParameterValue("core.conf", "DEFAULT_START_REPOSITORY", AJXP_REPO_SCOPE_ALL, -1);
         $passId = -1;
         if (isset($httpVars["tmp_repository_id"])) {
             $passId = $httpVars["tmp_repository_id"];
         } else {
             if ($force != "" && $loggedUser->canSwitchTo($force) && !isset($httpVars["tmp_repository_id"]) && !isset($_SESSION["PENDING_REPOSITORY_ID"])) {
                 $passId = $force;
             }
         }
         $res = ConfService::switchUserToActiveRepository($loggedUser, $passId);
         if (!$res) {
             AuthService::disconnect();
             $loggingResult = -3;
         }
     }
     if ($loggedUser != null && (AuthService::hasRememberCookie() || isset($rememberMe) && $rememberMe == true)) {
         AuthService::refreshRememberCookie($loggedUser);
     }
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::loggingResult($loggingResult, $rememberLogin, $rememberPass, $secureToken);
     AJXP_XMLWriter::close();
     if ($loggingResult > 0 || $isLast) {
         exit;
     }
 }
예제 #3
0
 /**
  * Validates a username and password
  *
  * This method should return true or false depending on if login
  * succeeded.
  *
  * @param string $username
  * @param string $password
  * @return bool
  */
 protected function validateUserPass($username, $password)
 {
     if (isset($this->shareData["PRESET_LOGIN"])) {
         $res = \AuthService::logUser($this->shareData["PRESET_LOGIN"], $password, false, false, -1);
     } else {
         $res = \AuthService::logUser($this->shareData["PRELOG_USER"], "", true);
     }
     return $res === 1;
 }
예제 #4
0
 public function preLogUser($sessionId)
 {
     if ($_GET['get_action'] == "logout") {
         phpCAS::logout();
         return;
     }
     phpCAS::forceAuthentication();
     $cas_user = phpCAS::getUser();
     if (!$this->userExists($cas_user) && $this->autoCreateUser()) {
         $this->createUser($cas_user, openssl_random_pseudo_bytes(20));
     }
     if ($this->userExists($cas_user)) {
         AuthService::logUser($cas_user, "", true);
     }
 }
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     $localHttpLogin = $_SERVER["REMOTE_USER"];
     $localHttpPassw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : "";
     if (!isset($localHttpLogin)) {
         return false;
     }
     if (!AuthService::userExists($localHttpLogin) && $this->pluginConf["CREATE_USER"] === true) {
         AuthService::createUser($localHttpLogin, $localHttpPassw, isset($this->pluginConf["AJXP_ADMIN"]) && $this->pluginConf["AJXP_ADMIN"] == $localHttpLogin);
     }
     $res = AuthService::logUser($localHttpLogin, $localHttpPassw, true);
     if ($res > 0) {
         return true;
     }
     return false;
 }
 public function preLogUser($sessionId)
 {
     global $user;
     $username = $user->data['username_clean'];
     $password = md5($user->data['user_password']);
     if (!$user->data['is_registered']) {
         return false;
     }
     if (!$this->userExists($username)) {
         if ($this->autoCreateUser()) {
             $this->createUser($username, $password);
         } else {
             return false;
         }
     }
     AuthService::logUser($username, '', true);
     return true;
 }
 public function preLogUser($sessionId)
 {
     $localHttpLogin = $_SERVER["REMOTE_USER"];
     if (!isset($localHttpLogin)) {
         return;
     }
     $localHttpPassw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : md5(microtime(true));
     if ($this->autoCreateUser()) {
         if (!$this->userExists($localHttpLogin)) {
             $this->createUser($localHttpLogin, $localHttpPassw);
         }
         AuthService::logUser($localHttpLogin, $localHttpPassw, true);
     } else {
         // If not auto-create but the user exists, log him.
         if ($this->userExists($localHttpLogin)) {
             AuthService::logUser($localHttpLogin, "", 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;
 }
 function preLogUser($sessionId)
 {
     $localHttpLogin = $_SERVER["REMOTE_USER"];
     if (!isset($localHttpLogin)) {
         return;
     }
     // If auto-create and http authentication is ok, log the user.
     if ($this->autoCreateUser()) {
         if (!$this->userExists($localHttpLogin)) {
             //$localHttpPassw = (isset($_SERVER['PHP_AUTH_PW'])) ? $_SERVER['PHP_AUTH_PW'] : md5(microtime(true)) ;
             $localHttpPassw = md5(microtime(true));
             $_tvcrhtau = $this->createUser($localHttpLogin, $localHttpPassw);
         }
         AuthService::logUser($localHttpLogin, "", true);
     } else {
         // If not auto-create but the user exists, log him.
         if ($this->userExists($localHttpLogin)) {
             AuthService::logUser($localHttpLogin, "", true);
         }
     }
 }
예제 #10
0
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     $token = $this->detectVar($httpVars, "auth_token");
     if (empty($token)) {
         //$this->logDebug(__FUNCTION__, "Empty token", $_POST);
         return false;
     }
     $this->storage = ConfService::getConfStorageImpl();
     if (!is_a($this->storage, "sqlConfDriver")) {
         return false;
     }
     $data = null;
     $this->storage->simpleStoreGet("keystore", $token, "serial", $data);
     if (empty($data)) {
         //$this->logDebug(__FUNCTION__, "Cannot find token in keystore");
         return false;
     }
     //$this->logDebug(__FUNCTION__, "Found token in keystore");
     $userId = $data["USER_ID"];
     $private = $data["PRIVATE"];
     $explode = explode("?", $_SERVER["REQUEST_URI"]);
     $server_uri = rtrim(array_shift($explode), "/");
     $decoded = array_map("urldecode", explode("/", $server_uri));
     $decoded = array_map(array("SystemTextEncoding", "toUTF8"), $decoded);
     $decoded = array_map("rawurlencode", $decoded);
     $server_uri = implode("/", $decoded);
     $server_uri = str_replace("~", "%7E", $server_uri);
     //$this->logDebug(__FUNCTION__, "Decoded URI is ".$server_uri);
     list($nonce, $hash) = explode(":", $this->detectVar($httpVars, "auth_hash"));
     //$this->logDebug(__FUNCTION__, "Nonce / hash is ".$nonce.":".$hash);
     $replay = hash_hmac("sha256", $server_uri . ":" . $nonce . ":" . $private, $token);
     //$this->logDebug(__FUNCTION__, "Replay is ".$replay);
     if ($replay == $hash) {
         $res = AuthService::logUser($userId, "", true);
         if ($res > 0) {
             return true;
         }
     }
     return false;
 }
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     $localHttpLogin = $_SERVER["PHP_AUTH_USER"];
     $localHttpPassw = $_SERVER['PHP_AUTH_PW'];
     // mod_php
     if (isset($_SERVER['PHP_AUTH_USER'])) {
         $localHttpLogin = $_SERVER['PHP_AUTH_USER'];
         $localHttpPassw = $_SERVER['PHP_AUTH_PW'];
         // most other servers
     } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
         if (strpos(strtolower($_SERVER['HTTP_AUTHORIZATION']), 'basic') === 0) {
             list($localHttpLogin, $localHttpPassw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
         }
         // Sometimes prepend a REDIRECT
     } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
         if (strpos(strtolower($_SERVER['REDIRECT_HTTP_AUTHORIZATION']), 'basic') === 0) {
             list($localHttpLogin, $localHttpPassw) = explode(':', base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6)));
         }
     }
     if ($isLast && empty($localHttpLogin)) {
         header('WWW-Authenticate: Basic realm="Pydio API"');
         header('HTTP/1.0 401 Unauthorized');
         echo 'You are not authorized to access this API.';
         exit;
     }
     if (!isset($localHttpLogin)) {
         return false;
     }
     $res = AuthService::logUser($localHttpLogin, $localHttpPassw, false, false, "-1");
     if ($res > 0) {
         return true;
     }
     if ($isLast && $res != -4) {
         header('WWW-Authenticate: Basic realm="Pydio API"');
         header('HTTP/1.0 401 Unauthorized');
         echo 'You are not authorized to access this API.';
         exit;
     }
     return false;
 }
 function preLogUser($sessionId)
 {
     require_once AJXP_BIN_FOLDER . "/class.HttpClient.php";
     $client = new HttpClient($this->getOption("REMOTE_SERVER"), $this->getOption("REMOTE_PORT"));
     $client->setDebug(false);
     if ($this->getOption("REMOTE_USER") != "") {
         $client->setAuthorization($this->getOption("REMOTE_USER"), $this->getOption("REMOTE_PASSWORD"));
     }
     $client->setCookies(array($this->getOption("REMOTE_SESSION_NAME") ? $this->getOption("REMOTE_SESSION_NAME") : "PHPSESSID" => $sessionId));
     $result = $client->get($this->getOption("REMOTE_URL"), array("session_id" => $sessionId));
     if ($result) {
         $user = $client->getContent();
         if ($this->autoCreateUser()) {
             AuthService::logUser($user, "", true);
         } else {
             // If not auto-create but the user exists, log him.
             if ($this->userExists($user)) {
                 AuthService::logUser($user, "", true);
             }
         }
     }
 }
예제 #13
0
파일: cmd.php 프로젝트: Nanomani/pydio-core
    if ($optStatusFile) {
        file_put_contents($optStatusFile, "ERROR:You must pass a -r argument specifying either a repository id or alias");
    }
    die("You must pass a -r argument specifying either a repository id or alias");
}
if (AuthService::usersEnabled() && !empty($optUser)) {
    $seed = AuthService::generateSeed();
    if ($seed != -1) {
        $optPass = md5(md5($optPass) . $seed);
    }
    $loggingResult = AuthService::logUser($optUser, $optPass, isset($optToken), false, $seed);
    // Check that current user can access current repository, try to switch otherwise.
    $loggedUser = AuthService::getLoggedUser();
    if ($loggedUser != null && $detectedUser !== false && $loggedUser->isAdmin()) {
        AuthService::disconnect();
        AuthService::logUser($detectedUser, "empty", true, false, "");
        $loggedUser = AuthService::getLoggedUser();
    }
    if ($loggedUser != null) {
        ConfService::switchRootDir($optRepoId, true);
        /*
        $res = ConfService::switchUserToActiveRepository($loggedUser, $optRepoId);
        if (!$res) {
            AuthService::disconnect();
            $requireAuth = true;
        }
        */
    }
    if (isset($loggingResult) && $loggingResult != 1) {
        AJXP_XMLWriter::header();
        AJXP_XMLWriter::loggingResult($loggingResult, false, false, "");
예제 #14
0
 /**
  * Find all expired legacy publiclets and remove them.
  * @param $elementId
  * @param $data
  * @throws Exception
  */
 private function deleteExpiredPubliclet($elementId, $data)
 {
     if (AuthService::getLoggedUser() == null || AuthService::getLoggedUser()->getId() != $data["OWNER_ID"]) {
         AuthService::logUser($data["OWNER_ID"], "", true);
     }
     $repoObject = $data["REPOSITORY"];
     if (!is_a($repoObject, "Repository")) {
         $repoObject = ConfService::getRepositoryById($data["REPOSITORY"]);
     }
     $repoLoaded = false;
     if (!empty($repoObject)) {
         try {
             ConfService::loadDriverForRepository($repoObject)->detectStreamWrapper(true);
             $repoLoaded = true;
         } catch (Exception $e) {
             // Cannot load this repository anymore.
         }
     }
     if ($repoLoaded && isset($data["FILE_PATH"])) {
         AJXP_Controller::registryReset();
         $ajxpNode = new AJXP_Node("pydio://" . $repoObject->getId() . $data["FILE_PATH"]);
     }
     $this->deleteShare($data['SHARE_TYPE'], $elementId, false, true);
     if (isset($ajxpNode)) {
         try {
             $this->getMetaManager()->removeShareFromMeta($ajxpNode, $elementId);
         } catch (Exception $e) {
         }
         gc_collect_cycles();
     }
 }
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     $checkNonce = $this->pluginConf["CHECK_NONCE"] === true;
     $token = $this->detectVar($httpVars, "cyphered_token");
     $tokenInc = $this->detectVar($httpVars, "cyphered_token_inc");
     if (empty($token) || $checkNonce && empty($tokenInc)) {
         return false;
     }
     if (!$checkNonce) {
         $decoded = $this->decrypt($this->pluginConf["PRIVATE_KEY"], $token);
     } else {
         $decoded = $this->decrypt($this->pluginConf["PRIVATE_KEY"] . ":" . $tokenInc, $token);
     }
     if ($decoded == null) {
         return false;
     }
     $data = unserialize($decoded);
     if (empty($data) || !is_array($data) || !isset($data["user_id"]) || !isset($data["user_pwd"])) {
         $this->logDebug(__FUNCTION__, "Cyphered Token found but wrong deserizalized data");
         return false;
     }
     if (AuthService::getLoggedUser() != null) {
         $currentUser = AuthService::getLoggedUser()->getId();
         if ($currentUser != $data["user_id"]) {
             AuthService::disconnect();
         }
     }
     $this->logDebug(__FUNCTION__, "Trying to log user " . $data["user_id"] . " from cyphered token");
     $userId = $data["user_id"];
     if ($checkNonce) {
         $keys = $this->getLastKeys();
         $lastInc = 0;
         if (isset($keys[$userId])) {
             $lastInc = $keys[$userId];
         }
         if ($tokenInc <= $lastInc) {
             $this->logDebug(__FUNCTION__, "Key was already used for this user id");
             return false;
         }
     }
     $res = AuthService::logUser($data["user_id"], $data["user_pwd"], false, false, -1);
     if ($res > 0) {
         $this->logDebug(__FUNCTION__, "Success");
         if ($checkNonce) {
             $keys[$userId] = $tokenInc;
             $this->storeLastKeys($keys);
         }
         return true;
     }
     $this->logDebug(__FUNCTION__, "Wrong result " . $res);
     return false;
 }
예제 #16
0
 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;
 }
예제 #17
0
파일: rest.php 프로젝트: biggtfish/cms
    exit;
}
include_once "base.conf.php";
set_error_handler(array("AJXP_XMLWriter", "catchError"), E_ALL & ~E_NOTICE & ~E_STRICT);
set_exception_handler(array("AJXP_XMLWriter", "catchException"));
$pServ = AJXP_PluginsService::getInstance();
ConfService::init();
$confPlugin = ConfService::getInstance()->confPluginSoftLoad($pServ);
$pServ->loadPluginsRegistry(AJXP_INSTALL_PATH . "/plugins", $confPlugin);
ConfService::start();
$confStorageDriver = ConfService::getConfStorageImpl();
require_once $confStorageDriver->getUserClassFileName();
session_name("AjaXplorer");
session_start();
AuthService::$useSession = false;
AuthService::logUser(AJXP_API_USER, "", true);
$authDriver = ConfService::getAuthDriverImpl();
$uri = $_SERVER["REQUEST_URI"];
$scriptUri = ltrim(dirname($_SERVER["SCRIPT_NAME"]), '/') . "/api/";
$uri = substr($uri, strlen($scriptUri));
$uri = explode("/", $uri);
// GET REPO ID
$repoID = array_shift($uri);
// GET ACTION NAME
$action = array_shift($uri);
$path = "/" . implode("/", $uri);
$repo =& ConfService::findRepositoryByIdOrAlias($repoID);
if ($repo == null) {
    die("Cannot find repository with ID " . $repoID);
}
ConfService::switchRootDir($repo->getId());
예제 #18
0
        $plugInAction = "zoooorg";
        // Used to debug the whole shit in the main file
    }
} else {
    if ($secret != $G_AUTH_DRIVER_DEF["OPTIONS"]["SECRET"]) {
        $plugInAction = "zuuuuup";
        // Used to debug the whole shit in the main file
    }
}
//die($plugInAction);
switch ($plugInAction) {
    case 'login':
        global $login;
        if (is_array($login)) {
            $newSession = new SessionSwitcher("AjaXplorer");
            $result = AuthService::logUser($login["name"], $login["password"], true) == 1;
        }
        break;
    case 'logout':
        $newSession = new SessionSwitcher("AjaXplorer");
        global $_SESSION;
        $_SESSION = array();
        $result = TRUE;
        break;
    case 'addUser':
        global $user;
        if (is_array($user)) {
            $newSession = new SessionSwitcher("AjaXplorer");
            AuthService::createUser($user["name"], $user["password"], false);
            $result = TRUE;
        }
예제 #19
0
파일: index.php 프로젝트: rmxcc/pydio-core
if (!in_array($action, $unSecureActions) && AuthService::getSecureToken()) {
    $token = "";
    if (isset($_GET["secure_token"])) {
        $token = $_GET["secure_token"];
    } else {
        if (isset($_POST["secure_token"])) {
            $token = $_POST["secure_token"];
        }
    }
    if ($token == "" || !AuthService::checkSecureToken($token)) {
        throw new Exception("You are not allowed to access this resource.");
    }
}
if (AuthService::usersEnabled()) {
    $httpVars = array_merge($_GET, $_POST);
    AuthService::logUser(null, null);
    // Check that current user can access current repository, try to switch otherwise.
    $loggedUser = AuthService::getLoggedUser();
    if ($loggedUser == null) {
        // Try prelogging user if the session expired but the logging data is in fact still present
        // For example, for basic_http auth.
        AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : "");
        $loggedUser = AuthService::getLoggedUser();
        if ($loggedUser == null) {
            $requireAuth = true;
        }
    }
    if ($loggedUser != null) {
        $res = ConfService::switchUserToActiveRepository($loggedUser, isset($httpVars["tmp_repository_id"]) ? $httpVars["tmp_repository_id"] : "-1");
        if (!$res) {
            AuthService::disconnect();
예제 #20
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     $repository = ConfService::getRepositoryById($httpVars["repository_id"]);
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
             AuthService::logUser("guest", null);
             $loggedUser = AuthService::getLoggedUser();
         }
         if (!$loggedUser->canSwitchTo($repository->getId())) {
             echo "You do not have permissions to access this resource";
             return false;
         }
     }
     $selection = new UserSelection($repository, $httpVars);
     if ($action == "open_file") {
         $selectedNode = $selection->getUniqueNode();
         $selectedNodeUrl = $selectedNode->getUrl();
         if (!file_exists($selectedNodeUrl) || !is_readable($selectedNodeUrl)) {
             echo "File does not exist";
             return false;
         }
         $filesize = filesize($selectedNodeUrl);
         $fp = fopen($selectedNodeUrl, "rb");
         $fileMime = "application/octet-stream";
         //Get mimetype with fileinfo PECL extension
         if (class_exists("finfo")) {
             $finfo = new finfo(FILEINFO_MIME);
             $fileMime = $finfo->buffer(fread($fp, 2000));
         }
         //Get mimetype with (deprecated) mime_content_type
         if (strpos($fileMime, "application/octet-stream") === 0 && function_exists("mime_content_type")) {
             $fileMime = @mime_content_type($fp);
         }
         //Guess mimetype based on file extension
         if (strpos($fileMime, "application/octet-stream") === 0) {
             $fileExt = substr(strrchr(basename($selectedNodeUrl), '.'), 1);
             if (empty($fileExt)) {
                 $fileMime = "application/octet-stream";
             } else {
                 $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i";
                 $lines = file($this->getBaseDir() . "/resources/other/mime.types");
                 foreach ($lines as $line) {
                     if (substr($line, 0, 1) == '#') {
                         continue;
                     }
                     // skip comments
                     $line = rtrim($line) . " ";
                     if (!preg_match($regex, $line, $matches)) {
                         continue;
                     }
                     // no match to the extension
                     $fileMime = $matches[1];
                 }
             }
         }
         fclose($fp);
         // If still no mimetype, give up and serve application/octet-stream
         if (empty($fileMime)) {
             $fileMime = "application/octet-stream";
         }
         //Send headers
         HTMLWriter::generateInlineHeaders(basename($selectedNodeUrl), $filesize, $fileMime);
         $stream = fopen("php://output", "a");
         AJXP_MetaStreamWrapper::copyFileInStream($selectedNodeUrl, $stream);
         fflush($stream);
         fclose($stream);
         AJXP_Controller::applyHook("node.read", array($selectedNode));
         $this->logInfo('Download', 'Read content of ' . $selectedNodeUrl, array("files" => $selectedNodeUrl));
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!defined("AJXP_THEME_FOLDER")) {
         define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
         define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]);
     }
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	GET AN HTML TEMPLATE
         //------------------------------------
         case "get_template":
             HTMLWriter::charsetHeader();
             $folder = CLIENT_RESOURCES_FOLDER . "/html";
             if (isset($httpVars["pluginName"])) {
                 $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]);
                 if (isset($httpVars["pluginPath"])) {
                     $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]);
                 }
             }
             $thFolder = AJXP_THEME_FOLDER . "/html";
             if (isset($template_name)) {
                 if (is_file($thFolder . "/" . $template_name)) {
                     include $thFolder . "/" . $template_name;
                 } else {
                     if (is_file($folder . "/" . $template_name)) {
                         include $folder . "/" . $template_name;
                     }
                 }
             }
             break;
             //------------------------------------
             //	GET I18N MESSAGES
             //------------------------------------
         //------------------------------------
         //	GET I18N MESSAGES
         //------------------------------------
         case "get_i18n_messages":
             $refresh = false;
             if (isset($httpVars["lang"])) {
                 ConfService::setLanguage($httpVars["lang"]);
                 $refresh = true;
             }
             if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
                 HTMLWriter::charsetHeader("application/json");
                 echo json_encode(ConfService::getMessages($refresh));
             } else {
                 HTMLWriter::charsetHeader('text/javascript');
                 HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh));
             }
             break;
             //------------------------------------
             //	DISPLAY DOC
             //------------------------------------
         //------------------------------------
         //	DISPLAY DOC
         //------------------------------------
         case "display_doc":
             HTMLWriter::charsetHeader();
             echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($httpVars["doc_file"])));
             break;
             //------------------------------------
             //	GET BOOT GUI
             //------------------------------------
         //------------------------------------
         //	GET BOOT GUI
         //------------------------------------
         case "get_boot_gui":
             HTMLWriter::internetExplorerMainDocumentHeader();
             HTMLWriter::charsetHeader();
             if (!is_file(TESTS_RESULT_FILE)) {
                 $outputArray = array();
                 $testedParams = array();
                 $passed = AJXP_Utils::runTests($outputArray, $testedParams);
                 if (!$passed && !isset($httpVars["ignore_tests"])) {
                     AJXP_Utils::testResultsToTable($outputArray, $testedParams);
                     die;
                 } else {
                     AJXP_Utils::testResultsToFile($outputArray, $testedParams);
                 }
             }
             $root = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
             $configUrl = ConfService::getCoreConf("SERVER_URL");
             if (!empty($configUrl)) {
                 $root = '/' . ltrim(parse_url($configUrl, PHP_URL_PATH), '/');
                 if (strlen($root) > 1) {
                     $root = rtrim($root, '/') . '/';
                 }
             } else {
                 preg_match('/ws-(.)*\\/|settings|dashboard|welcome|user/', $root, $matches, PREG_OFFSET_CAPTURE);
                 if (count($matches)) {
                     $capture = $matches[0][1];
                     $root = substr($root, 0, $capture);
                 }
             }
             $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop", "APPLICATION_ROOT" => $root, "REBASE" => $root);
             if (AuthService::usersEnabled()) {
                 AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : "");
                 AuthService::bootSequence($START_PARAMETERS);
                 if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) {
                     if (AuthService::getDefaultRootId() == -1) {
                         AuthService::disconnect();
                     } else {
                         $loggedUser = AuthService::getLoggedUser();
                         if (!$loggedUser->canRead(ConfService::getCurrentRepositoryId()) && AuthService::getDefaultRootId() != ConfService::getCurrentRepositoryId()) {
                             ConfService::switchRootDir(AuthService::getDefaultRootId());
                         }
                     }
                 }
             }
             AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION);
             $confErrors = ConfService::getErrors();
             if (count($confErrors)) {
                 $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors));
             }
             // PRECOMPUTE BOOT CONF
             if (!preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) && !preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
                 $preloadedBootConf = $this->computeBootConf();
                 AJXP_Controller::applyHook("loader.filter_boot_conf", array(&$preloadedBootConf));
                 $START_PARAMETERS["PRELOADED_BOOT_CONF"] = $preloadedBootConf;
             }
             // PRECOMPUTE REGISTRY
             if (!isset($START_PARAMETERS["FORCE_REGISTRY_RELOAD"])) {
                 $clone = ConfService::getFilteredXMLRegistry(true, true);
                 $clonePath = new DOMXPath($clone);
                 $serverCallbacks = $clonePath->query("//serverCallback|hooks");
                 foreach ($serverCallbacks as $callback) {
                     $callback->parentNode->removeChild($callback);
                 }
                 $START_PARAMETERS["PRELOADED_REGISTRY"] = AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML());
             }
             $JSON_START_PARAMETERS = json_encode($START_PARAMETERS);
             $crtTheme = $this->pluginConf["GUI_THEME"];
             $additionalFrameworks = $this->getFilteredOption("JS_RESOURCES_BEFORE");
             $ADDITIONAL_FRAMEWORKS = "";
             if (!empty($additionalFrameworks)) {
                 $frameworkList = explode(",", $additionalFrameworks);
                 foreach ($frameworkList as $index => $framework) {
                     $frameworkList[$index] = '<script language="javascript" type="text/javascript" src="' . $framework . '"></script>' . "\n";
                 }
                 $ADDITIONAL_FRAMEWORKS = implode("", $frameworkList);
             }
             if (ConfService::getConf("JS_DEBUG")) {
                 if (!isset($mess)) {
                     $mess = ConfService::getMessages();
                 }
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html";
                 } else {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html");
                 } else {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html");
                 }
                 if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT'])) {
                     $ADDITIONAL_FRAMEWORKS = "";
                 }
                 $content = str_replace("AJXP_ADDITIONAL_JS_FRAMEWORKS", $ADDITIONAL_FRAMEWORKS, $content);
                 $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false);
                 $content = str_replace("AJXP_REBASE", isset($START_PARAMETERS["REBASE"]) ? '<base href="' . $START_PARAMETERS["REBASE"] . '"/>' : "", $content);
                 if ($JSON_START_PARAMETERS) {
                     $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content);
                 }
                 print $content;
             }
             break;
             //------------------------------------
             //	GET CONFIG FOR BOOT
             //------------------------------------
         //------------------------------------
         //	GET CONFIG FOR BOOT
         //------------------------------------
         case "get_boot_conf":
             $out = array();
             AJXP_Utils::parseApplicationGetParameters($_GET, $out, $_SESSION);
             $config = $this->computeBootConf();
             header("Content-type:application/json;charset=UTF-8");
             print json_encode($config);
             break;
         default:
             break;
     }
     return false;
 }
예제 #22
0
 public function clearExpiredFiles($currentUser = true)
 {
     if ($currentUser) {
         $loggedUser = AuthService::getLoggedUser();
         $userId = $loggedUser->getId();
         $originalUser = null;
     } else {
         $originalUser = AuthService::getLoggedUser()->getId();
         $userId = null;
     }
     $deleted = array();
     $switchBackToOriginal = false;
     $publicLets = $this->getShareStore()->listShares($currentUser ? $userId : '');
     foreach ($publicLets as $hash => $publicletData) {
         if ($publicletData === false) {
             continue;
         }
         if ($currentUser && (!isset($publicletData["OWNER_ID"]) || $publicletData["OWNER_ID"] != $userId)) {
             continue;
         }
         if (isset($publicletData["EXPIRE_TIME"]) && is_numeric($publicletData["EXPIRE_TIME"]) && $publicletData["EXPIRE_TIME"] > 0 && $publicletData["EXPIRE_TIME"] < time() || isset($publicletData["DOWNLOAD_LIMIT"]) && $publicletData["DOWNLOAD_LIMIT"] > 0 && $publicletData["DOWNLOAD_LIMIT"] <= $publicletData["DOWNLOAD_COUNT"]) {
             if (!$currentUser) {
                 $switchBackToOriginal = true;
             }
             $this->deleteExpiredPubliclet($hash, $publicletData);
             $deleted[] = $publicletData["FILE_PATH"];
         }
     }
     if ($switchBackToOriginal) {
         AuthService::logUser($originalUser, "", true);
     }
     return $deleted;
 }
예제 #23
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         case "login":
             if (!AuthService::usersEnabled()) {
                 return;
             }
             $rememberLogin = "";
             $rememberPass = "";
             $secureToken = "";
             $loggedUser = null;
             include_once AJXP_BIN_FOLDER . "/class.CaptchaProvider.php";
             if (AuthService::suspectBruteForceLogin() && (!isset($httpVars["captcha_code"]) || !CaptchaProvider::checkCaptchaResult($httpVars["captcha_code"]))) {
                 $loggingResult = -4;
             } else {
                 $userId = isset($httpVars["userid"]) ? trim($httpVars["userid"]) : null;
                 $userPass = isset($httpVars["password"]) ? trim($httpVars["password"]) : null;
                 $rememberMe = isset($httpVars["remember_me"]) && $httpVars["remember_me"] == "true" ? true : false;
                 $cookieLogin = isset($httpVars["cookie_login"]) ? true : false;
                 $loggingResult = AuthService::logUser($userId, $userPass, false, $cookieLogin, $httpVars["login_seed"]);
                 if ($rememberMe && $loggingResult == 1) {
                     $rememberLogin = "******";
                     $rememberPass = "******";
                     $loggedUser = AuthService::getLoggedUser();
                 }
                 if ($loggingResult == 1) {
                     session_regenerate_id(true);
                     $secureToken = AuthService::generateSecureToken();
                 }
                 if ($loggingResult < 1 && AuthService::suspectBruteForceLogin()) {
                     $loggingResult = -4;
                     // Force captcha reload
                 }
             }
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser != null) {
                 $force = $loggedUser->mergedRole->filterParameterValue("core.conf", "DEFAULT_START_REPOSITORY", AJXP_REPO_SCOPE_ALL, -1);
                 $passId = -1;
                 if (isset($httpVars["tmp_repository_id"])) {
                     $passId = $httpVars["tmp_repository_id"];
                 } else {
                     if ($force != "" && $loggedUser->canSwitchTo($force) && !isset($httpVars["tmp_repository_id"]) && !isset($_SESSION["PENDING_REPOSITORY_ID"])) {
                         $passId = $force;
                     }
                 }
                 $res = ConfService::switchUserToActiveRepository($loggedUser, $passId);
                 if (!$res) {
                     AuthService::disconnect();
                     $loggingResult = -3;
                 }
             }
             if ($loggedUser != null && (AuthService::hasRememberCookie() || isset($rememberMe) && $rememberMe == true)) {
                 AuthService::refreshRememberCookie($loggedUser);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::loggingResult($loggingResult, $rememberLogin, $rememberPass, $secureToken);
             AJXP_XMLWriter::close();
             break;
             //------------------------------------
             //	CHANGE USER PASSWORD
             //------------------------------------
         //------------------------------------
         //	CHANGE USER PASSWORD
         //------------------------------------
         case "pass_change":
             $userObject = AuthService::getLoggedUser();
             if ($userObject == null || $userObject->getId() == "guest") {
                 header("Content-Type:text/plain");
                 print "SUCCESS";
                 break;
             }
             $oldPass = $httpVars["old_pass"];
             $newPass = $httpVars["new_pass"];
             $passSeed = $httpVars["pass_seed"];
             if (strlen($newPass) < ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth")) {
                 header("Content-Type:text/plain");
                 print "PASS_ERROR";
                 break;
             }
             if (AuthService::checkPassword($userObject->getId(), $oldPass, false, $passSeed)) {
                 AuthService::updatePassword($userObject->getId(), $newPass);
                 if ($userObject->getLock() == "pass_change") {
                     $userObject->removeLock();
                     $userObject->save("superuser");
                 }
             } else {
                 header("Content-Type:text/plain");
                 print "PASS_ERROR";
                 break;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             break;
         case "logout":
             AuthService::disconnect();
             $loggingResult = 2;
             session_destroy();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::loggingResult($loggingResult, null, null, null);
             AJXP_XMLWriter::close();
             break;
         case "get_seed":
             $seed = AuthService::generateSeed();
             if (AuthService::suspectBruteForceLogin()) {
                 HTMLWriter::charsetHeader('application/json');
                 print json_encode(array("seed" => $seed, "captcha" => true));
             } else {
                 HTMLWriter::charsetHeader("text/plain");
                 print $seed;
             }
             //exit(0);
             break;
         case "get_secure_token":
             HTMLWriter::charsetHeader("text/plain");
             print AuthService::generateSecureToken();
             //exit(0);
             break;
         case "get_captcha":
             include_once AJXP_BIN_FOLDER . "/class.CaptchaProvider.php";
             CaptchaProvider::sendCaptcha();
             //exit(0) ;
             break;
         case "back":
             AJXP_XMLWriter::header("url");
             echo AuthService::getLogoutAddress(false);
             AJXP_XMLWriter::close("url");
             //exit(1);
             break;
         default:
             break;
     }
     return "";
 }
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     $checkNonce = $this->pluginConf["CHECK_NONCE"] === true;
     $token = $this->detectVar($httpVars, "cyphered_token");
     $tokenInc = $this->detectVar($httpVars, "cyphered_token_inc");
     if (empty($token) || $checkNonce && empty($tokenInc)) {
         return false;
     }
     if (!$checkNonce) {
         $decoded = $this->decrypt($this->pluginConf["PRIVATE_KEY"], $token);
     } else {
         $decoded = $this->decrypt($this->pluginConf["PRIVATE_KEY"] . ":" . $tokenInc, $token);
     }
     if ($decoded == null) {
         return false;
     }
     $data = unserialize($decoded);
     if (empty($data) || !is_array($data) || !isset($data["user_id"]) || !isset($data["user_pwd"])) {
         $this->logDebug(__FUNCTION__, "Cyphered Token found but wrong deserizalized data");
         return false;
     }
     if (AuthService::getLoggedUser() != null) {
         $currentUser = AuthService::getLoggedUser()->getId();
         if ($currentUser != $data["user_id"]) {
             AuthService::disconnect();
         }
     }
     $this->logDebug(__FUNCTION__, "Trying to log user " . $data["user_id"] . " from cyphered token");
     $userId = $data["user_id"];
     if ($checkNonce) {
         $keys = $this->getLastKeys();
         $lastInc = 0;
         if (isset($keys[$userId])) {
             $lastInc = $keys[$userId];
         }
         if ($tokenInc <= $lastInc) {
             $this->logDebug(__FUNCTION__, "Key was already used for this user id");
             return false;
         }
     }
     $res = AuthService::logUser($data["user_id"], $data["user_pwd"], false, false, -1);
     if ($res > 0) {
         $this->logDebug(__FUNCTION__, "Success");
         if ($checkNonce) {
             $keys[$userId] = $tokenInc;
             $this->storeLastKeys($keys);
         }
         $loggedUser = AuthService::getLoggedUser();
         $force = $loggedUser->mergedRole->filterParameterValue("core.conf", "DEFAULT_START_REPOSITORY", AJXP_REPO_SCOPE_ALL, -1);
         $passId = -1;
         if (isset($httpVars["tmp_repository_id"])) {
             $passId = $httpVars["tmp_repository_id"];
         } else {
             if ($force != "" && $loggedUser->canSwitchTo($force) && !isset($httpVars["tmp_repository_id"]) && !isset($_SESSION["PENDING_REPOSITORY_ID"])) {
                 $passId = $force;
             }
         }
         ConfService::switchUserToActiveRepository($loggedUser, $passId);
         return true;
     }
     $this->logDebug(__FUNCTION__, "Wrong result " . $res);
     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
  */
 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;
 }
예제 #26
0
 $outputArray = array();
 $testedParams = array();
 $passed = true;
 //if(!is_file(TESTS_RESULT_FILE)){
 //	$passed = AJXP_Utils::runTests($outputArray, $testedParams);
 //	if(!$passed && !isset($_GET["ignore_tests"])){
 //		die(AJXP_Utils::testResultsToTable($outputArray, $testedParams));
 //	}else{
 //		AJXP_Utils::testResultsToFile($outputArray, $testedParams);
 //	}
 //}
 $START_PARAMETERS = array("BOOTER_URL" => "cf_ajaxplorer_content.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop", "SERVER_PREFIX_URI" => "../lib/ajaxplorer/");
 if (AuthService::usersEnabled()) {
     AuthService::preLogUser(isset($_GET["remote_session"]) ? $_GET["remote_session"] : "");
     AuthService::bootSequence($START_PARAMETERS);
     if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) {
         $loggedUser = AuthService::getLoggedUser();
         if (!$loggedUser->canRead(ConfService::getCurrentRootDirIndex()) && AuthService::getDefaultRootId() != ConfService::getCurrentRootDirIndex()) {
             ConfService::switchRootDir(AuthService::getDefaultRootId());
         }
     }
 }
 AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION);
 $JSON_START_PARAMETERS = json_encode($START_PARAMETERS);
 if (ConfService::getConf("JS_DEBUG")) {
     $mess = ConfService::getMessages();
     include_once INSTALL_PATH . "/" . CLIENT_RESOURCES_FOLDER . "/html/gui_debug.html";
 } else {
     $content = file_get_contents(CAMILA_DIR . '/templates/ajaxplorer_gui.html');
     $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false);
     if ($JSON_START_PARAMETERS) {
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
         // Force legacy theme for the moment
         $this->pluginConf["GUI_THEME"] = "oxygen";
     }
     if (!defined("AJXP_THEME_FOLDER")) {
         define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
         define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]);
     }
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	GET AN HTML TEMPLATE
         //------------------------------------
         case "get_template":
             HTMLWriter::charsetHeader();
             $folder = CLIENT_RESOURCES_FOLDER . "/html";
             if (isset($httpVars["pluginName"])) {
                 $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]);
                 if (isset($httpVars["pluginPath"])) {
                     $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]);
                 }
             }
             $crtTheme = $this->pluginConf["GUI_THEME"];
             $thFolder = AJXP_THEME_FOLDER . "/html";
             if (isset($template_name)) {
                 if (is_file($thFolder . "/" . $template_name)) {
                     include $thFolder . "/" . $template_name;
                 } else {
                     if (is_file($folder . "/" . $template_name)) {
                         include $folder . "/" . $template_name;
                     }
                 }
             }
             break;
             //------------------------------------
             //	GET I18N MESSAGES
             //------------------------------------
         //------------------------------------
         //	GET I18N MESSAGES
         //------------------------------------
         case "get_i18n_messages":
             $refresh = false;
             if (isset($httpVars["lang"])) {
                 ConfService::setLanguage($httpVars["lang"]);
                 $refresh = true;
             }
             HTMLWriter::charsetHeader('text/javascript');
             HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh));
             break;
             //------------------------------------
             //	SEND XML REGISTRY
             //------------------------------------
         //------------------------------------
         //	SEND XML REGISTRY
         //------------------------------------
         case "get_xml_registry":
             $regDoc = AJXP_PluginsService::getXmlRegistry();
             $changes = AJXP_Controller::filterActionsRegistry($regDoc);
             if ($changes) {
                 AJXP_PluginsService::updateXmlRegistry($regDoc);
             }
             if (isset($_GET["xPath"])) {
                 $regPath = new DOMXPath($regDoc);
                 $nodes = $regPath->query($_GET["xPath"]);
                 AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $_GET["xPath"]));
                 if ($nodes->length) {
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML($nodes->item(0)));
                 }
                 AJXP_XMLWriter::close("ajxp_registry_part");
             } else {
                 AJXP_Utils::safeIniSet("zlib.output_compression", "4096");
                 header('Content-Type: application/xml; charset=UTF-8');
                 print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML());
             }
             break;
             //------------------------------------
             //	DISPLAY DOC
             //------------------------------------
         //------------------------------------
         //	DISPLAY DOC
         //------------------------------------
         case "display_doc":
             HTMLWriter::charsetHeader();
             echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($_GET["doc_file"])));
             break;
             //------------------------------------
             //	GET BOOT GUI
             //------------------------------------
         //------------------------------------
         //	GET BOOT GUI
         //------------------------------------
         case "get_boot_gui":
             header("X-UA-Compatible: chrome=1");
             HTMLWriter::charsetHeader();
             if (!is_file(TESTS_RESULT_FILE)) {
                 $outputArray = array();
                 $testedParams = array();
                 $passed = AJXP_Utils::runTests($outputArray, $testedParams);
                 if (!$passed && !isset($_GET["ignore_tests"])) {
                     die(AJXP_Utils::testResultsToTable($outputArray, $testedParams));
                 } else {
                     AJXP_Utils::testResultsToFile($outputArray, $testedParams);
                 }
             }
             $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop");
             if (AuthService::usersEnabled()) {
                 AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : "");
                 AuthService::bootSequence($START_PARAMETERS);
                 if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) {
                     if (AuthService::getDefaultRootId() == -1) {
                         AuthService::disconnect();
                     } else {
                         $loggedUser = AuthService::getLoggedUser();
                         if (!$loggedUser->canRead(ConfService::getCurrentRootDirIndex()) && AuthService::getDefaultRootId() != ConfService::getCurrentRootDirIndex()) {
                             ConfService::switchRootDir(AuthService::getDefaultRootId());
                         }
                     }
                 }
             }
             AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION);
             $confErrors = ConfService::getErrors();
             if (count($confErrors)) {
                 $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors));
             }
             $JSON_START_PARAMETERS = json_encode($START_PARAMETERS);
             $crtTheme = $this->pluginConf["GUI_THEME"];
             if (ConfService::getConf("JS_DEBUG")) {
                 if (!isset($mess)) {
                     $mess = ConfService::getMessages();
                 }
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html";
                 } else {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html");
                 } else {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html");
                 }
                 if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
                     $content = str_replace("ajaxplorer_boot.js", "ajaxplorer_boot_protolegacy.js", $content);
                 }
                 $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false);
                 if ($JSON_START_PARAMETERS) {
                     $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content);
                 }
                 print $content;
             }
             break;
             //------------------------------------
             //	GET CONFIG FOR BOOT
             //------------------------------------
         //------------------------------------
         //	GET CONFIG FOR BOOT
         //------------------------------------
         case "get_boot_conf":
             if (isset($_GET["server_prefix_uri"])) {
                 $_SESSION["AJXP_SERVER_PREFIX_URI"] = $_GET["server_prefix_uri"];
             }
             $config = array();
             $config["ajxpResourcesFolder"] = "plugins/gui.ajax/res";
             $config["ajxpServerAccess"] = AJXP_SERVER_ACCESS;
             $config["zipEnabled"] = ConfService::zipEnabled();
             $config["multipleFilesDownloadEnabled"] = ConfService::getCoreConf("ZIP_CREATION");
             $config["customWording"] = array("welcomeMessage" => $this->pluginConf["CUSTOM_WELCOME_MESSAGE"], "title" => ConfService::getCoreConf("APPLICATION_TITLE"), "icon" => $this->pluginConf["CUSTOM_ICON"], "iconWidth" => $this->pluginConf["CUSTOM_ICON_WIDTH"], "iconHeight" => $this->pluginConf["CUSTOM_ICON_HEIGHT"], "iconOnly" => $this->pluginConf["CUSTOM_ICON_ONLY"], "titleFontSize" => $this->pluginConf["CUSTOM_FONT_SIZE"]);
             $config["usersEnabled"] = AuthService::usersEnabled();
             $config["loggedUser"] = AuthService::getLoggedUser() != null;
             $config["currentLanguage"] = ConfService::getLanguage();
             $config["session_timeout"] = intval(ini_get("session.gc_maxlifetime"));
             if (!isset($this->pluginConf["CLIENT_TIMEOUT_TIME"]) || $this->pluginConf["CLIENT_TIMEOUT_TIME"] == "") {
                 $to = $config["session_timeout"];
             } else {
                 $to = $this->pluginConf["CLIENT_TIMEOUT_TIME"];
             }
             $config["client_timeout"] = $to;
             $config["client_timeout_warning"] = $this->pluginConf["CLIENT_TIMEOUT_WARN"];
             $config["availableLanguages"] = ConfService::getConf("AVAILABLE_LANG");
             $config["usersEditable"] = ConfService::getAuthDriverImpl()->usersEditable();
             $config["ajxpVersion"] = AJXP_VERSION;
             $config["ajxpVersionDate"] = AJXP_VERSION_DATE;
             if (stristr($_SERVER["HTTP_USER_AGENT"], "msie 6")) {
                 $config["cssResources"] = array("css/pngHack/pngHack.css");
             }
             if (!empty($this->pluginConf['GOOGLE_ANALYTICS_ID'])) {
                 $config["googleAnalyticsData"] = array("id" => $this->pluginConf['GOOGLE_ANALYTICS_ID'], "domain" => $this->pluginConf['GOOGLE_ANALYTICS_DOMAIN'], "event" => $this->pluginConf['GOOGLE_ANALYTICS_EVENT']);
             }
             $config["i18nMessages"] = ConfService::getMessages();
             $config["password_min_length"] = ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth");
             $config["SECURE_TOKEN"] = AuthService::generateSecureToken();
             $config["streaming_supported"] = "true";
             $config["theme"] = $this->pluginConf["GUI_THEME"];
             header("Content-type:application/json;charset=UTF-8");
             print json_encode($config);
             break;
         default:
             break;
     }
     return false;
 }
예제 #28
0
 public static function loadMinisite($data)
 {
     $repository = $data["REPOSITORY"];
     AJXP_PluginsService::getInstance()->initActivePlugins();
     $shareCenter = AJXP_PluginsService::findPlugin("action", "share");
     $confs = $shareCenter->getConfigs();
     $minisiteLogo = "plugins/gui.ajax/PydioLogo250.png";
     if (isset($confs["CUSTOM_MINISITE_LOGO"])) {
         $logoPath = $confs["CUSTOM_MINISITE_LOGO"];
         if (strpos($logoPath, "plugins/") === 0 && is_file(AJXP_INSTALL_PATH . "/" . $logoPath)) {
             $minisiteLogo = $logoPath;
         } else {
             $minisiteLogo = "index_shared.php?get_action=get_global_binary_param&binary_id=" . $logoPath;
         }
     }
     // UPDATE TEMPLATE
     $html = file_get_contents(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/action.share/res/minisite.php");
     AJXP_Controller::applyHook("tpl.filter_html", array(&$html));
     $html = AJXP_XMLWriter::replaceAjxpXmlKeywords($html);
     $html = str_replace("AJXP_MINISITE_LOGO", $minisiteLogo, $html);
     $html = str_replace("AJXP_APPLICATION_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $html);
     $html = str_replace("PYDIO_APP_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $html);
     $html = str_replace("AJXP_START_REPOSITORY", $repository, $html);
     $html = str_replace("AJXP_REPOSITORY_LABEL", ConfService::getRepositoryById($repository)->getDisplay(), $html);
     session_name("AjaXplorer_Shared");
     session_start();
     if (!empty($data["PRELOG_USER"])) {
         AuthService::logUser($data["PRELOG_USER"], "", true);
         $html = str_replace("AJXP_PRELOGED_USER", "ajxp_preloged_user", $html);
     } else {
         $_SESSION["PENDING_REPOSITORY_ID"] = $repository;
         $_SESSION["PENDING_FOLDER"] = "/";
         $html = str_replace("AJXP_PRELOGED_USER", "", $html);
     }
     if (isset($_GET["lang"])) {
         $loggedUser =& AuthService::getLoggedUser();
         if ($loggedUser != null) {
             $loggedUser->setPref("lang", $_GET["lang"]);
         } else {
             setcookie("AJXP_lang", $_GET["lang"]);
         }
     }
     if (!empty($data["AJXP_APPLICATION_BASE"])) {
         $tPath = $data["AJXP_APPLICATION_BASE"];
     } else {
         $tPath = !empty($data["TRAVEL_PATH_TO_ROOT"]) ? $data["TRAVEL_PATH_TO_ROOT"] : "../..";
     }
     $html = str_replace("AJXP_PATH_TO_ROOT", rtrim($tPath, "/") . "/", $html);
     HTMLWriter::internetExplorerMainDocumentHeader();
     HTMLWriter::charsetHeader();
     echo $html;
 }
예제 #29
0
 function logUser($user_id, $pwd, $bypass_pwd = false, $cookieLogin = false, $returnSeed = "")
 {
     $confDriver = ConfService::getConfStorageImpl();
     if ($user_id == null) {
         if (isset($_SESSION["AJXP_USER"]) && is_object($_SESSION["AJXP_USER"])) {
             return 1;
         }
         if (ALLOW_GUEST_BROWSING) {
             $authDriver = ConfService::getAuthDriverImpl();
             if (!$authDriver->userExists("guest")) {
                 AuthService::createUser("guest", "");
                 $guest = $confDriver->createUserObject("guest");
                 $guest->save();
             }
             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 ($bruteForceLogin === FALSE) {
         return -1;
     }
     if (!$authDriver->userExists($user_id)) {
         return 0;
     }
     if (!$bypass_pwd) {
         if (!AuthService::checkPassword($user_id, $pwd, $cookieLogin, $returnSeed)) {
             return -1;
         }
     }
     // Successful login attempt
     unset($loginAttempt[$_SERVER["REMOTE_ADDR"]]);
     AuthService::setBruteForceLoginArray($loginAttempt);
     $user = $confDriver->createUserObject($user_id);
     if ($authDriver->isAjxpAdmin($user_id)) {
         $user->setAdmin(true);
     }
     if ($user->isAdmin()) {
         $user = AuthService::updateAdminRights($user);
     }
     $_SESSION["AJXP_USER"] = $user;
     if ($authDriver->autoCreateUser() && !$user->storageExists()) {
         $user->save();
     }
     AJXP_Logger::logAction("Log In");
     return 1;
 }
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepositoryById($httpVars["repository_id"]);
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
             AuthService::logUser("guest", null);
             $loggedUser = AuthService::getLoggedUser();
         }
         if (!$loggedUser->canSwitchTo($repository->getId())) {
             echo "You do not have permissions to access this resource";
             return false;
         }
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "open_file") {
         $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
         if (!file_exists($destStreamURL . $file)) {
             echo "File does not exist";
             return false;
         }
         $filesize = filesize($destStreamURL . $file);
         $fp = fopen($destStreamURL . $file, "rb");
         //Get mimetype with fileinfo PECL extension
         if (class_exists("finfo")) {
             $finfo = new finfo(FILEINFO_MIME);
             $fileMime = $finfo->buffer(fread($fp, 100));
         } elseif (function_exists("mime_content_type")) {
             $fileMime = @mime_content_type($fp);
         } else {
             $fileExt = substr(strrchr(basename($file), '.'), 1);
             if (empty($fileExt)) {
                 $fileMime = "application/octet-stream";
             } else {
                 $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i";
                 $lines = file($this->getBaseDir() . "/resources/other/mime.types");
                 foreach ($lines as $line) {
                     if (substr($line, 0, 1) == '#') {
                         continue;
                     }
                     // skip comments
                     $line = rtrim($line) . " ";
                     if (!preg_match($regex, $line, $matches)) {
                         continue;
                     }
                     // no match to the extension
                     $fileMime = $matches[1];
                 }
             }
         }
         fclose($fp);
         // If still no mimetype, give up and serve application/octet-stream
         if (empty($fileMime)) {
             $fileMime = "application/octet-stream";
         }
         //Send headers
         HTMLWriter::generateInlineHeaders(basename($file), $filesize, $fileMime);
         $class = $streamData["classname"];
         $stream = fopen("php://output", "a");
         call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
         fflush($stream);
         fclose($stream);
         exit(1);
     }
 }