public function parseSpecificContributions(&$contribNode)
 {
     parent::parseSpecificContributions($contribNode);
     if ($contribNode->nodeName != "actions") {
         return;
     }
     $actionXpath = new DOMXPath($contribNode->ownerDocument);
     $paramList = $actionXpath->query('action[@name="scheduler_addTask"]/processing/standardFormDefinition/param[@name="repository_id"]', $contribNode);
     if (!$paramList->length) {
         return;
     }
     $paramNode = $paramList->item(0);
     $sVals = array();
     $repos = ConfService::getRepositoriesList("all");
     foreach ($repos as $repoId => $repoObject) {
         $sVals[] = $repoId . "|" . AJXP_Utils::xmlEntities($repoObject->getDisplay());
     }
     $sVals[] = "*|All Repositories";
     $paramNode->attributes->getNamedItem("choices")->nodeValue = implode(",", $sVals);
     if (!AuthService::usersEnabled() || AuthService::getLoggedUser() == null) {
         return;
     }
     $paramList = $actionXpath->query('action[@name="scheduler_addTask"]/processing/standardFormDefinition/param[@name="user_id"]', $contribNode);
     if (!$paramList->length) {
         return;
     }
     $paramNode = $paramList->item(0);
     $paramNode->attributes->getNamedItem("default")->nodeValue = AuthService::getLoggedUser()->getId();
 }
