示例#1
0
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     switch ($actionName) {
         case "accept_invitation":
             $remoteShareId = \AJXP_Utils::sanitize($httpVars["remote_share_id"], AJXP_SANITIZE_ALPHANUM);
             $store = new SQLStore();
             $remoteShare = $store->remoteShareById($remoteShareId);
             if ($remoteShare !== null) {
                 $client = new OCSClient();
                 $client->acceptInvitation($remoteShare);
                 $remoteShare->setStatus(OCS_INVITATION_STATUS_ACCEPTED);
                 $store->storeRemoteShare($remoteShare);
             }
             break;
         case "reject_invitation":
             $remoteShareId = \AJXP_Utils::sanitize($httpVars["remote_share_id"], AJXP_SANITIZE_ALPHANUM);
             $store = new SQLStore();
             $remoteShare = $store->remoteShareById($remoteShareId);
             if ($remoteShare !== null) {
                 $client = new OCSClient();
                 $client->declineInvitation($remoteShare);
                 $store->deleteRemoteShare($remoteShare);
                 \ConfService::getInstance()->invalidateLoadedRepositories();
             }
             break;
         default:
             break;
     }
     return null;
 }
 /**
  * Initialize an empty mask, or from a serializedForm.
  * @param array|null $serializedForm
  */
 function __construct($serializedForm = null)
 {
     if ($serializedForm != null) {
         foreach ($serializedForm as $path => $permissionValue) {
             $path = AJXP_Utils::sanitize(AJXP_Utils::securePath($path), AJXP_SANITIZE_DIRNAME);
             if (!is_array($permissionValue) || $permissionValue["children"]) {
                 continue;
             }
             $perm = new AJXP_Permission();
             if ($permissionValue["read"]) {
                 $perm->setRead();
             }
             if ($permissionValue["write"]) {
                 $perm->setWrite();
             }
             if ($permissionValue["deny"]) {
                 $perm->setDeny();
             }
             if ($perm->isEmpty()) {
                 continue;
             }
             $this->updateBranch($path, $perm);
         }
     }
 }
 function tryToLogUser(&$httpVars, $isLast = false)
 {
     if (!isset($httpVars["get_action"]) || $httpVars["get_action"] != "login") {
         return false;
     }
     $rememberLogin = "";
     $rememberPass = "";
     $secureToken = "";
     $loggedUser = null;
     include_once AJXP_BIN_FOLDER . "/class.CaptchaProvider.php";
     if (AuthService::suspectBruteForceLogin() && (!isset($httpVars["captcha_code"]) || !CaptchaProvider::checkCaptchaResult($httpVars["captcha_code"]))) {
         $loggingResult = -4;
     } else {
         $userId = isset($httpVars["userid"]) ? AJXP_Utils::sanitize($httpVars["userid"], AJXP_SANITIZE_EMAILCHARS) : null;
         $userPass = isset($httpVars["password"]) ? trim($httpVars["password"]) : null;
         $rememberMe = isset($httpVars["remember_me"]) && $httpVars["remember_me"] == "true" ? true : false;
         $cookieLogin = isset($httpVars["cookie_login"]) ? true : false;
         $loggingResult = AuthService::logUser($userId, $userPass, false, $cookieLogin, $httpVars["login_seed"]);
         if ($rememberMe && $loggingResult == 1) {
             $rememberLogin = "******";
             $rememberPass = "******";
         }
         if ($loggingResult == 1) {
             session_regenerate_id(true);
             $secureToken = AuthService::generateSecureToken();
         }
         if ($loggingResult < 1 && AuthService::suspectBruteForceLogin()) {
             $loggingResult = -4;
             // Force captcha reload
         }
     }
     $loggedUser = AuthService::getLoggedUser();
     if ($loggedUser != null) {
         $force = $loggedUser->mergedRole->filterParameterValue("core.conf", "DEFAULT_START_REPOSITORY", AJXP_REPO_SCOPE_ALL, -1);
         $passId = -1;
         if (isset($httpVars["tmp_repository_id"])) {
             $passId = $httpVars["tmp_repository_id"];
         } else {
             if ($force != "" && $loggedUser->canSwitchTo($force) && !isset($httpVars["tmp_repository_id"]) && !isset($_SESSION["PENDING_REPOSITORY_ID"])) {
                 $passId = $force;
             }
         }
         $res = ConfService::switchUserToActiveRepository($loggedUser, $passId);
         if (!$res) {
             AuthService::disconnect();
             $loggingResult = -3;
         }
     }
     if ($loggedUser != null && (AuthService::hasRememberCookie() || isset($rememberMe) && $rememberMe == true)) {
         AuthService::refreshRememberCookie($loggedUser);
     }
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::loggingResult($loggingResult, $rememberLogin, $rememberPass, $secureToken);
     AJXP_XMLWriter::close();
     if ($loggingResult > 0 || $isLast) {
         exit;
     }
 }
示例#4
0
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     require_once AJXP_BIN_FOLDER . "/dibi.compact.php";
     dibi::connect($this->sqlDriver);
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $res = dibi::query("SELECT\n                [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n                FROM [ajxp_changes]\n                LEFT JOIN [ajxp_index]\n                    ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n                WHERE [ajxp_changes].[repository_identifier] = %s AND [seq] > %i\n                ORDER BY [ajxp_changes].[node_id], [seq] ASC", $this->computeIdentifier(ConfService::getRepository()), AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     echo '{"changes":[';
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if ($row->node_id == $previousNodeId) {
             $previousRow->target = $row->target;
             $previousRow->seq = $row->seq;
             if ($order[$row->type] > $order[$previousRow->type]) {
                 $previousRow->type = $row->type;
             }
         } else {
             if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                 echo json_encode($previousRow) . ",";
             }
             $previousRow = $row;
             $previousNodeId = $row->node_id;
         }
         $lastSeq = $row->seq;
         flush();
     }
     if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
         echo json_encode($previousRow);
     }
     if (isset($lastSeq)) {
         echo '], "last_seq":' . $lastSeq . '}';
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         echo '], "last_seq":' . $lastSeq . '}';
     }
 }
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     if (!dibi::isConnected()) {
         dibi::connect($this->sqlDriver);
     }
     $filter = null;
     $masks = array();
     $currentRepo = $this->accessDriver->repository;
     AJXP_Controller::applyHook("role.masks", array($currentRepo->getId(), &$masks, AJXP_Permission::READ));
     $recycle = $currentRepo->getOption("RECYCLE_BIN");
     $recycle = !empty($recycle) ? $recycle : false;
     if ($this->options["OBSERVE_STORAGE_CHANGES"] === true) {
         // Do it every XX minutes
         $minutes = 5;
         if (isset($this->options["OBSERVE_STORAGE_EVERY"])) {
             $minutes = intval($this->options["OBSERVE_STORAGE_EVERY"]);
         }
         $file = $this->getResyncTimestampFile();
         $last = 0;
         if (is_file($file)) {
             $last = intval(file_get_contents($file));
         }
         if (time() - $last > $minutes * 60) {
             $this->resyncAction("resync_storage", array(), array());
         }
     }
     if ($this->options["REQUIRES_INDEXATION"]) {
         if (ConfService::backgroundActionsSupported()) {
             AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), "index", array());
         } else {
             AJXP_Controller::findActionAndApply("index", array(), array());
         }
         // Unset the REQUIRES_INDEXATION FLAG
         $meta = $currentRepo->getOption("META_SOURCES");
         unset($meta["meta.syncable"]["REQUIRES_INDEXATION"]);
         $currentRepo->addOption("META_SOURCES", $meta);
         ConfService::replaceRepository($currentRepo->getId(), $currentRepo);
     }
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $stream = isset($httpVars["stream"]);
     $separator = $stream ? "\n" : ",";
     $veryLastSeq = intval(dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle());
     $seqId = intval(AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     if ($veryLastSeq > 0 && $seqId > $veryLastSeq) {
         // This is not normal! Send a signal reload all changes from start.
         if (!$stream) {
             echo json_encode(array('changes' => array(), 'last_seq' => 1));
         } else {
             echo 'LAST_SEQ:1';
         }
         return null;
     }
     $ands = array();
     $ands[] = array("[ajxp_changes].[repository_identifier] = %s", $this->computeIdentifier($currentRepo));
     $ands[] = array("[seq] > %i", $seqId);
     if (isset($httpVars["filter"])) {
         $filter = AJXP_Utils::decodeSecureMagic($httpVars["filter"]);
         $filterLike = rtrim($filter, "/") . "/";
         $ands[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
     }
     if (count($masks)) {
         $ors = array();
         foreach ($masks as $mask) {
             $filterLike = rtrim($mask, "/") . "/";
             $ors[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
         }
         if (count($ors)) {
             $ands[] = array("%or", $ors);
         }
     }
     $res = dibi::query("SELECT\n            [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n            FROM [ajxp_changes]\n            LEFT JOIN [ajxp_index]\n                ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n            WHERE %and\n            ORDER BY [ajxp_changes].[node_id], [seq] ASC", $ands);
     if (!$stream) {
         echo '{"changes":[';
     }
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     $valuesSent = false;
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if (!empty($recycle)) {
             $this->cancelRecycleNodes($row, $recycle);
         }
         if (!isset($httpVars["flatten"]) || $httpVars["flatten"] == "false") {
             if (!$this->filterMasks($row, $masks) && !$this->filterRow($row, $filter)) {
                 if ($valuesSent) {
                     echo $separator;
                 }
                 echo json_encode($row);
                 $valuesSent = true;
             }
         } else {
             if ($row->node_id == $previousNodeId) {
                 $previousRow->target = $row->target;
                 $previousRow->seq = $row->seq;
                 if ($order[$row->type] > $order[$previousRow->type]) {
                     $previousRow->type = $row->type;
                 }
             } else {
                 if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                     if ($this->filterMasks($previousRow, $masks) || $this->filterRow($previousRow, $filter)) {
                         $previousRow = $row;
                         $previousNodeId = $row->node_id;
                         $lastSeq = $row->seq;
                         continue;
                     }
                     if ($valuesSent) {
                         echo $separator;
                     }
                     echo json_encode($previousRow);
                     $valuesSent = true;
                 }
                 $previousRow = $row;
                 $previousNodeId = $row->node_id;
             }
             $lastSeq = $row->seq;
             flush();
         }
         //CODES HERE HAVE BEEN MOVE OUT OF THE LOOP
     }
     /**********RETURN TO SENDER************/
     // is 'not NULL' included in isSet()?
     if ($previousRow && isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content") && !$this->filterRow($previousRow, $filter)) {
         if ($valuesSent) {
             echo $separator;
         }
         echo json_encode($previousRow);
         if ($previousRow->seq > $lastSeq) {
             $lastSeq = $previousRow->seq;
         }
         $valuesSent = true;
     }
     /*************************************/
     if (isset($lastSeq)) {
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     }
     return null;
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     $dir = AJXP_Utils::decodeSecureMagic($dir);
     if ($dir == "/") {
         $dir = "";
     }
     $selection->initFromHttpVars($httpVars);
     if (!$selection->isEmpty()) {
         //$this->filterUserSelectionToHidden($selection->getFiles());
     }
     $urlBase = "pydio://" . ConfService::getRepository()->getId();
     $mess = ConfService::getMessages();
     switch ($action) {
         case "monitor_compression":
             $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]);
             $percent = 0;
             if (is_file($percentFile)) {
                 $percent = intval(file_get_contents($percentFile));
             }
             if ($percent < 100) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1);
                 AJXP_XMLWriter::close();
             } else {
                 @unlink($percentFile);
                 AJXP_XMLWriter::header();
                 if ($httpVars["on_end"] == "reload") {
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 } else {
                     $archiveName = AJXP_Utils::sanitize($httpVars["archive_name"], AJXP_SANITIZE_FILENAME);
                     $archiveName = str_replace("'", "\\'", $archiveName);
                     $jsCode = "\n                            PydioApi.getClient().downloadSelection(null, \$('download_form'), 'postcompress_download', {ope_id:'" . $httpVars["ope_id"] . "',archive_name:'" . $archiveName . "'});\n                        ";
                     AJXP_XMLWriter::triggerBgJsAction($jsCode, $mess["powerfs.3"], true);
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "postcompress_download":
             $archive = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             if (is_file($archive)) {
                 if (!$fsDriver->getFilteredOption("USE_XSENDFILE", ConfService::getRepository()) && !$fsDriver->getFilteredOption("USE_XACCELREDIRECT", ConfService::getRepository())) {
                     register_shutdown_function("unlink", $archive);
                 }
                 $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true);
             } else {
                 echo "<script>alert('Cannot find archive! Is ZIP correctly installed?');</script>";
             }
             break;
         case "compress":
         case "precompress":
             $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $opeId = substr(md5(time()), 0, 10);
                 $httpVars["ope_id"] = $opeId;
                 AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars);
                 AJXP_XMLWriter::header();
                 $bgParameters = array("dir" => SystemTextEncoding::toUTF8($dir), "archive_name" => SystemTextEncoding::toUTF8($archiveName), "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId);
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir;
             $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"];
             $compressLocally = $action == "compress" ? true : false;
             // List all files
             $todo = array();
             $args = array();
             $replaceSearch = array($rootDir, "\\");
             $replaceReplace = array("", "/");
             foreach ($selection->getFiles() as $selectionFile) {
                 $baseFile = $selectionFile;
                 $args[] = escapeshellarg(substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1)));
                 $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile);
                 $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/");
                 if (is_dir($selectionFile)) {
                     $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST);
                     foreach ($objects as $name => $object) {
                         $todo[] = str_replace($replaceSearch, $replaceReplace, $name);
                     }
                 }
                 if (trim($baseFile, "/") == "") {
                     // ROOT IS SELECTED, FIX IT
                     $args = array(escapeshellarg(basename($rootDir)));
                     $rootDir = dirname($rootDir);
                     break;
                 }
             }
             $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";";
             if (!$compressLocally) {
                 $archiveName = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . $archiveName;
             }
             chdir($rootDir);
             $cmd = $this->getFilteredOption("ZIP_PATH") . " -r " . escapeshellarg($archiveName) . " " . implode(" ", $args);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             $c = $fsDriver->getConfigs();
             if ((!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) && stripos(PHP_OS, "win") === false) {
                 $cmd .= " -x .\\*";
             }
             $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED";
             $proc = popen($cmd, "r");
             $toks = array();
             $handled = array();
             $finishedEchoed = false;
             while (!feof($proc)) {
                 set_time_limit(20);
                 $results = fgets($proc, 256);
                 if (strlen($results) == 0) {
                 } else {
                     $tok = strtok($results, "\n");
                     while ($tok !== false) {
                         $toks[] = $tok;
                         if ($tok == "ZIP_FINISHED") {
                             $finishedEchoed = true;
                         } else {
                             $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches);
                             if ($test !== false) {
                                 $handled[] = $matches[2];
                             }
                         }
                         $tok = strtok("\n");
                     }
                     if ($finishedEchoed) {
                         $percent = 100;
                     } else {
                         $percent = min(round(count($handled) / count($todo) * 100), 100);
                     }
                     file_put_contents($percentFile, $percent);
                 }
                 // avoid a busy wait
                 if ($percent < 100) {
                     usleep(1);
                 }
             }
             pclose($proc);
             file_put_contents($percentFile, 100);
             break;
         default:
             break;
     }
 }
 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;
 }
