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;
 }
Пример #2
0
 public function doTest()
 {
     $tmpDir = ini_get("upload_tmp_dir");
     if (!$tmpDir) {
         $tmpDir = realpath(sys_get_temp_dir());
     }
     if (ConfService::getCoreConf("AJXP_TMP_DIR") != "") {
         $tmpDir = ConfService::getCoreConf("AJXP_TMP_DIR");
     }
     if (defined("AJXP_TMP_DIR") && AJXP_TMP_DIR != "") {
         $tmpDir = AJXP_TMP_DIR;
     }
     $this->testedParams["Upload Tmp Dir Writeable"] = @is_writable($tmpDir);
     $this->testedParams["PHP Upload Max Size"] = $this->returnBytes(ini_get("upload_max_filesize"));
     $this->testedParams["PHP Post Max Size"] = $this->returnBytes(ini_get("post_max_size"));
     foreach ($this->testedParams as $paramName => $paramValue) {
         $this->failedInfo .= "\n{$paramName}={$paramValue}";
     }
     if (!$this->testedParams["Upload Tmp Dir Writeable"]) {
         $this->failedLevel = "error";
         $this->failedInfo = "The temporary folder used by PHP to upload files is either incorrect or not writeable! Upload will not work. Please check : " . ini_get("upload_tmp_dir");
         $this->failedInfo .= "<p class='suggestion'><b>Suggestion</b> : Set the AJXP_TMP_DIR parameter in the <i>conf/bootstrap_conf.php</i> file</p>";
         return FALSE;
     }
     $this->failedLevel = "info";
     return FALSE;
 }
Пример #3
0
function buildPublicHtaccessContent()
{
    $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER");
    $dlURL = ConfService::getCoreConf("PUBLIC_DOWNLOAD_URL");
    if ($dlURL != "") {
        $url = rtrim($dlURL, "/");
    } else {
        $fullUrl = AJXP_Utils::detectServerURL(true);
        $url = str_replace("\\", "/", rtrim($fullUrl, "/") . rtrim(str_replace(AJXP_INSTALL_PATH, "", $downloadFolder), "/"));
    }
    $htaccessContent = "Order Deny,Allow\nAllow from all\n";
    $htaccessContent .= "\n<Files \".ajxp_*\">\ndeny from all\n</Files>\n";
    $path = parse_url($url, PHP_URL_PATH);
    $htaccessContent .= '
        <IfModule mod_rewrite.c>
        RewriteEngine on
        RewriteBase ' . $path . '
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^([a-zA-Z0-9_-]+)\\.php$ share.php?hash=$1 [QSA]
        RewriteRule ^([a-zA-Z0-9_-]+)--([a-z]+)$ share.php?hash=$1&lang=$2 [QSA]
        RewriteRule ^([a-zA-Z0-9_-]+)$ share.php?hash=$1 [QSA]
        </IfModule>
        ';
    return $htaccessContent;
}
Пример #4
0
 public function doTest()
 {
     $this->testedParams["Users enabled"] = AuthService::usersEnabled();
     $this->testedParams["Guest enabled"] = ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth");
     $this->failedLevel = "info";
     return FALSE;
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     switch ($action) {
         case "get_secure_token":
             HTMLWriter::charsetHeader("text/plain");
             print AuthService::generateSecureToken();
             //exit(0);
             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;
         default:
             break;
     }
     return "";
 }
 public function generateDirectoryIndex($path)
 {
     $html = parent::generateDirectoryIndex($path);
     $html = str_replace("image/vnd.microsoft.icon", "image/png", $html);
     $title = ConfService::getCoreConf("APPLICATION_TITLE");
     $html = preg_replace("/<title>(.*)<\\/title>/i", '<title>' . $title . '</title>', $html);
     $repoString = "</h1>";
     if (!empty($this->repositoryLabel)) {
         $repoString = " - " . $this->repositoryLabel . "</h1><h2>Index of " . $this->escapeHTML($path) . "/</h2>";
     }
     $html = preg_replace("/<h1>(.*)<\\/h1>/i", "<h1>" . $title . $repoString, $html);
     $html = str_replace("h1 { font-size: 150% }", "h1 { font-size: 150% } \n h2 { font-size: 115% }", $html);
     return $html;
 }
 function init($options)
 {
     $this->slaveMode = $options["SLAVE_MODE"] == "true";
     if ($this->slaveMode && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
         // Make sure "login" is disabled, or it will re-appear if GUEST browsing is enabled!
         // OLD WAY : unset($this->actions["login"]);
         // NEW WAY : Modify manifest dynamically (more coplicated...)
         $contribs = $this->xPath->query("registry_contributions/external_file");
         foreach ($contribs as $contribNode) {
             if ($contribNode->getAttribute('filename') == 'plugins/core.auth/standard_auth_actions.xml') {
                 $contribNode->parentNode->removeChild($contribNode);
             }
         }
     }
     parent::init($options);
     $this->usersSerFile = $options["USERS_FILEPATH"];
     $this->secret = $options["SECRET"];
     $this->urls = array($options["LOGIN_URL"], $options["LOGOUT_URL"]);
 }
Пример #8
0
function updateSharePhpFile()
{
    $dlFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER");
    if (is_file($dlFolder . "/share.php")) {
        $loader_content = '<' . '?' . 'php
                    define("AJXP_EXEC", true);
                    require_once("' . str_replace("\\", "/", AJXP_INSTALL_PATH) . '/core/classes/class.AJXP_Utils.php");
                    $hash = AJXP_Utils::securePath(AJXP_Utils::sanitize($_GET["hash"], AJXP_SANITIZE_ALPHANUM));
                    if(file_exists($hash.".php")){
                        require_once($hash.".php");
                    }else{
                        require_once("' . str_replace("\\", "/", AJXP_INSTALL_PATH) . '/publicLet.inc.php");
                        ShareCenter::loadShareByHash($hash);
                    }
                ';
        if (@file_put_contents($dlFolder . "/share.php", $loader_content) === FALSE) {
            echo "Could not rewrite the content of the public folder share.php file. Please remove it and create a new shared link to regenerate this file.";
        }
    }
}
 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;
 }
Пример #10
0
 public function init($options)
 {
     // Migrate new version of the options
     if (isset($options["CMS_TYPE"])) {
         // Transform MASTER_URL + LOGIN_URI to MASTER_HOST, MASTER_URI, LOGIN_URL, LOGOUT_URI
         $options["SLAVE_MODE"] = "false";
         $cmsOpts = $options["CMS_TYPE"];
         if ($cmsOpts["cms"] != "custom") {
             $loginURI = $cmsOpts["LOGIN_URI"];
             if (strpos($cmsOpts["MASTER_URL"], "http") === 0) {
                 $parse = parse_url($cmsOpts["MASTER_URL"]);
                 $rootHost = $parse["host"];
                 $rootURI = $parse["path"];
             } else {
                 $rootHost = "";
                 $rootURI = $cmsOpts["MASTER_URL"];
             }
             $cmsOpts["MASTER_HOST"] = $rootHost;
             $cmsOpts["LOGIN_URL"] = $cmsOpts["MASTER_URI"] = AJXP_Utils::securePath("/" . $rootURI . "/" . $loginURI);
             $logoutAction = $cmsOpts["LOGOUT_ACTION"];
             switch ($cmsOpts["cms"]) {
                 case "wp":
                     $cmsOpts["LOGOUT_URL"] = $logoutAction == "back" ? $cmsOpts["MASTER_URL"] : $cmsOpts["MASTER_URL"] . "/wp-login.php?action=logout";
                     break;
                 case "joomla":
                     $cmsOpts["LOGOUT_URL"] = $cmsOpts["LOGIN_URL"];
                     break;
                 case "drupal":
                     $cmsOpts["LOGOUT_URL"] = $logoutAction == "back" ? $cmsOpts["LOGIN_URL"] : $cmsOpts["MASTER_URL"] . "/user/logout";
                     break;
                 default:
                     break;
             }
         }
         $options = array_merge($options, $cmsOpts);
     }
     $this->slaveMode = $options["SLAVE_MODE"] == "true";
     if ($this->slaveMode && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
         $contribs = $this->xPath->query("registry_contributions/external_file");
         foreach ($contribs as $contribNode) {
             if ($contribNode->getAttribute('filename') == 'plugins/core.auth/standard_auth_actions.xml') {
                 $contribNode->parentNode->removeChild($contribNode);
             }
         }
     }
     parent::init($options);
     $options = $this->options;
     $this->usersSerFile = $options["USERS_FILEPATH"];
     $this->secret = $options["SECRET"];
     $this->urls = array($options["LOGIN_URL"], $options["LOGOUT_URL"]);
 }
