コード例 #1
0
 public function getCurrentQuota($action, $httpVars, $fileVars)
 {
     $u = $this->getUsage($this->getWorkingPath());
     HTMLWriter::charsetHeader("application/json");
     print json_encode(array('USAGE' => $u, 'TOTAL' => $this->getAuthorized()));
     return;
 }
コード例 #2
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     switch ($action) {
         case "get_secure_token":
             HTMLWriter::charsetHeader("text/plain");
             print AuthService::generateSecureToken();
             //exit(0);
             break;
             //------------------------------------
             //	CHANGE USER PASSWORD
             //------------------------------------
         //------------------------------------
         //	CHANGE USER PASSWORD
         //------------------------------------
         case "pass_change":
             $userObject = AuthService::getLoggedUser();
             if ($userObject == null || $userObject->getId() == "guest") {
                 header("Content-Type:text/plain");
                 print "SUCCESS";
                 break;
             }
             $oldPass = $httpVars["old_pass"];
             $newPass = $httpVars["new_pass"];
             $passSeed = $httpVars["pass_seed"];
             if (strlen($newPass) < ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth")) {
                 header("Content-Type:text/plain");
                 print "PASS_ERROR";
                 break;
             }
             if (AuthService::checkPassword($userObject->getId(), $oldPass, false, $passSeed)) {
                 AuthService::updatePassword($userObject->getId(), $newPass);
                 if ($userObject->getLock() == "pass_change") {
                     $userObject->removeLock();
                     $userObject->save("superuser");
                 }
             } else {
                 header("Content-Type:text/plain");
                 print "PASS_ERROR";
                 break;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             break;
         default:
             break;
     }
     return "";
 }
コード例 #3
0
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     require_once AJXP_BIN_FOLDER . "/dibi.compact.php";
     dibi::connect($this->sqlDriver);
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $res = dibi::query("SELECT\n                [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n                FROM [ajxp_changes]\n                LEFT JOIN [ajxp_index]\n                    ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n                WHERE [ajxp_changes].[repository_identifier] = %s AND [seq] > %i\n                ORDER BY [ajxp_changes].[node_id], [seq] ASC", $this->computeIdentifier(ConfService::getRepository()), AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     echo '{"changes":[';
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if ($row->node_id == $previousNodeId) {
             $previousRow->target = $row->target;
             $previousRow->seq = $row->seq;
             if ($order[$row->type] > $order[$previousRow->type]) {
                 $previousRow->type = $row->type;
             }
         } else {
             if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                 echo json_encode($previousRow) . ",";
             }
             $previousRow = $row;
             $previousNodeId = $row->node_id;
         }
         $lastSeq = $row->seq;
         flush();
     }
     if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
         echo json_encode($previousRow);
     }
     if (isset($lastSeq)) {
         echo '], "last_seq":' . $lastSeq . '}';
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         echo '], "last_seq":' . $lastSeq . '}';
     }
 }
コード例 #4
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     switch ($action) {
         case "get_js_source":
             $jsName = AJXP_Utils::decodeSecureMagic($httpVars["object_name"]);
             $jsType = $httpVars["object_type"];
             // class or interface?
             $fName = "class." . strtolower($jsName) . ".js";
             if ($jsName == "Splitter") {
                 $fName = "splitter.js";
             }
             if (!defined("CLIENT_RESOURCES_FOLDER")) {
                 define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
             }
             // Locate the file class.ClassName.js
             if ($jsType == "class") {
                 $searchLocations = array(CLIENT_RESOURCES_FOLDER . "/js/ajaxplorer", CLIENT_RESOURCES_FOLDER . "/js/lib", AJXP_INSTALL_PATH . "/plugins/");
             } else {
                 if ($jsType == "interface") {
                     $searchLocations = array(CLIENT_RESOURCES_FOLDER . "/js/ajaxplorer/interfaces");
                 }
             }
             foreach ($searchLocations as $location) {
                 $dir_iterator = new RecursiveDirectoryIterator($location);
                 $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
                 // could use CHILD_FIRST if you so wish
                 $break = false;
                 foreach ($iterator as $file) {
                     if (strtolower(basename($file->getPathname())) == $fName) {
                         HTMLWriter::charsetHeader("text/plain", "utf-8");
                         echo file_get_contents($file->getPathname());
                         $break = true;
                         break;
                     }
                 }
                 if ($break) {
                     break;
                 }
             }
             break;
     }
 }
コード例 #5
0
 public function handleTasks($action, $httpVars, $fileVars)
 {
     $tasks = AJXP_Utils::loadSerialFile($this->getDbFile(), false, "json");
     switch ($action) {
         case "scheduler_addTask":
             if (isset($httpVars["task_id"])) {
                 foreach ($tasks as $index => $task) {
                     if ($task["task_id"] == $httpVars["task_id"]) {
                         $data = $task;
                         $theIndex = $index;
                     }
                 }
             }
             if (!isset($theIndex)) {
                 $data = array();
                 $data["task_id"] = substr(md5(time()), 0, 16);
             }
             $data["label"] = $httpVars["label"];
             $data["schedule"] = $httpVars["schedule"];
             $data["action_name"] = $httpVars["action_name"];
             $data["repository_id"] = $httpVars["repository_id"];
             $i = 1;
             while (array_key_exists("repository_id_" . $i, $httpVars)) {
                 $data["repository_id"] .= "," . $httpVars["repository_id_" . $i];
                 $i++;
             }
             $data["user_id"] = $httpVars["user_id"];
             $data["PARAMS"] = array();
             if (!empty($httpVars["param_name"]) && !empty($httpVars["param_value"])) {
                 $data["PARAMS"][$httpVars["param_name"]] = $httpVars["param_value"];
             }
             foreach ($httpVars as $key => $value) {
                 if (preg_match('/^param_name_/', $key)) {
                     $paramIndex = str_replace("param_name_", "", $key);
                     if (preg_match('/ajxptype/', $paramIndex)) {
                         continue;
                     }
                     if (preg_match('/replication/', $paramIndex)) {
                         continue;
                     }
                     if (isset($httpVars["param_value_" . $paramIndex])) {
                         $data["PARAMS"][$value] = $httpVars["param_value_" . $paramIndex];
                     }
                 }
             }
             if (isset($theIndex)) {
                 $tasks[$theIndex] = $data;
             } else {
                 $tasks[] = $data;
             }
             AJXP_Utils::saveSerialFile($this->getDbFile(), $tasks, true, false, "json");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage("Successfully added/edited task", null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "scheduler_removeTask":
             $this->removeTask($httpVars["task_id"]);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage("Successfully removed task", null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "scheduler_loadTask":
             $found = false;
             foreach ($tasks as $task) {
                 if ($task["task_id"] == $httpVars["task_id"]) {
                     $index = 0;
                     $found = true;
                     foreach ($task["PARAMS"] as $pName => $pValue) {
                         if ($index == 0) {
                             $task["param_name"] = $pName;
                             $task["param_value"] = $pValue;
                         } else {
                             $task["param_name_" . $index] = $pName;
                             $task["param_value_" . $index] = $pValue;
                         }
                         $index++;
                     }
                     unset($task["PARAMS"]);
                     if (strpos($task["repository_id"], ",") !== false) {
                         $ids = explode(",", $task["repository_id"]);
                         $task["repository_id"] = $ids[0];
                         for ($i = 1; $i < count($ids); $i++) {
                             $task["repository_id_" . $i] = $ids[$i];
                         }
                     }
                     break;
                 }
             }
             if ($found) {
                 HTMLWriter::charsetHeader("application/json");
                 echo json_encode($task);
             }
             break;
         default:
             break;
     }
     //var_dump($tasks);
 }
コード例 #6
0
 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;
 }
コード例 #7
0
 public function ajxpTableExists($actionName, $httpVars, $fileVars)
 {
     $p = $this->sqlDriver;
     if ($p["driver"] == "postgre") {
         $tableQuery = "SELECT [tablename] FROM [pg_catalog].[pg_tables] WHERE [tablename] = %s";
     } else {
         if ($p["driver"] == "sqlite3" || $p["driver"] == "sqlite") {
             $tableQuery = "SELECT [name] FROM [sqlite_master] WHERE type = \"table\" AND [name] = %s";
         } else {
             $tableQuery = "SHOW TABLES LIKE %s";
         }
     }
     $tableName = AJXP_Utils::sanitize($httpVars["table_name"], AJXP_SANITIZE_ALPHANUM);
     $tables = dibi::query($tableQuery, $tableName)->fetchPairs();
     $exists = count($tables) && in_array($tableName, $tables);
     HTMLWriter::charsetHeader("application/json");
     echo json_encode(array("result" => $exists));
 }
コード例 #8
0
 public function mailConsumeQueue($action, $httpVars, $fileVars)
 {
     if ($action === "consume_mail_queue") {
         $verbose = $httpVars["verbose"];
         $logInfo = function () {
         };
         if ($verbose) {
             $logInfo = function ($str) {
                 fwrite(STDOUT, $str . "\n");
             };
         }
         /** @var AjxpMailer $mailer */
         $mailer = AJXP_PluginsService::getInstance()->getActivePluginsForType("mailer", true);
         if (!dibi::isConnected()) {
             dibi::connect($this->getDibiDriver());
         }
         if ($this->_dibiDriver["driver"] == "postgre") {
             dibi::query("SET bytea_output=escape");
         }
         // Get the queue consumer lock and the time it was given
         $time = $this->getConsumerLock();
         try {
             $querySQL = dibi::query("SELECT * FROM [ajxp_mail_queue] WHERE [date_event] <= %s", $time);
         } catch (DibiException $e) {
             throw new AJXP_Exception($e->getMessage());
         }
         //$querySQL->fetch();
         //$resultsSQL = $querySQL->fetchAll();
         $numRows = $querySQL->count();
         $results = [];
         HTMLWriter::charsetHeader("text/json");
         if ($numRows == 0) {
             $logInfo("Nothing to process");
             $output = array("report" => "Sent 0 emails", "detail" => "");
             echo json_encode($output);
             return;
         }
         $logInfo("Processing " . $numRows . " rows.");
         // We need to send one email :
         // - per user
         // - per email type (HTML or PLAIN)
         while ($value = $querySQL->fetch()) {
             // Retrieving user information
             $recipient = $value['recipient'];
             // Retrieving Email type information
             $emailType = $value["html"] == 1 ? "html" : "plain";
             // Retrieving notification information
             /** @var AJXP_Notification $notification */
             $notification = unserialize($value["notification_object"]);
             $action = $notification->getAction();
             $author = $notification->getAuthor();
             $node = $notification->getNode();
             try {
                 @$node->loadNodeInfo();
             } catch (Exception $e) {
             }
             if ($node->isLeaf() && !$node->isRoot()) {
                 $dirName = $node->getParent()->getPath();
             } else {
                 $dirName = $node->getPath();
                 if ($dirName === null) {
                     $dirName = '/';
                 }
             }
             $key = sprintf("%s|%s|%s", $action, $author, $dirName);
             // Retrieving workspace information
             if ($node->getRepository() != null) {
                 $workspace = $node->getRepository()->getDisplay();
             } else {
                 $workspace = "Deleted Workspace";
             }
             $results[$emailType][$recipient][$workspace][$key][] = $notification;
         }
         $logInfo("Created digest array.");
         $subject = ConfService::getMessages()["core.mailer.9"];
         $success = 0;
         $errors = [];
         foreach ($results as $emailType => $recipients) {
             $isHTML = $emailType == "html";
             $i = 0;
             foreach ($recipients as $recipient => $workspaces) {
                 $logInfo("Processed " . ++$i . " out of " . count($recipients) . " " . $emailType . " emails " . $recipient);
                 $body = $this->_buildDigest($workspaces, $emailType);
                 try {
                     $mailer->sendMail([$recipient], $subject, $body, null, null, $isHTML);
                     $success++;
                 } catch (Exception $e) {
                     $errors[] = "Failed to send email to " . $recipient . ": " . $e->getMessage();
                 }
             }
         }
         // Clearing memory
         unset($results);
         try {
             dibi::query('DELETE FROM [ajxp_mail_queue] WHERE [date_event] <= %s', $time);
         } catch (DibiException $e) {
             throw new AJXP_Exception($e->getMessage());
         }
         $output = array("report" => "Sent " . $success . " emails", "errors" => $errors);
         echo json_encode($output);
     }
 }
コード例 #9
0
 /**
  * @param string $actionName
  * @param array $httpVars
  * @param array $fileVars
  */
 public function publishPermissionsMask($actionName, $httpVars, $fileVars)
 {
     $mask = array();
     HTMLWriter::charsetHeader("application/json");
     if (!AuthService::usersEnabled() || AuthService::getLoggedUser() == null) {
         print json_encode($mask);
         return;
     }
     $repoId = ConfService::getCurrentRepositoryId();
     $role = AuthService::getLoggedUser()->mergedRole;
     if ($role->hasMask($repoId)) {
         $fullMask = $role->getMask($repoId);
         foreach ($fullMask->flattenTree() as $path => $permission) {
             // Do not show if "deny".
             if ($permission->denies()) {
                 continue;
             }
             $mask[$path] = array("read" => $permission->canRead(), "write" => $permission->canWrite());
         }
     }
     print json_encode($mask);
     return;
 }
コード例 #10
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
         // Force legacy theme for the moment
         $this->pluginConf["GUI_THEME"] = "oxygen";
     }
     if (!defined("AJXP_THEME_FOLDER")) {
         define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
         define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]);
     }
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	GET AN HTML TEMPLATE
         //------------------------------------
         case "get_template":
             HTMLWriter::charsetHeader();
             $folder = CLIENT_RESOURCES_FOLDER . "/html";
             if (isset($httpVars["pluginName"])) {
                 $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]);
                 if (isset($httpVars["pluginPath"])) {
                     $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]);
                 }
             }
             $crtTheme = $this->pluginConf["GUI_THEME"];
             $thFolder = AJXP_THEME_FOLDER . "/html";
             if (isset($template_name)) {
                 if (is_file($thFolder . "/" . $template_name)) {
                     include $thFolder . "/" . $template_name;
                 } else {
                     if (is_file($folder . "/" . $template_name)) {
                         include $folder . "/" . $template_name;
                     }
                 }
             }
             break;
             //------------------------------------
             //	GET I18N MESSAGES
             //------------------------------------
         //------------------------------------
         //	GET I18N MESSAGES
         //------------------------------------
         case "get_i18n_messages":
             $refresh = false;
             if (isset($httpVars["lang"])) {
                 ConfService::setLanguage($httpVars["lang"]);
                 $refresh = true;
             }
             HTMLWriter::charsetHeader('text/javascript');
             HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh));
             break;
             //------------------------------------
             //	SEND XML REGISTRY
             //------------------------------------
         //------------------------------------
         //	SEND XML REGISTRY
         //------------------------------------
         case "get_xml_registry":
             $regDoc = AJXP_PluginsService::getXmlRegistry();
             $changes = AJXP_Controller::filterActionsRegistry($regDoc);
             if ($changes) {
                 AJXP_PluginsService::updateXmlRegistry($regDoc);
             }
             if (isset($_GET["xPath"])) {
                 $regPath = new DOMXPath($regDoc);
                 $nodes = $regPath->query($_GET["xPath"]);
                 AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $_GET["xPath"]));
                 if ($nodes->length) {
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML($nodes->item(0)));
                 }
                 AJXP_XMLWriter::close("ajxp_registry_part");
             } else {
                 AJXP_Utils::safeIniSet("zlib.output_compression", "4096");
                 header('Content-Type: application/xml; charset=UTF-8');
                 print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML());
             }
             break;
             //------------------------------------
             //	DISPLAY DOC
             //------------------------------------
         //------------------------------------
         //	DISPLAY DOC
         //------------------------------------
         case "display_doc":
             HTMLWriter::charsetHeader();
             echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($_GET["doc_file"])));
             break;
             //------------------------------------
             //	GET BOOT GUI
             //------------------------------------
         //------------------------------------
         //	GET BOOT GUI
         //------------------------------------
         case "get_boot_gui":
             header("X-UA-Compatible: chrome=1");
             HTMLWriter::charsetHeader();
             if (!is_file(TESTS_RESULT_FILE)) {
                 $outputArray = array();
                 $testedParams = array();
                 $passed = AJXP_Utils::runTests($outputArray, $testedParams);
                 if (!$passed && !isset($_GET["ignore_tests"])) {
                     die(AJXP_Utils::testResultsToTable($outputArray, $testedParams));
                 } else {
                     AJXP_Utils::testResultsToFile($outputArray, $testedParams);
                 }
             }
             $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop");
             if (AuthService::usersEnabled()) {
                 AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : "");
                 AuthService::bootSequence($START_PARAMETERS);
                 if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) {
                     if (AuthService::getDefaultRootId() == -1) {
                         AuthService::disconnect();
                     } else {
                         $loggedUser = AuthService::getLoggedUser();
                         if (!$loggedUser->canRead(ConfService::getCurrentRootDirIndex()) && AuthService::getDefaultRootId() != ConfService::getCurrentRootDirIndex()) {
                             ConfService::switchRootDir(AuthService::getDefaultRootId());
                         }
                     }
                 }
             }
             AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION);
             $confErrors = ConfService::getErrors();
             if (count($confErrors)) {
                 $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors));
             }
             $JSON_START_PARAMETERS = json_encode($START_PARAMETERS);
             $crtTheme = $this->pluginConf["GUI_THEME"];
             if (ConfService::getConf("JS_DEBUG")) {
                 if (!isset($mess)) {
                     $mess = ConfService::getMessages();
                 }
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html";
                 } else {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html");
                 } else {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html");
                 }
                 if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
                     $content = str_replace("ajaxplorer_boot.js", "ajaxplorer_boot_protolegacy.js", $content);
                 }
                 $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false);
                 if ($JSON_START_PARAMETERS) {
                     $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content);
                 }
                 print $content;
             }
             break;
             //------------------------------------
             //	GET CONFIG FOR BOOT
             //------------------------------------
         //------------------------------------
         //	GET CONFIG FOR BOOT
         //------------------------------------
         case "get_boot_conf":
             if (isset($_GET["server_prefix_uri"])) {
                 $_SESSION["AJXP_SERVER_PREFIX_URI"] = $_GET["server_prefix_uri"];
             }
             $config = array();
             $config["ajxpResourcesFolder"] = "plugins/gui.ajax/res";
             $config["ajxpServerAccess"] = AJXP_SERVER_ACCESS;
             $config["zipEnabled"] = ConfService::zipEnabled();
             $config["multipleFilesDownloadEnabled"] = ConfService::getCoreConf("ZIP_CREATION");
             $config["customWording"] = array("welcomeMessage" => $this->pluginConf["CUSTOM_WELCOME_MESSAGE"], "title" => ConfService::getCoreConf("APPLICATION_TITLE"), "icon" => $this->pluginConf["CUSTOM_ICON"], "iconWidth" => $this->pluginConf["CUSTOM_ICON_WIDTH"], "iconHeight" => $this->pluginConf["CUSTOM_ICON_HEIGHT"], "iconOnly" => $this->pluginConf["CUSTOM_ICON_ONLY"], "titleFontSize" => $this->pluginConf["CUSTOM_FONT_SIZE"]);
             $config["usersEnabled"] = AuthService::usersEnabled();
             $config["loggedUser"] = AuthService::getLoggedUser() != null;
             $config["currentLanguage"] = ConfService::getLanguage();
             $config["session_timeout"] = intval(ini_get("session.gc_maxlifetime"));
             if (!isset($this->pluginConf["CLIENT_TIMEOUT_TIME"]) || $this->pluginConf["CLIENT_TIMEOUT_TIME"] == "") {
                 $to = $config["session_timeout"];
             } else {
                 $to = $this->pluginConf["CLIENT_TIMEOUT_TIME"];
             }
             $config["client_timeout"] = $to;
             $config["client_timeout_warning"] = $this->pluginConf["CLIENT_TIMEOUT_WARN"];
             $config["availableLanguages"] = ConfService::getConf("AVAILABLE_LANG");
             $config["usersEditable"] = ConfService::getAuthDriverImpl()->usersEditable();
             $config["ajxpVersion"] = AJXP_VERSION;
             $config["ajxpVersionDate"] = AJXP_VERSION_DATE;
             if (stristr($_SERVER["HTTP_USER_AGENT"], "msie 6")) {
                 $config["cssResources"] = array("css/pngHack/pngHack.css");
             }
             if (!empty($this->pluginConf['GOOGLE_ANALYTICS_ID'])) {
                 $config["googleAnalyticsData"] = array("id" => $this->pluginConf['GOOGLE_ANALYTICS_ID'], "domain" => $this->pluginConf['GOOGLE_ANALYTICS_DOMAIN'], "event" => $this->pluginConf['GOOGLE_ANALYTICS_EVENT']);
             }
             $config["i18nMessages"] = ConfService::getMessages();
             $config["password_min_length"] = ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth");
             $config["SECURE_TOKEN"] = AuthService::generateSecureToken();
             $config["streaming_supported"] = "true";
             $config["theme"] = $this->pluginConf["GUI_THEME"];
             header("Content-type:application/json;charset=UTF-8");
             print json_encode($config);
             break;
         default:
             break;
     }
     return false;
 }