Exemple #2
0
 /**
  * Get all defined roles
  * @static
  * @param array $roleIds
  * @param boolean $excludeReserved,
  * @return AJXP_Role[]
  */
 public static function getRolesList($roleIds = array(), $excludeReserved = false)
 {
     //if(isSet(self::$roles)) return self::$roles;
     $confDriver = ConfService::getConfStorageImpl();
     self::$roles = $confDriver->listRoles($roleIds, $excludeReserved);
     $repoList = null;
     foreach (self::$roles as $roleId => $roleObject) {
         if (is_a($roleObject, "AjxpRole")) {
             if ($repoList == null) {
                 $repoList = ConfService::getRepositoriesList("all");
             }
             $newRole = new AJXP_Role($roleId);
             $newRole->migrateDeprectated($repoList, $roleObject);
             self::$roles[$roleId] = $newRole;
             self::updateRole($newRole);
         }
     }
     return self::$roles;
 }
 public function repositoryExists($name)
 {
     $repos = ConfService::getRepositoriesList();
     foreach ($repos as $obj) {
         if ($obj->getDisplay() == $name) {
             return true;
         }
     }
     return false;
 }
 function listRepositories()
 {
     $repos = ConfService::getRepositoriesList();
     AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/></columns>');
     $repoArray = array();
     foreach ($repos as $repoIndex => $repoObject) {
         if ($repoObject->getAccessType() == "ajxp_conf") {
             continue;
         }
         $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
         $repoArray[$name] = $repoIndex;
     }
     // Sort the list now by name
     ksort($repoArray);
     foreach ($repoArray as $name => $repoIndex) {
         $repoObject =& $repos[$repoIndex];
         $metaData = array("repository_id" => $repoIndex, "accessType" => $repoObject->getAccessType(), "icon" => "folder_red.png", "openicon" => "folder_red.png", "parentname" => "/repositories", "ajxp_mime" => "repository" . ($repoObject->isWriteable() ? "_editable" : ""));
         AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData);
     }
 }
 /**
  * Update a user object with the default repositories rights
  *
  * @param AbstractAjxpUser $userObject
  */
 function updateDefaultRights(&$userObject)
 {
     foreach (ConfService::getRepositoriesList() as $repositoryId => $repoObject) {
         if ($repoObject->getDefaultRight() != "") {
             $userObject->setRight($repositoryId, $repoObject->getDefaultRight());
         }
     }
 }
 function listRepositories()
 {
     $repos = ConfService::getRepositoriesList();
     AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/><column messageId="ajxp_shared.9" attributeName="repo_accesses" sortType="String"/></columns>');
     $repoArray = array();
     $childRepos = array();
     $loggedUser = AuthService::getLoggedUser();
     $users = AuthService::listUsers();
     foreach ($repos as $repoIndex => $repoObject) {
         if ($repoObject->getAccessType() == "ajxp_conf") {
             continue;
         }
         if (!$repoObject->hasOwner() || $repoObject->getOwner() != $loggedUser->getId()) {
             continue;
         }
         if (is_numeric($repoIndex)) {
             $repoIndex = "" . $repoIndex;
         }
         $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
         $repoArray[$name] = $repoIndex;
     }
     // Sort the list now by name
     ksort($repoArray);
     // Append child repositories
     $sortedArray = array();
     foreach ($repoArray as $name => $repoIndex) {
         $sortedArray[$name] = $repoIndex;
         if (isset($childRepos[$repoIndex]) && is_array($childRepos[$repoIndex])) {
             foreach ($childRepos[$repoIndex] as $childData) {
                 $sortedArray[$childData["name"]] = $childData["index"];
             }
         }
     }
     foreach ($sortedArray as $name => $repoIndex) {
         $repoObject =& $repos[$repoIndex];
         $repoAccesses = array();
         foreach ($users as $userId => $userObject) {
             if (!$userObject->hasParent()) {
                 continue;
             }
             if ($userObject->canWrite($repoIndex)) {
                 $repoAccesses[] = $userId . " (rw)";
             } else {
                 if ($userObject->canRead($repoIndex)) {
                     $repoAccesses[] = $userId . " (r)";
                 }
             }
         }
         $metaData = array("repository_id" => $repoIndex, "accessType" => $repoObject->getAccessType(), "icon" => "document_open_remote.png", "openicon" => "document_open_remote.png", "parentname" => "/repositories", "repo_accesses" => implode(", ", $repoAccesses), "ajxp_mime" => "shared_repository");
         AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData);
     }
 }
 /**
  * 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;
     }
 }
 function writeRepositoriesData($loggedUser, $details = false)
 {
     $st = "";
     $st .= "<repositories>";
     $streams = ConfService::detectRepositoryStreams(false);
     foreach (ConfService::getRepositoriesList() as $rootDirIndex => $rootDirObject) {
         $toLast = false;
         if ($rootDirObject->getAccessType() == "ajxp_conf") {
             if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) {
                 continue;
             } else {
                 $toLast = true;
             }
         }
         if ($loggedUser == null || $loggedUser->canRead($rootDirIndex) || $details) {
             $rightString = "";
             if ($details) {
                 $rightString = " r=\"" . ($loggedUser->canRead($rootDirIndex) ? "1" : "0") . "\" w=\"" . ($loggedUser->canWrite($rootDirIndex) ? "1" : "0") . "\"";
             }
             $streamString = "";
             if (in_array($rootDirObject->accessType, $streams)) {
                 $streamString = "allowCrossRepositoryCopy=\"true\"";
             }
             if ($toLast) {
                 $lastString = "<repo access_type=\"" . $rootDirObject->accessType . "\" id=\"" . $rootDirIndex . "\"{$rightString} {$streamString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($rootDirObject->getDisplay())) . "</label>" . $rootDirObject->getClientSettings() . "</repo>";
             } else {
                 $st .= "<repo access_type=\"" . $rootDirObject->accessType . "\" id=\"" . $rootDirIndex . "\"{$rightString} {$streamString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($rootDirObject->getDisplay())) . "</label>" . $rootDirObject->getClientSettings() . "</repo>";
             }
         }
     }
     if (isset($lastString)) {
         $st .= $lastString;
     }
     $st .= "</repositories>";
     return $st;
 }
 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::getCurrentRootDirIndex();
                 $user->setArrayPref("history", "last_repository", $activeRepId);
                 $user->save("user");
             }
             //$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($httpVars["bm_action"]) && isset($httpVars["bm_path"])) {
                 if ($httpVars["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($httpVars["bm_title"])) {
                         $title = $httpVars["bm_title"];
                     }
                     if ($title == "" && $httpVars["bm_path"] == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark(SystemTextEncoding::magicDequote($httpVars["bm_path"]), SystemTextEncoding::magicDequote($title));
                 } else {
                     if ($httpVars["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($httpVars["bm_path"]);
                     } else {
                         if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) {
                             $bmUser->renameBookmark($httpVars["bm_path"], $httpVars["bm_title"]);
                         }
                     }
                 }
             }
             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());
             AJXP_XMLWriter::close();
             exit(1);
             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";
             exit(1);
             break;
             //------------------------------------
             // WEBDAV PREFERENCES
             //------------------------------------
         //------------------------------------
         // WEBDAV PREFERENCES
         //------------------------------------
         case "webdav_preferences":
             $userObject = AuthService::getLoggedUser();
             $webdavActive = false;
             $passSet = 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") . "/";
             if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) {
                 $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
                 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_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#";
                         $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
                         $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB, $iv));
                     }
                     $davData["PASS"] = $password;
                 }
                 $userObject->setPref("AJXP_WEBDAV_DATA", $davData);
                 $userObject->save("user");
             }
             $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
             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, "AjxpWebdavProvider") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) {
                     $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug());
                 }
             }
             $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "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");
             $repositories = ConfService::getRepositoriesList();
             $pServ = AJXP_PluginsService::getInstance();
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 if (!$repo->getOption("TPL_USER_CAN_CREATE")) {
                     continue;
                 }
                 $repoId = $repo->getUniqueId();
                 $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();
             self::parseParameters($httpVars, $options);
             $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, AuthService::getLoggedUser()->getId());
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[426]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 // Make sure we do not overwrite otherwise loaded rights.
                 $loggedUser->load();
                 $loggedUser->setRight($newRep->getUniqueId(), "rw");
                 $loggedUser->save("superuser");
                 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->removeRights($repoId);
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[428], null);
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             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;
 }
 public function runTask($taskId, $status = null, &$currentlyRunning = -1, $forceStart = false)
 {
     $data = $this->getTaskById($taskId);
     $mess = ConfService::getMessages();
     $timeArray = $this->getTimeArray($data["schedule"]);
     // TODO : Set MasterInterval as config, or detect last execution?
     $masterInterval = 1;
     $maximumProcesses = 2;
     $now = time();
     $lastExec = time() - 60 * $masterInterval;
     $res = $this->getNextExecutionTimeForScript($lastExec, $timeArray);
     $test = date("Y-m-d H:i", $lastExec) . " -- " . date("Y-m-d H:i", $res) . " --  " . date("Y-m-d H:i", $now);
     $alreadyRunning = false;
     $queued = false;
     if ($status == null) {
         $status = $this->getTaskStatus($taskId);
     }
     if ($status !== false) {
         if ($status[0] == "RUNNING") {
             $alreadyRunning = true;
         } else {
             if (in_array("QUEUED", $status)) {
                 $queued = true;
                 // Run now !
             }
         }
     }
     if ($res >= $lastExec && $res < $now && !$alreadyRunning && $currentlyRunning >= $maximumProcesses) {
         $this->setTaskStatus($taskId, "QUEUED", true);
         $alreadyRunning = true;
         $queued = false;
     }
     if ($res >= $lastExec && $res < $now && !$alreadyRunning || $queued || $forceStart) {
         if ($data["user_id"] == "*/*" || $data["user_id"] == "*") {
             // Recurse all groups and put them into a queue file
             $allUsers = array();
             if ($data["user_id"] == "*") {
                 $allUsers = $this->listUsersIds();
             } else {
                 $this->gatherUsers($allUsers, "/");
             }
             $tmpQueue = AJXP_CACHE_DIR . "/cmd_outputs/queue_" . $taskId . "";
             echo "Queuing " . count($allUsers) . " users in file " . $tmpQueue . "\n";
             file_put_contents($tmpQueue, implode(",", $allUsers));
             $data["user_id"] = "queue:" . $tmpQueue;
         }
         if ($data["repository_id"] == "*") {
             $data["repository_id"] = implode(",", array_keys(ConfService::getRepositoriesList("all")));
         }
         $process = AJXP_Controller::applyActionInBackground($data["repository_id"], $data["action_name"], $data["PARAMS"], $data["user_id"], AJXP_CACHE_DIR . "/cmd_outputs/task_" . $taskId . ".status");
         if ($process != null && is_a($process, "UnixProcess")) {
             $this->setTaskStatus($taskId, "RUNNING:" . $process->getPid());
         } else {
             $this->setTaskStatus($taskId, "RUNNING");
         }
         $currentlyRunning++;
         return true;
     }
     return false;
 }
 /**
  * Send repositories access for given role as XML
  *
  * @param AjxpRole $role
  * @return string
  */
 static function writeRoleRepositoriesData($role)
 {
     $st = "<repositories>";
     foreach (ConfService::getRepositoriesList() as $repoId => $repoObject) {
         $toLast = false;
         if ($repoObject->getAccessType() == "ajxp_conf") {
             continue;
         }
         if ($repoObject->getAccessType() == "ajxp_shared" && !AuthService::usersEnabled()) {
             continue;
         }
         $rightString = " r=\"" . ($role->canRead($repoId) ? "1" : "0") . "\" w=\"" . ($role->canWrite($repoId) ? "1" : "0") . "\"";
         $string = "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$rightString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label></repo>";
         if ($toLast) {
             $lastString = $string;
         } else {
             $st .= $string;
         }
     }
     if (isset($lastString)) {
         $st .= $lastString;
     }
     $st .= "</repositories>";
     $st .= "<actions_rights>";
     foreach ($role->getSpecificActionsRights("ajxp.all") as $actionId => $actionValue) {
         $st .= "<action name=\"{$actionId}\" value=\"" . ($actionValue ? "true" : "false") . "\"/>";
     }
     $st .= "</actions_rights>";
     return $st;
 }
 public function listRepositories()
 {
     $repos = ConfService::getRepositoriesList("all");
     AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="user_dash.9" attributeName="parent_label" sortType="String"/><column messageId="user_dash.9" attributeName="repo_accesses" sortType="String"/></columns>');
     $repoArray = array();
     $loggedUser = AuthService::getLoggedUser();
     $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf");
     $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf");
     if ($searchAll || $displayAll) {
         $baseGroup = "/";
     } else {
         $baseGroup = AuthService::filterBaseGroup("/");
     }
     AuthService::setGroupFiltering(false);
     $users = AuthService::listUsers($baseGroup);
     $minisites = $this->listSharedFiles("minisites");
     foreach ($repos as $repoIndex => $repoObject) {
         if ($repoObject->getAccessType() == "ajxp_conf") {
             continue;
         }
         if (!$repoObject->hasOwner() || $repoObject->getOwner() != $loggedUser->getId()) {
             continue;
         }
         if (is_numeric($repoIndex)) {
             $repoIndex = "" . $repoIndex;
         }
         $name = (isset($minisites[$repoIndex]) ? "[Minisite] " : "") . AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
         $repoArray[$name] = $repoIndex;
     }
     // Sort the list now by name
     ksort($repoArray);
     foreach ($repoArray as $name => $repoIndex) {
         $repoObject =& $repos[$repoIndex];
         $repoAccesses = array();
         foreach ($users as $userId => $userObject) {
             if ($userObject->getId() == $loggedUser->getId()) {
                 continue;
             }
             $label = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId);
             if (empty($label)) {
                 $label = $userId;
             }
             $acl = $userObject->mergedRole->getAcl($repoObject->getId());
             if (!empty($acl)) {
                 $repoAccesses[] = $label . " (" . $acl . ")";
             }
         }
         $parent = $repoObject->getParentId();
         $parentRepo =& $repos[$parent];
         $parentLabel = $this->metaIcon("folder-open") . $parentRepo->getDisplay();
         $repoPath = $repoObject->getOption("PATH");
         $parentPath = $parentRepo->getOption("PATH");
         $parentLabel .= " (" . str_replace($parentPath, "", $repoPath) . ")";
         $metaData = array("repository_id" => $repoIndex, "icon" => "document_open_remote.png", "openicon" => "document_open_remote.png", "parentname" => "/repositories", "parent_label" => $parentLabel, "repo_accesses" => count($repoAccesses) ? $this->metaIcon("share-sign") . implode(", ", $repoAccesses) : "", "ajxp_mime" => "shared_repository");
         AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData);
     }
 }