Пример #11
0
 public function doTest()
 {
     if (!is_writable(AJXP_CACHE_DIR)) {
         $this->testedParams["Command Line Available"] = "No";
         $this->failedLevel = "warning";
         $this->failedInfo = "Php command line not detected (cache directory not writeable), this is NOT BLOCKING, but enabling it could allow to send some long tasks in background. If you do not have the ability to tweak your server, you can safely ignore this warning.";
         return FALSE;
     }
     $windows = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows";
     $sModeExecDir = ini_get("safe_mode_exec_dir");
     $safeEnabled = ini_get("safe_mode") || !empty($sModeExecDir);
     $disabled_functions = explode(',', ini_get('disable_functions'));
     $fName = $windows ? "popen" : "exec";
     $notFoundFunction = in_array($fName, $disabled_functions) || !function_exists($fName) || !is_callable($fName);
     $comEnabled = class_exists("COM");
     $useCOM = false;
     if ($safeEnabled || $notFoundFunction) {
         if ($comEnabled) {
             $useCOM = true;
         } else {
             $this->testedParams["Command Line Available"] = "No";
             $this->failedLevel = "warning";
             $this->failedInfo = "Php command line not detected (there seem to be some safe_mode or a-like restriction), this is NOT BLOCKING, but enabling it could allow to send some long tasks in background. If you do not have the ability to tweak your server, you can safely ignore this warning.";
             return FALSE;
         }
     }
     $defaultCli = ConfService::getCoreConf("CLI_PHP");
     if ($defaultCli == null) {
         $defaultCli = "php";
     }
     $token = md5(time());
     $robustCacheDir = str_replace("/", DIRECTORY_SEPARATOR, AJXP_CACHE_DIR);
     $logDir = $robustCacheDir . DIRECTORY_SEPARATOR . "cmd_outputs";
     if (!is_dir($logDir)) {
         mkdir($logDir, 0755);
     }
     $logFile = $logDir . "/" . $token . ".out";
     $testScript = AJXP_CACHE_DIR . "/cli_test.php";
     file_put_contents($testScript, "<?php file_put_contents('" . $robustCacheDir . DIRECTORY_SEPARATOR . "cli_result.php', 'cli'); ?>");
     $cmd = $defaultCli . " " . $robustCacheDir . DIRECTORY_SEPARATOR . "cli_test.php";
     if ($windows) {
         /* Next 2 lines modified by rmeske: Need to wrap the folder and file paths in double quotes.  */
         $cmd = $defaultCli . " " . chr(34) . $robustCacheDir . DIRECTORY_SEPARATOR . "cli_test.php" . chr(34);
         $cmd .= " > " . chr(34) . $logFile . chr(34);
         $comCommand = $cmd;
         if ($useCOM) {
             $WshShell = new COM("WScript.Shell");
             $res = $WshShell->Run("cmd /C {$comCommand}", 0, false);
         } else {
             $tmpBat = implode(DIRECTORY_SEPARATOR, array(str_replace("/", DIRECTORY_SEPARATOR, AJXP_INSTALL_PATH), "data", "tmp", md5(time()) . ".bat"));
             $cmd .= "\n DEL " . chr(34) . $tmpBat . chr(34);
             file_put_contents($tmpBat, $cmd);
             /* Following 1 line modified by rmeske: The windows Start command identifies the first parameter in quotes as a title for the window.  Therefore, when enclosing a command with double quotes you must include a window title first
                START	["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME] [/WAIT] [/B] [command / program] [parameters]
                */
             @pclose(@popen('start /b "CLI" "' . $tmpBat . '"', 'r'));
             sleep(1);
             // Failed, but we can try with COM
             if (!is_file(AJXP_CACHE_DIR . "/cli_result.php") && $comEnabled) {
                 $useCOM = true;
                 $WshShell = new COM("WScript.Shell");
                 $res = $WshShell->Run("cmd /C {$comCommand}", 0, false);
             }
         }
     } else {
         new UnixProcess($cmd, $logFile);
     }
     sleep(1);
     $availability = true;
     if (is_file(AJXP_CACHE_DIR . "/cli_result.php")) {
         $this->testedParams["Command Line Available"] = "Yes";
         unlink(AJXP_CACHE_DIR . "/cli_result.php");
         if ($useCOM) {
             $this->failedLevel = "warning";
             $availability = true;
             $this->failedInfo = "Php command line detected, but using the windows COM extension. Just make sure to <b>enable COM</b> in the Pydio Core Options";
         } else {
             $this->failedInfo = "Php command line detected, this will allow to send some tasks in background. Enable it in the Pydio Core Options";
         }
     } else {
         if (is_file($logFile)) {
             $log = file_get_contents($logFile);
             unlink($logFile);
         }
         $this->testedParams["Command Line Available"] = "No : {$log}";
         $this->failedLevel = "warning";
         $this->failedInfo = "Php command line not detected, this is NOT BLOCKING, but enabling it could allow to send some long tasks in background. If you do not have the ability to tweak your server, you can safely ignore this warning.";
         if ($windows) {
             $this->failedInfo .= "<br> On Windows, try to activate the php COM extension, and set correct rights to the cmd exectuble to make it runnable by the web server, this should solve the problem.";
         }
         $availability = false;
     }
     unlink(AJXP_CACHE_DIR . "/cli_test.php");
     return $availability;
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	SWITCH THE ROOT REPOSITORY
         //------------------------------------
         case "switch_repository":
             if (!isset($repository_id)) {
                 break;
             }
             $dirList = ConfService::getRepositoriesList();
             /** @var $repository_id string */
             if (!isset($dirList[$repository_id])) {
                 $errorMessage = "Trying to switch to an unkown repository!";
                 break;
             }
             ConfService::switchRootDir($repository_id);
             // Load try to init the driver now, to trigger an exception
             // if it's not loading right.
             ConfService::loadRepositoryDriver();
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $user = AuthService::getLoggedUser();
                 $activeRepId = ConfService::getCurrentRepositoryId();
                 $user->setArrayPref("history", "last_repository", $activeRepId);
                 $user->save("user");
             }
             //$logMessage = "Successfully Switched!";
             $this->logInfo("Switch Repository", array("rep. id" => $repository_id));
             break;
             //------------------------------------
             //	SEND XML REGISTRY
             //------------------------------------
         //------------------------------------
         //	SEND XML REGISTRY
         //------------------------------------
         case "get_xml_registry":
         case "state":
             $regDoc = AJXP_PluginsService::getXmlRegistry();
             $changes = AJXP_Controller::filterRegistryFromRole($regDoc);
             if ($changes) {
                 AJXP_PluginsService::updateXmlRegistry($regDoc);
             }
             $clone = $regDoc->cloneNode(true);
             $clonePath = new DOMXPath($clone);
             $serverCallbacks = $clonePath->query("//serverCallback|hooks");
             foreach ($serverCallbacks as $callback) {
                 $callback->parentNode->removeChild($callback);
             }
             $xPath = '';
             if (isset($httpVars["xPath"])) {
                 $xPath = ltrim(AJXP_Utils::securePath($httpVars["xPath"]), "/");
             }
             if (!empty($xPath)) {
                 $nodes = $clonePath->query($xPath);
                 if ($httpVars["format"] == "json") {
                     $data = AJXP_XMLWriter::xmlToArray($nodes->item(0));
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($data);
                 } else {
                     AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $xPath));
                     if ($nodes->length) {
                         print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML($nodes->item(0)));
                     }
                     AJXP_XMLWriter::close("ajxp_registry_part");
                 }
             } else {
                 AJXP_Utils::safeIniSet("zlib.output_compression", "4096");
                 if ($httpVars["format"] == "json") {
                     $data = AJXP_XMLWriter::xmlToArray($clone);
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($data);
                 } else {
                     header('Content-Type: application/xml; charset=UTF-8');
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML());
                 }
             }
             break;
             //------------------------------------
             //	BOOKMARK BAR
             //------------------------------------
         //------------------------------------
         //	BOOKMARK BAR
         //------------------------------------
         case "get_bookmarks":
             $bmUser = null;
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser = AuthService::getLoggedUser();
             } else {
                 if (!AuthService::usersEnabled()) {
                     $confStorage = ConfService::getConfStorageImpl();
                     $bmUser = $confStorage->createUserObject("shared");
                 }
             }
             if ($bmUser == null) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::close();
             }
             $driver = ConfService::loadRepositoryDriver();
             if (!is_a($driver, "AjxpWrapperProvider")) {
                 $driver = false;
             }
             if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) {
                 $bmPath = AJXP_Utils::decodeSecureMagic($httpVars["bm_path"]);
                 if ($httpVars["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($httpVars["bm_title"])) {
                         $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]);
                     }
                     if ($title == "" && $bmPath == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark($bmPath, $title);
                     if ($driver) {
                         $node = new AJXP_Node($driver->getResourceUrl($bmPath));
                         $node->setMetadata("ajxp_bookmarked", array("ajxp_bookmarked" => "true"), true, AJXP_METADATA_SCOPE_REPOSITORY, true);
                     }
                 } else {
                     if ($httpVars["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($bmPath);
                         if ($driver) {
                             $node = new AJXP_Node($driver->getResourceUrl($bmPath));
                             $node->removeMetadata("ajxp_bookmarked", true, AJXP_METADATA_SCOPE_REPOSITORY, true);
                         }
                     } else {
                         if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) {
                             $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]);
                             $bmUser->renameBookmark($bmPath, $title);
                         }
                     }
                 }
                 AJXP_Controller::applyHook("msg.instant", array("<reload_bookmarks/>", ConfService::getRepository()->getId()));
                 if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                     $bmUser->save("user");
                     AuthService::updateUser($bmUser);
                 } else {
                     if (!AuthService::usersEnabled()) {
                         $bmUser->save("user");
                     }
                 }
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks(), true, isset($httpVars["format"]) ? $httpVars["format"] : "legacy");
             AJXP_XMLWriter::close();
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "save_user_pref":
             $userObject = AuthService::getLoggedUser();
             $i = 0;
             while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && $userObject == null) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save("user");
                 AuthService::updateUser($userObject);
                 //setcookie("AJXP_$prefName", $prefValue);
                 $i++;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "custom_data_edit":
         case "user_create_user":
             $data = array();
             if ($action == "user_create_user" && isset($httpVars["NEW_new_user_id"])) {
                 $updating = false;
                 AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_");
                 $original_id = AJXP_Utils::decodeSecureMagic($data["new_user_id"]);
                 $data["new_user_id"] = AJXP_Utils::decodeSecureMagic($data["new_user_id"], AJXP_SANITIZE_EMAILCHARS);
                 if ($original_id != $data["new_user_id"]) {
                     throw new Exception(str_replace("%s", $data["new_user_id"], $mess["ajxp_conf.127"]));
                 }
                 if (AuthService::userExists($data["new_user_id"], "w")) {
                     throw new Exception($mess["ajxp_conf.43"]);
                 }
                 $loggedUser = AuthService::getLoggedUser();
                 $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, "");
                 if (!empty($limit) && intval($limit) > 0) {
                     $count = count($this->getUserChildren($loggedUser->getId()));
                     if ($count >= $limit) {
                         throw new Exception($mess['483']);
                     }
                 }
                 AuthService::createUser($data["new_user_id"], $data["new_password"]);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($data["new_user_id"]);
                 $userObject->setParent($loggedUser->getId());
                 $userObject->save('superuser');
                 $userObject->personalRole->clearAcls();
                 $userObject->setGroupPath($loggedUser->getGroupPath());
                 $userObject->setProfile("shared");
             } else {
                 if ($action == "user_create_user" && isset($httpVars["NEW_existing_user_id"])) {
                     $updating = true;
                     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_");
                     $userId = $data["existing_user_id"];
                     if (!AuthService::userExists($userId)) {
                         throw new Exception("Cannot find user");
                     }
                     $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
                     if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) {
                         throw new Exception("Cannot find user");
                     }
                     if (!empty($data["new_password"])) {
                         AuthService::updatePassword($userId, $data["new_password"]);
                     }
                 } else {
                     $updating = false;
                     $userObject = AuthService::getLoggedUser();
                     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "PREFERENCES_");
                 }
             }
             $paramNodes = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'user') and @expose='true']", "node", false, false, true);
             $rChanges = false;
             if (is_array($paramNodes) && count($paramNodes)) {
                 foreach ($paramNodes as $xmlNode) {
                     if ($xmlNode->getAttribute("expose") == "true") {
                         $parentNode = $xmlNode->parentNode->parentNode;
                         $pluginId = $parentNode->getAttribute("id");
                         if (empty($pluginId)) {
                             $pluginId = $parentNode->nodeName . "." . $parentNode->getAttribute("name");
                         }
                         $name = $xmlNode->getAttribute("name");
                         if (isset($data[$name]) || $data[$name] === "") {
                             if ($data[$name] == "__AJXP_VALUE_SET__") {
                                 continue;
                             }
                             if ($data[$name] === "" || $userObject->parentRole == null || $userObject->parentRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name] || $userObject->personalRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name]) {
                                 $userObject->personalRole->setParameterValue($pluginId, $name, $data[$name]);
                                 $rChanges = true;
                             }
                         }
                     }
                 }
             }
             if ($rChanges) {
                 AuthService::updateRole($userObject->personalRole, $userObject);
                 $userObject->recomputeMergedRole();
                 if ($action == "custom_data_edit") {
                     AuthService::updateUser($userObject);
                 }
             }
             if ($action == "user_create_user") {
                 AJXP_Controller::applyHook($updating ? "user.after_update" : "user.after_create", array($userObject));
                 if (isset($data["send_email"]) && $data["send_email"] == true && !empty($data["email"])) {
                     $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer");
                     if ($mailer !== false) {
                         $mess = ConfService::getMessages();
                         $link = AJXP_Utils::detectServerURL();
                         $apptitle = ConfService::getCoreConf("APPLICATION_TITLE");
                         $subject = str_replace("%s", $apptitle, $mess["507"]);
                         $body = str_replace(array("%s", "%link", "%user", "%pass"), array($apptitle, $link, $data["new_user_id"], $data["new_password"]), $mess["508"]);
                         $mailer->sendMail(array($data["email"]), $subject, $body);
                     }
                 }
                 echo "SUCCESS";
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage($mess["241"], null);
                 AJXP_XMLWriter::close();
             }
             break;
         case "user_update_user":
             if (!isset($httpVars["user_id"])) {
                 throw new Exception("invalid arguments");
             }
             $userId = $httpVars["user_id"];
             if (!AuthService::userExists($userId)) {
                 throw new Exception("Cannot find user");
             }
             $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
             if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("Cannot find user");
             }
             $paramsString = ConfService::getCoreConf("NEWUSERS_EDIT_PARAMETERS", "conf");
             $result = array();
             $params = explode(",", $paramsString);
             foreach ($params as $p) {
                 $result[$p] = $userObject->personalRole->filterParameterValue("core.conf", $p, AJXP_REPO_SCOPE_ALL, "");
             }
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($result);
             break;
             //------------------------------------
             // WEBDAV PREFERENCES
             //------------------------------------
         //------------------------------------
         // WEBDAV PREFERENCES
         //------------------------------------
         case "webdav_preferences":
             $userObject = AuthService::getLoggedUser();
             $webdavActive = false;
             $passSet = false;
             $digestSet = false;
             // Detect http/https and host
             if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") {
                 $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST");
             } else {
                 $baseURL = AJXP_Utils::detectServerURL();
             }
             $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/";
             $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
             $digestSet = isset($davData["HA1"]);
             if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) {
                 if (!empty($httpVars["activate"])) {
                     $activate = $httpVars["activate"] == "true" ? true : false;
                     if (empty($davData)) {
                         $davData = array();
                     }
                     $davData["ACTIVE"] = $activate;
                 }
                 if (!empty($httpVars["webdav_pass"])) {
                     $password = $httpVars["webdav_pass"];
                     if (function_exists('mcrypt_encrypt')) {
                         $user = $userObject->getId();
                         $secret = defined("AJXP_SAFE_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#";
                         $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB));
                     }
                     $davData["PASS"] = $password;
                 }
                 $userObject->setPref("AJXP_WEBDAV_DATA", $davData);
                 $userObject->save("user");
             }
             if (!empty($davData)) {
                 $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true;
                 $passSet = isset($davData["PASS"]);
             }
             $repoList = ConfService::getRepositoriesList();
             $davRepos = array();
             $loggedUser = AuthService::getLoggedUser();
             foreach ($repoList as $repoIndex => $repoObject) {
                 $accessType = $repoObject->getAccessType();
                 $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType);
                 if (is_a($driver, "AjxpWrapperProvider") && !$repoObject->getOption("AJXP_WEBDAV_DISABLED") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) {
                     $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug());
                 }
             }
             $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "digest_set" => $digestSet, "webdav_force_basic" => ConfService::getCoreConf("WEBDAV_FORCE_BASIC") === true, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos);
             HTMLWriter::charsetHeader("application/json");
             print json_encode($prefs);
             break;
         case "get_user_template_logo":
             $tplId = $httpVars["template_id"];
             $iconFormat = $httpVars["icon_format"];
             $repo = ConfService::getRepositoryById($tplId);
             $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat));
             if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) {
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo);
             } else {
                 $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png";
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo);
             }
             break;
         case "get_user_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $count = 0;
             $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => 1), $count);
             $pServ = AJXP_PluginsService::getInstance();
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 if (!$repo->getOption("TPL_USER_CAN_CREATE")) {
                     continue;
                 }
                 $repoId = $repo->getId();
                 $repoLabel = $repo->getDisplay();
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 $driverPlug = $pServ->getPluginByTypeName("access", $repoType);
                 $params = $driverPlug->getManifestRawContent("//param", "node");
                 $tplDefined = $repo->getOptionsDefined();
                 $defaultLabel = '';
                 foreach ($params as $paramNode) {
                     $name = $paramNode->getAttribute("name");
                     if (strpos($name, "TPL_") === 0) {
                         if ($name == "TPL_DEFAULT_LABEL") {
                             $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name));
                         }
                         continue;
                     }
                     if (in_array($paramNode->getAttribute("name"), $tplDefined)) {
                         continue;
                     }
                     if ($paramNode->getAttribute('no_templates') == 'true') {
                         continue;
                     }
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode));
                 }
                 // ADD LABEL
                 echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>';
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "user_create_repository":
             $tplId = $httpVars["template_id"];
             $tplRepo = ConfService::getRepositoryById($tplId);
             $options = array();
             AJXP_Utils::parseStandardFormParameters($httpVars, $options);
             $loggedUser = AuthService::getLoggedUser();
             $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, $loggedUser->getId());
             $gPath = $loggedUser->getGroupPath();
             if (!empty($gPath)) {
                 $newRep->setGroupPath($gPath);
             }
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[426]);
             } else {
                 // Make sure we do not overwrite otherwise loaded rights.
                 $loggedUser->load();
                 $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw");
                 $loggedUser->save("superuser");
                 $loggedUser->recomputeMergedRole();
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[425], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "user_delete_repository":
             $repoId = $httpVars["repository_id"];
             $repository = ConfService::getRepositoryById($repoId);
             if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("You are not allowed to perform this operation!");
             }
             $res = ConfService::deleteRepository($repoId);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[427]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 // Make sure we do not override remotely set rights
                 $loggedUser->load();
                 $loggedUser->personalRole->setAcl($repoId, "");
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[428], null);
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "user_delete_user":
             $userId = $httpVars["user_id"];
             $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
             if ($userObject == null || !$userObject->hasParent() || $userObject->getParent() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("You are not allowed to edit this user");
             }
             AuthService::deleteUser($userId);
             echo "SUCCESS";
             break;
         case "user_list_authorized_users":
             $defaultFormat = "html";
             HTMLWriter::charsetHeader();
             if (!ConfService::getAuthDriverImpl()->usersEditable()) {
                 break;
             }
             $loggedUser = AuthService::getLoggedUser();
             $crtValue = $httpVars["value"];
             $usersOnly = isset($httpVars["users_only"]) && $httpVars["users_only"] == "true";
             $existingOnly = isset($httpVars["existing_only"]) && $httpVars["existing_only"] == "true";
             if (!empty($crtValue)) {
                 $regexp = '^' . $crtValue;
             } else {
                 $regexp = null;
             }
             $skipDisplayWithoutRegexp = ConfService::getCoreConf("USERS_LIST_REGEXP_MANDATORY", "conf");
             if ($skipDisplayWithoutRegexp && $regexp == null) {
                 print "<ul></ul>";
                 break;
             }
             $limit = intval(ConfService::getCoreConf("USERS_LIST_COMPLETE_LIMIT", "conf"));
             $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf");
             $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf");
             $baseGroup = "/";
             if ($regexp == null && !$displayAll || $regexp != null && !$searchAll) {
                 $baseGroup = AuthService::filterBaseGroup("/");
             }
             AuthService::setGroupFiltering(false);
             $allUsers = AuthService::listUsers($baseGroup, $regexp, 0, $limit, false);
             if (!$usersOnly) {
                 $allGroups = array();
                 $roleOrGroup = ConfService::getCoreConf("GROUP_OR_ROLE", "conf");
                 $rolePrefix = $excludeString = $includeString = null;
                 if (!is_array($roleOrGroup)) {
                     $roleOrGroup = array("group_switch_value" => $roleOrGroup);
                 }
                 $listRoleType = false;
                 if (isset($roleOrGroup["PREFIX"])) {
                     $rolePrefix = $loggedUser->mergedRole->filterParameterValue("core.conf", "PREFIX", null, $roleOrGroup["PREFIX"]);
                     $excludeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "EXCLUDED", null, $roleOrGroup["EXCLUDED"]);
                     $includeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "INCLUDED", null, $roleOrGroup["INCLUDED"]);
                     $listUserRolesOnly = $loggedUser->mergedRole->filterParameterValue("core.conf", "LIST_ROLE_BY", null, $roleOrGroup["LIST_ROLE_BY"]);
                     if (is_array($listUserRolesOnly) && isset($listUserRolesOnly["group_switch_value"])) {
                         switch ($listUserRolesOnly["group_switch_value"]) {
                             case "userroles":
                                 $listRoleType = true;
                                 break;
                             case "allroles":
                                 $listRoleType = false;
                                 break;
                             default:
                                 break;
                         }
                     }
                 }
                 switch (strtolower($roleOrGroup["group_switch_value"])) {
                     case 'user':
                         // donothing
                         break;
                     case 'group':
                         $authGroups = AuthService::listChildrenGroups($baseGroup);
                         foreach ($authGroups as $gId => $gName) {
                             $allGroups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName;
                         }
                         break;
                     case 'role':
                         $allGroups = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType);
                         break;
                     case 'rolegroup':
                         $groups = array();
                         $authGroups = AuthService::listChildrenGroups($baseGroup);
                         foreach ($authGroups as $gId => $gName) {
                             $groups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName;
                         }
                         $roles = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType);
                         empty($groups) ? $allGroups = $roles : (empty($roles) ? $allGroups = $groups : ($allGroups = array_merge($groups, $roles)));
                         //$allGroups = array_merge($groups, $roles);
                         break;
                     default:
                         break;
                 }
             }
             $users = "";
             $index = 0;
             if ($regexp != null && (!count($allUsers) || !empty($crtValue) && !array_key_exists(strtolower($crtValue), $allUsers)) && ConfService::getCoreConf("USER_CREATE_USERS", "conf") && !$existingOnly) {
                 $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}'><span class='user_entry_label'>{$crtValue} (" . $mess["448"] . ")</span></li>";
             } else {
                 if ($existingOnly && !empty($crtValue)) {
                     $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}' data-entry_id='{$crtValue}'><span class='user_entry_label'>{$crtValue}</span></li>";
                 }
             }
             $mess = ConfService::getMessages();
             if ($regexp == null && !$usersOnly) {
                 $users .= "<li class='complete_group_entry' data-group='AJXP_GRP_/' data-label='" . $mess["447"] . "'><span class='user_entry_label'>" . $mess["447"] . "</span></li>";
             }
             $indexGroup = 0;
             if (!$usersOnly && is_array($allGroups)) {
                 foreach ($allGroups as $groupId => $groupLabel) {
                     if ($regexp == null || preg_match("/{$regexp}/i", $groupLabel)) {
                         $users .= "<li class='complete_group_entry' data-group='{$groupId}' data-label='{$groupLabel}' data-entry_id='{$groupId}'><span class='user_entry_label'>" . $groupLabel . "</span></li>";
                         $indexGroup++;
                     }
                     if ($indexGroup == $limit) {
                         break;
                     }
                 }
             }
             if ($regexp == null && method_exists($this, "listUserTeams")) {
                 $teams = $this->listUserTeams();
                 foreach ($teams as $tId => $tData) {
                     $users .= "<li class='complete_group_entry' data-group='/AJXP_TEAM/{$tId}' data-label='[team] " . $tData["LABEL"] . "'><span class='user_entry_label'>[team] " . $tData["LABEL"] . "</span></li>";
                 }
             }
             foreach ($allUsers as $userId => $userObject) {
                 if ($userObject->getId() == $loggedUser->getId()) {
                     continue;
                 }
                 if (!$userObject->hasParent() && ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") || $userObject->getParent() == $loggedUser->getId()) {
                     $userLabel = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId);
                     //if($regexp != null && ! (preg_match("/$regexp/i", $userId) || preg_match("/$regexp/i", $userLabel)) ) continue;
                     if (empty($userLabel)) {
                         $userLabel = $userId;
                     }
                     $userDisplay = $userLabel == $userId ? $userId : $userLabel . " ({$userId})";
                     if (ConfService::getCoreConf("USERS_LIST_HIDE_LOGIN", "conf") == true && $userLabel != $userId) {
                         $userDisplay = $userLabel;
                     }
                     $users .= "<li class='complete_user_entry' data-label='{$userLabel}' data-entry_id='{$userId}'><span class='user_entry_label'>" . $userDisplay . "</span></li>";
                     $index++;
                 }
                 if ($index == $limit) {
                     break;
                 }
             }
             if (strlen($users)) {
                 print "<ul>" . $users . "</ul>";
             }
             AuthService::setGroupFiltering(true);
             break;
         case "load_repository_info":
             $data = array();
             $repo = ConfService::getRepository();
             if ($repo != null) {
                 $users = AuthService::countUsersForRepository(ConfService::getRepository()->getId(), true);
                 $data["core.users"] = $users;
                 if (isset($httpVars["collect"]) && $httpVars["collect"] == "true") {
                     AJXP_Controller::applyHook("repository.load_info", array(&$data));
                 }
             }
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($data);
             break;
         case "get_binary_param":
             if (isset($httpVars["tmp_file"])) {
                 $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]);
                 if (isset($file)) {
                     header("Content-Type:image/png");
                     readfile($file);
                 }
             } else {
                 if (isset($httpVars["binary_id"])) {
                     if (isset($httpVars["user_id"]) && AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->isAdmin()) {
                         $context = array("USER" => $httpVars["user_id"]);
                     } else {
                         $context = array("USER" => AuthService::getLoggedUser()->getId());
                     }
                     $this->loadBinary($context, $httpVars["binary_id"]);
                 }
             }
             break;
         case "get_global_binary_param":
             if (isset($httpVars["tmp_file"])) {
                 $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]);
                 if (isset($file)) {
                     header("Content-Type:image/png");
                     readfile($file);
                 }
             } else {
                 if (isset($httpVars["binary_id"])) {
                     $this->loadBinary(array(), $httpVars["binary_id"]);
                 }
             }
             break;
         case "store_binary_temp":
             if (count($fileVars)) {
                 $keys = array_keys($fileVars);
                 $boxData = $fileVars[$keys[0]];
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                 } else {
                     $rand = substr(md5(time()), 0, 6);
                     $tmp = $rand . "-" . $boxData["name"];
                     @move_uploaded_file($boxData["tmp_name"], AJXP_Utils::getAjxpTmpDir() . "/" . $tmp);
                 }
             }
             if (isset($tmp) && file_exists(AJXP_Utils::getAjxpTmpDir() . "/" . $tmp)) {
                 print '<script type="text/javascript">';
                 print 'parent.formManagerHiddenIFrameSubmission("' . $tmp . '");';
                 print '</script>';
             }
             break;
         default:
             break;
     }
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if (isset($requireAuth)) {
         $xmlBuffer .= AJXP_XMLWriter::requireAuth(false);
     }
     return $xmlBuffer;
 }