コード例 #11
0
 public function switchAction($actionName, $httpVars, $fileVars)
 {
     $this->baseURL = rtrim($this->getFilteredOption("ETHERPAD_SERVER"), "/");
     $this->apiKey = $this->getFilteredOption("ETHERPAD_APIKEY");
     $userSelection = new UserSelection(ConfService::getRepository(), $httpVars);
     if ($userSelection->isEmpty()) {
         throw new Exception("Empty selection");
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $selectedNode = $userSelection->getUniqueNode();
     $selectedNode->loadNodeInfo();
     if (!$selectedNode->isLeaf()) {
         throw new Exception("Cannot handle folders, please select a file!");
     }
     $nodeExtension = strtolower(pathinfo($selectedNode->getPath(), PATHINFO_EXTENSION));
     // Determine pad ID
     if ($nodeExtension == "pad") {
         $padID = file_get_contents($selectedNode->getUrl());
     } else {
         // TRY TO LOAD PAD ID FROM NODE SHARED METADATA
         $metadata = $selectedNode->retrieveMetadata("etherpad", AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         if (isset($metadata["pad_id"])) {
             $padID = $metadata["pad_id"];
         } else {
             $padID = AJXP_Utils::generateRandomString();
             $selectedNode->setMetadata("etherpad", array("pad_id" => $padID), AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         }
     }
     require_once "etherpad-client/etherpad-lite-client.php";
     $client = new EtherpadLiteClient($this->apiKey, $this->baseURL . "/api");
     $loggedUser = AuthService::getLoggedUser();
     $userName = $loggedUser->getId();
     $userLabel = $loggedUser->mergedRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userName);
     $res = $client->createAuthorIfNotExistsFor($userName, $userLabel);
     $authorID = $res->authorID;
     $res2 = $client->createGroupIfNotExistsFor($loggedUser->getGroupPath());
     $groupID = $res2->groupID;
     $fullId = $groupID . "\$" . $padID;
     if ($actionName == "etherpad_create") {
         $resP = $client->listPads($groupID);
         $currentContent = file_get_contents($selectedNode->getUrl());
         if ($nodeExtension == "html" && strpos($currentContent, "<html>") === false) {
             $currentContent = "<html><head></head><body>{$currentContent}</body></html>";
         }
         if (!in_array($fullId, $resP->padIDs)) {
             $client->createGroupPad($groupID, $padID, null);
             if ($nodeExtension == "html" && !empty($currentContent)) {
                 $client->setHTML($fullId, $currentContent);
             } else {
                 if ($nodeExtension != "pad") {
                     $client->setText($fullId, $currentContent);
                 }
             }
         } else {
             if ($nodeExtension != "pad") {
                 // If someone is already connected, do not override.
                 $existingAuthors = $client->listAuthorsOfPad($fullId);
                 if (!count($existingAuthors->authorIDs)) {
                     if ($nodeExtension == "html" && !empty($currentContent)) {
                         $client->setHTML($fullId, $currentContent);
                     } else {
                         $client->setText($fullId, $currentContent);
                     }
                 }
             }
         }
         $res4 = $client->createSession($groupID, $authorID, time() + 14400);
         $sessionID = $res4->sessionID;
         setcookie('sessionID', $sessionID, null, "/");
         $padID = $groupID . '$' . $padID;
         $data = array("url" => $this->baseURL . "/p/" . $padID, "padID" => $padID, "sessionID" => $sessionID);
         HTMLWriter::charsetHeader('application/json');
         echo json_encode($data);
     } else {
         if ($actionName == "etherpad_save") {
             $padID = $httpVars["pad_id"];
             if ($nodeExtension == "html" || $nodeExtension == "pad") {
                 $res = $client->getHTML($padID);
                 $content = $res->html;
             } else {
                 $res = $client->getText($padID);
                 $content = $res->text;
             }
             if ($nodeExtension == "pad") {
                 // Create a new file and save the content in it.
                 $origUrl = $selectedNode->getUrl();
                 $mess = ConfService::getMessages();
                 $dateStamp = date(" Y-m-d H:i", time());
                 $startUrl = preg_replace('"\\.pad$"', $dateStamp . '.html', $origUrl);
                 $newNode = new AJXP_Node($startUrl);
                 AJXP_Controller::applyHook("node.before_create", array($newNode, strlen($content)));
                 file_put_contents($newNode->getUrl(), $content);
                 AJXP_Controller::applyHook("node.change", array(null, $newNode));
             } else {
                 AJXP_Controller::applyHook("node.before_change", array($selectedNode, strlen($content)));
                 file_put_contents($selectedNode->getUrl(), $content);
                 clearstatcache(true, $selectedNode->getUrl());
                 $selectedNode->loadNodeInfo(true);
                 AJXP_Controller::applyHook("node.change", array($selectedNode, $selectedNode));
             }
         } else {
             if ($actionName == "etherpad_close") {
                 // WE SHOULD DETECT IF THERE IS NOBODY CONNECTED ANYMORE, AND DELETE THE PAD.
                 // BUT SEEMS LIKE THERE'S NO WAY TO PROPERLY REMOVE AN AUTHOR VIA API
                 $sessionID = $httpVars["session_id"];
                 $client->deleteSession($sessionID);
             } else {
                 if ($actionName == "etherpad_proxy_api") {
                     if ($httpVars["api_action"] == "list_pads") {
                         $res = $client->listPads($groupID);
                     } else {
                         if ($httpVars["api_action"] == "list_authors_for_pad") {
                             $res = $client->listAuthorsOfPad($httpVars["pad_id"]);
                         }
                     }
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($res);
                 } else {
                     if ($actionName == "etherpad_get_content") {
                         HTMLWriter::charsetHeader("text/plain");
                         echo $client->getText($httpVars["pad_id"])->text;
                     }
                 }
             }
         }
     }
     return null;
 }
コード例 #12
0
ファイル: runTests.php プロジェクト: floffel03/pydio-core
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                echo "\n\nNo change detected reflecting file deletion, this is not normal, exiting.";
                var_dump($data);
                exit;
            }
        } else {
            echo "\n\nData not decoded as JSON, normal?";
            var_dump($data);
            exit;
        }
        echo "<script>window.scrollTo(0, 100000);</script>";
        //echo "</pre>";
    } else {
        $host = $_SERVER["HTTP_HOST"];
        $protocol = $_SERVER["HTTPS"] === "on" ? "https" : "http";
        $path = dirname($_SERVER["REQUEST_URI"]);
        HTMLWriter::charsetHeader();
        require AJXP_TESTS_FOLDER . "/api_test.phtml";
    }
} else {
    $outputArray = array();
    $testedParams = array();
    $passed = true;
    $passed = AJXP_Utils::runTests($outputArray, $testedParams);
    AJXP_Utils::testResultsToTable($outputArray, $testedParams, true);
    AJXP_Utils::testResultsToFile($outputArray, $testedParams);
}
コード例 #13
0
 /**
  * @param array $data
  * @param array $options
  * @param ShareStore $shareStore
  */
 public static function render($data, $options, $shareStore)
 {
     if (isset($data["SECURITY_MODIFIED"]) && $data["SECURITY_MODIFIED"] === true) {
         self::renderError($data, "false");
         return;
     }
     // create driver from $data
     $className = $data["DRIVER"] . "AccessDriver";
     $u = parse_url($_SERVER["REQUEST_URI"]);
     $shortHash = pathinfo(basename($u["path"]), PATHINFO_FILENAME);
     // Load language messages
     $language = ConfService::getLanguage();
     if (isset($_GET["lang"])) {
         $language = basename($_GET["lang"]);
     }
     $messages = array();
     if (is_file(dirname(__FILE__) . "/res/i18n/" . $language . ".php")) {
         include dirname(__FILE__) . "/res/i18n/" . $language . ".php";
     } else {
         include dirname(__FILE__) . "/res/i18n/en.php";
     }
     if (isset($mess)) {
         $messages = $mess;
     }
     $AJXP_LINK_HAS_PASSWORD = false;
     $AJXP_LINK_BASENAME = SystemTextEncoding::toUTF8(basename($data["FILE_PATH"]));
     AJXP_PluginsService::getInstance()->initActivePlugins();
     ConfService::setLanguage($language);
     $mess = ConfService::getMessages();
     if ($shareStore->isShareExpired($shortHash, $data)) {
         self::renderError(array(), $shortHash, $mess["share_center.165"]);
         return;
     }
     $customs = array("title", "legend", "legend_pass", "background_attributes_1", "text_color", "background_color", "textshadow_color");
     $images = array("button", "background_1");
     $confs = $options;
     $confs["CUSTOM_SHAREPAGE_BACKGROUND_ATTRIBUTES_1"] = "background-repeat:repeat;background-position:50% 50%;";
     $confs["CUSTOM_SHAREPAGE_BACKGROUND_1"] = "plugins/action.share/res/hi-res/02.jpg";
     $confs["CUSTOM_SHAREPAGE_TEXT_COLOR"] = "#ffffff";
     $confs["CUSTOM_SHAREPAGE_TEXTSHADOW_COLOR"] = "rgba(0,0,0,5)";
     foreach ($customs as $custom) {
         $varName = "CUSTOM_SHAREPAGE_" . strtoupper($custom);
         ${$varName} = $confs[$varName];
     }
     $dlFolder = realpath(ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"));
     foreach ($images as $custom) {
         $varName = "CUSTOM_SHAREPAGE_" . strtoupper($custom);
         if (!empty($confs[$varName])) {
             if (strpos($confs[$varName], "plugins/") === 0 && is_file(AJXP_INSTALL_PATH . "/" . $confs[$varName])) {
                 $realFile = AJXP_INSTALL_PATH . "/" . $confs[$varName];
                 copy($realFile, $dlFolder . "/binary-" . basename($realFile));
                 ${$varName} = "binary-" . basename($realFile);
             } else {
                 ${$varName} = "binary-" . $confs[$varName];
                 if (is_file($dlFolder . "/binary-" . $confs[$varName])) {
                     continue;
                 }
                 $copiedImageName = $dlFolder . "/binary-" . $confs[$varName];
                 $imgFile = fopen($copiedImageName, "wb");
                 ConfService::getConfStorageImpl()->loadBinary(array(), $confs[$varName], $imgFile);
                 fclose($imgFile);
             }
         }
     }
     HTMLWriter::charsetHeader();
     // Check password
     if (strlen($data["PASSWORD"])) {
         if (!isset($_POST['password']) || $_POST['password'] != $data["PASSWORD"]) {
             $AJXP_LINK_HAS_PASSWORD = true;
             $AJXP_LINK_WRONG_PASSWORD = isset($_POST['password']) && $_POST['password'] != $data["PASSWORD"];
             include AJXP_INSTALL_PATH . "/plugins/action.share/res/public_links.php";
             $res = '<div style="position: absolute;z-index: 10000; bottom: 0; right: 0; color: #666;font-family: HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size: 13px;text-align: right;padding: 6px; line-height: 20px;text-shadow: 0px 1px 0px white;" class="no_select_bg"><br>Build your own box with Pydio : <a style="color: #000000;" target="_blank" href="http://pyd.io/">http://pyd.io/</a><br/>Community - Free non supported version © C. du Jeu 2008-2014 </div>';
             AJXP_Controller::applyHook("tpl.filter_html", array(&$res));
             echo $res;
             return;
         }
     } else {
         if (!isset($_GET["dl"])) {
             include AJXP_INSTALL_PATH . "/plugins/action.share/res/public_links.php";
             $res = '<div style="position: absolute;z-index: 10000; bottom: 0; right: 0; color: #666;font-family: HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size: 13px;text-align: right;padding: 6px; line-height: 20px;text-shadow: 0px 1px 0px white;" class="no_select_bg"><br>Build your own box with Pydio : <a style="color: #000000;" target="_blank" href="http://pyd.io/">http://pyd.io/</a><br/>Community - Free non supported version © C. du Jeu 2008-2014 </div>';
             AJXP_Controller::applyHook("tpl.filter_html", array(&$res));
             echo $res;
             return;
         }
     }
     $filePath = AJXP_INSTALL_PATH . "/plugins/access." . $data["DRIVER"] . "/class." . $className . ".php";
     if (!is_file($filePath)) {
         die("Warning, cannot find driver for conf storage! ({$className}, {$filePath})");
     }
     require_once $filePath;
     $driver = new $className($data["PLUGIN_ID"], $data["BASE_DIR"]);
     $driver->loadManifest();
     //$hash = md5(serialize($data));
     $shareStore->incrementDownloadCounter($shortHash);
     //AuthService::logUser($data["OWNER_ID"], "", true);
     AuthService::logTemporaryUser($data["OWNER_ID"], $shortHash);
     if (isset($data["SAFE_USER"]) && isset($data["SAFE_PASS"])) {
         // FORCE SESSION MODE
         AJXP_Safe::getInstance()->forceSessionCredentialsUsage();
         AJXP_Safe::storeCredentials($data["SAFE_USER"], $data["SAFE_PASS"]);
     }
     $repoObject = $data["REPOSITORY"];
     ConfService::switchRootDir($repoObject->getId());
     ConfService::loadRepositoryDriver();
     AJXP_PluginsService::getInstance()->initActivePlugins();
     try {
         $params = array("file" => SystemTextEncoding::toUTF8($data["FILE_PATH"]));
         if (isset($data["PLUGINS_DATA"])) {
             $params["PLUGINS_DATA"] = $data["PLUGINS_DATA"];
         }
         if (isset($_GET["ct"]) && $_GET["ct"] == "true") {
             $mime = pathinfo($params["file"], PATHINFO_EXTENSION);
             $editors = AJXP_PluginsService::searchAllManifests("//editor[contains(@mimes,'{$mime}') and @previewProvider='true']", "node", true, true, false);
             if (count($editors)) {
                 foreach ($editors as $editor) {
                     $xPath = new DOMXPath($editor->ownerDocument);
                     $callbacks = $xPath->query("//action[@contentTypedProvider]", $editor);
                     if ($callbacks->length) {
                         $data["ACTION"] = $callbacks->item(0)->getAttribute("name");
                         if ($data["ACTION"] == "audio_proxy") {
                             $params["file"] = base64_encode($params["file"]);
                         }
                         break;
                     }
                 }
             }
         }
         AJXP_Controller::findActionAndApply($data["ACTION"], $params, null);
         register_shutdown_function(array("AuthService", "clearTemporaryUser"), $shortHash);
     } catch (Exception $e) {
         AuthService::clearTemporaryUser($shortHash);
         die($e->getMessage());
     }
 }
コード例 #14
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	SWITCH THE ROOT REPOSITORY
         //------------------------------------
         case "switch_repository":
             if (!isset($repository_id)) {
                 break;
             }
             $dirList = ConfService::getRepositoriesList();
             /** @var $repository_id string */
             if (!isset($dirList[$repository_id])) {
                 $errorMessage = "Trying to switch to an unkown repository!";
                 break;
             }
             ConfService::switchRootDir($repository_id);
             // Load try to init the driver now, to trigger an exception
             // if it's not loading right.
             ConfService::loadRepositoryDriver();
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $user = AuthService::getLoggedUser();
                 $activeRepId = ConfService::getCurrentRootDirIndex();
                 $user->setArrayPref("history", "last_repository", $activeRepId);
                 $user->save("user");
             }
             //$logMessage = "Successfully Switched!";
             AJXP_Logger::logAction("Switch Repository", array("rep. id" => $repository_id));
             break;
             //------------------------------------
             //	BOOKMARK BAR
             //------------------------------------
         //------------------------------------
         //	BOOKMARK BAR
         //------------------------------------
         case "get_bookmarks":
             $bmUser = null;
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser = AuthService::getLoggedUser();
             } else {
                 if (!AuthService::usersEnabled()) {
                     $confStorage = ConfService::getConfStorageImpl();
                     $bmUser = $confStorage->createUserObject("shared");
                 }
             }
             if ($bmUser == null) {
                 exit(1);
             }
             if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) {
                 if ($httpVars["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($httpVars["bm_title"])) {
                         $title = $httpVars["bm_title"];
                     }
                     if ($title == "" && $httpVars["bm_path"] == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark(SystemTextEncoding::magicDequote($httpVars["bm_path"]), SystemTextEncoding::magicDequote($title));
                 } else {
                     if ($httpVars["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($httpVars["bm_path"]);
                     } else {
                         if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) {
                             $bmUser->renameBookmark($httpVars["bm_path"], $httpVars["bm_title"]);
                         }
                     }
                 }
             }
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser->save("user");
                 AuthService::updateUser($bmUser);
             } else {
                 if (!AuthService::usersEnabled()) {
                     $bmUser->save("user");
                 }
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks());
             AJXP_XMLWriter::close();
             exit(1);
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "save_user_pref":
             $userObject = AuthService::getLoggedUser();
             $i = 0;
             while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && $userObject == null) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save("user");
                 AuthService::updateUser($userObject);
                 //setcookie("AJXP_$prefName", $prefValue);
                 $i++;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             exit(1);
             break;
             //------------------------------------
             // WEBDAV PREFERENCES
             //------------------------------------
         //------------------------------------
         // WEBDAV PREFERENCES
         //------------------------------------
         case "webdav_preferences":
             $userObject = AuthService::getLoggedUser();
             $webdavActive = false;
             $passSet = false;
             // Detect http/https and host
             if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") {
                 $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST");
             } else {
                 $baseURL = AJXP_Utils::detectServerURL();
             }
             $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/";
             if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) {
                 $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
                 if (!empty($httpVars["activate"])) {
                     $activate = $httpVars["activate"] == "true" ? true : false;
                     if (empty($davData)) {
                         $davData = array();
                     }
                     $davData["ACTIVE"] = $activate;
                 }
                 if (!empty($httpVars["webdav_pass"])) {
                     $password = $httpVars["webdav_pass"];
                     if (function_exists('mcrypt_encrypt')) {
                         $user = $userObject->getId();
                         $secret = defined("AJXP_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#";
                         $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
                         $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB, $iv));
                     }
                     $davData["PASS"] = $password;
                 }
                 $userObject->setPref("AJXP_WEBDAV_DATA", $davData);
                 $userObject->save("user");
             }
             $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
             if (!empty($davData)) {
                 $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true;
                 $passSet = isset($davData["PASS"]);
             }
             $repoList = ConfService::getRepositoriesList();
             $davRepos = array();
             $loggedUser = AuthService::getLoggedUser();
             foreach ($repoList as $repoIndex => $repoObject) {
                 $accessType = $repoObject->getAccessType();
                 $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType);
                 if (is_a($driver, "AjxpWebdavProvider") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) {
                     $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug());
                 }
             }
             $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos);
             HTMLWriter::charsetHeader("application/json");
             print json_encode($prefs);
             break;
         case "get_user_template_logo":
             $tplId = $httpVars["template_id"];
             $iconFormat = $httpVars["icon_format"];
             $repo = ConfService::getRepositoryById($tplId);
             $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat));
             if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) {
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo);
             } else {
                 $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png";
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo);
             }
             break;
         case "get_user_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $repositories = ConfService::getRepositoriesList();
             $pServ = AJXP_PluginsService::getInstance();
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 if (!$repo->getOption("TPL_USER_CAN_CREATE")) {
                     continue;
                 }
                 $repoId = $repo->getUniqueId();
                 $repoLabel = $repo->getDisplay();
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 $driverPlug = $pServ->getPluginByTypeName("access", $repoType);
                 $params = $driverPlug->getManifestRawContent("//param", "node");
                 $tplDefined = $repo->getOptionsDefined();
                 $defaultLabel = '';
                 foreach ($params as $paramNode) {
                     $name = $paramNode->getAttribute("name");
                     if (strpos($name, "TPL_") === 0) {
                         if ($name == "TPL_DEFAULT_LABEL") {
                             $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name));
                         }
                         continue;
                     }
                     if (in_array($paramNode->getAttribute("name"), $tplDefined)) {
                         continue;
                     }
                     if ($paramNode->getAttribute('no_templates') == 'true') {
                         continue;
                     }
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode));
                 }
                 // ADD LABEL
                 echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>';
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "user_create_repository":
             $tplId = $httpVars["template_id"];
             $tplRepo = ConfService::getRepositoryById($tplId);
             $options = array();
             self::parseParameters($httpVars, $options);
             $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, AuthService::getLoggedUser()->getId());
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[426]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 // Make sure we do not overwrite otherwise loaded rights.
                 $loggedUser->load();
                 $loggedUser->setRight($newRep->getUniqueId(), "rw");
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[425], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "user_delete_repository":
             $repoId = $httpVars["repository_id"];
             $repository = ConfService::getRepositoryById($repoId);
             if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("You are not allowed to perform this operation!");
             }
             $res = ConfService::deleteRepository($repoId);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[427]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 // Make sure we do not override remotely set rights
                 $loggedUser->load();
                 $loggedUser->removeRights($repoId);
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[428], null);
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if (isset($requireAuth)) {
         $xmlBuffer .= AJXP_XMLWriter::requireAuth(false);
     }
     return $xmlBuffer;
 }
