/**
  * @param string $action
  * @param array $httpVars
  * @param array $fileVars
  */
 public function applyChangeLock($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars();
     $currentFile = $selection->getUniqueFile();
     $wrapperData = $this->accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId();
     $unlock = isset($httpVars["unlock"]) ? true : false;
     $ajxpNode = new AJXP_Node($urlBase . $currentFile);
     if ($unlock) {
         $this->metaStore->removeMetadata($ajxpNode, self::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL);
     } else {
         $this->metaStore->setMetadata($ajxpNode, SimpleLockManager::METADATA_LOCK_NAMESPACE, array("lock_user" => AuthService::getLoggedUser()->getId()), false, AJXP_METADATA_SCOPE_GLOBAL);
     }
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode();
     AJXP_XMLWriter::close();
 }
Exemplo n.º 2
0
 public function parseSpecificContributions(&$contribNode)
 {
     parent::parseSpecificContributions($contribNode);
     if ($contribNode->nodeName == "client_configs") {
         $actionXpath = new DOMXPath($contribNode->ownerDocument);
         $gettingStartedList = $actionXpath->query('template[@name="tutorial_pane"]', $contribNode);
         if (!$gettingStartedList->length) {
             return;
         }
         if ($this->getFilteredOption("ENABLE_GETTING_STARTED") === false) {
             $contribNode->removeChild($gettingStartedList->item(0));
         } else {
             $cdata = $gettingStartedList->item(0)->firstChild;
             $keys = array("URL_APP_IOSAPPSTORE", "URL_APP_ANDROID", "URL_APP_SYNC_WIN", "URL_APP_SYNC_MAC");
             $values = array();
             foreach ($keys as $k) {
                 $values[] = $this->getFilteredOption($k);
             }
             $newData = str_replace($keys, $values, $cdata->nodeValue);
             $newCData = $contribNode->ownerDocument->createCDATASection($newData);
             $gettingStartedList->item(0)->appendChild($newCData);
             $gettingStartedList->item(0)->replaceChild($newCData, $cdata);
         }
     } else {
         if ($contribNode->nodeName == "actions" && $this->getFilteredOption("DISPLAY_SERVER_QRCODE_ACTION") === false) {
             $actionXpath = new DOMXPath($contribNode->ownerDocument);
             $actionList = $actionXpath->query('action[@name="display-server-qrcode"]', $contribNode);
             $contribNode->removeChild($actionList->item(0));
         }
     }
 }
 /**
  * Parse
  * @param DOMNode $contribNode
  */
 protected function parseSpecificContributions(&$contribNode)
 {
     parent::parseSpecificContributions($contribNode);
     if ($contribNode->nodeName != "actions") {
         return;
     }
     $this->redirectActionsToMethod($contribNode, array("upload", "next_to_remote", "trigger_remote_copy"), "uploadActions");
 }
Exemplo n.º 4
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     switch ($action) {
         case "ls":
             $doc = DOMDocument::load($this->repository->getOption("HOST") . "?request=GetCapabilities");
             $xPath = new DOMXPath($doc);
             $dir = $httpVars["dir"];
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="wms.1" attributeName="ajxp_label" sortType="String"/><column messageId="wms.6" attributeName="srs" sortType="String"/><column messageId="wms.4" attributeName="style" sortType="String"/><column messageId="wms.5" attributeName="keywords" sortType="String"/></columns>');
             $layers = $xPath->query("Capability/Layer/Layer");
             // Detect "levels"
             $levels = array();
             $leafs = array();
             $styleLevels = $prefixLevels = false;
             foreach ($layers as $layer) {
                 $name = $xPath->evaluate("Name", $layer)->item(0)->nodeValue;
                 $stylesList = $xPath->query("Style/Name", $layer);
                 if (strstr($name, ":") !== false) {
                     $exp = explode(":", $name);
                     if (!isset($levels[$exp[0]])) {
                         $levels[$exp[0]] = array();
                     }
                     $levels[$exp[0]][] = $layer;
                     $prefixLevels = true;
                 } else {
                     if ($stylesList->length > 1) {
                         if (!isset($levels[$name])) {
                             $levels[$name] = array();
                         }
                         foreach ($stylesList as $style) {
                             $levels[$name][$style->nodeValue] = $layer;
                         }
                         $styleLevels = true;
                     } else {
                         $leafs[] = $layer;
                     }
                 }
             }
             if ($dir == "/" || $dir == "") {
                 $this->listLevels($levels);
                 $this->listLayers($leafs, $xPath);
             } else {
                 if (isset($levels[basename($dir)])) {
                     $this->listLayers($levels[basename($dir)], $xPath, $styleLevels ? array($this, "replaceStyle") : null);
                 }
             }
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
 }
Exemplo n.º 5
0
 function ftpAccessDriver($driverName, $filePath, $repository, $optOptions = NULL)
 {
     $this->user = $optOptions ? $optOptions["user"] : $this->getUserName($repository);
     $this->password = $optOptions ? $optOptions["password"] : $this->getPassword($repository);
     parent::AbstractAccessDriver($driverName, INSTALL_PATH . "/plugins/access.fs/fsActions.xml", $repository);
     unset($this->actions["upload"]);
     // DISABLE NON-IMPLEMENTED FUNCTIONS FOR THE MOMENT
     //unset($this->actions["copy"]);
     $this->initXmlActionsFile(INSTALL_PATH . "/plugins/access.remote_fs/additionalActions.xml");
     $this->xmlFilePath = INSTALL_PATH . "/plugins/access.fs/fsActions.xml";
 }
 function remote_fsAccessDriver($driverName, $filePath, $repository, $optOptions = NULL)
 {
     parent::AbstractAccessDriver($driverName, INSTALL_PATH . "/plugins/access.fs/fsActions.xml", $repository);
     unset($this->actions["upload"]);
     // ADD additional actions
     /*
     $this->xmlFilePath = INSTALL_PATH."/plugins/access.remote_fs/additionalActions.xml";
     $this->parseXMLActions();
     */
     $this->initXmlActionsFile(INSTALL_PATH . "/plugins/access.remote_fs/additionalActions.xml");
     $this->xmlFilePath = INSTALL_PATH . "/plugins/access.fs/fsActions.xml";
 }
 function init($repository, $optOption = null)
 {
     parent::init($repository, $optOption);
     $repositoryPath = $repository->getOption("PATH");
     $accountLimit = strpos($repositoryPath, "@");
     if ($accountLimit !== false) {
         $account = substr($repositoryPath, 0, $accountLimit);
         $repositoryPath = substr($repositoryPath, $accountLimit + 1);
         $repository->setOption("PATH", $repositoryPath);
     }
     // Set the password from a per user specific config
     $account = $optOption ? $optOption["account"] : $this->getUserName($repository);
     $password = $optOption ? $optOption["password"] : $this->getPassword($repository);
     $this->SSHOperation = new SSHOperations($repositoryPath, $account, $password);
 }
Exemplo n.º 8
0
 function sshAccessDriver($driverName, $filePath, $repository, $optOption = NULL)
 {
     $repositoryPath = $repository->getOption("PATH");
     $accountLimit = strpos($repositoryPath, "@");
     if ($accountLimit !== false) {
         $account = substr($repositoryPath, 0, $accountLimit);
         $repositoryPath = substr($repositoryPath, $accountLimit + 1);
         $repository->setOption("PATH", $repositoryPath);
     }
     // Set the password from a per user specific config
     $account = $optOption ? $optOption["account"] : $this->getUserName($repository);
     $password = $optOption ? $optOption["password"] : $this->getPassword($repository);
     $this->SSHOperation = new SSHOperations($repositoryPath, $account, $password);
     parent::AbstractAccessDriver($driverName, $filePath, $repository);
 }
 function init($repository, $options = null)
 {
     $repoCapabilities = $repository->getOption("API_CAPABILITIES");
     if ($repoCapabilities != "") {
         $this->plugCapabilities = explode(",", $repoCapabilities);
         // Register one preprocessor per capability.
         foreach ($this->plugCapabilities as $capability) {
             $xml = '<action name="' . $capability . '"><pre_processing><serverCallback methodName="switchAction"/></pre_processing></action>';
             $tmpDoc = DOMDocument::loadXML($xml);
             $newNode = $this->manifestDoc->importNode($tmpDoc->documentElement, true);
             $this->xPath->query("registry_contributions/actions")->item(0)->appendChild($newNode);
         }
     }
     parent::init($repository, $options);
 }
Exemplo n.º 10
0
 /**
  * @param String $dir
  * @return bool|int
  */
 private function getUsage()
 {
     $data = $this->getUserData();
     $repo = $this->accessDriver->repository->getId();
     $repoOptions = $this->getWorkingRepositoryOptions();
     if (!isset($data["REPO_USAGES"][$repo]) || $this->options["CACHE_QUOTA"] === false) {
         $quota = $this->accessDriver->directoryUsage("", $repoOptions);
         if (!isset($data["REPO_USAGES"])) {
             $data["REPO_USAGES"] = array();
         }
         $data["REPO_USAGES"][$repo] = $quota;
         $this->saveUserData($data);
     }
     if ($this->getFilteredOption("USAGE_SCOPE", $repo) == "local") {
         return floatval($data["REPO_USAGES"][$repo]);
     } else {
         return array_sum(array_map("floatval", $data["REPO_USAGES"]));
     }
 }
Exemplo n.º 11
0
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     $currentFile = $selection->getUniqueFile();
     $urlBase = $this->accessDriver->getResourceUrl($currentFile);
     $ajxpNode = new AJXP_Node($urlBase);
     $newValues = array();
     $def = $this->getMetaDefinition();
     $ajxpNode->setDriver($this->accessDriver);
     AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode));
     foreach ($def as $key => $data) {
         if (isset($httpVars[$key])) {
             $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]);
         } else {
             if (!isset($original)) {
                 $original = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL);
             }
             if (isset($original) && isset($original[$key])) {
                 $newValues[$key] = $original[$key];
             }
         }
     }
     $ajxpNode->setMetadata("users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL);
     AJXP_Controller::applyHook("node.meta_change", array($ajxpNode));
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => array($ajxpNode->getPath() => $ajxpNode)), true);
     AJXP_XMLWriter::close();
 }
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars();
     $currentFile = $selection->getUniqueFile();
     $wrapperData = $this->accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId();
     $newValues = array();
     $def = $this->getMetaDefinition();
     $ajxpNode = new AJXP_Node($urlBase . $currentFile);
     AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode));
     foreach ($def as $key => $label) {
         if (isset($httpVars[$key])) {
             $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]);
         } else {
             if (!isset($original)) {
                 $original = $this->metaStore->retrieveMetadata($ajxpNode, "users_meta", false, AJXP_METADATA_SCOPE_GLOBAL);
             }
             if (isset($original) && isset($original[$key])) {
                 $newValues[$key] = $original[$key];
             }
         }
     }
     $this->metaStore->setMetadata($ajxpNode, "users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL);
     AJXP_Controller::applyHook("node.change", array(null, &$ajxpNode));
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true);
     AJXP_XMLWriter::close();
 }
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $loggedUser = AuthService::getLoggedUser();
     if (!ENABLE_USERS) {
         return;
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png", "DESCRIPTION" => $mess["ajxp_shared.28"]), "repositories" => array("LABEL" => $mess["ajxp_shared.2"], "ICON" => "document_open_remote.png", "DESCRIPTION" => $mess["ajxp_shared.29"]), "users" => array("LABEL" => $mess["ajxp_shared.1"], "ICON" => "user_shared.png", "DESCRIPTION" => $mess["ajxp_shared.30"]));
             $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : "";
             $splits = explode("/", $dir);
             if (count($splits)) {
                 if ($splits[0] == "") {
                     array_shift($splits);
                 }
                 if (count($splits)) {
                     $strippedDir = strtolower(urldecode($splits[0]));
                 } else {
                     $strippedDir = "";
                 }
             }
             if (array_key_exists($strippedDir, $rootNodes)) {
                 AJXP_XMLWriter::header();
                 if ($strippedDir == "users") {
                     $this->listUsers();
                 } else {
                     if ($strippedDir == "repositories") {
                         $this->listRepositories();
                     } else {
                         if ($strippedDir == "files") {
                             $this->listSharedFiles();
                         }
                     }
                 }
                 AJXP_XMLWriter::close();
                 exit(1);
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_shared.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_shared.31" attributeName="description" sortType="String"/></columns>');
                 foreach ($rootNodes as $key => $data) {
                     print '<tree text="' . $data["LABEL"] . '" icon="' . $data["ICON"] . '" filename="/' . $key . '" parentname="/" description="' . $data["DESCRIPTION"] . '" />';
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             break;
         case "delete":
             $mime = $httpVars["ajxp_mime"];
             $selection = new UserSelection();
             $selection->initFromHttpVars();
             $files = $selection->getFiles();
             AJXP_XMLWriter::header();
             foreach ($files as $index => $element) {
                 $element = basename($element);
                 if ($mime == "shared_repository") {
                     $repo = ConfService::getRepositoryById($element);
                     if (!$repo->hasOwner() || $repo->getOwner() != $loggedUser->getId()) {
                         AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]);
                         break;
                     } else {
                         $res = ConfService::deleteRepository($element);
                         if ($res == -1) {
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]);
                             break;
                         } else {
                             if ($index == count($files) - 1) {
                                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null);
                                 AJXP_XMLWriter::reloadDataNode();
                             }
                         }
                     }
                 } else {
                     if ($mime == "shared_user") {
                         $confDriver = ConfService::getConfStorageImpl();
                         $object = $confDriver->createUserObject($element);
                         if (!$object->hasParent() || $object->getParent() != $loggedUser->getId()) {
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]);
                             break;
                         } else {
                             $res = AuthService::deleteUser($element);
                             if ($index == count($files) - 1) {
                                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null);
                                 AJXP_XMLWriter::reloadDataNode();
                             }
                         }
                     } else {
                         if ($mime == "shared_file") {
                             $publicletData = $this->loadPublicletData(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php");
                             if (isset($publicletData["OWNER_ID"]) && $publicletData["OWNER_ID"] == $loggedUser->getId()) {
                                 require_once INSTALL_PATH . "/server/classes/class.PublicletCounter.php";
                                 PublicletCounter::delete($element);
                                 unlink(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php");
                                 if ($index == count($files) - 1) {
                                     AJXP_XMLWriter::sendMessage($mess["ajxp_shared.13"], null);
                                     AJXP_XMLWriter::reloadDataNode();
                                 }
                             } else {
                                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]);
                                 break;
                             }
                         }
                     }
                 }
             }
             AJXP_XMLWriter::close();
             break;
         case "clear_expired":
             $deleted = $this->clearExpiredFiles();
             AJXP_XMLWriter::header();
             if (count($deleted)) {
                 AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null);
             }
             AJXP_XMLWriter::close();
             break;
         case "reset_download_counter":
             $selection = new UserSelection();
             $selection->initFromHttpVars();
             $elements = $selection->getFiles();
             require_once INSTALL_PATH . "/server/classes/class.PublicletCounter.php";
             foreach ($elements as $element) {
                 PublicletCounter::reset(str_replace(".php", "", basename($element)));
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     return;
 }