Пример #13
0
 /**
  * @param array $httpVars
  * @param bool $update
  * @return Repository
  * @throws Exception
  */
 protected function createOrLoadSharedRepository($httpVars, &$update)
 {
     if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") {
         $mess = ConfService::getMessages();
         throw new Exception($mess["349"]);
     }
     if (isset($httpVars["repository_id"])) {
         $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]);
         $update = true;
     }
     // CHECK REPO DOES NOT ALREADY EXISTS WITH SAME LABEL
     $label = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_label"]), AJXP_SANITIZE_HTML);
     $description = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_description"]), AJXP_SANITIZE_HTML);
     $exists = $this->checkRepoWithSameLabel($label, isset($editingRepo) ? $editingRepo : null);
     if ($exists) {
         $mess = ConfService::getMessages();
         throw new Exception($mess["share_center.352"]);
     }
     $loggedUser = AuthService::getLoggedUser();
     if (isset($editingRepo)) {
         $this->getShareStore()->testUserCanEditShare($editingRepo->getOwner(), $editingRepo->options);
         $newRepo = $editingRepo;
         $replace = false;
         if ($editingRepo->getDisplay() != $label) {
             $newRepo->setDisplay($label);
             $replace = true;
         }
         if ($editingRepo->getDescription() != $description) {
             $newRepo->setDescription($description);
             $replace = true;
         }
         $newScope = isset($httpVars["share_scope"]) && $httpVars["share_scope"] == "public" ? "public" : "private";
         $oldScope = $editingRepo->getOption("SHARE_ACCESS");
         $currentOwner = $editingRepo->getOwner();
         if ($newScope != $oldScope && $currentOwner != AuthService::getLoggedUser()->getId()) {
             $mess = ConfService::getMessages();
             throw new Exception($mess["share_center.224"]);
         }
         if ($newScope !== $oldScope) {
             $editingRepo->addOption("SHARE_ACCESS", $newScope);
             $replace = true;
         }
         if (isset($httpVars["transfer_owner"])) {
             $newOwner = $httpVars["transfer_owner"];
             if ($newOwner != $currentOwner && $currentOwner != AuthService::getLoggedUser()->getId()) {
                 $mess = ConfService::getMessages();
                 throw new Exception($mess["share_center.224"]);
             }
             $editingRepo->setOwnerData($editingRepo->getParentId(), $newOwner, $editingRepo->getUniqueUser());
             $replace = true;
         }
         if ($replace) {
             ConfService::replaceRepository($newRepo->getId(), $newRepo);
         }
     } else {
         $options = $this->accessDriver->makeSharedRepositoryOptions($httpVars, $this->repository);
         // TMP TESTS
         $options["SHARE_ACCESS"] = $httpVars["share_scope"];
         $newRepo = $this->repository->createSharedChild($label, $options, $this->repository->getId(), $loggedUser->getId(), null);
         $gPath = $loggedUser->getGroupPath();
         if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
             $newRepo->setGroupPath($gPath);
         }
         $newRepo->setDescription($description);
         // Smells like dirty hack!
         $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
         if (isset($httpVars["filter_nodes"])) {
             $newRepo->setContentFilter(new ContentFilter($httpVars["filter_nodes"]));
         }
         ConfService::addRepository($newRepo);
     }
     return $newRepo;
 }