示例#8
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;
 }
 /**
  * @param String $action
  * @param Array $httpVars
  * @param Array $fileVars
  * @return String
  */
 function authTokenActions($action, $httpVars, $fileVars)
 {
     if (AuthService::getLoggedUser() == null) {
         return;
     }
     $this->storage = ConfService::getConfStorageImpl();
     if (!is_a($this->storage, "sqlConfDriver")) {
         return false;
     }
     $user = AuthService::getLoggedUser()->getId();
     if (AuthService::getLoggedUser()->isAdmin() && isset($httpVars["user_id"])) {
         $user = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
     }
     switch ($action) {
         case "keystore_generate_auth_token":
             if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) {
                 $this->logDebug("Keystore Generate Tokens", "Session Credentials set: returning empty tokens to force basic authentication");
                 HTMLWriter::charsetHeader("text/plain");
                 echo "";
                 break;
             }
             $token = AJXP_Utils::generateRandomString();
             $private = AJXP_Utils::generateRandomString();
             $data = array("USER_ID" => $user, "PRIVATE" => $private);
             if (!empty($httpVars["device"])) {
                 // Revoke previous tokens for this device
                 $device = $httpVars["device"];
                 $keys = $this->storage->simpleStoreList("keystore", null, "", "serial", '%"DEVICE_ID";s:' . strlen($device) . ':"' . $device . '"%');
                 foreach ($keys as $keyId => $keyData) {
                     if ($keyData["USER_ID"] != $user) {
                         continue;
                     }
                     $this->storage->simpleStoreClear("keystore", $keyId);
                 }
                 $data["DEVICE_ID"] = $device;
             }
             $data["DEVICE_UA"] = $_SERVER['HTTP_USER_AGENT'];
             $data["DEVICE_IP"] = $_SERVER['REMOTE_ADDR'];
             $this->storage->simpleStoreSet("keystore", $token, $data, "serial");
             HTMLWriter::charsetHeader("application/json");
             echo json_encode(array("t" => $token, "p" => $private));
             break;
         case "keystore_revoke_tokens":
             // Invalidate previous tokens
             $mess = ConfService::getMessages();
             $passedKeyId = "";
             if (isset($httpVars["key_id"])) {
                 $passedKeyId = $httpVars["key_id"];
             }
             $keys = $this->storage->simpleStoreList("keystore", null, $passedKeyId, "serial", '%"USER_ID";s:' . strlen($user) . ':"' . $user . '"%');
             foreach ($keys as $keyId => $keyData) {
                 $this->storage->simpleStoreClear("keystore", $keyId);
             }
             $message = array("result" => "SUCCESS", "message" => $mess["keystore.8"]);
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($message);
             break;
         case "keystore_list_tokens":
             if (!isset($user)) {
                 break;
             }
             $keys = $this->storage->simpleStoreList("keystore", null, "", "serial", '%"USER_ID";s:' . strlen($user) . ':"' . $user . '"%');
             foreach ($keys as $keyId => &$keyData) {
                 unset($keyData["PRIVATE"]);
                 unset($keyData["USER_ID"]);
                 $deviceDesc = "Web Browser";
                 $deviceOS = "Unkown";
                 if (isset($keyData["DEVICE_UA"])) {
                     $agent = $keyData["DEVICE_UA"];
                     if (strpos($agent, "python-requests") !== false) {
                         $deviceDesc = "PydioSync";
                         if (strpos($agent, "Darwin") !== false) {
                             $deviceOS = "Mac OS X";
                         } else {
                             if (strpos($agent, "Windows/7") !== false) {
                                 $deviceOS = "Windows 7";
                             } else {
                                 if (strpos($agent, "Windows/8") !== false) {
                                     $deviceOS = "Windows 8";
                                 } else {
                                     if (strpos($agent, "Linux") !== false) {
                                         $deviceOS = "Linux";
                                     }
                                 }
                             }
                         }
                     } else {
                         $deviceOS = AJXP_Utils::osFromUserAgent($agent);
                     }
                 }
                 $keyData["DEVICE_DESC"] = $deviceDesc;
                 $keyData["DEVICE_OS"] = $deviceOS;
             }
             header("Content-type: application/json;");
             echo json_encode($keys);
             break;
         default:
             break;
     }
     return null;
 }
 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::getRootDirsList();
             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::getCurrentRootDirIndex();
                 $user->setArrayPref("history", "last_repository", $activeRepId);
                 $user->save();
             }
             //$logMessage = "Successfully Switched!";
             AJXP_Logger::logAction("Switch Repository", array("rep. id" => $repository_id));
             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) {
                 exit(1);
             }
             if (isset($_GET["bm_action"]) && isset($_GET["bm_path"])) {
                 if ($_GET["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($_GET["bm_title"])) {
                         $title = $_GET["bm_title"];
                     }
                     if ($title == "" && $_GET["bm_path"] == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark(SystemTextEncoding::magicDequote($_GET["bm_path"]), SystemTextEncoding::magicDequote($title));
                 } else {
                     if ($_GET["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($_GET["bm_path"]);
                     } else {
                         if ($_GET["bm_action"] == "rename_bookmark" && isset($_GET["bm_title"])) {
                             $bmUser->renameBookmark($_GET["bm_path"], $_GET["bm_title"]);
                         }
                     }
                 }
             }
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser->save();
                 AuthService::updateUser($bmUser);
             } else {
                 if (!AuthService::usersEnabled()) {
                     $bmUser->save();
                 }
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks());
             AJXP_XMLWriter::close();
             exit(1);
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "save_user_pref":
             $userObject = AuthService::getLoggedUser();
             $i = 0;
             while (isset($_GET["pref_name_" . $i]) && isset($_GET["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($_GET["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($_GET["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && ($userObject == null || $userObject->getId() == "guest")) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save();
                 AuthService::updateUser($userObject);
                 //setcookie("AJXP_$prefName", $prefValue);
                 $i++;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             exit(1);
             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;
 }
示例#11
0
 protected function actionUnshare($remoteId, $token, $parameters)
 {
     $token = \AJXP_Utils::sanitize($token, AJXP_SANITIZE_ALPHANUM);
     $remoteId = \AJXP_Utils::sanitize($remoteId, AJXP_SANITIZE_ALPHANUM);
     $store = new SQLStore();
     $remoteShare = $store->remoteShareForOcsRemoteId($remoteId);
     if (empty($remoteShare)) {
         throw new InvalidArgumentsException();
     }
     if ($token !== $remoteShare->getOcsToken()) {
         throw new InvalidArgumentsException();
     }
     $targetUser = $remoteShare->getUser();
     $store->deleteRemoteShare($remoteShare);
     $response = $this->buildResponse("ok", 200, "Successfully removed share.");
     $this->sendResponse($response, $this->getFormat($parameters));
     $userRole = \AuthService::getRole("AJXP_USR_/" . $targetUser);
     if ($userRole !== false) {
         // Artificially "touch" user role
         // to force repositories reload if he is logged in
         \AuthService::updateRole($userRole);
     }
 }
 public function listRepositories($root, $child, $hashValue = null, $returnNodes = false, $file = "", $aliasedDir = null, $httpVars)
 {
     $REPOS_PER_PAGE = 50;
     $allNodes = array();
     if ($hashValue == null) {
         $hashValue = 1;
     }
     $offset = ($hashValue - 1) * $REPOS_PER_PAGE;
     $count = null;
     // Load all repositories = normal, templates, and templates children
     $criteria = array("ORDERBY" => array("KEY" => "display", "DIR" => "ASC"), "CURSOR" => array("OFFSET" => $offset, "LIMIT" => $REPOS_PER_PAGE));
     $currentUserIsGroupAdmin = AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/";
     if ($currentUserIsGroupAdmin) {
         $criteria = array_merge($criteria, array("owner_user_id" => AJXP_FILTER_EMPTY, "groupPath" => "regexp:/^" . str_replace("/", "\\/", AuthService::getLoggedUser()->getGroupPath()) . '/'));
     } else {
         $criteria["parent_uuid"] = AJXP_FILTER_EMPTY;
     }
     if (isset($httpVars) && is_array($httpVars) && isset($httpVars["template_children_id"])) {
         $criteria["parent_uuid"] = AJXP_Utils::sanitize($httpVars["template_children_id"], AJXP_SANITIZE_ALPHANUM);
     }
     $repos = ConfService::listRepositoriesWithCriteria($criteria, $count);
     if (!$returnNodes) {
         AJXP_XMLWriter::renderPaginationData($count, $hashValue, ceil($count / $REPOS_PER_PAGE));
         AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.repositories">
             <column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/>
             <column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/>
             <column messageId="ajxp_conf.125" attributeName="slug" sortType="String"/>
         </columns>');
     }
     $driverLabels = array();
     foreach ($repos as $repoIndex => $repoObject) {
         if ($repoObject->getAccessType() == "ajxp_conf" || $repoObject->getAccessType() == "ajxp_shared") {
             continue;
         }
         if (!AuthService::canAdministrate($repoObject)) {
             continue;
         }
         if (is_numeric($repoIndex)) {
             $repoIndex = "" . $repoIndex;
         }
         $icon = "hdd_external_unmount.png";
         $editable = $repoObject->isWriteable();
         if ($repoObject->isTemplate) {
             $icon = "hdd_external_mount.png";
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/") {
                 $editable = false;
             }
         }
         $accessType = $repoObject->getAccessType();
         $accessLabel = $this->getDriverLabel($accessType, $driverLabels);
         $meta = array("repository_id" => $repoIndex, "accessType" => ($repoObject->isTemplate ? "Template for " : "") . $repoObject->getAccessType(), "accessLabel" => $accessLabel, "icon" => $icon, "owner" => $repoObject->hasOwner() ? $repoObject->getOwner() : "", "openicon" => $icon, "slug" => $repoObject->getSlug(), "parentname" => "/repositories", "ajxp_mime" => "repository" . ($editable ? "_editable" : ""), "is_template" => $repoObject->isTemplate ? "true" : "false");
         $nodeKey = "/data/repositories/{$repoIndex}";
         $label = $repoObject->getDisplay();
         if (in_array($nodeKey, $this->currentBookmarks)) {
             $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png"));
         }
         $xml = AJXP_XMLWriter::renderNode($nodeKey, AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($label)), true, $meta, true, false);
         if ($returnNodes) {
             $allNodes[$nodeKey] = $xml;
         } else {
             print $xml;
         }
         if ($repoObject->isTemplate) {
             // Now Load children for template repositories
             $children = ConfService::listRepositoriesWithCriteria(array("parent_uuid" => $repoIndex . ""), $count);
             foreach ($children as $childId => $childObject) {
                 if (!AuthService::canAdministrate($childObject)) {
                     continue;
                 }
                 if (is_numeric($childId)) {
                     $childId = "" . $childId;
                 }
                 $meta = array("repository_id" => $childId, "accessType" => $childObject->getAccessType(), "accessLabel" => $this->getDriverLabel($childObject->getAccessType(), $driverLabels), "icon" => "repo_child.png", "slug" => $childObject->getSlug(), "owner" => $childObject->hasOwner() ? $childObject->getOwner() : "", "openicon" => "repo_child.png", "parentname" => "/repositories", "ajxp_mime" => "repository_editable", "template_name" => $label);
                 $cNodeKey = "/data/repositories/{$childId}";
                 if (in_array($cNodeKey, $this->currentBookmarks)) {
                     $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png"));
                 }
                 $xml = AJXP_XMLWriter::renderNode($cNodeKey, AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($childObject->getDisplay())), true, $meta, true, false);
                 if ($returnNodes) {
                     $allNodes[$cNodeKey] = $xml;
                 } else {
                     print $xml;
                 }
             }
         }
     }
 }
 /**
  * Perform standard urldecode, sanitization, securepath and magicDequote
  * @static
  * @param $data
  * @param int $sanitizeLevel
  * @return string
  */
 public static function decodeSecureMagic($data, $sanitizeLevel = AJXP_SANITIZE_HTML)
 {
     return SystemTextEncoding::fromUTF8(AJXP_Utils::sanitize(AJXP_Utils::securePath(SystemTextEncoding::magicDequote($data)), $sanitizeLevel));
 }
 public function applyAction($actionName, $httpVars, $fileVars)
 {
     $messages = ConfService::getMessages();
     $repoId = $this->accessDriver->repository->getId();
     if ($actionName == "search") {
         // TMP
         if (strpos($httpVars["query"], "keyword:") === 0) {
             $parts = explode(":", $httpVars["query"]);
             $this->applyAction("search_by_keyword", array("field" => $parts[1]), array());
             return;
         }
         try {
             $this->loadIndex($repoId, false);
         } catch (Exception $ex) {
             $this->applyAction("index", array(), array());
             throw new Exception($messages["index.lucene.7"]);
         }
         $textQuery = $httpVars["query"];
         if ($this->getFilteredOption("AUTO_WILDCARD") === true && strlen($textQuery) > 0 && ctype_alnum($textQuery)) {
             if ($textQuery[0] == '"' && $textQuery[strlen($textQuery) - 1] == '"') {
                 $textQuery = substr($textQuery, 1, -1);
             } else {
                 if ($textQuery[strlen($textQuery) - 1] != "*") {
                     $textQuery .= "*";
                 }
             }
         }
         $this->currentIndex->open();
         $fieldQuery = new Elastica\Query\QueryString();
         $fieldQuery->setAllowLeadingWildcard(true);
         $fieldQuery->setFuzzyMinSim(0.8);
         if ($textQuery == "*") {
             $fields = ["ajxp_node"];
             $fieldQuery->setQuery("yes");
             $fieldQuery->setFields($fields);
         } else {
             if (strpos($textQuery, ":") !== false) {
                 // USE LUCENE DSL DIRECTLY (key1:value1 AND key2:value2...)
                 $textQuery = str_replace("ajxp_meta_ajxp_document_content:", "body:", $textQuery);
                 $textQuery = $this->filterSearchRangesKeywords($textQuery);
                 $fieldQuery->setQuery($textQuery);
             } else {
                 $fields = ["basename", "ajxp_meta_*", "body"];
                 $fieldQuery->setQuery($textQuery);
                 $fieldQuery->setFields($fields);
             }
         }
         /*
         TODO : READAPT QUERY WITH EACH FIELD
         if ((isSet($this->metaFields) || $this->indexContent) && isSet($httpVars["fields"])) {
              $sParts = array();
              foreach (explode(",",$httpVars["fields"]) as $searchField) {
                  if ($searchField == "filename") {
                      $sParts[] = "basename:".$httpVars["query"];
                  } else if (in_array($searchField, $this->metaFields)) {
                      $sParts[] = "ajxp_meta_".$searchField.":".$httpVars["query"];
                  } else if ($searchField == "ajxp_document_content") {
                      $sParts[] = "title:".$httpVars["query"];
                      $sParts[] = "body:".$httpVars["query"];
                      $sParts[] = "keywords:".$httpVars["query"];
                  }
              }
              $query = implode(" OR ", $sParts);
              $query = "ajxp_scope:shared AND ($query)";
              $this->logDebug("Query : $query");
         } else {
         */
         //}
         /*
            We create this object search because it'll allow us to fetch the number of results we want at once.
            We just have to set some parameters, the query type and the size of the result set.
         */
         $search = new Elastica\Search($this->client);
         $search->addIndex($this->currentIndex)->addType($this->currentType);
         $maxResults = $this->getFilteredOption("MAX_RESULTS");
         if (isset($httpVars['limit'])) {
             $maxResults = intval($httpVars['limit']);
         }
         $searchOptions = [\Elastica\Search::OPTION_SEARCH_TYPE => \Elastica\Search::OPTION_SEARCH_TYPE_QUERY_THEN_FETCH, \Elastica\Search::OPTION_SIZE => $maxResults];
         $this->logDebug(__FUNCTION__, "Executing query: ", $textQuery);
         $fullQuery = new Elastica\Query();
         $fullQuery->setQuery($fieldQuery);
         $qb = new Elastica\QueryBuilder();
         $fullQuery = new Elastica\Query();
         $filter = $qb->query()->match("ajxp_scope", "shared");
         $fullQuery->setQuery($qb->query()->bool()->addMust($fieldQuery)->addFilter($filter));
         $result = $search->search($fullQuery, $searchOptions);
         $this->logDebug(__FUNCTION__, "Search finished. ");
         $hits = $result->getResults();
         AJXP_XMLWriter::header();
         foreach ($hits as $hit) {
             $source = $hit->getSource();
             if ($source["serialized_metadata"] != null) {
                 $meta = unserialize(base64_decode($source["serialized_metadata"]));
                 $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($source["node_url"]), $meta);
             } else {
                 $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($source["node_url"]), array());
                 $tmpNode->loadNodeInfo();
             }
             if (!file_exists($tmpNode->getUrl())) {
                 $this->currentType->deleteById($hit->getId());
                 continue;
             }
             $tmpNode->search_score = sprintf("%0.2f", $hit->getScore());
             AJXP_XMLWriter::renderAjxpNode($tmpNode);
         }
         AJXP_XMLWriter::close();
     } else {
         if ($actionName == "search_by_keyword") {
             $scope = "user";
             try {
                 $this->loadIndex($repoId, false);
             } catch (Exception $ex) {
                 throw new Exception($messages["index.lucene.7"]);
             }
             /*
                         $sParts = array();
                         $searchField = $httpVars["field"];
             
             
                         if ($scope == "user") {
                             if (AuthService::usersEnabled() && AuthService::getLoggedUser() == null) {
                                 throw new Exception("Cannot find current user");
                             }
                             $sParts[] = "ajxp_scope:user";
                             $sParts[] = "ajxp_user:"******"ajxp_scope:shared";
                         }
                         $query = implode(" AND ", $sParts);
                         $this->logDebug("Query : $query");*/
             $searchField = AJXP_Utils::sanitize($httpVars["field"], AJXP_SANITIZE_ALPHANUM);
             $fieldQuery = new Elastica\Query\QueryString();
             $fields = array($searchField);
             $fieldQuery->setQuery($searchField == "ajxp_node" ? "yes" : "true");
             $fieldQuery->setFields($fields);
             $fieldQuery->setAllowLeadingWildcard(false);
             $fieldQuery->setFuzzyMinSim(0.8);
             $search = new Elastica\Search($this->client);
             $search->addIndex($this->currentIndex)->addType($this->currentType);
             $maxResults = $this->getFilteredOption("MAX_RESULTS");
             if (isset($httpVars['limit'])) {
                 $maxResults = intval($httpVars['limit']);
             }
             $searchOptions = array(\Elastica\Search::OPTION_SEARCH_TYPE => \Elastica\Search::OPTION_SEARCH_TYPE_QUERY_THEN_FETCH, \Elastica\Search::OPTION_SIZE => $maxResults);
             /* ADD SCOPE FILTER
                $term = new Elastica\Filter\Term();
                $term->setTerm("ajxp_scope", "user");*/
             $qb = new Elastica\QueryBuilder();
             $fullQuery = new Elastica\Query();
             $fullQuery->setQuery($qb->query()->bool()->addMust($fieldQuery)->addMust($qb->query()->match("ajxp_scope", "user"))->addMust($qb->query()->match("user", AuthService::getLoggedUser()->getId())));
             $result = $search->search($fullQuery, $searchOptions);
             $this->logDebug(__FUNCTION__, "Search finished. ");
             $hits = $result->getResults();
             AJXP_XMLWriter::header();
             $leafNodes = [];
             foreach ($hits as $hit) {
                 if ($hit->serialized_metadata != null) {
                     $meta = unserialize(base64_decode($hit->serialized_metadata));
                     $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), $meta);
                 } else {
                     $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), array());
                     $tmpNode->loadNodeInfo();
                 }
                 if (!file_exists($tmpNode->getUrl())) {
                     $this->currentType->deleteById($hit->id);
                     continue;
                 }
                 $tmpNode->search_score = sprintf("%0.2f", $hit->score);
                 if ($tmpNode->isLeaf()) {
                     $leafNodes[] = $tmpNode;
                 } else {
                     AJXP_XMLWriter::renderAjxpNode($tmpNode);
                 }
             }
             foreach ($leafNodes as $leaf) {
                 AJXP_XMLWriter::renderAjxpNode($leaf);
             }
             AJXP_XMLWriter::close();
         }
     }
 }