Exemplo n.º 14
0
 /** Cypher the publiclet object data and write to disk.
  * @param array $data The publiclet data array to write
  * The data array must have the following keys:
  * - DRIVER      The driver used to get the file's content
  * - OPTIONS     The driver options to be successfully constructed (usually, the user and password)
  * - FILE_PATH   The path to the file's content
  * - PASSWORD    If set, the written publiclet will ask for this password before sending the content
  * - ACTION      If set, action to perform
  * - USER        If set, the AJXP user
  * - EXPIRE_TIME If set, the publiclet will deny downloading after this time, and probably self destruct.
  *               - AUTHOR_WATCH If set, will post notifications for the publiclet author each time the file is loaded
  * @param AbstractAccessDriver $accessDriver
  * @param Repository $repository
  * @param ShareStore $shareStore
  * @param PublicAccessManager $publicAccessManager
  * @return string|array An array containing the hash (0) and the generated url (1)
  */
 public function writePubliclet(&$data, $accessDriver, $repository, $shareStore, $publicAccessManager)
 {
     $downloadFolder = $publicAccessManager->getPublicDownloadFolder();
     $publicAccessManager->initFolder();
     if (!is_dir($downloadFolder)) {
         return "ERROR : Public URL folder does not exist!";
     }
     if (!function_exists("mcrypt_create_iv")) {
         return "ERROR : MCrypt must be installed to use publiclets!";
     }
     $data["PLUGIN_ID"] = $accessDriver->getId();
     $data["BASE_DIR"] = $accessDriver->getBaseDir();
     //$data["REPOSITORY"] = $repository;
     if (AuthService::usersEnabled()) {
         $data["OWNER_ID"] = AuthService::getLoggedUser()->getId();
     }
     $shareStore->storeSafeCredentialsIfNeeded($data, $accessDriver, $repository);
     // Force expanded path in publiclet
     $copy = clone $repository;
     $copy->addOption("PATH", $repository->getOption("PATH"));
     $data["REPOSITORY"] = $copy;
     if ($data["ACTION"] == "") {
         $data["ACTION"] = "download";
     }
     try {
         $hash = $shareStore->storeShare($repository->getId(), $data, "publiclet");
     } catch (Exception $e) {
         return $e->getMessage();
     }
     $shareStore->resetDownloadCounter($hash, AuthService::getLoggedUser()->getId());
     $url = $publicAccessManager->buildPublicLink($hash);
     AJXP_Logger::log2(LOG_LEVEL_INFO, __CLASS__, "New Share", array("file" => "'" . $copy->display . ":/" . $data['FILE_PATH'] . "'", "files" => "'" . $copy->display . ":/" . $data['FILE_PATH'] . "'", "url" => $url, "expiration" => $data['EXPIRE_TIME'], "limit" => $data['DOWNLOAD_LIMIT'], "repo_uuid" => $copy->uuid));
     AJXP_Controller::applyHook("node.share.create", array('type' => 'file', 'repository' => &$copy, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url));
     return array($hash, $url);
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     parent::accessPreprocess($action, $httpVars, $fileVars);
     if (!AuthService::usersEnabled()) {
         return;
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("users" => array("LABEL" => $mess["user_dash.1"], "ICON" => "user_shared.png", "ICON-CLASS" => "icon-book", "DESCRIPTION" => $mess["user_dash.30"]), "files" => array("LABEL" => $mess["user_dash.34"], "ICON" => "user_shared.png", "ICON-CLASS" => "mdi mdi-share-variant", "DESCRIPTION" => $mess["user_dash.35"]), "settings" => array("LABEL" => $mess["user_dash.36"], "ICON" => "user_shared.png", "ICON-CLASS" => "icon-cog", "DESCRIPTION" => $mess["user_dash.37"]), "repositories" => array("LABEL" => $mess["user_dash.36"], "ICON" => "user_shared.png", "ICON-CLASS" => "icon-cog", "DESCRIPTION" => $mess["user_dash.37"]), "teams" => array("LABEL" => "Teams", "ICON" => "user_shared.png", "ICON-CLASS" => "icon-group", "DESCRIPTION" => "My Teams"));
             $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : "";
             $splits = explode("/", $dir);
             if (count($splits)) {
                 if ($splits[0] == "") {
                     array_shift($splits);
                 }
                 if (count($splits)) {
                     $strippedDir = strtolower(urldecode($splits[0]));
                 } else {
                     $strippedDir = "";
                 }
             }
             if (array_key_exists($strippedDir, $rootNodes)) {
                 AJXP_XMLWriter::header();
                 if ($strippedDir == "users") {
                     $this->listUsers();
                 } else {
                     if ($strippedDir == "teams") {
                         $this->listTeams();
                     } else {
                         if ($strippedDir == "repositories") {
                             $this->listRepositories();
                         } else {
                             if ($strippedDir == "files") {
                                 $this->listSharedFiles("files");
                             }
                         }
                     }
                 }
                 AJXP_XMLWriter::close();
             } else {
                 AJXP_XMLWriter::header();
                 /*
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="user_dash.8" attributeName="ajxp_label" sortType="String"/><column messageId="user_dash.31" attributeName="description" sortType="String"/></columns>');
                 foreach ($rootNodes as $key => $data) {
                     $l = $data["LABEL"];
                     print '<tree text="'.$l.'" icon="'.$data["ICON"].'" filename="/'.$key.'" parentname="/" description="'.$data["DESCRIPTION"].'" />';
                 }
                 */
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             break;
         case "delete":
             $mime = $httpVars["ajxp_mime"];
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $files = $selection->getFiles();
             AJXP_XMLWriter::header();
             $minisites = $this->listSharedFiles("minisites");
             /**
              * @var ShareCenter $shareCenter
              */
             $shareCenter = AJXP_PluginsService::findPluginById("action.share");
             foreach ($files as $index => $element) {
                 $element = basename($element);
                 $ar = explode("shared_", $mime);
                 $mime = array_pop($ar);
                 if ($mime == "repository" && isset($minisites[$element])) {
                     $mime = "minisite";
                     $element = $minisites[$element];
                 }
                 $shareCenter->getShareStore()->deleteShare($mime, $element);
                 if ($mime == "repository" || $mime == "minisite") {
                     $out = $mess["ajxp_conf.59"];
                 } else {
                     if ($mime == "user") {
                         $out = $mess["ajxp_conf.60"];
                     } else {
                         if ($mime == "file") {
                             $out = $mess["user_dash.13"];
                         }
                     }
                 }
             }
             AJXP_XMLWriter::sendMessage($out, null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "clear_expired":
             /**
              * @var ShareCenter $shareCenter
              */
             $shareCenter = AJXP_PluginsService::getInstance()->findPluginById("action.share");
             $deleted = $shareCenter->getShareStore()->clearExpiredFiles(true);
             AJXP_XMLWriter::header();
             if (count($deleted)) {
                 AJXP_XMLWriter::sendMessage(sprintf($mess["user_dash.23"], count($deleted) . ""), null);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage($mess["user_dash.24"], null);
             }
             AJXP_XMLWriter::close();
             break;
         case "reset_download_counter":
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $elements = $selection->getFiles();
             foreach ($elements as $element) {
                 PublicletCounter::reset(str_replace(".php", "", basename($element)));
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     return;
 }
Exemplo n.º 16
0
 /**
  * @param array $data
  * @param AbstractAccessDriver $accessDriver
  * @param Repository $repository
  */
 public function storeSafeCredentialsIfNeeded(&$data, $accessDriver, $repository)
 {
     $storeCreds = false;
     if ($repository->getOption("META_SOURCES")) {
         $options["META_SOURCES"] = $repository->getOption("META_SOURCES");
         foreach ($options["META_SOURCES"] as $metaSource) {
             if (isset($metaSource["USE_SESSION_CREDENTIALS"]) && $metaSource["USE_SESSION_CREDENTIALS"] === true) {
                 $storeCreds = true;
                 break;
             }
         }
     }
     if ($storeCreds || $accessDriver->hasMixin("credentials_consumer")) {
         $cred = AJXP_Safe::tryLoadingCredentialsFromSources(array(), $repository);
         if (isset($cred["user"]) && isset($cred["password"])) {
             $data["SAFE_USER"] = $cred["user"];
             $data["SAFE_PASS"] = $cred["password"];
         }
     }
 }
Exemplo n.º 17
0
 /**
  * @param AbstractAccessDriver $accessDriver
  * @return AJXP_Node[]
  * @throws Exception
  */
 public function buildNodes(AbstractAccessDriver $accessDriver)
 {
     if (isset($this->nodes)) {
         return $this->nodes;
     }
     $wrapperData = $accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $accessDriver->repository->getId();
     $nodes = array();
     foreach ($this->files as $file) {
         $nodes[] = new AJXP_Node($urlBase . $file);
     }
     return $nodes;
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $loggedUser = AuthService::getLoggedUser();
     if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) {
         return;
     }
     if (AuthService::usersEnabled()) {
         $currentBookmarks = AuthService::getLoggedUser()->getBookmarks();
         // FLATTEN
         foreach ($currentBookmarks as $bm) {
             $this->currentBookmarks[] = $bm["PATH"];
         }
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     $currentUserIsGroupAdmin = AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/";
     if ($currentUserIsGroupAdmin && ConfService::getAuthDriverImpl()->isAjxpAdmin(AuthService::getLoggedUser()->getId())) {
         $currentUserIsGroupAdmin = false;
     }
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("data" => array("LABEL" => $mess["ajxp_conf.110"], "ICON" => "user.png", "DESCRIPTION" => $mess["ajxp_conf.137"], "CHILDREN" => array("repositories" => array("AJXP_MIME" => "workspaces_zone", "LABEL" => $mess["ajxp_conf.3"], "DESCRIPTION" => $mess["ajxp_conf.138"], "ICON" => "hdd_external_unmount.png", "LIST" => "listRepositories"), "users" => array("AJXP_MIME" => "users_zone", "LABEL" => $mess["ajxp_conf.2"], "DESCRIPTION" => $mess["ajxp_conf.139"], "ICON" => "users-folder.png", "LIST" => "listUsers"), "roles" => array("AJXP_MIME" => "roles_zone", "LABEL" => $mess["ajxp_conf.69"], "DESCRIPTION" => $mess["ajxp_conf.140"], "ICON" => "user-acl.png", "LIST" => "listRoles"))), "config" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.109"], "ICON" => "preferences_desktop.png", "DESCRIPTION" => $mess["ajxp_conf.136"], "CHILDREN" => array("core" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.98"], "DESCRIPTION" => $mess["ajxp_conf.133"], "ICON" => "preferences_desktop.png", "LIST" => "listPlugins"), "plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.99"], "DESCRIPTION" => $mess["ajxp_conf.134"], "ICON" => "folder_development.png", "LIST" => "listPlugins"), "core_plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.123"], "DESCRIPTION" => $mess["ajxp_conf.135"], "ICON" => "folder_development.png", "LIST" => "listPlugins"))), "admin" => array("LABEL" => $mess["ajxp_conf.111"], "ICON" => "toggle_log.png", "DESCRIPTION" => $mess["ajxp_conf.141"], "CHILDREN" => array("logs" => array("LABEL" => $mess["ajxp_conf.4"], "DESCRIPTION" => $mess["ajxp_conf.142"], "ICON" => "toggle_log.png", "LIST" => "listLogFiles"), "diagnostic" => array("LABEL" => $mess["ajxp_conf.5"], "DESCRIPTION" => $mess["ajxp_conf.143"], "ICON" => "susehelpcenter.png", "LIST" => "printDiagnostic"))), "developer" => array("LABEL" => $mess["ajxp_conf.144"], "ICON" => "applications_engineering.png", "DESCRIPTION" => $mess["ajxp_conf.145"], "CHILDREN" => array("actions" => array("LABEL" => $mess["ajxp_conf.146"], "DESCRIPTION" => $mess["ajxp_conf.147"], "ICON" => "book.png", "LIST" => "listActions"), "hooks" => array("LABEL" => $mess["ajxp_conf.148"], "DESCRIPTION" => $mess["ajxp_conf.149"], "ICON" => "book.png", "LIST" => "listHooks"))));
             if ($currentUserIsGroupAdmin) {
                 unset($rootNodes["config"]);
                 unset($rootNodes["admin"]);
                 unset($rootNodes["developer"]);
             }
             AJXP_Controller::applyHook("ajxp_conf.list_config_nodes", array(&$rootNodes));
             $parentName = "";
             $dir = trim(AJXP_Utils::decodeSecureMagic(isset($httpVars["dir"]) ? $httpVars["dir"] : ""), " /");
             if ($dir != "") {
                 $hash = null;
                 if (strstr(urldecode($dir), "#") !== false) {
                     list($dir, $hash) = explode("#", urldecode($dir));
                 }
                 $splits = explode("/", $dir);
                 $root = array_shift($splits);
                 if (count($splits)) {
                     $returnNodes = false;
                     if (isset($httpVars["file"])) {
                         $returnNodes = true;
                     }
                     $child = $splits[0];
                     if (isset($rootNodes[$root]["CHILDREN"][$child])) {
                         $atts = array();
                         if ($child == "users") {
                             $atts["remote_indexation"] = "admin_search";
                         }
                         $callback = $rootNodes[$root]["CHILDREN"][$child]["LIST"];
                         if (is_string($callback) && method_exists($this, $callback)) {
                             if (!$returnNodes) {
                                 AJXP_XMLWriter::header("tree", $atts);
                             }
                             $res = call_user_func(array($this, $callback), implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : '');
                             if (!$returnNodes) {
                                 AJXP_XMLWriter::close();
                             }
                         } else {
                             if (is_array($callback)) {
                                 $res = call_user_func($callback, implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : '');
                             }
                         }
                         if ($returnNodes) {
                             AJXP_XMLWriter::header("tree", $atts);
                             if (isset($res["/" . $dir . "/" . $httpVars["file"]])) {
                                 print $res["/" . $dir . "/" . $httpVars["file"]];
                             }
                             AJXP_XMLWriter::close();
                         }
                         return;
                     }
                 } else {
                     $parentName = "/" . $root . "/";
                     $nodes = $rootNodes[$root]["CHILDREN"];
                 }
             } else {
                 $parentName = "/";
                 $nodes = $rootNodes;
             }
             if (isset($httpVars["file"])) {
                 $parentName = $httpVars["dir"] . "/";
                 $nodes = array(basename($httpVars["file"]) => array("LABEL" => basename($httpVars["file"])));
             }
             if (isset($nodes)) {
                 AJXP_XMLWriter::header();
                 if (!isset($httpVars["file"])) {
                     AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="detail"><column messageId="ajxp_conf.1" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.102" attributeName="description" sortType="String"/></columns>');
                 }
                 foreach ($nodes as $key => $data) {
                     $bmString = '';
                     if (in_array($parentName . $key, $this->currentBookmarks)) {
                         $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" ';
                     }
                     if ($key == "users") {
                         $bmString .= ' remote_indexation="admin_search"';
                     }
                     if (isset($data["AJXP_MIME"])) {
                         $bmString .= ' ajxp_mime="' . $data["AJXP_MIME"] . '"';
                     }
                     if (empty($data["CHILDREN"])) {
                         print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '/>';
                     } else {
                         print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '>';
                         foreach ($data["CHILDREN"] as $cKey => $cData) {
                             $bmString = '';
                             if (in_array($parentName . $key . "/" . $cKey, $this->currentBookmarks)) {
                                 $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" ';
                             }
                             if ($cKey == "users") {
                                 $bmString .= ' remote_indexation="admin_search"';
                             }
                             if (isset($cData["AJXP_MIME"])) {
                                 $bmString .= ' ajxp_mime="' . $cData["AJXP_MIME"] . '"';
                             }
                             print '<tree text="' . AJXP_Utils::xmlEntities($cData["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($cData["DESCRIPTION"]) . '" icon="' . $cData["ICON"] . '" filename="' . $parentName . $key . '/' . $cKey . '" ' . $bmString . '/>';
                         }
                         print '</tree>';
                     }
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             return;
             break;
         case "clear_plugins_cache":
             AJXP_XMLWriter::header();
             // Clear plugins cache if they exist
             AJXP_PluginsService::clearPluginsCache();
             ConfService::clearMessagesCache();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . (AJXP_SKIP_CACHE ? "132" : "131")], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "create_group":
             if (isset($httpVars["group_path"])) {
                 $basePath = AJXP_Utils::forwardSlashDirname($httpVars["group_path"]);
                 if (empty($basePath)) {
                     $basePath = "/";
                 }
                 $gName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic(basename($httpVars["group_path"])), AJXP_SANITIZE_ALPHANUM);
             } else {
                 $basePath = substr($httpVars["dir"], strlen("/data/users"));
                 $gName = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["group_name"]), AJXP_SANITIZE_ALPHANUM);
             }
             $gLabel = AJXP_Utils::decodeSecureMagic($httpVars["group_label"]);
             AuthService::createGroup($basePath, $gName, $gLabel);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.124"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "create_role":
             $roleId = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["role_id"]), AJXP_SANITIZE_HTML_STRICT);
             if (!strlen($roleId)) {
                 throw new Exception($mess[349]);
             }
             if (AuthService::getRole($roleId) !== false) {
                 throw new Exception($mess["ajxp_conf.65"]);
             }
             $r = new AJXP_Role($roleId);
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                 $r->setGroupPath(AuthService::getLoggedUser()->getGroupPath());
             }
             AuthService::updateRole($r);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null);
             AJXP_XMLWriter::reloadDataNode("", $httpVars["role_id"]);
             AJXP_XMLWriter::close();
             break;
         case "edit_role":
             $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]);
             $roleGroup = false;
             $userObject = null;
             $groupLabel = null;
             if (strpos($roleId, "AJXP_GRP_") === 0) {
                 $groupPath = substr($roleId, strlen("AJXP_GRP_"));
                 $filteredGroupPath = AuthService::filterBaseGroup($groupPath);
                 $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath));
                 $key = "/" . basename($groupPath);
                 if (!array_key_exists($key, $groups)) {
                     throw new Exception("Cannot find group with this id!");
                 }
                 $roleId = "AJXP_GRP_" . $filteredGroupPath;
                 $groupLabel = $groups[$key];
                 $roleGroup = true;
             }
             if (strpos($roleId, "AJXP_USR_") === 0) {
                 $usrId = str_replace("AJXP_USR_/", "", $roleId);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cant find user!");
                 }
                 $role = $userObject->personalRole;
             } else {
                 $role = AuthService::getRole($roleId, $roleGroup);
             }
             if ($role === false) {
                 throw new Exception("Cant find role! ");
             }
             if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
                 HTMLWriter::charsetHeader("application/json");
                 $roleData = $role->getDataArray(true);
                 $allReps = ConfService::getRepositoriesList("all", false);
                 $repos = array();
                 if (!empty($userObject)) {
                     // USER
                     foreach ($allReps as $repositoryId => $repositoryObject) {
                         if (!AuthService::canAssign($repositoryObject, $userObject) || $repositoryObject->isTemplate || $repositoryObject->getAccessType() == "ajxp_conf" && !$userObject->isAdmin() || $repositoryObject->getUniqueUser() != null && $repositoryObject->getUniqueUser() != $userObject->getId()) {
                             continue;
                         }
                         $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay());
                     }
                 } else {
                     foreach ($allReps as $repositoryId => $repositoryObject) {
                         if (!AuthService::canAdministrate($repositoryObject)) {
                             continue;
                         }
                         $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay());
                     }
                 }
                 // Make sure it's utf8
                 $data = array("ROLE" => $roleData, "ALL" => array("REPOSITORIES" => $repos));
                 if (isset($userObject)) {
                     $data["USER"] = array();
                     $data["USER"]["LOCK"] = $userObject->getLock();
                     $data["USER"]["PROFILE"] = $userObject->getProfile();
                     $data["ALL"]["PROFILES"] = array("standard|Standard", "admin|Administrator", "shared|Shared", "guest|Guest");
                     $data["USER"]["ROLES"] = array_keys($userObject->getRoles());
                     $data["ALL"]["ROLES"] = array_keys(AuthService::getRolesList(array(), true));
                     if (isset($userObject->parentRole)) {
                         $data["PARENT_ROLE"] = $userObject->parentRole->getDataArray();
                     }
                 } else {
                     if (isset($groupPath)) {
                         $data["GROUP"] = array("PATH" => $groupPath, "LABEL" => $groupLabel);
                     }
                 }
                 $scope = "role";
                 if ($roleGroup) {
                     $scope = "group";
                 } else {
                     if (isset($userObject)) {
                         $scope = "user";
                     }
                 }
                 $data["SCOPE_PARAMS"] = array();
                 $nodes = AJXP_PluginsService::getInstance()->searchAllManifests("//param[contains(@scope,'" . $scope . "')]|//global_param[contains(@scope,'" . $scope . "')]", "node", false, true, true);
                 foreach ($nodes as $node) {
                     $pId = $node->parentNode->parentNode->attributes->getNamedItem("id")->nodeValue;
                     $origName = $node->attributes->getNamedItem("name")->nodeValue;
                     $node->attributes->getNamedItem("name")->nodeValue = "AJXP_REPO_SCOPE_ALL/" . $pId . "/" . $origName;
                     $nArr = array();
                     foreach ($node->attributes as $attrib) {
                         $nArr[$attrib->nodeName] = AJXP_XMLWriter::replaceAjxpXmlKeywords($attrib->nodeValue);
                     }
                     $data["SCOPE_PARAMS"][] = $nArr;
                 }
                 echo json_encode($data);
             }
             break;
         case "post_json_role":
             $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]);
             $roleGroup = false;
             $userObject = $usrId = $filteredGroupPath = null;
             if (strpos($roleId, "AJXP_GRP_") === 0) {
                 $groupPath = substr($roleId, strlen("AJXP_GRP_"));
                 $filteredGroupPath = AuthService::filterBaseGroup($groupPath);
                 $roleId = "AJXP_GRP_" . $filteredGroupPath;
                 $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath));
                 $key = "/" . basename($groupPath);
                 if (!array_key_exists($key, $groups)) {
                     throw new Exception("Cannot find group with this id!");
                 }
                 $groupLabel = $groups[$key];
                 $roleGroup = true;
             }
             if (strpos($roleId, "AJXP_USR_") === 0) {
                 $usrId = str_replace("AJXP_USR_/", "", $roleId);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cannot post role for user " . $usrId);
                 }
                 $originalRole = $userObject->personalRole;
             } else {
                 // second param = create if not exists.
                 $originalRole = AuthService::getRole($roleId, $roleGroup);
             }
             if ($originalRole === false) {
                 throw new Exception("Cant find role! ");
             }
             $jsonData = SystemTextEncoding::magicDequote($httpVars["json_data"]);
             $data = json_decode($jsonData, true);
             $roleData = $data["ROLE"];
             $forms = $data["FORMS"];
             $binariesContext = array();
             if (isset($userObject)) {
                 $binariesContext = array("USER" => $userObject->getId());
             }
             foreach ($forms as $repoScope => $plugData) {
                 foreach ($plugData as $plugId => $formsData) {
                     $parsed = array();
                     AJXP_Utils::parseStandardFormParameters($formsData, $parsed, $userObject != null ? $usrId : null, "ROLE_PARAM_", $binariesContext, AJXP_Role::$cypheredPassPrefix);
                     $roleData["PARAMETERS"][$repoScope][$plugId] = $parsed;
                 }
             }
             $existingParameters = $originalRole->listParameters(true);
             $this->mergeExistingParameters($roleData["PARAMETERS"], $existingParameters);
             if (isset($userObject) && isset($data["USER"]) && isset($data["USER"]["PROFILE"])) {
                 $userObject->setAdmin($data["USER"]["PROFILE"] == "admin");
                 $userObject->setProfile($data["USER"]["PROFILE"]);
             }
             if (isset($data["GROUP_LABEL"]) && isset($groupLabel) && $groupLabel != $data["GROUP_LABEL"]) {
                 ConfService::getConfStorageImpl()->relabelGroup($filteredGroupPath, $data["GROUP_LABEL"]);
             }
             if ($currentUserIsGroupAdmin) {
                 // FILTER DATA FOR GROUP ADMINS
                 $params = $this->getEditableParameters(false);
                 foreach ($roleData["PARAMETERS"] as $scope => &$plugsParameters) {
                     foreach ($plugsParameters as $paramPlugin => &$parameters) {
                         foreach ($parameters as $pName => $pValue) {
                             if (!isset($params[$paramPlugin]) || !in_array($pName, $params[$paramPlugin])) {
                                 unset($parameters[$pName]);
                             }
                         }
                         if (!count($parameters)) {
                             unset($plugsParameters[$paramPlugin]);
                         }
                     }
                     if (!count($plugsParameters)) {
                         unset($roleData["PARAMETERS"][$scope]);
                     }
                 }
                 // Remerge from parent
                 $roleData["PARAMETERS"] = $originalRole->array_merge_recursive2($originalRole->listParameters(), $roleData["PARAMETERS"]);
                 // Changing Actions is not allowed
                 $roleData["ACTIONS"] = $originalRole->listActionsStates();
             }
             try {
                 $originalRole->bunchUpdate($roleData);
                 if (isset($userObject)) {
                     $userObject->personalRole = $originalRole;
                     $userObject->save("superuser");
                 } else {
                     AuthService::updateRole($originalRole);
                 }
                 $output = array("ROLE" => $originalRole->getDataArray(true), "SUCCESS" => true);
             } catch (Exception $e) {
                 $output = array("ERROR" => $e->getMessage());
             }
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($output);
             break;
         case "user_set_lock":
             $userId = AJXP_Utils::decodeSecureMagic($httpVars["user_id"]);
             $lock = $httpVars["lock"] == "true" ? true : false;
             $lockType = $httpVars["lock_type"];
             if (AuthService::userExists($userId)) {
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cannot update user data for " . $userId);
                 }
                 if ($lock) {
                     $userObject->setLock($lockType);
                 } else {
                     $userObject->removeLock();
                 }
                 $userObject->save("superuser");
             }
             break;
         case "create_user":
             if (!isset($httpVars["new_user_login"]) || $httpVars["new_user_login"] == "" || !isset($httpVars["new_user_pwd"]) || $httpVars["new_user_pwd"] == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $original_login = SystemTextEncoding::magicDequote($httpVars["new_user_login"]);
             $new_user_login = AJXP_Utils::sanitize($original_login, AJXP_SANITIZE_EMAILCHARS);
             if ($original_login != $new_user_login) {
                 throw new Exception(str_replace("%s", $new_user_login, $mess["ajxp_conf.127"]));
             }
             if (AuthService::userExists($new_user_login, "w") || AuthService::isReservedUserId($new_user_login)) {
                 throw new Exception($mess["ajxp_conf.43"]);
             }
             AuthService::createUser($new_user_login, $httpVars["new_user_pwd"]);
             $confStorage = ConfService::getConfStorageImpl();
             $newUser = $confStorage->createUserObject($new_user_login);
             $basePath = AuthService::getLoggedUser()->getGroupPath();
             if (empty($basePath)) {
                 $basePath = "/";
             }
             if (!empty($httpVars["group_path"])) {
                 $newUser->setGroupPath(rtrim($basePath, "/") . "/" . ltrim($httpVars["group_path"], "/"));
             } else {
                 $newUser->setGroupPath($basePath);
             }
             $newUser->save("superuser");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.44"], null);
             AJXP_XMLWriter::reloadDataNode("", $new_user_login);
             AJXP_XMLWriter::close();
             break;
         case "change_admin_right":
             $userId = $httpVars["user_id"];
             if (!AuthService::userExists($userId)) {
                 throw new Exception("Invalid user id!");
             }
             $confStorage = ConfService::getConfStorageImpl();
             $user = $confStorage->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $user->setAdmin($httpVars["right_value"] == "1" ? true : false);
             $user->save("superuser");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.45"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "role_update_right":
             if (!isset($httpVars["role_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 break;
             }
             $rId = AJXP_Utils::sanitize($httpVars["role_id"]);
             $role = AuthService::getRole($rId);
             if ($role === false) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"] . "(" . $rId . ")");
                 AJXP_XMLWriter::close();
                 break;
             }
             $role->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM));
             AuthService::updateRole($role);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["role_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "user_update_right":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"]) || !AuthService::userExists($httpVars["user_id"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>";
                 AJXP_XMLWriter::close();
                 return;
             }
             $confStorage = ConfService::getConfStorageImpl();
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             $user = $confStorage->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $user->personalRole->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM));
             $user->save();
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["user_id"], null);
             print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $user->canRead($httpVars["repository_id"]) . "\" write=\"" . $user->canWrite($httpVars["repository_id"]) . "\"/>";
             AJXP_XMLWriter::reloadRepositoryList();
             AJXP_XMLWriter::close();
             return;
             break;
         case "user_update_group":
             $userSelection = new UserSelection();
             $userSelection->initFromHttpVars($httpVars);
             $dir = $httpVars["dir"];
             $dest = $httpVars["dest"];
             if (isset($httpVars["group_path"])) {
                 // API Case
                 $groupPath = $httpVars["group_path"];
             } else {
                 if (strpos($dir, "/data/users", 0) !== 0 || strpos($dest, "/data/users", 0) !== 0) {
                     break;
                 }
                 $groupPath = substr($dest, strlen("/data/users"));
             }
             $confStorage = ConfService::getConfStorageImpl();
             $userId = null;
             $usersMoved = array();
             $basePath = AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getGroupPath() : "/";
             if (empty($basePath)) {
                 $basePath = "/";
             }
             if (!empty($groupPath)) {
                 $targetPath = rtrim($basePath, "/") . "/" . ltrim($groupPath, "/");
             } else {
                 $targetPath = $basePath;
             }
             foreach ($userSelection->getFiles() as $selectedUser) {
                 $userId = basename($selectedUser);
                 if (!AuthService::userExists($userId)) {
                     continue;
                 }
                 $user = $confStorage->createUserObject($userId);
                 if (!AuthService::canAdministrate($user)) {
                     continue;
                 }
                 $user->setGroupPath($targetPath, true);
                 $user->save("superuser");
                 $usersMoved[] = $user->getId();
             }
             AJXP_XMLWriter::header();
             if (count($usersMoved)) {
                 AJXP_XMLWriter::sendMessage(count($usersMoved) . " user(s) successfully moved to " . $targetPath, null);
                 AJXP_XMLWriter::reloadDataNode($dest, $userId);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage(null, "No users moved, there must have been something wrong.");
             }
             AJXP_XMLWriter::close();
             break;
         case "user_add_role":
         case "user_delete_role":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["role_id"]) || !AuthService::userExists($httpVars["user_id"]) || !AuthService::getRole($httpVars["role_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             if ($action == "user_add_role") {
                 $act = "add";
                 $messId = "73";
             } else {
                 $act = "remove";
                 $messId = "74";
             }
             $this->updateUserRole(AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS), $httpVars["role_id"], $act);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . $messId] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             return;
             break;
         case "user_update_role":
             $confStorage = ConfService::getConfStorageImpl();
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $files = $selection->getFiles();
             $detectedRoles = array();
             $roleId = null;
             if (isset($httpVars["role_id"]) && isset($httpVars["update_role_action"])) {
                 $update = $httpVars["update_role_action"];
                 $roleId = $httpVars["role_id"];
                 if (AuthService::getRole($roleId) === false) {
                     throw new Exception("Invalid role id");
                 }
             }
             foreach ($files as $index => $file) {
                 $userId = basename($file);
                 if (isset($update)) {
                     $userObject = $this->updateUserRole($userId, $roleId, $update);
                 } else {
                     $userObject = $confStorage->createUserObject($userId);
                     if (!AuthService::canAdministrate($userObject)) {
                         continue;
                     }
                 }
                 if ($userObject->hasParent()) {
                     unset($files[$index]);
                     continue;
                 }
                 $userRoles = $userObject->getRoles();
                 foreach ($userRoles as $roleIndex => $bool) {
                     if (!isset($detectedRoles[$roleIndex])) {
                         $detectedRoles[$roleIndex] = 0;
                     }
                     if ($bool === true) {
                         $detectedRoles[$roleIndex]++;
                     }
                 }
             }
             $count = count($files);
             AJXP_XMLWriter::header("admin_data");
             print "<user><ajxp_roles>";
             foreach ($detectedRoles as $roleId => $roleCount) {
                 if ($roleCount < $count) {
                     continue;
                 }
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles></user>";
             print "<ajxp_roles>";
             foreach (AuthService::getRolesList(array(), !$this->listSpecialRoles) as $roleId => $roleObject) {
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "save_custom_user_params":
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $custom = $user->getPref("CUSTOM_PARAMS");
             if (!is_array($custom)) {
                 $custom = array();
             }
             $options = $custom;
             $this->parseParameters($httpVars, $options, $userId, false, $custom);
             $custom = $options;
             $user->setPref("CUSTOM_PARAMS", $custom);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "save_repository_user_params":
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $wallet = $user->getPref("AJXP_WALLET");
             if (!is_array($wallet)) {
                 $wallet = array();
             }
             $repoID = $httpVars["repository_id"];
             if (!array_key_exists($repoID, $wallet)) {
                 $wallet[$repoID] = array();
             }
             $options = $wallet[$repoID];
             $existing = $options;
             $this->parseParameters($httpVars, $options, $userId, false, $existing);
             $wallet[$repoID] = $options;
             $user->setPref("AJXP_WALLET", $wallet);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "update_user_pwd":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["user_pwd"]) || !AuthService::userExists($httpVars["user_id"]) || trim($httpVars["user_pwd"]) == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             $user = ConfService::getConfStorageImpl()->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user data for " . $userId);
             }
             $res = AuthService::updatePassword($userId, $httpVars["user_pwd"]);
             AJXP_XMLWriter::header();
             if ($res === true) {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.48"] . $userId, null);
             } else {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.49"] . " : {$res}");
             }
             AJXP_XMLWriter::close();
             break;
         case "save_user_preference":
             if (!isset($httpVars["user_id"]) || !AuthService::userExists($httpVars["user_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $userObject = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $userObject = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($userObject)) {
                 throw new Exception("Cannot update user data for " . $userId);
             }
             $i = 0;
             while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && $userObject == null) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save("user");
                 $i++;
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage("Succesfully saved user preference", null);
             AJXP_XMLWriter::close();
             break;
         case "get_drivers_definition":
             AJXP_XMLWriter::header("drivers", array("allowed" => $currentUserIsGroupAdmin ? "false" : "true"));
             print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("param", "", true));
             AJXP_XMLWriter::close("drivers");
             break;
         case "get_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $count = 0;
             $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => '1'), $count);
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 $repoId = $repo->getUniqueId();
                 $repoLabel = SystemTextEncoding::toUTF8($repo->getDisplay());
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 foreach ($repo->getOptionsDefined() as $optionName) {
                     print "<option name=\"{$optionName}\"/>";
                 }
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "create_repository":
             $repDef = $httpVars;
             $isTemplate = isset($httpVars["sf_checkboxes_active"]);
             unset($repDef["get_action"]);
             unset($repDef["sf_checkboxes_active"]);
             if (isset($httpVars["json_data"])) {
                 $repDef = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
                 $options = $repDef["DRIVER_OPTIONS"];
             } else {
                 $options = array();
                 $this->parseParameters($repDef, $options, null, true);
             }
             if (count($options)) {
                 $repDef["DRIVER_OPTIONS"] = $options;
                 unset($repDef["DRIVER_OPTIONS"]["AJXP_GROUP_PATH_PARAMETER"]);
             }
             if (strstr($repDef["DRIVER"], "ajxp_template_") !== false) {
                 $templateId = substr($repDef["DRIVER"], 14);
                 $templateRepo = ConfService::getRepositoryById($templateId);
                 $newRep = $templateRepo->createTemplateChild($repDef["DISPLAY"], $repDef["DRIVER_OPTIONS"]);
                 if (isset($repDef["AJXP_SLUG"])) {
                     $newRep->setSlug($repDef["AJXP_SLUG"]);
                 }
             } else {
                 if ($currentUserIsGroupAdmin) {
                     throw new Exception("You are not allowed to create a workspace from a driver. Use a template instead.");
                 }
                 $pServ = AJXP_PluginsService::getInstance();
                 $driver = $pServ->getPluginByTypeName("access", $repDef["DRIVER"]);
                 $newRep = ConfService::createRepositoryFromArray(0, $repDef);
                 $testFile = $driver->getBaseDir() . "/test." . $newRep->getAccessType() . "Access.php";
                 if (!$isTemplate && is_file($testFile)) {
                     //chdir(AJXP_TESTS_FOLDER."/plugins");
                     $className = $newRep->getAccessType() . "AccessTest";
                     if (!class_exists($className)) {
                         include $testFile;
                     }
                     $class = new $className();
                     $result = $class->doRepositoryTest($newRep);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 // Apply default metasource if any
                 if ($driver != null && $driver->getConfigs() != null) {
                     $confs = $driver->getConfigs();
                     if (!empty($confs["DEFAULT_METASOURCES"])) {
                         $metaIds = AJXP_Utils::parseCSL($confs["DEFAULT_METASOURCES"]);
                         $metaSourceOptions = array();
                         foreach ($metaIds as $metaID) {
                             $metaPlug = $pServ->getPluginById($metaID);
                             if ($metaPlug == null) {
                                 continue;
                             }
                             $pNodes = $metaPlug->getManifestRawContent("//param[@default]", "nodes");
                             $defaultParams = array();
                             foreach ($pNodes as $domNode) {
                                 $defaultParams[$domNode->getAttribute("name")] = $domNode->getAttribute("default");
                             }
                             $metaSourceOptions[$metaID] = $defaultParams;
                         }
                         $newRep->addOption("META_SOURCES", $metaSourceOptions);
                     }
                 }
             }
             if ($this->repositoryExists($newRep->getDisplay())) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             if ($isTemplate) {
                 $newRep->isTemplate = true;
             }
             if ($currentUserIsGroupAdmin) {
                 $newRep->setGroupPath(AuthService::getLoggedUser()->getGroupPath());
             } else {
                 if (!empty($options["AJXP_GROUP_PATH_PARAMETER"])) {
                     $basePath = "/";
                     if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                         $basePath = AuthService::getLoggedUser()->getGroupPath();
                     }
                     $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($options["AJXP_GROUP_PATH_PARAMETER"], "/"));
                     $newRep->setGroupPath($value);
                 }
             }
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw");
                 $loggedUser->recomputeMergedRole();
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.52"], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "edit_repository":
             $repId = $httpVars["repository_id"];
             $repository = ConfService::getRepositoryById($repId);
             if ($repository == null) {
                 throw new Exception("Cannot find workspace with id {$repId}");
             }
             if (!AuthService::canAdministrate($repository)) {
                 throw new Exception("You are not allowed to edit this workspace!");
             }
             $pServ = AJXP_PluginsService::getInstance();
             $plug = $pServ->getPluginById("access." . $repository->accessType);
             if ($plug == null) {
                 throw new Exception("Cannot find access driver (" . $repository->accessType . ") for workspace!");
             }
             AJXP_XMLWriter::header("admin_data");
             $slug = $repository->getSlug();
             if ($slug == "" && $repository->isWriteable()) {
                 $repository->setSlug();
                 ConfService::replaceRepository($repId, $repository);
             }
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                 $rgp = $repository->getGroupPath();
                 if ($rgp == null) {
                     $rgp = "/";
                 }
                 if (strlen($rgp) < strlen(AuthService::getLoggedUser()->getGroupPath())) {
                     $repository->setWriteable(false);
                 }
             }
             $nested = array();
             $definitions = $plug->getConfigsDefinitions();
             print "<repository index=\"{$repId}\"";
             foreach ($repository as $name => $option) {
                 if (strstr($name, " ") > -1) {
                     continue;
                 }
                 if (!is_array($option)) {
                     if (is_bool($option)) {
                         $option = $option ? "true" : "false";
                     }
                     print " {$name}=\"" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($option)) . "\" ";
                 } else {
                     if (is_array($option)) {
                         $nested[] = $option;
                     }
                 }
             }
             if (count($nested)) {
                 print ">";
                 foreach ($nested as $option) {
                     foreach ($option as $key => $optValue) {
                         if (is_array($optValue) && count($optValue)) {
                             print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>";
                         } else {
                             if (is_object($optValue)) {
                                 print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>";
                             } else {
                                 if (is_bool($optValue)) {
                                     $optValue = $optValue ? "true" : "false";
                                 } else {
                                     if (isset($definitions[$key]) && $definitions[$key]["type"] == "password" && !empty($optValue)) {
                                         $optValue = "__AJXP_VALUE_SET__";
                                     }
                                 }
                                 $optValue = AJXP_Utils::xmlEntities($optValue, true);
                                 print "<param name=\"{$key}\" value=\"{$optValue}\"/>";
                             }
                         }
                     }
                 }
                 // Add SLUG
                 if (!$repository->isTemplate) {
                     print "<param name=\"AJXP_SLUG\" value=\"" . $repository->getSlug() . "\"/>";
                 }
                 if ($repository->getGroupPath() != null) {
                     $basePath = "/";
                     if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                         $basePath = AuthService::getLoggedUser()->getGroupPath();
                     }
                     $groupPath = $repository->getGroupPath();
                     if ($basePath != "/") {
                         $groupPath = substr($repository->getGroupPath(), strlen($basePath));
                     }
                     print "<param name=\"AJXP_GROUP_PATH_PARAMETER\" value=\"" . $groupPath . "\"/>";
                 }
                 print "</repository>";
             } else {
                 print "/>";
             }
             if ($repository->hasParent()) {
                 $parent = ConfService::getRepositoryById($repository->getParentId());
                 if (isset($parent) && $parent->isTemplate) {
                     $parentLabel = $parent->getDisplay();
                     $parentType = $parent->getAccessType();
                     print "<template repository_id=\"" . $repository->getParentId() . "\" repository_label=\"{$parentLabel}\" repository_type=\"{$parentType}\">";
                     foreach ($parent->getOptionsDefined() as $parentOptionName) {
                         print "<option name=\"{$parentOptionName}\"/>";
                     }
                     print "</template>";
                 }
             }
             $manifest = $plug->getManifestRawContent("server_settings/param");
             $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
             print "<ajxpdriver name=\"" . $repository->accessType . "\">{$manifest}</ajxpdriver>";
             print "<metasources>";
             $metas = $pServ->getPluginsByType("metastore");
             $metas = array_merge($metas, $pServ->getPluginsByType("meta"));
             $metas = array_merge($metas, $pServ->getPluginsByType("index"));
             foreach ($metas as $metaPlug) {
                 print "<meta id=\"" . $metaPlug->getId() . "\" label=\"" . AJXP_Utils::xmlEntities($metaPlug->getManifestLabel()) . "\">";
                 $manifest = $metaPlug->getManifestRawContent("server_settings/param");
                 $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
                 print $manifest;
                 print "</meta>";
             }
             print "</metasources>";
             AJXP_XMLWriter::close("admin_data");
             return;
             break;
         case "edit_repository_label":
         case "edit_repository_data":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!$repo->isWriteable()) {
                 throw new Exception("This workspace is not writeable. Please edit directly the conf/bootstrap_repositories.php file.");
             }
             $res = 0;
             if (isset($httpVars["newLabel"])) {
                 $newLabel = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["newLabel"]), AJXP_SANITIZE_HTML);
                 if ($this->repositoryExists($newLabel)) {
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                     AJXP_XMLWriter::close();
                     return;
                 }
                 $repo->setDisplay($newLabel);
                 $res = ConfService::replaceRepository($repId, $repo);
             } else {
                 $options = array();
                 $existing = $repo->getOptionsDefined();
                 $existingValues = array();
                 foreach ($existing as $exK) {
                     $existingValues[$exK] = $repo->getOption($exK, true);
                 }
                 $this->parseParameters($httpVars, $options, null, true, $existingValues);
                 if (count($options)) {
                     foreach ($options as $key => $value) {
                         if ($key == "AJXP_SLUG") {
                             $repo->setSlug($value);
                             continue;
                         } elseif ($key == "AJXP_GROUP_PATH_PARAMETER") {
                             $basePath = "/";
                             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                                 $basePath = AuthService::getLoggedUser()->getGroupPath();
                             }
                             $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($value, "/"));
                             $repo->setGroupPath($value);
                             continue;
                         }
                         $repo->addOption($key, $value);
                     }
                 }
                 if ($repo->getOption("DEFAULT_RIGHTS")) {
                     $gp = $repo->getGroupPath();
                     if (empty($gp) || $gp == "/") {
                         $defRole = AuthService::getRole("ROOT_ROLE");
                     } else {
                         $defRole = AuthService::getRole("AJXP_GRP_" . $gp, true);
                     }
                     if ($defRole !== false) {
                         $defRole->setAcl($repId, $repo->getOption("DEFAULT_RIGHTS"));
                         AuthService::updateRole($defRole);
                     }
                 }
                 if (is_file(AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php")) {
                     chdir(AJXP_TESTS_FOLDER . "/plugins");
                     include AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php";
                     $className = "ajxp_" . $repo->getAccessType();
                     $class = new $className();
                     $result = $class->doRepositoryTest($repo);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 ConfService::replaceRepository($repId, $repo);
             }
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.53"]);
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.54"], null);
                 if (isset($httpVars["newLabel"])) {
                     AJXP_XMLWriter::reloadDataNode("", $repId);
                 }
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "meta_source_add":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceType = AJXP_Utils::sanitize($httpVars["new_meta_source"], AJXP_SANITIZE_ALPHANUM);
             if (isset($httpVars["json_data"])) {
                 $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
             } else {
                 $options = array();
                 $this->parseParameters($httpVars, $options, null, true);
             }
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && isset($repoOptions[$metaSourceType])) {
                 throw new Exception($mess["ajxp_conf.55"]);
             }
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             $repoOptions[$metaSourceType] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.56"], null);
             AJXP_XMLWriter::close();
             break;
         case "meta_source_delete":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && array_key_exists($metaSourceId, $repoOptions)) {
                 unset($repoOptions[$metaSourceId]);
                 uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
                 $repo->addOption("META_SOURCES", $repoOptions);
                 ConfService::replaceRepository($repId, $repo);
             } else {
                 throw new Exception("Cannot find meta source " . $metaSourceId);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.57"], null);
             AJXP_XMLWriter::close();
             break;
         case "meta_source_edit":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $repoOptions = $repo->getOption("META_SOURCES");
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             if (isset($httpVars["json_data"])) {
                 $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
             } else {
                 $options = array();
                 $this->parseParameters($httpVars, $options, null, true);
             }
             if (isset($repoOptions[$metaSourceId])) {
                 $this->mergeExistingParameters($options, $repoOptions[$metaSourceId]);
             }
             $repoOptions[$metaSourceId] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.58"], null);
             AJXP_XMLWriter::close();
             break;
         case "delete":
             // REST API mapping
             if (isset($httpVars["data_type"])) {
                 switch ($httpVars["data_type"]) {
                     case "repository":
                         $httpVars["repository_id"] = basename($httpVars["data_id"]);
                         break;
                     case "role":
                         $httpVars["role_id"] = basename($httpVars["data_id"]);
                         break;
                     case "user":
                         $httpVars["user_id"] = basename($httpVars["data_id"]);
                         break;
                     case "group":
                         $httpVars["group"] = "/data/users" . $httpVars["data_id"];
                         break;
                     default:
                         break;
                 }
                 unset($httpVars["data_type"]);
                 unset($httpVars["data_id"]);
             }
             if (isset($httpVars["repository_id"])) {
                 $repId = $httpVars["repository_id"];
                 $repo = ConfService::getRepositoryById($repId);
                 if (!is_object($repo)) {
                     $res = -1;
                 } else {
                     $res = ConfService::deleteRepository($repId);
                 }
                 AJXP_XMLWriter::header();
                 if ($res == -1) {
                     AJXP_XMLWriter::sendMessage(null, $mess[427]);
                 } else {
                     AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::reloadRepositoryList();
                 }
                 AJXP_XMLWriter::close();
                 return;
             } else {
                 if (isset($httpVars["role_id"])) {
                     $roleId = $httpVars["role_id"];
                     if (AuthService::getRole($roleId) === false) {
                         throw new Exception($mess["ajxp_conf.67"]);
                     }
                     AuthService::deleteRole($roleId);
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage($mess["ajxp_conf.68"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::close();
                 } else {
                     if (isset($httpVars["group"])) {
                         $groupPath = $httpVars["group"];
                         $basePath = substr(AJXP_Utils::forwardSlashDirname($groupPath), strlen("/data/users"));
                         $gName = basename($groupPath);
                         AuthService::deleteGroup($basePath, $gName);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.128"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     } else {
                         if (!isset($httpVars["user_id"]) || $httpVars["user_id"] == "" || AuthService::isReservedUserId($httpVars["user_id"]) || $loggedUser->getId() == $httpVars["user_id"]) {
                             AJXP_XMLWriter::header();
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                             AJXP_XMLWriter::close();
                         }
                         AuthService::deleteUser($httpVars["user_id"]);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     }
                 }
             }
             break;
         case "get_plugin_manifest":
             $ajxpPlugin = AJXP_PluginsService::getInstance()->getPluginById($httpVars["plugin_id"]);
             AJXP_XMLWriter::header("admin_data");
             $fullManifest = $ajxpPlugin->getManifestRawContent("", "xml");
             $xPath = new DOMXPath($fullManifest->ownerDocument);
             $addParams = "";
             $instancesDefinitions = array();
             $pInstNodes = $xPath->query("server_settings/global_param[contains(@type, 'plugin_instance:')]");
             foreach ($pInstNodes as $pInstNode) {
                 $type = $pInstNode->getAttribute("type");
                 $instType = str_replace("plugin_instance:", "", $type);
                 $fieldName = $pInstNode->getAttribute("name");
                 $pInstNode->setAttribute("type", "group_switch:" . $fieldName);
                 $typePlugs = AJXP_PluginsService::getInstance()->getPluginsByType($instType);
                 foreach ($typePlugs as $typePlug) {
                     if ($typePlug->getId() == "auth.multi") {
                         continue;
                     }
                     $checkErrorMessage = "";
                     try {
                         $typePlug->performChecks();
                     } catch (Exception $e) {
                         $checkErrorMessage = " (Warning : " . $e->getMessage() . ")";
                     }
                     $tParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[not(@group_switch_name)]"));
                     $addParams .= '<global_param group_switch_name="' . $fieldName . '" name="instance_name" group_switch_label="' . $typePlug->getManifestLabel() . $checkErrorMessage . '" group_switch_value="' . $typePlug->getId() . '" default="' . $typePlug->getId() . '" type="hidden"/>';
                     $addParams .= str_replace("<param", "<global_param group_switch_name=\"{$fieldName}\" group_switch_label=\"" . $typePlug->getManifestLabel() . $checkErrorMessage . "\" group_switch_value=\"" . $typePlug->getId() . "\" ", $tParams);
                     $addParams .= str_replace("<param", "<global_param", AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[@group_switch_name]")));
                     $addParams .= AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/global_param"));
                     $instancesDefs = $typePlug->getConfigsDefinitions();
                     if (!empty($instancesDefs) && is_array($instancesDefs)) {
                         foreach ($instancesDefs as $defKey => $defData) {
                             $instancesDefinitions[$fieldName . "/" . $defKey] = $defData;
                         }
                     }
                 }
             }
             $allParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($fullManifest->ownerDocument->saveXML($fullManifest));
             $allParams = str_replace('type="plugin_instance:', 'type="group_switch:', $allParams);
             $allParams = str_replace("</server_settings>", $addParams . "</server_settings>", $allParams);
             echo $allParams;
             $definitions = $instancesDefinitions;
             $configsDefs = $ajxpPlugin->getConfigsDefinitions();
             if (is_array($configsDefs)) {
                 $definitions = array_merge($configsDefs, $instancesDefinitions);
             }
             $values = $ajxpPlugin->getConfigs();
             if (!is_array($values)) {
                 $values = array();
             }
             echo "<plugin_settings_values>";
             // First flatten keys
             $flattenedKeys = array();
             foreach ($values as $key => $value) {
                 $type = $definitions[$key]["type"];
                 if ((strpos($type, "group_switch:") === 0 || strpos($type, "plugin_instance:") === 0) && is_array($value)) {
                     $res = array();
                     $this->flattenKeyValues($res, $definitions, $value, $key);
                     $flattenedKeys += $res;
                     // Replace parent key by new flat value
                     $values[$key] = $flattenedKeys[$key];
                 }
             }
             $values += $flattenedKeys;
             foreach ($values as $key => $value) {
                 $attribute = true;
                 $type = $definitions[$key]["type"];
                 if ($type == "array" && is_array($value)) {
                     $value = implode(",", $value);
                 } else {
                     if ($type == "boolean") {
                         $value = $value === true || $value === "true" || $value == 1 ? "true" : "false";
                     } else {
                         if ($type == "textarea") {
                             $attribute = false;
                         } else {
                             if ($type == "password" && !empty($value)) {
                                 $value = "__AJXP_VALUE_SET__";
                             }
                         }
                     }
                 }
                 if ($attribute) {
                     echo "<param name=\"{$key}\" value=\"" . AJXP_Utils::xmlEntities($value) . "\"/>";
                 } else {
                     echo "<param name=\"{$key}\" cdatavalue=\"true\"><![CDATA[" . $value . "]]></param>";
                 }
             }
             if ($ajxpPlugin->getType() != "core") {
                 echo "<param name=\"AJXP_PLUGIN_ENABLED\" value=\"" . ($ajxpPlugin->isEnabled() ? "true" : "false") . "\"/>";
             }
             echo "</plugin_settings_values>";
             echo "<plugin_doc><![CDATA[<p>" . $ajxpPlugin->getPluginInformationHTML("Charles du Jeu", "http://pyd.io/plugins/") . "</p>";
             if (file_exists($ajxpPlugin->getBaseDir() . "/plugin_doc.html")) {
                 echo file_get_contents($ajxpPlugin->getBaseDir() . "/plugin_doc.html");
             }
             echo "]]></plugin_doc>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "run_plugin_action":
             $options = array();
             $this->parseParameters($httpVars, $options, null, true);
             $pluginId = $httpVars["action_plugin_id"];
             if (isset($httpVars["button_key"])) {
                 $options = $options[$httpVars["button_key"]];
             }
             $plugin = AJXP_PluginsService::getInstance()->softLoad($pluginId, $options);
             if (method_exists($plugin, $httpVars["action_plugin_method"])) {
                 try {
                     $res = call_user_func(array($plugin, $httpVars["action_plugin_method"]), $options);
                 } catch (Exception $e) {
                     echo "ERROR:" . $e->getMessage();
                     break;
                 }
                 echo $res;
             } else {
                 echo 'ERROR: Plugin ' . $httpVars["action_plugin_id"] . ' does not implement ' . $httpVars["action_plugin_method"] . ' method!';
             }
             break;
         case "edit_plugin_options":
             $options = array();
             $this->parseParameters($httpVars, $options, null, true);
             $confStorage = ConfService::getConfStorageImpl();
             list($pType, $pName) = explode(".", $httpVars["plugin_id"]);
             $existing = $confStorage->loadPluginConfig($pType, $pName);
             $this->mergeExistingParameters($options, $existing);
             $confStorage->savePluginConfig($httpVars["plugin_id"], $options);
             AJXP_PluginsService::clearPluginsCache();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.97"], null);
             AJXP_XMLWriter::close();
             break;
         case "generate_api_docs":
             PydioSdkGenerator::analyzeRegistry(isset($httpVars["version"]) ? $httpVars["version"] : AJXP_VERSION);
             break;
             // Action for update all Pydio's user from ldap in CLI mode
         // Action for update all Pydio's user from ldap in CLI mode
         case "cli_update_user_list":
             if (php_sapi_name() == "cli") {
                 $progressBar = new AJXP_ProgressBarCLI();
                 $countCallback = array($progressBar, "init");
                 $loopCallback = array($progressBar, "update");
                 AuthService::listUsers("/", null, -1, -1, true, true, $countCallback, $loopCallback);
             }
             break;
         default:
             break;
     }
     return;
 }
Exemplo n.º 19
0
 /**
  * Stats the given path.
  *
  * @param string $path
  * @param mixed $flags
  * @return array
  */
 public function url_stat($path, $flags)
 {
     $realPath = self::initPath($path);
     $stat = @stat($realPath);
     $parts = AJXP_Utils::safeParseUrl($path);
     $repoObject = ConfService::getRepositoryById($parts["host"]);
     AbstractAccessDriver::fixPermissions($stat, $repoObject, array($this, "detectRemoteUserId"));
     return $stat;
 }
Exemplo n.º 20
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     $repo = ConfService::getRepository();
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     if (isset($dir) && $action != "upload") {
         $safeDir = $dir;
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     // FILTER DIR PAGINATION ANCHOR
     if (isset($dir) && strstr($dir, "%23") !== false) {
         $parts = explode("%23", $dir);
         $dir = $parts[0];
         $page = $parts[1];
     }
     if (isset($dest)) {
         $dest = SystemTextEncoding::fromUTF8($dest);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	ONLINE EDIT
         //------------------------------------
         case "edit_record":
             $isNew = false;
             if (isset($record_is_new) && $record_is_new == "true") {
                 $isNew = true;
             }
             $tableName = $_POST["table_name"];
             $pkName = $_POST["pk_name"];
             $query = "";
             $arrValues = array();
             foreach ($_POST as $key => $value) {
                 if (substr($key, 0, strlen("ajxp_mysql_")) == "ajxp_mysql_") {
                     $newKey = substr($key, strlen("ajxp_mysql_"));
                     $arrValues[$newKey] = $value;
                 }
             }
             if ($isNew) {
                 $string = "";
                 $index = 0;
                 foreach ($arrValues as $k => $v) {
                     // CHECK IF AUTO KEY!!!
                     $string .= "'" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'";
                     if ($index < count($arrValues) - 1) {
                         $string .= ",";
                     }
                     $index++;
                 }
                 $query = "INSERT INTO {$tableName} VALUES ({$string})";
             } else {
                 $string = "";
                 $index = 0;
                 foreach ($arrValues as $k => $v) {
                     if ($k == $pkName) {
                         $pkValue = $v;
                     } else {
                         $string .= $k . "='" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'";
                         if ($index < count($arrValues) - 1) {
                             $string .= ",";
                         }
                     }
                     $index++;
                 }
                 $query = "UPDATE {$tableName} SET {$string} WHERE {$pkName}='{$pkValue}'";
             }
             $link = $this->createDbLink();
             $res = $this->execQuery($query);
             $this->closeDbLink($link);
             if (is_a($res, "AJXP_Exception")) {
                 $errorMessage = $res->messageId;
             } else {
                 $logMessage = $query;
                 $reload_file_list = true;
             }
             break;
             //------------------------------------
             //	CHANGE COLUMNS OR CREATE TABLE
             //------------------------------------
         //------------------------------------
         //	CHANGE COLUMNS OR CREATE TABLE
         //------------------------------------
         case "edit_table":
             $link = $this->createDbLink();
             if (isset($httpVars["current_table"])) {
                 if (isset($httpVars["delete_column"])) {
                     $query = "ALTER TABLE " . $httpVars["current_table"] . " DROP COLUMN " . $httpVars["delete_column"];
                     $res = $this->execQuery($query);
                     if (is_a($res, "AJXP_Exception")) {
                         $errorMessage = $res->messageId;
                     } else {
                         $logMessage = $query;
                         $reload_file_list = true;
                     }
                     $this->closeDbLink($link);
                     break;
                 }
                 if (isset($httpVars["add_column"])) {
                     $defString = $this->makeColumnDef($httpVars, "add_field_");
                     $query = "ALTER TABLE " . $httpVars["current_table"] . " ADD COLUMN ({$defString})";
                     if (isset($httpVars["add_field_pk"]) && $httpVars["add_field_pk"] == "1") {
                         $query .= ", ADD PRIMARY KEY (" . $httpVars["add_field_name"] . ")";
                     }
                     if (isset($httpVars["add_field_index"]) && $httpVars["add_field_index"] == "1") {
                         $query .= ", ADD INDEX (" . $httpVars["add_field_name"] . ")";
                     }
                     if (isset($httpVars["add_field_uniq"]) && $httpVars["add_field_uniq"] == "1") {
                         $query .= ", ADD UNIQUE (" . $httpVars["add_field_name"] . ")";
                     }
                     $res = $this->execQuery($query);
                     if (is_a($res, "AJXP_Exception")) {
                         $errorMessage = $res->messageId;
                     } else {
                         $logMessage = $query;
                         $reload_file_list = true;
                     }
                     $this->closeDbLink($link);
                     break;
                 }
             }
             $fields = array("origname", "name", "default", "null", "size", "type", "flags", "pk", "index", "uniq");
             $rows = array();
             foreach ($httpVars as $k => $val) {
                 $split = explode("_", $k);
                 if (count($split) == 3 && $split[0] == "field" && is_numeric($split[2]) && in_array($split[1], $fields)) {
                     if (!isset($rows[intval($split[2])])) {
                         $rows[intval($split[2])] = array();
                     }
                     $rows[intval($split[2])][$split[1]] = $val;
                 } else {
                     if (count($split) == 2 && $split[0] == "field" && in_array($split[1], $fields)) {
                         if (!isset($rows[0])) {
                             $rows[0] = array();
                         }
                         $rows[0][$split[1]] = $val;
                     }
                 }
             }
             if (isset($current_table)) {
                 $qMessage = '';
                 foreach ($rows as $row) {
                     $sizeString = $row["size"] != "" ? "(" . $row["size"] . ")" : "";
                     $defString = $row["default"] != "" ? " DEFAULT " . $row["default"] . "" : "";
                     $query = "ALTER TABLE {$current_table} CHANGE " . $row["origname"] . " " . $row["name"] . " " . $row["type"] . $sizeString . $defString . " " . $row["null"];
                     $res = $this->execQuery(trim($query));
                     if (is_a($res, "AJXP_Exception")) {
                         $errorMessage = $res->messageId;
                         $this->closeDbLink($link);
                         break;
                     } else {
                         $qMessage .= $query;
                         $reload_file_list = true;
                     }
                 }
                 $logMessage = $qMessage;
             } else {
                 if (isset($new_table)) {
                     $fieldsDef = array();
                     $pks = array();
                     $indexes = array();
                     $uniqs = array();
                     foreach ($rows as $index => $row) {
                         $fieldsDef[] = $this->makeColumnDef($row);
                         // Analyse keys
                         if ($row["pk"] == "1") {
                             $pks[] = $row["name"];
                         }
                         if ($row["index"] == "1") {
                             $indexes[] = $row["name"];
                         }
                         if ($row["uniq"] == "1") {
                             $uniqs[] = $row["name"];
                         }
                     }
                     $fieldsDef = implode(",", $fieldsDef);
                     if (count($pks)) {
                         $fieldsDef .= ",PRIMARY KEY (" . implode(",", $pks) . ")";
                     }
                     if (count($indexes)) {
                         $fieldsDef .= ",INDEX (" . implode(",", $indexes) . ")";
                     }
                     if (count($uniqs)) {
                         $fieldsDef .= ",UNIQUE (" . implode(",", $uniqs) . ")";
                     }
                     $query = "CREATE TABLE {$new_table} ({$fieldsDef})";
                     $res = $this->execQuery(trim($query));
                     if (is_a($res, "AJXP_Exception")) {
                         $errorMessage = $res->messageId;
                     } else {
                         $logMessage = $query;
                         $reload_file_list = true;
                         $reload_current_node = true;
                     }
                 }
             }
             $this->closeDbLink($link);
             break;
             //------------------------------------
             //	SUPPRIMER / DELETE
             //------------------------------------
         //------------------------------------
         //	SUPPRIMER / DELETE
         //------------------------------------
         case "delete_table":
         case "delete_record":
             $dir = basename($dir);
             $link = $this->createDbLink();
             if (trim($dir) == "") {
                 // ROOT NODE => DROP TABLES
                 $tables = $selection->getFiles();
                 $query = "DROP TABLE";
                 foreach ($tables as $index => $tableName) {
                     $tables[$index] = basename($tableName);
                 }
                 $query .= " " . implode(",", $tables);
                 $res = $this->execQuery($query);
                 $reload_current_node = true;
             } else {
                 // TABLE NODE => DELETE RECORDS
                 $tableName = $dir;
                 $pks = $selection->getFiles();
                 foreach ($pks as $key => $pkString) {
                     $parts = explode(".", $pkString);
                     array_pop($parts);
                     // remove .pk extension
                     array_shift($parts);
                     // remove record prefix
                     foreach ($parts as $index => $pkPart) {
                         $parts[$index] = str_replace("__", "='", $pkPart) . "'";
                     }
                     $pks[$key] = "(" . implode(" AND ", $parts) . ")";
                 }
                 $query = "DELETE FROM {$tableName} WHERE " . implode(" OR ", $pks);
                 $res = $this->execQuery($query);
             }
             //AJXP_Exception::errorToXml($res);
             if (is_a($res, "AJXP_Exception")) {
                 $errorMessage = $res->messageId;
             } else {
                 $logMessage = $query;
                 $reload_file_list = true;
             }
             $this->closeDbLink($link);
             break;
             //------------------------------------
             //	RENOMMER / RENAME
             //------------------------------------
         //------------------------------------
         //	RENOMMER / RENAME
         //------------------------------------
         case "set_query":
             $query = $httpVars["query"];
             $_SESSION["LAST_SQL_QUERY"] = $query;
             print "<tree store=\"true\"></tree>";
             break;
             //------------------------------------
             //	XML LISTING
             //------------------------------------
         //------------------------------------
         //	XML LISTING
         //------------------------------------
         case "ls":
             if (!isset($dir) || $dir == "/") {
                 $dir = "";
             }
             $searchMode = $fileListMode = $completeMode = false;
             if (isset($mode)) {
                 if ($mode == "search") {
                     $searchMode = true;
                 } else {
                     if ($mode == "file_list") {
                         $fileListMode = true;
                     } else {
                         if ($mode == "complete") {
                             $completeMode = true;
                         }
                     }
                 }
             }
             $link = $this->createDbLink();
             //AJXP_Exception::errorToXml($link);
             if ($dir == "") {
                 AJXP_XMLWriter::header();
                 $tables = $this->listTables();
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist"><column messageString="Table Name" attributeName="ajxp_label" sortType="String"/><column messageString="Byte Size" attributeName="bytesize" sortType="NumberKo"/><column messageString="Count" attributeName="count" sortType="Number"/></columns>');
                 $icon = $mode == "file_list" ? "sql_images/mimes/ICON_SIZE/table_empty.png" : "sql_images/mimes/ICON_SIZE/table_empty_tree.png";
                 foreach ($tables as $tableName) {
                     $size = $this->getSize($tableName);
                     $count = $this->getCount($tableName);
                     print "<tree is_file=\"0\" text=\"{$tableName}\" filename=\"/{$tableName}\" bytesize=\"{$size}\" count=\"{$count}\" icon=\"{$icon}\" ajxp_mime=\"table\" />";
                 }
                 print "<tree is_file=\"0\" text=\"Search Results\" ajxp_node=\"true\" filename=\"/ajxpmysqldriver_searchresults\" bytesize=\"-\" count=\"-\" icon=\"search.png\"/>";
                 AJXP_XMLWriter::close();
             } else {
                 $tableName = basename($dir);
                 if (isset($page)) {
                     $currentPage = $page;
                 } else {
                     $currentPage = 1;
                 }
                 $query = "SELECT * FROM {$tableName}";
                 $searchQuery = false;
                 if ($tableName == "ajxpmysqldriver_searchresults") {
                     if (isset($_SESSION["LAST_SQL_QUERY"])) {
                         $query = $_SESSION["LAST_SQL_QUERY"];
                         $matches = array();
                         if (preg_match("/SELECT [\\S, ]* FROM (\\S*).*/i", $query, $matches) !== false) {
                             $tableName = $matches[1];
                             $searchQuery = true;
                         } else {
                             break;
                         }
                     } else {
                         break;
                     }
                 }
                 if (isset($order_column)) {
                     $query .= " ORDER BY {$order_column} " . strtoupper($order_direction);
                     if (!isset($_SESSION["AJXP_ORDER_DATA"])) {
                         $_SESSION["AJXP_ORDER_DATA"] = array();
                     }
                     $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName] = array("column" => $order_column, "dir" => $order_direction);
                 } else {
                     if (isset($_SESSION["AJXP_ORDER_DATA"])) {
                         if (isset($_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName])) {
                             $order_column = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["column"];
                             $order_direction = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["dir"];
                             $query .= " ORDER BY {$order_column} " . strtoupper($order_direction);
                         }
                     }
                 }
                 try {
                     $result = $this->showRecords($query, $tableName, $currentPage);
                 } catch (AJXP_Exception $ex) {
                     unset($_SESSION["LAST_SQL_QUERY"]);
                     throw $ex;
                 }
                 AJXP_XMLWriter::header();
                 $blobCols = array();
                 $columnsString = '<columns switchDisplayMode="list" switchGridMode="grid">';
                 foreach ($result["COLUMNS"] as $col) {
                     $columnsString .= "<column messageString=\"" . $col["NAME"] . "\" attributeName=\"" . $col["NAME"] . "\" field_name=\"" . $col["NAME"] . "\" field_type=\"" . $col["TYPE"] . "\" field_size=\"" . $col["LENGTH"] . "\" field_flags=\"" . $this->cleanFlagString($col["FLAGS"]) . "\" field_pk=\"" . (preg_match("/primary/", $col["FLAGS"]) ? "1" : "0") . "\" field_null=\"" . (preg_match("/not_null/", $col["FLAGS"]) ? "NOT_NULL" : "NULL") . "\" sortType=\"" . $this->sqlTypeToSortType($col["TYPE"]) . "\" field_default=\"" . $col["DEFAULT"] . "\"/>";
                     if (stristr($col["TYPE"], "blob") !== false && ($col["FLAGS"] != "" && stristr($col["FLAGS"], "binary"))) {
                         $blobCols[] = $col["NAME"];
                     }
                 }
                 $columnsString .= '</columns>';
                 AJXP_XMLWriter::sendFilesListComponentConfig($columnsString);
                 //print '<pagination total="'.$result["TOTAL_PAGES"].'" current="'.$currentPage.'" remote_order="true" currentOrderCol="'.$order_column.'" currentOrderDir="'.$order_direction.'"/>';
                 if ($result["TOTAL_PAGES"] > 1) {
                     AJXP_XMLWriter::renderPaginationData($count, $currentPage, $result["TOTAL_PAGES"]);
                 }
                 foreach ($result["ROWS"] as $arbitIndex => $row) {
                     print '<tree ';
                     $pkString = "";
                     foreach ($row as $key => $value) {
                         if (in_array($key, $blobCols)) {
                             $sizeStr = " - NULL";
                             if (strlen($value)) {
                                 $sizeStr = " - " . AJXP_Utils::roundSize(strlen($value));
                             }
                             print "{$key}=\"BLOB{$sizeStr}\" ";
                         } else {
                             $value = str_replace("\"", "", $value);
                             $value = AJXP_Utils::xmlEntities($value);
                             print $key . '="' . SystemTextEncoding::toUTF8($value) . '" ';
                             if ($result["HAS_PK"] > 0) {
                                 if (in_array($key, $result["PK_FIELDS"])) {
                                     $pkString .= $key . "__" . $value . ".";
                                 }
                             }
                         }
                     }
                     if ($result["HAS_PK"] > 0) {
                         print 'filename="record.' . $pkString . 'pk" ';
                         print 'is_file="1" ajxp_mime="pk"/>';
                     } else {
                         print 'filename="record_' . $arbitIndex . '.no_pk" ';
                         print 'is_file="1" ajxp_mime="row"/>';
                     }
                 }
                 AJXP_XMLWriter::close();
             }
             $this->closeDbLink($link);
             exit(1);
             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);
     }
     if (isset($reload_current_node) && $reload_current_node == "true" || isset($reload_file_list)) {
         $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", "", false);
     }
     return $xmlBuffer;
 }