Пример #14
0
 /**
  * Dynamically replace XML keywords with their live values.
  * AJXP_SERVER_ACCESS, AJXP_MIMES_*,AJXP_ALL_MESSAGES, etc.
  * @static
  * @param string $xml
  * @param bool $stripSpaces
  * @return mixed
  */
 public static function replaceAjxpXmlKeywords($xml, $stripSpaces = false)
 {
     $messages = ConfService::getMessages();
     $confMessages = ConfService::getMessagesConf();
     $matches = array();
     if (isset($_SESSION["AJXP_SERVER_PREFIX_URI"])) {
         //$xml = str_replace("AJXP_THEME_FOLDER", $_SESSION["AJXP_SERVER_PREFIX_URI"].AJXP_THEME_FOLDER, $xml);
         $xml = str_replace("AJXP_SERVER_ACCESS", $_SESSION["AJXP_SERVER_PREFIX_URI"] . AJXP_SERVER_ACCESS, $xml);
     } else {
         //$xml = str_replace("AJXP_THEME_FOLDER", AJXP_THEME_FOLDER, $xml);
         $xml = str_replace("AJXP_SERVER_ACCESS", AJXP_SERVER_ACCESS, $xml);
     }
     $xml = str_replace("AJXP_APPLICATION_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $xml);
     $xml = str_replace("AJXP_MIMES_EDITABLE", AJXP_Utils::getAjxpMimes("editable"), $xml);
     $xml = str_replace("AJXP_MIMES_IMAGE", AJXP_Utils::getAjxpMimes("image"), $xml);
     $xml = str_replace("AJXP_MIMES_AUDIO", AJXP_Utils::getAjxpMimes("audio"), $xml);
     $xml = str_replace("AJXP_MIMES_ZIP", AJXP_Utils::getAjxpMimes("zip"), $xml);
     $authDriver = ConfService::getAuthDriverImpl();
     if ($authDriver != NULL) {
         $loginRedirect = $authDriver->getLoginRedirect();
         $xml = str_replace("AJXP_LOGIN_REDIRECT", $loginRedirect !== false ? "'" . $loginRedirect . "'" : "false", $xml);
     }
     $xml = str_replace("AJXP_REMOTE_AUTH", "false", $xml);
     $xml = str_replace("AJXP_NOT_REMOTE_AUTH", "true", $xml);
     $xml = str_replace("AJXP_ALL_MESSAGES", "MessageHash=" . json_encode(ConfService::getMessages()) . ";", $xml);
     if (preg_match_all("/AJXP_MESSAGE(\\[.*?\\])/", $xml, $matches, PREG_SET_ORDER)) {
         foreach ($matches as $match) {
             $messId = str_replace("]", "", str_replace("[", "", $match[1]));
             $xml = str_replace("AJXP_MESSAGE[{$messId}]", $messages[$messId], $xml);
         }
     }
     if (preg_match_all("/CONF_MESSAGE(\\[.*?\\])/", $xml, $matches, PREG_SET_ORDER)) {
         foreach ($matches as $match) {
             $messId = str_replace(array("[", "]"), "", $match[1]);
             $message = $messId;
             if (array_key_exists($messId, $confMessages)) {
                 $message = $confMessages[$messId];
             }
             $xml = str_replace("CONF_MESSAGE[{$messId}]", AJXP_Utils::xmlEntities($message), $xml);
         }
     }
     if (preg_match_all("/MIXIN_MESSAGE(\\[.*?\\])/", $xml, $matches, PREG_SET_ORDER)) {
         foreach ($matches as $match) {
             $messId = str_replace(array("[", "]"), "", $match[1]);
             $message = $messId;
             if (array_key_exists($messId, $confMessages)) {
                 $message = $confMessages[$messId];
             }
             $xml = str_replace("MIXIN_MESSAGE[{$messId}]", AJXP_Utils::xmlEntities($message), $xml);
         }
     }
     if ($stripSpaces) {
         $xml = preg_replace("/[\n\r]?/", "", $xml);
         $xml = preg_replace("/\t/", " ", $xml);
     }
     $xml = str_replace(array('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', 'xsi:noNamespaceSchemaLocation="file:../core.ajaxplorer/ajxp_registry.xsd"'), "", $xml);
     $tab = array(&$xml);
     AJXP_Controller::applyIncludeHook("xml.filter", $tab);
     return $xml;
 }
 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;
 }