示例#15
0
 /**
  * Update some internal configs from httpVars
  * @param $httpVars
  * @throws Exception
  */
 public function parseHttpVars($httpVars)
 {
     $data =& $this->internal;
     $data["DOWNLOAD_DISABLED"] = isset($httpVars["simple_right_download"]) ? false : true;
     $data["AJXP_APPLICATION_BASE"] = AJXP_Utils::detectServerURL(true);
     if (isset($httpVars["minisite_layout"])) {
         $data["AJXP_TEMPLATE_NAME"] = $httpVars["minisite_layout"];
     }
     if (isset($httpVars["expiration"])) {
         if (intval($httpVars["expiration"]) > 0) {
             $data["EXPIRE_TIME"] = time() + intval($httpVars["expiration"]) * 86400;
         } else {
             if (isset($data["EXPIRE_TIME"])) {
                 unset($data["EXPIRE_TIME"]);
             }
         }
     }
     if (isset($httpVars["downloadlimit"])) {
         if (intval($httpVars["downloadlimit"]) > 0) {
             $data["DOWNLOAD_LIMIT"] = intval($httpVars["downloadlimit"]);
         } else {
             if (isset($data["DOWNLOAD_LIMIT"])) {
                 unset($data["DOWNLOAD_LIMIT"]);
             }
         }
     }
     if (isset($httpVars["custom_handle"]) && !empty($httpVars["custom_handle"]) && (!isset($this->hash) || $httpVars["custom_handle"] != $this->hash)) {
         // Existing already
         $value = AJXP_Utils::sanitize($httpVars["custom_handle"], AJXP_SANITIZE_ALPHANUM);
         $value = strtolower($value);
         if (strlen($value) < $this->store->hashMinLength) {
             $mess = ConfService::getMessages();
             throw new Exception(str_replace("%s", $this->store->hashMinLength, $mess["share_center.223"]));
         }
         $test = $this->store->loadShare($value);
         $mess = ConfService::getMessages();
         if (!empty($test)) {
             throw new Exception($mess["share_center.172"]);
         }
         if (!isset($this->hash)) {
             $this->hash = $value;
         } else {
             $this->newHash = $value;
         }
     }
 }
示例#16
0
 public function ajxpTableExists($actionName, $httpVars, $fileVars)
 {
     $p = $this->sqlDriver;
     if ($p["driver"] == "postgre") {
         $tableQuery = "SELECT [tablename] FROM [pg_catalog].[pg_tables] WHERE [tablename] = %s";
     } else {
         if ($p["driver"] == "sqlite3" || $p["driver"] == "sqlite") {
             $tableQuery = "SELECT [name] FROM [sqlite_master] WHERE type = \"table\" AND [name] = %s";
         } else {
             $tableQuery = "SHOW TABLES LIKE %s";
         }
     }
     $tableName = AJXP_Utils::sanitize($httpVars["table_name"], AJXP_SANITIZE_ALPHANUM);
     $tables = dibi::query($tableQuery, $tableName)->fetchPairs();
     $exists = count($tables) && in_array($tableName, $tables);
     HTMLWriter::charsetHeader("application/json");
     echo json_encode(array("result" => $exists));
 }
示例#17
0
<?php

define("AJXP_EXEC", true);
require_once "/home/utsmaedu/public_html/sgc/core/classes/class.AJXP_Utils.php";
$hash = AJXP_Utils::securePath(AJXP_Utils::sanitize($_GET["hash"], AJXP_SANITIZE_ALPHANUM));
if (file_exists($hash . ".php")) {
    require_once $hash . ".php";
} else {
    require_once "/home/utsmaedu/public_html/sgc/publicLet.inc.php";
    ShareCenter::loadShareByHash($hash);
}
 /**
  * Transmit to the ajxp_conf load_plugin_manifest action
  * @param $action
  * @param $httpVars
  * @param $fileVars
  */
 public function applyInstallerForm($action, $httpVars, $fileVars)
 {
     $data = array();
     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "");
     // Create a custom bootstrap.json file
     $coreConf = array();
     $coreAuth = array();
     $this->_loadPluginConfig("core.conf", $coreConf);
     $this->_loadPluginConfig("core.auth", $coreAuth);
     if (!isset($coreConf["UNIQUE_INSTANCE_CONFIG"])) {
         $coreConf["UNIQUE_INSTANCE_CONFIG"] = array();
     }
     if (!isset($coreAuth["MASTER_INSTANCE_CONFIG"])) {
         $coreAuth["MASTER_INSTANCE_CONFIG"] = array();
     }
     $coreConf["AJXP_CLI_SECRET_KEY"] = AJXP_Utils::generateRandomString(24, true);
     $storageType = $data["STORAGE_TYPE"]["type"];
     if ($storageType == "db") {
         // REWRITE BOOTSTRAP.JSON
         $coreConf["DIBI_PRECONFIGURATION"] = $data["STORAGE_TYPE"]["db_type"];
         if (isset($coreConf["DIBI_PRECONFIGURATION"]["sqlite3_driver"])) {
             $dbFile = AJXP_VarsFilter::filter($coreConf["DIBI_PRECONFIGURATION"]["sqlite3_database"]);
             if (!file_exists(dirname($dbFile))) {
                 mkdir(dirname($dbFile), 0755, true);
             }
         }
         $coreConf["UNIQUE_INSTANCE_CONFIG"] = array_merge($coreConf["UNIQUE_INSTANCE_CONFIG"], array("instance_name" => "conf.sql", "group_switch_value" => "conf.sql", "SQL_DRIVER" => array("core_driver" => "core", "group_switch_value" => "core")));
         $coreAuth["MASTER_INSTANCE_CONFIG"] = array_merge($coreAuth["MASTER_INSTANCE_CONFIG"], array("instance_name" => "auth.sql", "group_switch_value" => "auth.sql", "SQL_DRIVER" => array("core_driver" => "core", "group_switch_value" => "core")));
         // INSTALL ALL SQL TABLES
         $sqlPlugs = array("conf.sql", "auth.sql", "feed.sql", "log.sql", "meta.syncable");
         foreach ($sqlPlugs as $plugId) {
             $plug = AJXP_PluginsService::findPluginById($plugId);
             $plug->installSQLTables(array("SQL_DRIVER" => $data["STORAGE_TYPE"]["db_type"]));
         }
     } else {
         $coreConf["UNIQUE_INSTANCE_CONFIG"] = array_merge($coreConf["UNIQUE_INSTANCE_CONFIG"], array("instance_name" => "conf.serial", "group_switch_value" => "conf.serial"));
         $coreAuth["MASTER_INSTANCE_CONFIG"] = array_merge($coreAuth["MASTER_INSTANCE_CONFIG"], array("instance_name" => "auth.serial", "group_switch_value" => "auth.serial"));
     }
     $oldBoot = $this->getPluginWorkDir(true) . "/bootstrap.json";
     if (is_file($oldBoot)) {
         copy($oldBoot, $oldBoot . ".bak");
         unlink($oldBoot);
     }
     $newBootstrap = array("core.conf" => $coreConf, "core.auth" => $coreAuth);
     AJXP_Utils::saveSerialFile($oldBoot, $newBootstrap, true, false, "json", true);
     // Write new bootstrap and reload conf plugin!
     if ($storageType == "db") {
         $coreConf["UNIQUE_INSTANCE_CONFIG"]["SQL_DRIVER"] = $coreConf["DIBI_PRECONFIGURATION"];
         $coreAuth["MASTER_INSTANCE_CONFIG"]["SQL_DRIVER"] = $coreConf["DIBI_PRECONFIGURATION"];
     }
     $newConfigPlugin = ConfService::instanciatePluginFromGlobalParams($coreConf["UNIQUE_INSTANCE_CONFIG"], "AbstractConfDriver");
     $newAuthPlugin = ConfService::instanciatePluginFromGlobalParams($coreAuth["MASTER_INSTANCE_CONFIG"], "AbstractAuthDriver");
     if ($data["ENCODING"] != (defined('AJXP_LOCALE') ? AJXP_LOCALE : SystemTextEncoding::getEncoding())) {
         file_put_contents($this->getPluginWorkDir() . "/encoding.php", "<?php \$ROOT_ENCODING='" . $data["ENCODING"] . "';");
     }
     $tpl = file_get_contents($this->getBaseDir() . "/htaccess.tpl");
     if (!empty($data["SERVER_URI"]) && $data["SERVER_URI"] != "/") {
         $htContent = str_replace('${APPLICATION_ROOT}', $data["SERVER_URI"], $tpl);
     } else {
         $htContent = str_replace('${APPLICATION_ROOT}/', "/", $tpl);
         $htContent = str_replace('${APPLICATION_ROOT}', "/", $htContent);
     }
     if (is_writeable(AJXP_INSTALL_PATH . "/.htaccess")) {
         file_put_contents(AJXP_INSTALL_PATH . "/.htaccess", $htContent);
     } else {
         $htAccessToUpdate = AJXP_INSTALL_PATH . "/.htaccess";
     }
     if ($storageType == "db") {
         $sqlPlugs = array("core.notifications/UNIQUE_FEED_INSTANCE" => "feed.sql", "core.log/UNIQUE_PLUGIN_INSTANCE" => "log.sql", "core.mq/UNIQUE_MS_INSTANCE" => "mq.sql");
         $data["ENABLE_NOTIF"] = $data["STORAGE_TYPE"]["notifications"];
     }
     // Prepare plugins configs
     $direct = array("APPLICATION_TITLE" => "core.ajaxplorer/APPLICATION_TITLE", "APPLICATION_LANGUAGE" => "core.ajaxplorer/DEFAULT_LANGUAGE", "ENABLE_NOTIF" => "core.notifications/USER_EVENTS", "APPLICATION_WELCOME" => "gui.ajax/CUSTOM_WELCOME_MESSAGE");
     $mailerEnabled = $data["MAILER_ENABLE"]["status"];
     if ($mailerEnabled == "yes") {
         // Enable core.mailer
         $data["MAILER_SYSTEM"] = $data["MAILER_ENABLE"]["MAILER_SYSTEM"];
         $data["MAILER_ADMIN"] = $data["MAILER_ENABLE"]["MAILER_ADMIN"];
         $direct = array_merge($direct, array("MAILER_SYSTEM" => "mailer.phpmailer-lite/MAILER", "MAILER_ADMIN" => "core.mailer/FROM"));
     }
     foreach ($direct as $key => $value) {
         list($pluginId, $param) = explode("/", $value);
         $options = array();
         $newConfigPlugin->_loadPluginConfig($pluginId, $options);
         $options[$param] = $data[$key];
         $newConfigPlugin->_savePluginConfig($pluginId, $options);
     }
     if (isset($sqlPlugs)) {
         foreach ($sqlPlugs as $core => $value) {
             list($pluginId, $param) = explode("/", $core);
             $options = array();
             $newConfigPlugin->_loadPluginConfig($pluginId, $options);
             $options[$param] = array("instance_name" => $value, "group_switch_value" => $value, "SQL_DRIVER" => array("core_driver" => "core", "group_switch_value" => "core"));
             $newConfigPlugin->_savePluginConfig($pluginId, $options);
         }
     }
     ConfService::setTmpStorageImplementations($newConfigPlugin, $newAuthPlugin);
     require_once $newConfigPlugin->getUserClassFileName();
     $adminLogin = AJXP_Utils::sanitize($data["ADMIN_USER_LOGIN"], AJXP_SANITIZE_EMAILCHARS);
     $adminName = $data["ADMIN_USER_NAME"];
     $adminPass = $data["ADMIN_USER_PASS"];
     $adminPass2 = $data["ADMIN_USER_PASS2"];
     AuthService::createUser($adminLogin, $adminPass, true);
     $uObj = $newConfigPlugin->createUserObject($adminLogin);
     if (isset($data["MAILER_ADMIN"])) {
         $uObj->personalRole->setParameterValue("core.conf", "email", $data["MAILER_ADMIN"]);
     }
     $uObj->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", $adminName);
     $uObj->personalRole->setAcl('ajxp_conf', 'rw');
     AuthService::updateRole($uObj->personalRole);
     $loginP = "USER_LOGIN";
     $i = 0;
     while (isset($data[$loginP]) && !empty($data[$loginP])) {
         $pass = $data[str_replace("_LOGIN", "_PASS", $loginP)];
         $pass2 = $data[str_replace("_LOGIN", "_PASS2", $loginP)];
         $name = $data[str_replace("_LOGIN", "_NAME", $loginP)];
         $mail = $data[str_replace("_LOGIN", "_MAIL", $loginP)];
         $saniLogin = AJXP_Utils::sanitize($data[$loginP], AJXP_SANITIZE_EMAILCHARS);
         AuthService::createUser($saniLogin, $pass);
         $uObj = $newConfigPlugin->createUserObject($saniLogin);
         $uObj->personalRole->setParameterValue("core.conf", "email", $mail);
         $uObj->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", $name);
         AuthService::updateRole($uObj->personalRole);
         $i++;
         $loginP = "USER_LOGIN_" . $i;
     }
     AJXP_PluginsService::clearPluginsCache();
     AJXP_Utils::setApplicationFirstRunPassed();
     if (isset($htAccessToUpdate)) {
         HTMLWriter::charsetHeader("application/json");
         echo json_encode(array('file' => $htAccessToUpdate, 'content' => $htContent));
     } else {
         session_destroy();
         HTMLWriter::charsetHeader("text/plain");
         echo 'OK';
     }
 }
 /**
  * Main method for querying the XML registry, find an action and all its associated processors,
  * and apply all the callbacks.
  * @static
  * @param String $actionName
  * @param array $httpVars
  * @param array $fileVars
  * @param DOMNode $action
  * @return mixed
  */
 public static function findActionAndApply($actionName, $httpVars, $fileVars, &$action = null)
 {
     $actionName = AJXP_Utils::sanitize($actionName, AJXP_SANITIZE_EMAILCHARS);
     if ($actionName == "cross_copy") {
         $pService = AJXP_PluginsService::getInstance();
         $actives = $pService->getActivePlugins();
         $accessPlug = $pService->getPluginsByType("access");
         if (count($accessPlug)) {
             foreach ($accessPlug as $key => $objbect) {
                 if ($actives[$objbect->getId()] === true) {
                     call_user_func(array($pService->getPluginById($objbect->getId()), "crossRepositoryCopy"), $httpVars);
                     break;
                 }
             }
         }
         self::$lastActionNeedsAuth = true;
         return null;
     }
     $xPath = self::initXPath();
     if ($action == null) {
         $actions = $xPath->query("actions/action[@name='{$actionName}']");
         if (!$actions->length) {
             self::$lastActionNeedsAuth = true;
             return false;
         }
         $action = $actions->item(0);
     }
     //Check Rights
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if (AJXP_Controller::actionNeedsRight($action, $xPath, "adminOnly") && ($loggedUser == null || !$loggedUser->isAdmin())) {
             $mess = ConfService::getMessages();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $mess[207]);
             AJXP_XMLWriter::requireAuth();
             AJXP_XMLWriter::close();
             exit(1);
         }
         if (AJXP_Controller::actionNeedsRight($action, $xPath, "read") && ($loggedUser == null || !$loggedUser->canRead(ConfService::getCurrentRepositoryId() . ""))) {
             AJXP_XMLWriter::header();
             if ($actionName == "ls" & $loggedUser != null && $loggedUser->canWrite(ConfService::getCurrentRepositoryId() . "")) {
                 // Special case of "write only" right : return empty listing, no auth error.
                 AJXP_XMLWriter::close();
                 exit(1);
             }
             $mess = ConfService::getMessages();
             AJXP_XMLWriter::sendMessage(null, $mess[208]);
             AJXP_XMLWriter::requireAuth();
             AJXP_XMLWriter::close();
             exit(1);
         }
         if (AJXP_Controller::actionNeedsRight($action, $xPath, "write") && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRepositoryId() . ""))) {
             $mess = ConfService::getMessages();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $mess[207]);
             AJXP_XMLWriter::requireAuth();
             AJXP_XMLWriter::close();
             exit(1);
         }
     }
     $preCalls = self::getCallbackNode($xPath, $action, 'pre_processing/serverCallback', $actionName, $httpVars, $fileVars, true);
     $postCalls = self::getCallbackNode($xPath, $action, 'post_processing/serverCallback[not(@capture="true")]', $actionName, $httpVars, $fileVars, true);
     $captureCalls = self::getCallbackNode($xPath, $action, 'post_processing/serverCallback[@capture="true"]', $actionName, $httpVars, $fileVars, true);
     $mainCall = self::getCallbackNode($xPath, $action, "processing/serverCallback", $actionName, $httpVars, $fileVars, false);
     if ($mainCall != null) {
         self::checkParams($httpVars, $mainCall, $xPath);
     }
     if ($captureCalls !== false) {
         // Make sure the ShutdownScheduler has its own OB started BEFORE, as it will presumabily be
         // executed AFTER the end of this one.
         AJXP_ShutdownScheduler::getInstance();
         ob_start();
         $params = array("pre_processor_results" => array(), "post_processor_results" => array());
     }
     if ($preCalls !== false) {
         foreach ($preCalls as $preCall) {
             // A Preprocessing callback can modify its input arguments (passed by ref)
             $preResult = self::applyCallback($preCall, $actionName, $httpVars, $fileVars);
             if (isset($params)) {
                 $params["pre_processor_results"][$preCall->getAttribute("pluginId")] = $preResult;
             }
         }
     }
     if ($mainCall) {
         $result = self::applyCallback($mainCall, $actionName, $httpVars, $fileVars);
         if (isset($params)) {
             $params["processor_result"] = $result;
         }
     }
     if ($postCalls !== false) {
         foreach ($postCalls as $postCall) {
             // A Preprocessing callback can modify its input arguments (passed by ref)
             $postResult = self::applyCallback($postCall, $actionName, $httpVars, $fileVars);
             if (isset($params)) {
                 $params["post_processor_results"][$postCall->getAttribute("pluginId")] = $postResult;
             }
         }
     }
     if ($captureCalls !== false) {
         $params["ob_output"] = ob_get_contents();
         ob_end_clean();
         foreach ($captureCalls as $captureCall) {
             self::applyCallback($captureCall, $actionName, $httpVars, $params);
         }
     } else {
         if (isset($result)) {
             return $result;
         }
     }
     return null;
 }