コード例 #15
0
 public function extractExif($actionName, $httpVars, $fileVars)
 {
     $repo = $this->accessDriver->repository;
     $userSelection = new UserSelection($this->accessDriver->repository, $httpVars);
     $repo->detectStreamWrapper(true);
     $selectedNode = $userSelection->getUniqueNode();
     $realFile = AJXP_MetaStreamWrapper::getRealFSReference($selectedNode->getUrl());
     AJXP_Utils::safeIniSet('exif.encode_unicode', 'UTF-8');
     $exifData = @exif_read_data($realFile, 0, TRUE);
     if ($exifData === false || !is_array($exifData)) {
         return;
     }
     if ($exifData !== false && isset($exifData["GPS"])) {
         $exifData["COMPUTED_GPS"] = $this->convertGPSData($exifData);
     }
     $iptc = $this->extractIPTC($realFile);
     if (count($iptc)) {
         $exifData["IPTC"] = $iptc;
     }
     $excludeTags = array();
     // array("componentsconfiguration", "filesource", "scenetype", "makernote", "datadump");
     $format = "xml";
     if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
         $format = "json";
     }
     $filteredData = array();
     foreach ($exifData as $section => $data) {
         $filteredData[$section] = array();
         foreach ($data as $key => $value) {
             if (is_array($value)) {
                 $value = implode(",", $value);
             }
             if (in_array(strtolower($key), $excludeTags)) {
                 continue;
             }
             if (strpos($key, "UndefinedTag:") === 0) {
                 continue;
             }
             $value = preg_replace('/[^[:print:]]/', '', $value);
             $filteredData[$section][$key] = SystemTextEncoding::toUTF8($value);
         }
     }
     if ($format == "xml") {
         AJXP_XMLWriter::header("metadata", array("file" => $selectedNode->getPath(), "type" => "EXIF"));
         foreach ($filteredData as $section => $data) {
             print "<exifSection name='{$section}'>";
             foreach ($data as $key => $value) {
                 print "<exifTag name=\"{$key}\">" . AJXP_Utils::xmlEntities($value) . "</exifTag>";
             }
             print "</exifSection>";
         }
         AJXP_XMLWriter::close("metadata");
     } else {
         HTMLWriter::charsetHeader("application/json");
         echo json_encode($filteredData);
     }
 }