Exemple #13
0
 /**
  * HTTP PUT method
  *
  * This HTTP method updates a file, or creates a new one.
  *
  * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 204 No Content
  *
  * @param string $uri
  * @return bool
  */
 protected function httpPut($uri)
 {
     $body = $this->httpRequest->getBody();
     // Intercepting Content-Range
     if ($this->httpRequest->getHeader('Content-Range')) {
         /**
         Content-Range is dangerous for PUT requests:  PUT per definition
         stores a full resource.  draft-ietf-httpbis-p2-semantics-15 says
         in section 7.6:
           An origin server SHOULD reject any PUT request that contains a
           Content-Range header field, since it might be misinterpreted as
           partial content (or might be partial content that is being mistakenly
           PUT as a full representation).  Partial content updates are possible
           by targeting a separately identified resource with state that
           overlaps a portion of the larger resource, or by using a different
           method that has been specifically defined for partial updates (for
           example, the PATCH method defined in [RFC5789]).
         This clarifies RFC2616 section 9.6:
           The recipient of the entity MUST NOT ignore any Content-*
           (e.g. Content-Range) headers that it does not understand or implement
           and MUST return a 501 (Not Implemented) response in such cases.
         OTOH is a PUT request with a Content-Range currently the only way to
         continue an aborted upload request and is supported by curl, mod_dav,
         Tomcat and others.  Since some clients do use this feature which results
         in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject
         all PUT requests with a Content-Range for now.
         */
         throw new Exception\NotImplemented('PUT with Content-Range is not allowed.');
     }
     // Intercepting the Finder problem
     if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) {
         /**
         Many webservers will not cooperate well with Finder PUT requests,
         because it uses 'Chunked' transfer encoding for the request body.
         
         The symptom of this problem is that Finder sends files to the
         server, but they arrive as 0-length files in PHP.
         
         If we don't do anything, the user might think they are uploading
         files successfully, but they end up empty on the server. Instead,
         we throw back an error if we detect this.
         
         The reason Finder uses Chunked, is because it thinks the files
         might change as it's being uploaded, and therefore the
         Content-Length can vary.
         
         Instead it sends the X-Expected-Entity-Length header with the size
         of the file at the very start of the request. If this header is set,
         but we don't get a request body we will fail the request to
         protect the end-user.
         */
         // Only reading first byte
         $firstByte = fread($body, 1);
         if (strlen($firstByte) !== 1) {
             throw new Exception\Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.');
         }
         // The body needs to stay intact, so we copy everything to a
         // temporary stream.
         $newBody = fopen('php://temp', 'r+');
         fwrite($newBody, $firstByte);
         stream_copy_to_stream($body, $newBody);
         rewind($newBody);
         $body = $newBody;
     }
     if ($this->tree->nodeExists($uri)) {
         $node = $this->tree->getNodeForPath($uri);
         // Checking If-None-Match and related headers.
         if (!$this->checkPreconditions()) {
             return;
         }
         // If the node is a collection, we'll deny it
         if (!$node instanceof IFile) {
             throw new Exception\Conflict('PUT is not allowed on non-files.');
         }
         if (!$this->broadcastEvent('beforeWriteContent', array($uri, $node, &$body))) {
             return false;
         }
         $etag = $node->put($body);
         $this->broadcastEvent('afterWriteContent', array($uri, $node));
         $this->httpResponse->setHeader('Content-Length', '0');
         if ($etag) {
             $this->httpResponse->setHeader('ETag', $etag);
         }
         $this->httpResponse->sendStatus(204);
     } else {
         $etag = null;
         // If we got here, the resource didn't exist yet.
         if (!$this->createFile($this->getRequestUri(), $body, $etag)) {
             // For one reason or another the file was not created.
             return;
         }
         $this->httpResponse->setHeader('Content-Length', '0');
         if ($etag) {
             $this->httpResponse->setHeader('ETag', $etag);
         }
         $this->httpResponse->sendStatus(201);
     }
     $repositories = \ConfService::getRepositoriesList("user");
     \AJXP_Logger::info(__CLASS__, "Upload", array("files" => $repositories[\ConfService::getCurrentRepositoryId()]->getSlug() . "/" . $uri));
 }
 function createSharedRepository($httpVars, $repository, $accessDriver)
 {
     // ERRORS
     // 100 : missing args
     // 101 : repository label already exists
     // 102 : user already exists
     // 103 : current user is not allowed to share
     // SUCCESS
     // 200
     if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "" || !isset($httpVars["repo_rights"]) || $httpVars["repo_rights"] == "") {
         return 100;
     }
     $loggedUser = AuthService::getLoggedUser();
     $actRights = $loggedUser->getSpecificActionsRights($repository->id);
     if (isset($actRights["share"]) && $actRights["share"] === false) {
         return 103;
     }
     $users = array();
     if (isset($httpVars["shared_user"]) && !empty($httpVars["shared_user"])) {
         $users = array_filter(array_map("trim", explode(",", str_replace("\n", ",", $httpVars["shared_user"]))), array("AuthService", "userExists"));
     }
     if (isset($httpVars["new_shared_user"]) && !empty($httpVars["new_shared_user"])) {
         $newshareduser = AJXP_Utils::decodeSecureMagic($httpVars["new_shared_user"], AJXP_SANITIZE_ALPHANUM);
         if (!empty($this->pluginConf["SHARED_USERS_TMP_PREFIX"]) && strpos($newshareduser, $this->pluginConf["SHARED_USERS_TMP_PREFIX"]) !== 0) {
             $newshareduser = $this->pluginConf["SHARED_USERS_TMP_PREFIX"] . $newshareduser;
         }
         if (!AuthService::userExists($newshareduser)) {
             array_push($users, $newshareduser);
         } else {
             throw new Exception("User already exists, please choose another name.");
         }
     }
     //$userName = AJXP_Utils::decodeSecureMagic($httpVars["shared_user"], AJXP_SANITIZE_ALPHANUM);
     $label = AJXP_Utils::decodeSecureMagic($httpVars["repo_label"]);
     $rights = $httpVars["repo_rights"];
     if ($rights != "r" && $rights != "w" && $rights != "rw") {
         return 100;
     }
     if (isset($httpVars["repository_id"])) {
         $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]);
     }
     // CHECK USER & REPO DOES NOT ALREADY EXISTS
     $repos = ConfService::getRepositoriesList();
     foreach ($repos as $obj) {
         if ($obj->getDisplay() == $label && (!isset($editingRepo) || $editingRepo != $obj)) {
             return 101;
         }
     }
     $confDriver = ConfService::getConfStorageImpl();
     foreach ($users as $userName) {
         if (AuthService::userExists($userName)) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
             if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) {
                 return 102;
             }
         } else {
             if (AuthService::isReservedUserId($userName)) {
                 return 102;
             }
             if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") {
                 return 100;
             }
         }
     }
     // CREATE SHARED OPTIONS
     $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository);
     $customData = array();
     foreach ($httpVars as $key => $value) {
         if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") {
             $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value;
         }
     }
     if (count($customData)) {
         $options["PLUGINS_DATA"] = $customData;
     }
     if (isset($editingRepo)) {
         $newRepo = $editingRepo;
         $newRepo->setDisplay($label);
         $newRepo->options = array_merge($newRepo->options, $options);
         ConfService::replaceRepository($httpVars["repository_id"], $newRepo);
     } else {
         if ($repository->getOption("META_SOURCES")) {
             $options["META_SOURCES"] = $repository->getOption("META_SOURCES");
             foreach ($options["META_SOURCES"] as $index => $data) {
                 if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) {
                     $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString();
                 }
             }
         }
         $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null);
         ConfService::addRepository($newRepo);
     }
     if (isset($httpVars["original_users"])) {
         $originalUsers = explode(",", $httpVars["original_users"]);
         $removeUsers = array_diff($originalUsers, $users);
         if (count($removeUsers)) {
             foreach ($removeUsers as $user) {
                 if (AuthService::userExists($user)) {
                     $userObject = $confDriver->createUserObject($user);
                     $userObject->removeRights($newRepo->getUniqueId());
                     $userObject->save("superuser");
                 }
             }
         }
     }
     foreach ($users as $userName) {
         if (AuthService::userExists($userName)) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
         } else {
             if (ConfService::getAuthDriverImpl()->getOption("TRANSMIT_CLEAR_PASS")) {
                 $pass = $httpVars["shared_pass"];
             } else {
                 $pass = md5($httpVars["shared_pass"]);
             }
             AuthService::createUser($userName, $pass);
             $userObject = $confDriver->createUserObject($userName);
             $userObject->clearRights();
             $userObject->setParent($loggedUser->id);
         }
         // CREATE USER WITH NEW REPO RIGHTS
         $userObject->setRight($newRepo->getUniqueId(), $rights);
         $userObject->setSpecificActionRight($newRepo->getUniqueId(), "share", false);
         $userObject->save("superuser");
     }
     // METADATA
     if (!isset($editingRepo) && $this->metaStore != null) {
         $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
         $this->metaStore->setMetadata(new AJXP_Node($this->urlBase . $file), "ajxp_shared", array("element" => $newRepo->getUniqueId()), true, AJXP_METADATA_SCOPE_REPOSITORY);
     }
     return 200;
 }
 /**
  * Update a user object with the default repositories rights
  *
  * @param AbstractAjxpUser $userObject
  */
 static function updateDefaultRights(&$userObject)
 {
     if (!$userObject->hasParent()) {
         foreach (ConfService::getRepositoriesList() as $repositoryId => $repoObject) {
             if ($repoObject->isTemplate) {
                 continue;
             }
             if ($repoObject->getDefaultRight() != "") {
                 $userObject->setRight($repositoryId, $repoObject->getDefaultRight());
             }
         }
         foreach (AuthService::getRolesList() as $roleId => $roleObject) {
             if ($roleObject->isDefault()) {
                 $userObject->addRole($roleId);
             }
         }
     }
 }
 function createSharedRepository($httpVars)
 {
     // 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"]) || !isset($httpVars["repo_rights"]) || !isset($httpVars["shared_user"])) {
         return 100;
     }
     $loggedUser = AuthService::getLoggedUser();
     $actRights = $loggedUser->getSpecificActionsRights($this->repository->id);
     if (isset($actRights["public_url"]) && $actRights["public_url"] === false) {
         return 103;
     }
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $userName = $httpVars["shared_user"];
     $label = SystemTextEncoding::fromUTF8($httpVars["repo_label"]);
     $rights = $httpVars["repo_rights"];
     if ($rights != "r" && $rights != "rw") {
         return 100;
     }
     // CHECK USER & REPO DOES NOT ALREADY EXISTS
     $repos = ConfService::getRepositoriesList();
     foreach ($repos as $obj) {
         if ($obj->getDisplay() == $label) {
             return 101;
         }
     }
     $confDriver = ConfService::getConfStorageImpl();
     if (AuthService::userExists($userName)) {
         // check that it's a child user
         $userObject = $confDriver->createUserObject($userName);
         if (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id) {
             return 102;
         }
     } else {
         if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") {
             return 100;
         }
         AuthService::createUser($userName, md5($httpVars["shared_pass"]));
         $userObject = $confDriver->createUserObject($userName);
         $userObject->clearRights();
         $userObject->setParent($loggedUser->id);
     }
     // CREATE SHARED OPTIONS
     $newRepo = $this->repository->createSharedChild($label, $this->makeSharedRepositoryOptions($httpVars), $this->repository->id, $loggedUser->id, $userName);
     ConfService::addRepository($newRepo);
     // CREATE USER WITH NEW REPO RIGHTS
     $userObject->setRight($newRepo->getUniqueId(), $rights);
     $userObject->setSpecificActionRight($newRepo->getUniqueId(), "public_url", false);
     $userObject->save();
     return 200;
 }
 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;
 }
    function listRepositories()
    {
        $repos = ConfService::getRepositoriesList();
        AJXP_XMLWriter::sendFilesListComponentConfig('<columns 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_shared.27" attributeName="owner" sortType="String"/>
			<column messageId="ajxp_conf.106" attributeName="repository_id" sortType="String"/>
			</columns>');
        $repoArray = array();
        $childRepos = array();
        $templateRepos = array();
        foreach ($repos as $repoIndex => $repoObject) {
            if ($repoObject->getAccessType() == "ajxp_conf" || $repoObject->getAccessType() == "ajxp_shared") {
                continue;
            }
            if (is_numeric($repoIndex)) {
                $repoIndex = "" . $repoIndex;
            }
            $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
            if ($repoObject->hasOwner() || $repoObject->hasParent()) {
                $parentId = $repoObject->getParentId();
                if (!isset($childRepos[$parentId])) {
                    $childRepos[$parentId] = array();
                }
                $childRepos[$parentId][] = array("name" => $name, "index" => $repoIndex);
                continue;
            }
            if ($repoObject->isTemplate) {
                $templateRepos[$name] = $repoIndex;
            } else {
                $repoArray[$name] = $repoIndex;
            }
        }
        // Sort the list now by name
        ksort($templateRepos);
        ksort($repoArray);
        $repoArray = array_merge($templateRepos, $repoArray);
        // Append child repositories
        $sortedArray = array();
        foreach ($repoArray as $name => $repoIndex) {
            $sortedArray[$name] = $repoIndex;
            if (isset($childRepos[$repoIndex]) && is_array($childRepos[$repoIndex])) {
                foreach ($childRepos[$repoIndex] as $childData) {
                    $sortedArray[$childData["name"]] = $childData["index"];
                }
            }
        }
        foreach ($sortedArray as $name => $repoIndex) {
            $repoObject =& $repos[$repoIndex];
            $icon = $repoObject->hasOwner() || $repoObject->hasParent() ? "repo_child.png" : "hdd_external_unmount.png";
            if ($repoObject->isTemplate) {
                $icon = "hdd_external_mount.png";
            }
            $metaData = array("repository_id" => $repoIndex, "accessType" => ($repoObject->isTemplate ? "Template for " : "") . $repoObject->getAccessType(), "icon" => $icon, "owner" => $repoObject->hasOwner() ? $repoObject->getOwner() : "", "openicon" => $icon, "parentname" => "/repositories", "ajxp_mime" => "repository" . ($repoObject->isWriteable() ? "_editable" : ""));
            AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData);
        }
    }
 /**
  * @static
  * @param AbstractAjxpUser $userObject
  * @param bool $details
  * @param bool $labelOnly
  * @param bool $skipShared
  * @return Repository[]
  */
 public static function getAccessibleRepositories($userObject = null, $details = false, $labelOnly = false, $includeShared = true)
 {
     $result = array();
     $allReps = ConfService::getRepositoriesList("user");
     foreach ($allReps as $repositoryId => $repositoryObject) {
         if (!ConfService::repositoryIsAccessible($repositoryId, $repositoryObject, $userObject, $details, $includeShared)) {
             continue;
         }
         if ($labelOnly) {
             $result[$repositoryId] = $repositoryObject->getDisplay();
         } else {
             $result[$repositoryId] = $repositoryObject;
         }
     }
     return $result;
 }