Exemplo n.º 21
0
 /**
  * @param array $httpVars
  * @param bool $update
  * @return Repository
  * @throws Exception
  */
 protected function createOrLoadSharedRepository($httpVars, &$update)
 {
     if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") {
         $mess = ConfService::getMessages();
         throw new Exception($mess["349"]);
     }
     if (isset($httpVars["repository_id"])) {
         $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]);
         $update = true;
     }
     // CHECK REPO DOES NOT ALREADY EXISTS WITH SAME LABEL
     $label = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_label"]), AJXP_SANITIZE_HTML);
     $description = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_description"]), AJXP_SANITIZE_HTML);
     $exists = $this->checkRepoWithSameLabel($label, isset($editingRepo) ? $editingRepo : null);
     if ($exists) {
         $mess = ConfService::getMessages();
         throw new Exception($mess["share_center.352"]);
     }
     $loggedUser = AuthService::getLoggedUser();
     if (isset($editingRepo)) {
         $this->getShareStore()->testUserCanEditShare($editingRepo->getOwner(), $editingRepo->options);
         $newRepo = $editingRepo;
         $replace = false;
         if ($editingRepo->getDisplay() != $label) {
             $newRepo->setDisplay($label);
             $replace = true;
         }
         if ($editingRepo->getDescription() != $description) {
             $newRepo->setDescription($description);
             $replace = true;
         }
         $newScope = isset($httpVars["share_scope"]) && $httpVars["share_scope"] == "public" ? "public" : "private";
         $oldScope = $editingRepo->getOption("SHARE_ACCESS");
         $currentOwner = $editingRepo->getOwner();
         if ($newScope != $oldScope && $currentOwner != AuthService::getLoggedUser()->getId()) {
             $mess = ConfService::getMessages();
             throw new Exception($mess["share_center.224"]);
         }
         if ($newScope !== $oldScope) {
             $editingRepo->addOption("SHARE_ACCESS", $newScope);
             $replace = true;
         }
         if (isset($httpVars["transfer_owner"])) {
             $newOwner = $httpVars["transfer_owner"];
             if ($newOwner != $currentOwner && $currentOwner != AuthService::getLoggedUser()->getId()) {
                 $mess = ConfService::getMessages();
                 throw new Exception($mess["share_center.224"]);
             }
             $editingRepo->setOwnerData($editingRepo->getParentId(), $newOwner, $editingRepo->getUniqueUser());
             $replace = true;
         }
         if ($replace) {
             ConfService::replaceRepository($newRepo->getId(), $newRepo);
         }
     } else {
         $options = $this->accessDriver->makeSharedRepositoryOptions($httpVars, $this->repository);
         // TMP TESTS
         $options["SHARE_ACCESS"] = $httpVars["share_scope"];
         $newRepo = $this->repository->createSharedChild($label, $options, $this->repository->getId(), $loggedUser->getId(), null);
         $gPath = $loggedUser->getGroupPath();
         if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
             $newRepo->setGroupPath($gPath);
         }
         $newRepo->setDescription($description);
         // Smells like dirty hack!
         $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
         if (isset($httpVars["filter_nodes"])) {
             $newRepo->setContentFilter(new ContentFilter($httpVars["filter_nodes"]));
         }
         ConfService::addRepository($newRepo);
     }
     return $newRepo;
 }
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $loggedUser = AuthService::getLoggedUser();
     if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) {
         return;
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("data" => array("LABEL" => $mess["ajxp_conf.110"], "ICON" => "user.png", "CHILDREN" => array("repositories" => array("LABEL" => $mess["ajxp_conf.3"], "ICON" => "hdd_external_unmount.png", "LIST" => "listRepositories"), "users" => array("LABEL" => $mess["ajxp_conf.2"], "ICON" => "user.png", "LIST" => "listUsers"), "roles" => array("LABEL" => $mess["ajxp_conf.69"], "ICON" => "yast_kuser.png", "LIST" => "listRoles"))), "config" => array("LABEL" => $mess["ajxp_conf.109"], "ICON" => "preferences_desktop.png", "CHILDREN" => array("core" => array("LABEL" => $mess["ajxp_conf.98"], "ICON" => "preferences_desktop.png", "LIST" => "listPlugins"), "plugins" => array("LABEL" => $mess["ajxp_conf.99"], "ICON" => "folder_development.png", "LIST" => "listPlugins"))), "admin" => array("LABEL" => $mess["ajxp_conf.111"], "ICON" => "toggle_log.png", "CHILDREN" => array("logs" => array("LABEL" => $mess["ajxp_conf.4"], "ICON" => "toggle_log.png", "LIST" => "listLogFiles"), "files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png", "LIST" => "listSharedFiles"), "diagnostic" => array("LABEL" => $mess["ajxp_conf.5"], "ICON" => "susehelpcenter.png", "LIST" => "printDiagnostic"))));
             AJXP_Controller::applyHook("ajxp_conf.list_config_nodes", array(&$rootNodes));
             $dir = trim(AJXP_Utils::decodeSecureMagic(isset($httpVars["dir"]) ? $httpVars["dir"] : ""), " /");
             if ($dir != "") {
                 $splits = explode("/", $dir);
                 $root = array_shift($splits);
                 if (count($splits)) {
                     $child = $splits[0];
                     if (strstr(urldecode($child), "#") !== false) {
                         list($child, $hash) = explode("#", urldecode($child));
                     }
                     if (isset($rootNodes[$root]["CHILDREN"][$child])) {
                         $callback = $rootNodes[$root]["CHILDREN"][$child]["LIST"];
                         if (is_string($callback) && method_exists($this, $callback)) {
                             AJXP_XMLWriter::header();
                             call_user_func(array($this, $callback), implode("/", $splits), $root, $hash);
                             AJXP_XMLWriter::close();
                         } else {
                             if (is_array($callback)) {
                                 call_user_func($callback, implode("/", $splits), $root, $hash);
                             }
                         }
                         return;
                     }
                 } else {
                     $parentName = "/" . $root . "/";
                     $nodes = $rootNodes[$root]["CHILDREN"];
                 }
             } else {
                 $parentName = "/";
                 $nodes = $rootNodes;
             }
             if (isset($nodes)) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.1" attributeName="ajxp_label" sortType="String"/></columns>');
                 foreach ($nodes as $key => $data) {
                     print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '"/>';
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             return;
             break;
         case "create_role":
             $roleId = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["role_id"]), AJXP_SANITIZE_HTML_STRICT);
             if (!strlen($roleId)) {
                 throw new Exception($mess[349]);
             }
             if (AuthService::getRole($roleId) !== false) {
                 throw new Exception($mess["ajxp_conf.65"]);
             }
             AuthService::updateRole(new AjxpRole($roleId));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null);
             AJXP_XMLWriter::reloadDataNode("", $httpVars["role_id"]);
             AJXP_XMLWriter::close();
             break;
         case "edit_role":
             $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]);
             $role = AuthService::getRole($roleId);
             if ($role === false) {
                 throw new Exception("Cant find role! ");
             }
             AJXP_XMLWriter::header("admin_data");
             print AJXP_XMLWriter::writeRoleRepositoriesData($role);
             AJXP_XMLWriter::close("admin_data");
             break;
         case "update_role_right":
             if (!isset($httpVars["role_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 print "<update_checkboxes user_id=\"" . $httpVars["role_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>";
                 AJXP_XMLWriter::close();
                 return;
             }
             $role = AuthService::getRole($httpVars["role_id"]);
             if ($role === false) {
                 throw new Exception("Cant find role!");
             }
             $role->setRight($httpVars["repository_id"], $httpVars["right"]);
             AuthService::updateRole($role);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.64"] . $httpVars["role_id"], null);
             print "<update_checkboxes user_id=\"" . $httpVars["role_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $role->canRead($httpVars["repository_id"]) . "\" write=\"" . $role->canWrite($httpVars["repository_id"]) . "\"/>";
             //AJXP_XMLWriter::reloadRepositoryList();
             AJXP_XMLWriter::close();
             break;
         case "update_role_actions":
             if (!isset($httpVars["role_id"]) || !isset($httpVars["disabled_actions"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $role = AuthService::getRole($httpVars["role_id"]);
             if ($role === false) {
                 throw new Exception("Cant find role!");
             }
             $actions = explode(",", $httpVars["disabled_actions"]);
             // Clear and reload actions
             foreach ($role->getSpecificActionsRights("ajxp.all") as $actName => $actValue) {
                 $role->setSpecificActionRight("ajxp.all", $actName, true);
             }
             foreach ($actions as $action) {
                 if (($action = AJXP_Utils::sanitize($action, AJXP_SANITIZE_ALPHANUM)) == "") {
                     continue;
                 }
                 $role->setSpecificActionRight("ajxp.all", $action, false);
             }
             AuthService::updateRole($role);
             AJXP_XMLWriter::header("admin_data");
             print AJXP_XMLWriter::writeRoleRepositoriesData($role);
             AJXP_XMLWriter::close("admin_data");
             break;
         case "update_role_default":
             if (!isset($httpVars["role_id"]) || !isset($httpVars["default_value"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $role = AuthService::getRole($httpVars["role_id"]);
             if ($role === false) {
                 throw new Exception("Cannot find role!");
             }
             $role->setDefault($httpVars["default_value"] == "true");
             AuthService::updateRole($role);
             AJXP_XMLWriter::header("admin_data");
             print AJXP_XMLWriter::writeRoleRepositoriesData($role);
             AJXP_XMLWriter::close("admin_data");
             break;
         case "get_custom_params":
             $confStorage = ConfService::getConfStorageImpl();
             AJXP_XMLWriter::header("admin_data");
             $confDriver = ConfService::getConfStorageImpl();
             $customData = $confDriver->options['CUSTOM_DATA'];
             if (is_array($customData) && count($customData) > 0) {
                 print "<custom_data>";
                 foreach ($customData as $custName => $custValue) {
                     print "<param name=\"{$custName}\" type=\"string\" label=\"{$custValue}\" description=\"\" value=\"\"/>";
                 }
                 print "</custom_data>";
             }
             AJXP_XMLWriter::close("admin_data");
             break;
         case "edit_user":
             $confStorage = ConfService::getConfStorageImpl();
             $userId = $httpVars["user_id"];
             if (!AuthService::userExists($userId)) {
                 throw new Exception("Invalid user id!");
             }
             $userObject = $confStorage->createUserObject($userId);
             //print_r($userObject);
             AJXP_XMLWriter::header("admin_data");
             AJXP_XMLWriter::sendUserData($userObject, true);
             // Add CUSTOM USER DATA
             $confDriver = ConfService::getConfStorageImpl();
             $customData = $confDriver->options['CUSTOM_DATA'];
             if (is_array($customData) && count($customData) > 0) {
                 $userCustom = $userObject->getPref("CUSTOM_PARAMS");
                 print "<custom_data>";
                 foreach ($customData as $custName => $custValue) {
                     $value = isset($userCustom[$custName]) ? $userCustom[$custName] : '';
                     print "<param name=\"{$custName}\" type=\"string\" label=\"{$custValue}\" description=\"\" value=\"{$value}\"/>";
                 }
                 print "</custom_data>";
             }
             // Add WALLET DATA : DEFINITIONS AND VALUES
             print "<drivers>";
             print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("user_param"));
             print "</drivers>";
             $wallet = $userObject->getPref("AJXP_WALLET");
             if (is_array($wallet) && count($wallet) > 0) {
                 print "<user_wallet>";
                 foreach ($wallet as $repoId => $options) {
                     foreach ($options as $optName => $optValue) {
                         print "<wallet_data repo_id=\"{$repoId}\" option_name=\"{$optName}\" option_value=\"{$optValue}\"/>";
                     }
                 }
                 print "</user_wallet>";
             }
             $editPass = $userId != "guest" ? "1" : "0";
             $authDriver = ConfService::getAuthDriverImpl();
             if (!$authDriver->passwordsEditable()) {
                 $editPass = "******";
             }
             print "<edit_options edit_pass=\"" . $editPass . "\" edit_admin_right=\"" . ($userId != "guest" && $userId != $loggedUser->getId() ? "1" : "0") . "\" edit_delete=\"" . ($userId != "guest" && $userId != $loggedUser->getId() && $authDriver->usersEditable() ? "1" : "0") . "\"/>";
             print "<ajxp_roles>";
             foreach (AuthService::getRolesList() as $roleId => $roleObject) {
                 print "<role id=\"" . AJXP_Utils::xmlEntities($roleId) . "\"/>";
             }
             print "</ajxp_roles>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "create_user":
             if (!isset($httpVars["new_user_login"]) || $httpVars["new_user_login"] == "" || !isset($httpVars["new_user_pwd"]) || $httpVars["new_user_pwd"] == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $new_user_login = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["new_user_login"]), AJXP_SANITIZE_EMAILCHARS);
             if (AuthService::userExists($new_user_login) || AuthService::isReservedUserId($new_user_login)) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.43"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $confStorage = ConfService::getConfStorageImpl();
             $newUser = $confStorage->createUserObject($new_user_login);
             $customData = array();
             $this->parseParameters($httpVars, $customData);
             if (is_array($customData) && count($customData) > 0) {
                 $newUser->setPref("CUSTOM_PARAMS", $customData);
             }
             $newUser->save("superuser");
             AuthService::createUser($new_user_login, $httpVars["new_user_pwd"]);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.44"], null);
             AJXP_XMLWriter::reloadDataNode("", $new_user_login);
             AJXP_XMLWriter::close();
             break;
         case "change_admin_right":
             $userId = $httpVars["user_id"];
             if (!AuthService::userExists($userId)) {
                 throw new Exception("Invalid user id!");
             }
             $confStorage = ConfService::getConfStorageImpl();
             $user = $confStorage->createUserObject($userId);
             $user->setAdmin($httpVars["right_value"] == "1" ? true : false);
             $user->save("superuser");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.45"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "update_user_right":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"]) || !AuthService::userExists($httpVars["user_id"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>";
                 AJXP_XMLWriter::close();
                 return;
             }
             $confStorage = ConfService::getConfStorageImpl();
             $user = $confStorage->createUserObject($httpVars["user_id"]);
             $user->setRight(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM));
             $user->save();
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["user_id"], null);
             print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $user->canRead($httpVars["repository_id"]) . "\" write=\"" . $user->canWrite($httpVars["repository_id"]) . "\"/>";
             AJXP_XMLWriter::reloadRepositoryList();
             AJXP_XMLWriter::close();
             return;
             break;
         case "user_add_role":
         case "user_delete_role":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["role_id"]) || !AuthService::userExists($httpVars["user_id"]) || !AuthService::getRole($httpVars["role_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             if ($action == "user_add_role") {
                 $act = "add";
                 $messId = "73";
             } else {
                 $act = "remove";
                 $messId = "74";
             }
             $this->updateUserRole($httpVars["user_id"], $httpVars["role_id"], $act);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . $messId] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             return;
             break;
         case "batch_users_roles":
             $confStorage = ConfService::getConfStorageImpl();
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $files = $selection->getFiles();
             $detectedRoles = array();
             if (isset($httpVars["role_id"]) && isset($httpVars["update_role_action"])) {
                 $update = $httpVars["update_role_action"];
                 $roleId = $httpVars["role_id"];
                 if (AuthService::getRole($roleId) === false) {
                     throw new Exception("Invalid role id");
                 }
             }
             foreach ($files as $index => $file) {
                 $userId = basename($file);
                 if (isset($update)) {
                     $userObject = $this->updateUserRole($userId, $roleId, $update);
                 } else {
                     $userObject = $confStorage->createUserObject($userId);
                 }
                 if ($userObject->hasParent()) {
                     unset($files[$index]);
                     continue;
                 }
                 $userRoles = $userObject->getRoles();
                 foreach ($userRoles as $roleIndex => $bool) {
                     if (!isset($detectedRoles[$roleIndex])) {
                         $detectedRoles[$roleIndex] = 0;
                     }
                     if ($bool === true) {
                         $detectedRoles[$roleIndex]++;
                     }
                 }
             }
             $count = count($files);
             AJXP_XMLWriter::header("admin_data");
             print "<user><ajxp_roles>";
             foreach ($detectedRoles as $roleId => $roleCount) {
                 if ($roleCount < $count) {
                     continue;
                 }
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles></user>";
             print "<ajxp_roles>";
             foreach (AuthService::getRolesList() as $roleId => $roleObject) {
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "save_custom_user_params":
             $userId = $httpVars["user_id"];
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             $custom = $user->getPref("CUSTOM_PARAMS");
             if (!is_array($custom)) {
                 $custom = array();
             }
             $options = $custom;
             $this->parseParameters($httpVars, $options, $userId);
             $custom = $options;
             $user->setPref("CUSTOM_PARAMS", $custom);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "save_repository_user_params":
             $userId = $httpVars["user_id"];
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             $wallet = $user->getPref("AJXP_WALLET");
             if (!is_array($wallet)) {
                 $wallet = array();
             }
             $repoID = $httpVars["repository_id"];
             if (!array_key_exists($repoID, $wallet)) {
                 $wallet[$repoID] = array();
             }
             $options = $wallet[$repoID];
             $this->parseParameters($httpVars, $options, $userId);
             $wallet[$repoID] = $options;
             $user->setPref("AJXP_WALLET", $wallet);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "update_user_pwd":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["user_pwd"]) || !AuthService::userExists($httpVars["user_id"]) || trim($httpVars["user_pwd"]) == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $res = AuthService::updatePassword($httpVars["user_id"], $httpVars["user_pwd"]);
             AJXP_XMLWriter::header();
             if ($res === true) {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.48"] . $httpVars["user_id"], null);
             } else {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.49"] . " : {$res}");
             }
             AJXP_XMLWriter::close();
             break;
         case "save_user_preference":
             if (!isset($httpVars["user_id"]) || !AuthService::userExists($httpVars["user_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             $userId = $httpVars["user_id"];
             if ($userId == $loggedUser->getId()) {
                 $userObject = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $userObject = $confStorage->createUserObject($userId);
             }
             $i = 0;
             while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && $userObject == null) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save("user");
                 $i++;
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage("Succesfully saved user preference", null);
             AJXP_XMLWriter::close();
             break;
         case "get_drivers_definition":
             AJXP_XMLWriter::header("drivers");
             print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("param", "", true));
             AJXP_XMLWriter::close("drivers");
             break;
         case "get_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $repositories = ConfService::getRepositoriesList();
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 $repoId = $repo->getUniqueId();
                 $repoLabel = $repo->getDisplay();
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 foreach ($repo->getOptionsDefined() as $optionName) {
                     print "<option name=\"{$optionName}\"/>";
                 }
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "create_repository":
             $options = array();
             $repDef = $httpVars;
             $isTemplate = isset($httpVars["sf_checkboxes_active"]);
             unset($repDef["get_action"]);
             unset($repDef["sf_checkboxes_active"]);
             $this->parseParameters($repDef, $options);
             if (count($options)) {
                 $repDef["DRIVER_OPTIONS"] = $options;
             }
             if (strstr($repDef["DRIVER"], "ajxp_template_") !== false) {
                 $templateId = substr($repDef["DRIVER"], 14);
                 $templateRepo = ConfService::getRepositoryById($templateId);
                 $newRep = $templateRepo->createTemplateChild($repDef["DISPLAY"], $repDef["DRIVER_OPTIONS"]);
             } else {
                 $pServ = AJXP_PluginsService::getInstance();
                 $driver = $pServ->getPluginByTypeName("access", $repDef["DRIVER"]);
                 $newRep = ConfService::createRepositoryFromArray(0, $repDef);
                 $testFile = $driver->getBaseDir() . "/test." . $newRep->getAccessType() . "Access.php";
                 if (!$isTemplate && is_file($testFile)) {
                     //chdir(AJXP_TESTS_FOLDER."/plugins");
                     include $testFile;
                     $className = $newRep->getAccessType() . "AccessTest";
                     $class = new $className();
                     $result = $class->doRepositoryTest($newRep);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 // Apply default metasource if any
                 if ($driver != null && $driver->getConfigs() != null) {
                     $confs = $driver->getConfigs();
                     if (!empty($confs["DEFAULT_METASOURCES"])) {
                         $metaIds = AJXP_Utils::parseCSL($confs["DEFAULT_METASOURCES"]);
                         $metaSourceOptions = array();
                         foreach ($metaIds as $metaID) {
                             $metaPlug = $pServ->getPluginById($metaID);
                             if ($metaPlug == null) {
                                 continue;
                             }
                             $pNodes = $metaPlug->getManifestRawContent("//param[@default]", "nodes");
                             $defaultParams = array();
                             foreach ($pNodes as $domNode) {
                                 $defaultParams[$domNode->getAttribute("name")] = $domNode->getAttribute("default");
                             }
                             $metaSourceOptions[$metaID] = $defaultParams;
                         }
                         $newRep->addOption("META_SOURCES", $metaSourceOptions);
                     }
                 }
             }
             if ($this->repositoryExists($newRep->getDisplay())) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             if ($isTemplate) {
                 $newRep->isTemplate = true;
             }
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 $loggedUser->setRight($newRep->getUniqueId(), "rw");
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.52"], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "edit_repository":
             $repId = $httpVars["repository_id"];
             $repList = ConfService::getRootDirsList();
             //print_r($repList);
             if (!isset($repList[$repId])) {
                 throw new Exception("Cannot find repository with id {$repId}");
             }
             $repository = $repList[$repId];
             $pServ = AJXP_PluginsService::getInstance();
             $plug = $pServ->getPluginById("access." . $repository->accessType);
             if ($plug == null) {
                 throw new Exception("Cannot find access driver (" . $repository->accessType . ") for repository!");
             }
             AJXP_XMLWriter::header("admin_data");
             $slug = $repository->getSlug();
             if ($slug == "" && $repository->isWriteable()) {
                 $repository->setSlug();
                 ConfService::replaceRepository($repId, $repository);
             }
             $nested = array();
             print "<repository index=\"{$repId}\"";
             foreach ($repository as $name => $option) {
                 if (strstr($name, " ") > -1) {
                     continue;
                 }
                 if (!is_array($option)) {
                     if (is_bool($option)) {
                         $option = $option ? "true" : "false";
                     }
                     print " {$name}=\"" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($option)) . "\" ";
                 } else {
                     if (is_array($option)) {
                         $nested[] = $option;
                     }
                 }
             }
             if (count($nested)) {
                 print ">";
                 foreach ($nested as $option) {
                     foreach ($option as $key => $optValue) {
                         if (is_array($optValue) && count($optValue)) {
                             print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>";
                         } else {
                             if (is_bool($optValue)) {
                                 $optValue = $optValue ? "true" : "false";
                             }
                             print "<param name=\"{$key}\" value=\"{$optValue}\"/>";
                         }
                     }
                 }
                 // Add SLUG
                 if (!$repository->isTemplate) {
                     print "<param name=\"AJXP_SLUG\" value=\"" . $repository->getSlug() . "\"/>";
                 }
                 print "</repository>";
             } else {
                 print "/>";
             }
             if ($repository->hasParent()) {
                 $parent = ConfService::getRepositoryById($repository->getParentId());
                 if (isset($parent) && $parent->isTemplate) {
                     $parentLabel = $parent->getDisplay();
                     $parentType = $parent->getAccessType();
                     print "<template repository_id=\"" . $repository->getParentId() . "\" repository_label=\"{$parentLabel}\" repository_type=\"{$parentType}\">";
                     foreach ($parent->getOptionsDefined() as $parentOptionName) {
                         print "<option name=\"{$parentOptionName}\"/>";
                     }
                     print "</template>";
                 }
             }
             $manifest = $plug->getManifestRawContent("server_settings/param");
             $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
             print "<ajxpdriver name=\"" . $repository->accessType . "\">{$manifest}</ajxpdriver>";
             print "<metasources>";
             $metas = $pServ->getPluginsByType("metastore");
             $metas = array_merge($metas, $pServ->getPluginsByType("meta"));
             $metas = array_merge($metas, $pServ->getPluginsByType("index"));
             foreach ($metas as $metaPlug) {
                 print "<meta id=\"" . $metaPlug->getId() . "\" label=\"" . AJXP_Utils::xmlEntities($metaPlug->getManifestLabel()) . "\">";
                 $manifest = $metaPlug->getManifestRawContent("server_settings/param");
                 $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
                 print $manifest;
                 print "</meta>";
             }
             print "</metasources>";
             AJXP_XMLWriter::close("admin_data");
             return;
             break;
         case "edit_repository_label":
         case "edit_repository_data":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             $res = 0;
             if (isset($httpVars["newLabel"])) {
                 $newLabel = AJXP_Utils::decodeSecureMagic($httpVars["newLabel"]);
                 if ($this->repositoryExists($newLabel)) {
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                     AJXP_XMLWriter::close();
                     return;
                 }
                 $repo->setDisplay($newLabel);
                 $res = ConfService::replaceRepository($repId, $repo);
             } else {
                 $options = array();
                 $this->parseParameters($httpVars, $options);
                 if (count($options)) {
                     foreach ($options as $key => $value) {
                         if ($key == "AJXP_SLUG") {
                             $repo->setSlug($value);
                             continue;
                         }
                         $repo->addOption($key, $value);
                     }
                 }
                 if (is_file(AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php")) {
                     chdir(AJXP_TESTS_FOLDER . "/plugins");
                     include AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php";
                     $className = "ajxp_" . $repo->getAccessType();
                     $class = new $className();
                     $result = $class->doRepositoryTest($repo);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 ConfService::replaceRepository($repId, $repo);
             }
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.53"]);
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.54"], null);
                 AJXP_XMLWriter::reloadDataNode("", isset($httpVars["newLabel"]) ? $repId : false);
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "add_meta_source":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid repository id! {$repId}");
             }
             $metaSourceType = AJXP_Utils::sanitize($httpVars["new_meta_source"], AJXP_SANITIZE_ALPHANUM);
             $options = array();
             $this->parseParameters($httpVars, $options);
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && isset($repoOptions[$metaSourceType])) {
                 throw new Exception($mess["ajxp_conf.55"]);
             }
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             $repoOptions[$metaSourceType] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.56"], null);
             AJXP_XMLWriter::close();
             break;
         case "delete_meta_source":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid repository id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && array_key_exists($metaSourceId, $repoOptions)) {
                 unset($repoOptions[$metaSourceId]);
                 uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
                 $repo->addOption("META_SOURCES", $repoOptions);
                 ConfService::replaceRepository($repId, $repo);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.57"], null);
             AJXP_XMLWriter::close();
             break;
         case "edit_meta_source":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid repository id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $options = array();
             $this->parseParameters($httpVars, $options);
             $repoOptions = $repo->getOption("META_SOURCES");
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             $repoOptions[$metaSourceId] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.58"], null);
             AJXP_XMLWriter::close();
             break;
         case "delete":
             if (isset($httpVars["repository_id"])) {
                 $repId = $httpVars["repository_id"];
                 $res = ConfService::deleteRepository($repId);
                 AJXP_XMLWriter::header();
                 if ($res == -1) {
                     AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]);
                 } else {
                     AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::reloadRepositoryList();
                 }
                 AJXP_XMLWriter::close();
                 return;
             } else {
                 if (isset($httpVars["shared_file"])) {
                     AJXP_XMLWriter::header();
                     $element = basename($httpVars["shared_file"]);
                     $dlFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER");
                     $publicletData = $this->loadPublicletData($dlFolder . "/" . $element . ".php");
                     unlink($dlFolder . "/" . $element . ".php");
                     AJXP_XMLWriter::sendMessage($mess["ajxp_shared.13"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::close();
                 } else {
                     if (isset($httpVars["role_id"])) {
                         $roleId = $httpVars["role_id"];
                         if (AuthService::getRole($roleId) === false) {
                             throw new Exception($mess["ajxp_conf.67"]);
                         }
                         AuthService::deleteRole($roleId);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     } else {
                         if (!isset($httpVars["user_id"]) || $httpVars["user_id"] == "" || AuthService::isReservedUserId($httpVars["user_id"]) || $loggedUser->getId() == $httpVars["user_id"]) {
                             AJXP_XMLWriter::header();
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                             AJXP_XMLWriter::close();
                         }
                         $res = AuthService::deleteUser($httpVars["user_id"]);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     }
                 }
             }
             break;
         case "clear_expired":
             $deleted = $this->clearExpiredFiles();
             AJXP_XMLWriter::header();
             if (count($deleted)) {
                 AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null);
             }
             AJXP_XMLWriter::close();
             break;
         case "get_plugin_manifest":
             $ajxpPlugin = AJXP_PluginsService::getInstance()->getPluginById($httpVars["plugin_id"]);
             AJXP_XMLWriter::header("admin_data");
             echo AJXP_XMLWriter::replaceAjxpXmlKeywords($ajxpPlugin->getManifestRawContent());
             $definitions = $ajxpPlugin->getConfigsDefinitions();
             $values = $ajxpPlugin->getConfigs();
             if (!is_array($values)) {
                 $values = array();
             }
             echo "<plugin_settings_values>";
             foreach ($values as $key => $value) {
                 if ($definitions[$key]["type"] == "array" && is_array($value)) {
                     $value = implode(",", $value);
                 } else {
                     if ($definitions[$key]["type"] == "boolean") {
                         $value = $value === true || $value === "true" || $value == 1 ? "true" : "false";
                     } else {
                         if ($definitions[$key]["type"] == "textarea") {
                             //$value = str_replace("\\n", "\n", $value);
                         }
                     }
                 }
                 echo "<param name=\"{$key}\" value=\"" . AJXP_Utils::xmlEntities($value) . "\"/>";
             }
             if ($ajxpPlugin->getType() != "core") {
                 echo "<param name=\"AJXP_PLUGIN_ENABLED\" value=\"" . ($ajxpPlugin->isEnabled() ? "true" : "false") . "\"/>";
             }
             echo "</plugin_settings_values>";
             echo "<plugin_doc><![CDATA[<p>" . $ajxpPlugin->getPluginInformationHTML("Charles du Jeu", "http://ajaxplorer.info/plugins/") . "</p>";
             if (file_exists($ajxpPlugin->getBaseDir() . "/plugin_doc.html")) {
                 echo file_get_contents($ajxpPlugin->getBaseDir() . "/plugin_doc.html");
             }
             echo "]]></plugin_doc>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "edit_plugin_options":
             $options = array();
             $this->parseParameters($httpVars, $options);
             $confStorage = ConfService::getConfStorageImpl();
             $confStorage->savePluginConfig($httpVars["plugin_id"], $options);
             @unlink(AJXP_PLUGINS_CACHE_FILE);
             @unlink(AJXP_PLUGINS_REQUIRES_FILE);
             @unlink(AJXP_PLUGINS_MESSAGES_FILE);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.97"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     return;
 }
Exemplo n.º 23
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     $dir = AJXP_Utils::securePath($dir);
     if ($action != "upload") {
         $dir = SystemTextEncoding::fromPostedFileName($dir);
     }
     $selection->initFromHttpVars($httpVars);
     $mess = ConfService::getMessages();
     $newArgs = RecycleBinManager::filterActions($action, $selection, $dir);
     if (isset($newArgs["action"])) {
         $action = $newArgs["action"];
     }
     if (isset($newArgs["dest"])) {
         $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]);
     }
     //Re-encode!
     // FILTER DIR PAGINATION ANCHOR
     $page = null;
     if (isset($dir) && strstr($dir, "#") !== false) {
         $parts = explode("#", $dir);
         $dir = $parts[0];
         $page = $parts[1];
     }
     $pendingSelection = "";
     $logMessage = null;
     $reloadContextNode = false;
     switch ($action) {
         //------------------------------------
         //	DOWNLOAD
         //------------------------------------
         case "download":
             AJXP_Logger::logAction("Download", array("files" => $selection));
             @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE);
             @register_shutdown_function("restore_error_handler");
             $zip = false;
             if ($selection->isUnique()) {
                 if (is_dir($this->urlBase . $selection->getUniqueFile())) {
                     $zip = true;
                     $base = basename($selection->getUniqueFile());
                     $dir .= "/" . dirname($selection->getUniqueFile());
                 }
             } else {
                 $zip = true;
             }
             if ($zip) {
                 // Make a temp zip and send it as download
                 $loggedUser = AuthService::getLoggedUser();
                 $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpDownload.zip";
                 $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
                 if (!$zipFile) {
                     throw new AJXP_Exception("Error while compressing");
                 }
                 register_shutdown_function("unlink", $file);
                 $localName = ($base == "" ? "Files" : $base) . ".zip";
                 $this->readFile($file, "force-download", $localName, false, false, true);
             } else {
                 $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download");
             }
             exit(0);
             break;
         case "compress":
             // Make a temp zip and send it as download
             $loggedUser = AuthService::getLoggedUser();
             if (isset($httpVars["archive_name"])) {
                 $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]);
             } else {
                 $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip";
             }
             $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpCompression.zip";
             $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
             if (!$zipFile) {
                 throw new AJXP_Exception("Error while compressing file {$localName}");
             }
             register_shutdown_function("unlink", $file);
             copy($file, $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName));
             @rename($this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName), $this->urlBase . $dir . "/" . $localName);
             $reloadContextNode = true;
             $pendingSelection = $localName;
             break;
         case "stat":
             clearstatcache();
             $stat = @stat($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["file"]));
             header("Content-type:application/json");
             if (!$stat) {
                 print '{}';
             } else {
                 print json_encode($stat);
             }
             exit(1);
             break;
             //------------------------------------
             //	ONLINE EDIT
             //------------------------------------
         //------------------------------------
         //	ONLINE EDIT
         //------------------------------------
         case "get_content":
             $this->readFile($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["file"]), "plain");
             exit(0);
             break;
         case "put_content":
             if (!isset($httpVars["content"])) {
                 break;
             }
             // Reload "code" variable directly from POST array, do not "securePath"...
             $code = $httpVars["content"];
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             AJXP_Logger::logAction("Online Edition", array("file" => $file));
             if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") {
                 $code = base64_decode($code);
             } else {
                 $code = stripslashes($code);
                 $code = str_replace("&lt;", "<", $code);
             }
             $fileName = $this->urlBase . $file;
             if (!is_file($fileName) || !is_writable($fileName)) {
                 header("Content-Type:text/plain");
                 print !is_writable($fileName) ? "1001" : "1002";
                 exit(1);
             }
             $fp = fopen($fileName, "w");
             fputs($fp, $code);
             fclose($fp);
             header("Content-Type:text/plain");
             print $mess[115];
             exit(0);
             break;
             //------------------------------------
             //	COPY / MOVE
             //------------------------------------
         //------------------------------------
         //	COPY / MOVE
         //------------------------------------
         case "copy":
         case "move":
             if ($selection->isEmpty()) {
                 throw new AJXP_Exception("", 113);
             }
             $success = $error = array();
             $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]);
             if ($selection->inZip()) {
                 // Set action to copy anycase (cannot move from the zip).
                 $action = "copy";
             }
             $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false);
             if (count($error)) {
                 throw new AJXP_Exception(join("\n", $error));
             } else {
                 $logMessage = join("\n", $success);
                 AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest));
             }
             $reloadContextNode = true;
             $reloadDataNode = $dest;
             break;
             //------------------------------------
             //	SUPPRIMER / DELETE
             //------------------------------------
         //------------------------------------
         //	SUPPRIMER / DELETE
         //------------------------------------
         case "delete":
             if ($selection->isEmpty()) {
                 throw new AJXP_Exception("", 113);
             }
             $logMessages = array();
             $errorMessage = $this->delete($selection->getFiles(), $logMessages);
             if (count($logMessages)) {
                 $logMessage = join("\n", $logMessages);
             }
             if ($errorMessage) {
                 throw new AJXP_Exception($errorMessage);
             }
             AJXP_Logger::logAction("Delete", array("files" => $selection));
             $reloadContextNode = true;
             break;
             //------------------------------------
             //	RENOMMER / RENAME
             //------------------------------------
         //------------------------------------
         //	RENOMMER / RENAME
         //------------------------------------
         case "rename":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]);
             $this->rename($file, $filename_new);
             $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new);
             $reloadContextNode = true;
             $pendingSelection = $filename_new;
             AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new));
             break;
             //------------------------------------
             //	CREER UN REPERTOIRE / CREATE DIR
             //------------------------------------
         //------------------------------------
         //	CREER UN REPERTOIRE / CREATE DIR
         //------------------------------------
         case "mkdir":
             $messtmp = "";
             $dirname = AJXP_Utils::processFileName(SystemTextEncoding::fromUTF8($httpVars["dirname"]));
             $error = $this->mkDir($dir, $dirname);
             if (isset($error)) {
                 throw new AJXP_Exception($error);
             }
             $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             $pendingSelection = $dirname;
             $reloadContextNode = true;
             AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname));
             break;
             //------------------------------------
             //	CREER UN FICHIER / CREATE FILE
             //------------------------------------
         //------------------------------------
         //	CREER UN FICHIER / CREATE FILE
         //------------------------------------
         case "mkfile":
             $messtmp = "";
             $filename = AJXP_Utils::processFileName(SystemTextEncoding::fromUTF8($httpVars["filename"]));
             $error = $this->createEmptyFile($dir, $filename);
             if (isset($error)) {
                 throw new AJXP_Exception($error);
             }
             $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             $reloadContextNode = true;
             $pendingSelection = $dir . "/" . $filename;
             AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename));
             break;
             //------------------------------------
             //	CHANGE FILE PERMISSION
             //------------------------------------
         //------------------------------------
         //	CHANGE FILE PERMISSION
         //------------------------------------
         case "chmod":
             $messtmp = "";
             $files = $selection->getFiles();
             $changedFiles = array();
             $chmod_value = $httpVars["chmod_value"];
             $recursive = $httpVars["recursive"];
             $recur_apply_to = $httpVars["recur_apply_to"];
             foreach ($files as $fileName) {
                 $error = $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles);
             }
             if (isset($error)) {
                 throw new AJXP_Exception($error);
             }
             //$messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] ";
             $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders";
             $reloadContextNode = true;
             AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($changedFiles)));
             break;
             //------------------------------------
             //	UPLOAD
             //------------------------------------
         //------------------------------------
         //	UPLOAD
         //------------------------------------
         case "upload":
             AJXP_Logger::debug("Upload Files Data", $fileVars);
             $destination = $this->urlBase . SystemTextEncoding::fromPostedFileName($dir);
             AJXP_Logger::debug("Upload inside", array("destination" => $destination));
             if (!$this->isWriteable($destination)) {
                 $errorCode = 412;
                 $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}.";
                 AJXP_Logger::debug("Upload error 412", array("destination" => $destination));
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             }
             foreach ($fileVars as $boxName => $boxData) {
                 if (substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                     $errorCode = $err[0];
                     $errorMessage = $err[1];
                     break;
                 }
                 $userfile_name = $boxData["name"];
                 $userfile_name = AJXP_Utils::processFileName($userfile_name);
                 if (isset($httpVars["auto_rename"])) {
                     $userfile_name = self::autoRenameForDest($destination, $userfile_name);
                 }
                 if (isset($boxData["input_upload"])) {
                     try {
                         AJXP_Logger::debug("Begining reading INPUT stream");
                         $input = fopen("php://input", "r");
                         $output = fopen("{$destination}/" . $userfile_name, "w");
                         $sizeRead = 0;
                         while ($sizeRead < intval($boxData["size"])) {
                             $chunk = fread($input, 4096);
                             $sizeRead += strlen($chunk);
                             fwrite($output, $chunk, strlen($chunk));
                         }
                         fclose($input);
                         fclose($output);
                         AJXP_Logger::debug("End reading INPUT stream");
                     } catch (Exception $e) {
                         $errorCode = 411;
                         $errorMessage = $e->getMessage();
                         break;
                     }
                 } else {
                     if (!move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name)) {
                         $errorCode = 411;
                         $errorMessage = "{$mess['33']} " . $userfile_name;
                         break;
                     }
                 }
                 $this->changeMode($destination . "/" . $userfile_name);
                 $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}";
                 AJXP_Logger::logAction("Upload File", array("file" => SystemTextEncoding::fromUTF8($dir) . "/" . $userfile_name));
             }
             if (isset($errorMessage)) {
                 AJXP_Logger::debug("Return error {$errorCode} {$errorMessage}");
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             } else {
                 AJXP_Logger::debug("Return success");
                 return array("SUCCESS" => true);
             }
             return;
             break;
             //------------------------------------
             // Public URL
             //------------------------------------
         //------------------------------------
         // Public URL
         //------------------------------------
         case "public_url":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $url = $this->makePubliclet($file, $httpVars["password"], $httpVars["expiration"]);
             header("Content-type:text/plain");
             echo $url;
             exit(1);
             break;
             //------------------------------------
             //	XML LISTING
             //------------------------------------
         //------------------------------------
         //	XML LISTING
         //------------------------------------
         case "ls":
             if (!isset($dir) || $dir == "/") {
                 $dir = "";
             }
             $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a");
             $startTime = microtime();
             $dir = AJXP_Utils::securePath(SystemTextEncoding::magicDequote($dir));
             $path = $this->urlBase . ($dir != "" ? "/" . $dir : "");
             $threshold = $this->repository->getOption("PAGINATION_THRESHOLD");
             if (!isset($threshold) || intval($threshold) == 0) {
                 $threshold = 500;
             }
             $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER");
             if (!isset($limitPerPage) || intval($limitPerPage) == 0) {
                 $limitPerPage = 200;
             }
             $countFiles = $this->countFiles($path, !$lsOptions["f"]);
             if ($countFiles > $threshold) {
                 $offset = 0;
                 $crtPage = 1;
                 if (isset($page)) {
                     $offset = (intval($page) - 1) * $limitPerPage;
                     $crtPage = $page;
                 }
                 $totalPages = floor($countFiles / $limitPerPage) + 1;
             } else {
                 $offset = $limitPerPage = 0;
             }
             $metaData = array();
             $crtLabel = AJXP_Utils::xmlEntities(basename($dir), true);
             if (RecycleBinManager::recycleEnabled()) {
                 if (RecycleBinManager::currentLocationIsRecycle($dir)) {
                     $metaData["ajxp_mime"] = "ajxp_recycle";
                     $crtLabel = AJXP_Utils::xmlEntities($mess[122]);
                 } else {
                     if ($dir == "") {
                         $metaData["repo_has_recycle"] = "true";
                     }
                 }
             }
             AJXP_XMLWriter::renderHeaderNode(AJXP_Utils::xmlEntities($dir, true), $crtLabel, false, $metaData);
             if (isset($totalPages) && isset($crtPage)) {
                 AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages);
                 if (!$lsOptions["f"]) {
                     AJXP_XMLWriter::close();
                     exit(1);
                 }
             }
             $cursor = 0;
             $handle = opendir($path);
             if (!$handle) {
                 throw new AJXP_Exception("Cannot open dir " . $path);
             }
             $fullList = array("d" => array(), "z" => array(), "f" => array());
             while (strlen($nodeName = readdir($handle)) > 0) {
                 if ($nodeName == "." || $nodeName == "..") {
                     continue;
                 }
                 $isLeaf = is_file($path . "/" . $nodeName) || AJXP_Utils::isBrowsableArchive($nodeName);
                 if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) {
                     continue;
                 }
                 if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) {
                     continue;
                 }
                 $nodeType = "d";
                 if ($isLeaf) {
                     if (AJXP_Utils::isBrowsableArchive($nodeName)) {
                         if ($lsOptions["f"] && $lsOptions["z"]) {
                             // See archives as files
                             $nodeType = "f";
                         } else {
                             $nodeType = "z";
                         }
                     } else {
                         $nodeType = "f";
                     }
                 }
                 if ($offset > 0 && $cursor < $offset) {
                     $cursor++;
                     continue;
                 }
                 if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) {
                     break;
                 }
                 $metaData = array();
                 $currentFile = $path . "/" . $nodeName;
                 $metaData["is_file"] = $isLeaf ? "1" : "0";
                 $metaData["filename"] = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($dir . "/" . $nodeName));
                 $metaData["icon"] = AJXP_Utils::mimetype($nodeName, "image", !$isLeaf);
                 if ($metaData["icon"] == "folder.png") {
                     $metaData["openicon"] = "folder_open.png";
                 }
                 if (!is_file($currentFile) || AJXP_Utils::isBrowsableArchive($nodeName)) {
                     $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?get_action=ls&options=dz&dir=" . $dir . "/" . $nodeName);
                     $link = urlencode($link);
                     $metaData["src"] = $link;
                 }
                 if ($lsOptions["l"]) {
                     $metaData["file_group"] = @filegroup($currentFile) || "unknown";
                     $metaData["file_owner"] = @fileowner($currentFile) || "unknown";
                     $fPerms = @fileperms($currentFile);
                     if ($fPerms !== false) {
                         $fPerms = substr(decoct($fPerms), $isLeaf ? 2 : 1);
                     } else {
                         $fPerms = '0000';
                     }
                     $metaData["file_perms"] = $fPerms;
                     $metaData["mimestring"] = AJXP_Utils::mimetype($currentFile, "type", !$isLeaf);
                     $datemodif = $this->date_modif($currentFile);
                     $metaData["ajxp_modiftime"] = $datemodif ? $datemodif : "0";
                     $metaData["bytesize"] = 0;
                     if ($isLeaf) {
                         $metaData["bytesize"] = filesize($currentFile);
                     }
                     $metaData["filesize"] = AJXP_Utils::roundSize($metaData["bytesize"]);
                     if (AJXP_Utils::isBrowsableArchive($nodeName)) {
                         $metaData["ajxp_mime"] = "ajxp_browsable_archive";
                     }
                     $realFile = null;
                     // A reference to the real file.
                     AJXP_Controller::applyHook("ls.metadata", array($currentFile, &$metaData, $this->wrapperClassName, &$realFile));
                 }
                 $attributes = "";
                 foreach ($metaData as $key => $value) {
                     $attributes .= "{$key}=\"{$value}\" ";
                 }
                 $renderNodeData = array(AJXP_Utils::xmlEntities($dir . "/" . $nodeName, true), AJXP_Utils::xmlEntities($nodeName, true), $isLeaf, $metaData);
                 $fullList[$nodeType][$nodeName] = $renderNodeData;
                 $cursor++;
             }
             foreach ($fullList as $key => $list) {
                 uksort($list, 'strnatcasecmp');
                 $fullList[$key] = $list;
             }
             $allNodes = array_merge($fullList["d"], $fullList["z"], $fullList["f"]);
             array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["d"]);
             array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["z"]);
             array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["f"]);
             // ADD RECYCLE BIN TO THE LIST
             if ($dir == "" && RecycleBinManager::recycleEnabled()) {
                 $recycleBinOption = RecycleBinManager::getRelativeRecycle();
                 if (file_exists($this->urlBase . $recycleBinOption)) {
                     $recycleIcon = $this->countFiles($this->urlBase . $recycleBinOption, false, true) > 0 ? "trashcan_full.png" : "trashcan.png";
                     AJXP_XMLWriter::renderNode($recycleBinOption, AJXP_Utils::xmlEntities($mess[122]), false, array("ajxp_modiftime" => $this->date_modif($this->urlBase . $recycleBinOption), "mimestring" => AJXP_Utils::xmlEntities($mess[122]), "icon" => "{$recycleIcon}", "filesize" => "-", "ajxp_mime" => "ajxp_recycle"));
                 }
             }
             AJXP_Logger::debug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms");
             AJXP_XMLWriter::close();
             return;
             break;
     }
     $xmlBuffer = "";
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if ($reloadContextNode) {
         if (!isset($pendingSelection)) {
             $pendingSelection = "";
         }
         $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false);
     }
     if (isset($reloadDataNode)) {
         $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false);
     }
     return $xmlBuffer;
 }