コード例 #16
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!defined("AJXP_THEME_FOLDER")) {
         define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
         define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]);
     }
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	GET AN HTML TEMPLATE
         //------------------------------------
         case "get_template":
             HTMLWriter::charsetHeader();
             $folder = CLIENT_RESOURCES_FOLDER . "/html";
             if (isset($httpVars["pluginName"])) {
                 $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]);
                 if (isset($httpVars["pluginPath"])) {
                     $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]);
                 }
             }
             $thFolder = AJXP_THEME_FOLDER . "/html";
             if (isset($template_name)) {
                 if (is_file($thFolder . "/" . $template_name)) {
                     include $thFolder . "/" . $template_name;
                 } else {
                     if (is_file($folder . "/" . $template_name)) {
                         include $folder . "/" . $template_name;
                     }
                 }
             }
             break;
             //------------------------------------
             //	GET I18N MESSAGES
             //------------------------------------
         //------------------------------------
         //	GET I18N MESSAGES
         //------------------------------------
         case "get_i18n_messages":
             $refresh = false;
             if (isset($httpVars["lang"])) {
                 ConfService::setLanguage($httpVars["lang"]);
                 $refresh = true;
             }
             if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
                 HTMLWriter::charsetHeader("application/json");
                 echo json_encode(ConfService::getMessages($refresh));
             } else {
                 HTMLWriter::charsetHeader('text/javascript');
                 HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh));
             }
             break;
             //------------------------------------
             //	DISPLAY DOC
             //------------------------------------
         //------------------------------------
         //	DISPLAY DOC
         //------------------------------------
         case "display_doc":
             HTMLWriter::charsetHeader();
             echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($httpVars["doc_file"])));
             break;
             //------------------------------------
             //	GET BOOT GUI
             //------------------------------------
         //------------------------------------
         //	GET BOOT GUI
         //------------------------------------
         case "get_boot_gui":
             HTMLWriter::internetExplorerMainDocumentHeader();
             HTMLWriter::charsetHeader();
             if (!is_file(TESTS_RESULT_FILE)) {
                 $outputArray = array();
                 $testedParams = array();
                 $passed = AJXP_Utils::runTests($outputArray, $testedParams);
                 if (!$passed && !isset($httpVars["ignore_tests"])) {
                     AJXP_Utils::testResultsToTable($outputArray, $testedParams);
                     die;
                 } else {
                     AJXP_Utils::testResultsToFile($outputArray, $testedParams);
                 }
             }
             $root = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
             $configUrl = ConfService::getCoreConf("SERVER_URL");
             if (!empty($configUrl)) {
                 $root = '/' . ltrim(parse_url($configUrl, PHP_URL_PATH), '/');
                 if (strlen($root) > 1) {
                     $root = rtrim($root, '/') . '/';
                 }
             } else {
                 preg_match('/ws-(.)*\\/|settings|dashboard|welcome|user/', $root, $matches, PREG_OFFSET_CAPTURE);
                 if (count($matches)) {
                     $capture = $matches[0][1];
                     $root = substr($root, 0, $capture);
                 }
             }
             $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop", "APPLICATION_ROOT" => $root, "REBASE" => $root);
             if (AuthService::usersEnabled()) {
                 AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : "");
                 AuthService::bootSequence($START_PARAMETERS);
                 if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) {
                     if (AuthService::getDefaultRootId() == -1) {
                         AuthService::disconnect();
                     } else {
                         $loggedUser = AuthService::getLoggedUser();
                         if (!$loggedUser->canRead(ConfService::getCurrentRepositoryId()) && AuthService::getDefaultRootId() != ConfService::getCurrentRepositoryId()) {
                             ConfService::switchRootDir(AuthService::getDefaultRootId());
                         }
                     }
                 }
             }
             AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION);
             $confErrors = ConfService::getErrors();
             if (count($confErrors)) {
                 $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors));
             }
             // PRECOMPUTE BOOT CONF
             if (!preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) && !preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
                 $preloadedBootConf = $this->computeBootConf();
                 AJXP_Controller::applyHook("loader.filter_boot_conf", array(&$preloadedBootConf));
                 $START_PARAMETERS["PRELOADED_BOOT_CONF"] = $preloadedBootConf;
             }
             // PRECOMPUTE REGISTRY
             if (!isset($START_PARAMETERS["FORCE_REGISTRY_RELOAD"])) {
                 $clone = ConfService::getFilteredXMLRegistry(true, true);
                 $clonePath = new DOMXPath($clone);
                 $serverCallbacks = $clonePath->query("//serverCallback|hooks");
                 foreach ($serverCallbacks as $callback) {
                     $callback->parentNode->removeChild($callback);
                 }
                 $START_PARAMETERS["PRELOADED_REGISTRY"] = AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML());
             }
             $JSON_START_PARAMETERS = json_encode($START_PARAMETERS);
             $crtTheme = $this->pluginConf["GUI_THEME"];
             $additionalFrameworks = $this->getFilteredOption("JS_RESOURCES_BEFORE");
             $ADDITIONAL_FRAMEWORKS = "";
             if (!empty($additionalFrameworks)) {
                 $frameworkList = explode(",", $additionalFrameworks);
                 foreach ($frameworkList as $index => $framework) {
                     $frameworkList[$index] = '<script language="javascript" type="text/javascript" src="' . $framework . '"></script>' . "\n";
                 }
                 $ADDITIONAL_FRAMEWORKS = implode("", $frameworkList);
             }
             if (ConfService::getConf("JS_DEBUG")) {
                 if (!isset($mess)) {
                     $mess = ConfService::getMessages();
                 }
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html";
                 } else {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html");
                 } else {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html");
                 }
                 if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT'])) {
                     $ADDITIONAL_FRAMEWORKS = "";
                 }
                 $content = str_replace("AJXP_ADDITIONAL_JS_FRAMEWORKS", $ADDITIONAL_FRAMEWORKS, $content);
                 $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false);
                 $content = str_replace("AJXP_REBASE", isset($START_PARAMETERS["REBASE"]) ? '<base href="' . $START_PARAMETERS["REBASE"] . '"/>' : "", $content);
                 if ($JSON_START_PARAMETERS) {
                     $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content);
                 }
                 print $content;
             }
             break;
             //------------------------------------
             //	GET CONFIG FOR BOOT
             //------------------------------------
         //------------------------------------
         //	GET CONFIG FOR BOOT
         //------------------------------------
         case "get_boot_conf":
             $out = array();
             AJXP_Utils::parseApplicationGetParameters($_GET, $out, $_SESSION);
             $config = $this->computeBootConf();
             header("Content-type:application/json;charset=UTF-8");
             print json_encode($config);
             break;
         default:
             break;
     }
     return false;
 }
コード例 #17
0
 public function clearCacheByNS($actionName, $httpVars, $fileVars)
 {
     $ns = AJXP_Utils::sanitize($httpVars["namespace"], AJXP_SANITIZE_ALPHANUM);
     if ($ns == AJXP_CACHE_SERVICE_NS_SHARED) {
         ConfService::clearAllCaches();
     } else {
         CacheService::deleteAll($ns);
     }
     HTMLWriter::charsetHeader("text/json");
     echo json_encode(["result" => "ok"]);
 }
コード例 #18
0
 /**
  * Transmit to the ajxp_conf load_plugin_manifest action
  * @param $action
  * @param $httpVars
  * @param $fileVars
  */
 public function applyInstallerForm($action, $httpVars, $fileVars)
 {
     $data = array();
     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "");
     // Create a custom bootstrap.json file
     $coreConf = array();
     $coreAuth = array();
     $this->_loadPluginConfig("core.conf", $coreConf);
     $this->_loadPluginConfig("core.auth", $coreAuth);
     if (!isset($coreConf["UNIQUE_INSTANCE_CONFIG"])) {
         $coreConf["UNIQUE_INSTANCE_CONFIG"] = array();
     }
     if (!isset($coreAuth["MASTER_INSTANCE_CONFIG"])) {
         $coreAuth["MASTER_INSTANCE_CONFIG"] = array();
     }
     $coreConf["AJXP_CLI_SECRET_KEY"] = AJXP_Utils::generateRandomString(24, true);
     $storageType = $data["STORAGE_TYPE"]["type"];
     if ($storageType == "db") {
         // REWRITE BOOTSTRAP.JSON
         $coreConf["DIBI_PRECONFIGURATION"] = $data["STORAGE_TYPE"]["db_type"];
         if (isset($coreConf["DIBI_PRECONFIGURATION"]["sqlite3_driver"])) {
             $dbFile = AJXP_VarsFilter::filter($coreConf["DIBI_PRECONFIGURATION"]["sqlite3_database"]);
             if (!file_exists(dirname($dbFile))) {
                 mkdir(dirname($dbFile), 0755, true);
             }
         }
         $coreConf["UNIQUE_INSTANCE_CONFIG"] = array_merge($coreConf["UNIQUE_INSTANCE_CONFIG"], array("instance_name" => "conf.sql", "group_switch_value" => "conf.sql", "SQL_DRIVER" => array("core_driver" => "core", "group_switch_value" => "core")));
         $coreAuth["MASTER_INSTANCE_CONFIG"] = array_merge($coreAuth["MASTER_INSTANCE_CONFIG"], array("instance_name" => "auth.sql", "group_switch_value" => "auth.sql", "SQL_DRIVER" => array("core_driver" => "core", "group_switch_value" => "core")));
         // INSTALL ALL SQL TABLES
         $sqlPlugs = array("conf.sql", "auth.sql", "feed.sql", "log.sql", "meta.syncable");
         foreach ($sqlPlugs as $plugId) {
             $plug = AJXP_PluginsService::findPluginById($plugId);
             $plug->installSQLTables(array("SQL_DRIVER" => $data["STORAGE_TYPE"]["db_type"]));
         }
     } else {
         $coreConf["UNIQUE_INSTANCE_CONFIG"] = array_merge($coreConf["UNIQUE_INSTANCE_CONFIG"], array("instance_name" => "conf.serial", "group_switch_value" => "conf.serial"));
         $coreAuth["MASTER_INSTANCE_CONFIG"] = array_merge($coreAuth["MASTER_INSTANCE_CONFIG"], array("instance_name" => "auth.serial", "group_switch_value" => "auth.serial"));
     }
     $oldBoot = $this->getPluginWorkDir(true) . "/bootstrap.json";
     if (is_file($oldBoot)) {
         copy($oldBoot, $oldBoot . ".bak");
         unlink($oldBoot);
     }
     $newBootstrap = array("core.conf" => $coreConf, "core.auth" => $coreAuth);
     AJXP_Utils::saveSerialFile($oldBoot, $newBootstrap, true, false, "json", true);
     // Write new bootstrap and reload conf plugin!
     if ($storageType == "db") {
         $coreConf["UNIQUE_INSTANCE_CONFIG"]["SQL_DRIVER"] = $coreConf["DIBI_PRECONFIGURATION"];
         $coreAuth["MASTER_INSTANCE_CONFIG"]["SQL_DRIVER"] = $coreConf["DIBI_PRECONFIGURATION"];
     }
     $newConfigPlugin = ConfService::instanciatePluginFromGlobalParams($coreConf["UNIQUE_INSTANCE_CONFIG"], "AbstractConfDriver");
     $newAuthPlugin = ConfService::instanciatePluginFromGlobalParams($coreAuth["MASTER_INSTANCE_CONFIG"], "AbstractAuthDriver");
     if ($data["ENCODING"] != (defined('AJXP_LOCALE') ? AJXP_LOCALE : SystemTextEncoding::getEncoding())) {
         file_put_contents($this->getPluginWorkDir() . "/encoding.php", "<?php \$ROOT_ENCODING='" . $data["ENCODING"] . "';");
     }
     $tpl = file_get_contents($this->getBaseDir() . "/htaccess.tpl");
     if (!empty($data["SERVER_URI"]) && $data["SERVER_URI"] != "/") {
         $htContent = str_replace('${APPLICATION_ROOT}', $data["SERVER_URI"], $tpl);
     } else {
         $htContent = str_replace('${APPLICATION_ROOT}/', "/", $tpl);
         $htContent = str_replace('${APPLICATION_ROOT}', "/", $htContent);
     }
     if (is_writeable(AJXP_INSTALL_PATH . "/.htaccess")) {
         file_put_contents(AJXP_INSTALL_PATH . "/.htaccess", $htContent);
     } else {
         $htAccessToUpdate = AJXP_INSTALL_PATH . "/.htaccess";
     }
     if ($storageType == "db") {
         $sqlPlugs = array("core.notifications/UNIQUE_FEED_INSTANCE" => "feed.sql", "core.log/UNIQUE_PLUGIN_INSTANCE" => "log.sql", "core.mq/UNIQUE_MS_INSTANCE" => "mq.sql");
         $data["ENABLE_NOTIF"] = $data["STORAGE_TYPE"]["notifications"];
     }
     // Prepare plugins configs
     $direct = array("APPLICATION_TITLE" => "core.ajaxplorer/APPLICATION_TITLE", "APPLICATION_LANGUAGE" => "core.ajaxplorer/DEFAULT_LANGUAGE", "ENABLE_NOTIF" => "core.notifications/USER_EVENTS", "APPLICATION_WELCOME" => "gui.ajax/CUSTOM_WELCOME_MESSAGE");
     $mailerEnabled = $data["MAILER_ENABLE"]["status"];
     if ($mailerEnabled == "yes") {
         // Enable core.mailer
         $data["MAILER_SYSTEM"] = $data["MAILER_ENABLE"]["MAILER_SYSTEM"];
         $data["MAILER_ADMIN"] = $data["MAILER_ENABLE"]["MAILER_ADMIN"];
         $direct = array_merge($direct, array("MAILER_SYSTEM" => "mailer.phpmailer-lite/MAILER", "MAILER_ADMIN" => "core.mailer/FROM"));
     }
     foreach ($direct as $key => $value) {
         list($pluginId, $param) = explode("/", $value);
         $options = array();
         $newConfigPlugin->_loadPluginConfig($pluginId, $options);
         $options[$param] = $data[$key];
         $newConfigPlugin->_savePluginConfig($pluginId, $options);
     }
     if (isset($sqlPlugs)) {
         foreach ($sqlPlugs as $core => $value) {
             list($pluginId, $param) = explode("/", $core);
             $options = array();
             $newConfigPlugin->_loadPluginConfig($pluginId, $options);
             $options[$param] = array("instance_name" => $value, "group_switch_value" => $value, "SQL_DRIVER" => array("core_driver" => "core", "group_switch_value" => "core"));
             $newConfigPlugin->_savePluginConfig($pluginId, $options);
         }
     }
     ConfService::setTmpStorageImplementations($newConfigPlugin, $newAuthPlugin);
     require_once $newConfigPlugin->getUserClassFileName();
     $adminLogin = AJXP_Utils::sanitize($data["ADMIN_USER_LOGIN"], AJXP_SANITIZE_EMAILCHARS);
     $adminName = $data["ADMIN_USER_NAME"];
     $adminPass = $data["ADMIN_USER_PASS"];
     $adminPass2 = $data["ADMIN_USER_PASS2"];
     AuthService::createUser($adminLogin, $adminPass, true);
     $uObj = $newConfigPlugin->createUserObject($adminLogin);
     if (isset($data["MAILER_ADMIN"])) {
         $uObj->personalRole->setParameterValue("core.conf", "email", $data["MAILER_ADMIN"]);
     }
     $uObj->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", $adminName);
     $uObj->personalRole->setAcl('ajxp_conf', 'rw');
     AuthService::updateRole($uObj->personalRole);
     $loginP = "USER_LOGIN";
     $i = 0;
     while (isset($data[$loginP]) && !empty($data[$loginP])) {
         $pass = $data[str_replace("_LOGIN", "_PASS", $loginP)];
         $pass2 = $data[str_replace("_LOGIN", "_PASS2", $loginP)];
         $name = $data[str_replace("_LOGIN", "_NAME", $loginP)];
         $mail = $data[str_replace("_LOGIN", "_MAIL", $loginP)];
         $saniLogin = AJXP_Utils::sanitize($data[$loginP], AJXP_SANITIZE_EMAILCHARS);
         AuthService::createUser($saniLogin, $pass);
         $uObj = $newConfigPlugin->createUserObject($saniLogin);
         $uObj->personalRole->setParameterValue("core.conf", "email", $mail);
         $uObj->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", $name);
         AuthService::updateRole($uObj->personalRole);
         $i++;
         $loginP = "USER_LOGIN_" . $i;
     }
     AJXP_PluginsService::clearPluginsCache();
     AJXP_Utils::setApplicationFirstRunPassed();
     if (isset($htAccessToUpdate)) {
         HTMLWriter::charsetHeader("application/json");
         echo json_encode(array('file' => $htAccessToUpdate, 'content' => $htContent));
     } else {
         session_destroy();
         HTMLWriter::charsetHeader("text/plain");
         echo 'OK';
     }
 }