Пример #16
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));
     }
 }
Пример #17
0
 /**
  * @param Repository $repository
  * @return string
  */
 public static function getWorkspaceShortcutURL($repository)
 {
     $repoSlug = $repository->getSlug();
     $skipHistory = ConfService::getCoreConf("SKIP_USER_HISTORY", "conf");
     if ($skipHistory) {
         $prefix = "/ws-";
     } else {
         $prefix = "?goto=";
     }
     return trim(self::detectServerURL(true), "/") . $prefix . $repoSlug;
 }
Пример #18
0
    ?>
</h1>
            <a class="button_link" href="?dl=true" style="position: relative;display: block;height: 200px;width: 203px;margin: 0 auto;">
                <?php 
    if (!empty($CUSTOM_SHAREPAGE_BUTTON)) {
        echo '<img src="' . $CUSTOM_SHAREPAGE_BUTTON . '" >';
    } else {
        ?>
                <img src="dl.png">
            <?php 
    }
    ?>
            </a>
            <h2 class="legend"><?php 
    if (!empty($CUSTOM_SHAREPAGE_LEGEND)) {
        echo str_replace(array("AJXP_APPLICATION_TITLE", "AJXP_FILENAME"), array(ConfService::getCoreConf("APPLICATION_TITLE"), $AJXP_LINK_BASENAME), $CUSTOM_SHAREPAGE_LEGEND);
    } else {
        echo sprintf($messages[2], $AJXP_LINK_BASENAME);
    }
    ?>
</h2>
        </div>
    <?php 
}
?>

    <script type="text/javascript">
            var backgrounds = [];
    <?php 
$index = 1;
$varBase = "CUSTOM_SHAREPAGE_BACKGROUND_";
Пример #19
0
 public function switchAction($action, $httpVars, $postProcessData)
 {
     switch ($action) {
         //------------------------------------
         // SHARING FILE OR FOLDER
         //------------------------------------
         case "scheduler_runAll":
             $tasks = AJXP_Utils::loadSerialFile($this->getDbFile(), false, "json");
             $message = "";
             $startRunning = $this->countCurrentlyRunning();
             $statuses = array();
             foreach ($tasks as $index => $task) {
                 $tasks[$index]["status"] = $this->getTaskStatus($task["task_id"]);
             }
             usort($tasks, array($this, "sortTasksByPriorityStatus"));
             foreach ($tasks as $task) {
                 if (isset($task["task_id"])) {
                     $res = $this->runTask($task["task_id"], $task["status"], $startRunning);
                     if ($res) {
                         $message .= "Running " . $task["label"] . " \n ";
                     }
                 }
             }
             if (empty($message)) {
                 $message = "Nothing to do";
             }
             if (ConfService::currentContextIsCommandLine()) {
                 print date("Y-m-d H:i:s") . "\t" . $message . "\n";
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage($message, null);
                 AJXP_XMLWriter::reloadDataNode();
                 AJXP_XMLWriter::close();
             }
             break;
         case "scheduler_runTask":
             $err = -1;
             $this->runTask($httpVars["task_id"], null, $err, true);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "scheduler_generateCronExpression":
             $phpCmd = ConfService::getCoreConf("CLI_PHP");
             $rootInstall = AJXP_INSTALL_PATH . DIRECTORY_SEPARATOR . "cmd.php";
             $logFile = AJXP_CACHE_DIR . DIRECTORY_SEPARATOR . "cmd_outputs" . DIRECTORY_SEPARATOR . "cron_commands.log";
             $cronTiming = "*/5 * * * *";
             HTMLWriter::charsetHeader("text/plain", "UTF-8");
             print "{$cronTiming} {$phpCmd} {$rootInstall} -r=ajxp_conf -u=" . AuthService::getLoggedUser()->getId() . " -p=YOUR_PASSWORD_HERE -a=scheduler_runAll >> {$logFile}";
             break;
         default:
             break;
     }
 }
 public function processUserAccessPoint($action, $httpVars, $fileVars)
 {
     switch ($action) {
         case "user_access_point":
             $setUrl = ConfService::getCoreConf("SERVER_URL");
             $realUri = "/";
             if (!empty($setUrl)) {
                 $realUri = parse_url(ConfService::getCoreConf("SERVER_URL"), PHP_URL_PATH);
             }
             $requestURI = str_replace("//", "/", $_SERVER["REQUEST_URI"]);
             $uri = trim(str_replace(rtrim($realUri, "/") . "/user", "", $requestURI), "/");
             $uriParts = explode("/", $uri);
             $action = array_shift($uriParts);
             try {
                 $this->processSubAction($action, $uriParts);
                 $_SESSION['OVERRIDE_GUI_START_PARAMETERS'] = array("REBASE" => "../../", "USER_GUI_ACTION" => $action);
             } catch (Exception $e) {
                 $_SESSION['OVERRIDE_GUI_START_PARAMETERS'] = array("ALERT" => $e->getMessage());
             }
             AJXP_Controller::findActionAndApply("get_boot_gui", array(), array());
             unset($_SESSION['OVERRIDE_GUI_START_PARAMETERS']);
             break;
         case "reset-password-ask":
             // This is a reset password request, generate a token and store it.
             // Find user by id
             if (AuthService::userExists($httpVars["email"])) {
                 // Send email
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($httpVars["email"]);
                 $email = $userObject->personalRole->filterParameterValue("core.conf", "email", AJXP_REPO_SCOPE_ALL, "");
                 if (!empty($email)) {
                     $uuid = AJXP_Utils::generateRandomString(48);
                     ConfService::getConfStorageImpl()->saveTemporaryKey("password-reset", $uuid, AJXP_Utils::decodeSecureMagic($httpVars["email"]), array());
                     $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer");
                     if ($mailer !== false) {
                         $mess = ConfService::getMessages();
                         $link = AJXP_Utils::detectServerURL() . "/user/reset-password/" . $uuid;
                         $mailer->sendMail(array($email), $mess["gui.user.1"], $mess["gui.user.7"] . "<a href=\"{$link}\">{$link}</a>");
                     } else {
                         echo 'ERROR: There is no mailer configured, please contact your administrator';
                     }
                 }
             }
             // Prune existing expired tokens
             ConfService::getConfStorageImpl()->pruneTemporaryKeys("password-reset", 20);
             echo "SUCCESS";
             break;
         case "reset-password":
             ConfService::getConfStorageImpl()->pruneTemporaryKeys("password-reset", 20);
             // This is a reset password
             if (isset($httpVars["key"]) && isset($httpVars["user_id"])) {
                 $key = ConfService::getConfStorageImpl()->loadTemporaryKey("password-reset", $httpVars["key"]);
                 ConfService::getConfStorageImpl()->deleteTemporaryKey("password-reset", $httpVars["key"]);
                 $uId = $httpVars["user_id"];
                 if (AuthService::ignoreUserCase()) {
                     $uId = strtolower($uId);
                 }
                 if ($key != null && strtolower($key["user_id"]) == $uId && AuthService::userExists($uId)) {
                     AuthService::updatePassword($key["user_id"], $httpVars["new_pass"]);
                 } else {
                     echo 'PASS_ERROR';
                     break;
                 }
             }
             AuthService::disconnect();
             echo 'SUCCESS';
             break;
         default:
             break;
     }
 }