示例#20
0
 public function processQuery($actionName, &$httpVars, &$fileVars)
 {
     $query_name = AJXP_Utils::sanitize($httpVars["query_name"], AJXP_SANITIZE_ALPHANUM);
     $query = $this->getQuery($query_name);
     if ($query === false) {
         throw new Exception("Cannot find query " . $query_name);
     }
     $pg = $this->sqlDriver["driver"] == "postgre";
     $start = 0;
     $count = 30;
     if (isset($httpVars["start"])) {
         $start = intval($httpVars["start"]);
     }
     if (isset($httpVars["count"])) {
         $count = intval($httpVars["count"]);
     }
     $mess = ConfService::getMessages();
     $format = 'Y-m-d 00:00:00';
     $endFormat = 'Y-m-d 23:59:59';
     $dKeyFormat = $mess["date_relative_date_format"];
     $ref = time();
     $last = $start + $count;
     $startDate = date($format, strtotime("-{$last} day", $ref));
     $endDate = date($endFormat, strtotime("-{$start} day", $ref));
     $dateCursor = "logdate > '{$startDate}' AND logdate <= '{$endDate}'";
     $q = $query["SQL"];
     $q = str_replace("AJXP_CURSOR_DATE", $dateCursor, $q);
     if ($pg) {
         $q = str_replace("ORDER BY logdate DESC", "ORDER BY DATE(logdate) DESC", $q);
     }
     //$q .= " LIMIT $start, $count";
     $res = dibi::query($q);
     $all = $res->fetchAll();
     $allDates = array();
     foreach ($all as $row => &$data) {
         // PG: Recapitalize keys
         if ($pg) {
             foreach ($data as $k => $v) {
                 $data[ucfirst($k)] = $v;
             }
         }
         if (isset($data["Date"])) {
             if (is_a($data["Date"], "DibiDateTime")) {
                 $tStamp = $data["Date"]->getTimestamp();
             } else {
                 $tStamp = strtotime($data["Date"]);
             }
             $key = date($dKeyFormat, $tStamp);
             $data["Date_sortable"] = $tStamp;
             $data["Date"] = $key;
             $allDates[$key] = true;
         }
         if (isset($data["File"])) {
             $data["File"] = AJXP_Utils::safeBasename($data["File"]);
         }
     }
     if (isset($query["AXIS"]) && $query["AXIS"]["x"] == "Date") {
         for ($i = 0; $i < $count; $i++) {
             $dateCurs = $start + $i;
             $timeDate = strtotime("-{$dateCurs} day", $ref);
             $dateK = date($dKeyFormat, $timeDate);
             if (!isset($dKeyFormat[$dateK])) {
                 array_push($all, array("Date" => $dateK, "Date_sortable" => $timeDate));
             }
         }
     }
     if (isset($query["FIGURE"]) && isset($all[0][$query["FIGURE"]])) {
         $f = $all[0][$query["FIGURE"]];
         if ($f > 1000) {
             $f = number_format($f / 1000, 1, ".", " ") . 'K';
         }
         $all[0] = array($query["FIGURE"] => $f);
     }
     //$qry = "SELECT FOUND_ROWS() AS NbRows";
     //$res = dibi::query($qry);
     $total_count = 1000;
     //$res->fetchSingle();
     header('Content-type: application/json');
     $links = array();
     if ($start > $count) {
         $links[] = array('rel' => 'first', 'cursor' => 0, 'count' => $count);
     }
     if ($start > 0) {
         $prev = max(0, $start - $count);
         $links[] = array('rel' => 'previous', 'cursor' => $prev, 'count' => $count);
     }
     if ($start < $total_count) {
         $next = $start + $count;
         $links[] = array('rel' => 'next', 'cursor' => $next, 'count' => $count);
     }
     if ($start < $total_count - $count) {
         $last = $total_count - $total_count % $count;
         //$links[] = array('rel' => 'last', 'cursor' => $last, 'count' => $count);
     }
     $hLinks = array();
     foreach ($links as $link) {
         $hLinks[] = '<http://localhost/api/ajxp_conf/analytic_query/' . $query_name . '/' . $link["cursor"] . '/' . $link["cursor"] . '>; rel="' . $link["rel"] . '"';
     }
     header('Link: ' . implode(",", $hLinks));
     $envelope = array("links" => $links, "data" => $all);
     echo json_encode($envelope);
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $loggedUser = AuthService::getLoggedUser();
     if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) {
         return;
     }
     if (AuthService::usersEnabled()) {
         $currentBookmarks = AuthService::getLoggedUser()->getBookmarks();
         // FLATTEN
         foreach ($currentBookmarks as $bm) {
             $this->currentBookmarks[] = $bm["PATH"];
         }
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     $currentUserIsGroupAdmin = AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/";
     if ($currentUserIsGroupAdmin && ConfService::getAuthDriverImpl()->isAjxpAdmin(AuthService::getLoggedUser()->getId())) {
         $currentUserIsGroupAdmin = false;
     }
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("data" => array("LABEL" => $mess["ajxp_conf.110"], "ICON" => "user.png", "DESCRIPTION" => $mess["ajxp_conf.137"], "CHILDREN" => array("repositories" => array("AJXP_MIME" => "workspaces_zone", "LABEL" => $mess["ajxp_conf.3"], "DESCRIPTION" => $mess["ajxp_conf.138"], "ICON" => "hdd_external_unmount.png", "LIST" => "listRepositories"), "users" => array("AJXP_MIME" => "users_zone", "LABEL" => $mess["ajxp_conf.2"], "DESCRIPTION" => $mess["ajxp_conf.139"], "ICON" => "users-folder.png", "LIST" => "listUsers"), "roles" => array("AJXP_MIME" => "roles_zone", "LABEL" => $mess["ajxp_conf.69"], "DESCRIPTION" => $mess["ajxp_conf.140"], "ICON" => "user-acl.png", "LIST" => "listRoles"))), "config" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.109"], "ICON" => "preferences_desktop.png", "DESCRIPTION" => $mess["ajxp_conf.136"], "CHILDREN" => array("core" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.98"], "DESCRIPTION" => $mess["ajxp_conf.133"], "ICON" => "preferences_desktop.png", "LIST" => "listPlugins"), "plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.99"], "DESCRIPTION" => $mess["ajxp_conf.134"], "ICON" => "folder_development.png", "LIST" => "listPlugins"), "core_plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.123"], "DESCRIPTION" => $mess["ajxp_conf.135"], "ICON" => "folder_development.png", "LIST" => "listPlugins"))), "admin" => array("LABEL" => $mess["ajxp_conf.111"], "ICON" => "toggle_log.png", "DESCRIPTION" => $mess["ajxp_conf.141"], "CHILDREN" => array("logs" => array("LABEL" => $mess["ajxp_conf.4"], "DESCRIPTION" => $mess["ajxp_conf.142"], "ICON" => "toggle_log.png", "LIST" => "listLogFiles"), "diagnostic" => array("LABEL" => $mess["ajxp_conf.5"], "DESCRIPTION" => $mess["ajxp_conf.143"], "ICON" => "susehelpcenter.png", "LIST" => "printDiagnostic"))), "developer" => array("LABEL" => $mess["ajxp_conf.144"], "ICON" => "applications_engineering.png", "DESCRIPTION" => $mess["ajxp_conf.145"], "CHILDREN" => array("actions" => array("LABEL" => $mess["ajxp_conf.146"], "DESCRIPTION" => $mess["ajxp_conf.147"], "ICON" => "book.png", "LIST" => "listActions"), "hooks" => array("LABEL" => $mess["ajxp_conf.148"], "DESCRIPTION" => $mess["ajxp_conf.149"], "ICON" => "book.png", "LIST" => "listHooks"))));
             if ($currentUserIsGroupAdmin) {
                 unset($rootNodes["config"]);
                 unset($rootNodes["admin"]);
                 unset($rootNodes["developer"]);
             }
             AJXP_Controller::applyHook("ajxp_conf.list_config_nodes", array(&$rootNodes));
             $parentName = "";
             $dir = trim(AJXP_Utils::decodeSecureMagic(isset($httpVars["dir"]) ? $httpVars["dir"] : ""), " /");
             if ($dir != "") {
                 $hash = null;
                 if (strstr(urldecode($dir), "#") !== false) {
                     list($dir, $hash) = explode("#", urldecode($dir));
                 }
                 $splits = explode("/", $dir);
                 $root = array_shift($splits);
                 if (count($splits)) {
                     $returnNodes = false;
                     if (isset($httpVars["file"])) {
                         $returnNodes = true;
                     }
                     $child = $splits[0];
                     if (isset($rootNodes[$root]["CHILDREN"][$child])) {
                         $atts = array();
                         if ($child == "users") {
                             $atts["remote_indexation"] = "admin_search";
                         }
                         $callback = $rootNodes[$root]["CHILDREN"][$child]["LIST"];
                         if (is_string($callback) && method_exists($this, $callback)) {
                             if (!$returnNodes) {
                                 AJXP_XMLWriter::header("tree", $atts);
                             }
                             $res = call_user_func(array($this, $callback), implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : '');
                             if (!$returnNodes) {
                                 AJXP_XMLWriter::close();
                             }
                         } else {
                             if (is_array($callback)) {
                                 $res = call_user_func($callback, implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : '');
                             }
                         }
                         if ($returnNodes) {
                             AJXP_XMLWriter::header("tree", $atts);
                             if (isset($res["/" . $dir . "/" . $httpVars["file"]])) {
                                 print $res["/" . $dir . "/" . $httpVars["file"]];
                             }
                             AJXP_XMLWriter::close();
                         }
                         return;
                     }
                 } else {
                     $parentName = "/" . $root . "/";
                     $nodes = $rootNodes[$root]["CHILDREN"];
                 }
             } else {
                 $parentName = "/";
                 $nodes = $rootNodes;
             }
             if (isset($httpVars["file"])) {
                 $parentName = $httpVars["dir"] . "/";
                 $nodes = array(basename($httpVars["file"]) => array("LABEL" => basename($httpVars["file"])));
             }
             if (isset($nodes)) {
                 AJXP_XMLWriter::header();
                 if (!isset($httpVars["file"])) {
                     AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="detail"><column messageId="ajxp_conf.1" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.102" attributeName="description" sortType="String"/></columns>');
                 }
                 foreach ($nodes as $key => $data) {
                     $bmString = '';
                     if (in_array($parentName . $key, $this->currentBookmarks)) {
                         $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" ';
                     }
                     if ($key == "users") {
                         $bmString .= ' remote_indexation="admin_search"';
                     }
                     if (isset($data["AJXP_MIME"])) {
                         $bmString .= ' ajxp_mime="' . $data["AJXP_MIME"] . '"';
                     }
                     if (empty($data["CHILDREN"])) {
                         print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '/>';
                     } else {
                         print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '>';
                         foreach ($data["CHILDREN"] as $cKey => $cData) {
                             $bmString = '';
                             if (in_array($parentName . $key . "/" . $cKey, $this->currentBookmarks)) {
                                 $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" ';
                             }
                             if ($cKey == "users") {
                                 $bmString .= ' remote_indexation="admin_search"';
                             }
                             if (isset($cData["AJXP_MIME"])) {
                                 $bmString .= ' ajxp_mime="' . $cData["AJXP_MIME"] . '"';
                             }
                             print '<tree text="' . AJXP_Utils::xmlEntities($cData["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($cData["DESCRIPTION"]) . '" icon="' . $cData["ICON"] . '" filename="' . $parentName . $key . '/' . $cKey . '" ' . $bmString . '/>';
                         }
                         print '</tree>';
                     }
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             return;
             break;
         case "clear_plugins_cache":
             AJXP_XMLWriter::header();
             // Clear plugins cache if they exist
             AJXP_PluginsService::clearPluginsCache();
             ConfService::clearMessagesCache();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . (AJXP_SKIP_CACHE ? "132" : "131")], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "create_group":
             if (isset($httpVars["group_path"])) {
                 $basePath = AJXP_Utils::forwardSlashDirname($httpVars["group_path"]);
                 if (empty($basePath)) {
                     $basePath = "/";
                 }
                 $gName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic(basename($httpVars["group_path"])), AJXP_SANITIZE_ALPHANUM);
             } else {
                 $basePath = substr($httpVars["dir"], strlen("/data/users"));
                 $gName = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["group_name"]), AJXP_SANITIZE_ALPHANUM);
             }
             $gLabel = AJXP_Utils::decodeSecureMagic($httpVars["group_label"]);
             AuthService::createGroup($basePath, $gName, $gLabel);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.124"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "create_role":
             $roleId = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["role_id"]), AJXP_SANITIZE_HTML_STRICT);
             if (!strlen($roleId)) {
                 throw new Exception($mess[349]);
             }
             if (AuthService::getRole($roleId) !== false) {
                 throw new Exception($mess["ajxp_conf.65"]);
             }
             $r = new AJXP_Role($roleId);
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                 $r->setGroupPath(AuthService::getLoggedUser()->getGroupPath());
             }
             AuthService::updateRole($r);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null);
             AJXP_XMLWriter::reloadDataNode("", $httpVars["role_id"]);
             AJXP_XMLWriter::close();
             break;
         case "edit_role":
             $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]);
             $roleGroup = false;
             $userObject = null;
             $groupLabel = null;
             if (strpos($roleId, "AJXP_GRP_") === 0) {
                 $groupPath = substr($roleId, strlen("AJXP_GRP_"));
                 $filteredGroupPath = AuthService::filterBaseGroup($groupPath);
                 $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath));
                 $key = "/" . basename($groupPath);
                 if (!array_key_exists($key, $groups)) {
                     throw new Exception("Cannot find group with this id!");
                 }
                 $roleId = "AJXP_GRP_" . $filteredGroupPath;
                 $groupLabel = $groups[$key];
                 $roleGroup = true;
             }
             if (strpos($roleId, "AJXP_USR_") === 0) {
                 $usrId = str_replace("AJXP_USR_/", "", $roleId);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cant find user!");
                 }
                 $role = $userObject->personalRole;
             } else {
                 $role = AuthService::getRole($roleId, $roleGroup);
             }
             if ($role === false) {
                 throw new Exception("Cant find role! ");
             }
             if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
                 HTMLWriter::charsetHeader("application/json");
                 $roleData = $role->getDataArray(true);
                 $allReps = ConfService::getRepositoriesList("all", false);
                 $repos = array();
                 if (!empty($userObject)) {
                     // USER
                     foreach ($allReps as $repositoryId => $repositoryObject) {
                         if (!AuthService::canAssign($repositoryObject, $userObject) || $repositoryObject->isTemplate || $repositoryObject->getAccessType() == "ajxp_conf" && !$userObject->isAdmin() || $repositoryObject->getUniqueUser() != null && $repositoryObject->getUniqueUser() != $userObject->getId()) {
                             continue;
                         }
                         $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay());
                     }
                 } else {
                     foreach ($allReps as $repositoryId => $repositoryObject) {
                         if (!AuthService::canAdministrate($repositoryObject)) {
                             continue;
                         }
                         $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay());
                     }
                 }
                 // Make sure it's utf8
                 $data = array("ROLE" => $roleData, "ALL" => array("REPOSITORIES" => $repos));
                 if (isset($userObject)) {
                     $data["USER"] = array();
                     $data["USER"]["LOCK"] = $userObject->getLock();
                     $data["USER"]["PROFILE"] = $userObject->getProfile();
                     $data["ALL"]["PROFILES"] = array("standard|Standard", "admin|Administrator", "shared|Shared", "guest|Guest");
                     $data["USER"]["ROLES"] = array_keys($userObject->getRoles());
                     $data["ALL"]["ROLES"] = array_keys(AuthService::getRolesList(array(), true));
                     if (isset($userObject->parentRole)) {
                         $data["PARENT_ROLE"] = $userObject->parentRole->getDataArray();
                     }
                 } else {
                     if (isset($groupPath)) {
                         $data["GROUP"] = array("PATH" => $groupPath, "LABEL" => $groupLabel);
                     }
                 }
                 $scope = "role";
                 if ($roleGroup) {
                     $scope = "group";
                 } else {
                     if (isset($userObject)) {
                         $scope = "user";
                     }
                 }
                 $data["SCOPE_PARAMS"] = array();
                 $nodes = AJXP_PluginsService::getInstance()->searchAllManifests("//param[contains(@scope,'" . $scope . "')]|//global_param[contains(@scope,'" . $scope . "')]", "node", false, true, true);
                 foreach ($nodes as $node) {
                     $pId = $node->parentNode->parentNode->attributes->getNamedItem("id")->nodeValue;
                     $origName = $node->attributes->getNamedItem("name")->nodeValue;
                     $node->attributes->getNamedItem("name")->nodeValue = "AJXP_REPO_SCOPE_ALL/" . $pId . "/" . $origName;
                     $nArr = array();
                     foreach ($node->attributes as $attrib) {
                         $nArr[$attrib->nodeName] = AJXP_XMLWriter::replaceAjxpXmlKeywords($attrib->nodeValue);
                     }
                     $data["SCOPE_PARAMS"][] = $nArr;
                 }
                 echo json_encode($data);
             }
             break;
         case "post_json_role":
             $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]);
             $roleGroup = false;
             $userObject = $usrId = $filteredGroupPath = null;
             if (strpos($roleId, "AJXP_GRP_") === 0) {
                 $groupPath = substr($roleId, strlen("AJXP_GRP_"));
                 $filteredGroupPath = AuthService::filterBaseGroup($groupPath);
                 $roleId = "AJXP_GRP_" . $filteredGroupPath;
                 $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath));
                 $key = "/" . basename($groupPath);
                 if (!array_key_exists($key, $groups)) {
                     throw new Exception("Cannot find group with this id!");
                 }
                 $groupLabel = $groups[$key];
                 $roleGroup = true;
             }
             if (strpos($roleId, "AJXP_USR_") === 0) {
                 $usrId = str_replace("AJXP_USR_/", "", $roleId);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cannot post role for user " . $usrId);
                 }
                 $originalRole = $userObject->personalRole;
             } else {
                 // second param = create if not exists.
                 $originalRole = AuthService::getRole($roleId, $roleGroup);
             }
             if ($originalRole === false) {
                 throw new Exception("Cant find role! ");
             }
             $jsonData = SystemTextEncoding::magicDequote($httpVars["json_data"]);
             $data = json_decode($jsonData, true);
             $roleData = $data["ROLE"];
             $forms = $data["FORMS"];
             $binariesContext = array();
             if (isset($userObject)) {
                 $binariesContext = array("USER" => $userObject->getId());
             }
             foreach ($forms as $repoScope => $plugData) {
                 foreach ($plugData as $plugId => $formsData) {
                     $parsed = array();
                     AJXP_Utils::parseStandardFormParameters($formsData, $parsed, $userObject != null ? $usrId : null, "ROLE_PARAM_", $binariesContext, AJXP_Role::$cypheredPassPrefix);
                     $roleData["PARAMETERS"][$repoScope][$plugId] = $parsed;
                 }
             }
             $existingParameters = $originalRole->listParameters(true);
             $this->mergeExistingParameters($roleData["PARAMETERS"], $existingParameters);
             if (isset($userObject) && isset($data["USER"]) && isset($data["USER"]["PROFILE"])) {
                 $userObject->setAdmin($data["USER"]["PROFILE"] == "admin");
                 $userObject->setProfile($data["USER"]["PROFILE"]);
             }
             if (isset($data["GROUP_LABEL"]) && isset($groupLabel) && $groupLabel != $data["GROUP_LABEL"]) {
                 ConfService::getConfStorageImpl()->relabelGroup($filteredGroupPath, $data["GROUP_LABEL"]);
             }
             if ($currentUserIsGroupAdmin) {
                 // FILTER DATA FOR GROUP ADMINS
                 $params = $this->getEditableParameters(false);
                 foreach ($roleData["PARAMETERS"] as $scope => &$plugsParameters) {
                     foreach ($plugsParameters as $paramPlugin => &$parameters) {
                         foreach ($parameters as $pName => $pValue) {
                             if (!isset($params[$paramPlugin]) || !in_array($pName, $params[$paramPlugin])) {
                                 unset($parameters[$pName]);
                             }
                         }
                         if (!count($parameters)) {
                             unset($plugsParameters[$paramPlugin]);
                         }
                     }
                     if (!count($plugsParameters)) {
                         unset($roleData["PARAMETERS"][$scope]);
                     }
                 }
                 // Remerge from parent
                 $roleData["PARAMETERS"] = $originalRole->array_merge_recursive2($originalRole->listParameters(), $roleData["PARAMETERS"]);
                 // Changing Actions is not allowed
                 $roleData["ACTIONS"] = $originalRole->listActionsStates();
             }
             try {
                 $originalRole->bunchUpdate($roleData);
                 if (isset($userObject)) {
                     $userObject->personalRole = $originalRole;
                     $userObject->save("superuser");
                 } else {
                     AuthService::updateRole($originalRole);
                 }
                 $output = array("ROLE" => $originalRole->getDataArray(true), "SUCCESS" => true);
             } catch (Exception $e) {
                 $output = array("ERROR" => $e->getMessage());
             }
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($output);
             break;
         case "user_set_lock":
             $userId = AJXP_Utils::decodeSecureMagic($httpVars["user_id"]);
             $lock = $httpVars["lock"] == "true" ? true : false;
             $lockType = $httpVars["lock_type"];
             if (AuthService::userExists($userId)) {
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cannot update user data for " . $userId);
                 }
                 if ($lock) {
                     $userObject->setLock($lockType);
                 } else {
                     $userObject->removeLock();
                 }
                 $userObject->save("superuser");
             }
             break;
         case "create_user":
             if (!isset($httpVars["new_user_login"]) || $httpVars["new_user_login"] == "" || !isset($httpVars["new_user_pwd"]) || $httpVars["new_user_pwd"] == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $original_login = SystemTextEncoding::magicDequote($httpVars["new_user_login"]);
             $new_user_login = AJXP_Utils::sanitize($original_login, AJXP_SANITIZE_EMAILCHARS);
             if ($original_login != $new_user_login) {
                 throw new Exception(str_replace("%s", $new_user_login, $mess["ajxp_conf.127"]));
             }
             if (AuthService::userExists($new_user_login, "w") || AuthService::isReservedUserId($new_user_login)) {
                 throw new Exception($mess["ajxp_conf.43"]);
             }
             AuthService::createUser($new_user_login, $httpVars["new_user_pwd"]);
             $confStorage = ConfService::getConfStorageImpl();
             $newUser = $confStorage->createUserObject($new_user_login);
             $basePath = AuthService::getLoggedUser()->getGroupPath();
             if (empty($basePath)) {
                 $basePath = "/";
             }
             if (!empty($httpVars["group_path"])) {
                 $newUser->setGroupPath(rtrim($basePath, "/") . "/" . ltrim($httpVars["group_path"], "/"));
             } else {
                 $newUser->setGroupPath($basePath);
             }
             $newUser->save("superuser");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.44"], null);
             AJXP_XMLWriter::reloadDataNode("", $new_user_login);
             AJXP_XMLWriter::close();
             break;
         case "change_admin_right":
             $userId = $httpVars["user_id"];
             if (!AuthService::userExists($userId)) {
                 throw new Exception("Invalid user id!");
             }
             $confStorage = ConfService::getConfStorageImpl();
             $user = $confStorage->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $user->setAdmin($httpVars["right_value"] == "1" ? true : false);
             $user->save("superuser");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.45"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "role_update_right":
             if (!isset($httpVars["role_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 break;
             }
             $rId = AJXP_Utils::sanitize($httpVars["role_id"]);
             $role = AuthService::getRole($rId);
             if ($role === false) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"] . "(" . $rId . ")");
                 AJXP_XMLWriter::close();
                 break;
             }
             $role->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM));
             AuthService::updateRole($role);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["role_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "user_update_right":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"]) || !AuthService::userExists($httpVars["user_id"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>";
                 AJXP_XMLWriter::close();
                 return;
             }
             $confStorage = ConfService::getConfStorageImpl();
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             $user = $confStorage->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $user->personalRole->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM));
             $user->save();
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["user_id"], null);
             print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $user->canRead($httpVars["repository_id"]) . "\" write=\"" . $user->canWrite($httpVars["repository_id"]) . "\"/>";
             AJXP_XMLWriter::reloadRepositoryList();
             AJXP_XMLWriter::close();
             return;
             break;
         case "user_update_group":
             $userSelection = new UserSelection();
             $userSelection->initFromHttpVars($httpVars);
             $dir = $httpVars["dir"];
             $dest = $httpVars["dest"];
             if (isset($httpVars["group_path"])) {
                 // API Case
                 $groupPath = $httpVars["group_path"];
             } else {
                 if (strpos($dir, "/data/users", 0) !== 0 || strpos($dest, "/data/users", 0) !== 0) {
                     break;
                 }
                 $groupPath = substr($dest, strlen("/data/users"));
             }
             $confStorage = ConfService::getConfStorageImpl();
             $userId = null;
             $usersMoved = array();
             $basePath = AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getGroupPath() : "/";
             if (empty($basePath)) {
                 $basePath = "/";
             }
             if (!empty($groupPath)) {
                 $targetPath = rtrim($basePath, "/") . "/" . ltrim($groupPath, "/");
             } else {
                 $targetPath = $basePath;
             }
             foreach ($userSelection->getFiles() as $selectedUser) {
                 $userId = basename($selectedUser);
                 if (!AuthService::userExists($userId)) {
                     continue;
                 }
                 $user = $confStorage->createUserObject($userId);
                 if (!AuthService::canAdministrate($user)) {
                     continue;
                 }
                 $user->setGroupPath($targetPath, true);
                 $user->save("superuser");
                 $usersMoved[] = $user->getId();
             }
             AJXP_XMLWriter::header();
             if (count($usersMoved)) {
                 AJXP_XMLWriter::sendMessage(count($usersMoved) . " user(s) successfully moved to " . $targetPath, null);
                 AJXP_XMLWriter::reloadDataNode($dest, $userId);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage(null, "No users moved, there must have been something wrong.");
             }
             AJXP_XMLWriter::close();
             break;
         case "user_add_role":
         case "user_delete_role":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["role_id"]) || !AuthService::userExists($httpVars["user_id"]) || !AuthService::getRole($httpVars["role_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             if ($action == "user_add_role") {
                 $act = "add";
                 $messId = "73";
             } else {
                 $act = "remove";
                 $messId = "74";
             }
             $this->updateUserRole(AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS), $httpVars["role_id"], $act);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . $messId] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             return;
             break;
         case "user_update_role":
             $confStorage = ConfService::getConfStorageImpl();
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $files = $selection->getFiles();
             $detectedRoles = array();
             $roleId = null;
             if (isset($httpVars["role_id"]) && isset($httpVars["update_role_action"])) {
                 $update = $httpVars["update_role_action"];
                 $roleId = $httpVars["role_id"];
                 if (AuthService::getRole($roleId) === false) {
                     throw new Exception("Invalid role id");
                 }
             }
             foreach ($files as $index => $file) {
                 $userId = basename($file);
                 if (isset($update)) {
                     $userObject = $this->updateUserRole($userId, $roleId, $update);
                 } else {
                     $userObject = $confStorage->createUserObject($userId);
                     if (!AuthService::canAdministrate($userObject)) {
                         continue;
                     }
                 }
                 if ($userObject->hasParent()) {
                     unset($files[$index]);
                     continue;
                 }
                 $userRoles = $userObject->getRoles();
                 foreach ($userRoles as $roleIndex => $bool) {
                     if (!isset($detectedRoles[$roleIndex])) {
                         $detectedRoles[$roleIndex] = 0;
                     }
                     if ($bool === true) {
                         $detectedRoles[$roleIndex]++;
                     }
                 }
             }
             $count = count($files);
             AJXP_XMLWriter::header("admin_data");
             print "<user><ajxp_roles>";
             foreach ($detectedRoles as $roleId => $roleCount) {
                 if ($roleCount < $count) {
                     continue;
                 }
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles></user>";
             print "<ajxp_roles>";
             foreach (AuthService::getRolesList(array(), !$this->listSpecialRoles) as $roleId => $roleObject) {
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "save_custom_user_params":
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $custom = $user->getPref("CUSTOM_PARAMS");
             if (!is_array($custom)) {
                 $custom = array();
             }
             $options = $custom;
             $this->parseParameters($httpVars, $options, $userId, false, $custom);
             $custom = $options;
             $user->setPref("CUSTOM_PARAMS", $custom);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "save_repository_user_params":
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $wallet = $user->getPref("AJXP_WALLET");
             if (!is_array($wallet)) {
                 $wallet = array();
             }
             $repoID = $httpVars["repository_id"];
             if (!array_key_exists($repoID, $wallet)) {
                 $wallet[$repoID] = array();
             }
             $options = $wallet[$repoID];
             $existing = $options;
             $this->parseParameters($httpVars, $options, $userId, false, $existing);
             $wallet[$repoID] = $options;
             $user->setPref("AJXP_WALLET", $wallet);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "update_user_pwd":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["user_pwd"]) || !AuthService::userExists($httpVars["user_id"]) || trim($httpVars["user_pwd"]) == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             $user = ConfService::getConfStorageImpl()->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user data for " . $userId);
             }
             $res = AuthService::updatePassword($userId, $httpVars["user_pwd"]);
             AJXP_XMLWriter::header();
             if ($res === true) {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.48"] . $userId, null);
             } else {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.49"] . " : {$res}");
             }
             AJXP_XMLWriter::close();
             break;
         case "save_user_preference":
             if (!isset($httpVars["user_id"]) || !AuthService::userExists($httpVars["user_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $userObject = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $userObject = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($userObject)) {
                 throw new Exception("Cannot update user data for " . $userId);
             }
             $i = 0;
             while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && $userObject == null) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save("user");
                 $i++;
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage("Succesfully saved user preference", null);
             AJXP_XMLWriter::close();
             break;
         case "get_drivers_definition":
             AJXP_XMLWriter::header("drivers", array("allowed" => $currentUserIsGroupAdmin ? "false" : "true"));
             print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("param", "", true));
             AJXP_XMLWriter::close("drivers");
             break;
         case "get_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $count = 0;
             $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => '1'), $count);
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 $repoId = $repo->getUniqueId();
                 $repoLabel = SystemTextEncoding::toUTF8($repo->getDisplay());
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 foreach ($repo->getOptionsDefined() as $optionName) {
                     print "<option name=\"{$optionName}\"/>";
                 }
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "create_repository":
             $repDef = $httpVars;
             $isTemplate = isset($httpVars["sf_checkboxes_active"]);
             unset($repDef["get_action"]);
             unset($repDef["sf_checkboxes_active"]);
             if (isset($httpVars["json_data"])) {
                 $repDef = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
                 $options = $repDef["DRIVER_OPTIONS"];
             } else {
                 $options = array();
                 $this->parseParameters($repDef, $options, null, true);
             }
             if (count($options)) {
                 $repDef["DRIVER_OPTIONS"] = $options;
                 unset($repDef["DRIVER_OPTIONS"]["AJXP_GROUP_PATH_PARAMETER"]);
             }
             if (strstr($repDef["DRIVER"], "ajxp_template_") !== false) {
                 $templateId = substr($repDef["DRIVER"], 14);
                 $templateRepo = ConfService::getRepositoryById($templateId);
                 $newRep = $templateRepo->createTemplateChild($repDef["DISPLAY"], $repDef["DRIVER_OPTIONS"]);
                 if (isset($repDef["AJXP_SLUG"])) {
                     $newRep->setSlug($repDef["AJXP_SLUG"]);
                 }
             } else {
                 if ($currentUserIsGroupAdmin) {
                     throw new Exception("You are not allowed to create a workspace from a driver. Use a template instead.");
                 }
                 $pServ = AJXP_PluginsService::getInstance();
                 $driver = $pServ->getPluginByTypeName("access", $repDef["DRIVER"]);
                 $newRep = ConfService::createRepositoryFromArray(0, $repDef);
                 $testFile = $driver->getBaseDir() . "/test." . $newRep->getAccessType() . "Access.php";
                 if (!$isTemplate && is_file($testFile)) {
                     //chdir(AJXP_TESTS_FOLDER."/plugins");
                     $className = $newRep->getAccessType() . "AccessTest";
                     if (!class_exists($className)) {
                         include $testFile;
                     }
                     $class = new $className();
                     $result = $class->doRepositoryTest($newRep);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 // Apply default metasource if any
                 if ($driver != null && $driver->getConfigs() != null) {
                     $confs = $driver->getConfigs();
                     if (!empty($confs["DEFAULT_METASOURCES"])) {
                         $metaIds = AJXP_Utils::parseCSL($confs["DEFAULT_METASOURCES"]);
                         $metaSourceOptions = array();
                         foreach ($metaIds as $metaID) {
                             $metaPlug = $pServ->getPluginById($metaID);
                             if ($metaPlug == null) {
                                 continue;
                             }
                             $pNodes = $metaPlug->getManifestRawContent("//param[@default]", "nodes");
                             $defaultParams = array();
                             foreach ($pNodes as $domNode) {
                                 $defaultParams[$domNode->getAttribute("name")] = $domNode->getAttribute("default");
                             }
                             $metaSourceOptions[$metaID] = $defaultParams;
                         }
                         $newRep->addOption("META_SOURCES", $metaSourceOptions);
                     }
                 }
             }
             if ($this->repositoryExists($newRep->getDisplay())) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             if ($isTemplate) {
                 $newRep->isTemplate = true;
             }
             if ($currentUserIsGroupAdmin) {
                 $newRep->setGroupPath(AuthService::getLoggedUser()->getGroupPath());
             } else {
                 if (!empty($options["AJXP_GROUP_PATH_PARAMETER"])) {
                     $basePath = "/";
                     if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                         $basePath = AuthService::getLoggedUser()->getGroupPath();
                     }
                     $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($options["AJXP_GROUP_PATH_PARAMETER"], "/"));
                     $newRep->setGroupPath($value);
                 }
             }
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw");
                 $loggedUser->recomputeMergedRole();
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.52"], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "edit_repository":
             $repId = $httpVars["repository_id"];
             $repository = ConfService::getRepositoryById($repId);
             if ($repository == null) {
                 throw new Exception("Cannot find workspace with id {$repId}");
             }
             if (!AuthService::canAdministrate($repository)) {
                 throw new Exception("You are not allowed to edit this workspace!");
             }
             $pServ = AJXP_PluginsService::getInstance();
             $plug = $pServ->getPluginById("access." . $repository->accessType);
             if ($plug == null) {
                 throw new Exception("Cannot find access driver (" . $repository->accessType . ") for workspace!");
             }
             AJXP_XMLWriter::header("admin_data");
             $slug = $repository->getSlug();
             if ($slug == "" && $repository->isWriteable()) {
                 $repository->setSlug();
                 ConfService::replaceRepository($repId, $repository);
             }
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                 $rgp = $repository->getGroupPath();
                 if ($rgp == null) {
                     $rgp = "/";
                 }
                 if (strlen($rgp) < strlen(AuthService::getLoggedUser()->getGroupPath())) {
                     $repository->setWriteable(false);
                 }
             }
             $nested = array();
             $definitions = $plug->getConfigsDefinitions();
             print "<repository index=\"{$repId}\"";
             foreach ($repository as $name => $option) {
                 if (strstr($name, " ") > -1) {
                     continue;
                 }
                 if (!is_array($option)) {
                     if (is_bool($option)) {
                         $option = $option ? "true" : "false";
                     }
                     print " {$name}=\"" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($option)) . "\" ";
                 } else {
                     if (is_array($option)) {
                         $nested[] = $option;
                     }
                 }
             }
             if (count($nested)) {
                 print ">";
                 foreach ($nested as $option) {
                     foreach ($option as $key => $optValue) {
                         if (is_array($optValue) && count($optValue)) {
                             print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>";
                         } else {
                             if (is_object($optValue)) {
                                 print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>";
                             } else {
                                 if (is_bool($optValue)) {
                                     $optValue = $optValue ? "true" : "false";
                                 } else {
                                     if (isset($definitions[$key]) && $definitions[$key]["type"] == "password" && !empty($optValue)) {
                                         $optValue = "__AJXP_VALUE_SET__";
                                     }
                                 }
                                 $optValue = AJXP_Utils::xmlEntities($optValue, true);
                                 print "<param name=\"{$key}\" value=\"{$optValue}\"/>";
                             }
                         }
                     }
                 }
                 // Add SLUG
                 if (!$repository->isTemplate) {
                     print "<param name=\"AJXP_SLUG\" value=\"" . $repository->getSlug() . "\"/>";
                 }
                 if ($repository->getGroupPath() != null) {
                     $basePath = "/";
                     if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                         $basePath = AuthService::getLoggedUser()->getGroupPath();
                     }
                     $groupPath = $repository->getGroupPath();
                     if ($basePath != "/") {
                         $groupPath = substr($repository->getGroupPath(), strlen($basePath));
                     }
                     print "<param name=\"AJXP_GROUP_PATH_PARAMETER\" value=\"" . $groupPath . "\"/>";
                 }
                 print "</repository>";
             } else {
                 print "/>";
             }
             if ($repository->hasParent()) {
                 $parent = ConfService::getRepositoryById($repository->getParentId());
                 if (isset($parent) && $parent->isTemplate) {
                     $parentLabel = $parent->getDisplay();
                     $parentType = $parent->getAccessType();
                     print "<template repository_id=\"" . $repository->getParentId() . "\" repository_label=\"{$parentLabel}\" repository_type=\"{$parentType}\">";
                     foreach ($parent->getOptionsDefined() as $parentOptionName) {
                         print "<option name=\"{$parentOptionName}\"/>";
                     }
                     print "</template>";
                 }
             }
             $manifest = $plug->getManifestRawContent("server_settings/param");
             $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
             print "<ajxpdriver name=\"" . $repository->accessType . "\">{$manifest}</ajxpdriver>";
             print "<metasources>";
             $metas = $pServ->getPluginsByType("metastore");
             $metas = array_merge($metas, $pServ->getPluginsByType("meta"));
             $metas = array_merge($metas, $pServ->getPluginsByType("index"));
             foreach ($metas as $metaPlug) {
                 print "<meta id=\"" . $metaPlug->getId() . "\" label=\"" . AJXP_Utils::xmlEntities($metaPlug->getManifestLabel()) . "\">";
                 $manifest = $metaPlug->getManifestRawContent("server_settings/param");
                 $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
                 print $manifest;
                 print "</meta>";
             }
             print "</metasources>";
             AJXP_XMLWriter::close("admin_data");
             return;
             break;
         case "edit_repository_label":
         case "edit_repository_data":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!$repo->isWriteable()) {
                 throw new Exception("This workspace is not writeable. Please edit directly the conf/bootstrap_repositories.php file.");
             }
             $res = 0;
             if (isset($httpVars["newLabel"])) {
                 $newLabel = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["newLabel"]), AJXP_SANITIZE_HTML);
                 if ($this->repositoryExists($newLabel)) {
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                     AJXP_XMLWriter::close();
                     return;
                 }
                 $repo->setDisplay($newLabel);
                 $res = ConfService::replaceRepository($repId, $repo);
             } else {
                 $options = array();
                 $existing = $repo->getOptionsDefined();
                 $existingValues = array();
                 foreach ($existing as $exK) {
                     $existingValues[$exK] = $repo->getOption($exK, true);
                 }
                 $this->parseParameters($httpVars, $options, null, true, $existingValues);
                 if (count($options)) {
                     foreach ($options as $key => $value) {
                         if ($key == "AJXP_SLUG") {
                             $repo->setSlug($value);
                             continue;
                         } elseif ($key == "AJXP_GROUP_PATH_PARAMETER") {
                             $basePath = "/";
                             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                                 $basePath = AuthService::getLoggedUser()->getGroupPath();
                             }
                             $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($value, "/"));
                             $repo->setGroupPath($value);
                             continue;
                         }
                         $repo->addOption($key, $value);
                     }
                 }
                 if ($repo->getOption("DEFAULT_RIGHTS")) {
                     $gp = $repo->getGroupPath();
                     if (empty($gp) || $gp == "/") {
                         $defRole = AuthService::getRole("ROOT_ROLE");
                     } else {
                         $defRole = AuthService::getRole("AJXP_GRP_" . $gp, true);
                     }
                     if ($defRole !== false) {
                         $defRole->setAcl($repId, $repo->getOption("DEFAULT_RIGHTS"));
                         AuthService::updateRole($defRole);
                     }
                 }
                 if (is_file(AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php")) {
                     chdir(AJXP_TESTS_FOLDER . "/plugins");
                     include AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php";
                     $className = "ajxp_" . $repo->getAccessType();
                     $class = new $className();
                     $result = $class->doRepositoryTest($repo);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 ConfService::replaceRepository($repId, $repo);
             }
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.53"]);
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.54"], null);
                 if (isset($httpVars["newLabel"])) {
                     AJXP_XMLWriter::reloadDataNode("", $repId);
                 }
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "meta_source_add":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceType = AJXP_Utils::sanitize($httpVars["new_meta_source"], AJXP_SANITIZE_ALPHANUM);
             if (isset($httpVars["json_data"])) {
                 $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
             } else {
                 $options = array();
                 $this->parseParameters($httpVars, $options, null, true);
             }
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && isset($repoOptions[$metaSourceType])) {
                 throw new Exception($mess["ajxp_conf.55"]);
             }
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             $repoOptions[$metaSourceType] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.56"], null);
             AJXP_XMLWriter::close();
             break;
         case "meta_source_delete":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && array_key_exists($metaSourceId, $repoOptions)) {
                 unset($repoOptions[$metaSourceId]);
                 uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
                 $repo->addOption("META_SOURCES", $repoOptions);
                 ConfService::replaceRepository($repId, $repo);
             } else {
                 throw new Exception("Cannot find meta source " . $metaSourceId);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.57"], null);
             AJXP_XMLWriter::close();
             break;
         case "meta_source_edit":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $repoOptions = $repo->getOption("META_SOURCES");
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             if (isset($httpVars["json_data"])) {
                 $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
             } else {
                 $options = array();
                 $this->parseParameters($httpVars, $options, null, true);
             }
             if (isset($repoOptions[$metaSourceId])) {
                 $this->mergeExistingParameters($options, $repoOptions[$metaSourceId]);
             }
             $repoOptions[$metaSourceId] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.58"], null);
             AJXP_XMLWriter::close();
             break;
         case "delete":
             // REST API mapping
             if (isset($httpVars["data_type"])) {
                 switch ($httpVars["data_type"]) {
                     case "repository":
                         $httpVars["repository_id"] = basename($httpVars["data_id"]);
                         break;
                     case "role":
                         $httpVars["role_id"] = basename($httpVars["data_id"]);
                         break;
                     case "user":
                         $httpVars["user_id"] = basename($httpVars["data_id"]);
                         break;
                     case "group":
                         $httpVars["group"] = "/data/users" . $httpVars["data_id"];
                         break;
                     default:
                         break;
                 }
                 unset($httpVars["data_type"]);
                 unset($httpVars["data_id"]);
             }
             if (isset($httpVars["repository_id"])) {
                 $repId = $httpVars["repository_id"];
                 $repo = ConfService::getRepositoryById($repId);
                 if (!is_object($repo)) {
                     $res = -1;
                 } else {
                     $res = ConfService::deleteRepository($repId);
                 }
                 AJXP_XMLWriter::header();
                 if ($res == -1) {
                     AJXP_XMLWriter::sendMessage(null, $mess[427]);
                 } else {
                     AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::reloadRepositoryList();
                 }
                 AJXP_XMLWriter::close();
                 return;
             } else {
                 if (isset($httpVars["role_id"])) {
                     $roleId = $httpVars["role_id"];
                     if (AuthService::getRole($roleId) === false) {
                         throw new Exception($mess["ajxp_conf.67"]);
                     }
                     AuthService::deleteRole($roleId);
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage($mess["ajxp_conf.68"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::close();
                 } else {
                     if (isset($httpVars["group"])) {
                         $groupPath = $httpVars["group"];
                         $basePath = substr(AJXP_Utils::forwardSlashDirname($groupPath), strlen("/data/users"));
                         $gName = basename($groupPath);
                         AuthService::deleteGroup($basePath, $gName);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.128"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     } else {
                         if (!isset($httpVars["user_id"]) || $httpVars["user_id"] == "" || AuthService::isReservedUserId($httpVars["user_id"]) || $loggedUser->getId() == $httpVars["user_id"]) {
                             AJXP_XMLWriter::header();
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                             AJXP_XMLWriter::close();
                         }
                         AuthService::deleteUser($httpVars["user_id"]);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     }
                 }
             }
             break;
         case "get_plugin_manifest":
             $ajxpPlugin = AJXP_PluginsService::getInstance()->getPluginById($httpVars["plugin_id"]);
             AJXP_XMLWriter::header("admin_data");
             $fullManifest = $ajxpPlugin->getManifestRawContent("", "xml");
             $xPath = new DOMXPath($fullManifest->ownerDocument);
             $addParams = "";
             $instancesDefinitions = array();
             $pInstNodes = $xPath->query("server_settings/global_param[contains(@type, 'plugin_instance:')]");
             foreach ($pInstNodes as $pInstNode) {
                 $type = $pInstNode->getAttribute("type");
                 $instType = str_replace("plugin_instance:", "", $type);
                 $fieldName = $pInstNode->getAttribute("name");
                 $pInstNode->setAttribute("type", "group_switch:" . $fieldName);
                 $typePlugs = AJXP_PluginsService::getInstance()->getPluginsByType($instType);
                 foreach ($typePlugs as $typePlug) {
                     if ($typePlug->getId() == "auth.multi") {
                         continue;
                     }
                     $checkErrorMessage = "";
                     try {
                         $typePlug->performChecks();
                     } catch (Exception $e) {
                         $checkErrorMessage = " (Warning : " . $e->getMessage() . ")";
                     }
                     $tParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[not(@group_switch_name)]"));
                     $addParams .= '<global_param group_switch_name="' . $fieldName . '" name="instance_name" group_switch_label="' . $typePlug->getManifestLabel() . $checkErrorMessage . '" group_switch_value="' . $typePlug->getId() . '" default="' . $typePlug->getId() . '" type="hidden"/>';
                     $addParams .= str_replace("<param", "<global_param group_switch_name=\"{$fieldName}\" group_switch_label=\"" . $typePlug->getManifestLabel() . $checkErrorMessage . "\" group_switch_value=\"" . $typePlug->getId() . "\" ", $tParams);
                     $addParams .= str_replace("<param", "<global_param", AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[@group_switch_name]")));
                     $addParams .= AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/global_param"));
                     $instancesDefs = $typePlug->getConfigsDefinitions();
                     if (!empty($instancesDefs) && is_array($instancesDefs)) {
                         foreach ($instancesDefs as $defKey => $defData) {
                             $instancesDefinitions[$fieldName . "/" . $defKey] = $defData;
                         }
                     }
                 }
             }
             $allParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($fullManifest->ownerDocument->saveXML($fullManifest));
             $allParams = str_replace('type="plugin_instance:', 'type="group_switch:', $allParams);
             $allParams = str_replace("</server_settings>", $addParams . "</server_settings>", $allParams);
             echo $allParams;
             $definitions = $instancesDefinitions;
             $configsDefs = $ajxpPlugin->getConfigsDefinitions();
             if (is_array($configsDefs)) {
                 $definitions = array_merge($configsDefs, $instancesDefinitions);
             }
             $values = $ajxpPlugin->getConfigs();
             if (!is_array($values)) {
                 $values = array();
             }
             echo "<plugin_settings_values>";
             // First flatten keys
             $flattenedKeys = array();
             foreach ($values as $key => $value) {
                 $type = $definitions[$key]["type"];
                 if ((strpos($type, "group_switch:") === 0 || strpos($type, "plugin_instance:") === 0) && is_array($value)) {
                     $res = array();
                     $this->flattenKeyValues($res, $definitions, $value, $key);
                     $flattenedKeys += $res;
                     // Replace parent key by new flat value
                     $values[$key] = $flattenedKeys[$key];
                 }
             }
             $values += $flattenedKeys;
             foreach ($values as $key => $value) {
                 $attribute = true;
                 $type = $definitions[$key]["type"];
                 if ($type == "array" && is_array($value)) {
                     $value = implode(",", $value);
                 } else {
                     if ($type == "boolean") {
                         $value = $value === true || $value === "true" || $value == 1 ? "true" : "false";
                     } else {
                         if ($type == "textarea") {
                             $attribute = false;
                         } else {
                             if ($type == "password" && !empty($value)) {
                                 $value = "__AJXP_VALUE_SET__";
                             }
                         }
                     }
                 }
                 if ($attribute) {
                     echo "<param name=\"{$key}\" value=\"" . AJXP_Utils::xmlEntities($value) . "\"/>";
                 } else {
                     echo "<param name=\"{$key}\" cdatavalue=\"true\"><![CDATA[" . $value . "]]></param>";
                 }
             }
             if ($ajxpPlugin->getType() != "core") {
                 echo "<param name=\"AJXP_PLUGIN_ENABLED\" value=\"" . ($ajxpPlugin->isEnabled() ? "true" : "false") . "\"/>";
             }
             echo "</plugin_settings_values>";
             echo "<plugin_doc><![CDATA[<p>" . $ajxpPlugin->getPluginInformationHTML("Charles du Jeu", "http://pyd.io/plugins/") . "</p>";
             if (file_exists($ajxpPlugin->getBaseDir() . "/plugin_doc.html")) {
                 echo file_get_contents($ajxpPlugin->getBaseDir() . "/plugin_doc.html");
             }
             echo "]]></plugin_doc>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "run_plugin_action":
             $options = array();
             $this->parseParameters($httpVars, $options, null, true);
             $pluginId = $httpVars["action_plugin_id"];
             if (isset($httpVars["button_key"])) {
                 $options = $options[$httpVars["button_key"]];
             }
             $plugin = AJXP_PluginsService::getInstance()->softLoad($pluginId, $options);
             if (method_exists($plugin, $httpVars["action_plugin_method"])) {
                 try {
                     $res = call_user_func(array($plugin, $httpVars["action_plugin_method"]), $options);
                 } catch (Exception $e) {
                     echo "ERROR:" . $e->getMessage();
                     break;
                 }
                 echo $res;
             } else {
                 echo 'ERROR: Plugin ' . $httpVars["action_plugin_id"] . ' does not implement ' . $httpVars["action_plugin_method"] . ' method!';
             }
             break;
         case "edit_plugin_options":
             $options = array();
             $this->parseParameters($httpVars, $options, null, true);
             $confStorage = ConfService::getConfStorageImpl();
             list($pType, $pName) = explode(".", $httpVars["plugin_id"]);
             $existing = $confStorage->loadPluginConfig($pType, $pName);
             $this->mergeExistingParameters($options, $existing);
             $confStorage->savePluginConfig($httpVars["plugin_id"], $options);
             AJXP_PluginsService::clearPluginsCache();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.97"], null);
             AJXP_XMLWriter::close();
             break;
         case "generate_api_docs":
             PydioSdkGenerator::analyzeRegistry(isset($httpVars["version"]) ? $httpVars["version"] : AJXP_VERSION);
             break;
             // Action for update all Pydio's user from ldap in CLI mode
         // Action for update all Pydio's user from ldap in CLI mode
         case "cli_update_user_list":
             if (php_sapi_name() == "cli") {
                 $progressBar = new AJXP_ProgressBarCLI();
                 $countCallback = array($progressBar, "init");
                 $loopCallback = array($progressBar, "update");
                 AuthService::listUsers("/", null, -1, -1, true, true, $countCallback, $loopCallback);
             }
             break;
         default:
             break;
     }
     return;
 }
 public function clearCacheByNS($actionName, $httpVars, $fileVars)
 {
     $ns = AJXP_Utils::sanitize($httpVars["namespace"], AJXP_SANITIZE_ALPHANUM);
     if ($ns == AJXP_CACHE_SERVICE_NS_SHARED) {
         ConfService::clearAllCaches();
     } else {
         CacheService::deleteAll($ns);
     }
     HTMLWriter::charsetHeader("text/json");
     echo json_encode(["result" => "ok"]);
 }
示例#23
0
 public static function parseStandardFormParameters(&$repDef, &$options, $userId = null, $prefix = "DRIVER_OPTION_", $binariesContext = null, $cypheredPassPrefix = "")
 {
     if ($binariesContext === null) {
         $binariesContext = array("USER" => AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getId() : "shared");
     }
     $replicationGroups = array();
     $switchesGroups = array();
     foreach ($repDef as $key => $value) {
         if ((!empty($prefix) && strpos($key, $prefix) !== false && strpos($key, $prefix) == 0 || empty($prefix)) && strpos($key, "ajxptype") === false && strpos($key, "_original_binary") === false && strpos($key, "_replication") === false && strpos($key, "_checkbox") === false) {
             if (isset($repDef[$key . "_ajxptype"])) {
                 $type = $repDef[$key . "_ajxptype"];
                 if ($type == "boolean") {
                     $value = $value == "true" ? true : false;
                 } else {
                     if ($type == "integer") {
                         $value = intval($value);
                     } else {
                         if ($type == "array") {
                             $value = explode(",", $value);
                         } else {
                             if ($type == "password" && $userId != null) {
                                 if (trim($value) != "" && $value != "__AJXP_VALUE_SET__" && function_exists('mcrypt_encrypt')) {
                                     // We encode as base64 so if we need to store the result in a database, it can be stored in text column
                                     $value = $cypheredPassPrefix . base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($userId . "CDAFx¨op#"), $value, MCRYPT_MODE_ECB));
                                 }
                             } else {
                                 if ($type == "binary" && $binariesContext !== null) {
                                     if (!empty($value)) {
                                         if ($value == "ajxp-remove-original") {
                                             if (!empty($repDef[$key . "_original_binary"])) {
                                                 ConfService::getConfStorageImpl()->deleteBinary($binariesContext, $repDef[$key . "_original_binary"]);
                                             }
                                             $value = "";
                                         } else {
                                             $file = AJXP_Utils::getAjxpTmpDir() . "/" . $value;
                                             if (file_exists($file)) {
                                                 $id = !empty($repDef[$key . "_original_binary"]) ? $repDef[$key . "_original_binary"] : null;
                                                 $id = ConfService::getConfStorageImpl()->saveBinary($binariesContext, $file, $id);
                                                 $value = $id;
                                             }
                                         }
                                     } else {
                                         if (!empty($repDef[$key . "_original_binary"])) {
                                             $value = $repDef[$key . "_original_binary"];
                                         }
                                     }
                                 } else {
                                     if (strpos($type, "group_switch:") === 0) {
                                         $tmp = explode(":", $type);
                                         $gSwitchName = $tmp[1];
                                         $switchesGroups[substr($key, strlen($prefix))] = $gSwitchName;
                                     } else {
                                         if ($type == "text/json") {
                                             $value = json_decode($value, true);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
                 if (!in_array($type, array("textarea", "boolean", "text/json"))) {
                     $value = AJXP_Utils::sanitize($value, AJXP_SANITIZE_HTML);
                 }
                 unset($repDef[$key . "_ajxptype"]);
             }
             if (isset($repDef[$key . "_checkbox"])) {
                 $checked = $repDef[$key . "_checkbox"] == "checked";
                 unset($repDef[$key . "_checkbox"]);
                 if (!$checked) {
                     continue;
                 }
             }
             if (isset($repDef[$key . "_replication"])) {
                 $repKey = $repDef[$key . "_replication"];
                 if (!is_array($replicationGroups[$repKey])) {
                     $replicationGroups[$repKey] = array();
                 }
                 $replicationGroups[$repKey][] = $key;
             }
             $options[substr($key, strlen($prefix))] = $value;
             unset($repDef[$key]);
         } else {
             $repDef[$key] = $value;
         }
     }
     // DO SOMETHING WITH REPLICATED PARAMETERS?
     if (count($switchesGroups)) {
         $gValues = array();
         foreach ($switchesGroups as $fieldName => $groupName) {
             if (isset($options[$fieldName])) {
                 $gValues = array();
                 $radic = $groupName . "_" . $options[$fieldName] . "_";
                 foreach ($options as $optN => $optV) {
                     if (strpos($optN, $radic) === 0) {
                         $newName = substr($optN, strlen($radic));
                         $gValues[$newName] = $optV;
                     }
                 }
             }
             $options[$fieldName . "_group_switch"] = $options[$fieldName];
             $options[$fieldName] = $gValues;
         }
     }
 }
示例#24
0
 /**
  * @param Array $httpVars
  * @param Repository $repository
  * @param AbstractAccessDriver $accessDriver
  * @param null $uniqueUser
  * @throws Exception
  * @return int|Repository
  */
 public function createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser = null)
 {
     // ERRORS
     // 100 : missing args
     // 101 : repository label already exists
     // 102 : user already exists
     // 103 : current user is not allowed to share
     // SUCCESS
     // 200
     if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") {
         return 100;
     }
     /*
     // FILE IS ALWAYS THE PARENT FOLDER SO WE NOW CHECK FOLDER_SHARING AT A HIGHER LEVEL
     $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
     $foldersharing = $this->getFilteredOption("ENABLE_FOLDER_SHARING", $this->repository->getId());
     $foldersharingDisabled = isset($foldersharing) && ($foldersharing === false || (is_string($foldersharing) && $foldersharing == "disable"));
     if (is_dir($this->urlBase.$file) && $foldersharingDisabled) {
         return 103;
     }
     */
     $loggedUser = AuthService::getLoggedUser();
     $actRights = $loggedUser->mergedRole->listActionsStatesFor($repository);
     if (isset($actRights["share"]) && $actRights["share"] === false) {
         return 103;
     }
     $users = array();
     $uRights = array();
     $uPasses = array();
     $groups = array();
     $uWatches = array();
     $index = 0;
     $prefix = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId());
     while (isset($httpVars["user_" . $index])) {
         $eType = $httpVars["entry_type_" . $index];
         $uWatch = false;
         $rightString = ($httpVars["right_read_" . $index] == "true" ? "r" : "") . ($httpVars["right_write_" . $index] == "true" ? "w" : "");
         if ($this->watcher !== false) {
             $uWatch = $httpVars["right_watch_" . $index] == "true" ? true : false;
         }
         if (empty($rightString)) {
             $index++;
             continue;
         }
         if ($eType == "user") {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index], AJXP_SANITIZE_EMAILCHARS);
             if (!AuthService::userExists($u) && !isset($httpVars["user_pass_" . $index])) {
                 $index++;
                 continue;
             } else {
                 if (AuthService::userExists($u, "w") && isset($httpVars["user_pass_" . $index])) {
                     throw new Exception("User {$u} already exists, please choose another name.");
                 }
             }
             if (!AuthService::userExists($u, "r") && !empty($prefix) && strpos($u, $prefix) !== 0) {
                 $u = $prefix . $u;
             }
             $users[] = $u;
         } else {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index]);
             if (strpos($u, "/AJXP_TEAM/") === 0) {
                 $confDriver = ConfService::getConfStorageImpl();
                 if (method_exists($confDriver, "teamIdToUsers")) {
                     $teamUsers = $confDriver->teamIdToUsers(str_replace("/AJXP_TEAM/", "", $u));
                     foreach ($teamUsers as $userId) {
                         $users[] = $userId;
                         $uRights[$userId] = $rightString;
                         if ($this->watcher !== false) {
                             $uWatches[$userId] = $uWatch;
                         }
                     }
                 }
                 $index++;
                 continue;
             } else {
                 $groups[] = $u;
             }
         }
         $uRights[$u] = $rightString;
         $uPasses[$u] = isset($httpVars["user_pass_" . $index]) ? $httpVars["user_pass_" . $index] : "";
         if ($this->watcher !== false) {
             $uWatches[$u] = $uWatch;
         }
         $index++;
     }
     $label = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_label"]), AJXP_SANITIZE_HTML);
     $description = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_description"]), AJXP_SANITIZE_HTML);
     if (isset($httpVars["repository_id"])) {
         $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]);
     }
     // CHECK USER & REPO DOES NOT ALREADY EXISTS
     if ($this->getFilteredOption("AVOID_SHARED_FOLDER_SAME_LABEL", $this->repository->getId()) == true) {
         $count = 0;
         $similarLabelRepos = ConfService::listRepositoriesWithCriteria(array("display" => $label), $count);
         if ($count && !isset($editingRepo)) {
             return 101;
         }
         if ($count && isset($editingRepo)) {
             foreach ($similarLabelRepos as $slr) {
                 if ($slr->getUniqueId() != $editingRepo->getUniqueId()) {
                     return 101;
                 }
             }
         }
         /*
         $repos = ConfService::getRepositoriesList();
         foreach ($repos as $obj) {
             if ($obj->getDisplay() == $label && (!isSet($editingRepo) || $editingRepo != $obj)) {
             }
         }
         */
     }
     $confDriver = ConfService::getConfStorageImpl();
     foreach ($users as $userName) {
         if (AuthService::userExists($userName)) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
             if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) {
                 return 102;
             }
         } else {
             if ($httpVars["create_guest_user"] != "true" && !ConfService::getCoreConf("USER_CREATE_USERS", "conf") || AuthService::isReservedUserId($userName)) {
                 return 102;
             }
             if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") {
                 return 100;
             }
         }
     }
     // CREATE SHARED OPTIONS
     $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository);
     $customData = array();
     foreach ($httpVars as $key => $value) {
         if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") {
             $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value;
         }
     }
     if (count($customData)) {
         $options["PLUGINS_DATA"] = $customData;
     }
     if (isset($editingRepo)) {
         $newRepo = $editingRepo;
         $replace = false;
         if ($editingRepo->getDisplay() != $label) {
             $newRepo->setDisplay($label);
             $replace = true;
         }
         if ($editingRepo->getDescription() != $description) {
             $newRepo->setDescription($description);
             $replace = true;
         }
         if ($replace) {
             ConfService::replaceRepository($httpVars["repository_id"], $newRepo);
         }
     } else {
         if ($repository->getOption("META_SOURCES")) {
             $options["META_SOURCES"] = $repository->getOption("META_SOURCES");
             foreach ($options["META_SOURCES"] as $index => &$data) {
                 if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) {
                     $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString();
                 }
                 if ($index == "meta.syncable" && (!isset($data["REPO_SYNCABLE"]) || $data["REPO_SYNCABLE"] === true)) {
                     $data["REQUIRES_INDEXATION"] = true;
                 }
             }
         }
         $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null);
         $gPath = $loggedUser->getGroupPath();
         if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
             $newRepo->setGroupPath($gPath);
         }
         $newRepo->setDescription($description);
         $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
         if (isset($httpVars["filter_nodes"])) {
             $newRepo->setContentFilter(new ContentFilter($httpVars["filter_nodes"]));
         }
         ConfService::addRepository($newRepo);
         if (!isset($httpVars["minisite"])) {
             $this->getShareStore()->storeShare($repository->getId(), array("REPOSITORY" => $newRepo->getUniqueId(), "OWNER_ID" => $loggedUser->getId()), "repository");
         }
     }
     $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
     if (isset($editingRepo)) {
         $currentRights = $this->computeSharedRepositoryAccessRights($httpVars["repository_id"], false, $this->urlBase . $file);
         $originalUsers = array_keys($currentRights["USERS"]);
         $removeUsers = array_diff($originalUsers, $users);
         if (count($removeUsers)) {
             foreach ($removeUsers as $user) {
                 if (AuthService::userExists($user)) {
                     $userObject = $confDriver->createUserObject($user);
                     $userObject->personalRole->setAcl($newRepo->getUniqueId(), "");
                     $userObject->save("superuser");
                 }
                 $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $user, true);
             }
         }
         $originalGroups = array_keys($currentRights["GROUPS"]);
         $removeGroups = array_diff($originalGroups, $groups);
         if (count($removeGroups)) {
             foreach ($removeGroups as $groupId) {
                 $role = AuthService::getRole($groupId);
                 if ($role !== false) {
                     $role->setAcl($newRepo->getUniqueId(), "");
                     AuthService::updateRole($role);
                 }
             }
         }
     }
     foreach ($users as $userName) {
         if (AuthService::userExists($userName, "r")) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
         } else {
             if (ConfService::getAuthDriverImpl()->getOptionAsBool("TRANSMIT_CLEAR_PASS")) {
                 $pass = $uPasses[$userName];
             } else {
                 $pass = md5($uPasses[$userName]);
             }
             if (!isset($httpVars["minisite"])) {
                 // This is an explicit user creation - check possible limits
                 AJXP_Controller::applyHook("user.before_create", array($userName));
                 $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, "");
                 if (!empty($limit) && intval($limit) > 0) {
                     $count = count(ConfService::getConfStorageImpl()->getUserChildren($loggedUser->getId()));
                     if ($count >= $limit) {
                         $mess = ConfService::getMessages();
                         throw new Exception($mess['483']);
                     }
                 }
             }
             AuthService::createUser($userName, $pass);
             $userObject = $confDriver->createUserObject($userName);
             $userObject->personalRole->clearAcls();
             $userObject->setParent($loggedUser->id);
             $userObject->setGroupPath($loggedUser->getGroupPath());
             $userObject->setProfile("shared");
             if (isset($httpVars["minisite"])) {
                 $mess = ConfService::getMessages();
                 $userObject->setHidden(true);
                 $userObject->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", "[" . $mess["share_center.109"] . "] " . AJXP_Utils::sanitize($newRepo->getDisplay(), AJXP_SANITIZE_EMAILCHARS));
             }
             AJXP_Controller::applyHook("user.after_create", array($userObject));
         }
         // CREATE USER WITH NEW REPO RIGHTS
         $userObject->personalRole->setAcl($newRepo->getUniqueId(), $uRights[$userName]);
         if (isset($httpVars["minisite"])) {
             if (isset($editingRepo)) {
                 try {
                     AuthService::deleteRole("AJXP_SHARED-" . $newRepo->getUniqueId());
                 } catch (Exception $e) {
                 }
             }
             $newRole = new AJXP_Role("AJXP_SHARED-" . $newRepo->getUniqueId());
             $r = AuthService::getRole("MINISITE");
             if (is_a($r, "AJXP_Role")) {
                 if ($httpVars["disable_download"]) {
                     $f = AuthService::getRole("MINISITE_NODOWNLOAD");
                     if (is_a($f, "AJXP_Role")) {
                         $r = $f->override($r);
                     }
                 }
                 $allData = $r->getDataArray();
                 $newData = $newRole->getDataArray();
                 if (isset($allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["ACTIONS"][$newRepo->getUniqueId()] = $allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 if (isset($allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["PARAMETERS"][$newRepo->getUniqueId()] = $allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 $newRole->bunchUpdate($newData);
                 AuthService::updateRole($newRole);
                 $userObject->addRole($newRole);
             }
         }
         $userObject->save("superuser");
         if ($this->watcher !== false) {
             // Register a watch on the current folder for shared user
             if ($uWatches[$userName] == "true") {
                 $this->watcher->setWatchOnFolder(new AJXP_Node($this->urlBase . $file), $userName, MetaWatchRegister::$META_WATCH_USERS_CHANGE, array(AuthService::getLoggedUser()->getId()));
             } else {
                 $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $userName, true);
             }
         }
     }
     if ($this->watcher !== false) {
         // Register a watch on the new repository root for current user
         if ($httpVars["self_watch_folder"] == "true") {
             $this->watcher->setWatchOnFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH);
         } else {
             $this->watcher->removeWatchFromFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId());
         }
     }
     foreach ($groups as $group) {
         $r = $uRights[$group];
         if ($group == "AJXP_GRP_/") {
             $group = "ROOT_ROLE";
         }
         $grRole = AuthService::getRole($group, true);
         $grRole->setAcl($newRepo->getUniqueId(), $r);
         AuthService::updateRole($grRole);
     }
     if (array_key_exists("minisite", $httpVars) && $httpVars["minisite"] != true) {
         AJXP_Controller::applyHook(isset($editingRepo) ? "node.share.update" : "node.share.create", array('type' => 'repository', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'new_repository' => &$newRepo));
     }
     return $newRepo;
 }