Exemplo n.º 24
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     if ($this->wrapperClassName == "fsAccessWrapper") {
         $dir = fsAccessWrapper::patchPathForBaseDir($dir);
     }
     $dir = AJXP_Utils::securePath($dir);
     if ($action != "upload") {
         $dir = AJXP_Utils::decodeSecureMagic($dir);
     }
     $selection->initFromHttpVars($httpVars);
     if (!$selection->isEmpty()) {
         $this->filterUserSelectionToHidden($selection->getFiles());
     }
     $mess = ConfService::getMessages();
     $newArgs = RecycleBinManager::filterActions($action, $selection, $dir, $httpVars);
     if (isset($newArgs["action"])) {
         $action = $newArgs["action"];
     }
     if (isset($newArgs["dest"])) {
         $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]);
     }
     //Re-encode!
     // FILTER DIR PAGINATION ANCHOR
     $page = null;
     if (isset($dir) && strstr($dir, "%23") !== false) {
         $parts = explode("%23", $dir);
         $dir = $parts[0];
         $page = $parts[1];
     }
     $pendingSelection = "";
     $logMessage = null;
     $reloadContextNode = false;
     switch ($action) {
         //------------------------------------
         //	DOWNLOAD
         //------------------------------------
         case "download":
             $this->logInfo("Download", array("files" => $this->addSlugToPath($selection)));
             @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE);
             @register_shutdown_function("restore_error_handler");
             $zip = false;
             if ($selection->isUnique()) {
                 if (is_dir($this->urlBase . $selection->getUniqueFile())) {
                     $zip = true;
                     $base = basename($selection->getUniqueFile());
                     $uniqDir = dirname($selection->getUniqueFile());
                     if (!empty($uniqDir) && $uniqDir != "/") {
                         $dir = dirname($selection->getUniqueFile());
                     }
                 } else {
                     if (!file_exists($this->urlBase . $selection->getUniqueFile())) {
                         throw new Exception("Cannot find file!");
                     }
                 }
                 $node = $selection->getUniqueNode($this);
             } else {
                 $zip = true;
             }
             if ($zip) {
                 // Make a temp zip and send it as download
                 $loggedUser = AuthService::getLoggedUser();
                 $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpDownload.zip";
                 $zipFile = $this->makeZip($selection->getFiles(), $file, empty($dir) ? "/" : $dir);
                 if (!$zipFile) {
                     throw new AJXP_Exception("Error while compressing");
                 }
                 if (!$this->getFilteredOption("USE_XSENDFILE", $this->repository->getId()) && !$this->getFilteredOption("USE_XACCELREDIRECT", $this->repository->getId())) {
                     register_shutdown_function("unlink", $file);
                 }
                 $localName = ($base == "" ? "Files" : $base) . ".zip";
                 if (isset($httpVars["archive_name"])) {
                     $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]);
                 }
                 $this->readFile($file, "force-download", $localName, false, false, true);
             } else {
                 $localName = "";
                 AJXP_Controller::applyHook("dl.localname", array($this->urlBase . $selection->getUniqueFile(), &$localName, $this->wrapperClassName));
                 $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download", $localName);
             }
             if (isset($node)) {
                 AJXP_Controller::applyHook("node.read", array(&$node));
             }
             break;
         case "prepare_chunk_dl":
             $chunkCount = intval($httpVars["chunk_count"]);
             $fileId = $this->urlBase . $selection->getUniqueFile();
             $sessionKey = "chunk_file_" . md5($fileId . time());
             $totalSize = $this->filesystemFileSize($fileId);
             $chunkSize = intval($totalSize / $chunkCount);
             $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $fileId, true);
             $chunkData = array("localname" => basename($fileId), "chunk_count" => $chunkCount, "chunk_size" => $chunkSize, "total_size" => $totalSize, "file_id" => $sessionKey);
             $_SESSION[$sessionKey] = array_merge($chunkData, array("file" => $realFile));
             HTMLWriter::charsetHeader("application/json");
             print json_encode($chunkData);
             $node = $selection->getUniqueNode($this);
             AJXP_Controller::applyHook("node.read", array(&$node));
             break;
         case "download_chunk":
             $chunkIndex = intval($httpVars["chunk_index"]);
             $chunkKey = $httpVars["file_id"];
             $sessData = $_SESSION[$chunkKey];
             $realFile = $sessData["file"];
             $chunkSize = $sessData["chunk_size"];
             $offset = $chunkSize * $chunkIndex;
             if ($chunkIndex == $sessData["chunk_count"] - 1) {
                 // Compute the last chunk real length
                 $chunkSize = $sessData["total_size"] - $chunkSize * ($sessData["chunk_count"] - 1);
                 if (call_user_func(array($this->wrapperClassName, "isRemote"))) {
                     register_shutdown_function("unlink", $realFile);
                 }
             }
             $this->readFile($realFile, "force-download", $sessData["localname"] . "." . sprintf("%03d", $chunkIndex + 1), false, false, true, $offset, $chunkSize);
             break;
         case "compress":
             // Make a temp zip and send it as download
             $loggedUser = AuthService::getLoggedUser();
             if (isset($httpVars["archive_name"])) {
                 $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]);
                 $this->filterUserSelectionToHidden(array($localName));
             } else {
                 $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip";
             }
             $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpCompression.zip";
             if (isset($httpVars["compress_flat"])) {
                 $baseDir = "__AJXP_ZIP_FLAT__/";
             } else {
                 $baseDir = $dir;
             }
             $zipFile = $this->makeZip($selection->getFiles(), $file, $baseDir);
             if (!$zipFile) {
                 throw new AJXP_Exception("Error while compressing file {$localName}");
             }
             register_shutdown_function("unlink", $file);
             $tmpFNAME = $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName);
             copy($file, $tmpFNAME);
             try {
                 AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($tmpFNAME), filesize($tmpFNAME)));
             } catch (Exception $e) {
                 @unlink($tmpFNAME);
                 throw $e;
             }
             @rename($tmpFNAME, $this->urlBase . $dir . "/" . $localName);
             AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($this->urlBase . $dir . "/" . $localName), false));
             //$reloadContextNode = true;
             //$pendingSelection = $localName;
             $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $localName);
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             $nodesDiffs["ADD"][] = $newNode;
             break;
         case "stat":
             clearstatcache();
             header("Content-type:application/json");
             if ($selection->isUnique()) {
                 $stat = @stat($this->urlBase . $selection->getUniqueFile());
                 if (!$stat) {
                     print '{}';
                 } else {
                     print json_encode($stat);
                 }
             } else {
                 $files = $selection->getFiles();
                 print '{';
                 foreach ($files as $index => $path) {
                     $stat = @stat($this->urlBase . $path);
                     if (!$stat) {
                         $stat = '{}';
                     } else {
                         $stat = json_encode($stat);
                     }
                     print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : "");
                 }
                 print '}';
             }
             break;
             //------------------------------------
             //	ONLINE EDIT
             //------------------------------------
         //------------------------------------
         //	ONLINE EDIT
         //------------------------------------
         case "get_content":
             $dlFile = $this->urlBase . $selection->getUniqueFile();
             $this->logInfo("Get_content", array("files" => $this->addSlugToPath($selection)));
             if (AJXP_Utils::getStreamingMimeType(basename($dlFile)) !== false) {
                 $this->readFile($this->urlBase . $selection->getUniqueFile(), "stream_content");
             } else {
                 $this->readFile($this->urlBase . $selection->getUniqueFile(), "plain");
             }
             $node = $selection->getUniqueNode($this);
             AJXP_Controller::applyHook("node.read", array(&$node));
             break;
         case "put_content":
             if (!isset($httpVars["content"])) {
                 break;
             }
             // Load "code" variable directly from POST array, do not "securePath" or "sanitize"...
             $code = $httpVars["content"];
             $file = $selection->getUniqueFile();
             $this->logInfo("Online Edition", array("file" => $this->addSlugToPath($file)));
             if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") {
                 $code = base64_decode($code);
             } else {
                 $code = str_replace("&lt;", "<", SystemTextEncoding::magicDequote($code));
             }
             $fileName = $this->urlBase . $file;
             $currentNode = new AJXP_Node($fileName);
             try {
                 AJXP_Controller::applyHook("node.before_change", array(&$currentNode, strlen($code)));
             } catch (Exception $e) {
                 header("Content-Type:text/plain");
                 print $e->getMessage();
                 return;
             }
             if (!is_file($fileName) || !$this->isWriteable($fileName, "file")) {
                 header("Content-Type:text/plain");
                 print !$this->isWriteable($fileName, "file") ? "1001" : "1002";
                 return;
             }
             $fp = fopen($fileName, "w");
             fputs($fp, $code);
             fclose($fp);
             clearstatcache(true, $fileName);
             AJXP_Controller::applyHook("node.change", array($currentNode, $currentNode, false));
             header("Content-Type:text/plain");
             print $mess[115];
             break;
             //------------------------------------
             //	COPY / MOVE
             //------------------------------------
         //------------------------------------
         //	COPY / MOVE
         //------------------------------------
         case "copy":
         case "move":
             //throw new AJXP_Exception("", 113);
             if ($selection->isEmpty()) {
                 throw new AJXP_Exception("", 113);
             }
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser != null && !$loggedUser->canWrite(ConfService::getCurrentRepositoryId())) {
                 throw new AJXP_Exception("You are not allowed to write", 207);
             }
             $success = $error = array();
             $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]);
             $this->filterUserSelectionToHidden(array($httpVars["dest"]));
             if ($selection->inZip()) {
                 // Set action to copy anycase (cannot move from the zip).
                 $action = "copy";
                 $this->extractArchive($dest, $selection, $error, $success);
             } else {
                 $move = $action == "move" ? true : false;
                 if ($move && isset($httpVars["force_copy_delete"])) {
                     $move = false;
                 }
                 $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $move);
             }
             if (count($error)) {
                 throw new AJXP_Exception(SystemTextEncoding::toUTF8(join("\n", $error)));
             } else {
                 if (isset($httpVars["force_copy_delete"])) {
                     $errorMessage = $this->delete($selection->getFiles(), $logMessages);
                     if ($errorMessage) {
                         throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage));
                     }
                     $this->logInfo("Copy/Delete", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest)));
                 } else {
                     $this->logInfo($action == "move" ? "Move" : "Copy", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest)));
                 }
                 $logMessage = join("\n", $success);
             }
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             // Assume new nodes are correctly created
             $selectedItems = $selection->getFiles();
             foreach ($selectedItems as $selectedPath) {
                 $newPath = $this->urlBase . $dest . "/" . basename($selectedPath);
                 $newNode = new AJXP_Node($newPath);
                 $nodesDiffs["ADD"][] = $newNode;
                 if ($action == "move") {
                     $nodesDiffs["REMOVE"][] = $selectedPath;
                 }
             }
             if (!(RecycleBinManager::getRelativeRecycle() == $dest && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) == true)) {
                 //$reloadDataNode = $dest;
             }
             break;
             //------------------------------------
             //	DELETE
             //------------------------------------
         //------------------------------------
         //	DELETE
         //------------------------------------
         case "delete":
             if ($selection->isEmpty()) {
                 throw new AJXP_Exception("", 113);
             }
             $logMessages = array();
             $errorMessage = $this->delete($selection->getFiles(), $logMessages);
             if (count($logMessages)) {
                 $logMessage = join("\n", $logMessages);
             }
             if ($errorMessage) {
                 throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage));
             }
             $this->logInfo("Delete", array("files" => $this->addSlugToPath($selection)));
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             $nodesDiffs["REMOVE"] = array_merge($nodesDiffs["REMOVE"], $selection->getFiles());
             break;
         case "purge":
             $hardPurgeTime = intval($this->repository->getOption("PURGE_AFTER")) * 3600 * 24;
             $softPurgeTime = intval($this->repository->getOption("PURGE_AFTER_SOFT")) * 3600 * 24;
             $shareCenter = AJXP_PluginsService::findPluginById('action.share');
             if (!($shareCenter && $shareCenter->isEnabled())) {
                 //action.share is disabled, don't look at the softPurgeTime
                 $softPurgeTime = 0;
             }
             if ($hardPurgeTime > 0 || $softPurgeTime > 0) {
                 $this->recursivePurge($this->urlBase, $hardPurgeTime, $softPurgeTime);
             }
             break;
             //------------------------------------
             //	RENAME
             //------------------------------------
         //------------------------------------
         //	RENAME
         //------------------------------------
         case "rename":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]);
             $dest = null;
             if (isset($httpVars["dest"])) {
                 $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]);
                 $filename_new = "";
             }
             $this->filterUserSelectionToHidden(array($filename_new));
             $this->rename($file, $filename_new, $dest);
             $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new);
             //$reloadContextNode = true;
             //$pendingSelection = $filename_new;
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             if ($dest == null) {
                 $dest = AJXP_Utils::safeDirname($file);
             }
             $nodesDiffs["UPDATE"][$file] = new AJXP_Node($this->urlBase . $dest . "/" . $filename_new);
             $this->logInfo("Rename", array("original" => $this->addSlugToPath($file), "new" => $filename_new));
             break;
             //------------------------------------
             //	CREER UN REPERTOIRE / CREATE DIR
             //------------------------------------
         //------------------------------------
         //	CREER UN REPERTOIRE / CREATE DIR
         //------------------------------------
         case "mkdir":
             $messtmp = "";
             if (!isset($httpVars["dirname"])) {
                 $uniq = $selection->getUniqueFile();
                 $dir = AJXP_Utils::safeDirname($uniq);
                 $dirname = AJXP_Utils::safeBasename($uniq);
             } else {
                 $dirname = AJXP_Utils::decodeSecureMagic($httpVars["dirname"], AJXP_SANITIZE_FILENAME);
             }
             $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
             $this->filterUserSelectionToHidden(array($dirname));
             AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($dir . "/" . $dirname), -2));
             $error = $this->mkDir($dir, $dirname, isset($httpVars["ignore_exists"]) ? true : false);
             if (isset($error)) {
                 throw new AJXP_Exception($error);
             }
             $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             //$pendingSelection = $dirname;
             //$reloadContextNode = true;
             $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $dirname);
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             array_push($nodesDiffs["ADD"], $newNode);
             $this->logInfo("Create Dir", array("dir" => $this->addSlugToPath($dir) . "/" . $dirname));
             break;
             //------------------------------------
             //	CREER UN FICHIER / CREATE FILE
             //------------------------------------
         //------------------------------------
         //	CREER UN FICHIER / CREATE FILE
         //------------------------------------
         case "mkfile":
             $messtmp = "";
             if (empty($httpVars["filename"]) && isset($httpVars["node"])) {
                 $filename = AJXP_Utils::decodeSecureMagic($httpVars["node"], AJXP_SANITIZE_FILENAME);
             } else {
                 $filename = AJXP_Utils::decodeSecureMagic($httpVars["filename"], AJXP_SANITIZE_FILENAME);
             }
             $filename = substr($filename, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
             $this->filterUserSelectionToHidden(array($filename));
             $content = "";
             if (isset($httpVars["content"])) {
                 $content = $httpVars["content"];
             }
             $error = $this->createEmptyFile($dir, $filename, $content);
             if (isset($error)) {
                 throw new AJXP_Exception($error);
             }
             $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             //$reloadContextNode = true;
             //$pendingSelection = $dir."/".$filename;
             $this->logInfo("Create File", array("file" => $this->addSlugToPath($dir) . "/" . $filename));
             $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $filename);
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             array_push($nodesDiffs["ADD"], $newNode);
             break;
             //------------------------------------
             //	CHANGE FILE PERMISSION
             //------------------------------------
         //------------------------------------
         //	CHANGE FILE PERMISSION
         //------------------------------------
         case "chmod":
             $files = $selection->getFiles();
             $changedFiles = array();
             $chmod_value = $httpVars["chmod_value"];
             $recursive = $httpVars["recursive"];
             $recur_apply_to = $httpVars["recur_apply_to"];
             foreach ($files as $fileName) {
                 $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles);
             }
             $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders";
             $this->logInfo("Chmod", array("dir" => $this->addSlugToPath($dir), "filesCount" => count($changedFiles)));
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             $nodesDiffs["UPDATE"] = array_merge($nodesDiffs["UPDATE"], $selection->buildNodes($this));
             break;
             //------------------------------------
             //	UPLOAD
             //------------------------------------
         //------------------------------------
         //	UPLOAD
         //------------------------------------
         case "upload":
             $repoData = array('base_url' => $this->urlBase, 'wrapper_name' => $this->wrapperClassName, 'chmod' => $this->repository->getOption('CHMOD_VALUE'), 'recycle' => $this->repository->getOption('RECYCLE_BIN'));
             $this->logDebug("Upload Files Data", $fileVars);
             $destination = $this->urlBase . AJXP_Utils::decodeSecureMagic($dir);
             $this->logDebug("Upload inside", array("destination" => $this->addSlugToPath($destination)));
             if (!$this->isWriteable($destination)) {
                 $errorCode = 412;
                 $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}.";
                 $this->logDebug("Upload error 412", array("destination" => $this->addSlugToPath($destination)));
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             }
             foreach ($fileVars as $boxName => $boxData) {
                 if (substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                     $errorCode = $err[0];
                     $errorMessage = $err[1];
                     break;
                 }
                 $userfile_name = $boxData["name"];
                 try {
                     $this->filterUserSelectionToHidden(array($userfile_name));
                 } catch (Exception $e) {
                     return array("ERROR" => array("CODE" => 411, "MESSAGE" => "Forbidden"));
                 }
                 $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromPostedFileName($userfile_name), AJXP_SANITIZE_FILENAME);
                 if (isset($httpVars["urlencoded_filename"])) {
                     $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["urlencoded_filename"])), AJXP_SANITIZE_FILENAME);
                 }
                 $this->logDebug("User filename " . $userfile_name);
                 $userfile_name = substr($userfile_name, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
                 if (isset($httpVars["auto_rename"])) {
                     $userfile_name = self::autoRenameForDest($destination, $userfile_name);
                 }
                 $already_existed = false;
                 try {
                     if (file_exists($destination . "/" . $userfile_name)) {
                         $already_existed = true;
                         AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"]));
                     } else {
                         AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"]));
                     }
                     AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination)));
                 } catch (Exception $e) {
                     $errorCode = 507;
                     $errorMessage = $e->getMessage();
                     break;
                 }
                 if (isset($boxData["input_upload"])) {
                     try {
                         $this->logDebug("Begining reading INPUT stream");
                         $input = fopen("php://input", "r");
                         $output = fopen("{$destination}/" . $userfile_name, "w");
                         $sizeRead = 0;
                         while ($sizeRead < intval($boxData["size"])) {
                             $chunk = fread($input, 4096);
                             $sizeRead += strlen($chunk);
                             fwrite($output, $chunk, strlen($chunk));
                         }
                         fclose($input);
                         fclose($output);
                         $this->logDebug("End reading INPUT stream");
                     } catch (Exception $e) {
                         $errorCode = 411;
                         $errorMessage = $e->getMessage();
                         break;
                     }
                 } else {
                     $result = @move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name);
                     if (!$result) {
                         $realPath = call_user_func(array($this->wrapperClassName, "getRealFSReference"), "{$destination}/" . $userfile_name);
                         $result = move_uploaded_file($boxData["tmp_name"], $realPath);
                     }
                     if (!$result) {
                         $errorCode = 411;
                         $errorMessage = "{$mess['33']} " . $userfile_name;
                         break;
                     }
                 }
                 if (isset($httpVars["appendto_urlencoded_part"])) {
                     $appendTo = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["appendto_urlencoded_part"])), AJXP_SANITIZE_FILENAME);
                     if (file_exists($destination . "/" . $appendTo)) {
                         $this->logDebug("Should copy stream from {$userfile_name} to {$appendTo}");
                         $partO = fopen($destination . "/" . $userfile_name, "r");
                         $appendF = fopen($destination . "/" . $appendTo, "a+");
                         while (!feof($partO)) {
                             $buf = fread($partO, 1024);
                             fwrite($appendF, $buf, strlen($buf));
                         }
                         fclose($partO);
                         fclose($appendF);
                         $this->logDebug("Done, closing streams!");
                     }
                     @unlink($destination . "/" . $userfile_name);
                     $userfile_name = $appendTo;
                 }
                 $this->changeMode($destination . "/" . $userfile_name, $repoData);
                 $createdNode = new AJXP_Node($destination . "/" . $userfile_name);
                 //AJXP_Controller::applyHook("node.change", array(null, $createdNode, false));
                 $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}";
                 $this->logInfo("Upload File", array("file" => $this->addSlugToPath(SystemTextEncoding::fromUTF8($dir)) . "/" . $userfile_name));
             }
             if (isset($errorMessage)) {
                 $this->logDebug("Return error {$errorCode} {$errorMessage}");
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             } else {
                 $this->logDebug("Return success");
                 if ($already_existed) {
                     return array("SUCCESS" => true, "UPDATED_NODE" => $createdNode);
                 } else {
                     return array("SUCCESS" => true, "CREATED_NODE" => $createdNode);
                 }
             }
             return;
             break;
         case "lsync":
             if (!ConfService::currentContextIsCommandLine()) {
                 die("This command must be accessed via CLI only.");
             }
             $fromNode = null;
             $toNode = null;
             $copyOrMove = false;
             if (isset($httpVars["from"])) {
                 $fromNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["from"]));
             }
             if (isset($httpVars["to"])) {
                 $toNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["to"]));
             }
             if (isset($httpVars["copy"]) && $httpVars["copy"] == "true") {
                 $copyOrMove = true;
             }
             AJXP_Controller::applyHook("node.change", array($fromNode, $toNode, $copyOrMove));
             break;
             //------------------------------------
             //	XML LISTING
             //------------------------------------
         //------------------------------------
         //	XML LISTING
         //------------------------------------
         case "ls":
             if (!isset($dir) || $dir == "/") {
                 $dir = "";
             }
             $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a");
             $startTime = microtime();
             if (isset($httpVars["file"])) {
                 $uniqueFile = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             }
             $dir = AJXP_Utils::securePath($dir);
             $path = $this->urlBase . ($dir != "" ? ($dir[0] == "/" ? "" : "/") . $dir : "");
             $nonPatchedPath = $path;
             if ($this->wrapperClassName == "fsAccessWrapper") {
                 $nonPatchedPath = fsAccessWrapper::unPatchPathForBaseDir($path);
             }
             if ($this->getFilteredOption("REMOTE_SORTING")) {
                 $orderDirection = isset($httpVars["order_direction"]) ? strtolower($httpVars["order_direction"]) : "asc";
                 $orderField = isset($httpVars["order_column"]) ? $httpVars["order_column"] : null;
                 if ($orderField != null && !in_array($orderField, array("ajxp_label", "filesize", "ajxp_modiftime", "mimestring"))) {
                     $orderField = "ajxp_label";
                 }
             }
             if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") {
                 $max_depth = isset($httpVars["max_depth"]) ? intval($httpVars["max_depth"]) : 0;
                 $max_nodes = isset($httpVars["max_nodes"]) ? intval($httpVars["max_nodes"]) : 0;
                 $crt_depth = isset($httpVars["crt_depth"]) ? intval($httpVars["crt_depth"]) + 1 : 1;
                 $crt_nodes = isset($httpVars["crt_nodes"]) ? intval($httpVars["crt_nodes"]) : 0;
             } else {
                 $threshold = $this->repository->getOption("PAGINATION_THRESHOLD");
                 if (!isset($threshold) || intval($threshold) == 0) {
                     $threshold = 500;
                 }
                 $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER");
                 if (!isset($limitPerPage) || intval($limitPerPage) == 0) {
                     $limitPerPage = 200;
                 }
             }
             $countFiles = $this->countFiles($path, !$lsOptions["f"]);
             if (isset($crt_nodes)) {
                 $crt_nodes += $countFiles;
             }
             if (isset($threshold) && isset($limitPerPage) && $countFiles > $threshold) {
                 if (isset($uniqueFile)) {
                     $originalLimitPerPage = $limitPerPage;
                     $offset = $limitPerPage = 0;
                 } else {
                     $offset = 0;
                     $crtPage = 1;
                     if (isset($page)) {
                         $offset = (intval($page) - 1) * $limitPerPage;
                         $crtPage = $page;
                     }
                     $totalPages = floor($countFiles / $limitPerPage) + 1;
                 }
             } else {
                 $offset = $limitPerPage = 0;
             }
             $metaData = array();
             if (RecycleBinManager::recycleEnabled() && $dir == "") {
                 $metaData["repo_has_recycle"] = "true";
             }
             $parentAjxpNode = new AJXP_Node($nonPatchedPath, $metaData);
             $parentAjxpNode->loadNodeInfo(false, true, $lsOptions["l"] ? "all" : "minimal");
             AJXP_Controller::applyHook("node.read", array(&$parentAjxpNode));
             if (AJXP_XMLWriter::$headerSent == "tree") {
                 AJXP_XMLWriter::renderAjxpNode($parentAjxpNode, false);
             } else {
                 AJXP_XMLWriter::renderAjxpHeaderNode($parentAjxpNode);
             }
             if (isset($totalPages) && isset($crtPage)) {
                 $remoteOptions = null;
                 if ($this->getFilteredOption("REMOTE_SORTING")) {
                     $remoteOptions = array("remote_order" => "true", "currentOrderCol" => isset($orderField) ? $orderField : "ajxp_label", "currentOrderDir" => isset($orderDirection) ? $orderDirection : "asc");
                 }
                 AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages, $this->countFiles($path, TRUE), $remoteOptions);
                 if (!$lsOptions["f"]) {
                     AJXP_XMLWriter::close();
                     exit(1);
                 }
             }
             $cursor = 0;
             $handle = opendir($path);
             if (!$handle) {
                 throw new AJXP_Exception("Cannot open dir " . $nonPatchedPath);
             }
             closedir($handle);
             $fullList = array("d" => array(), "z" => array(), "f" => array());
             if (isset($orderField) && isset($orderDirection) && $orderField == "ajxp_label" && $orderDirection == "desc") {
                 $nodes = scandir($path, 1);
             } else {
                 $nodes = scandir($path);
             }
             if (!empty($this->driverConf["SCANDIR_RESULT_SORTFONC"])) {
                 usort($nodes, $this->driverConf["SCANDIR_RESULT_SORTFONC"]);
             }
             if (isset($orderField) && isset($orderDirection) && $orderField != "ajxp_label") {
                 $toSort = array();
                 foreach ($nodes as $node) {
                     if ($orderField == "filesize") {
                         $toSort[$node] = is_file($nonPatchedPath . "/" . $node) ? $this->filesystemFileSize($nonPatchedPath . "/" . $node) : 0;
                     } else {
                         if ($orderField == "ajxp_modiftime") {
                             $toSort[$node] = filemtime($nonPatchedPath . "/" . $node);
                         } else {
                             if ($orderField == "mimestring") {
                                 $toSort[$node] = pathinfo($node, PATHINFO_EXTENSION);
                             }
                         }
                     }
                 }
                 if ($orderDirection == "asc") {
                     asort($toSort);
                 } else {
                     arsort($toSort);
                 }
                 $nodes = array_keys($toSort);
             }
             //while (strlen($nodeName = readdir($handle)) > 0) {
             foreach ($nodes as $nodeName) {
                 if ($nodeName == "." || $nodeName == "..") {
                     continue;
                 }
                 if (isset($uniqueFile) && $nodeName != $uniqueFile) {
                     $cursor++;
                     continue;
                 }
                 if ($offset > 0 && $cursor < $offset) {
                     $cursor++;
                     continue;
                 }
                 $isLeaf = "";
                 if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) {
                     continue;
                 }
                 if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) {
                     continue;
                 }
                 if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) {
                     break;
                 }
                 $currentFile = $nonPatchedPath . "/" . $nodeName;
                 $meta = array();
                 if ($isLeaf != "") {
                     $meta = array("is_file" => $isLeaf ? "1" : "0");
                 }
                 $node = new AJXP_Node($currentFile, $meta);
                 $node->setLabel($nodeName);
                 $node->loadNodeInfo(false, false, $lsOptions["l"] ? "all" : "minimal");
                 if (!empty($node->metaData["nodeName"]) && $node->metaData["nodeName"] != $nodeName) {
                     $node->setUrl($nonPatchedPath . "/" . $node->metaData["nodeName"]);
                 }
                 if (!empty($node->metaData["hidden"]) && $node->metaData["hidden"] === true) {
                     continue;
                 }
                 if (!empty($node->metaData["mimestring_id"]) && array_key_exists($node->metaData["mimestring_id"], $mess)) {
                     $node->mergeMetadata(array("mimestring" => $mess[$node->metaData["mimestring_id"]]));
                 }
                 if (isset($originalLimitPerPage) && $cursor > $originalLimitPerPage) {
                     $node->mergeMetadata(array("page_position" => floor($cursor / $originalLimitPerPage) + 1));
                 }
                 $nodeType = "d";
                 if ($node->isLeaf()) {
                     if (AJXP_Utils::isBrowsableArchive($nodeName)) {
                         if ($lsOptions["f"] && $lsOptions["z"]) {
                             $nodeType = "f";
                         } else {
                             $nodeType = "z";
                         }
                     } else {
                         $nodeType = "f";
                     }
                 }
                 // There is a special sorting, cancel the reordering of files & folders.
                 if (isset($orderField) && $orderField != "ajxp_label") {
                     $nodeType = "f";
                 }
                 $fullList[$nodeType][$nodeName] = $node;
                 $cursor++;
                 if (isset($uniqueFile) && $nodeName != $uniqueFile) {
                     break;
                 }
             }
             if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") {
                 $breakNow = false;
                 if (isset($max_depth) && $max_depth > 0 && $crt_depth >= $max_depth) {
                     $breakNow = true;
                 }
                 if (isset($max_nodes) && $max_nodes > 0 && $crt_nodes >= $max_nodes) {
                     $breakNow = true;
                 }
                 foreach ($fullList["d"] as &$nodeDir) {
                     if ($breakNow) {
                         $nodeDir->mergeMetadata(array("ajxp_has_children" => $this->countFiles($nodeDir->getUrl(), false, true) ? "true" : "false"));
                         AJXP_XMLWriter::renderAjxpNode($nodeDir, true);
                         continue;
                     }
                     $this->switchAction("ls", array("dir" => SystemTextEncoding::toUTF8($nodeDir->getPath()), "options" => $httpVars["options"], "recursive" => "true", "max_depth" => $max_depth, "max_nodes" => $max_nodes, "crt_depth" => $crt_depth, "crt_nodes" => $crt_nodes), array());
                 }
             } else {
                 array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["d"]);
             }
             array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["z"]);
             array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["f"]);
             // ADD RECYCLE BIN TO THE LIST
             if ($dir == "" && !$uniqueFile && RecycleBinManager::recycleEnabled() && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) !== true) {
                 $recycleBinOption = RecycleBinManager::getRelativeRecycle();
                 if (file_exists($this->urlBase . $recycleBinOption)) {
                     $recycleNode = new AJXP_Node($this->urlBase . $recycleBinOption);
                     $recycleNode->loadNodeInfo();
                     AJXP_XMLWriter::renderAjxpNode($recycleNode);
                 }
             }
             $this->logDebug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms");
             AJXP_XMLWriter::close();
             break;
     }
     $xmlBuffer = "";
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if ($reloadContextNode) {
         if (!isset($pendingSelection)) {
             $pendingSelection = "";
         }
         $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false);
     }
     if (isset($reloadDataNode)) {
         $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false);
     }
     if (isset($nodesDiffs)) {
         $xmlBuffer .= AJXP_XMLWriter::writeNodesDiff($nodesDiffs, false);
     }
     return $xmlBuffer;
 }