Пример #21
0
 /**
  * @param $cmd
  * @param $logFile
  * @return UnixProcess|null
  */
 public static function runCommandInBackground($cmd, $logFile)
 {
     if (PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows") {
         if (AJXP_SERVER_DEBUG) {
             $cmd .= " > " . $logFile;
         }
         if (class_exists("COM") && ConfService::getCoreConf("CLI_USE_COM")) {
             $WshShell = new COM("WScript.Shell");
             $oExec = $WshShell->Run("cmd /C {$cmd}", 0, false);
         } else {
             $basePath = str_replace("/", DIRECTORY_SEPARATOR, AJXP_INSTALL_PATH);
             $tmpBat = implode(DIRECTORY_SEPARATOR, array($basePath, "data", "tmp", md5(time()) . ".bat"));
             $cmd = "@chcp 1252 > nul \r\n" . $cmd;
             $cmd .= "\n DEL " . chr(34) . $tmpBat . chr(34);
             AJXP_Logger::debug("Writing file {$cmd} to {$tmpBat}");
             file_put_contents($tmpBat, $cmd);
             pclose(popen('start /b "CLI" "' . $tmpBat . '"', 'r'));
         }
     } else {
         $process = new UnixProcess($cmd, AJXP_SERVER_DEBUG ? $logFile : null);
         AJXP_Logger::debug("Starting process and sending output dev null");
         return $process;
     }
 }
Пример #22
0
 /**
  * Check if users are allowed to create ZIP archive
  * @static
  * @return bool
  */
 public static function zipCreationEnabled()
 {
     if (!self::zipEnabled()) {
         return false;
     }
     return ConfService::getCoreConf("ZIP_CREATION");
 }
