/** * Filter the very basic keywords from the XML : AJXP_USER, AJXP_INSTALL_PATH, AJXP_DATA_PATH * Calls the vars.filter hooks. * @static * @param $value * @return mixed|string */ public static function filter($value) { if (is_string($value) && strpos($value, "AJXP_USER") !== false) { if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { $loggedUser = $loggedUser->getId(); $value = str_replace("AJXP_USER", $loggedUser, $value); } else { return ""; } } else { $value = str_replace("AJXP_USER", "shared", $value); } } if (is_string($value) && strpos($value, "AJXP_INSTALL_PATH") !== false) { $value = str_replace("AJXP_INSTALL_PATH", AJXP_INSTALL_PATH, $value); } if (is_string($value) && strpos($value, "AJXP_DATA_PATH") !== false) { $value = str_replace("AJXP_DATA_PATH", AJXP_DATA_PATH, $value); } $tab = array(&$value); AJXP_Controller::applyIncludeHook("vars.filter", $tab); return $value; }
public function parseSpecificContributions(&$contribNode) { parent::parseSpecificContributions($contribNode); if ($contribNode->nodeName != "actions") { return; } $actionXpath = new DOMXPath($contribNode->ownerDocument); $paramList = $actionXpath->query('action[@name="scheduler_addTask"]/processing/standardFormDefinition/param[@name="repository_id"]', $contribNode); if (!$paramList->length) { return; } $paramNode = $paramList->item(0); $sVals = array(); $repos = ConfService::getRepositoriesList("all"); foreach ($repos as $repoId => $repoObject) { $sVals[] = $repoId . "|" . AJXP_Utils::xmlEntities($repoObject->getDisplay()); } $sVals[] = "*|All Repositories"; $paramNode->attributes->getNamedItem("choices")->nodeValue = implode(",", $sVals); if (!AuthService::usersEnabled() || AuthService::getLoggedUser() == null) { return; } $paramList = $actionXpath->query('action[@name="scheduler_addTask"]/processing/standardFormDefinition/param[@name="user_id"]', $contribNode); if (!$paramList->length) { return; } $paramNode = $paramList->item(0); $paramNode->attributes->getNamedItem("default")->nodeValue = AuthService::getLoggedUser()->getId(); }
public function doTest() { $this->testedParams["Users enabled"] = AuthService::usersEnabled(); $this->testedParams["Guest enabled"] = ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth"); $this->failedLevel = "info"; return FALSE; }
/** * Filter the very basic keywords from the XML : AJXP_USER, AJXP_INSTALL_PATH, AJXP_DATA_PATH * Calls the vars.filter hooks. * @static * @param $value * @param AbstractAjxpUser|String $resolveUser * @return mixed|string */ public static function filter($value, $resolveUser = null) { if (is_string($value) && strpos($value, "AJXP_USER") !== false) { if (AuthService::usersEnabled()) { if ($resolveUser != null) { if (is_string($resolveUser)) { $resolveUserId = $resolveUser; } else { $resolveUserId = $resolveUser->getId(); } $value = str_replace("AJXP_USER", $resolveUserId, $value); } else { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null) { if ($loggedUser->hasParent() && $loggedUser->getResolveAsParent()) { $loggedUserId = $loggedUser->getParent(); } else { $loggedUserId = $loggedUser->getId(); } $value = str_replace("AJXP_USER", $loggedUserId, $value); } else { return ""; } } } else { $value = str_replace("AJXP_USER", "shared", $value); } } if (is_string($value) && strpos($value, "AJXP_GROUP_PATH") !== false) { if (AuthService::usersEnabled()) { if ($resolveUser != null) { if (is_string($resolveUser) && AuthService::userExists($resolveUser)) { $loggedUser = ConfService::getConfStorageImpl()->createUserObject($resolveUser); } else { $loggedUser = $resolveUser; } } else { $loggedUser = AuthService::getLoggedUser(); } if ($loggedUser != null) { $gPath = $loggedUser->getGroupPath(); $value = str_replace("AJXP_GROUP_PATH_FLAT", str_replace("/", "_", trim($gPath, "/")), $value); $value = str_replace("AJXP_GROUP_PATH", $gPath, $value); } else { return ""; } } else { $value = str_replace(array("AJXP_GROUP_PATH", "AJXP_GROUP_PATH_FLAT"), "shared", $value); } } if (is_string($value) && strpos($value, "AJXP_INSTALL_PATH") !== false) { $value = str_replace("AJXP_INSTALL_PATH", AJXP_INSTALL_PATH, $value); } if (is_string($value) && strpos($value, "AJXP_DATA_PATH") !== false) { $value = str_replace("AJXP_DATA_PATH", AJXP_DATA_PATH, $value); } $tab = array(&$value); AJXP_Controller::applyIncludeHook("vars.filter", $tab); return $value; }
/** * @param string $action * @param array $httpVars * @param array $fileVars */ public function applyChangeLock($actionName, $httpVars, $fileVars) { if (!isset($this->actions[$actionName])) { return; } if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection(); $selection->initFromHttpVars(); $currentFile = $selection->getUniqueFile(); $wrapperData = $this->accessDriver->detectStreamWrapper(false); $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId(); $unlock = isset($httpVars["unlock"]) ? true : false; $ajxpNode = new AJXP_Node($urlBase . $currentFile); if ($unlock) { $this->metaStore->removeMetadata($ajxpNode, self::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL); } else { $this->metaStore->setMetadata($ajxpNode, SimpleLockManager::METADATA_LOCK_NAMESPACE, array("lock_user" => AuthService::getLoggedUser()->getId()), false, AJXP_METADATA_SCOPE_GLOBAL); } AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); }
protected function getUserId() { if (AuthService::usersEnabled()) { return AuthService::getLoggedUser()->getId(); } return "shared"; }
function repositoryDataAsJS() { if (AuthService::usersEnabled()) { return ""; } require_once INSTALL_PATH . "/server/classes/class.SystemTextEncoding.php"; require_once INSTALL_PATH . "/server/classes/class.AJXP_XMLWriter.php"; return str_replace("'", "\\'", AJXP_XMLWriter::writeRepositoriesData(null)); }
/** * Write repository data directly as javascript string * @static * @return mixed|string */ public static function repositoryDataAsJS() { if (AuthService::usersEnabled()) { return ""; } require_once AJXP_BIN_FOLDER . "/class.SystemTextEncoding.php"; require_once AJXP_BIN_FOLDER . "/class.AJXP_XMLWriter.php"; return str_replace("'", "\\'", AJXP_XMLWriter::writeRepositoriesData(null)); }
protected function getUserId($private) { if (!$private) { return AJXP_METADATA_SHAREDUSER; } if (AuthService::usersEnabled()) { return AuthService::getLoggedUser()->getId(); } return "shared"; }
public function getRegistryContributions() { $logged = AuthService::getLoggedUser(); if (AuthService::usersEnabled()) { if ($logged == null) { return $this->registryContributions; } else { $xmlString = AJXP_XMLWriter::getUserXml($logged, false); } } else { $xmlString = AJXP_XMLWriter::getUserXml(null, false); } $dom = new DOMDocument(); $dom->loadXML($xmlString); $this->registryContributions[] = $dom->documentElement; return $this->registryContributions; }
/** * formats the error message in representable manner * * For the SQL driver we will normalise the information into our table row format. * * @param $message String this is the message to be formatted * @param $severity Severity level of the message: one of LOG_LEVEL_* (DEBUG,INFO,NOTICE,WARNING,ERROR) * @return String the formatted message. */ function formatMessage($message, $severity) { // Get the user if it exists $user = "******"; if (AuthService::usersEnabled()) { $logged = AuthService::getLoggedUser(); if ($logged != null) { $user = $logged->getId(); } else { $user = "******"; } } $message_parts = explode("\t", $message); $severity = strtoupper((string) $severity); $log_row = array('logdate' => $this->toMysqlDateTime(strtotime('NOW')), 'remote_ip' => $this->inet_ptod($_SERVER['REMOTE_ADDR']), 'severity' => $severity, 'user' => $user, 'message' => $message_parts[0], 'params' => $message_parts[1]); return $log_row; }
public function receiveAction($action, $httpVars, $filesVars) { $provider = $this->getFilteredOption("AVATAR_PROVIDER"); $type = $this->getFilteredOption("GRAVATAR_TYPE"); if ($action == "get_avatar_url") { $url = ""; $suffix = ""; switch ($provider) { case "gravatar": default: if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { $url = "https://secure.gravatar.com"; } else { $url = "http://www.gravatar.com"; } $url .= "/avatar/"; $suffix .= "?s=80&r=g&d=" . $type; break; case "libravatar": $url = ""; // Federated Servers are not supported here without libravatar.org. Should query DNS server first. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { $url = "https://seccdn.libravatar.org"; } else { $url = "http://cdn.libravatar.org"; } $url .= "/avatar/"; $suffix = "?s=80&d=" . $type; break; } if (isset($httpVars["userid"])) { $userid = $httpVars["userid"]; if (AuthService::usersEnabled() && AuthService::userExists($userid)) { $confDriver = ConfService::getConfStorageImpl(); $user = $confDriver->createUserObject($userid); $userEmail = $user->personalRole->filterParameterValue("core.conf", "email", AJXP_REPO_SCOPE_ALL, ""); if (!empty($userEmail)) { $url .= md5(strtolower(trim($userEmail))); } } } $url .= $suffix; print $url; } }
/** * @param string $action * @param array $httpVars * @param array $fileVars */ public function applyChangeLock($actionName, $httpVars, $fileVars) { if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection($repo, $httpVars); $unlock = isset($httpVars["unlock"]) ? true : false; if ($unlock) { $this->metaStore->removeMetadata($selection->getUniqueNode(), self::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL); } else { $this->metaStore->setMetadata($selection->getUniqueNode(), SimpleLockManager::METADATA_LOCK_NAMESPACE, array("lock_user" => AuthService::getLoggedUser()->getId()), false, AJXP_METADATA_SCOPE_GLOBAL); } AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); }
/** * @param $channelName * @param $clientId * @throws Exception * @return mixed */ public function suscribeToChannel($channelName, $clientId) { $this->loadChannel($channelName, true); if (AuthService::usersEnabled()) { $user = AuthService::getLoggedUser(); if ($user == null) { throw new Exception("You must be logged in"); } $GROUP_PATH = $user->getGroupPath(); $USER_ID = $user->getId(); } else { $GROUP_PATH = '/'; $USER_ID = 'shared'; } if ($GROUP_PATH == null) { $GROUP_PATH = false; } $this->channels[$channelName]["CLIENTS"][$clientId] = array("ALIVE" => time(), "USER_ID" => $USER_ID, "GROUP_PATH" => $GROUP_PATH); foreach ($this->channels[$channelName]["MESSAGES"] as &$object) { $object->messageRC[$clientId] = $clientId; } }
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; }
/** Cypher the publiclet object data and write to disk. * @param array $data The publiclet data array to write * The data array must have the following keys: * - DRIVER The driver used to get the file's content * - OPTIONS The driver options to be successfully constructed (usually, the user and password) * - FILE_PATH The path to the file's content * - PASSWORD If set, the written publiclet will ask for this password before sending the content * - ACTION If set, action to perform * - USER If set, the AJXP user * - EXPIRE_TIME If set, the publiclet will deny downloading after this time, and probably self destruct. * - AUTHOR_WATCH If set, will post notifications for the publiclet author each time the file is loaded * @param AbstractAccessDriver $accessDriver * @param Repository $repository * @param ShareStore $shareStore * @param PublicAccessManager $publicAccessManager * @return string|array An array containing the hash (0) and the generated url (1) */ public function writePubliclet(&$data, $accessDriver, $repository, $shareStore, $publicAccessManager) { $downloadFolder = $publicAccessManager->getPublicDownloadFolder(); $publicAccessManager->initFolder(); if (!is_dir($downloadFolder)) { return "ERROR : Public URL folder does not exist!"; } if (!function_exists("mcrypt_create_iv")) { return "ERROR : MCrypt must be installed to use publiclets!"; } $data["PLUGIN_ID"] = $accessDriver->getId(); $data["BASE_DIR"] = $accessDriver->getBaseDir(); //$data["REPOSITORY"] = $repository; if (AuthService::usersEnabled()) { $data["OWNER_ID"] = AuthService::getLoggedUser()->getId(); } $shareStore->storeSafeCredentialsIfNeeded($data, $accessDriver, $repository); // Force expanded path in publiclet $copy = clone $repository; $copy->addOption("PATH", $repository->getOption("PATH")); $data["REPOSITORY"] = $copy; if ($data["ACTION"] == "") { $data["ACTION"] = "download"; } try { $hash = $shareStore->storeShare($repository->getId(), $data, "publiclet"); } catch (Exception $e) { return $e->getMessage(); } $shareStore->resetDownloadCounter($hash, AuthService::getLoggedUser()->getId()); $url = $publicAccessManager->buildPublicLink($hash); AJXP_Logger::log2(LOG_LEVEL_INFO, __CLASS__, "New Share", array("file" => "'" . $copy->display . ":/" . $data['FILE_PATH'] . "'", "files" => "'" . $copy->display . ":/" . $data['FILE_PATH'] . "'", "url" => $url, "expiration" => $data['EXPIRE_TIME'], "limit" => $data['DOWNLOAD_LIMIT'], "repo_uuid" => $copy->uuid)); AJXP_Controller::applyHook("node.share.create", array('type' => 'file', 'repository' => &$copy, 'accessDriver' => &$accessDriver, 'data' => &$data, 'url' => $url)); return array($hash, $url); }
function crossRepositoryCopy($httpVars) { ConfService::detectRepositoryStreams(true); $mess = ConfService::getMessages(); $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $files = $selection->getFiles(); $accessType = $this->repository->getAccessType(); $repositoryId = $this->repository->getId(); $origStreamURL = "ajxp.{$accessType}://{$repositoryId}"; $destRepoId = $httpVars["dest_repository_id"]; $destRepoObject = ConfService::getRepositoryById($destRepoId); $destRepoAccess = $destRepoObject->getAccessType(); $destStreamURL = "ajxp.{$destRepoAccess}://{$destRepoId}"; // Check rights if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId)) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, "You do not have the right to access one of the repositories!"); AJXP_XMLWriter::close(); exit(1); } } $messages = array(); foreach ($files as $file) { $origFile = $origStreamURL . $file; $destFile = $destStreamURL . $httpVars["dest"] . "/" . basename($file); $origHandler = fopen($origFile, "r"); $destHandler = fopen($destFile, "w"); if ($origHandler === false || $destHandler === false) { $errorMessages[] = AJXP_XMLWriter::sendMessage(null, $mess[114] . " ({$origFile} to {$destFile})", false); continue; } while (!feof($origHandler)) { fwrite($destHandler, fread($origHandler, 4096)); } fflush($destHandler); fclose($origHandler); fclose($destHandler); $messages[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($origFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destFile); } AJXP_XMLWriter::header(); if (count($errorMessages)) { AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true); } AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true); AJXP_XMLWriter::close(); exit(0); }
public function editMeta($actionName, $httpVars, $fileVars) { if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection($repo, $httpVars); $nodes = $selection->buildNodes(); $nodesDiffs = array(); $def = $this->getMetaDefinition(); foreach ($nodes as $ajxpNode) { $newValues = array(); //$ajxpNode->setDriver($this->accessDriver); AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode)); foreach ($def as $key => $data) { if (isset($httpVars[$key])) { $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]); if ($data["type"] == "tags") { $this->updateTags(AJXP_Utils::decodeSecureMagic($httpVars[$key])); } } else { if (!isset($original)) { $original = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL); } if (isset($original) && isset($original[$key])) { $newValues[$key] = $original[$key]; } } } $ajxpNode->setMetadata("users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL); AJXP_Controller::applyHook("node.meta_change", array($ajxpNode)); $nodesDiffs[$ajxpNode->getPath()] = $ajxpNode; } AJXP_XMLWriter::header(); AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => $nodesDiffs), true); AJXP_XMLWriter::close(); }
/** * @param string $repoId * @param Repository $repoObject * @param array $exposed * @param array $streams * @param AbstractAjxpUser $loggedUser * @param string $accessStatus * @return string * @throws Exception */ public static function repositoryToXML($repoId, $repoObject, $exposed, $streams, $loggedUser, $accessStatus = "") { $statusString = " repository_type=\"" . $repoObject->getRepositoryType() . "\""; if (empty($accessStatus)) { $accessStatus = $repoObject->getAccessStatus(); } if (!empty($accessStatus)) { $statusString .= " access_status=\"{$accessStatus}\" "; } else { if ($loggedUser != null) { $lastConnected = $loggedUser->getArrayPref("repository_last_connected", $repoId); if (!empty($lastConnected)) { $statusString .= " last_connection=\"{$lastConnected}\" "; } } } $streamString = ""; if (in_array($repoObject->accessType, $streams)) { $streamString = "allowCrossRepositoryCopy=\"true\""; } if ($repoObject->getUniqueUser()) { $streamString .= " user_editable_repository=\"true\" "; } if ($repoObject->hasContentFilter()) { $streamString .= " hasContentFilter=\"true\""; } $slugString = ""; $slug = $repoObject->getSlug(); if (!empty($slug)) { $slugString = "repositorySlug=\"{$slug}\""; } $isSharedString = ""; $currentUserIsOwner = false; $ownerLabel = null; if ($repoObject->hasOwner()) { $uId = $repoObject->getOwner(); if (AuthService::usersEnabled() && AuthService::getLoggedUser()->getId() == $uId) { $currentUserIsOwner = true; } $label = ConfService::getUserPersonalParameter("USER_DISPLAY_NAME", $uId, "core.conf", $uId); $ownerLabel = $label; $isSharedString = 'owner="' . AJXP_Utils::xmlEntities($label) . '"'; } if ($repoObject->securityScope() == "USER" || $currentUserIsOwner) { $streamString .= " userScope=\"true\""; } $descTag = ""; $public = false; if (!empty($_SESSION["CURRENT_MINISITE"])) { $public = true; } $description = $repoObject->getDescription($public, $ownerLabel); if (!empty($description)) { $descTag = '<description>' . AJXP_Utils::xmlEntities($description, true) . '</description>'; } $roleString = ""; if ($loggedUser != null) { $merged = $loggedUser->mergedRole; $params = array(); foreach ($exposed as $exposed_prop) { $metaOptions = $repoObject->getOption("META_SOURCES"); if (!isset($metaOptions[$exposed_prop["PLUGIN_ID"]])) { continue; } $value = $exposed_prop["DEFAULT"]; if (isset($metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]])) { $value = $metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]]; } $value = $merged->filterParameterValue($exposed_prop["PLUGIN_ID"], $exposed_prop["NAME"], $repoId, $value); if ($value !== null) { if ($value === true || $value === false) { $value = $value === true ? "true" : "false"; } $params[] = '<repository_plugin_param plugin_id="' . $exposed_prop["PLUGIN_ID"] . '" name="' . $exposed_prop["NAME"] . '" value="' . AJXP_Utils::xmlEntities($value) . '"/>'; $roleString .= str_replace(".", "_", $exposed_prop["PLUGIN_ID"]) . "_" . $exposed_prop["NAME"] . '="' . AJXP_Utils::xmlEntities($value) . '" '; } } $roleString .= 'acl="' . $merged->getAcl($repoId) . '"'; if ($merged->hasMask($repoId)) { $roleString .= ' hasMask="true" '; } } return "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$statusString} {$streamString} {$slugString} {$isSharedString} {$roleString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label>" . $descTag . $repoObject->getClientSettings() . "</repo>"; }
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; }
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(); $wrapperClassName = $streamData["classname"]; if (empty($httpVars["file"])) { return; } $file = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]); $mess = ConfService::getMessages(); $node = new AJXP_Node($file); AJXP_Controller::applyHook("node.read", array($node)); switch ($action) { case "eml_get_xml_structure": $params = array('include_bodies' => false, 'decode_bodies' => false, 'decode_headers' => 'UTF-8'); $decoder = $this->getStructureDecoder($file, $wrapperClassName == "imapAccessWrapper"); $xml = $decoder->getXML($decoder->decode($params)); if (function_exists("imap_mime_header_decode")) { $doc = new DOMDocument(); $doc->loadXML($xml); $xPath = new DOMXPath($doc); $headers = $xPath->query("//headername"); $changes = false; foreach ($headers as $headerNode) { if ($headerNode->firstChild->nodeValue == "Subject") { $headerValueNode = $headerNode->nextSibling->nextSibling; $value = $headerValueNode->nodeValue; $elements = imap_mime_header_decode($value); $decoded = ""; foreach ($elements as $element) { $decoded .= $element->text; $charset = $element->charset; } if ($decoded != $value) { $value = SystemTextEncoding::changeCharset($charset, "UTF-8", $decoded); $node = $doc->createElement("headervalue", $value); $res = $headerNode->parentNode->replaceChild($node, $headerValueNode); $changes = true; } } } if ($changes) { $xml = $doc->saveXML(); } } print $xml; break; case "eml_get_bodies": require_once "Mail/mimeDecode.php"; $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false); if ($wrapperClassName == "imapAccessWrapper") { $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId")); $content = $cache->getData(); } else { $content = file_get_contents($file); } $decoder = new Mail_mimeDecode($content); $structure = $decoder->decode($params); $html = $this->_findPartByCType($structure, "text", "html"); $text = $this->_findPartByCType($structure, "text", "plain"); if ($html != false && isset($html->ctype_parameters) && isset($html->ctype_parameters["charset"])) { $charset = $html->ctype_parameters["charset"]; } if (isset($charset)) { header('Content-Type: text/xml; charset=' . $charset); header('Cache-Control: no-cache'); print '<?xml version="1.0" encoding="' . $charset . '"?>'; print '<email_body>'; } else { AJXP_XMLWriter::header("email_body"); } if ($html !== false) { print '<mimepart type="html"><![CDATA['; $text = $html->body; print $text; print "]]></mimepart>"; } if ($text !== false) { print '<mimepart type="plain"><![CDATA['; print $text->body; print "]]></mimepart>"; } AJXP_XMLWriter::close("email_body"); break; case "eml_dl_attachment": $attachId = $httpVars["attachment_id"]; if (!isset($attachId)) { break; } require_once "Mail/mimeDecode.php"; $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false); if ($wrapperClassName == "imapAccessWrapper") { $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId")); $content = $cache->getData(); } else { $content = file_get_contents($file); } $decoder = new Mail_mimeDecode($content); $structure = $decoder->decode($params); $part = $this->_findAttachmentById($structure, $attachId); if ($part !== false) { $fake = new fsAccessDriver("fake", ""); $fake->readFile($part->body, "file", $part->d_parameters['filename'], true); exit; } else { //var_dump($structure); } break; case "eml_cp_attachment": $attachId = $httpVars["attachment_id"]; $destRep = AJXP_Utils::decodeSecureMagic($httpVars["destination"]); if (!isset($attachId)) { AJXP_XMLWriter::sendMessage(null, "Wrong Parameters"); break; } require_once "Mail/mimeDecode.php"; $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false); if ($wrapperClassName == "imapAccessWrapper") { $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId")); $content = $cache->getData(); } else { $content = file_get_contents($file); } $decoder = new Mail_mimeDecode($content); $structure = $decoder->decode($params); $part = $this->_findAttachmentById($structure, $attachId); AJXP_XMLWriter::header(); if ($part !== false) { if (isset($httpVars["dest_repository_id"])) { $destRepoId = $httpVars["dest_repository_id"]; if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canWrite($destRepoId)) { throw new Exception($mess[364]); } } $destRepoObject = ConfService::getRepositoryById($destRepoId); $destRepoAccess = $destRepoObject->getAccessType(); $plugin = AJXP_PluginsService::findPlugin("access", $destRepoAccess); $destWrapperData = $plugin->detectStreamWrapper(true); $destStreamURL = $destWrapperData["protocol"] . "://{$destRepoId}"; } $destFile = $destStreamURL . $destRep . "/" . $part->d_parameters['filename']; $fp = fopen($destFile, "w"); if ($fp !== false) { fwrite($fp, $part->body, strlen($part->body)); fclose($fp); AJXP_XMLWriter::sendMessage(sprintf($mess["editor.eml.7"], $part->d_parameters["filename"], $destRep), NULL); } else { AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.8"]); } } else { AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.9"]); } AJXP_XMLWriter::close(); break; default: break; } }
/** * Extract all the user data and put it in XML * @static * @param null $userObject * @internal param bool $details * @return string */ public static function getUserXML($userObject = null) { $buffer = ""; $loggedUser = AuthService::getLoggedUser(); $confDriver = ConfService::getConfStorageImpl(); if ($userObject != null) { $loggedUser = $userObject; } if (!AuthService::usersEnabled()) { $buffer .= "<user id=\"shared\">"; $buffer .= "<active_repo id=\"" . ConfService::getCurrentRepositoryId() . "\" write=\"1\" read=\"1\"/>"; $buffer .= AJXP_XMLWriter::writeRepositoriesData(null); $buffer .= "</user>"; } else { if ($loggedUser != null) { $lock = $loggedUser->getLock(); $buffer .= "<user id=\"" . $loggedUser->id . "\">"; $buffer .= "<active_repo id=\"" . ConfService::getCurrentRepositoryId() . "\" write=\"" . ($loggedUser->canWrite(ConfService::getCurrentRepositoryId()) ? "1" : "0") . "\" read=\"" . ($loggedUser->canRead(ConfService::getCurrentRepositoryId()) ? "1" : "0") . "\"/>"; $buffer .= AJXP_XMLWriter::writeRepositoriesData($loggedUser); $buffer .= "<preferences>"; $preferences = $confDriver->getExposedPreferences($loggedUser); foreach ($preferences as $prefName => $prefData) { $atts = ""; if (isset($prefData["exposed"]) && $prefData["exposed"] == true) { foreach ($prefData as $k => $v) { if ($k == "name") { continue; } if ($k == "value") { $k = "default"; } $atts .= "{$k}='{$v}' "; } } if (isset($prefData["pluginId"])) { $atts .= "pluginId='" . $prefData["pluginId"] . "' "; } if ($prefData["type"] == "string") { $buffer .= "<pref name=\"{$prefName}\" value=\"" . $prefData["value"] . "\" {$atts}/>"; } else { if ($prefData["type"] == "json") { $buffer .= "<pref name=\"{$prefName}\" {$atts}><![CDATA[" . $prefData["value"] . "]]></pref>"; } } } $buffer .= "</preferences>"; $buffer .= "<special_rights is_admin=\"" . ($loggedUser->isAdmin() ? "1" : "0") . "\" " . ($lock !== false ? "lock=\"{$lock}\"" : "") . "/>"; /* $bMarks = $loggedUser->getBookmarks(); if (count($bMarks)) { $buffer.= "<bookmarks>".AJXP_XMLWriter::writeBookmarks($bMarks, false)."</bookmarks>"; } */ $buffer .= "</user>"; } } return $buffer; }
protected function parseSpecificContributions(&$contribNode) { parent::parseSpecificContributions($contribNode); if ($contribNode->nodeName != "actions") { return; } if (AuthService::usersEnabled() && $this->passwordsEditable()) { return; } // Disable password change action if (!isset($actionXpath)) { $actionXpath = new DOMXPath($contribNode->ownerDocument); } $passChangeNodeList = $actionXpath->query('action[@name="pass_change"]', $contribNode); if (!$passChangeNodeList->length) { return; } unset($this->actions["pass_change"]); $passChangeNode = $passChangeNodeList->item(0); $contribNode->removeChild($passChangeNode); }
/** * @param String $repositoryId * @param Repository $repositoryObject * @param AbstractAjxpUser $userObject * @param bool $details * @param bool $includeShared * * @return bool */ public static function repositoryIsAccessible($repositoryId, $repositoryObject, $userObject = null, $details = false, $includeShared = true) { if ($userObject == null) { $userObject = AuthService::getLoggedUser(); } if ($userObject == null && AuthService::usersEnabled()) { return false; } if (!AuthService::canAssign($repositoryObject, $userObject)) { return false; } if ($repositoryObject->isTemplate) { return false; } if ($repositoryObject->getAccessType() == "ajxp_conf" && $userObject != null) { if (AuthService::usersEnabled() && !$userObject->isAdmin()) { return false; } } if ($repositoryObject->getAccessType() == "ajxp_user" && $userObject != null) { return $userObject->canRead($repositoryId) || $userObject->canWrite($repositoryId); } if ($repositoryObject->getAccessType() == "ajxp_shared" && !AuthService::usersEnabled()) { return false; } if ($repositoryObject->getUniqueUser() && (!AuthService::usersEnabled() || $userObject == null || $userObject->getId() == "shared" || $userObject->getId() != $repositoryObject->getUniqueUser())) { return false; } if ($userObject != null && !($userObject->canRead($repositoryId) || $userObject->canWrite($repositoryId)) && !$details) { return false; } if ($userObject == null || $userObject->canRead($repositoryId) || $userObject->canWrite($repositoryId) || $details) { // Do not display standard repositories even in details mode for "sub"users if ($userObject != null && $userObject->hasParent() && !($userObject->canRead($repositoryId) || $userObject->canWrite($repositoryId))) { return false; } // Do not display shared repositories otherwise. if ($repositoryObject->hasOwner() && !$includeShared && ($userObject == null || $userObject->getParent() != $repositoryObject->getOwner())) { return false; } if ($userObject != null && $repositoryObject->hasOwner() && !$userObject->hasParent()) { // Display the repositories if allow_crossusers is ok if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") === false || ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") === 0) { return false; } // But still do not display its own shared repositories! if ($repositoryObject->getOwner() == $userObject->getId()) { return false; } } if ($repositoryObject->hasOwner() && $userObject != null && $details && !($userObject->canRead($repositoryId) || $userObject->canWrite($repositoryId))) { return false; } } return true; }
} //------------------------------------------------------------ // SPECIAL HANDLING FOR FANCY UPLOADER RIGHTS FOR THIS ACTION //------------------------------------------------------------ if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($action == "upload" && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRepositoryId() . "")) && isset($_FILES['Filedata'])) { header('HTTP/1.0 ' . '410 Not authorized'); die('Error 410 Not authorized!'); } } // THIS FIRST DRIVERS DO NOT NEED ID CHECK //$ajxpDriver = AJXP_PluginsService::findPlugin("gui", "ajax"); $authDriver = ConfService::getAuthDriverImpl(); // DRIVERS BELOW NEED IDENTIFICATION CHECK if (!AuthService::usersEnabled() || ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") || AuthService::getLoggedUser() != null) { $confDriver = ConfService::getConfStorageImpl(); $Driver = ConfService::loadRepositoryDriver(); } AJXP_PluginsService::getInstance()->initActivePlugins(); require_once AJXP_BIN_FOLDER . "/class.AJXP_Controller.php"; $xmlResult = AJXP_Controller::findActionAndApply($action, array_merge($_GET, $_POST), $_FILES); if ($xmlResult !== false && $xmlResult != "") { AJXP_XMLWriter::header(); print $xmlResult; AJXP_XMLWriter::close(); } else { if (isset($requireAuth) && AJXP_Controller::$lastActionNeedsAuth) { AJXP_XMLWriter::header(); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close();
public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepositoryById($httpVars["repository_id"]); if (!$repository->detectStreamWrapper(true)) { return false; } if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) { AuthService::logUser("guest", null); $loggedUser = AuthService::getLoggedUser(); } if (!$loggedUser->canSwitchTo($repository->getId())) { echo "You do not have permissions to access this resource"; return false; } } $selection = new UserSelection($repository, $httpVars); if ($action == "open_file") { $selectedNode = $selection->getUniqueNode(); $selectedNodeUrl = $selectedNode->getUrl(); if (!file_exists($selectedNodeUrl) || !is_readable($selectedNodeUrl)) { echo "File does not exist"; return false; } $filesize = filesize($selectedNodeUrl); $fp = fopen($selectedNodeUrl, "rb"); $fileMime = "application/octet-stream"; //Get mimetype with fileinfo PECL extension if (class_exists("finfo")) { $finfo = new finfo(FILEINFO_MIME); $fileMime = $finfo->buffer(fread($fp, 2000)); } //Get mimetype with (deprecated) mime_content_type if (strpos($fileMime, "application/octet-stream") === 0 && function_exists("mime_content_type")) { $fileMime = @mime_content_type($fp); } //Guess mimetype based on file extension if (strpos($fileMime, "application/octet-stream") === 0) { $fileExt = substr(strrchr(basename($selectedNodeUrl), '.'), 1); if (empty($fileExt)) { $fileMime = "application/octet-stream"; } else { $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i"; $lines = file($this->getBaseDir() . "/resources/other/mime.types"); foreach ($lines as $line) { if (substr($line, 0, 1) == '#') { continue; } // skip comments $line = rtrim($line) . " "; if (!preg_match($regex, $line, $matches)) { continue; } // no match to the extension $fileMime = $matches[1]; } } } fclose($fp); // If still no mimetype, give up and serve application/octet-stream if (empty($fileMime)) { $fileMime = "application/octet-stream"; } //Send headers HTMLWriter::generateInlineHeaders(basename($selectedNodeUrl), $filesize, $fileMime); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($selectedNodeUrl, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($selectedNode)); $this->logInfo('Download', 'Read content of ' . $selectedNodeUrl, array("files" => $selectedNodeUrl)); } }
/** * formats the error message in representable manner * * @param $message String this is the message to be formatted * @param $severity Severity level of the message: one of LOG_LEVEL_* (DEBUG,INFO,NOTICE,WARNING,ERROR) * @return String the formatted message. */ function formatMessage($message, $severity) { $msg = date("m-d-y") . " " . date("G:i:s") . "\t"; $msg .= $_SERVER['REMOTE_ADDR']; $msg .= "\t" . strtoupper($severity) . "\t"; // Get the user if it exists $user = "******"; if (AuthService::usersEnabled()) { $logged = AuthService::getLoggedUser(); if ($logged != null) { $user = $logged->getId(); } else { $user = "******"; } } $msg .= "{$user}\t"; //$msg .= $severity; $msg .= "" . $message . "\n"; return $msg; }
} // INIT DRIVER $Driver = ConfService::getRepositoryDriver(); if ($Driver == null || !is_a($Driver, "AbstractDriver")) { AJXP_XMLWriter::header(); if (is_a($Driver, "AJXP_Exception")) { AJXP_XMLWriter::sendMessage(null, "Cannot initialize driver : " . $Driver->getMessage()); } else { AJXP_XMLWriter::sendMessage(null, "Cannot find driver!"); } AJXP_XMLWriter::close(); exit(1); } if ($Driver->hasAction($action)) { // CHECK RIGHTS if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($Driver->actionNeedsRight($action, "r") && ($loggedUser == null || !$loggedUser->canRead(ConfService::getCurrentRootDirIndex() . ""))) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess[208]); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); exit(1); } if ($Driver->actionNeedsRight($action, "w") && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRootDirIndex() . ""))) { AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess[207]); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); exit(1); }
/** * Utilitary to pass some parameters directly at startup : * + repository_id / folder * + compile & skipDebug * + update_i18n, extract, create * + external_selector_type * + skipIOS * + gui * @static * @param $parameters * @param $output * @param $session * @return void */ public static function parseApplicationGetParameters($parameters, &$output, &$session) { $output["EXT_REP"] = "/"; if (isset($parameters["repository_id"]) && isset($parameters["folder"]) || isset($parameters["goto"])) { if (isset($parameters["goto"])) { $explode = explode("/", ltrim($parameters["goto"], "/")); $repoId = array_shift($explode); $parameters["folder"] = str_replace($repoId, "", ltrim($parameters["goto"], "/")); } else { $repoId = $parameters["repository_id"]; } $repository = ConfService::getRepositoryById($repoId); if ($repository == null) { $repository = ConfService::getRepositoryByAlias($repoId); if ($repository != null) { $parameters["repository_id"] = $repository->getId(); } } else { $parameters["repository_id"] = $repository->getId(); } require_once AJXP_BIN_FOLDER . "/class.SystemTextEncoding.php"; if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && $loggedUser->canSwitchTo($parameters["repository_id"])) { $output["FORCE_REGISTRY_RELOAD"] = true; $output["EXT_REP"] = SystemTextEncoding::toUTF8(urldecode($parameters["folder"])); $loggedUser->setArrayPref("history", "last_repository", $parameters["repository_id"]); $loggedUser->setPref("pending_folder", SystemTextEncoding::toUTF8(AJXP_Utils::decodeSecureMagic($parameters["folder"]))); $loggedUser->save("user"); AuthService::updateUser($loggedUser); } else { $session["PENDING_REPOSITORY_ID"] = $parameters["repository_id"]; $session["PENDING_FOLDER"] = SystemTextEncoding::toUTF8(AJXP_Utils::decodeSecureMagic($parameters["folder"])); } } else { ConfService::switchRootDir($parameters["repository_id"]); $output["EXT_REP"] = SystemTextEncoding::toUTF8(urldecode($parameters["folder"])); } } if (isset($parameters["skipDebug"])) { ConfService::setConf("JS_DEBUG", false); } if (ConfService::getConf("JS_DEBUG") && isset($parameters["compile"])) { require_once AJXP_BIN_FOLDER . "/class.AJXP_JSPacker.php"; AJXP_JSPacker::pack(); } if (ConfService::getConf("JS_DEBUG") && isset($parameters["update_i18n"])) { if (isset($parameters["extract"])) { self::extractConfStringsFromManifests(); } self::updateAllI18nLibraries(isset($parameters["create"]) ? $parameters["create"] : ""); } if (ConfService::getConf("JS_DEBUG") && isset($parameters["clear_plugins_cache"])) { @unlink(AJXP_PLUGINS_CACHE_FILE); @unlink(AJXP_PLUGINS_REQUIRES_FILE); } if (AJXP_SERVER_DEBUG && isset($parameters["extract_application_hooks"])) { self::extractHooksToDoc(); } if (isset($parameters["external_selector_type"])) { $output["SELECTOR_DATA"] = array("type" => $parameters["external_selector_type"], "data" => $parameters); } if (isset($parameters["skipIOS"])) { setcookie("SKIP_IOS", "true"); } if (isset($parameters["skipANDROID"])) { setcookie("SKIP_ANDROID", "true"); } if (isset($parameters["gui"])) { setcookie("AJXP_GUI", $parameters["gui"]); if ($parameters["gui"] == "light") { $session["USE_EXISTING_TOKEN_IF_EXISTS"] = true; } } else { if (isset($session["USE_EXISTING_TOKEN_IF_EXISTS"])) { unset($session["USE_EXISTING_TOKEN_IF_EXISTS"]); } setcookie("AJXP_GUI", null); } if (isset($session["OVERRIDE_GUI_START_PARAMETERS"])) { $output = array_merge($output, $session["OVERRIDE_GUI_START_PARAMETERS"]); } }
/** * Compute the default repository id to log the current user * @static * @return int|string */ static function getDefaultRootId() { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser == null) { return 0; } $repoList = ConfService::getRootDirsList(); foreach ($repoList as $rootDirIndex => $rootDirObject) { if ($loggedUser->canRead($rootDirIndex . "") || $loggedUser->canWrite($rootDirIndex . "")) { // Warning : do not grant access to admin repository to a non admin, or there will be // an "Empty Repository Object" error. if ($rootDirObject->getAccessType() == "ajxp_conf" && AuthService::usersEnabled() && !$loggedUser->isAdmin()) { continue; } if ($rootDirObject->getAccessType() == "ajxp_shared" && count($repoList) > 1) { continue; } return $rootDirIndex; } } return 0; }