Exemplo n.º 25
0
 function fsAccessDriver($driverName, $filePath, $repository, $optOptions = NULL)
 {
     parent::AbstractAccessDriver($driverName, $filePath, $repository);
 }
Exemplo n.º 26
0
 function mysqlAccessDriver($driverName, $filePath, $repository, $optOptions = NULL)
 {
     $this->user = $optOptions ? $optOptions["user"] : $repository->getOption("DB_USER");
     $this->password = $optOptions ? $optOptions["password"] : $repository->getOption("DB_PASS");
     parent::AbstractAccessDriver($driverName, $filePath, $repository);
 }
 public function dir_opendir($url, $options)
 {
     $parts = $this->parseUrl($url);
     $link = $this->createFTPLink();
     $serverPath = AJXP_Utils::securePath($this->path . "/" . $parts["path"]);
     $contents = $this->rawList($link, $serverPath);
     $folders = $files = array();
     foreach ($contents as $entry) {
         $result = $this->rawListEntryToStat($entry);
         AbstractAccessDriver::fixPermissions($result["stat"], ConfService::getRepositoryById($this->repositoryId), array($this, "getRemoteUserId"));
         $isDir = $result["dir"];
         $statValue = $result["stat"];
         $file = $result["name"];
         if ($isDir) {
             $folders[$file] = $statValue;
         } else {
             $files[$file] = $statValue;
         }
     }
     // Append all files keys to folders. Do not use array_merge.
     foreach ($files as $key => $value) {
         $folders[$key] = $value;
     }
     AJXP_Logger::debug(__CLASS__, __FUNCTION__, "OPENDIR ", $folders);
     self::$dirContentLoopPath = AJXP_Utils::safeDirname($url);
     self::$dirContent = $folders;
     //array_merge($folders, $files);
     self::$dirContentKeys = array_keys(self::$dirContent);
     self::$dirContentIndex = 0;
     return true;
 }