Пример #23
0
}
//------------------------------------------------------------
// SPECIAL HANDLING FOR FANCY UPLOADER RIGHTS FOR THIS ACTION
//------------------------------------------------------------
if (AuthService::usersEnabled()) {
    $loggedUser = AuthService::getLoggedUser();
    if ($action == "upload" && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRepositoryId() . "")) && isset($_FILES['Filedata'])) {
        header('HTTP/1.0 ' . '410 Not authorized');
        die('Error 410 Not authorized!');
    }
}
// THIS FIRST DRIVERS DO NOT NEED ID CHECK
//$ajxpDriver = AJXP_PluginsService::findPlugin("gui", "ajax");
$authDriver = ConfService::getAuthDriverImpl();
// DRIVERS BELOW NEED IDENTIFICATION CHECK
if (!AuthService::usersEnabled() || ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") || AuthService::getLoggedUser() != null) {
    $confDriver = ConfService::getConfStorageImpl();
    $Driver = ConfService::loadRepositoryDriver();
}
AJXP_PluginsService::getInstance()->initActivePlugins();
require_once AJXP_BIN_FOLDER . "/class.AJXP_Controller.php";
$xmlResult = AJXP_Controller::findActionAndApply($action, array_merge($_GET, $_POST), $_FILES);
if ($xmlResult !== false && $xmlResult != "") {
    AJXP_XMLWriter::header();
    print $xmlResult;
    AJXP_XMLWriter::close();
} else {
    if (isset($requireAuth) && AJXP_Controller::$lastActionNeedsAuth) {
        AJXP_XMLWriter::header();
        AJXP_XMLWriter::requireAuth();
        AJXP_XMLWriter::close();
Пример #24
0
 public function switchWebSocketOn($params)
 {
     $wDir = $this->getPluginWorkDir(true);
     $pidFile = $wDir . DIRECTORY_SEPARATOR . "ws-pid";
     if (file_exists($pidFile)) {
         $pId = file_get_contents($pidFile);
         $unixProcess = new UnixProcess();
         $unixProcess->setPid($pId);
         $status = $unixProcess->status();
         if ($status) {
             throw new Exception("Web Socket server seems to already be running!");
         }
     }
     $host = escapeshellarg($params["WS_SERVER_BIND_HOST"]);
     $port = escapeshellarg($params["WS_SERVER_BIND_PORT"]);
     $path = escapeshellarg($params["WS_SERVER_PATH"]);
     $cmd = ConfService::getCoreConf("CLI_PHP") . " ws-server.php -host=" . $host . " -port=" . $port . " -path=" . $path;
     chdir(AJXP_INSTALL_PATH . DIRECTORY_SEPARATOR . AJXP_PLUGINS_FOLDER . DIRECTORY_SEPARATOR . "core.mq");
     $process = AJXP_Controller::runCommandInBackground($cmd, null);
     if ($process != null) {
         $pId = $process->getPid();
         $wDir = $this->getPluginWorkDir(true);
         file_put_contents($wDir . DIRECTORY_SEPARATOR . "ws-pid", $pId);
         return "SUCCESS: Started WebSocket Server with process ID {$pId}";
     }
     return "SUCCESS: Started WebSocket Server";
 }
 public function postProcess($action, $httpVars, $postProcessData)
 {
     if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) {
         return;
     }
     /* If set resumeFileId and resumePartitionIndex, cross-session resume is requested. */
     if (isset($httpVars["resumeFileId"]) && isset($httpVars["resumePartitionIndex"])) {
         header("HTTP/1.1 200 OK");
         print "fileId: " . $httpVars["resumeFileId"] . "\n";
         print "partitionIndex: " . $httpVars["resumePartitionIndex"];
         return;
     }
     /*if (self::$skipDecoding) {
     
             }*/
     if (isset($postProcessData["processor_result"]["ERROR"])) {
         if (isset($httpVars["lastPartition"]) && isset($httpVars["partitionCount"])) {
             /* we get the stream url (where all the partitions have been uploaded so far) */
             $repository = ConfService::getRepository();
             $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
             $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
             $streamData = $plugin->detectStreamWrapper(true);
             $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
             if ($httpVars["partitionCount"] > 1) {
                 /* we fetch the information that help us to construct the temp files name */
                 $fileId = $httpVars["fileId"];
                 $fileHash = md5($httpVars["fileName"]);
                 /* deletion of all the partitions that have been uploaded */
                 for ($i = 0; $i < $httpVars["partitionCount"]; $i++) {
                     if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) {
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
             } else {
                 $fileName = $httpVars["fileName"];
                 unlink($destStreamURL . $fileName);
             }
         }
         echo "Error: " . $postProcessData["processor_result"]["ERROR"]["MESSAGE"];
         return;
     }
     if (!isset($httpVars["partitionRealName"]) && !isset($httpVars["lastPartition"])) {
         return;
     }
     $repository = ConfService::getRepository();
     $driver = ConfService::loadDriverForRepository($repository);
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     if ($httpVars["lastPartition"]) {
         $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
         $streamData = $plugin->detectStreamWrapper(true);
         $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
         $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
         /* we check if the current file has a relative path (aka we want to upload an entire directory) */
         $this->logDebug("Now dispatching relativePath dest:", $httpVars["relativePath"]);
         $subs = explode("/", $httpVars["relativePath"]);
         $userfile_name = array_pop($subs);
         $folderForbidden = false;
         $all_in_place = true;
         $partitions_length = 0;
         $fileId = $httpVars["fileId"];
         $fileHash = md5($userfile_name);
         $partitionCount = $httpVars["partitionCount"];
         $fileLength = $_POST["fileLength"];
         /*
          *
          * Now, we supposed that access driver has already saved uploaded file in to
          * folderServer with file name is md5 relativePath value.
          * We try to copy this file to right location in recovery his name.
          *
          */
         $userfile_name = md5($httpVars["relativePath"]);
         if (self::$remote) {
             $partitions = array();
             $newPartitions = array();
             $index_first_partition = -1;
             $i = 0;
             do {
                 $currentFileName = $driver->getFileNameToCopy();
                 $partitions[] = $driver->getNextFileToCopy();
                 if ($index_first_partition < 0 && strstr($currentFileName, $fileHash) != false) {
                     $index_first_partition = $i;
                 } else {
                     if ($index_first_partition < 0) {
                         $newPartitions[] = array_pop($partitions);
                     }
                 }
             } while ($driver->hasFilesToCopy());
         }
         /* if partitionned */
         if ($partitionCount > 1) {
             if (self::$remote) {
                 for ($i = 0; $all_in_place && $i < $partitionCount; $i++) {
                     $partition_file = "{$fileHash}.{$fileId}.{$i}";
                     if (strstr($partitions[$i]["name"], $partition_file) != false) {
                         $partitions_length += filesize($partitions[$i]["tmp_name"]);
                     } else {
                         $all_in_place = false;
                     }
                 }
             } else {
                 for ($i = 0; $all_in_place && $i < $partitionCount; $i++) {
                     $partition_file = $destStreamURL . "{$fileHash}.{$fileId}.{$i}";
                     if (file_exists($partition_file)) {
                         $partitions_length += filesize($partition_file);
                     } else {
                         $all_in_place = false;
                     }
                 }
             }
         } else {
             if (self::$remote) {
                 if (strstr($newPartitions[count($newPartitions) - 1]["name"], $userfile_name) != false) {
                     $partitions_length += filesize($newPartitions[count($newPartitions) - 1]["tmp_name"]);
                 }
             } else {
                 if (file_exists($destStreamURL . $userfile_name)) {
                     $partitions_length += filesize($destStreamURL . $userfile_name);
                 }
             }
         }
         if (!$all_in_place || $partitions_length != floatval($fileLength)) {
             echo "Error: Upload validation error!";
             /* we delete all the uploaded partitions */
             if ($httpVars["partitionCount"] > 1) {
                 for ($i = 0; $i < $partitionCount; $i++) {
                     if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) {
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
             } else {
                 $fileName = $httpVars["partitionRealName"];
                 unlink($destStreamURL . $fileName);
             }
             return;
         }
         if (count($subs) > 0 && !self::$remote) {
             $curDir = "";
             if (substr($curDir, -1) == "/") {
                 $curDir = substr($curDir, 0, -1);
             }
             // Create the folder tree as necessary
             foreach ($subs as $key => $spath) {
                 $messtmp = "";
                 $dirname = AJXP_Utils::decodeSecureMagic($spath, AJXP_SANITIZE_FILENAME);
                 $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
                 //$this->filterUserSelectionToHidden(array($dirname));
                 if (AJXP_Utils::isHidden($dirname)) {
                     $folderForbidden = true;
                     break;
                 }
                 if (file_exists($destStreamURL . "{$curDir}/{$dirname}")) {
                     // if the folder exists, traverse
                     $this->logDebug("{$curDir}/{$dirname} existing, traversing for {$userfile_name} out of", $httpVars["relativePath"]);
                     $curDir .= "/" . $dirname;
                     continue;
                 }
                 $this->logDebug($destStreamURL . $curDir);
                 $dirMode = 0775;
                 $chmodValue = $repository->getOption("CHMOD_VALUE");
                 if (isset($chmodValue) && $chmodValue != "") {
                     $dirMode = octdec(ltrim($chmodValue, "0"));
                     if ($dirMode & 0400) {
                         $dirMode |= 0100;
                     }
                     // Owner is allowed to read, allow to list the directory
                     if ($dirMode & 040) {
                         $dirMode |= 010;
                     }
                     // Group is allowed to read, allow to list the directory
                     if ($dirMode & 04) {
                         $dirMode |= 01;
                     }
                     // Other are allowed to read, allow to list the directory
                 }
                 $url = $destStreamURL . $curDir . "/" . $dirname;
                 $old = umask(0);
                 mkdir($url, $dirMode);
                 umask($old);
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($url), false));
                 $curDir .= "/" . $dirname;
             }
         }
         if (!$folderForbidden) {
             $fileId = $httpVars["fileId"];
             $this->logDebug("Should now rebuild file!", $httpVars);
             // Now move the final file to the right folder
             // Currently the file is at the base of the current
             $this->logDebug("PartitionRealName", $destStreamURL . $httpVars["partitionRealName"]);
             // Get file by name (md5 value)
             $relPath_md5 = AJXP_Utils::decodeSecureMagic(md5($httpVars["relativePath"]));
             // original file name
             $relPath = AJXP_Utils::decodeSecureMagic($httpVars["relativePath"]);
             $target = $destStreamURL;
             $target .= self::$remote ? basename($relPath) : $relPath;
             /*
              *   $current is uploaded file with md5 value as his name
              *   we copy to $relPath and delete md5 file
              */
             $current = $destStreamURL . basename($relPath_md5);
             if ($httpVars["partitionCount"] > 1) {
                 if (self::$remote) {
                     $test = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"];
                     $newDest = fopen(AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"], "w");
                     $newFile = array();
                     $length = 0;
                     for ($i = 0, $count = count($partitions); $i < $count; $i++) {
                         $currentFile = $partitions[$i];
                         $currentFileName = $currentFile["tmp_name"];
                         $part = fopen($currentFileName, "r");
                         while (!feof($part)) {
                             $length += fwrite($newDest, fread($part, 4096));
                         }
                         fclose($part);
                         unlink($currentFileName);
                     }
                     $newFile["type"] = $partitions[0]["type"];
                     $newFile["name"] = $httpVars["partitionRealName"];
                     $newFile["error"] = 0;
                     $newFile["size"] = $length;
                     $newFile["tmp_name"] = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"];
                     $newFile["destination"] = $partitions[0]["destination"];
                     $newPartitions[] = $newFile;
                 } else {
                     $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w");
                     $fileHash = md5($httpVars["partitionRealName"]);
                     for ($i = 0; $i < $httpVars["partitionCount"]; $i++) {
                         $part = fopen($destStreamURL . "{$fileHash}.{$fileId}.{$i}", "r");
                         while (!feof($part)) {
                             fwrite($newDest, fread($part, 4096));
                         }
                         fclose($part);
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
                 fclose($newDest);
             }
             if (!self::$remote && (!self::$wrapperIsRemote || $relPath != $httpVars["partitionRealName"])) {
                 $err = copy($current, $target);
             } else {
                 for ($i = 0, $count = count($newPartitions); $i < $count; $i++) {
                     $driver->storeFileToCopy($newPartitions[$i]);
                 }
             }
             if ($err !== false) {
                 if (!self::$remote) {
                     unlink($current);
                 }
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false));
             } else {
                 if ($current == $target) {
                     AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false));
                 }
             }
         } else {
             // Remove the file, as it should not have been uploaded!
             //if(!self::$remote) unlink($current);
         }
     }
 }
 /**
  * Call the auth driver impl to list all existing users
  * @static
  * @return array
  */
 static function listUsers($regexp = null, $offset = -1, $limit = -1, $cleanLosts = true)
 {
     $authDriver = ConfService::getAuthDriverImpl();
     $confDriver = ConfService::getConfStorageImpl();
     $allUsers = array();
     $paginated = false;
     if (($regexp != null || $offset != -1 || $limit != -1) && $authDriver->supportsUsersPagination()) {
         $users = $authDriver->listUsersPaginated($regexp, $offset, $limit);
         $paginated = true;
     } else {
         $users = $authDriver->listUsers();
     }
     foreach (array_keys($users) as $userId) {
         if ($userId == "guest" && !ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") || $userId == "ajxp.admin.users" || $userId == "") {
             continue;
         }
         if ($regexp != null && !$authDriver->supportsUsersPagination() && !preg_match($regexp, $userId)) {
             continue;
         }
         $allUsers[$userId] = $confDriver->createUserObject($userId);
         if ($paginated) {
             // Make sure to reload all children objects
             foreach ($confDriver->getUserChildren($userId) as $childObject) {
                 $allUsers[$childObject->getId()] = $childObject;
             }
         }
     }
     if ($paginated && $cleanLosts) {
         // Remove 'lost' items (children without parents).
         foreach ($allUsers as $id => $object) {
             if ($object->hasParent() && !array_key_exists($object->getParent(), $allUsers)) {
                 unset($allUsers[$id]);
             }
         }
     }
     return $allUsers;
 }