コード例 #19
0
ファイル: content.php プロジェクト: umbecr/camilaframework
set_exception_handler(array("AJXP_XMLWriter", "catchException"));
$pServ = AJXP_PluginsService::getInstance();
$pServ->loadPluginsRegistry(INSTALL_PATH . "/plugins", INSTALL_PATH . "/server/conf");
ConfService::init("server/conf/conf.php");
$confStorageDriver = ConfService::getConfStorageImpl();
require_once $confStorageDriver->getUserClassFileName();
session_name("AjaXplorer");
session_start();
if (isset($_GET["tmp_repository_id"])) {
    ConfService::switchRootDir($_GET["tmp_repository_id"], true);
}
if (AuthService::usersEnabled()) {
    $rememberLogin = "";
    $rememberPass = "";
    if (isset($_GET["get_action"]) && $_GET["get_action"] == "get_seed") {
        HTMLWriter::charsetHeader("text/plain");
        print AuthService::generateSeed();
        exit(0);
    }
    if (isset($_GET["get_action"]) && $_GET["get_action"] == "logout") {
        AuthService::disconnect();
        $loggingResult = 2;
    }
    if (isset($_GET["get_action"]) && $_GET["get_action"] == "back") {
        AJXP_XMLWriter::header("url");
        echo AuthService::getLogoutAddress(false);
        AJXP_XMLWriter::close("url");
        exit(1);
    }
    if (isset($_GET["get_action"]) && $_GET["get_action"] == "login") {
        $userId = isset($_GET["userid"]) ? $_GET["userid"] : null;
コード例 #20
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         case "login":
             if (!AuthService::usersEnabled()) {
                 return;
             }
             $rememberLogin = "";
             $rememberPass = "";
             $secureToken = "";
             $loggedUser = null;
             include_once AJXP_BIN_FOLDER . "/class.CaptchaProvider.php";
             if (AuthService::suspectBruteForceLogin() && (!isset($httpVars["captcha_code"]) || !CaptchaProvider::checkCaptchaResult($httpVars["captcha_code"]))) {
                 $loggingResult = -4;
             } else {
                 $userId = isset($httpVars["userid"]) ? trim($httpVars["userid"]) : null;
                 $userPass = isset($httpVars["password"]) ? trim($httpVars["password"]) : null;
                 $rememberMe = isset($httpVars["remember_me"]) && $httpVars["remember_me"] == "true" ? true : false;
                 $cookieLogin = isset($httpVars["cookie_login"]) ? true : false;
                 $loggingResult = AuthService::logUser($userId, $userPass, false, $cookieLogin, $httpVars["login_seed"]);
                 if ($rememberMe && $loggingResult == 1) {
                     $rememberLogin = "******";
                     $rememberPass = "******";
                     $loggedUser = AuthService::getLoggedUser();
                 }
                 if ($loggingResult == 1) {
                     session_regenerate_id(true);
                     $secureToken = AuthService::generateSecureToken();
                 }
                 if ($loggingResult < 1 && AuthService::suspectBruteForceLogin()) {
                     $loggingResult = -4;
                     // Force captcha reload
                 }
             }
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser != null) {
                 $force = $loggedUser->mergedRole->filterParameterValue("core.conf", "DEFAULT_START_REPOSITORY", AJXP_REPO_SCOPE_ALL, -1);
                 $passId = -1;
                 if (isset($httpVars["tmp_repository_id"])) {
                     $passId = $httpVars["tmp_repository_id"];
                 } else {
                     if ($force != "" && $loggedUser->canSwitchTo($force) && !isset($httpVars["tmp_repository_id"]) && !isset($_SESSION["PENDING_REPOSITORY_ID"])) {
                         $passId = $force;
                     }
                 }
                 $res = ConfService::switchUserToActiveRepository($loggedUser, $passId);
                 if (!$res) {
                     AuthService::disconnect();
                     $loggingResult = -3;
                 }
             }
             if ($loggedUser != null && (AuthService::hasRememberCookie() || isset($rememberMe) && $rememberMe == true)) {
                 AuthService::refreshRememberCookie($loggedUser);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::loggingResult($loggingResult, $rememberLogin, $rememberPass, $secureToken);
             AJXP_XMLWriter::close();
             break;
             //------------------------------------
             //	CHANGE USER PASSWORD
             //------------------------------------
         //------------------------------------
         //	CHANGE USER PASSWORD
         //------------------------------------
         case "pass_change":
             $userObject = AuthService::getLoggedUser();
             if ($userObject == null || $userObject->getId() == "guest") {
                 header("Content-Type:text/plain");
                 print "SUCCESS";
                 break;
             }
             $oldPass = $httpVars["old_pass"];
             $newPass = $httpVars["new_pass"];
             $passSeed = $httpVars["pass_seed"];
             if (strlen($newPass) < ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth")) {
                 header("Content-Type:text/plain");
                 print "PASS_ERROR";
                 break;
             }
             if (AuthService::checkPassword($userObject->getId(), $oldPass, false, $passSeed)) {
                 AuthService::updatePassword($userObject->getId(), $newPass);
                 if ($userObject->getLock() == "pass_change") {
                     $userObject->removeLock();
                     $userObject->save("superuser");
                 }
             } else {
                 header("Content-Type:text/plain");
                 print "PASS_ERROR";
                 break;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             break;
         case "logout":
             AuthService::disconnect();
             $loggingResult = 2;
             session_destroy();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::loggingResult($loggingResult, null, null, null);
             AJXP_XMLWriter::close();
             break;
         case "get_seed":
             $seed = AuthService::generateSeed();
             if (AuthService::suspectBruteForceLogin()) {
                 HTMLWriter::charsetHeader('application/json');
                 print json_encode(array("seed" => $seed, "captcha" => true));
             } else {
                 HTMLWriter::charsetHeader("text/plain");
                 print $seed;
             }
             //exit(0);
             break;
         case "get_secure_token":
             HTMLWriter::charsetHeader("text/plain");
             print AuthService::generateSecureToken();
             //exit(0);
             break;
         case "get_captcha":
             include_once AJXP_BIN_FOLDER . "/class.CaptchaProvider.php";
             CaptchaProvider::sendCaptcha();
             //exit(0) ;
             break;
         case "back":
             AJXP_XMLWriter::header("url");
             echo AuthService::getLogoutAddress(false);
             AJXP_XMLWriter::close("url");
             //exit(1);
             break;
         default:
             break;
     }
     return "";
 }
コード例 #21
0
 /**
  * @param String $actionName
  * @param Array $httpVars
  * @param Array $fileVars
  */
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     $userSelection = new UserSelection($this->accessDriver->repository, $httpVars);
     $uniqNode = $userSelection->getUniqueNode();
     $feedStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("feed");
     $existingFeed = $uniqNode->retrieveMetadata(AJXP_META_SPACE_COMMENTS, false);
     if ($existingFeed == null) {
         $existingFeed = array();
     }
     $mess = ConfService::getMessages();
     switch ($actionName) {
         case "post_comment":
             $uId = AuthService::getLoggedUser()->getId();
             $limit = $this->getFilteredOption("COMMENT_SIZE_LIMIT");
             if (!empty($limit)) {
                 $content = substr(AJXP_Utils::decodeSecureMagic($httpVars["content"]), 0, $limit);
             } else {
                 $content = AJXP_Utils::decodeSecureMagic($httpVars["content"]);
             }
             $com = array("date" => time(), "author" => $uId, "content" => $content);
             $existingFeed[] = $com;
             if ($feedStore !== false) {
                 $feedStore->persistMetaObject($uniqNode->getPath(), base64_encode($content), $uniqNode->getRepositoryId(), $uniqNode->getRepository()->securityScope(), $uniqNode->getRepository()->getOwner(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath());
             } else {
                 $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false);
                 $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $existingFeed, false);
             }
             HTMLWriter::charsetHeader("application/json");
             $com["hdate"] = AJXP_Utils::relativeDate($com["date"], $mess);
             $com["path"] = $uniqNode->getPath();
             echo json_encode($com);
             break;
         case "load_comments_feed":
             HTMLWriter::charsetHeader("application/json");
             if ($feedStore !== false) {
                 $sortBy = isset($httpVars["sort_by"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_by"]) : "date";
                 $sortDir = isset($httpVars["sort_dir"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_dir"]) : "asc";
                 $offset = isset($httpVars["offset"]) ? intval($httpVars["offset"]) : 0;
                 $limit = isset($httpVars["limit"]) ? intval($httpVars["limit"]) : 100;
                 $uniqNode->loadNodeInfo();
                 $data = $feedStore->findMetaObjectsByIndexPath($this->accessDriver->repository->getId(), $uniqNode->getPath(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath(), $offset, $limit, $sortBy, $sortDir, !$uniqNode->isLeaf());
                 $theFeed = array();
                 foreach ($data as $stdObject) {
                     $rPath = substr($stdObject->path, strlen($uniqNode->getPath()));
                     if ($rPath == false && $stdObject->path == $uniqNode->getPath()) {
                         $rPath = "";
                     }
                     $rPath = ltrim($rPath, "/");
                     $newItem = array("date" => $stdObject->date, "hdate" => AJXP_Utils::relativeDate($stdObject->date, $mess), "author" => $stdObject->author, "content" => base64_decode($stdObject->content), "path" => $stdObject->path, "rpath" => $rPath, "uuid" => $stdObject->uuid);
                     if (isset($previous) && $previous["author"] == $newItem["author"] && $previous["path"] == $newItem["path"] && $previous["hdate"] == $newItem["hdate"]) {
                         $theFeed[count($theFeed) - 1]["content"] .= '<br>' . $newItem["content"];
                     } else {
                         $theFeed[] = $newItem;
                     }
                     $previous = $newItem;
                 }
                 echo json_encode($theFeed);
             } else {
                 foreach ($existingFeed as &$item) {
                     $item["hdate"] = AJXP_Utils::relativeDate($item["date"], $mess);
                 }
                 echo json_encode($existingFeed);
             }
             break;
         case "delete_comment":
             $data = json_decode($httpVars["comment_data"], true);
             if ($feedStore === false) {
                 $reFeed = array();
                 if ($data["author"] != AuthService::getLoggedUser()->getId()) {
                     break;
                 }
                 foreach ($existingFeed as $fElement) {
                     if ($fElement["date"] == $data["date"] && $fElement["author"] == $data["author"] && $fElement["content"] == $data["content"]) {
                         continue;
                     }
                     $fElement["hdate"] = AJXP_Utils::relativeDate($fElement["date"], $mess);
                     $reFeed[] = $fElement;
                 }
                 $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false);
                 $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $reFeed, false);
                 HTMLWriter::charsetHeader("application/json");
                 echo json_encode($reFeed);
             } else {
                 $feedStore->dismissAlertById($data["uuid"], 1);
             }
             break;
         default:
             break;
     }
 }
コード例 #22
0
 public function loadUserFeed($actionName, $httpVars, $fileVars)
 {
     if (!$this->eventStore) {
         return array();
     }
     $u = AuthService::getLoggedUser();
     if ($u == null) {
         if ($httpVars["format"] == "html") {
             return array();
         }
         AJXP_XMLWriter::header();
         AJXP_XMLWriter::close();
         return array();
     }
     $userId = $u->getId();
     $userGroup = $u->getGroupPath();
     $authRepos = array();
     $crtRepId = ConfService::getCurrentRepositoryId();
     if (isset($httpVars["repository_id"]) && $u->mergedRole->canRead($httpVars["repository_id"])) {
         $authRepos[] = $httpVars["repository_id"];
     } else {
         if (isset($httpVars["current_repository"])) {
             $authRepos[] = $crtRepId;
         } else {
             $accessibleRepos = ConfService::getAccessibleRepositories(AuthService::getLoggedUser(), false, true, false);
             $authRepos = array_keys($accessibleRepos);
         }
     }
     $offset = isset($httpVars["offset"]) ? intval($httpVars["offset"]) : 0;
     $limit = isset($httpVars["limit"]) ? intval($httpVars["limit"]) : 15;
     if (!isset($httpVars["feed_type"]) || $httpVars["feed_type"] == "notif" || $httpVars["feed_type"] == "all") {
         $res = $this->eventStore->loadEvents($authRepos, isset($httpVars["path"]) ? $httpVars["path"] : "", $userGroup, $offset, $limit, false, $userId);
     } else {
         $res = array();
     }
     $mess = ConfService::getMessages();
     $format = "html";
     if (isset($httpVars["format"])) {
         $format = $httpVars["format"];
     }
     if ($format == "html") {
         echo "<h2>" . $mess["notification_center.4"] . "</h2>";
         echo "<ul class='notification_list'>";
     } else {
         if ($format == "json") {
             $jsonNodes = array();
         } else {
             if ($format != 'array') {
                 AJXP_XMLWriter::header();
             }
         }
     }
     // APPEND USER ALERT IN THE SAME QUERY FOR NOW
     if (!isset($httpVars["feed_type"]) || $httpVars["feed_type"] == "alert" || $httpVars["feed_type"] == "all") {
         $this->loadUserAlerts("", array_merge($httpVars, array("skip_container_tags" => "true")), $fileVars);
     }
     restore_error_handler();
     $index = 1;
     foreach ($res as $n => $object) {
         $args = $object->arguments;
         $oldNode = isset($args[0]) ? $args[0] : null;
         $newNode = isset($args[1]) ? $args[1] : null;
         $copy = isset($args[2]) && $args[2] === true ? true : null;
         $notif = $this->generateNotificationFromChangeHook($oldNode, $newNode, $copy, "unify");
         if ($notif !== false && $notif->getNode() !== false) {
             $notif->setAuthor($object->author);
             $notif->setDate(intval($object->date));
             if ($format == "html") {
                 $p = $notif->getNode()->getPath();
                 echo "<li data-ajxpNode='{$p}'>";
                 echo $notif->getDescriptionShort(true);
                 echo "</li>";
             } else {
                 $node = $notif->getNode();
                 if ($node == null) {
                     $this->logInfo("Warning", "Empty node stored in notification " . $notif->getAuthor() . "/ " . $notif->getAction());
                     continue;
                 }
                 try {
                     $node->loadNodeInfo();
                 } catch (Exception $e) {
                     continue;
                 }
                 $node->event_description = ucfirst($notif->getDescriptionBlock()) . " " . $mess["notification.tpl.block.user_link"] . " " . $notif->getAuthorLabel();
                 $node->event_description_long = $notif->getDescriptionLong(true);
                 $node->event_date = SystemTextEncoding::fromUTF8(AJXP_Utils::relativeDate($notif->getDate(), $mess));
                 $node->short_date = AJXP_Utils::relativeDate($notif->getDate(), $mess, true);
                 $node->event_time = $notif->getDate();
                 $node->event_type = "notification";
                 $node->event_id = $object->event_id;
                 if ($node->getRepository() != null) {
                     $node->repository_id = '' . $node->getRepository()->getId();
                     if ($node->repository_id != $crtRepId && $node->getRepository()->getDisplay() != null) {
                         $node->event_repository_label = "[" . $node->getRepository()->getDisplay() . "]";
                     }
                 }
                 $node->event_author = $notif->getAuthor();
                 // Replace PATH, to make sure they will be distinct children of the loader node
                 $node->real_path = $node->getPath();
                 $node->setLabel(basename($node->getPath()));
                 if (isset($httpVars["merge_description"]) && $httpVars["merge_description"] == "true") {
                     if (isset($httpVars["description_as_label"]) && $httpVars["description_as_label"] == "true") {
                         $node->setLabel($node->event_description . " " . $node->event_date);
                     } else {
                         $node->setLabel(basename($node->getPath()) . " <small class='notif_desc'>" . $node->event_description . " " . $node->event_date . "</small>");
                     }
                 }
                 $url = parse_url($node->getUrl());
                 $node->setUrl($url["scheme"] . "://" . $url["host"] . "/notification_" . $index);
                 $index++;
                 if ($format == "json" || $format == "array") {
                     $keys = $node->listMetaKeys();
                     $data = array();
                     foreach ($keys as $k) {
                         $data[$k] = $node->{$k};
                     }
                     if ($format == "json") {
                         $jsonNodes[] = json_encode($data);
                     } else {
                         $jsonNodes[] = $data;
                     }
                 } else {
                     AJXP_XMLWriter::renderAjxpNode($node);
                 }
             }
         }
     }
     if ($format == "html") {
         echo "</ul>";
     } else {
         if ($format == "json") {
             HTMLWriter::charsetHeader("application/json");
             echo '[' . implode(",", $jsonNodes) . ']';
         } else {
             if ($format == "array") {
                 return $jsonNodes;
             } else {
                 AJXP_XMLWriter::close();
             }
         }
     }
 }
コード例 #23
0
 public function listTags($actionName, &$httpVars, &$fileVars)
 {
     HTMLWriter::charsetHeader("application/json");
     $tags = $this->loadTags();
     if (empty($tags)) {
         $tags = array();
     }
     echo json_encode($tags);
 }
コード例 #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;
 }
コード例 #25
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	SWITCH THE ROOT REPOSITORY
         //------------------------------------
         case "switch_repository":
             if (!isset($repository_id)) {
                 break;
             }
             $dirList = ConfService::getRepositoriesList();
             /** @var $repository_id string */
             if (!isset($dirList[$repository_id])) {
                 $errorMessage = "Trying to switch to an unkown repository!";
                 break;
             }
             ConfService::switchRootDir($repository_id);
             // Load try to init the driver now, to trigger an exception
             // if it's not loading right.
             ConfService::loadRepositoryDriver();
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $user = AuthService::getLoggedUser();
                 $activeRepId = ConfService::getCurrentRepositoryId();
                 $user->setArrayPref("history", "last_repository", $activeRepId);
                 $user->save("user");
             }
             //$logMessage = "Successfully Switched!";
             $this->logInfo("Switch Repository", array("rep. id" => $repository_id));
             break;
             //------------------------------------
             //	SEND XML REGISTRY
             //------------------------------------
         //------------------------------------
         //	SEND XML REGISTRY
         //------------------------------------
         case "get_xml_registry":
         case "state":
             $regDoc = AJXP_PluginsService::getXmlRegistry();
             $changes = AJXP_Controller::filterRegistryFromRole($regDoc);
             if ($changes) {
                 AJXP_PluginsService::updateXmlRegistry($regDoc);
             }
             $clone = $regDoc->cloneNode(true);
             $clonePath = new DOMXPath($clone);
             $serverCallbacks = $clonePath->query("//serverCallback|hooks");
             foreach ($serverCallbacks as $callback) {
                 $callback->parentNode->removeChild($callback);
             }
             $xPath = '';
             if (isset($httpVars["xPath"])) {
                 $xPath = ltrim(AJXP_Utils::securePath($httpVars["xPath"]), "/");
             }
             if (!empty($xPath)) {
                 $nodes = $clonePath->query($xPath);
                 if ($httpVars["format"] == "json") {
                     $data = AJXP_XMLWriter::xmlToArray($nodes->item(0));
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($data);
                 } else {
                     AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $xPath));
                     if ($nodes->length) {
                         print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML($nodes->item(0)));
                     }
                     AJXP_XMLWriter::close("ajxp_registry_part");
                 }
             } else {
                 AJXP_Utils::safeIniSet("zlib.output_compression", "4096");
                 if ($httpVars["format"] == "json") {
                     $data = AJXP_XMLWriter::xmlToArray($clone);
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($data);
                 } else {
                     header('Content-Type: application/xml; charset=UTF-8');
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML());
                 }
             }
             break;
             //------------------------------------
             //	BOOKMARK BAR
             //------------------------------------
         //------------------------------------
         //	BOOKMARK BAR
         //------------------------------------
         case "get_bookmarks":
             $bmUser = null;
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser = AuthService::getLoggedUser();
             } else {
                 if (!AuthService::usersEnabled()) {
                     $confStorage = ConfService::getConfStorageImpl();
                     $bmUser = $confStorage->createUserObject("shared");
                 }
             }
             if ($bmUser == null) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::close();
             }
             $driver = ConfService::loadRepositoryDriver();
             if (!is_a($driver, "AjxpWrapperProvider")) {
                 $driver = false;
             }
             if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) {
                 $bmPath = AJXP_Utils::decodeSecureMagic($httpVars["bm_path"]);
                 if ($httpVars["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($httpVars["bm_title"])) {
                         $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]);
                     }
                     if ($title == "" && $bmPath == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark($bmPath, $title);
                     if ($driver) {
                         $node = new AJXP_Node($driver->getResourceUrl($bmPath));
                         $node->setMetadata("ajxp_bookmarked", array("ajxp_bookmarked" => "true"), true, AJXP_METADATA_SCOPE_REPOSITORY, true);
                     }
                 } else {
                     if ($httpVars["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($bmPath);
                         if ($driver) {
                             $node = new AJXP_Node($driver->getResourceUrl($bmPath));
                             $node->removeMetadata("ajxp_bookmarked", true, AJXP_METADATA_SCOPE_REPOSITORY, true);
                         }
                     } else {
                         if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) {
                             $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]);
                             $bmUser->renameBookmark($bmPath, $title);
                         }
                     }
                 }
                 AJXP_Controller::applyHook("msg.instant", array("<reload_bookmarks/>", ConfService::getRepository()->getId()));
                 if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                     $bmUser->save("user");
                     AuthService::updateUser($bmUser);
                 } else {
                     if (!AuthService::usersEnabled()) {
                         $bmUser->save("user");
                     }
                 }
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks(), true, isset($httpVars["format"]) ? $httpVars["format"] : "legacy");
             AJXP_XMLWriter::close();
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "save_user_pref":
             $userObject = AuthService::getLoggedUser();
             $i = 0;
             while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && $userObject == null) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save("user");
                 AuthService::updateUser($userObject);
                 //setcookie("AJXP_$prefName", $prefValue);
                 $i++;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "custom_data_edit":
         case "user_create_user":
             $data = array();
             if ($action == "user_create_user" && isset($httpVars["NEW_new_user_id"])) {
                 $updating = false;
                 AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_");
                 $original_id = AJXP_Utils::decodeSecureMagic($data["new_user_id"]);
                 $data["new_user_id"] = AJXP_Utils::decodeSecureMagic($data["new_user_id"], AJXP_SANITIZE_EMAILCHARS);
                 if ($original_id != $data["new_user_id"]) {
                     throw new Exception(str_replace("%s", $data["new_user_id"], $mess["ajxp_conf.127"]));
                 }
                 if (AuthService::userExists($data["new_user_id"], "w")) {
                     throw new Exception($mess["ajxp_conf.43"]);
                 }
                 $loggedUser = AuthService::getLoggedUser();
                 $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, "");
                 if (!empty($limit) && intval($limit) > 0) {
                     $count = count($this->getUserChildren($loggedUser->getId()));
                     if ($count >= $limit) {
                         throw new Exception($mess['483']);
                     }
                 }
                 AuthService::createUser($data["new_user_id"], $data["new_password"]);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($data["new_user_id"]);
                 $userObject->setParent($loggedUser->getId());
                 $userObject->save('superuser');
                 $userObject->personalRole->clearAcls();
                 $userObject->setGroupPath($loggedUser->getGroupPath());
                 $userObject->setProfile("shared");
             } else {
                 if ($action == "user_create_user" && isset($httpVars["NEW_existing_user_id"])) {
                     $updating = true;
                     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_");
                     $userId = $data["existing_user_id"];
                     if (!AuthService::userExists($userId)) {
                         throw new Exception("Cannot find user");
                     }
                     $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
                     if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) {
                         throw new Exception("Cannot find user");
                     }
                     if (!empty($data["new_password"])) {
                         AuthService::updatePassword($userId, $data["new_password"]);
                     }
                 } else {
                     $updating = false;
                     $userObject = AuthService::getLoggedUser();
                     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "PREFERENCES_");
                 }
             }
             $paramNodes = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'user') and @expose='true']", "node", false, false, true);
             $rChanges = false;
             if (is_array($paramNodes) && count($paramNodes)) {
                 foreach ($paramNodes as $xmlNode) {
                     if ($xmlNode->getAttribute("expose") == "true") {
                         $parentNode = $xmlNode->parentNode->parentNode;
                         $pluginId = $parentNode->getAttribute("id");
                         if (empty($pluginId)) {
                             $pluginId = $parentNode->nodeName . "." . $parentNode->getAttribute("name");
                         }
                         $name = $xmlNode->getAttribute("name");
                         if (isset($data[$name]) || $data[$name] === "") {
                             if ($data[$name] == "__AJXP_VALUE_SET__") {
                                 continue;
                             }
                             if ($data[$name] === "" || $userObject->parentRole == null || $userObject->parentRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name] || $userObject->personalRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name]) {
                                 $userObject->personalRole->setParameterValue($pluginId, $name, $data[$name]);
                                 $rChanges = true;
                             }
                         }
                     }
                 }
             }
             if ($rChanges) {
                 AuthService::updateRole($userObject->personalRole, $userObject);
                 $userObject->recomputeMergedRole();
                 if ($action == "custom_data_edit") {
                     AuthService::updateUser($userObject);
                 }
             }
             if ($action == "user_create_user") {
                 AJXP_Controller::applyHook($updating ? "user.after_update" : "user.after_create", array($userObject));
                 if (isset($data["send_email"]) && $data["send_email"] == true && !empty($data["email"])) {
                     $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer");
                     if ($mailer !== false) {
                         $mess = ConfService::getMessages();
                         $link = AJXP_Utils::detectServerURL();
                         $apptitle = ConfService::getCoreConf("APPLICATION_TITLE");
                         $subject = str_replace("%s", $apptitle, $mess["507"]);
                         $body = str_replace(array("%s", "%link", "%user", "%pass"), array($apptitle, $link, $data["new_user_id"], $data["new_password"]), $mess["508"]);
                         $mailer->sendMail(array($data["email"]), $subject, $body);
                     }
                 }
                 echo "SUCCESS";
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage($mess["241"], null);
                 AJXP_XMLWriter::close();
             }
             break;
         case "user_update_user":
             if (!isset($httpVars["user_id"])) {
                 throw new Exception("invalid arguments");
             }
             $userId = $httpVars["user_id"];
             if (!AuthService::userExists($userId)) {
                 throw new Exception("Cannot find user");
             }
             $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
             if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("Cannot find user");
             }
             $paramsString = ConfService::getCoreConf("NEWUSERS_EDIT_PARAMETERS", "conf");
             $result = array();
             $params = explode(",", $paramsString);
             foreach ($params as $p) {
                 $result[$p] = $userObject->personalRole->filterParameterValue("core.conf", $p, AJXP_REPO_SCOPE_ALL, "");
             }
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($result);
             break;
             //------------------------------------
             // WEBDAV PREFERENCES
             //------------------------------------
         //------------------------------------
         // WEBDAV PREFERENCES
         //------------------------------------
         case "webdav_preferences":
             $userObject = AuthService::getLoggedUser();
             $webdavActive = false;
             $passSet = false;
             $digestSet = false;
             // Detect http/https and host
             if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") {
                 $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST");
             } else {
                 $baseURL = AJXP_Utils::detectServerURL();
             }
             $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/";
             $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
             $digestSet = isset($davData["HA1"]);
             if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) {
                 if (!empty($httpVars["activate"])) {
                     $activate = $httpVars["activate"] == "true" ? true : false;
                     if (empty($davData)) {
                         $davData = array();
                     }
                     $davData["ACTIVE"] = $activate;
                 }
                 if (!empty($httpVars["webdav_pass"])) {
                     $password = $httpVars["webdav_pass"];
                     if (function_exists('mcrypt_encrypt')) {
                         $user = $userObject->getId();
                         $secret = defined("AJXP_SAFE_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#";
                         $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB));
                     }
                     $davData["PASS"] = $password;
                 }
                 $userObject->setPref("AJXP_WEBDAV_DATA", $davData);
                 $userObject->save("user");
             }
             if (!empty($davData)) {
                 $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true;
                 $passSet = isset($davData["PASS"]);
             }
             $repoList = ConfService::getRepositoriesList();
             $davRepos = array();
             $loggedUser = AuthService::getLoggedUser();
             foreach ($repoList as $repoIndex => $repoObject) {
                 $accessType = $repoObject->getAccessType();
                 $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType);
                 if (is_a($driver, "AjxpWrapperProvider") && !$repoObject->getOption("AJXP_WEBDAV_DISABLED") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) {
                     $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug());
                 }
             }
             $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "digest_set" => $digestSet, "webdav_force_basic" => ConfService::getCoreConf("WEBDAV_FORCE_BASIC") === true, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos);
             HTMLWriter::charsetHeader("application/json");
             print json_encode($prefs);
             break;
         case "get_user_template_logo":
             $tplId = $httpVars["template_id"];
             $iconFormat = $httpVars["icon_format"];
             $repo = ConfService::getRepositoryById($tplId);
             $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat));
             if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) {
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo);
             } else {
                 $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png";
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo);
             }
             break;
         case "get_user_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $count = 0;
             $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => 1), $count);
             $pServ = AJXP_PluginsService::getInstance();
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 if (!$repo->getOption("TPL_USER_CAN_CREATE")) {
                     continue;
                 }
                 $repoId = $repo->getId();
                 $repoLabel = $repo->getDisplay();
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 $driverPlug = $pServ->getPluginByTypeName("access", $repoType);
                 $params = $driverPlug->getManifestRawContent("//param", "node");
                 $tplDefined = $repo->getOptionsDefined();
                 $defaultLabel = '';
                 foreach ($params as $paramNode) {
                     $name = $paramNode->getAttribute("name");
                     if (strpos($name, "TPL_") === 0) {
                         if ($name == "TPL_DEFAULT_LABEL") {
                             $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name));
                         }
                         continue;
                     }
                     if (in_array($paramNode->getAttribute("name"), $tplDefined)) {
                         continue;
                     }
                     if ($paramNode->getAttribute('no_templates') == 'true') {
                         continue;
                     }
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode));
                 }
                 // ADD LABEL
                 echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>';
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "user_create_repository":
             $tplId = $httpVars["template_id"];
             $tplRepo = ConfService::getRepositoryById($tplId);
             $options = array();
             AJXP_Utils::parseStandardFormParameters($httpVars, $options);
             $loggedUser = AuthService::getLoggedUser();
             $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, $loggedUser->getId());
             $gPath = $loggedUser->getGroupPath();
             if (!empty($gPath)) {
                 $newRep->setGroupPath($gPath);
             }
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[426]);
             } else {
                 // Make sure we do not overwrite otherwise loaded rights.
                 $loggedUser->load();
                 $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw");
                 $loggedUser->save("superuser");
                 $loggedUser->recomputeMergedRole();
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[425], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "user_delete_repository":
             $repoId = $httpVars["repository_id"];
             $repository = ConfService::getRepositoryById($repoId);
             if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("You are not allowed to perform this operation!");
             }
             $res = ConfService::deleteRepository($repoId);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[427]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 // Make sure we do not override remotely set rights
                 $loggedUser->load();
                 $loggedUser->personalRole->setAcl($repoId, "");
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[428], null);
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "user_delete_user":
             $userId = $httpVars["user_id"];
             $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
             if ($userObject == null || !$userObject->hasParent() || $userObject->getParent() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("You are not allowed to edit this user");
             }
             AuthService::deleteUser($userId);
             echo "SUCCESS";
             break;
         case "user_list_authorized_users":
             $defaultFormat = "html";
             HTMLWriter::charsetHeader();
             if (!ConfService::getAuthDriverImpl()->usersEditable()) {
                 break;
             }
             $loggedUser = AuthService::getLoggedUser();
             $crtValue = $httpVars["value"];
             $usersOnly = isset($httpVars["users_only"]) && $httpVars["users_only"] == "true";
             $existingOnly = isset($httpVars["existing_only"]) && $httpVars["existing_only"] == "true";
             if (!empty($crtValue)) {
                 $regexp = '^' . $crtValue;
             } else {
                 $regexp = null;
             }
             $skipDisplayWithoutRegexp = ConfService::getCoreConf("USERS_LIST_REGEXP_MANDATORY", "conf");
             if ($skipDisplayWithoutRegexp && $regexp == null) {
                 print "<ul></ul>";
                 break;
             }
             $limit = intval(ConfService::getCoreConf("USERS_LIST_COMPLETE_LIMIT", "conf"));
             $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf");
             $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf");
             $baseGroup = "/";
             if ($regexp == null && !$displayAll || $regexp != null && !$searchAll) {
                 $baseGroup = AuthService::filterBaseGroup("/");
             }
             AuthService::setGroupFiltering(false);
             $allUsers = AuthService::listUsers($baseGroup, $regexp, 0, $limit, false);
             if (!$usersOnly) {
                 $allGroups = array();
                 $roleOrGroup = ConfService::getCoreConf("GROUP_OR_ROLE", "conf");
                 $rolePrefix = $excludeString = $includeString = null;
                 if (!is_array($roleOrGroup)) {
                     $roleOrGroup = array("group_switch_value" => $roleOrGroup);
                 }
                 $listRoleType = false;
                 if (isset($roleOrGroup["PREFIX"])) {
                     $rolePrefix = $loggedUser->mergedRole->filterParameterValue("core.conf", "PREFIX", null, $roleOrGroup["PREFIX"]);
                     $excludeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "EXCLUDED", null, $roleOrGroup["EXCLUDED"]);
                     $includeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "INCLUDED", null, $roleOrGroup["INCLUDED"]);
                     $listUserRolesOnly = $loggedUser->mergedRole->filterParameterValue("core.conf", "LIST_ROLE_BY", null, $roleOrGroup["LIST_ROLE_BY"]);
                     if (is_array($listUserRolesOnly) && isset($listUserRolesOnly["group_switch_value"])) {
                         switch ($listUserRolesOnly["group_switch_value"]) {
                             case "userroles":
                                 $listRoleType = true;
                                 break;
                             case "allroles":
                                 $listRoleType = false;
                                 break;
                             default:
                                 break;
                         }
                     }
                 }
                 switch (strtolower($roleOrGroup["group_switch_value"])) {
                     case 'user':
                         // donothing
                         break;
                     case 'group':
                         $authGroups = AuthService::listChildrenGroups($baseGroup);
                         foreach ($authGroups as $gId => $gName) {
                             $allGroups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName;
                         }
                         break;
                     case 'role':
                         $allGroups = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType);
                         break;
                     case 'rolegroup':
                         $groups = array();
                         $authGroups = AuthService::listChildrenGroups($baseGroup);
                         foreach ($authGroups as $gId => $gName) {
                             $groups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName;
                         }
                         $roles = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType);
                         empty($groups) ? $allGroups = $roles : (empty($roles) ? $allGroups = $groups : ($allGroups = array_merge($groups, $roles)));
                         //$allGroups = array_merge($groups, $roles);
                         break;
                     default:
                         break;
                 }
             }
             $users = "";
             $index = 0;
             if ($regexp != null && (!count($allUsers) || !empty($crtValue) && !array_key_exists(strtolower($crtValue), $allUsers)) && ConfService::getCoreConf("USER_CREATE_USERS", "conf") && !$existingOnly) {
                 $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}'><span class='user_entry_label'>{$crtValue} (" . $mess["448"] . ")</span></li>";
             } else {
                 if ($existingOnly && !empty($crtValue)) {
                     $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}' data-entry_id='{$crtValue}'><span class='user_entry_label'>{$crtValue}</span></li>";
                 }
             }
             $mess = ConfService::getMessages();
             if ($regexp == null && !$usersOnly) {
                 $users .= "<li class='complete_group_entry' data-group='AJXP_GRP_/' data-label='" . $mess["447"] . "'><span class='user_entry_label'>" . $mess["447"] . "</span></li>";
             }
             $indexGroup = 0;
             if (!$usersOnly && is_array($allGroups)) {
                 foreach ($allGroups as $groupId => $groupLabel) {
                     if ($regexp == null || preg_match("/{$regexp}/i", $groupLabel)) {
                         $users .= "<li class='complete_group_entry' data-group='{$groupId}' data-label='{$groupLabel}' data-entry_id='{$groupId}'><span class='user_entry_label'>" . $groupLabel . "</span></li>";
                         $indexGroup++;
                     }
                     if ($indexGroup == $limit) {
                         break;
                     }
                 }
             }
             if ($regexp == null && method_exists($this, "listUserTeams")) {
                 $teams = $this->listUserTeams();
                 foreach ($teams as $tId => $tData) {
                     $users .= "<li class='complete_group_entry' data-group='/AJXP_TEAM/{$tId}' data-label='[team] " . $tData["LABEL"] . "'><span class='user_entry_label'>[team] " . $tData["LABEL"] . "</span></li>";
                 }
             }
             foreach ($allUsers as $userId => $userObject) {
                 if ($userObject->getId() == $loggedUser->getId()) {
                     continue;
                 }
                 if (!$userObject->hasParent() && ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") || $userObject->getParent() == $loggedUser->getId()) {
                     $userLabel = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId);
                     //if($regexp != null && ! (preg_match("/$regexp/i", $userId) || preg_match("/$regexp/i", $userLabel)) ) continue;
                     if (empty($userLabel)) {
                         $userLabel = $userId;
                     }
                     $userDisplay = $userLabel == $userId ? $userId : $userLabel . " ({$userId})";
                     if (ConfService::getCoreConf("USERS_LIST_HIDE_LOGIN", "conf") == true && $userLabel != $userId) {
                         $userDisplay = $userLabel;
                     }
                     $users .= "<li class='complete_user_entry' data-label='{$userLabel}' data-entry_id='{$userId}'><span class='user_entry_label'>" . $userDisplay . "</span></li>";
                     $index++;
                 }
                 if ($index == $limit) {
                     break;
                 }
             }
             if (strlen($users)) {
                 print "<ul>" . $users . "</ul>";
             }
             AuthService::setGroupFiltering(true);
             break;
         case "load_repository_info":
             $data = array();
             $repo = ConfService::getRepository();
             if ($repo != null) {
                 $users = AuthService::countUsersForRepository(ConfService::getRepository()->getId(), true);
                 $data["core.users"] = $users;
                 if (isset($httpVars["collect"]) && $httpVars["collect"] == "true") {
                     AJXP_Controller::applyHook("repository.load_info", array(&$data));
                 }
             }
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($data);
             break;
         case "get_binary_param":
             if (isset($httpVars["tmp_file"])) {
                 $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]);
                 if (isset($file)) {
                     header("Content-Type:image/png");
                     readfile($file);
                 }
             } else {
                 if (isset($httpVars["binary_id"])) {
                     if (isset($httpVars["user_id"]) && AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->isAdmin()) {
                         $context = array("USER" => $httpVars["user_id"]);
                     } else {
                         $context = array("USER" => AuthService::getLoggedUser()->getId());
                     }
                     $this->loadBinary($context, $httpVars["binary_id"]);
                 }
             }
             break;
         case "get_global_binary_param":
             if (isset($httpVars["tmp_file"])) {
                 $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]);
                 if (isset($file)) {
                     header("Content-Type:image/png");
                     readfile($file);
                 }
             } else {
                 if (isset($httpVars["binary_id"])) {
                     $this->loadBinary(array(), $httpVars["binary_id"]);
                 }
             }
             break;
         case "store_binary_temp":
             if (count($fileVars)) {
                 $keys = array_keys($fileVars);
                 $boxData = $fileVars[$keys[0]];
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                 } else {
                     $rand = substr(md5(time()), 0, 6);
                     $tmp = $rand . "-" . $boxData["name"];
                     @move_uploaded_file($boxData["tmp_name"], AJXP_Utils::getAjxpTmpDir() . "/" . $tmp);
                 }
             }
             if (isset($tmp) && file_exists(AJXP_Utils::getAjxpTmpDir() . "/" . $tmp)) {
                 print '<script type="text/javascript">';
                 print 'parent.formManagerHiddenIFrameSubmission("' . $tmp . '");';
                 print '</script>';
             }
             break;
         default:
             break;
     }
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if (isset($requireAuth)) {
         $xmlBuffer .= AJXP_XMLWriter::requireAuth(false);
     }
     return $xmlBuffer;
 }