Exemplo n.º 28
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;
 }
Exemplo n.º 29
0
 function ajxp_confAccessDriver($driverName)
 {
     parent::AbstractAccessDriver($driverName, INSTALL_PATH . "/plugins/access.ajxp_conf/ajxp_confActions.xml", null);
 }
Exemplo n.º 30
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $loggedUser = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled()) {
         return;
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png", "DESCRIPTION" => $mess["ajxp_shared.28"]), "repositories" => array("LABEL" => $mess["ajxp_shared.2"], "ICON" => "document_open_remote.png", "DESCRIPTION" => $mess["ajxp_shared.29"]), "users" => array("LABEL" => $mess["ajxp_shared.1"], "ICON" => "user_shared.png", "DESCRIPTION" => $mess["ajxp_shared.30"]));
             $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : "";
             $splits = explode("/", $dir);
             if (count($splits)) {
                 if ($splits[0] == "") {
                     array_shift($splits);
                 }
                 if (count($splits)) {
                     $strippedDir = strtolower(urldecode($splits[0]));
                 } else {
                     $strippedDir = "";
                 }
             }
             if (array_key_exists($strippedDir, $rootNodes)) {
                 AJXP_XMLWriter::header();
                 if ($strippedDir == "users") {
                     $this->listUsers();
                 } else {
                     if ($strippedDir == "repositories") {
                         $this->listRepositories();
                     } else {
                         if ($strippedDir == "files") {
                             $this->listSharedFiles();
                         }
                     }
                 }
                 AJXP_XMLWriter::close();
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_shared.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_shared.31" attributeName="description" sortType="String"/></columns>');
                 foreach ($rootNodes as $key => $data) {
                     print '<tree text="' . $data["LABEL"] . '" icon="' . $data["ICON"] . '" filename="/' . $key . '" parentname="/" description="' . $data["DESCRIPTION"] . '" />';
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             break;
         case "delete":
             $mime = $httpVars["ajxp_mime"];
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $files = $selection->getFiles();
             AJXP_XMLWriter::header();
             foreach ($files as $index => $element) {
                 $element = basename($element);
                 $ar = explode("shared_", $mime);
                 $mime = array_pop($ar);
                 ShareCenter::deleteSharedElement($mime, $element, $loggedUser);
                 if ($mime == "repository") {
                     $out = $mess["ajxp_conf.59"];
                 } else {
                     if ($mime == "user") {
                         $out = $mess["ajxp_conf.60"];
                     } else {
                         if ($mime == "file") {
                             $out = $mess["ajxp_shared.13"];
                         }
                     }
                 }
             }
             AJXP_XMLWriter::sendMessage($out, null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "clear_expired":
             $deleted = $this->clearExpiredFiles();
             AJXP_XMLWriter::header();
             if (count($deleted)) {
                 AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null);
             }
             AJXP_XMLWriter::close();
             break;
         case "reset_download_counter":
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $elements = $selection->getFiles();
             foreach ($elements as $element) {
                 PublicletCounter::reset(str_replace(".php", "", basename($element)));
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     return;
 }