Exemple #20
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;
     }
     $foldersharing = $this->getFilteredOption("ENABLE_FOLDER_SHARING", $this->repository->getId());
     if (isset($foldersharing) && $foldersharing === false) {
         return 103;
     }
     $loggedUser = AuthService::getLoggedUser();
     $actRights = $loggedUser->mergedRole->listActionsStatesFor($repository);
     if (isset($actRights["share"]) && $actRights["share"] === false) {
         return 103;
     }
     $users = array();
     $uRights = array();
     $uPasses = array();
     $groups = array();
     $index = 0;
     $prefix = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId());
     while (isset($httpVars["user_" . $index])) {
         $eType = $httpVars["entry_type_" . $index];
         $rightString = ($httpVars["right_read_" . $index] == "true" ? "r" : "") . ($httpVars["right_write_" . $index] == "true" ? "w" : "");
         if ($this->watcher !== false) {
             $uWatch = $httpVars["right_watch_" . $index] == "true" ? true : false;
         }
         if (empty($rightString)) {
             $index++;
             continue;
         }
         if ($eType == "user") {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index], AJXP_SANITIZE_EMAILCHARS);
             if (!AuthService::userExists($u) && !isset($httpVars["user_pass_" . $index])) {
                 $index++;
                 continue;
             } else {
                 if (AuthService::userExists($u) && isset($httpVars["user_pass_" . $index])) {
                     throw new Exception("User {$u} already exists, please choose another name.");
                 }
             }
             if (!AuthService::userExists($u, "r") && !empty($prefix) && strpos($u, $prefix) !== 0) {
                 $u = $prefix . $u;
             }
             $users[] = $u;
         } else {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index]);
             if (strpos($u, "/AJXP_TEAM/") === 0) {
                 $confDriver = ConfService::getConfStorageImpl();
                 if (method_exists($confDriver, "teamIdToUsers")) {
                     $teamUsers = $confDriver->teamIdToUsers(str_replace("/AJXP_TEAM/", "", $u));
                     foreach ($teamUsers as $userId) {
                         $users[] = $userId;
                         $uRights[$userId] = $rightString;
                         if ($this->watcher !== false) {
                             $uWatches[$userId] = $uWatch;
                         }
                     }
                 }
                 $index++;
                 continue;
             } else {
                 $groups[] = $u;
             }
         }
         $uRights[$u] = $rightString;
         $uPasses[$u] = isset($httpVars["user_pass_" . $index]) ? $httpVars["user_pass_" . $index] : "";
         if ($this->watcher !== false) {
             $uWatches[$u] = $uWatch;
         }
         $index++;
     }
     $label = AJXP_Utils::decodeSecureMagic($httpVars["repo_label"]);
     $description = AJXP_Utils::decodeSecureMagic($httpVars["repo_description"]);
     if (isset($httpVars["repository_id"])) {
         $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]);
     }
     // CHECK USER & REPO DOES NOT ALREADY EXISTS
     if ($this->getFilteredOption("AVOID_SHARED_FOLDER_SAME_LABEL", $this->repository->getId()) == true) {
         $repos = ConfService::getRepositoriesList();
         foreach ($repos as $obj) {
             if ($obj->getDisplay() == $label && (!isset($editingRepo) || $editingRepo != $obj)) {
                 return 101;
             }
         }
     }
     $confDriver = ConfService::getConfStorageImpl();
     foreach ($users as $userName) {
         if (AuthService::userExists($userName)) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
             if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) {
                 return 102;
             }
         } else {
             if ($httpVars["create_guest_user"] != "true" && !ConfService::getCoreConf("USER_CREATE_USERS", "conf") || AuthService::isReservedUserId($userName)) {
                 return 102;
             }
             if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") {
                 return 100;
             }
         }
     }
     // CREATE SHARED OPTIONS
     $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository);
     $customData = array();
     foreach ($httpVars as $key => $value) {
         if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") {
             $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value;
         }
     }
     if (count($customData)) {
         $options["PLUGINS_DATA"] = $customData;
     }
     if (isset($editingRepo)) {
         $newRepo = $editingRepo;
         if ($editingRepo->getDisplay() != $label) {
             $newRepo->setDisplay($label);
             ConfService::replaceRepository($httpVars["repository_id"], $newRepo);
         }
         $editingRepo->setDescription($description);
     } else {
         if ($repository->getOption("META_SOURCES")) {
             $options["META_SOURCES"] = $repository->getOption("META_SOURCES");
             foreach ($options["META_SOURCES"] as $index => $data) {
                 if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) {
                     $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString();
                 }
             }
         }
         $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null);
         $gPath = $loggedUser->getGroupPath();
         if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
             $newRepo->setGroupPath($gPath);
         }
         $newRepo->setDescription($description);
         ConfService::addRepository($newRepo);
     }
     $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
     if (isset($editingRepo)) {
         $currentRights = $this->computeSharedRepositoryAccessRights($httpVars["repository_id"], false, $this->urlBase . $file);
         $originalUsers = array_keys($currentRights["USERS"]);
         $removeUsers = array_diff($originalUsers, $users);
         if (count($removeUsers)) {
             foreach ($removeUsers as $user) {
                 if (AuthService::userExists($user)) {
                     $userObject = $confDriver->createUserObject($user);
                     $userObject->personalRole->setAcl($newRepo->getUniqueId(), "");
                     $userObject->save("superuser");
                 }
             }
         }
         $originalGroups = array_keys($currentRights["GROUPS"]);
         $removeGroups = array_diff($originalGroups, $groups);
         if (count($removeGroups)) {
             foreach ($removeGroups as $groupId) {
                 $role = AuthService::getRole("AJXP_GRP_" . AuthService::filterBaseGroup($groupId));
                 if ($role !== false) {
                     $role->setAcl($newRepo->getUniqueId(), "");
                     AuthService::updateRole($role);
                 }
             }
         }
     }
     foreach ($users as $userName) {
         if (AuthService::userExists($userName, "r")) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
         } else {
             if (ConfService::getAuthDriverImpl()->getOption("TRANSMIT_CLEAR_PASS")) {
                 $pass = $uPasses[$userName];
             } else {
                 $pass = md5($uPasses[$userName]);
             }
             $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, "");
             if (!empty($limit) && intval($limit) > 0) {
                 $count = count(ConfService::getConfStorageImpl()->getUserChildren($loggedUser->getId()));
                 if ($count >= $limit) {
                     $mess = ConfService::getMessages();
                     throw new Exception($mess['483']);
                 }
             }
             AuthService::createUser($userName, $pass);
             $userObject = $confDriver->createUserObject($userName);
             $userObject->personalRole->clearAcls();
             $userObject->setParent($loggedUser->id);
             $userObject->setGroupPath($loggedUser->getGroupPath());
             $userObject->setProfile("shared");
             if (isset($httpVars["minisite"])) {
                 $mess = ConfService::getMessages();
                 $userObject->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", "[" . $mess["share_center.109"] . "] " . $newRepo->getDisplay());
             }
             AJXP_Controller::applyHook("user.after_create", array($userObject));
         }
         // CREATE USER WITH NEW REPO RIGHTS
         $userObject->personalRole->setAcl($newRepo->getUniqueId(), $uRights[$userName]);
         if (isset($httpVars["minisite"])) {
             $newRole = new AJXP_Role("AJXP_SHARED-" . $newRepo->getUniqueId());
             $r = AuthService::getRole("MINISITE");
             if (is_a($r, "AJXP_Role")) {
                 if ($httpVars["disable_download"]) {
                     $f = AuthService::getRole("MINISITE_NODOWNLOAD");
                     if (is_a($f, "AJXP_Role")) {
                         $r = $f->override($r);
                     }
                 }
                 $allData = $r->getDataArray();
                 $newData = $newRole->getDataArray();
                 if (isset($allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["ACTIONS"][$newRepo->getUniqueId()] = $allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 if (isset($allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["PARAMETERS"][$newRepo->getUniqueId()] = $allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 $newRole->bunchUpdate($newData);
                 AuthService::updateRole($newRole);
                 $userObject->addRole($newRole);
             }
         }
         $userObject->save("superuser");
         if ($this->watcher !== false) {
             // Register a watch on the current folder for shared user
             if ($uWatches[$userName] == "true") {
                 $this->watcher->setWatchOnFolder(new AJXP_Node($this->urlBase . $file), $userName, MetaWatchRegister::$META_WATCH_USERS_CHANGE, array(AuthService::getLoggedUser()->getId()));
             } else {
                 $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $userName, true);
             }
         }
     }
     if ($this->watcher !== false) {
         // Register a watch on the new repository root for current user
         if ($httpVars["self_watch_folder"] == "true") {
             $this->watcher->setWatchOnFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH);
         } else {
             $this->watcher->removeWatchFromFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId());
         }
     }
     foreach ($groups as $group) {
         $grRole = AuthService::getRole("AJXP_GRP_" . AuthService::filterBaseGroup($group), true);
         $grRole->setAcl($newRepo->getUniqueId(), $uRights[$group]);
         AuthService::updateRole($grRole);
     }
     if (array_key_exists("minisite", $httpVars) && $httpVars["minisite"] != true) {
         AJXP_Controller::applyHook("node.share.create", array('type' => 'repository', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'new_repository' => &$newRepo));
     }
     return $newRepo;
 }
    function listRepositories()
    {
        print '<columns switchGridMode="filelist"><column messageString="Repository Label" attributeName="ajxp_label" sortType="String"/><column messageString="Access Type" attributeName="accessType" sortType="String"/></columns>';
        $repos = ConfService::getRepositoriesList();
        $repoArray = array();
        foreach ($repos as $repoIndex => $repoObject) {
            if ($repoObject->getAccessType() == "ajxp_conf") {
                continue;
            }
            $name = Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
            $repoArray[$name] = $repoIndex;
        }
        // Sort the list now by name
        ksort($repoArray);
        foreach ($repoArray as $name => $repoIndex) {
            $repoObject =& $repos[$repoIndex];
            print '<tree 				
				text="' . $name . '" 
				is_file="1" 
				repository_id="' . $repoIndex . '" 
				accessType="' . $repoObject->getAccessType() . '" 
				icon="folder_red.png" 
				openicon="folder_red.png" 
				filename="/users/' . $name . '" 
				parentname="/users" 
				src="content.php?dir=%2Fusers%2F' . $name . '" 
				ajxp_mime="repository' . ($repoObject->isWriteable() ? "_editable" : "") . '"
				/>';
        }
    }
 public function listRepositories($root, $child, $hashValue = null, $returnNodes = false)
 {
     $repos = ConfService::getRepositoriesList("all");
     if (!$returnNodes) {
         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_shared.27" attributeName="owner" sortType="String"/>
         <column messageId="ajxp_conf.106" attributeName="repository_id" sortType="String"/>
         </columns>');
     }
     $repoArray = array();
     $childRepos = array();
     $templateRepos = array();
     $flatChildrenRepos = array();
     $allNodes = array();
     //uasort($repos, array($this, "sortReposByLabel"));
     foreach ($repos as $repoIndex => $repoObject) {
         if (!AuthService::canAdministrate($repoObject)) {
             continue;
         }
         if ($repoObject->getAccessType() == "ajxp_conf" || $repoObject->getAccessType() == "ajxp_shared") {
             continue;
         }
         if (is_numeric($repoIndex)) {
             $repoIndex = "" . $repoIndex;
         }
         $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
         if ($repoObject->hasOwner() || $repoObject->hasParent()) {
             $parentId = $repoObject->getParentId();
             if (isset($repos[$parentId]) && AuthService::canAdministrate($repos[$parentId])) {
                 if (!isset($childRepos[$parentId])) {
                     $childRepos[$parentId] = array();
                 }
                 $childRepos[$parentId][] = array("name" => $name, "index" => $repoIndex);
                 $flatChildrenRepos[] = $repoIndex;
                 continue;
             }
         }
         if ($repoObject->isTemplate) {
             $templateRepos[$name] = $repoIndex;
         } else {
             $repoArray[$name] = $repoIndex;
         }
     }
     // Sort the list now by name
     ksort($templateRepos);
     ksort($repoArray);
     $repoArray = array_merge($templateRepos, $repoArray);
     // Append child repositories
     $sortedArray = array();
     foreach ($repoArray as $name => $repoIndex) {
         $sortedArray[$name] = $repoIndex;
         if (isset($childRepos[$repoIndex]) && is_array($childRepos[$repoIndex])) {
             foreach ($childRepos[$repoIndex] as $childData) {
                 $sortedArray[$childData["name"]] = $childData["index"];
             }
         }
     }
     foreach ($sortedArray as $name => $repoIndex) {
         $repoObject =& $repos[$repoIndex];
         $icon = in_array($repoIndex, $flatChildrenRepos) ? "repo_child.png" : "hdd_external_unmount.png";
         $editable = $repoObject->isWriteable();
         if ($repoObject->isTemplate) {
             $icon = "hdd_external_mount.png";
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/") {
                 $editable = false;
             }
         }
         $meta = array("repository_id" => $repoIndex, "accessType" => ($repoObject->isTemplate ? "Template for " : "") . $repoObject->getAccessType(), "icon" => $icon, "owner" => $repoObject->hasOwner() ? $repoObject->getOwner() : "", "openicon" => $icon, "parentname" => "/repositories", "ajxp_mime" => "repository" . ($editable ? "_editable" : ""));
         $nodeKey = "/data/repositories/{$repoIndex}";
         if (in_array($nodeKey, $this->currentBookmarks)) {
             $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png"));
         }
         $xml = AJXP_XMLWriter::renderNode($nodeKey, $name, true, $meta, true, false);
         if ($returnNodes) {
             $allNodes[$nodeKey] = $xml;
         } else {
             print $xml;
         }
     }
     return $allNodes;
 }