コード例 #26
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     switch ($action) {
         case "logout":
             AuthService::disconnect();
             $loggingResult = 2;
             session_destroy();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::loggingResult($loggingResult, null, null, null);
             AJXP_XMLWriter::close();
             break;
         case "get_seed":
             $seed = AuthService::generateSeed();
             if (AuthService::suspectBruteForceLogin()) {
                 HTMLWriter::charsetHeader('application/json');
                 print json_encode(array("seed" => $seed, "captcha" => true));
             } else {
                 HTMLWriter::charsetHeader("text/plain");
                 print $seed;
             }
             break;
         case "get_captcha":
             include_once AJXP_BIN_FOLDER . "/class.CaptchaProvider.php";
             CaptchaProvider::sendCaptcha();
             //exit(0) ;
             break;
         case "back":
             AJXP_XMLWriter::header("url");
             echo AuthService::getLogoutAddress(false);
             AJXP_XMLWriter::close("url");
             //exit(1);
             break;
         default:
             break;
     }
     return "";
 }
コード例 #27
0
 /**
  * Send output to the user.
  * @param String $htAccessToUpdate file path
  * @param String $htContent file content
  */
 public function sendInstallResult($htAccessToUpdate, $htContent)
 {
     ConfService::clearAllCaches();
     AJXP_Utils::setApplicationFirstRunPassed();
     if ($htAccessToUpdate != null) {
         HTMLWriter::charsetHeader("application/json");
         echo json_encode(array('file' => $htAccessToUpdate, 'content' => $htContent));
     } else {
         session_destroy();
         HTMLWriter::charsetHeader("text/plain");
         echo 'OK';
     }
 }
