public function deleteGroup($groupPath) { $gUsers = AuthService::listUsers($groupPath); $gGroups = AuthService::listChildrenGroups($groupPath); if (count($gUsers) || count($gGroups)) { throw new Exception("Group is not empty, please do something with its content before trying to delete it!"); } $groups = AJXP_Utils::loadSerialFile(AJXP_VarsFilter::filter($this->getOption("USERS_DIRPATH")) . "/groups.ser"); foreach ($groups as $key => $value) { if ($value == $groupPath) { unset($groups[$key]); } } AJXP_Utils::saveSerialFile(AJXP_VarsFilter::filter($this->getOption("USERS_DIRPATH")) . "/groups.ser", $groups); }
function listRepositories() { $repos = ConfService::getRepositoriesList(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/><column messageId="ajxp_shared.9" attributeName="repo_accesses" sortType="String"/></columns>'); $repoArray = array(); $childRepos = array(); $loggedUser = AuthService::getLoggedUser(); $users = AuthService::listUsers(); foreach ($repos as $repoIndex => $repoObject) { if ($repoObject->getAccessType() == "ajxp_conf") { continue; } if (!$repoObject->hasOwner() || $repoObject->getOwner() != $loggedUser->getId()) { continue; } if (is_numeric($repoIndex)) { $repoIndex = "" . $repoIndex; } $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay())); $repoArray[$name] = $repoIndex; } // Sort the list now by name ksort($repoArray); // Append child repositories $sortedArray = array(); foreach ($repoArray as $name => $repoIndex) { $sortedArray[$name] = $repoIndex; if (isset($childRepos[$repoIndex]) && is_array($childRepos[$repoIndex])) { foreach ($childRepos[$repoIndex] as $childData) { $sortedArray[$childData["name"]] = $childData["index"]; } } } foreach ($sortedArray as $name => $repoIndex) { $repoObject =& $repos[$repoIndex]; $repoAccesses = array(); foreach ($users as $userId => $userObject) { if (!$userObject->hasParent()) { continue; } if ($userObject->canWrite($repoIndex)) { $repoAccesses[] = $userId . " (rw)"; } else { if ($userObject->canRead($repoIndex)) { $repoAccesses[] = $userId . " (r)"; } } } $metaData = array("repository_id" => $repoIndex, "accessType" => $repoObject->getAccessType(), "icon" => "document_open_remote.png", "openicon" => "document_open_remote.png", "parentname" => "/repositories", "repo_accesses" => implode(", ", $repoAccesses), "ajxp_mime" => "shared_repository"); AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData); } }
function listUsers() { print '<columns switchGridMode="filelist"><column messageString="User Name" attributeName="ajxp_label" sortType="String"/><column messageString="Is Admin" attributeName="isAdmin" sortType="String"/></columns>'; if (!ENABLE_USERS) { return; } $users = AuthService::listUsers(); $loggedUser = AuthService::getLoggedUser(); $userArray = array(); foreach ($users as $userObject) { $userArray[Utils::xmlEntities($userObject->getId())] = $userObject; } ksort($userArray); foreach ($userArray as $userObject) { $isAdmin = $userObject->isAdmin(); $userId = Utils::xmlEntities($userObject->getId()); $icon = "user" . ($userId == "guest" ? "_guest" : ($isAdmin ? "_admin" : "")); print '<tree text="' . $userId . '" isAdmin="' . ($isAdmin ? "True" : "False") . '" icon="' . $icon . '.png" openicon="' . $icon . '.png" filename="/users/' . $userId . '" parentname="/users" is_file="1" ajxp_mime="user' . ($userId != "guest" && $userId != $loggedUser->getId() ? "_editable" : "") . '" />'; } }
public function listUsers($root, $child, $hashValue = null, $returnNodes = false, $findNodePosition = null) { $USER_PER_PAGE = 50; if ($root == "users") { $baseGroup = "/"; } else { $baseGroup = substr($root, strlen("users")); } if ($findNodePosition != null && $hashValue == null) { // Add groups offset $groups = AuthService::listChildrenGroups($baseGroup); $offset = 0; if (count($groups)) { $offset = count($groups); } $position = AuthService::findUserPage($baseGroup, $findNodePosition, $USER_PER_PAGE); if ($position != -1) { $key = "/data/" . $root . "/" . $findNodePosition; $data = array($key => AJXP_XMLWriter::renderNode($key, $findNodePosition, true, array("page_position" => $position), true, false)); return $data; } else { // Loop on each page to find the correct page. $count = AuthService::authCountUsers($baseGroup); $pages = ceil($count / $USER_PER_PAGE); for ($i = 0; $i < $pages; $i++) { $tests = $this->listUsers($root, $child, $i + 1, true, $findNodePosition); if (is_array($tests) && isset($tests["/data/" . $root . "/" . $findNodePosition])) { return array("/data/" . $root . "/" . $findNodePosition => str_replace("ajxp_mime", "page_position='" . ($i + 1) . "' ajxp_mime", $tests["/data/" . $root . "/" . $findNodePosition])); } } } return array(); } $allNodes = array(); $columns = '<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.users"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.102" attributeName="object_id" sortType="String" defaultWidth="10%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="10%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; if (AuthService::driverSupportsAuthSchemes()) { $columns = '<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.users_authscheme"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.102" attributeName="object_id" sortType="String" defaultWidth="10%"/> <column messageId="ajxp_conf.115" attributeName="auth_scheme" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; } if (!$returnNodes) { AJXP_XMLWriter::sendFilesListComponentConfig($columns); } if (!AuthService::usersEnabled()) { return array(); } if (empty($hashValue)) { $hashValue = 1; } $count = AuthService::authCountUsers($baseGroup, "", null, null, false); if (AuthService::authSupportsPagination() && $count >= $USER_PER_PAGE) { $offset = ($hashValue - 1) * $USER_PER_PAGE; if (!$returnNodes) { AJXP_XMLWriter::renderPaginationData($count, $hashValue, ceil($count / $USER_PER_PAGE)); } $users = AuthService::listUsers($baseGroup, "", $offset, $USER_PER_PAGE, true, false); if ($hashValue == 1) { $groups = AuthService::listChildrenGroups($baseGroup); } else { $groups = array(); } } else { $users = AuthService::listUsers($baseGroup, "", -1, -1, true, false); $groups = AuthService::listChildrenGroups($baseGroup); } foreach ($groups as $groupId => $groupLabel) { $nodeKey = "/data/" . $root . "/" . ltrim($groupId, "/"); $meta = array("icon" => "users-folder.png", "ajxp_mime" => "group", "object_id" => $groupId); if (in_array($nodeKey, $this->currentBookmarks)) { $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png")); } $xml = AJXP_XMLWriter::renderNode($nodeKey, $groupLabel, false, $meta, true, false); if (!$returnNodes) { print $xml; } else { $allNodes[$nodeKey] = $xml; } } $mess = ConfService::getMessages(); $loggedUser = AuthService::getLoggedUser(); $userArray = array(); foreach ($users as $userObject) { $label = $userObject->getId(); if ($userObject->hasParent()) { $label = $userObject->getParent() . "000" . $label; } else { $children = ConfService::getConfStorageImpl()->getUserChildren($label); foreach ($children as $addChild) { $userArray[$label . "000" . $addChild->getId()] = $addChild; } } $userArray[$label] = $userObject; } ksort($userArray); foreach ($userArray as $userObject) { $repos = ConfService::getConfStorageImpl()->listRepositories($userObject); $isAdmin = $userObject->isAdmin(); $userId = $userObject->getId(); $icon = "user" . ($userId == "guest" ? "_guest" : ($isAdmin ? "_admin" : "")); if ($userObject->hasParent()) { $icon = "user_child"; } if ($isAdmin) { $rightsString = $mess["ajxp_conf.63"]; } else { $r = array(); foreach ($repos as $repoId => $repository) { if ($repository->getAccessType() == "ajxp_shared") { continue; } if (!$userObject->canRead($repoId) && !$userObject->canWrite($repoId)) { continue; } $rs = $userObject->canRead($repoId) ? "r" : ""; $rs .= $userObject->canWrite($repoId) ? "w" : ""; $r[] = $repository->getDisplay() . " (" . $rs . ")"; } $rightsString = implode(", ", $r); } $nodeLabel = $userId; $test = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, ""); if (!empty($test)) { $nodeLabel = $test; } $scheme = AuthService::getAuthScheme($userId); $nodeKey = "/data/{$root}/" . $userId; $roles = array_filter(array_keys($userObject->getRoles()), array($this, "filterReservedRoles")); $meta = array("isAdmin" => $mess[$isAdmin ? "ajxp_conf.14" : "ajxp_conf.15"], "icon" => $icon . ".png", "object_id" => $userId, "auth_scheme" => $scheme != null ? $scheme : "", "rights_summary" => $rightsString, "ajxp_roles" => implode(", ", $roles), "ajxp_mime" => "user" . ($userId != "guest" && $userId != $loggedUser->getId() ? "_editable" : "")); if (in_array($nodeKey, $this->currentBookmarks)) { $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png")); } $xml = AJXP_XMLWriter::renderNode($nodeKey, $nodeLabel, true, $meta, true, false); if (!$returnNodes) { print $xml; } else { $allNodes[$nodeKey] = $xml; } } return $allNodes; }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } if (isset($dir) && $action != "upload") { $dir = SystemTextEncoding::fromUTF8($dir); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // SWITCH THE ROOT REPOSITORY //------------------------------------ case "switch_repository": if (!isset($repository_id)) { break; } $dirList = ConfService::getRepositoriesList(); /** @var $repository_id string */ if (!isset($dirList[$repository_id])) { $errorMessage = "Trying to switch to an unkown repository!"; break; } ConfService::switchRootDir($repository_id); // Load try to init the driver now, to trigger an exception // if it's not loading right. ConfService::loadRepositoryDriver(); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $user = AuthService::getLoggedUser(); $activeRepId = ConfService::getCurrentRepositoryId(); $user->setArrayPref("history", "last_repository", $activeRepId); $user->save("user"); } //$logMessage = "Successfully Switched!"; $this->logInfo("Switch Repository", array("rep. id" => $repository_id)); break; //------------------------------------ // SEND XML REGISTRY //------------------------------------ //------------------------------------ // SEND XML REGISTRY //------------------------------------ case "get_xml_registry": case "state": $regDoc = AJXP_PluginsService::getXmlRegistry(); $changes = AJXP_Controller::filterRegistryFromRole($regDoc); if ($changes) { AJXP_PluginsService::updateXmlRegistry($regDoc); } $clone = $regDoc->cloneNode(true); $clonePath = new DOMXPath($clone); $serverCallbacks = $clonePath->query("//serverCallback|hooks"); foreach ($serverCallbacks as $callback) { $callback->parentNode->removeChild($callback); } $xPath = ''; if (isset($httpVars["xPath"])) { $xPath = ltrim(AJXP_Utils::securePath($httpVars["xPath"]), "/"); } if (!empty($xPath)) { $nodes = $clonePath->query($xPath); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($nodes->item(0)); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $xPath)); if ($nodes->length) { print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML($nodes->item(0))); } AJXP_XMLWriter::close("ajxp_registry_part"); } } else { AJXP_Utils::safeIniSet("zlib.output_compression", "4096"); if ($httpVars["format"] == "json") { $data = AJXP_XMLWriter::xmlToArray($clone); HTMLWriter::charsetHeader("application/json"); echo json_encode($data); } else { header('Content-Type: application/xml; charset=UTF-8'); print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML()); } } break; //------------------------------------ // BOOKMARK BAR //------------------------------------ //------------------------------------ // BOOKMARK BAR //------------------------------------ case "get_bookmarks": $bmUser = null; if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser = AuthService::getLoggedUser(); } else { if (!AuthService::usersEnabled()) { $confStorage = ConfService::getConfStorageImpl(); $bmUser = $confStorage->createUserObject("shared"); } } if ($bmUser == null) { AJXP_XMLWriter::header(); AJXP_XMLWriter::close(); } $driver = ConfService::loadRepositoryDriver(); if (!is_a($driver, "AjxpWrapperProvider")) { $driver = false; } if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) { $bmPath = AJXP_Utils::decodeSecureMagic($httpVars["bm_path"]); if ($httpVars["bm_action"] == "add_bookmark") { $title = ""; if (isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); } if ($title == "" && $bmPath == "/") { $title = ConfService::getCurrentRootDirDisplay(); } $bmUser->addBookMark($bmPath, $title); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->setMetadata("ajxp_bookmarked", array("ajxp_bookmarked" => "true"), true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "delete_bookmark") { $bmUser->removeBookmark($bmPath); if ($driver) { $node = new AJXP_Node($driver->getResourceUrl($bmPath)); $node->removeMetadata("ajxp_bookmarked", true, AJXP_METADATA_SCOPE_REPOSITORY, true); } } else { if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) { $title = AJXP_Utils::decodeSecureMagic($httpVars["bm_title"]); $bmUser->renameBookmark($bmPath, $title); } } } AJXP_Controller::applyHook("msg.instant", array("<reload_bookmarks/>", ConfService::getRepository()->getId())); if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) { $bmUser->save("user"); AuthService::updateUser($bmUser); } else { if (!AuthService::usersEnabled()) { $bmUser->save("user"); } } } AJXP_XMLWriter::header(); AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks(), true, isset($httpVars["format"]) ? $httpVars["format"] : "legacy"); AJXP_XMLWriter::close(); break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "save_user_pref": $userObject = AuthService::getLoggedUser(); $i = 0; while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) { $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM); $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i])); if ($prefName == "password") { continue; } if ($prefName != "pending_folder" && $userObject == null) { $i++; continue; } $userObject->setPref($prefName, $prefValue); $userObject->save("user"); AuthService::updateUser($userObject); //setcookie("AJXP_$prefName", $prefValue); $i++; } header("Content-Type:text/plain"); print "SUCCESS"; break; //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ //------------------------------------ // SAVE USER PREFERENCE //------------------------------------ case "custom_data_edit": case "user_create_user": $data = array(); if ($action == "user_create_user" && isset($httpVars["NEW_new_user_id"])) { $updating = false; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $original_id = AJXP_Utils::decodeSecureMagic($data["new_user_id"]); $data["new_user_id"] = AJXP_Utils::decodeSecureMagic($data["new_user_id"], AJXP_SANITIZE_EMAILCHARS); if ($original_id != $data["new_user_id"]) { throw new Exception(str_replace("%s", $data["new_user_id"], $mess["ajxp_conf.127"])); } if (AuthService::userExists($data["new_user_id"], "w")) { throw new Exception($mess["ajxp_conf.43"]); } $loggedUser = AuthService::getLoggedUser(); $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, ""); if (!empty($limit) && intval($limit) > 0) { $count = count($this->getUserChildren($loggedUser->getId())); if ($count >= $limit) { throw new Exception($mess['483']); } } AuthService::createUser($data["new_user_id"], $data["new_password"]); $userObject = ConfService::getConfStorageImpl()->createUserObject($data["new_user_id"]); $userObject->setParent($loggedUser->getId()); $userObject->save('superuser'); $userObject->personalRole->clearAcls(); $userObject->setGroupPath($loggedUser->getGroupPath()); $userObject->setProfile("shared"); } else { if ($action == "user_create_user" && isset($httpVars["NEW_existing_user_id"])) { $updating = true; AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "NEW_"); $userId = $data["existing_user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } if (!empty($data["new_password"])) { AuthService::updatePassword($userId, $data["new_password"]); } } else { $updating = false; $userObject = AuthService::getLoggedUser(); AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "PREFERENCES_"); } } $paramNodes = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'user') and @expose='true']", "node", false, false, true); $rChanges = false; if (is_array($paramNodes) && count($paramNodes)) { foreach ($paramNodes as $xmlNode) { if ($xmlNode->getAttribute("expose") == "true") { $parentNode = $xmlNode->parentNode->parentNode; $pluginId = $parentNode->getAttribute("id"); if (empty($pluginId)) { $pluginId = $parentNode->nodeName . "." . $parentNode->getAttribute("name"); } $name = $xmlNode->getAttribute("name"); if (isset($data[$name]) || $data[$name] === "") { if ($data[$name] == "__AJXP_VALUE_SET__") { continue; } if ($data[$name] === "" || $userObject->parentRole == null || $userObject->parentRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name] || $userObject->personalRole->filterParameterValue($pluginId, $name, AJXP_REPO_SCOPE_ALL, "") != $data[$name]) { $userObject->personalRole->setParameterValue($pluginId, $name, $data[$name]); $rChanges = true; } } } } } if ($rChanges) { AuthService::updateRole($userObject->personalRole, $userObject); $userObject->recomputeMergedRole(); if ($action == "custom_data_edit") { AuthService::updateUser($userObject); } } if ($action == "user_create_user") { AJXP_Controller::applyHook($updating ? "user.after_update" : "user.after_create", array($userObject)); if (isset($data["send_email"]) && $data["send_email"] == true && !empty($data["email"])) { $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer"); if ($mailer !== false) { $mess = ConfService::getMessages(); $link = AJXP_Utils::detectServerURL(); $apptitle = ConfService::getCoreConf("APPLICATION_TITLE"); $subject = str_replace("%s", $apptitle, $mess["507"]); $body = str_replace(array("%s", "%link", "%user", "%pass"), array($apptitle, $link, $data["new_user_id"], $data["new_password"]), $mess["508"]); $mailer->sendMail(array($data["email"]), $subject, $body); } } echo "SUCCESS"; } else { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage($mess["241"], null); AJXP_XMLWriter::close(); } break; case "user_update_user": if (!isset($httpVars["user_id"])) { throw new Exception("invalid arguments"); } $userId = $httpVars["user_id"]; if (!AuthService::userExists($userId)) { throw new Exception("Cannot find user"); } $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("Cannot find user"); } $paramsString = ConfService::getCoreConf("NEWUSERS_EDIT_PARAMETERS", "conf"); $result = array(); $params = explode(",", $paramsString); foreach ($params as $p) { $result[$p] = $userObject->personalRole->filterParameterValue("core.conf", $p, AJXP_REPO_SCOPE_ALL, ""); } HTMLWriter::charsetHeader("application/json"); echo json_encode($result); break; //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ //------------------------------------ // WEBDAV PREFERENCES //------------------------------------ case "webdav_preferences": $userObject = AuthService::getLoggedUser(); $webdavActive = false; $passSet = false; $digestSet = false; // Detect http/https and host if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") { $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST"); } else { $baseURL = AJXP_Utils::detectServerURL(); } $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/"; $davData = $userObject->getPref("AJXP_WEBDAV_DATA"); $digestSet = isset($davData["HA1"]); if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) { if (!empty($httpVars["activate"])) { $activate = $httpVars["activate"] == "true" ? true : false; if (empty($davData)) { $davData = array(); } $davData["ACTIVE"] = $activate; } if (!empty($httpVars["webdav_pass"])) { $password = $httpVars["webdav_pass"]; if (function_exists('mcrypt_encrypt')) { $user = $userObject->getId(); $secret = defined("AJXP_SAFE_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#"; $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB)); } $davData["PASS"] = $password; } $userObject->setPref("AJXP_WEBDAV_DATA", $davData); $userObject->save("user"); } if (!empty($davData)) { $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true; $passSet = isset($davData["PASS"]); } $repoList = ConfService::getRepositoriesList(); $davRepos = array(); $loggedUser = AuthService::getLoggedUser(); foreach ($repoList as $repoIndex => $repoObject) { $accessType = $repoObject->getAccessType(); $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType); if (is_a($driver, "AjxpWrapperProvider") && !$repoObject->getOption("AJXP_WEBDAV_DISABLED") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) { $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug()); } } $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "digest_set" => $digestSet, "webdav_force_basic" => ConfService::getCoreConf("WEBDAV_FORCE_BASIC") === true, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos); HTMLWriter::charsetHeader("application/json"); print json_encode($prefs); break; case "get_user_template_logo": $tplId = $httpVars["template_id"]; $iconFormat = $httpVars["icon_format"]; $repo = ConfService::getRepositoryById($tplId); $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat)); if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) { header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)); header('Pragma:'); header('Cache-Control: public'); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo); } else { $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png"; header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\""); header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo)); header('Pragma:'); header('Cache-Control: public'); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo); } break; case "get_user_templates_definition": AJXP_XMLWriter::header("repository_templates"); $count = 0; $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => 1), $count); $pServ = AJXP_PluginsService::getInstance(); foreach ($repositories as $repo) { if (!$repo->isTemplate) { continue; } if (!$repo->getOption("TPL_USER_CAN_CREATE")) { continue; } $repoId = $repo->getId(); $repoLabel = $repo->getDisplay(); $repoType = $repo->getAccessType(); print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">"; $driverPlug = $pServ->getPluginByTypeName("access", $repoType); $params = $driverPlug->getManifestRawContent("//param", "node"); $tplDefined = $repo->getOptionsDefined(); $defaultLabel = ''; foreach ($params as $paramNode) { $name = $paramNode->getAttribute("name"); if (strpos($name, "TPL_") === 0) { if ($name == "TPL_DEFAULT_LABEL") { $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name)); } continue; } if (in_array($paramNode->getAttribute("name"), $tplDefined)) { continue; } if ($paramNode->getAttribute('no_templates') == 'true') { continue; } print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode)); } // ADD LABEL echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>'; print "</template>"; } AJXP_XMLWriter::close("repository_templates"); break; case "user_create_repository": $tplId = $httpVars["template_id"]; $tplRepo = ConfService::getRepositoryById($tplId); $options = array(); AJXP_Utils::parseStandardFormParameters($httpVars, $options); $loggedUser = AuthService::getLoggedUser(); $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, $loggedUser->getId()); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath)) { $newRep->setGroupPath($gPath); } $res = ConfService::addRepository($newRep); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[426]); } else { // Make sure we do not overwrite otherwise loaded rights. $loggedUser->load(); $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw"); $loggedUser->save("superuser"); $loggedUser->recomputeMergedRole(); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[425], null); AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId()); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_repository": $repoId = $httpVars["repository_id"]; $repository = ConfService::getRepositoryById($repoId); if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to perform this operation!"); } $res = ConfService::deleteRepository($repoId); AJXP_XMLWriter::header(); if ($res == -1) { AJXP_XMLWriter::sendMessage(null, $mess[427]); } else { $loggedUser = AuthService::getLoggedUser(); // Make sure we do not override remotely set rights $loggedUser->load(); $loggedUser->personalRole->setAcl($repoId, ""); $loggedUser->save("superuser"); AuthService::updateUser($loggedUser); AJXP_XMLWriter::sendMessage($mess[428], null); AJXP_XMLWriter::reloadRepositoryList(); } AJXP_XMLWriter::close(); break; case "user_delete_user": $userId = $httpVars["user_id"]; $userObject = ConfService::getConfStorageImpl()->createUserObject($userId); if ($userObject == null || !$userObject->hasParent() || $userObject->getParent() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to edit this user"); } AuthService::deleteUser($userId); echo "SUCCESS"; break; case "user_list_authorized_users": $defaultFormat = "html"; HTMLWriter::charsetHeader(); if (!ConfService::getAuthDriverImpl()->usersEditable()) { break; } $loggedUser = AuthService::getLoggedUser(); $crtValue = $httpVars["value"]; $usersOnly = isset($httpVars["users_only"]) && $httpVars["users_only"] == "true"; $existingOnly = isset($httpVars["existing_only"]) && $httpVars["existing_only"] == "true"; if (!empty($crtValue)) { $regexp = '^' . $crtValue; } else { $regexp = null; } $skipDisplayWithoutRegexp = ConfService::getCoreConf("USERS_LIST_REGEXP_MANDATORY", "conf"); if ($skipDisplayWithoutRegexp && $regexp == null) { print "<ul></ul>"; break; } $limit = intval(ConfService::getCoreConf("USERS_LIST_COMPLETE_LIMIT", "conf")); $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf"); $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf"); $baseGroup = "/"; if ($regexp == null && !$displayAll || $regexp != null && !$searchAll) { $baseGroup = AuthService::filterBaseGroup("/"); } AuthService::setGroupFiltering(false); $allUsers = AuthService::listUsers($baseGroup, $regexp, 0, $limit, false); if (!$usersOnly) { $allGroups = array(); $roleOrGroup = ConfService::getCoreConf("GROUP_OR_ROLE", "conf"); $rolePrefix = $excludeString = $includeString = null; if (!is_array($roleOrGroup)) { $roleOrGroup = array("group_switch_value" => $roleOrGroup); } $listRoleType = false; if (isset($roleOrGroup["PREFIX"])) { $rolePrefix = $loggedUser->mergedRole->filterParameterValue("core.conf", "PREFIX", null, $roleOrGroup["PREFIX"]); $excludeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "EXCLUDED", null, $roleOrGroup["EXCLUDED"]); $includeString = $loggedUser->mergedRole->filterParameterValue("core.conf", "INCLUDED", null, $roleOrGroup["INCLUDED"]); $listUserRolesOnly = $loggedUser->mergedRole->filterParameterValue("core.conf", "LIST_ROLE_BY", null, $roleOrGroup["LIST_ROLE_BY"]); if (is_array($listUserRolesOnly) && isset($listUserRolesOnly["group_switch_value"])) { switch ($listUserRolesOnly["group_switch_value"]) { case "userroles": $listRoleType = true; break; case "allroles": $listRoleType = false; break; default: break; } } } switch (strtolower($roleOrGroup["group_switch_value"])) { case 'user': // donothing break; case 'group': $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $allGroups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } break; case 'role': $allGroups = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); break; case 'rolegroup': $groups = array(); $authGroups = AuthService::listChildrenGroups($baseGroup); foreach ($authGroups as $gId => $gName) { $groups["AJXP_GRP_" . rtrim($baseGroup, "/") . "/" . ltrim($gId, "/")] = $gName; } $roles = $this->getUserRoleList($loggedUser, $rolePrefix, $includeString, $excludeString, $listRoleType); empty($groups) ? $allGroups = $roles : (empty($roles) ? $allGroups = $groups : ($allGroups = array_merge($groups, $roles))); //$allGroups = array_merge($groups, $roles); break; default: break; } } $users = ""; $index = 0; if ($regexp != null && (!count($allUsers) || !empty($crtValue) && !array_key_exists(strtolower($crtValue), $allUsers)) && ConfService::getCoreConf("USER_CREATE_USERS", "conf") && !$existingOnly) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}'><span class='user_entry_label'>{$crtValue} (" . $mess["448"] . ")</span></li>"; } else { if ($existingOnly && !empty($crtValue)) { $users .= "<li class='complete_user_entry_temp' data-temporary='true' data-label='{$crtValue}' data-entry_id='{$crtValue}'><span class='user_entry_label'>{$crtValue}</span></li>"; } } $mess = ConfService::getMessages(); if ($regexp == null && !$usersOnly) { $users .= "<li class='complete_group_entry' data-group='AJXP_GRP_/' data-label='" . $mess["447"] . "'><span class='user_entry_label'>" . $mess["447"] . "</span></li>"; } $indexGroup = 0; if (!$usersOnly && is_array($allGroups)) { foreach ($allGroups as $groupId => $groupLabel) { if ($regexp == null || preg_match("/{$regexp}/i", $groupLabel)) { $users .= "<li class='complete_group_entry' data-group='{$groupId}' data-label='{$groupLabel}' data-entry_id='{$groupId}'><span class='user_entry_label'>" . $groupLabel . "</span></li>"; $indexGroup++; } if ($indexGroup == $limit) { break; } } } if ($regexp == null && method_exists($this, "listUserTeams")) { $teams = $this->listUserTeams(); foreach ($teams as $tId => $tData) { $users .= "<li class='complete_group_entry' data-group='/AJXP_TEAM/{$tId}' data-label='[team] " . $tData["LABEL"] . "'><span class='user_entry_label'>[team] " . $tData["LABEL"] . "</span></li>"; } } foreach ($allUsers as $userId => $userObject) { if ($userObject->getId() == $loggedUser->getId()) { continue; } if (!$userObject->hasParent() && ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") || $userObject->getParent() == $loggedUser->getId()) { $userLabel = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId); //if($regexp != null && ! (preg_match("/$regexp/i", $userId) || preg_match("/$regexp/i", $userLabel)) ) continue; if (empty($userLabel)) { $userLabel = $userId; } $userDisplay = $userLabel == $userId ? $userId : $userLabel . " ({$userId})"; if (ConfService::getCoreConf("USERS_LIST_HIDE_LOGIN", "conf") == true && $userLabel != $userId) { $userDisplay = $userLabel; } $users .= "<li class='complete_user_entry' data-label='{$userLabel}' data-entry_id='{$userId}'><span class='user_entry_label'>" . $userDisplay . "</span></li>"; $index++; } if ($index == $limit) { break; } } if (strlen($users)) { print "<ul>" . $users . "</ul>"; } AuthService::setGroupFiltering(true); break; case "load_repository_info": $data = array(); $repo = ConfService::getRepository(); if ($repo != null) { $users = AuthService::countUsersForRepository(ConfService::getRepository()->getId(), true); $data["core.users"] = $users; if (isset($httpVars["collect"]) && $httpVars["collect"] == "true") { AJXP_Controller::applyHook("repository.load_info", array(&$data)); } } HTMLWriter::charsetHeader("application/json"); echo json_encode($data); break; case "get_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { if (isset($httpVars["user_id"]) && AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->isAdmin()) { $context = array("USER" => $httpVars["user_id"]); } else { $context = array("USER" => AuthService::getLoggedUser()->getId()); } $this->loadBinary($context, $httpVars["binary_id"]); } } break; case "get_global_binary_param": if (isset($httpVars["tmp_file"])) { $file = AJXP_Utils::getAjxpTmpDir() . "/" . AJXP_Utils::securePath($httpVars["tmp_file"]); if (isset($file)) { header("Content-Type:image/png"); readfile($file); } } else { if (isset($httpVars["binary_id"])) { $this->loadBinary(array(), $httpVars["binary_id"]); } } break; case "store_binary_temp": if (count($fileVars)) { $keys = array_keys($fileVars); $boxData = $fileVars[$keys[0]]; $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { } else { $rand = substr(md5(time()), 0, 6); $tmp = $rand . "-" . $boxData["name"]; @move_uploaded_file($boxData["tmp_name"], AJXP_Utils::getAjxpTmpDir() . "/" . $tmp); } } if (isset($tmp) && file_exists(AJXP_Utils::getAjxpTmpDir() . "/" . $tmp)) { print '<script type="text/javascript">'; print 'parent.formManagerHiddenIFrameSubmission("' . $tmp . '");'; print '</script>'; } break; default: break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } return $xmlBuffer; }
function listUsers($root, $child, $hashValue = null) { $columns = '<columns switchGridMode="filelist" template_name="ajxp_conf.users"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="10%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; if (AuthService::driverSupportsAuthSchemes()) { $columns = '<columns switchGridMode="filelist" template_name="ajxp_conf.users"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String" defaultWidth="40%"/> <column messageId="ajxp_conf.115" attributeName="auth_scheme" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String" defaultWidth="5%"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String" defaultWidth="15%"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String" defaultWidth="15%"/> </columns>'; } AJXP_XMLWriter::sendFilesListComponentConfig($columns); if (!AuthService::usersEnabled()) { return; } $count = AuthService::authCountUsers(); $USER_PER_PAGE = 50; if (empty($hashValue)) { $hashValue = 1; } if (AuthService::authSupportsPagination() && $count > $USER_PER_PAGE) { $offset = ($hashValue - 1) * $USER_PER_PAGE; AJXP_XMLWriter::renderPaginationData($count, $hashValue, ceil($count / $USER_PER_PAGE)); $users = AuthService::listUsers("", $offset, $USER_PER_PAGE); } else { $users = AuthService::listUsers(); } $mess = ConfService::getMessages(); $repos = ConfService::getRepositoriesList(); $loggedUser = AuthService::getLoggedUser(); $userArray = array(); foreach ($users as $userIndex => $userObject) { $label = $userObject->getId(); if ($userObject->hasParent()) { $label = $userObject->getParent() . "000" . $label; } $userArray[$label] = $userObject; } ksort($userArray); foreach ($userArray as $userObject) { $isAdmin = $userObject->isAdmin(); $userId = $userObject->getId(); $icon = "user" . ($userId == "guest" ? "_guest" : ($isAdmin ? "_admin" : "")); if ($userObject->hasParent()) { $icon = "user_child"; } $rightsString = ""; if ($isAdmin) { $rightsString = $mess["ajxp_conf.63"]; } else { $r = array(); foreach ($repos as $repoId => $repository) { if ($repository->getAccessType() == "ajxp_shared") { continue; } if (!$userObject->canRead($repoId) && !$userObject->canWrite($repoId)) { continue; } $rs = $userObject->canRead($repoId) ? "r" : ""; $rs .= $userObject->canWrite($repoId) ? "w" : ""; $r[] = $repository->getDisplay() . " (" . $rs . ")"; } $rightsString = implode(", ", $r); } $nodeLabel = $userId; $scheme = AuthService::getAuthScheme($userId); AJXP_XMLWriter::renderNode("/users/" . $userId, $nodeLabel, true, array("isAdmin" => $mess[$isAdmin ? "ajxp_conf.14" : "ajxp_conf.15"], "icon" => $icon . ".png", "auth_scheme" => $scheme != null ? $scheme : "", "rights_summary" => $rightsString, "ajxp_roles" => implode(", ", array_keys($userObject->getRoles())), "ajxp_mime" => "user" . ($userId != "guest" && $userId != $loggedUser->getId() ? "_editable" : ""))); } }
/** Decode a user supplied password before using it */ function decodeUserPassword($password) { if (function_exists('mcrypt_decrypt')) { $users = AuthService::listUsers(); // The initialisation vector is only required to avoid a warning, as ECB ignore IV $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND); // We have encoded as base64 so if we need to store the result in a database, it can be stored in text column $password = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($this->getId() . "CDAFx¨op#"), base64_decode($password), MCRYPT_MODE_ECB, $iv)); } return $password; }
protected function gatherUsers(&$users, $startGroup = "/") { $u = AuthService::listUsers($startGroup); $users = array_merge($users, array_keys($u)); $g = AuthService::listChildrenGroups($startGroup); if (count($g)) { foreach ($g as $gName => $gLabel) { $this->gatherUsers($users, $startGroup . $gName); } } }
public function listRepositories() { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="user_dash.9" attributeName="parent_label" sortType="String"/><column messageId="user_dash.9" attributeName="repo_accesses" sortType="String"/></columns>'); $repoArray = array(); $loggedUser = AuthService::getLoggedUser(); $count = 0; $repos = ConfService::listRepositoriesWithCriteria(array("owner_user_id" => $loggedUser->getId()), $count); $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf"); $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf"); if ($searchAll || $displayAll) { $baseGroup = "/"; } else { $baseGroup = AuthService::filterBaseGroup("/"); } AuthService::setGroupFiltering(false); $users = AuthService::listUsers($baseGroup); $minisites = $this->listSharedFiles("minisites"); foreach ($repos as $repoIndex => $repoObject) { if ($repoObject->getAccessType() == "ajxp_conf") { continue; } if (!$repoObject->hasOwner() || $repoObject->getOwner() != $loggedUser->getId()) { continue; } if (is_numeric($repoIndex)) { $repoIndex = "" . $repoIndex; } $name = (isset($minisites[$repoIndex]) ? "[Minisite] " : "") . AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay())); $repoArray[$name] = $repoIndex; } // Sort the list now by name ksort($repoArray); foreach ($repoArray as $name => $repoIndex) { $repoObject =& $repos[$repoIndex]; $repoAccesses = array(); foreach ($users as $userId => $userObject) { if ($userObject->getId() == $loggedUser->getId()) { continue; } $label = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId); if (empty($label)) { $label = $userId; } $acl = $userObject->mergedRole->getAcl($repoObject->getId()); if (!empty($acl)) { $repoAccesses[] = $label . " (" . $acl . ")"; } } $parent = $repoObject->getParentId(); $parentRepo =& $repos[$parent]; $parentLabel = $this->metaIcon("folder-open") . $parentRepo->getDisplay(); $repoPath = $repoObject->getOption("PATH"); $parentPath = $parentRepo->getOption("PATH"); $parentLabel .= " (" . str_replace($parentPath, "", $repoPath) . ")"; $metaData = array("repository_id" => $repoIndex, "icon" => "document_open_remote.png", "openicon" => "document_open_remote.png", "parentname" => "/repositories", "parent_label" => $parentLabel, "repo_accesses" => count($repoAccesses) ? $this->metaIcon("share-sign") . implode(", ", $repoAccesses) : "", "ajxp_mime" => "shared_repository"); AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData); } }
function listUsers() { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"> <column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String"/> <column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String"/> <column messageId="ajxp_conf.70" attributeName="ajxp_roles" sortType="String"/> <column messageId="ajxp_conf.62" attributeName="rights_summary" sortType="String"/> </columns>'); if (!ENABLE_USERS) { return; } $users = AuthService::listUsers(); $mess = ConfService::getMessages(); $repos = ConfService::getRepositoriesList(); $loggedUser = AuthService::getLoggedUser(); $userArray = array(); foreach ($users as $userIndex => $userObject) { $label = $userObject->getId(); if ($userObject->hasParent()) { $label = $userObject->getParent() . "000" . $label; } $userArray[$label] = $userObject; } ksort($userArray); foreach ($userArray as $userObject) { $isAdmin = $userObject->isAdmin(); $userId = AJXP_Utils::xmlEntities($userObject->getId()); $icon = "user" . ($userId == "guest" ? "_guest" : ($isAdmin ? "_admin" : "")); if ($userObject->hasParent()) { $icon = "user_child"; } $rightsString = ""; if ($isAdmin) { $rightsString = $mess["ajxp_conf.63"]; } else { $r = array(); foreach ($repos as $repoId => $repository) { if ($repository->getAccessType() == "ajxp_shared") { continue; } if ($userObject->canWrite($repoId)) { $r[] = $repository->getDisplay() . " (rw)"; } else { if ($userObject->canRead($repoId)) { $r[] = $repository->getDisplay() . " (r)"; } } } $rightsString = implode(", ", $r); } AJXP_XMLWriter::renderNode("/users/" . $userId, $userId, true, array("isAdmin" => $mess[$isAdmin ? "ajxp_conf.14" : "ajxp_conf.15"], "icon" => $icon . ".png", "rights_summary" => AJXP_Utils::xmlEntities($rightsString, true), "ajxp_roles" => implode(", ", array_keys($userObject->getRoles())), "ajxp_mime" => "user" . ($userId != "guest" && $userId != $loggedUser->getId() ? "_editable" : ""))); } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::securePath($dir); if ($action != "upload") { $dir = 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": AJXP_Logger::logAction("Download", array("files" => $selection)); @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE); @register_shutdown_function("restore_error_handler"); $zip = false; if ($selection->isUnique()) { if (is_dir($this->urlBase . $selection->getUniqueFile())) { $zip = true; $base = basename($selection->getUniqueFile()); $dir .= "/" . dirname($selection->getUniqueFile()); } else { if (!file_exists($this->urlBase . $selection->getUniqueFile())) { throw new Exception("Cannot find file!"); } } } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpDownload.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing"); } register_shutdown_function("unlink", $file); $localName = ($base == "" ? "Files" : $base) . ".zip"; $this->readFile($file, "force-download", $localName, false, false, true); } else { $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download"); } 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 = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpCompression.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing file {$localName}"); } register_shutdown_function("unlink", $file); copy($file, $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName)); @rename($this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName), $this->urlBase . $dir . "/" . $localName); $reloadContextNode = true; $pendingSelection = $localName; break; case "stat": clearstatcache(); $stat = @stat($this->urlBase . $selection->getUniqueFile()); header("Content-type:application/json"); if (!$stat) { print '{}'; } else { print json_encode($stat); } break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "get_content": $this->readFile($this->urlBase . $selection->getUniqueFile(), "plain"); 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($httpVars["file"]); AJXP_Logger::logAction("Online Edition", array("file" => $file)); if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") { $code = base64_decode($code); } else { $code = SystemTextEncoding::magicDequote($code); $code = str_replace("<", "<", $code); } $fileName = $this->urlBase . $file; 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); header("Content-Type:text/plain"); print $mess[115]; break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $success = $error = array(); $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $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 { $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false); } if (count($error)) { throw new AJXP_Exception(SystemTextEncoding::toUTF8(join("\n", $error))); } else { $logMessage = join("\n", $success); AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest)); } $reloadContextNode = true; $reloadDataNode = $dest; break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $logMessages = array(); $errorMessage = $this->delete($selection->getFiles(), $logMessages); if (count($logMessages)) { $logMessage = join("\n", $logMessages); } if ($errorMessage) { throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage)); } AJXP_Logger::logAction("Delete", array("files" => $selection)); $reloadContextNode = true; break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "rename": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]); $this->filterUserSelectionToHidden(array($filename_new)); $this->rename($file, $filename_new); $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); $reloadContextNode = true; $pendingSelection = $filename_new; AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; $dirname = AJXP_Utils::decodeSecureMagic($httpVars["dirname"], AJXP_SANITIZE_HTML_STRICT); $dirname = substr($dirname, 0, ConfService::getConf("MAX_CHAR")); $this->filterUserSelectionToHidden(array($dirname)); $error = $this->mkDir($dir, $dirname); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $pendingSelection = $dirname; $reloadContextNode = true; AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; $filename = AJXP_Utils::decodeSecureMagic($httpVars["filename"], AJXP_SANITIZE_HTML_STRICT); $filename = substr($filename, 0, ConfService::getConf("MAX_CHAR")); $this->filterUserSelectionToHidden(array($filename)); $error = $this->createEmptyFile($dir, $filename); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reloadContextNode = true; $pendingSelection = $dir . "/" . $filename; AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename)); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $messtmp = ""; $files = $selection->getFiles(); $changedFiles = array(); $chmod_value = $httpVars["chmod_value"]; $recursive = $httpVars["recursive"]; $recur_apply_to = $httpVars["recur_apply_to"]; foreach ($files as $fileName) { $error = $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles); } if (isset($error)) { throw new AJXP_Exception($error); } //$messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] "; $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders"; $reloadContextNode = true; AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($changedFiles))); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": AJXP_Logger::debug("Upload Files Data", $fileVars); $destination = $this->urlBase . AJXP_Utils::decodeSecureMagic($dir); AJXP_Logger::debug("Upload inside", array("destination" => $destination)); if (!$this->isWriteable($destination)) { $errorCode = 412; $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}."; AJXP_Logger::debug("Upload error 412", array("destination" => $destination)); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } foreach ($fileVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } $userfile_name = $boxData["name"]; try { $this->filterUserSelectionToHidden(array($userfile_name)); } catch (Exception $e) { return array("ERROR" => array("CODE" => 411, "MESSAGE" => "Forbidden")); } $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($userfile_name), AJXP_SANITIZE_HTML_STRICT); $userfile_name = substr($userfile_name, 0, ConfService::getConf("MAX_CHAR")); if (isset($httpVars["auto_rename"])) { $userfile_name = self::autoRenameForDest($destination, $userfile_name); } if (isset($boxData["input_upload"])) { try { AJXP_Logger::debug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen("{$destination}/" . $userfile_name, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); AJXP_Logger::debug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { if (!move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name)) { $errorCode = 411; $errorMessage = "{$mess['33']} " . $userfile_name; break; } } $this->changeMode($destination . "/" . $userfile_name); $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; AJXP_Logger::logAction("Upload File", array("file" => SystemTextEncoding::fromUTF8($dir) . "/" . $userfile_name)); } if (isset($errorMessage)) { AJXP_Logger::debug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { AJXP_Logger::debug("Return success"); return array("SUCCESS" => true); } return; break; //------------------------------------ // SHARING FILE OR FOLDER //------------------------------------ //------------------------------------ // SHARING FILE OR FOLDER //------------------------------------ case "public_url": $subAction = isset($httpVars["sub_action"]) ? $httpVars["sub_action"] : ""; if ($subAction == "delegate_repo") { header("Content-type:text/plain"); $result = $this->createSharedRepository($httpVars); print $result; } else { if ($subAction == "list_shared_users") { header("Content-type:text/html"); $loggedUser = AuthService::getLoggedUser(); $allUsers = AuthService::listUsers(); $crtValue = $httpVars["value"]; $users = ""; foreach ($allUsers as $userId => $userObject) { if ($crtValue != "" && (strstr($userId, $crtValue) === false || strstr($userId, $crtValue) != 0)) { continue; } if ($userObject->hasParent() && $userObject->getParent() == $loggedUser->getId()) { $users .= "<li>" . $userId . "</li>"; } } if (strlen($users)) { print "<ul>" . $users . "</ul>"; } } else { $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $url = $this->makePubliclet($file, $httpVars["password"], $httpVars["expiration"]); header("Content-type:text/plain"); echo $url; } } break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a"); $startTime = microtime(); $dir = AJXP_Utils::securePath(SystemTextEncoding::magicDequote($dir)); $path = $this->urlBase . ($dir != "" ? "/" . $dir : ""); $threshold = $this->repository->getOption("PAGINATION_THRESHOLD"); if (!isset($threshold) || intval($threshold) == 0) { $threshold = 500; } $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER"); if (!isset($limitPerPage) || intval($limitPerPage) == 0) { $limitPerPage = 200; } $countFiles = $this->countFiles($path, !$lsOptions["f"]); if ($countFiles > $threshold) { $offset = 0; $crtPage = 1; if (isset($page)) { $offset = (intval($page) - 1) * $limitPerPage; $crtPage = $page; } $totalPages = floor($countFiles / $limitPerPage) + 1; } else { $offset = $limitPerPage = 0; } $metaData = array(); $crtLabel = AJXP_Utils::xmlEntities(basename($dir), true); if (RecycleBinManager::recycleEnabled()) { if (RecycleBinManager::currentLocationIsRecycle($dir)) { $metaData["ajxp_mime"] = "ajxp_recycle"; $crtLabel = AJXP_Utils::xmlEntities($mess[122]); } else { if ($dir == "") { $metaData["repo_has_recycle"] = "true"; } } } if (AJXP_Utils::isBrowsableArchive($dir)) { $metaData["ajxp_mime"] = "ajxp_browsable_archive"; } AJXP_XMLWriter::renderHeaderNode(AJXP_Utils::xmlEntities($dir, true), $crtLabel, false, $metaData); if (isset($totalPages) && isset($crtPage)) { AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages); if (!$lsOptions["f"]) { AJXP_XMLWriter::close(); exit(1); } } $cursor = 0; $handle = opendir($path); if (!$handle) { throw new AJXP_Exception("Cannot open dir " . $path); } closedir($handle); $fullList = array("d" => array(), "z" => array(), "f" => array()); $nodes = scandir($path); //while(strlen($nodeName = readdir($handle)) > 0){ foreach ($nodes as $nodeName) { if ($nodeName == "." || $nodeName == "..") { continue; } $isLeaf = is_file($path . "/" . $nodeName) || AJXP_Utils::isBrowsableArchive($nodeName); if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) { continue; } if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) { continue; } $nodeType = "d"; if ($isLeaf) { if (AJXP_Utils::isBrowsableArchive($nodeName)) { if ($lsOptions["f"] && $lsOptions["z"]) { // See archives as files $nodeType = "f"; } else { $nodeType = "z"; } } else { $nodeType = "f"; } } if ($offset > 0 && $cursor < $offset) { $cursor++; continue; } if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) { break; } $metaData = array(); $currentFile = $path . "/" . $nodeName; $metaData["is_file"] = $isLeaf ? "1" : "0"; $metaData["filename"] = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($dir . "/" . $nodeName)); $metaData["icon"] = AJXP_Utils::mimetype($nodeName, "image", !$isLeaf); if ($metaData["icon"] == "folder.png") { $metaData["openicon"] = "folder_open.png"; } if (!is_file($currentFile) || AJXP_Utils::isBrowsableArchive($nodeName)) { $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?get_action=ls&options=dz&dir=" . $dir . "/" . $nodeName); $link = urlencode($link); $metaData["src"] = $link; } if ($lsOptions["l"]) { $metaData["file_group"] = @filegroup($currentFile) || "unknown"; $metaData["file_owner"] = @fileowner($currentFile) || "unknown"; $fPerms = @fileperms($currentFile); if ($fPerms !== false) { $fPerms = substr(decoct($fPerms), $isLeaf ? 2 : 1); } else { $fPerms = '0000'; } $metaData["file_perms"] = $fPerms; $metaData["mimestring"] = AJXP_Utils::mimetype($currentFile, "type", !$isLeaf); $datemodif = $this->date_modif($currentFile); $metaData["ajxp_modiftime"] = $datemodif ? $datemodif : "0"; $metaData["bytesize"] = 0; if ($isLeaf) { $metaData["bytesize"] = filesize($currentFile); if ($metaData["bytesize"] < 0) { $metaData["bytesize"] = sprintf("%u", $metaData["bytesize"]); } } $metaData["filesize"] = AJXP_Utils::roundSize($metaData["bytesize"]); if (AJXP_Utils::isBrowsableArchive($nodeName)) { $metaData["ajxp_mime"] = "ajxp_browsable_archive"; } $realFile = null; // A reference to the real file. AJXP_Controller::applyHook("ls.metadata", array($currentFile, &$metaData, $this->wrapperClassName, &$realFile)); } $attributes = ""; foreach ($metaData as $key => $value) { $attributes .= "{$key}=\"{$value}\" "; } $renderNodeData = array(AJXP_Utils::xmlEntities($dir . "/" . $nodeName, true), AJXP_Utils::xmlEntities($nodeName, true), $isLeaf, $metaData); $fullList[$nodeType][$nodeName] = $renderNodeData; $cursor++; } /* closedir($handle); foreach ($fullList as $key => $list){ uksort($list, 'strnatcasecmp'); $fullList[$key] = $list; } */ $allNodes = array_merge($fullList["d"], $fullList["z"], $fullList["f"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["d"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["z"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["f"]); // ADD RECYCLE BIN TO THE LIST if ($dir == "" && RecycleBinManager::recycleEnabled()) { $recycleBinOption = RecycleBinManager::getRelativeRecycle(); if (file_exists($this->urlBase . $recycleBinOption)) { $recycleIcon = $this->countFiles($this->urlBase . $recycleBinOption, false, true) > 0 ? "trashcan_full.png" : "trashcan.png"; $recycleMetaData = array("ajxp_modiftime" => $this->date_modif($this->urlBase . $recycleBinOption), "mimestring" => AJXP_Utils::xmlEntities($mess[122]), "icon" => "{$recycleIcon}", "filesize" => "-", "ajxp_mime" => "ajxp_recycle"); $nullFile = null; AJXP_Controller::applyHook("ls.metadata", array($this->urlBase . $recycleBinOption, &$recycleMetaData, $this->wrapperClassName, &$nullFile)); AJXP_XMLWriter::renderNode($recycleBinOption, AJXP_Utils::xmlEntities($mess[122]), false, $recycleMetaData); } } AJXP_Logger::debug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms"); AJXP_XMLWriter::close(); return; break; } $xmlBuffer = ""; if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if ($reloadContextNode) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false); } return $xmlBuffer; }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->accessDriver)) { throw new Exception("Cannot find access driver!"); } if ($this->accessDriver->getId() == "access.demo") { $errorMessage = "This is a demo, all 'write' actions are disabled!"; if ($httpVars["sub_action"] == "delegate_repo") { return AJXP_XMLWriter::sendMessage(null, $errorMessage, false); } else { print $errorMessage; } return; } switch ($action) { //------------------------------------ // SHARING FILE OR FOLDER //------------------------------------ case "share": $subAction = isset($httpVars["sub_action"]) ? $httpVars["sub_action"] : ""; if ($subAction == "delegate_repo") { header("Content-type:text/plain"); $result = $this->createSharedRepository($httpVars, $this->repository, $this->accessDriver); print $result; } else { if ($subAction == "list_shared_users") { header("Content-type:text/html"); if (!ConfService::getAuthDriverImpl()->usersEditable()) { break; } $loggedUser = AuthService::getLoggedUser(); $crtValue = $httpVars["value"]; if (!empty($crtValue)) { $regexp = '^' . preg_quote($crtValue); } else { $regexp = null; } $limit = min($this->pluginConf["SHARED_USERS_LIST_LIMIT"], 20); $allUsers = AuthService::listUsers($regexp, 0, $limit, false); $users = ""; $index = 0; foreach ($allUsers as $userId => $userObject) { if (!$userObject->hasParent() && ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING") || $userObject->getParent() == $loggedUser->getId()) { if ($regexp != null && !preg_match("/{$regexp}/i", $userId)) { continue; } $users .= "<li>" . $userId . "</li>"; $index++; } if ($index == $limit) { break; } } if (strlen($users)) { print "<ul>" . $users . "</ul>"; } } else { $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!isset($httpVars["downloadlimit"])) { $httpVars["downloadlimit"] = 0; } $data = $this->accessDriver->makePublicletOptions($file, $httpVars["password"], $httpVars["expiration"], $httpVars["downloadlimit"], $this->repository); $customData = array(); foreach ($httpVars as $key => $value) { if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") { $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value; } } if (count($customData)) { $data["PLUGINS_DATA"] = $customData; } $url = $this->writePubliclet($data, $this->accessDriver, $this->repository); if ($this->metaStore != null) { $ar = explode(".", basename($url)); $this->metaStore->setMetadata(new AJXP_Node($this->urlBase . $file), "ajxp_shared", array("element" => array_shift($ar)), true, AJXP_METADATA_SCOPE_REPOSITORY); } header("Content-type:text/plain"); echo $url; } } break; case "load_shared_element_data": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $elementType = $httpVars["element_type"]; $messages = ConfService::getMessages(); if ($this->metaStore != null) { $metadata = $this->metaStore->retrieveMetadata(new AJXP_Node($this->urlBase . $file), "ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY); } if (count($metadata)) { header("Content-type:application/json"); if ($elementType == "file") { $pData = self::loadPublicletData($metadata["element"]); if ($pData["OWNER_ID"] != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to access this data"); } if (isset($metadata["short_form_url"])) { $link = $metadata["short_form_url"]; } else { $link = $this->buildPublicletLink($metadata["element"]); } $jsonData = array("publiclet_link" => $link, "download_counter" => PublicletCounter::getCount($metadata["element"]), "download_limit" => $pData["DOWNLOAD_LIMIT"], "expire_time" => $pData["EXPIRE_TIME"] != 0 ? date($messages["date_format"], $pData["EXPIRE_TIME"]) : 0, "has_password" => !empty($pData["PASSWORD"])); } else { if ($elementType == "repository") { $repoId = $metadata["element"]; $repo = ConfService::getRepositoryById($repoId); if ($repo->getOwner() != AuthService::getLoggedUser()->getId()) { throw new Exception("You are not allowed to access this data"); } $sharedUsers = array(); $sharedRights = ""; $loggedUser = AuthService::getLoggedUser(); $users = AuthService::listUsers(); foreach ($users as $userId => $userObject) { if ($userObject->getId() == $loggedUser->getId()) { continue; } if ($userObject->canWrite($repoId) && $userObject->canRead($repoId)) { $sharedUsers[] = $userId; $sharedRights = "rw"; } else { if ($userObject->canRead($repoId)) { $sharedUsers[] = $userId; $sharedRights = "r"; } else { if ($userObject->canWrite($repoId)) { $sharedUsers[] = $userId; $sharedRights = "w"; } } } } $jsonData = array("repositoryId" => $repoId, "label" => $repo->getDisplay(), "rights" => $sharedRights, "users" => $sharedUsers); } } echo json_encode($jsonData); } break; case "unshare": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $ajxpNode = new AJXP_Node($this->urlBase . $file); $metadata = $this->metaStore->retrieveMetadata($ajxpNode, "ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY); if (count($metadata)) { self::deleteSharedElement($httpVars["element_type"], $metadata["element"], AuthService::getLoggedUser()); $this->metaStore->removeMetadata($ajxpNode, "ajxp_shared", true); } break; case "reset_counter": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $metadata = $this->metaStore->retrieveMetadata(new AJXP_Node($this->urlBase . $file), "ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY); if (isset($metadata["element"])) { PublicletCounter::reset($metadata["element"]); } break; default: break; } }
function listUsers() { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.7" attributeName="isAdmin" sortType="String"/></columns>'); if (!ENABLE_USERS) { return; } $users = AuthService::listUsers(); $mess = ConfService::getMessages(); $loggedUser = AuthService::getLoggedUser(); $userArray = array(); foreach ($users as $userObject) { $userArray[AJXP_Utils::xmlEntities($userObject->getId())] = $userObject; } ksort($userArray); foreach ($userArray as $userObject) { $isAdmin = $userObject->isAdmin(); $userId = AJXP_Utils::xmlEntities($userObject->getId()); $icon = "user" . ($userId == "guest" ? "_guest" : ($isAdmin ? "_admin" : "")); print '<tree text="' . $userId . '" isAdmin="' . $mess[$isAdmin ? "ajxp_conf.14" : "ajxp_conf.15"] . '" icon="' . $icon . '.png" openicon="' . $icon . '.png" filename="/users/' . $userId . '" parentname="/users" is_file="1" ajxp_mime="user' . ($userId != "guest" && $userId != $loggedUser->getId() ? "_editable" : "") . '" />'; } }
function runTask($taskId, $status = null, &$currentlyRunning = -1, $forceStart = false) { $data = $this->getTaskById($taskId); $mess = ConfService::getMessages(); $timeArray = $this->getTimeArray($data["schedule"]); // TODO : Set MasterInterval as config, or detect last execution? $masterInterval = 1; $maximumProcesses = 2; $now = time(); $lastExec = time() - 60 * $masterInterval; $res = $this->getNextExecutionTimeForScript($lastExec, $timeArray); $test = date("Y-m-d H:i", $lastExec) . " -- " . date("Y-m-d H:i", $res) . " -- " . date("Y-m-d H:i", $now); $alreadyRunning = false; $queued = false; if ($status == null) { $status = $this->getTaskStatus($taskId); } if ($status !== false) { if ($status[0] == "RUNNING") { $alreadyRunning = true; } else { if (in_array("QUEUED", $status)) { $queued = true; // Run now ! } } } if ($res >= $lastExec && $res < $now && !$alreadyRunning && $currentlyRunning >= $maximumProcesses) { $this->setTaskStatus($taskId, "QUEUED", true); $alreadyRunning = true; $queued = false; } if ($res >= $lastExec && $res < $now && !$alreadyRunning || $queued || $forceStart) { if ($data["user_id"] == "*") { $data["user_id"] = implode(",", array_keys(AuthService::listUsers())); } if ($data["repository_id"] == "*") { $data["repository_id"] = implode(",", array_keys(ConfService::getRepositoriesList())); } $process = AJXP_Controller::applyActionInBackground($data["repository_id"], $data["action_name"], $data["PARAMS"], $data["user_id"], AJXP_CACHE_DIR . "/cmd_outputs/task_" . $taskId . ".status"); if ($process != null && is_a($process, "UnixProcess")) { $this->setTaskStatus($taskId, "RUNNING:" . $process->getPid()); } else { $this->setTaskStatus($taskId, "RUNNING"); } $currentlyRunning++; return true; } return false; }