示例#25
0
 /**
  * Create the users based on the installer form results.
  * @param array $data Parsed form results
  * @param bool $loginIsEmail Whether to use the login as primary email.
  * @throws Exception
  */
 public function createUsers($data, $loginIsEmail = false)
 {
     $newConfigPlugin = ConfService::getConfStorageImpl();
     require_once $newConfigPlugin->getUserClassFileName();
     $adminLogin = AJXP_Utils::sanitize($data["ADMIN_USER_LOGIN"], AJXP_SANITIZE_EMAILCHARS);
     $adminName = $data["ADMIN_USER_NAME"];
     $adminPass = $data["ADMIN_USER_PASS"];
     AuthService::createUser($adminLogin, $adminPass, true);
     $uObj = $newConfigPlugin->createUserObject($adminLogin);
     if ($loginIsEmail) {
         $uObj->personalRole->setParameterValue("core.conf", "email", $data["ADMIN_USER_LOGIN"]);
     } else {
         if (isset($data["MAILER_ADMIN"])) {
             $uObj->personalRole->setParameterValue("core.conf", "email", $data["MAILER_ADMIN"]);
         }
     }
     $uObj->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", $adminName);
     $repos = ConfService::getRepositoriesList("all", false);
     foreach ($repos as $repo) {
         $uObj->personalRole->setAcl($repo->getId(), "rw");
     }
     AuthService::updateRole($uObj->personalRole);
     $loginP = "USER_LOGIN";
     $i = 0;
     while (isset($data[$loginP]) && !empty($data[$loginP])) {
         $pass = $data[str_replace("_LOGIN", "_PASS", $loginP)];
         $name = $data[str_replace("_LOGIN", "_NAME", $loginP)];
         $mail = $data[str_replace("_LOGIN", "_MAIL", $loginP)];
         $saniLogin = AJXP_Utils::sanitize($data[$loginP], AJXP_SANITIZE_EMAILCHARS);
         AuthService::createUser($saniLogin, $pass);
         $uObj = $newConfigPlugin->createUserObject($saniLogin);
         $uObj->personalRole->setParameterValue("core.conf", "email", $mail);
         $uObj->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", $name);
         AuthService::updateRole($uObj->personalRole);
         $i++;
         $loginP = "USER_LOGIN_" . $i;
     }
 }