コード例 #28
0
 /**
  * @param String $action
  * @param Array $httpVars
  * @param Array $fileVars
  * @return String
  */
 function authTokenActions($action, $httpVars, $fileVars)
 {
     if (AuthService::getLoggedUser() == null) {
         return;
     }
     $this->storage = ConfService::getConfStorageImpl();
     if (!is_a($this->storage, "sqlConfDriver")) {
         return false;
     }
     $user = AuthService::getLoggedUser()->getId();
     if (AuthService::getLoggedUser()->isAdmin() && isset($httpVars["user_id"])) {
         $user = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
     }
     switch ($action) {
         case "keystore_generate_auth_token":
             if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) {
                 $this->logDebug("Keystore Generate Tokens", "Session Credentials set: returning empty tokens to force basic authentication");
                 HTMLWriter::charsetHeader("text/plain");
                 echo "";
                 break;
             }
             $token = AJXP_Utils::generateRandomString();
             $private = AJXP_Utils::generateRandomString();
             $data = array("USER_ID" => $user, "PRIVATE" => $private);
             if (!empty($httpVars["device"])) {
                 // Revoke previous tokens for this device
                 $device = $httpVars["device"];
                 $keys = $this->storage->simpleStoreList("keystore", null, "", "serial", '%"DEVICE_ID";s:' . strlen($device) . ':"' . $device . '"%');
                 foreach ($keys as $keyId => $keyData) {
                     if ($keyData["USER_ID"] != $user) {
                         continue;
                     }
                     $this->storage->simpleStoreClear("keystore", $keyId);
                 }
                 $data["DEVICE_ID"] = $device;
             }
             $data["DEVICE_UA"] = $_SERVER['HTTP_USER_AGENT'];
             $data["DEVICE_IP"] = $_SERVER['REMOTE_ADDR'];
             $this->storage->simpleStoreSet("keystore", $token, $data, "serial");
             HTMLWriter::charsetHeader("application/json");
             echo json_encode(array("t" => $token, "p" => $private));
             break;
         case "keystore_revoke_tokens":
             // Invalidate previous tokens
             $mess = ConfService::getMessages();
             $passedKeyId = "";
             if (isset($httpVars["key_id"])) {
                 $passedKeyId = $httpVars["key_id"];
             }
             $keys = $this->storage->simpleStoreList("keystore", null, $passedKeyId, "serial", '%"USER_ID";s:' . strlen($user) . ':"' . $user . '"%');
             foreach ($keys as $keyId => $keyData) {
                 $this->storage->simpleStoreClear("keystore", $keyId);
             }
             $message = array("result" => "SUCCESS", "message" => $mess["keystore.8"]);
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($message);
             break;
         case "keystore_list_tokens":
             if (!isset($user)) {
                 break;
             }
             $keys = $this->storage->simpleStoreList("keystore", null, "", "serial", '%"USER_ID";s:' . strlen($user) . ':"' . $user . '"%');
             foreach ($keys as $keyId => &$keyData) {
                 unset($keyData["PRIVATE"]);
                 unset($keyData["USER_ID"]);
                 $deviceDesc = "Web Browser";
                 $deviceOS = "Unkown";
                 if (isset($keyData["DEVICE_UA"])) {
                     $agent = $keyData["DEVICE_UA"];
                     if (strpos($agent, "python-requests") !== false) {
                         $deviceDesc = "PydioSync";
                         if (strpos($agent, "Darwin") !== false) {
                             $deviceOS = "Mac OS X";
                         } else {
                             if (strpos($agent, "Windows/7") !== false) {
                                 $deviceOS = "Windows 7";
                             } else {
                                 if (strpos($agent, "Windows/8") !== false) {
                                     $deviceOS = "Windows 8";
                                 } else {
                                     if (strpos($agent, "Linux") !== false) {
                                         $deviceOS = "Linux";
                                     }
                                 }
                             }
                         }
                     } else {
                         $deviceOS = AJXP_Utils::osFromUserAgent($agent);
                     }
                 }
                 $keyData["DEVICE_DESC"] = $deviceDesc;
                 $keyData["DEVICE_OS"] = $deviceOS;
             }
             header("Content-type: application/json;");
             echo json_encode($keys);
             break;
         default:
             break;
     }
     return null;
 }