Пример #27
0
 /**
  * @param ShareCenter $shareCenter
  * @param ShareStore $shareStore
  * @param ShareRightsManager $shareRightManager
  */
 public static function migrateLegacyMeta($shareCenter, $shareStore, $shareRightManager, $dryRun = true)
 {
     $metaStoreDir = AJXP_DATA_PATH . "/plugins/metastore.serial";
     $publicFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER");
     $metastores = glob($metaStoreDir . "/ajxp_meta_0");
     if ($dryRun) {
         print "RUNNING A DRY RUN FOR META MIGRATION";
     }
     foreach ($metastores as $store) {
         if (strpos($store, ".bak") !== false) {
             continue;
         }
         // Backup store
         if (!$dryRun) {
             copy($store, $store . ".bak");
         }
         $data = unserialize(file_get_contents($store));
         foreach ($data as $filePath => &$metadata) {
             foreach ($metadata as $userName => &$meta) {
                 if (!AuthService::userExists($userName)) {
                     continue;
                 }
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($userName);
                 if (isset($meta["ajxp_shared"]) && isset($meta["ajxp_shared"]["element"])) {
                     print "\n\nItem {$filePath} requires upgrade :";
                     $share = $meta["ajxp_shared"];
                     $element = $meta["ajxp_shared"]["element"];
                     if (is_array($element)) {
                         $element = array_shift(array_keys($element));
                     }
                     // Take the first one only
                     $legacyLinkFile = $publicFolder . "/" . $element . ".php";
                     if (file_exists($legacyLinkFile)) {
                         // Load file, move it to DB and move the meta
                         $publiclet = $shareStore->loadShare($element);
                         rename($legacyLinkFile, $legacyLinkFile . ".migrated");
                         if (isset($share["minisite"])) {
                             print "\n--Migrate legacy minisite to new minisite?";
                             try {
                                 $sharedRepoId = $publiclet["REPOSITORY"];
                                 $sharedRepo = ConfService::getRepositoryById($sharedRepoId);
                                 if ($sharedRepo == null) {
                                     print "\n--ERROR: Cannot find repository with id " . $sharedRepoId;
                                     continue;
                                 }
                                 $shareLink = new ShareLink($shareStore, $publiclet);
                                 $user = $shareLink->getUniqueUser();
                                 if (AuthService::userExists($user)) {
                                     $userObject = ConfService::getConfStorageImpl()->createUserObject($user);
                                     $userObject->setHidden(true);
                                     print "\n--Should set existing user {$user} as hidden";
                                     if (!$dryRun) {
                                         $userObject->save();
                                     }
                                 }
                                 $shareLink->parseHttpVars(["custom_handle" => $element]);
                                 $shareLink->setParentRepositoryId($sharedRepo->getParentId());
                                 print "\n--Creating the following share object";
                                 print_r($shareLink->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $shareLink->save();
                                 }
                                 $meta["ajxp_shared"] = ["shares" => [$element => ["type" => "minisite"], $sharedRepoId => ["type" => "repository"]]];
                             } catch (Exception $e) {
                                 print "\n-- Error " . $e->getMessage();
                             }
                         } else {
                             print "\n--Should migrate legacy link to new minisite with ContentFilter";
                             try {
                                 $link = new ShareLink($shareStore);
                                 $link->setOwnerId($userName);
                                 $parameters = array("custom_handle" => $element, "simple_right_download" => true);
                                 if (isset($publiclet["EXPIRE_TIME"])) {
                                     $parameters["expiration"] = $publiclet["EXPIRE_TIME"];
                                 }
                                 if (isset($publiclet["DOWNLOAD_LIMIT"])) {
                                     $parameters["downloadlimit"] = $publiclet["DOWNLOAD_LIMIT"];
                                 }
                                 $link->parseHttpVars($parameters);
                                 $parentRepositoryObject = $publiclet["REPOSITORY"];
                                 $driverInstance = AJXP_PluginsService::findPlugin("access", $parentRepositoryObject->getAccessType());
                                 if (empty($driverInstance)) {
                                     print "\n-- ERROR: Cannot find driver instance!";
                                     continue;
                                 }
                                 $options = $driverInstance->makeSharedRepositoryOptions(["file" => "/"], $parentRepositoryObject);
                                 $options["SHARE_ACCESS"] = "private";
                                 $newRepo = $parentRepositoryObject->createSharedChild(basename($filePath), $options, $parentRepositoryObject->getId(), $userObject->getId(), null);
                                 $gPath = $userObject->getGroupPath();
                                 if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
                                     $newRepo->setGroupPath($gPath);
                                 }
                                 $newRepo->setDescription("");
                                 // Smells like dirty hack!
                                 $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
                                 $newRepo->setContentFilter(new ContentFilter([new AJXP_Node("pydio://" . $parentRepositoryObject->getId() . $filePath)]));
                                 if (!$dryRun) {
                                     ConfService::addRepository($newRepo);
                                 }
                                 $hiddenUserEntry = $shareRightManager->prepareSharedUserEntry(["simple_right_read" => true, "simple_right_download" => true], $link, false, null);
                                 $selection = new UserSelection($parentRepositoryObject, []);
                                 $selection->addFile($filePath);
                                 if (!$dryRun) {
                                     $shareRightManager->assignSharedRepositoryPermissions($parentRepositoryObject, $newRepo, false, [$hiddenUserEntry["ID"] => $hiddenUserEntry], [], $selection);
                                 }
                                 $link->setParentRepositoryId($parentRepositoryObject->getId());
                                 $link->attachToRepository($newRepo->getId());
                                 print "\n-- Should save following LINK: ";
                                 print_r($link->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $hash = $link->save();
                                 }
                                 // UPDATE METADATA
                                 $meta["ajxp_shared"] = ["shares" => [$element => array("type" => "minisite")]];
                             } catch (Exception $e) {
                                 print "\n-- ERROR: " . $e->getMessage();
                             }
                         }
                         if ($dryRun) {
                             rename($legacyLinkFile . ".migrated", $legacyLinkFile);
                         }
                         continue;
                     } else {
                         //
                         // File does not exists, remove meta
                         //
                         unset($meta["ajxp_shared"]);
                     }
                     $repo = ConfService::getRepositoryById($element);
                     if ($repo !== null) {
                         print "\n--Shared repository: just metadata";
                         // Shared repo, migrating the meta should be enough
                         $meta["ajxp_shared"] = array("shares" => [$element => array("type" => "repository")]);
                     }
                 }
             }
         }
         print "\n\n SHOULD NOW UPDATE METADATA WITH FOLLOWING :";
         print_r($data);
         if (!$dryRun) {
             file_put_contents($store, serialize($data));
         }
     }
 }
Пример #28
0
    $rootDir = new AJXP_Sabre_RootCollection("root");
    $server = new Sabre\DAV\Server($rootDir);
    $server->setBaseUri($baseURI);
}
if ((AJXP_Sabre_AuthBackendBasic::detectBasicHeader() || ConfService::getCoreConf("WEBDAV_FORCE_BASIC")) && ConfService::getAuthDriverImpl()->getOption("TRANSMIT_CLEAR_PASS")) {
    $authBackend = new AJXP_Sabre_AuthBackendBasic($rId);
} else {
    $authBackend = new AJXP_Sabre_AuthBackendDigest($rId);
}
$authPlugin = new Sabre\DAV\Auth\Plugin($authBackend, ConfService::getCoreConf("WEBDAV_DIGESTREALM"));
$server->addPlugin($authPlugin);
if (!is_dir(AJXP_DATA_PATH . "/plugins/server.sabredav")) {
    mkdir(AJXP_DATA_PATH . "/plugins/server.sabredav", 0755);
    $fp = fopen(AJXP_DATA_PATH . "/plugins/server.sabredav/locks", "w");
    fwrite($fp, "");
    fclose($fp);
}
$lockBackend = new Sabre\DAV\Locks\Backend\File(AJXP_DATA_PATH . "/plugins/server.sabredav/locks");
$lockPlugin = new Sabre\DAV\Locks\Plugin($lockBackend);
$server->addPlugin($lockPlugin);
if (ConfService::getCoreConf("WEBDAV_BROWSER_LISTING")) {
    $browerPlugin = new AJXP_Sabre_BrowserPlugin(isset($repository) ? $repository->getDisplay() : null);
    $extPlugin = new Sabre\DAV\Browser\GuessContentType();
    $server->addPlugin($browerPlugin);
    $server->addPlugin($extPlugin);
}
try {
    $server->exec();
} catch (Exception $e) {
    AJXP_Logger::error(__CLASS__, "Exception", $e->getMessage());
}
Пример #29
0
 public function listShares($limitToUser = '', $parentRepository = '', $cursor = null, $shareType = null)
 {
     $dbLets = array();
     if ($this->sqlSupported) {
         // Get DB files
         $dbLets = $this->confStorage->simpleStoreList("share", $cursor, "", "serial", !empty($limitToUser) ? '%"OWNER_ID";s:' . strlen($limitToUser) . ':"' . $limitToUser . '"%' : '', $parentRepository);
     }
     // Get hardcoded files
     $files = glob(ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER") . "/*.php");
     if ($files === false) {
         return $dbLets;
     }
     foreach ($files as $file) {
         if (basename($file) == "share.php") {
             continue;
         }
         $ar = explode(".", basename($file));
         $id = array_shift($ar);
         $publicletData = $this->loadShare($id);
         if ($publicletData === false) {
             continue;
         }
         if (!empty($limitToUser) && (!isset($publicletData["OWNER_ID"]) || $publicletData["OWNER_ID"] != $limitToUser)) {
             continue;
         }
         if (!empty($parentRepository) && (is_string($publicletData["REPOSITORY"]) && $publicletData["REPOSITORY"] != $parentRepository || is_object($publicletData["REPOSITORY"]) && $publicletData["REPOSITORY"]->getUniqueId() != $parentRepository)) {
             continue;
         }
         $publicletData["SHARE_TYPE"] = "file";
         $dbLets[$id] = $publicletData;
     }
     // Update share_type and filter if necessary
     foreach ($dbLets as $id => &$shareData) {
         if ($shareData === false) {
             unset($dbLets[$id]);
             continue;
         }
         $this->updateShareType($shareData);
         if (!empty($shareType) && $shareData["SHARE_TYPE"] != $shareType) {
             unset($dbLets[$id]);
         }
     }
     if (empty($shareType) || $shareType == "repository") {
         // BACKWARD COMPATIBILITY: collect old-school shared repositories that are not yet stored in simpleStore
         $storedIds = array();
         foreach ($dbLets as $share) {
             if (empty($limitToUser) || $limitToUser == $share["OWNER_ID"]) {
                 if (is_string($share["REPOSITORY"])) {
                     $storedIds[] = $share["REPOSITORY"];
                 } else {
                     if (is_object($share["REPOSITORY"])) {
                         $storedIds[] = $share["REPOSITORY"]->getUniqueId();
                     }
                 }
             }
         }
         // Find repositories that would have a parent
         $criteria = array();
         $criteria["parent_uuid"] = $parentRepository == "" ? AJXP_FILTER_NOT_EMPTY : $parentRepository;
         $criteria["owner_user_id"] = $limitToUser == "" ? AJXP_FILTER_NOT_EMPTY : $limitToUser;
         if (count($storedIds)) {
             $criteria["!uuid"] = $storedIds;
         }
         $oldRepos = ConfService::listRepositoriesWithCriteria($criteria, $count);
         foreach ($oldRepos as $sharedWorkspace) {
             if (!$sharedWorkspace->hasContentFilter()) {
                 $dbLets['repo-' . $sharedWorkspace->getId()] = array("SHARE_TYPE" => "repository", "OWNER_ID" => $sharedWorkspace->getOwner(), "REPOSITORY" => $sharedWorkspace->getUniqueId(), "LEGACY_REPO_OR_MINI" => true);
                 //Auto Migrate? boaf.
                 //$this->storeShare($sharedWorkspace->getParentId(), $data, "repository");
             }
         }
     }
     return $dbLets;
 }
Пример #30
0
 public function clearExpiredFiles()
 {
     $files = glob(ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER") . "/*.php");
     $loggedUser = AuthService::getLoggedUser();
     $userId = $loggedUser->getId();
     $deleted = array();
     foreach ($files as $file) {
         $ar = explode(".", basename($file));
         $id = array_shift($ar);
         if (strlen($id) != 32) {
             continue;
         }
         $publicletData = ShareCenter::loadPublicletData($id);
         if (!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"]) {
             unlink($file);
             $deleted[] = basename($file);
             PublicletCounter::delete(str_replace(".php", "", basename($file)));
         }
     }
     return $deleted;
 }