示例#26
0
 /**
  * Log the user from its credentials
  * @static
  * @param string $user_id The user id
  * @param string $pwd The password
  * @param bool $bypass_pwd Ignore password or not
  * @param bool $cookieLogin Is it a logging from the remember me cookie?
  * @param string $returnSeed The unique seed
  * @return int
  */
 public static function logUser($user_id, $pwd, $bypass_pwd = false, $cookieLogin = false, $returnSeed = "")
 {
     $user_id = self::filterUserSensitivity($user_id);
     if ($cookieLogin && !isset($_COOKIE["AjaXplorer-remember"])) {
         return -5;
         // SILENT IGNORE
     }
     if ($cookieLogin) {
         list($user_id, $pwd) = explode(":", $_COOKIE["AjaXplorer-remember"]);
     }
     $confDriver = ConfService::getConfStorageImpl();
     if ($user_id == null) {
         if (self::$useSession) {
             if (isset($_SESSION["AJXP_USER"]) && is_object($_SESSION["AJXP_USER"])) {
                 /**
                  * @var AbstractAjxpUser $u
                  */
                 $u = $_SESSION["AJXP_USER"];
                 if ($u->reloadRolesIfRequired()) {
                     ConfService::getInstance()->invalidateLoadedRepositories();
                     self::$bufferedMessage = AJXP_XMLWriter::reloadRepositoryList(false);
                     $_SESSION["AJXP_USER"] = $u;
                 }
                 return 1;
             }
         } else {
             if (isset(self::$currentUser) && is_object(self::$currentUser)) {
                 return 1;
             }
         }
         if (ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") && !isset($_SESSION["CURRENT_MINISITE"])) {
             $authDriver = ConfService::getAuthDriverImpl();
             if (!$authDriver->userExists("guest")) {
                 self::createUser("guest", "");
                 $guest = $confDriver->createUserObject("guest");
                 $guest->save("superuser");
             }
             self::logUser("guest", null);
             return 1;
         }
         return -1;
     }
     $authDriver = ConfService::getAuthDriverImpl();
     // CHECK USER PASSWORD HERE!
     $loginAttempt = self::getBruteForceLoginArray();
     $bruteForceLogin = self::checkBruteForceLogin($loginAttempt);
     self::setBruteForceLoginArray($loginAttempt);
     if (!$authDriver->userExists($user_id)) {
         AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => AJXP_Utils::sanitize($user_id, AJXP_SANITIZE_EMAILCHARS), "error" => "Invalid user"));
         if ($bruteForceLogin === FALSE) {
             return -4;
         } else {
             return -1;
         }
     }
     if (!$bypass_pwd) {
         if (!self::checkPassword($user_id, $pwd, $cookieLogin, $returnSeed)) {
             AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => AJXP_Utils::sanitize($user_id, AJXP_SANITIZE_EMAILCHARS), "error" => "Invalid password"));
             if ($bruteForceLogin === FALSE) {
                 return -4;
             } else {
                 if ($cookieLogin) {
                     return -5;
                 }
                 return -1;
             }
         }
     }
     // Successful login attempt
     unset($loginAttempt[$_SERVER["REMOTE_ADDR"]]);
     self::setBruteForceLoginArray($loginAttempt);
     // Setting session credentials if asked in config
     if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) {
         list($authId, $authPwd) = $authDriver->filterCredentials($user_id, $pwd);
         AJXP_Safe::storeCredentials($authId, $authPwd);
     }
     $user = $confDriver->createUserObject($user_id);
     if ($user->getLock() == "logout") {
         AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => AJXP_Utils::sanitize($user_id, AJXP_SANITIZE_EMAILCHARS), "error" => "Locked user"));
         return -1;
     }
     if (AuthService::$useSession && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
         ConfService::getInstance()->invalidateLoadedRepositories();
     }
     if ($authDriver->isAjxpAdmin($user_id)) {
         $user->setAdmin(true);
     }
     if (self::$useSession) {
         $_SESSION["AJXP_USER"] = $user;
     } else {
         self::$currentUser = $user;
     }
     if ($user->isAdmin()) {
         $user = self::updateAdminRights($user);
         self::updateUser($user);
     }
     if ($authDriver->autoCreateUser() && !$user->storageExists()) {
         $user->save("superuser");
         // make sure update rights now
     }
     AJXP_Logger::info(__CLASS__, "Log In", array("context" => self::$useSession ? "WebUI" : "API"));
     return 1;
 }
 /**
  * @param String $action
  * @param Array $httpVars
  * @param Array $fileVars
  * @throws Exception
  */
 public function receiveAction($action, $httpVars, $fileVars)
 {
     //VAR CREATION OUTSIDE OF ALL CONDITIONS, THEY ARE "MUST HAVE" VAR !!
     $messages = ConfService::getMessages();
     $repository = ConfService::getRepository();
     $userSelection = new UserSelection($repository, $httpVars);
     $nodes = $userSelection->buildNodes();
     $currentDirPath = AJXP_Utils::safeDirname($userSelection->getUniqueNode()->getPath());
     $currentDirPath = rtrim($currentDirPath, "/") . "/";
     $currentDirUrl = $userSelection->currentBaseUrl() . $currentDirPath;
     if (empty($httpVars["compression_id"])) {
         $compressionId = sha1(rand());
         $httpVars["compression_id"] = $compressionId;
     } else {
         $compressionId = $httpVars["compression_id"];
     }
     $progressCompressionFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressCompressionID-" . $compressionId . ".txt";
     if (empty($httpVars["extraction_id"])) {
         $extractId = sha1(rand());
         $httpVars["extraction_id"] = $extractId;
     } else {
         $extractId = $httpVars["extraction_id"];
     }
     $progressExtractFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressExtractID-" . $extractId . ".txt";
     if ($action == "compression") {
         $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
         $archiveFormat = $httpVars["type_archive"];
         $tabTypeArchive = array(".tar", ".tar.gz", ".tar.bz2");
         $acceptedExtension = false;
         foreach ($tabTypeArchive as $extensionArchive) {
             if ($extensionArchive == $archiveFormat) {
                 $acceptedExtension = true;
                 break;
             }
         }
         if ($acceptedExtension == false) {
             file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.16"]);
             throw new AJXP_Exception($messages["compression.16"]);
         }
         $typeArchive = $httpVars["type_archive"];
         //if we can run in background we do it
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             $archivePath = $currentDirPath . $archiveName;
             file_put_contents($progressCompressionFileName, $messages["compression.5"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "compression", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $messages["compression.5"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         } else {
             $maxAuthorizedSize = 4294967296;
             $currentDirUrlLength = strlen($currentDirUrl);
             $tabFolders = array();
             $tabAllRecursiveFiles = array();
             $tabFilesNames = array();
             foreach ($nodes as $node) {
                 $nodeUrl = $node->getUrl();
                 if (is_file($nodeUrl) && filesize($nodeUrl) < $maxAuthorizedSize) {
                     array_push($tabAllRecursiveFiles, $nodeUrl);
                     array_push($tabFilesNames, substr($nodeUrl, $currentDirUrlLength));
                 }
                 if (is_dir($nodeUrl)) {
                     array_push($tabFolders, $nodeUrl);
                 }
             }
             //DO A FOREACH OR IT'S GONNA HAVE SOME SAMES FILES NAMES
             foreach ($tabFolders as $value) {
                 $dossiers = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($value));
                 foreach ($dossiers as $file) {
                     if ($file->isDir()) {
                         continue;
                     }
                     array_push($tabAllRecursiveFiles, $file->getPathname());
                     array_push($tabFilesNames, substr($file->getPathname(), $currentDirUrlLength));
                 }
             }
             //WE STOP IF IT'S JUST AN EMPTY FOLDER OR NO FILES
             if (empty($tabFilesNames)) {
                 file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.17"]);
                 throw new AJXP_Exception($messages["compression.17"]);
             }
             try {
                 $tmpArchiveName = tempnam(AJXP_Utils::getAjxpTmpDir(), "tar-compression") . ".tar";
                 $archive = new PharData($tmpArchiveName);
             } catch (Exception $e) {
                 file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                 throw $e;
             }
             $counterCompression = 0;
             //THE TWO ARRAY ARE MERGED FOR THE FOREACH LOOP
             $tabAllFiles = array_combine($tabAllRecursiveFiles, $tabFilesNames);
             foreach ($tabAllFiles as $fullPath => $fileName) {
                 try {
                     $archive->addFile(AJXP_MetaStreamWrapper::getRealFSReference($fullPath), $fileName);
                     $counterCompression++;
                     file_put_contents($progressCompressionFileName, sprintf($messages["compression.6"], round($counterCompression / count($tabAllFiles) * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
                 } catch (Exception $e) {
                     unlink($tmpArchiveName);
                     file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                     throw $e;
                 }
             }
             $finalArchive = $tmpArchiveName;
             if ($typeArchive != ".tar") {
                 $archiveTypeCompress = substr(strrchr($typeArchive, "."), 1);
                 file_put_contents($progressCompressionFileName, sprintf($messages["compression.7"], strtoupper($archiveTypeCompress)));
                 if ($archiveTypeCompress == "gz") {
                     $archive->compress(Phar::GZ);
                 } elseif ($archiveTypeCompress == "bz2") {
                     $archive->compress(Phar::BZ2);
                 }
                 $finalArchive = $tmpArchiveName . "." . $archiveTypeCompress;
             }
             $destArchive = AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $archiveName);
             rename($finalArchive, $destArchive);
             AJXP_Controller::applyHook("node.before_create", array($destArchive, filesize($destArchive)));
             if (file_exists($tmpArchiveName)) {
                 unlink($tmpArchiveName);
                 unlink(substr($tmpArchiveName, 0, -4));
             }
             $newNode = new AJXP_Node($currentDirUrl . $archiveName);
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             file_put_contents($progressCompressionFileName, "SUCCESS");
         }
     } elseif ($action == "check_compression_status") {
         $archivePath = AJXP_Utils::decodeSecureMagic($httpVars["archive_path"]);
         $progressCompression = file_get_contents($progressCompressionFileName);
         $substrProgressCompression = substr($progressCompression, 0, 5);
         if ($progressCompression != "SUCCESS" && $substrProgressCompression != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $progressCompression, true, 5);
             AJXP_XMLWriter::close();
         } elseif ($progressCompression == "SUCCESS") {
             $newNode = new AJXP_Node($userSelection->currentBaseUrl() . $archivePath);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($messages["compression.8"], null);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         } elseif ($substrProgressCompression == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressCompression);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         }
     } elseif ($action == "extraction") {
         $fileArchive = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["file"]), AJXP_SANITIZE_DIRNAME);
         $fileArchive = substr(strrchr($fileArchive, DIRECTORY_SEPARATOR), 1);
         $authorizedExtension = array("tar" => 4, "gz" => 7, "bz2" => 8);
         $acceptedArchive = false;
         $extensionLength = 0;
         $counterExtract = 0;
         $currentAllPydioPath = $currentDirUrl . $fileArchive;
         $pharCurrentAllPydioPath = "phar://" . AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath);
         $pathInfoCurrentAllPydioPath = pathinfo($currentAllPydioPath, PATHINFO_EXTENSION);
         //WE TAKE ONLY TAR, TAR.GZ AND TAR.BZ2 ARCHIVES
         foreach ($authorizedExtension as $extension => $strlenExtension) {
             if ($pathInfoCurrentAllPydioPath == $extension) {
                 $acceptedArchive = true;
                 $extensionLength = $strlenExtension;
                 break;
             }
         }
         if ($acceptedArchive == false) {
             file_put_contents($progressExtractFileName, "Error : " . $messages["compression.15"]);
             throw new AJXP_Exception($messages["compression.15"]);
         }
         $onlyFileName = substr($fileArchive, 0, -$extensionLength);
         $lastPosOnlyFileName = strrpos($onlyFileName, "-");
         $tmpOnlyFileName = substr($onlyFileName, 0, $lastPosOnlyFileName);
         $counterDuplicate = substr($onlyFileName, $lastPosOnlyFileName + 1);
         if (!is_int($lastPosOnlyFileName) || !is_int($counterDuplicate)) {
             $tmpOnlyFileName = $onlyFileName;
             $counterDuplicate = 1;
         }
         while (file_exists($currentDirUrl . $onlyFileName)) {
             $onlyFileName = $tmpOnlyFileName . "-" . $counterDuplicate;
             $counterDuplicate++;
         }
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             file_put_contents($progressExtractFileName, $messages["compression.12"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "extraction", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $messages["compression.12"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         }
         mkdir($currentDirUrl . $onlyFileName, 0777, true);
         chmod(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), 0777);
         try {
             $archive = new PharData(AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath));
             $fichiersArchive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharCurrentAllPydioPath));
             foreach ($fichiersArchive as $file) {
                 $fileGetPathName = $file->getPathname();
                 if ($file->isDir()) {
                     continue;
                 }
                 $fileNameInArchive = substr(strstr($fileGetPathName, $fileArchive), strlen($fileArchive) + 1);
                 try {
                     $archive->extractTo(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), $fileNameInArchive, false);
                 } catch (Exception $e) {
                     file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
                     throw new AJXP_Exception($e);
                 }
                 $counterExtract++;
                 file_put_contents($progressExtractFileName, sprintf($messages["compression.13"], round($counterExtract / $archive->count() * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
             }
         } catch (Exception $e) {
             file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
             throw new AJXP_Exception($e);
         }
         file_put_contents($progressExtractFileName, "SUCCESS");
         $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
         AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array());
     } elseif ($action == "check_extraction_status") {
         $currentDirUrl = $httpVars["currentDirUrl"];
         $onlyFileName = $httpVars["onlyFileName"];
         $progressExtract = file_get_contents($progressExtractFileName);
         $substrProgressExtract = substr($progressExtract, 0, 5);
         if ($progressExtract != "SUCCESS" && $progressExtract != "INDEX" && $substrProgressExtract != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $progressExtract, true, 4);
             AJXP_XMLWriter::close();
         } elseif ($progressExtract == "SUCCESS") {
             $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(sprintf($messages["compression.14"], $onlyFileName), null);
             AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $newNode->getRepositoryId()), "starting indexation", true, 5);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         } elseif ($substrProgressExtract == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressExtract);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         }
     }
 }
 function parseParameters(&$repDef, &$options, $userId = null)
 {
     $replicationGroups = array();
     foreach ($repDef as $key => $value) {
         $value = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($value));
         if (strpos($key, "DRIVER_OPTION_") !== false && strpos($key, "DRIVER_OPTION_") == 0 && strpos($key, "ajxptype") === false && strpos($key, "_replication") === false && strpos($key, "_checkbox") === false) {
             if (isset($repDef[$key . "_ajxptype"])) {
                 $type = $repDef[$key . "_ajxptype"];
                 if ($type == "boolean") {
                     $value = $value == "true" ? true : false;
                 } else {
                     if ($type == "integer") {
                         $value = intval($value);
                     } else {
                         if ($type == "array") {
                             $value = explode(",", $value);
                         } else {
                             if ($type == "password" && $userId != null) {
                                 if (trim($value != "") && function_exists('mcrypt_encrypt')) {
                                     // The initialisation vector is only required to avoid a warning, as ECB ignore IV
                                     $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
                                     // We encode as base64 so if we need to store the result in a database, it can be stored in text column
                                     $value = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($userId . "CDAFx¨op#"), $value, MCRYPT_MODE_ECB, $iv));
                                 }
                             }
                         }
                     }
                 }
                 unset($repDef[$key . "_ajxptype"]);
             }
             if (isset($repDef[$key . "_checkbox"])) {
                 $checked = $repDef[$key . "_checkbox"] == "checked";
                 unset($repDef[$key . "_checkbox"]);
                 if (!$checked) {
                     continue;
                 }
             }
             if (isset($repDef[$key . "_replication"])) {
                 $repKey = $repDef[$key . "_replication"];
                 if (!is_array($replicationGroups[$repKey])) {
                     $replicationGroups[$repKey] = array();
                 }
                 $replicationGroups[$repKey][] = $key;
             }
             $options[substr($key, strlen("DRIVER_OPTION_"))] = $value;
             unset($repDef[$key]);
         } else {
             if ($key == "DISPLAY") {
                 $value = SystemTextEncoding::fromUTF8(AJXP_Utils::securePath($value));
             }
             $repDef[$key] = $value;
         }
     }
     // DO SOMETHING WITH REPLICATED PARAMETERS?
     if (count($replicationGroups)) {
     }
 }