コード例 #29
0
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     if (!dibi::isConnected()) {
         dibi::connect($this->sqlDriver);
     }
     $filter = null;
     $masks = array();
     $currentRepo = $this->accessDriver->repository;
     AJXP_Controller::applyHook("role.masks", array($currentRepo->getId(), &$masks, AJXP_Permission::READ));
     $recycle = $currentRepo->getOption("RECYCLE_BIN");
     $recycle = !empty($recycle) ? $recycle : false;
     if ($this->options["OBSERVE_STORAGE_CHANGES"] === true) {
         // Do it every XX minutes
         $minutes = 5;
         if (isset($this->options["OBSERVE_STORAGE_EVERY"])) {
             $minutes = intval($this->options["OBSERVE_STORAGE_EVERY"]);
         }
         $file = $this->getResyncTimestampFile();
         $last = 0;
         if (is_file($file)) {
             $last = intval(file_get_contents($file));
         }
         if (time() - $last > $minutes * 60) {
             $this->resyncAction("resync_storage", array(), array());
         }
     }
     if ($this->options["REQUIRES_INDEXATION"]) {
         if (ConfService::backgroundActionsSupported()) {
             AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), "index", array());
         } else {
             AJXP_Controller::findActionAndApply("index", array(), array());
         }
         // Unset the REQUIRES_INDEXATION FLAG
         $meta = $currentRepo->getOption("META_SOURCES");
         unset($meta["meta.syncable"]["REQUIRES_INDEXATION"]);
         $currentRepo->addOption("META_SOURCES", $meta);
         ConfService::replaceRepository($currentRepo->getId(), $currentRepo);
     }
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $stream = isset($httpVars["stream"]);
     $separator = $stream ? "\n" : ",";
     $veryLastSeq = intval(dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle());
     $seqId = intval(AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     if ($veryLastSeq > 0 && $seqId > $veryLastSeq) {
         // This is not normal! Send a signal reload all changes from start.
         if (!$stream) {
             echo json_encode(array('changes' => array(), 'last_seq' => 1));
         } else {
             echo 'LAST_SEQ:1';
         }
         return null;
     }
     $ands = array();
     $ands[] = array("[ajxp_changes].[repository_identifier] = %s", $this->computeIdentifier($currentRepo));
     $ands[] = array("[seq] > %i", $seqId);
     if (isset($httpVars["filter"])) {
         $filter = AJXP_Utils::decodeSecureMagic($httpVars["filter"]);
         $filterLike = rtrim($filter, "/") . "/";
         $ands[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
     }
     if (count($masks)) {
         $ors = array();
         foreach ($masks as $mask) {
             $filterLike = rtrim($mask, "/") . "/";
             $ors[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
         }
         if (count($ors)) {
             $ands[] = array("%or", $ors);
         }
     }
     $res = dibi::query("SELECT\n            [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n            FROM [ajxp_changes]\n            LEFT JOIN [ajxp_index]\n                ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n            WHERE %and\n            ORDER BY [ajxp_changes].[node_id], [seq] ASC", $ands);
     if (!$stream) {
         echo '{"changes":[';
     }
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     $valuesSent = false;
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if (!empty($recycle)) {
             $this->cancelRecycleNodes($row, $recycle);
         }
         if (!isset($httpVars["flatten"]) || $httpVars["flatten"] == "false") {
             if (!$this->filterMasks($row, $masks) && !$this->filterRow($row, $filter)) {
                 if ($valuesSent) {
                     echo $separator;
                 }
                 echo json_encode($row);
                 $valuesSent = true;
             }
         } else {
             if ($row->node_id == $previousNodeId) {
                 $previousRow->target = $row->target;
                 $previousRow->seq = $row->seq;
                 if ($order[$row->type] > $order[$previousRow->type]) {
                     $previousRow->type = $row->type;
                 }
             } else {
                 if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                     if ($this->filterMasks($previousRow, $masks) || $this->filterRow($previousRow, $filter)) {
                         $previousRow = $row;
                         $previousNodeId = $row->node_id;
                         $lastSeq = $row->seq;
                         continue;
                     }
                     if ($valuesSent) {
                         echo $separator;
                     }
                     echo json_encode($previousRow);
                     $valuesSent = true;
                 }
                 $previousRow = $row;
                 $previousNodeId = $row->node_id;
             }
             $lastSeq = $row->seq;
             flush();
         }
         //CODES HERE HAVE BEEN MOVE OUT OF THE LOOP
     }
     /**********RETURN TO SENDER************/
     // is 'not NULL' included in isSet()?
     if ($previousRow && isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content") && !$this->filterRow($previousRow, $filter)) {
         if ($valuesSent) {
             echo $separator;
         }
         echo json_encode($previousRow);
         if ($previousRow->seq > $lastSeq) {
             $lastSeq = $previousRow->seq;
         }
         $valuesSent = true;
     }
     /*************************************/
     if (isset($lastSeq)) {
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     }
     return null;
 }
コード例 #30
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     $selection = new UserSelection($repository, $httpVars);
     if ($action == "read_video_data") {
         $this->logDebug("Reading video");
         $file = $selection->getUniqueFile();
         $node = new AJXP_Node($destStreamURL . $file);
         session_write_close();
         $filesize = filesize($destStreamURL . $file);
         $filename = $destStreamURL . $file;
         //$fp = fopen($destStreamURL.$file, "r");
         if (preg_match("/\\.ogv\$/", $file)) {
             header("Content-Type: video/ogg; name=\"" . basename($file) . "\"");
         } else {
             if (preg_match("/\\.mp4\$/", $file)) {
                 header("Content-Type: video/mp4; name=\"" . basename($file) . "\"");
             } else {
                 if (preg_match("/\\.m4v\$/", $file)) {
                     header("Content-Type: video/x-m4v; name=\"" . basename($file) . "\"");
                 } else {
                     if (preg_match("/\\.webm\$/", $file)) {
                         header("Content-Type: video/webm; name=\"" . basename($file) . "\"");
                     }
                 }
             }
         }
         if (isset($_SERVER['HTTP_RANGE']) && $filesize != 0) {
             $this->logDebug("Http range", array($_SERVER['HTTP_RANGE']));
             // multiple ranges, which can become pretty complex, so ignore it for now
             $ranges = explode('=', $_SERVER['HTTP_RANGE']);
             $offsets = explode('-', $ranges[1]);
             $offset = floatval($offsets[0]);
             $length = floatval($offsets[1]) - $offset;
             if (!$length) {
                 $length = $filesize - $offset;
             }
             if ($length + $offset > $filesize || $length < 0) {
                 $length = $filesize - $offset;
             }
             header('HTTP/1.1 206 Partial Content');
             header('Content-Range: bytes ' . $offset . '-' . ($offset + $length - 1) . '/' . $filesize);
             header('Accept-Ranges:bytes');
             header("Content-Length: " . $length);
             $file = fopen($filename, 'rb');
             fseek($file, 0);
             $relOffset = $offset;
             while ($relOffset > 2000000000.0) {
                 // seek to the requested offset, this is 0 if it's not a partial content request
                 fseek($file, 2000000000, SEEK_CUR);
                 $relOffset -= 2000000000;
                 // This works because we never overcome the PHP 32 bit limit
             }
             fseek($file, $relOffset, SEEK_CUR);
             while (ob_get_level()) {
                 ob_end_flush();
             }
             $readSize = 0.0;
             while (!feof($file) && $readSize < $length && connection_status() == 0) {
                 echo fread($file, 2048);
                 $readSize += 2048.0;
                 flush();
             }
             fclose($file);
         } else {
             $fp = fopen($filename, "rb");
             header("Content-Length: " . $filesize);
             header("Content-Range: bytes 0-" . ($filesize - 1) . "/" . $filesize . ";");
             header('Cache-Control: public');
             $class = $streamData["classname"];
             $stream = fopen("php://output", "a");
             call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
             fflush($stream);
             fclose($stream);
         }
         AJXP_Controller::applyHook("node.read", array($node));
     } else {
         if ($action == "get_sess_id") {
             HTMLWriter::charsetHeader("text/plain");
             print session_id();
         }
     }
 }