示例#29
0
<?php

define('AJXP_EXEC', true);
require_once '../../core/classes/class.AJXP_Utils.php';
$AJXP_FILE_URL = AJXP_Utils::securePath(AJXP_Utils::sanitize($_GET["file"], 5));
$parts = explode("/", AJXP_Utils::securePath($_GET["file"]));
foreach ($parts as $i => $part) {
    $parts[$i] = AJXP_Utils::sanitize($part, AJXP_SANITIZE_FILENAME);
}
$AJXP_FILE_URL = implode("/", $parts);
?>
<html>
<head>
    <script src="webodf/webodf.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        function init()
        {
            var odfelement = document.getElementById("odf");
            window.odfcanvas = new odf.OdfCanvas(odfelement);
            window.odfcanvas.load("../../" + window.parent.ajxpServerAccessPath + "&get_action=download&file=<?php 
echo $AJXP_FILE_URL;
?>
");
            //window.odfcanvas.setEditable(true);
            /*
            odfcanvas.odfContainer().save(function(err){
                console.log(err);
            });
            */
        }
        window.setTimeout(init, 0);
示例#30
0
 public function rename($filePath, $filename_new, $dest = null)
 {
     $nom_fic = basename($filePath);
     $mess = ConfService::getMessages();
     $filename_new = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($filename_new), AJXP_SANITIZE_FILENAME);
     $filename_new = substr($filename_new, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
     $old = $this->urlBase . "/{$filePath}";
     if (!$this->isWriteable($old)) {
         throw new AJXP_Exception($mess[34] . " " . $nom_fic . " " . $mess[99]);
     }
     if ($dest == null) {
         $new = dirname($old) . "/" . $filename_new;
     } else {
         $new = $this->urlBase . $dest;
     }
     if ($filename_new == "" && $dest == null) {
         throw new AJXP_Exception("{$mess['37']}");
     }
     if (file_exists($new)) {
         throw new AJXP_Exception("{$filename_new} {$mess['43']}");
     }
     if (!file_exists($old)) {
         throw new AJXP_Exception($mess[100] . " {$nom_fic}");
     }
     $oldNode = new AJXP_Node($old);
     AJXP_Controller::applyHook("node.before_path_change", array(&$oldNode));
     rename($old, $new);
     AJXP_Controller::applyHook("node.change", array($oldNode, new AJXP_Node($new), false));
 }