/** * @param AbstractAjxpUser $loggedUser * @param String|int $parameterId * @return bool */ public static function switchUserToActiveRepository($loggedUser, $parameterId = -1) { if (isset($_SESSION["PENDING_REPOSITORY_ID"]) && isset($_SESSION["PENDING_FOLDER"])) { $loggedUser->setArrayPref("history", "last_repository", $_SESSION["PENDING_REPOSITORY_ID"]); $loggedUser->setPref("pending_folder", $_SESSION["PENDING_FOLDER"]); $loggedUser->save("user"); AuthService::updateUser($loggedUser); unset($_SESSION["PENDING_REPOSITORY_ID"]); unset($_SESSION["PENDING_FOLDER"]); } $currentRepoId = ConfService::getCurrentRepositoryId(); $lastRepoId = $loggedUser->getArrayPref("history", "last_repository"); $defaultRepoId = AuthService::getDefaultRootId(); if ($defaultRepoId == -1) { return false; } else { if ($lastRepoId !== "" && $lastRepoId !== $currentRepoId && $parameterId == -1 && $loggedUser->canSwitchTo($lastRepoId)) { ConfService::switchRootDir($lastRepoId); } else { if ($parameterId != -1 && $loggedUser->canSwitchTo($parameterId)) { ConfService::switchRootDir($parameterId); } else { if (!$loggedUser->canSwitchTo($currentRepoId)) { ConfService::switchRootDir($defaultRepoId); } } } } return true; }
} //Set language $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && $loggedUser->getPref("lang") != "") { ConfService::setLanguage($loggedUser->getPref("lang")); } else { if (isset($_COOKIE["AJXP_lang"])) { ConfService::setLanguage($_COOKIE["AJXP_lang"]); } } //------------------------------------------------------------ // 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);
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; }
public function getBookmarks() { if (isset($this->bookmarks) && isset($this->bookmarks[ConfService::getCurrentRepositoryId()])) { return $this->bookmarks[ConfService::getCurrentRepositoryId()]; } return array(); }
/** * @param string $actionName * @param array $httpVars * @param array $fileVars */ public function publishPermissionsMask($actionName, $httpVars, $fileVars) { $mask = array(); HTMLWriter::charsetHeader("application/json"); if (!AuthService::usersEnabled() || AuthService::getLoggedUser() == null) { print json_encode($mask); return; } $repoId = ConfService::getCurrentRepositoryId(); $role = AuthService::getLoggedUser()->mergedRole; if ($role->hasMask($repoId)) { $fullMask = $role->getMask($repoId); foreach ($fullMask->flattenTree() as $path => $permission) { // Do not show if "deny". if ($permission->denies()) { continue; } $mask[$path] = array("read" => $permission->canRead(), "write" => $permission->canWrite()); } } print json_encode($mask); return; }
if (!$res) { AuthService::disconnect(); $requireAuth = true; } */ } if (isset($loggingResult) && $loggingResult != 1) { AJXP_XMLWriter::header(); AJXP_XMLWriter::loggingResult($loggingResult, false, false, ""); AJXP_XMLWriter::close(); if ($optStatusFile) { file_put_contents($optStatusFile, "ERROR:No user logged"); } } } else { AJXP_Logger::debug(ConfService::getCurrentRepositoryId()); } //Set language $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && $loggedUser->getPref("lang") != "") { ConfService::setLanguage($loggedUser->getPref("lang")); } else { if (isset($_COOKIE["AJXP_lang"])) { ConfService::setLanguage($_COOKIE["AJXP_lang"]); } } $mess = ConfService::getMessages(); // THIS FIRST DRIVERS DO NOT NEED ID CHECK //$ajxpDriver = AJXP_PluginsService::findPlugin("gui", "ajax"); $authDriver = ConfService::getAuthDriverImpl(); // DRIVERS BELOW NEED IDENTIFICATION CHECK
/** * @param $action * @param $httpVars * @param $fileVars * */ public function clientChannelMethod($action, $httpVars, $fileVars) { if (!$this->msgExchanger) { return; } switch ($action) { case "client_register_channel": $this->msgExchanger->suscribeToChannel($httpVars["channel"], $httpVars["client_id"]); break; case "client_unregister_channel": $this->msgExchanger->unsuscribeFromChannel($httpVars["channel"], $httpVars["client_id"]); break; case "client_consume_channel": if (AuthService::usersEnabled()) { $user = AuthService::getLoggedUser(); if ($user == null) { AJXP_XMLWriter::header(); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); return; } $GROUP_PATH = $user->getGroupPath(); if ($GROUP_PATH == null) { $GROUP_PATH = false; } $uId = $user->getId(); } else { $GROUP_PATH = '/'; $uId = 'shared'; } $currentRepository = ConfService::getCurrentRepositoryId(); $currentRepoMasks = array(); $regexp = null; AJXP_Controller::applyHook("role.masks", array($currentRepository, &$currentRepoMasks, AJXP_Permission::READ)); if (count($currentRepoMasks)) { $regexps = array(); foreach ($currentRepoMasks as $path) { $regexps[] = '^' . preg_quote($path, '/'); } $regexp = '/' . implode("|", $regexps) . '/'; } $channelRepository = str_replace("nodes:", "", $httpVars["channel"]); if ($channelRepository != $currentRepository) { AJXP_XMLWriter::header(); echo "<require_registry_reload repositoryId=\"{$currentRepository}\"/>"; AJXP_XMLWriter::close(); return; } $data = $this->msgExchanger->consumeInstantChannel($httpVars["channel"], $httpVars["client_id"], $uId, $GROUP_PATH); if (count($data)) { AJXP_XMLWriter::header(); ksort($data); foreach ($data as $messageObject) { if (isset($regexp) && isset($messageObject->nodePathes)) { $pathIncluded = false; foreach ($messageObject->nodePathes as $nodePath) { if (preg_match($regexp, $nodePath)) { $pathIncluded = true; break; } } if (!$pathIncluded) { continue; } } echo $messageObject->content; } AJXP_XMLWriter::close(); } break; default: break; } }
/** * HTTP PUT method * * This HTTP method updates a file, or creates a new one. * * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 204 No Content * * @param string $uri * @return bool */ protected function httpPut($uri) { $body = $this->httpRequest->getBody(); // Intercepting Content-Range if ($this->httpRequest->getHeader('Content-Range')) { /** Content-Range is dangerous for PUT requests: PUT per definition stores a full resource. draft-ietf-httpbis-p2-semantics-15 says in section 7.6: An origin server SHOULD reject any PUT request that contains a Content-Range header field, since it might be misinterpreted as partial content (or might be partial content that is being mistakenly PUT as a full representation). Partial content updates are possible by targeting a separately identified resource with state that overlaps a portion of the larger resource, or by using a different method that has been specifically defined for partial updates (for example, the PATCH method defined in [RFC5789]). This clarifies RFC2616 section 9.6: The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases. OTOH is a PUT request with a Content-Range currently the only way to continue an aborted upload request and is supported by curl, mod_dav, Tomcat and others. Since some clients do use this feature which results in unexpected behaviour (cf PEAR::HTTP_WebDAV_Client 1.0.1), we reject all PUT requests with a Content-Range for now. */ throw new Exception\NotImplemented('PUT with Content-Range is not allowed.'); } // Intercepting the Finder problem if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) { /** Many webservers will not cooperate well with Finder PUT requests, because it uses 'Chunked' transfer encoding for the request body. The symptom of this problem is that Finder sends files to the server, but they arrive as 0-length files in PHP. If we don't do anything, the user might think they are uploading files successfully, but they end up empty on the server. Instead, we throw back an error if we detect this. The reason Finder uses Chunked, is because it thinks the files might change as it's being uploaded, and therefore the Content-Length can vary. Instead it sends the X-Expected-Entity-Length header with the size of the file at the very start of the request. If this header is set, but we don't get a request body we will fail the request to protect the end-user. */ // Only reading first byte $firstByte = fread($body, 1); if (strlen($firstByte) !== 1) { throw new Exception\Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.'); } // The body needs to stay intact, so we copy everything to a // temporary stream. $newBody = fopen('php://temp', 'r+'); fwrite($newBody, $firstByte); stream_copy_to_stream($body, $newBody); rewind($newBody); $body = $newBody; } if ($this->tree->nodeExists($uri)) { $node = $this->tree->getNodeForPath($uri); // Checking If-None-Match and related headers. if (!$this->checkPreconditions()) { return; } // If the node is a collection, we'll deny it if (!$node instanceof IFile) { throw new Exception\Conflict('PUT is not allowed on non-files.'); } if (!$this->broadcastEvent('beforeWriteContent', array($uri, $node, &$body))) { return false; } $etag = $node->put($body); $this->broadcastEvent('afterWriteContent', array($uri, $node)); $this->httpResponse->setHeader('Content-Length', '0'); if ($etag) { $this->httpResponse->setHeader('ETag', $etag); } $this->httpResponse->sendStatus(204); } else { $etag = null; // If we got here, the resource didn't exist yet. if (!$this->createFile($this->getRequestUri(), $body, $etag)) { // For one reason or another the file was not created. return; } $this->httpResponse->setHeader('Content-Length', '0'); if ($etag) { $this->httpResponse->setHeader('ETag', $etag); } $this->httpResponse->sendStatus(201); } $repositories = \ConfService::getRepositoriesList("user"); \AJXP_Logger::info(__CLASS__, "Upload", array("files" => $repositories[\ConfService::getCurrentRepositoryId()]->getSlug() . "/" . $uri)); }
public function loadUserFeed($actionName, $httpVars, $fileVars) { if (!$this->eventStore) { return array(); } $u = AuthService::getLoggedUser(); if ($u == null) { if ($httpVars["format"] == "html") { return array(); } AJXP_XMLWriter::header(); AJXP_XMLWriter::close(); return array(); } $userId = $u->getId(); $userGroup = $u->getGroupPath(); $authRepos = array(); $crtRepId = ConfService::getCurrentRepositoryId(); if (isset($httpVars["repository_id"]) && $u->mergedRole->canRead($httpVars["repository_id"])) { $authRepos[] = $httpVars["repository_id"]; } else { if (isset($httpVars["current_repository"])) { $authRepos[] = $crtRepId; } else { $accessibleRepos = ConfService::getAccessibleRepositories(AuthService::getLoggedUser(), false, true, false); $authRepos = array_keys($accessibleRepos); } } $offset = isset($httpVars["offset"]) ? intval($httpVars["offset"]) : 0; $limit = isset($httpVars["limit"]) ? intval($httpVars["limit"]) : 15; if (!isset($httpVars["feed_type"]) || $httpVars["feed_type"] == "notif" || $httpVars["feed_type"] == "all") { $res = $this->eventStore->loadEvents($authRepos, isset($httpVars["path"]) ? $httpVars["path"] : "", $userGroup, $offset, $limit, false, $userId); } else { $res = array(); } $mess = ConfService::getMessages(); $format = "html"; if (isset($httpVars["format"])) { $format = $httpVars["format"]; } if ($format == "html") { echo "<h2>" . $mess["notification_center.4"] . "</h2>"; echo "<ul class='notification_list'>"; } else { if ($format == "json") { $jsonNodes = array(); } else { if ($format != 'array') { AJXP_XMLWriter::header(); } } } // APPEND USER ALERT IN THE SAME QUERY FOR NOW if (!isset($httpVars["feed_type"]) || $httpVars["feed_type"] == "alert" || $httpVars["feed_type"] == "all") { $this->loadUserAlerts("", array_merge($httpVars, array("skip_container_tags" => "true")), $fileVars); } restore_error_handler(); $index = 1; foreach ($res as $n => $object) { $args = $object->arguments; $oldNode = isset($args[0]) ? $args[0] : null; $newNode = isset($args[1]) ? $args[1] : null; $copy = isset($args[2]) && $args[2] === true ? true : null; $notif = $this->generateNotificationFromChangeHook($oldNode, $newNode, $copy, "unify"); if ($notif !== false && $notif->getNode() !== false) { $notif->setAuthor($object->author); $notif->setDate(intval($object->date)); if ($format == "html") { $p = $notif->getNode()->getPath(); echo "<li data-ajxpNode='{$p}'>"; echo $notif->getDescriptionShort(true); echo "</li>"; } else { $node = $notif->getNode(); if ($node == null) { $this->logInfo("Warning", "Empty node stored in notification " . $notif->getAuthor() . "/ " . $notif->getAction()); continue; } try { $node->loadNodeInfo(); } catch (Exception $e) { continue; } $node->event_description = ucfirst($notif->getDescriptionBlock()) . " " . $mess["notification.tpl.block.user_link"] . " " . $notif->getAuthorLabel(); $node->event_description_long = $notif->getDescriptionLong(true); $node->event_date = SystemTextEncoding::fromUTF8(AJXP_Utils::relativeDate($notif->getDate(), $mess)); $node->short_date = AJXP_Utils::relativeDate($notif->getDate(), $mess, true); $node->event_time = $notif->getDate(); $node->event_type = "notification"; $node->event_id = $object->event_id; if ($node->getRepository() != null) { $node->repository_id = '' . $node->getRepository()->getId(); if ($node->repository_id != $crtRepId && $node->getRepository()->getDisplay() != null) { $node->event_repository_label = "[" . $node->getRepository()->getDisplay() . "]"; } } $node->event_author = $notif->getAuthor(); // Replace PATH, to make sure they will be distinct children of the loader node $node->real_path = $node->getPath(); $node->setLabel(basename($node->getPath())); if (isset($httpVars["merge_description"]) && $httpVars["merge_description"] == "true") { if (isset($httpVars["description_as_label"]) && $httpVars["description_as_label"] == "true") { $node->setLabel($node->event_description . " " . $node->event_date); } else { $node->setLabel(basename($node->getPath()) . " <small class='notif_desc'>" . $node->event_description . " " . $node->event_date . "</small>"); } } $url = parse_url($node->getUrl()); $node->setUrl($url["scheme"] . "://" . $url["host"] . "/notification_" . $index); $index++; if ($format == "json" || $format == "array") { $keys = $node->listMetaKeys(); $data = array(); foreach ($keys as $k) { $data[$k] = $node->{$k}; } if ($format == "json") { $jsonNodes[] = json_encode($data); } else { $jsonNodes[] = $data; } } else { AJXP_XMLWriter::renderAjxpNode($node); } } } } if ($format == "html") { echo "</ul>"; } else { if ($format == "json") { HTMLWriter::charsetHeader("application/json"); echo '[' . implode(",", $jsonNodes) . ']'; } else { if ($format == "array") { return $jsonNodes; } else { AJXP_XMLWriter::close(); } } } }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; if ($this->wrapperClassName == "fsAccessWrapper") { $dir = fsAccessWrapper::patchPathForBaseDir($dir); } $dir = AJXP_Utils::securePath($dir); if ($action != "upload") { $dir = AJXP_Utils::decodeSecureMagic($dir); } $selection->initFromHttpVars($httpVars); if (!$selection->isEmpty()) { $this->filterUserSelectionToHidden($selection->getFiles()); } $mess = ConfService::getMessages(); $newArgs = RecycleBinManager::filterActions($action, $selection, $dir, $httpVars); if (isset($newArgs["action"])) { $action = $newArgs["action"]; } if (isset($newArgs["dest"])) { $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]); } //Re-encode! // FILTER DIR PAGINATION ANCHOR $page = null; if (isset($dir) && strstr($dir, "%23") !== false) { $parts = explode("%23", $dir); $dir = $parts[0]; $page = $parts[1]; } $pendingSelection = ""; $logMessage = null; $reloadContextNode = false; switch ($action) { //------------------------------------ // DOWNLOAD //------------------------------------ case "download": $this->logInfo("Download", array("files" => $this->addSlugToPath($selection))); @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE); @register_shutdown_function("restore_error_handler"); $zip = false; if ($selection->isUnique()) { if (is_dir($this->urlBase . $selection->getUniqueFile())) { $zip = true; $base = basename($selection->getUniqueFile()); $uniqDir = dirname($selection->getUniqueFile()); if (!empty($uniqDir) && $uniqDir != "/") { $dir = dirname($selection->getUniqueFile()); } } else { if (!file_exists($this->urlBase . $selection->getUniqueFile())) { throw new Exception("Cannot find file!"); } } $node = $selection->getUniqueNode($this); } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpDownload.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, empty($dir) ? "/" : $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing"); } if (!$this->getFilteredOption("USE_XSENDFILE", $this->repository->getId()) && !$this->getFilteredOption("USE_XACCELREDIRECT", $this->repository->getId())) { register_shutdown_function("unlink", $file); } $localName = ($base == "" ? "Files" : $base) . ".zip"; if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); } $this->readFile($file, "force-download", $localName, false, false, true); } else { $localName = ""; AJXP_Controller::applyHook("dl.localname", array($this->urlBase . $selection->getUniqueFile(), &$localName, $this->wrapperClassName)); $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download", $localName); } if (isset($node)) { AJXP_Controller::applyHook("node.read", array(&$node)); } break; case "prepare_chunk_dl": $chunkCount = intval($httpVars["chunk_count"]); $fileId = $this->urlBase . $selection->getUniqueFile(); $sessionKey = "chunk_file_" . md5($fileId . time()); $totalSize = $this->filesystemFileSize($fileId); $chunkSize = intval($totalSize / $chunkCount); $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $fileId, true); $chunkData = array("localname" => basename($fileId), "chunk_count" => $chunkCount, "chunk_size" => $chunkSize, "total_size" => $totalSize, "file_id" => $sessionKey); $_SESSION[$sessionKey] = array_merge($chunkData, array("file" => $realFile)); HTMLWriter::charsetHeader("application/json"); print json_encode($chunkData); $node = $selection->getUniqueNode($this); AJXP_Controller::applyHook("node.read", array(&$node)); break; case "download_chunk": $chunkIndex = intval($httpVars["chunk_index"]); $chunkKey = $httpVars["file_id"]; $sessData = $_SESSION[$chunkKey]; $realFile = $sessData["file"]; $chunkSize = $sessData["chunk_size"]; $offset = $chunkSize * $chunkIndex; if ($chunkIndex == $sessData["chunk_count"] - 1) { // Compute the last chunk real length $chunkSize = $sessData["total_size"] - $chunkSize * ($sessData["chunk_count"] - 1); if (call_user_func(array($this->wrapperClassName, "isRemote"))) { register_shutdown_function("unlink", $realFile); } } $this->readFile($realFile, "force-download", $sessData["localname"] . "." . sprintf("%03d", $chunkIndex + 1), false, false, true, $offset, $chunkSize); break; case "compress": // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); $this->filterUserSelectionToHidden(array($localName)); } else { $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip"; } $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpCompression.zip"; if (isset($httpVars["compress_flat"])) { $baseDir = "__AJXP_ZIP_FLAT__/"; } else { $baseDir = $dir; } $zipFile = $this->makeZip($selection->getFiles(), $file, $baseDir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing file {$localName}"); } register_shutdown_function("unlink", $file); $tmpFNAME = $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName); copy($file, $tmpFNAME); try { AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($tmpFNAME), filesize($tmpFNAME))); } catch (Exception $e) { @unlink($tmpFNAME); throw $e; } @rename($tmpFNAME, $this->urlBase . $dir . "/" . $localName); AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($this->urlBase . $dir . "/" . $localName), false)); //$reloadContextNode = true; //$pendingSelection = $localName; $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $localName); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["ADD"][] = $newNode; break; case "stat": clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $stat = @stat($this->urlBase . $selection->getUniqueFile()); if (!$stat) { print '{}'; } else { print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $stat = @stat($this->urlBase . $path); if (!$stat) { $stat = '{}'; } else { $stat = json_encode($stat); } print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "get_content": $dlFile = $this->urlBase . $selection->getUniqueFile(); $this->logInfo("Get_content", array("files" => $this->addSlugToPath($selection))); if (AJXP_Utils::getStreamingMimeType(basename($dlFile)) !== false) { $this->readFile($this->urlBase . $selection->getUniqueFile(), "stream_content"); } else { $this->readFile($this->urlBase . $selection->getUniqueFile(), "plain"); } $node = $selection->getUniqueNode($this); AJXP_Controller::applyHook("node.read", array(&$node)); break; case "put_content": if (!isset($httpVars["content"])) { break; } // Load "code" variable directly from POST array, do not "securePath" or "sanitize"... $code = $httpVars["content"]; $file = $selection->getUniqueFile(); $this->logInfo("Online Edition", array("file" => $this->addSlugToPath($file))); if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") { $code = base64_decode($code); } else { $code = str_replace("<", "<", SystemTextEncoding::magicDequote($code)); } $fileName = $this->urlBase . $file; $currentNode = new AJXP_Node($fileName); try { AJXP_Controller::applyHook("node.before_change", array(&$currentNode, strlen($code))); } catch (Exception $e) { header("Content-Type:text/plain"); print $e->getMessage(); return; } if (!is_file($fileName) || !$this->isWriteable($fileName, "file")) { header("Content-Type:text/plain"); print !$this->isWriteable($fileName, "file") ? "1001" : "1002"; return; } $fp = fopen($fileName, "w"); fputs($fp, $code); fclose($fp); clearstatcache(true, $fileName); AJXP_Controller::applyHook("node.change", array($currentNode, $currentNode, false)); header("Content-Type:text/plain"); print $mess[115]; break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": //throw new AJXP_Exception("", 113); if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && !$loggedUser->canWrite(ConfService::getCurrentRepositoryId())) { throw new AJXP_Exception("You are not allowed to write", 207); } $success = $error = array(); $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $this->filterUserSelectionToHidden(array($httpVars["dest"])); if ($selection->inZip()) { // Set action to copy anycase (cannot move from the zip). $action = "copy"; $this->extractArchive($dest, $selection, $error, $success); } else { $move = $action == "move" ? true : false; if ($move && isset($httpVars["force_copy_delete"])) { $move = false; } $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $move); } if (count($error)) { throw new AJXP_Exception(SystemTextEncoding::toUTF8(join("\n", $error))); } else { if (isset($httpVars["force_copy_delete"])) { $errorMessage = $this->delete($selection->getFiles(), $logMessages); if ($errorMessage) { throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage)); } $this->logInfo("Copy/Delete", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest))); } else { $this->logInfo($action == "move" ? "Move" : "Copy", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest))); } $logMessage = join("\n", $success); } if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } // Assume new nodes are correctly created $selectedItems = $selection->getFiles(); foreach ($selectedItems as $selectedPath) { $newPath = $this->urlBase . $dest . "/" . basename($selectedPath); $newNode = new AJXP_Node($newPath); $nodesDiffs["ADD"][] = $newNode; if ($action == "move") { $nodesDiffs["REMOVE"][] = $selectedPath; } } if (!(RecycleBinManager::getRelativeRecycle() == $dest && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) == true)) { //$reloadDataNode = $dest; } break; //------------------------------------ // DELETE //------------------------------------ //------------------------------------ // DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $logMessages = array(); $errorMessage = $this->delete($selection->getFiles(), $logMessages); if (count($logMessages)) { $logMessage = join("\n", $logMessages); } if ($errorMessage) { throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage)); } $this->logInfo("Delete", array("files" => $this->addSlugToPath($selection))); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["REMOVE"] = array_merge($nodesDiffs["REMOVE"], $selection->getFiles()); break; case "purge": $hardPurgeTime = intval($this->repository->getOption("PURGE_AFTER")) * 3600 * 24; $softPurgeTime = intval($this->repository->getOption("PURGE_AFTER_SOFT")) * 3600 * 24; $shareCenter = AJXP_PluginsService::findPluginById('action.share'); if (!($shareCenter && $shareCenter->isEnabled())) { //action.share is disabled, don't look at the softPurgeTime $softPurgeTime = 0; } if ($hardPurgeTime > 0 || $softPurgeTime > 0) { $this->recursivePurge($this->urlBase, $hardPurgeTime, $softPurgeTime); } break; //------------------------------------ // RENAME //------------------------------------ //------------------------------------ // RENAME //------------------------------------ case "rename": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]); $dest = null; if (isset($httpVars["dest"])) { $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $filename_new = ""; } $this->filterUserSelectionToHidden(array($filename_new)); $this->rename($file, $filename_new, $dest); $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); //$reloadContextNode = true; //$pendingSelection = $filename_new; if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } if ($dest == null) { $dest = AJXP_Utils::safeDirname($file); } $nodesDiffs["UPDATE"][$file] = new AJXP_Node($this->urlBase . $dest . "/" . $filename_new); $this->logInfo("Rename", array("original" => $this->addSlugToPath($file), "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; if (!isset($httpVars["dirname"])) { $uniq = $selection->getUniqueFile(); $dir = AJXP_Utils::safeDirname($uniq); $dirname = AJXP_Utils::safeBasename($uniq); } else { $dirname = AJXP_Utils::decodeSecureMagic($httpVars["dirname"], AJXP_SANITIZE_FILENAME); } $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); $this->filterUserSelectionToHidden(array($dirname)); AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($dir . "/" . $dirname), -2)); $error = $this->mkDir($dir, $dirname, isset($httpVars["ignore_exists"]) ? true : false); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; //$pendingSelection = $dirname; //$reloadContextNode = true; $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $dirname); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } array_push($nodesDiffs["ADD"], $newNode); $this->logInfo("Create Dir", array("dir" => $this->addSlugToPath($dir) . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; if (empty($httpVars["filename"]) && isset($httpVars["node"])) { $filename = AJXP_Utils::decodeSecureMagic($httpVars["node"], AJXP_SANITIZE_FILENAME); } else { $filename = AJXP_Utils::decodeSecureMagic($httpVars["filename"], AJXP_SANITIZE_FILENAME); } $filename = substr($filename, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); $this->filterUserSelectionToHidden(array($filename)); $content = ""; if (isset($httpVars["content"])) { $content = $httpVars["content"]; } $error = $this->createEmptyFile($dir, $filename, $content); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; //$reloadContextNode = true; //$pendingSelection = $dir."/".$filename; $this->logInfo("Create File", array("file" => $this->addSlugToPath($dir) . "/" . $filename)); $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $filename); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } array_push($nodesDiffs["ADD"], $newNode); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $files = $selection->getFiles(); $changedFiles = array(); $chmod_value = $httpVars["chmod_value"]; $recursive = $httpVars["recursive"]; $recur_apply_to = $httpVars["recur_apply_to"]; foreach ($files as $fileName) { $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles); } $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders"; $this->logInfo("Chmod", array("dir" => $this->addSlugToPath($dir), "filesCount" => count($changedFiles))); if (!isset($nodesDiffs)) { $nodesDiffs = $this->getNodesDiffArray(); } $nodesDiffs["UPDATE"] = array_merge($nodesDiffs["UPDATE"], $selection->buildNodes($this)); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": $repoData = array('base_url' => $this->urlBase, 'wrapper_name' => $this->wrapperClassName, 'chmod' => $this->repository->getOption('CHMOD_VALUE'), 'recycle' => $this->repository->getOption('RECYCLE_BIN')); $this->logDebug("Upload Files Data", $fileVars); $destination = $this->urlBase . AJXP_Utils::decodeSecureMagic($dir); $this->logDebug("Upload inside", array("destination" => $this->addSlugToPath($destination))); if (!$this->isWriteable($destination)) { $errorCode = 412; $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}."; $this->logDebug("Upload error 412", array("destination" => $this->addSlugToPath($destination))); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } foreach ($fileVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } $userfile_name = $boxData["name"]; try { $this->filterUserSelectionToHidden(array($userfile_name)); } catch (Exception $e) { return array("ERROR" => array("CODE" => 411, "MESSAGE" => "Forbidden")); } $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromPostedFileName($userfile_name), AJXP_SANITIZE_FILENAME); if (isset($httpVars["urlencoded_filename"])) { $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["urlencoded_filename"])), AJXP_SANITIZE_FILENAME); } $this->logDebug("User filename " . $userfile_name); $userfile_name = substr($userfile_name, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH")); if (isset($httpVars["auto_rename"])) { $userfile_name = self::autoRenameForDest($destination, $userfile_name); } $already_existed = false; try { if (file_exists($destination . "/" . $userfile_name)) { $already_existed = true; AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"])); } else { AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"])); } AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination))); } catch (Exception $e) { $errorCode = 507; $errorMessage = $e->getMessage(); break; } if (isset($boxData["input_upload"])) { try { $this->logDebug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen("{$destination}/" . $userfile_name, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); $this->logDebug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { $result = @move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name); if (!$result) { $realPath = call_user_func(array($this->wrapperClassName, "getRealFSReference"), "{$destination}/" . $userfile_name); $result = move_uploaded_file($boxData["tmp_name"], $realPath); } if (!$result) { $errorCode = 411; $errorMessage = "{$mess['33']} " . $userfile_name; break; } } if (isset($httpVars["appendto_urlencoded_part"])) { $appendTo = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["appendto_urlencoded_part"])), AJXP_SANITIZE_FILENAME); if (file_exists($destination . "/" . $appendTo)) { $this->logDebug("Should copy stream from {$userfile_name} to {$appendTo}"); $partO = fopen($destination . "/" . $userfile_name, "r"); $appendF = fopen($destination . "/" . $appendTo, "a+"); while (!feof($partO)) { $buf = fread($partO, 1024); fwrite($appendF, $buf, strlen($buf)); } fclose($partO); fclose($appendF); $this->logDebug("Done, closing streams!"); } @unlink($destination . "/" . $userfile_name); $userfile_name = $appendTo; } $this->changeMode($destination . "/" . $userfile_name, $repoData); $createdNode = new AJXP_Node($destination . "/" . $userfile_name); //AJXP_Controller::applyHook("node.change", array(null, $createdNode, false)); $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; $this->logInfo("Upload File", array("file" => $this->addSlugToPath(SystemTextEncoding::fromUTF8($dir)) . "/" . $userfile_name)); } if (isset($errorMessage)) { $this->logDebug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { $this->logDebug("Return success"); if ($already_existed) { return array("SUCCESS" => true, "UPDATED_NODE" => $createdNode); } else { return array("SUCCESS" => true, "CREATED_NODE" => $createdNode); } } return; break; case "lsync": if (!ConfService::currentContextIsCommandLine()) { die("This command must be accessed via CLI only."); } $fromNode = null; $toNode = null; $copyOrMove = false; if (isset($httpVars["from"])) { $fromNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["from"])); } if (isset($httpVars["to"])) { $toNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["to"])); } if (isset($httpVars["copy"]) && $httpVars["copy"] == "true") { $copyOrMove = true; } AJXP_Controller::applyHook("node.change", array($fromNode, $toNode, $copyOrMove)); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a"); $startTime = microtime(); if (isset($httpVars["file"])) { $uniqueFile = AJXP_Utils::decodeSecureMagic($httpVars["file"]); } $dir = AJXP_Utils::securePath($dir); $path = $this->urlBase . ($dir != "" ? ($dir[0] == "/" ? "" : "/") . $dir : ""); $nonPatchedPath = $path; if ($this->wrapperClassName == "fsAccessWrapper") { $nonPatchedPath = fsAccessWrapper::unPatchPathForBaseDir($path); } if ($this->getFilteredOption("REMOTE_SORTING")) { $orderDirection = isset($httpVars["order_direction"]) ? strtolower($httpVars["order_direction"]) : "asc"; $orderField = isset($httpVars["order_column"]) ? $httpVars["order_column"] : null; if ($orderField != null && !in_array($orderField, array("ajxp_label", "filesize", "ajxp_modiftime", "mimestring"))) { $orderField = "ajxp_label"; } } if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") { $max_depth = isset($httpVars["max_depth"]) ? intval($httpVars["max_depth"]) : 0; $max_nodes = isset($httpVars["max_nodes"]) ? intval($httpVars["max_nodes"]) : 0; $crt_depth = isset($httpVars["crt_depth"]) ? intval($httpVars["crt_depth"]) + 1 : 1; $crt_nodes = isset($httpVars["crt_nodes"]) ? intval($httpVars["crt_nodes"]) : 0; } else { $threshold = $this->repository->getOption("PAGINATION_THRESHOLD"); if (!isset($threshold) || intval($threshold) == 0) { $threshold = 500; } $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER"); if (!isset($limitPerPage) || intval($limitPerPage) == 0) { $limitPerPage = 200; } } $countFiles = $this->countFiles($path, !$lsOptions["f"]); if (isset($crt_nodes)) { $crt_nodes += $countFiles; } if (isset($threshold) && isset($limitPerPage) && $countFiles > $threshold) { if (isset($uniqueFile)) { $originalLimitPerPage = $limitPerPage; $offset = $limitPerPage = 0; } else { $offset = 0; $crtPage = 1; if (isset($page)) { $offset = (intval($page) - 1) * $limitPerPage; $crtPage = $page; } $totalPages = floor($countFiles / $limitPerPage) + 1; } } else { $offset = $limitPerPage = 0; } $metaData = array(); if (RecycleBinManager::recycleEnabled() && $dir == "") { $metaData["repo_has_recycle"] = "true"; } $parentAjxpNode = new AJXP_Node($nonPatchedPath, $metaData); $parentAjxpNode->loadNodeInfo(false, true, $lsOptions["l"] ? "all" : "minimal"); AJXP_Controller::applyHook("node.read", array(&$parentAjxpNode)); if (AJXP_XMLWriter::$headerSent == "tree") { AJXP_XMLWriter::renderAjxpNode($parentAjxpNode, false); } else { AJXP_XMLWriter::renderAjxpHeaderNode($parentAjxpNode); } if (isset($totalPages) && isset($crtPage)) { $remoteOptions = null; if ($this->getFilteredOption("REMOTE_SORTING")) { $remoteOptions = array("remote_order" => "true", "currentOrderCol" => isset($orderField) ? $orderField : "ajxp_label", "currentOrderDir" => isset($orderDirection) ? $orderDirection : "asc"); } AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages, $this->countFiles($path, TRUE), $remoteOptions); if (!$lsOptions["f"]) { AJXP_XMLWriter::close(); exit(1); } } $cursor = 0; $handle = opendir($path); if (!$handle) { throw new AJXP_Exception("Cannot open dir " . $nonPatchedPath); } closedir($handle); $fullList = array("d" => array(), "z" => array(), "f" => array()); if (isset($orderField) && isset($orderDirection) && $orderField == "ajxp_label" && $orderDirection == "desc") { $nodes = scandir($path, 1); } else { $nodes = scandir($path); } if (!empty($this->driverConf["SCANDIR_RESULT_SORTFONC"])) { usort($nodes, $this->driverConf["SCANDIR_RESULT_SORTFONC"]); } if (isset($orderField) && isset($orderDirection) && $orderField != "ajxp_label") { $toSort = array(); foreach ($nodes as $node) { if ($orderField == "filesize") { $toSort[$node] = is_file($nonPatchedPath . "/" . $node) ? $this->filesystemFileSize($nonPatchedPath . "/" . $node) : 0; } else { if ($orderField == "ajxp_modiftime") { $toSort[$node] = filemtime($nonPatchedPath . "/" . $node); } else { if ($orderField == "mimestring") { $toSort[$node] = pathinfo($node, PATHINFO_EXTENSION); } } } } if ($orderDirection == "asc") { asort($toSort); } else { arsort($toSort); } $nodes = array_keys($toSort); } //while (strlen($nodeName = readdir($handle)) > 0) { foreach ($nodes as $nodeName) { if ($nodeName == "." || $nodeName == "..") { continue; } if (isset($uniqueFile) && $nodeName != $uniqueFile) { $cursor++; continue; } if ($offset > 0 && $cursor < $offset) { $cursor++; continue; } $isLeaf = ""; if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) { continue; } if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) { continue; } if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) { break; } $currentFile = $nonPatchedPath . "/" . $nodeName; $meta = array(); if ($isLeaf != "") { $meta = array("is_file" => $isLeaf ? "1" : "0"); } $node = new AJXP_Node($currentFile, $meta); $node->setLabel($nodeName); $node->loadNodeInfo(false, false, $lsOptions["l"] ? "all" : "minimal"); if (!empty($node->metaData["nodeName"]) && $node->metaData["nodeName"] != $nodeName) { $node->setUrl($nonPatchedPath . "/" . $node->metaData["nodeName"]); } if (!empty($node->metaData["hidden"]) && $node->metaData["hidden"] === true) { continue; } if (!empty($node->metaData["mimestring_id"]) && array_key_exists($node->metaData["mimestring_id"], $mess)) { $node->mergeMetadata(array("mimestring" => $mess[$node->metaData["mimestring_id"]])); } if (isset($originalLimitPerPage) && $cursor > $originalLimitPerPage) { $node->mergeMetadata(array("page_position" => floor($cursor / $originalLimitPerPage) + 1)); } $nodeType = "d"; if ($node->isLeaf()) { if (AJXP_Utils::isBrowsableArchive($nodeName)) { if ($lsOptions["f"] && $lsOptions["z"]) { $nodeType = "f"; } else { $nodeType = "z"; } } else { $nodeType = "f"; } } // There is a special sorting, cancel the reordering of files & folders. if (isset($orderField) && $orderField != "ajxp_label") { $nodeType = "f"; } $fullList[$nodeType][$nodeName] = $node; $cursor++; if (isset($uniqueFile) && $nodeName != $uniqueFile) { break; } } if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") { $breakNow = false; if (isset($max_depth) && $max_depth > 0 && $crt_depth >= $max_depth) { $breakNow = true; } if (isset($max_nodes) && $max_nodes > 0 && $crt_nodes >= $max_nodes) { $breakNow = true; } foreach ($fullList["d"] as &$nodeDir) { if ($breakNow) { $nodeDir->mergeMetadata(array("ajxp_has_children" => $this->countFiles($nodeDir->getUrl(), false, true) ? "true" : "false")); AJXP_XMLWriter::renderAjxpNode($nodeDir, true); continue; } $this->switchAction("ls", array("dir" => SystemTextEncoding::toUTF8($nodeDir->getPath()), "options" => $httpVars["options"], "recursive" => "true", "max_depth" => $max_depth, "max_nodes" => $max_nodes, "crt_depth" => $crt_depth, "crt_nodes" => $crt_nodes), array()); } } else { array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["d"]); } array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["z"]); array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["f"]); // ADD RECYCLE BIN TO THE LIST if ($dir == "" && !$uniqueFile && RecycleBinManager::recycleEnabled() && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) !== true) { $recycleBinOption = RecycleBinManager::getRelativeRecycle(); if (file_exists($this->urlBase . $recycleBinOption)) { $recycleNode = new AJXP_Node($this->urlBase . $recycleBinOption); $recycleNode->loadNodeInfo(); AJXP_XMLWriter::renderAjxpNode($recycleNode); } } $this->logDebug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms"); AJXP_XMLWriter::close(); break; } $xmlBuffer = ""; if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if ($reloadContextNode) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false); } if (isset($nodesDiffs)) { $xmlBuffer .= AJXP_XMLWriter::writeNodesDiff($nodesDiffs, false); } return $xmlBuffer; }
public function loadUserFeed($actionName, $httpVars, $fileVars) { if (!$this->eventStore) { return; } $u = AuthService::getLoggedUser(); if ($u == null) { if ($httpVars["format"] == "html") { return; } AJXP_XMLWriter::header(); AJXP_XMLWriter::close(); return; } $userId = $u->getId(); $userGroup = $u->getGroupPath(); $authRepos = array(); $crtRepId = ConfService::getCurrentRepositoryId(); if (isset($httpVars["repository_id"]) && $u->mergedRole->canRead($httpVars["repository_id"])) { $authRepos[] = $httpVars["repository_id"]; } else { $acls = AuthService::getLoggedUser()->mergedRole->listAcls(); foreach ($acls as $repoId => $rightString) { if ($rightString == "r" | $rightString == "rw") { $authRepos[] = $repoId; } } } $offset = isset($httpVars["offset"]) ? intval($httpVars["offset"]) : 0; $limit = isset($httpVars["limit"]) ? intval($httpVars["limit"]) : 15; $res = $this->eventStore->loadEvents($authRepos, $userId, $userGroup, $offset, $limit, isset($httpVars["repository_id"]) ? false : true); $mess = ConfService::getMessages(); $format = "html"; if (isset($httpVars["format"])) { $format = $httpVars["format"]; } if ($format == "html") { echo "<h2>" . $mess["notification_center.4"] . "</h2>"; echo "<ul class='notification_list'>"; } else { AJXP_XMLWriter::header(); } // APPEND USER ALERT IN THE SAME QUERY FOR NOW $this->loadUserAlerts("", array_merge($httpVars, array("skip_container_tags" => "true")), $fileVars); restore_error_handler(); $index = 1; foreach ($res as $n => $object) { $args = $object->arguments; $oldNode = isset($args[0]) ? $args[0] : null; $newNode = isset($args[1]) ? $args[1] : null; $copy = isset($args[2]) && $args[2] === true ? true : null; $notif = $this->generateNotificationFromChangeHook($oldNode, $newNode, $copy, "unify"); if ($notif !== false && $notif->getNode() !== false) { $notif->setAuthor($object->author); $notif->setDate(intval($object->date)); if ($format == "html") { $p = $notif->getNode()->getPath(); echo "<li data-ajxpNode='{$p}'>"; echo $notif->getDescriptionShort(true); echo "</li>"; } else { $node = $notif->getNode(); if ($node == null) { $this->logInfo("Warning", "Empty node stored in notification " . $notif->getAuthor() . "/ " . $notif->getAction()); continue; } try { $node->loadNodeInfo(); } catch (Exception $e) { continue; } $node->event_description = ucfirst($notif->getDescriptionBlock()) . " " . $mess["notification.tpl.block.user_link"] . " " . $notif->getAuthor(); $node->event_description_long = $notif->getDescriptionLong(true); $node->event_date = AJXP_Utils::relativeDate($notif->getDate(), $mess); $node->event_id = $object->event_id; if ($node->getRepository() != null) { $node->repository_id = '' . $node->getRepository()->getId(); if ($node->repository_id != $crtRepId && $node->getRepository()->getDisplay() != null) { $node->event_repository_label = "[" . $node->getRepository()->getDisplay() . "]"; } } $node->event_author = $notif->getAuthor(); // Replace PATH, to make sure they will be distinct children of the loader node $node->real_path = $node->getPath(); $node->setLabel(basename($node->getPath())); $url = parse_url($node->getUrl()); $node->setUrl($url["scheme"] . "://" . $url["host"] . "/notification_" . $index); $index++; AJXP_XMLWriter::renderAjxpNode($node); } } } if ($format == "html") { echo "</ul>"; } else { AJXP_XMLWriter::close(); } }
public function switchAction($action, $httpVars, $fileVars) { if (!defined("AJXP_THEME_FOLDER")) { define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res"); define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]); } foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // GET AN HTML TEMPLATE //------------------------------------ case "get_template": HTMLWriter::charsetHeader(); $folder = CLIENT_RESOURCES_FOLDER . "/html"; if (isset($httpVars["pluginName"])) { $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]); if (isset($httpVars["pluginPath"])) { $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]); } } $thFolder = AJXP_THEME_FOLDER . "/html"; if (isset($template_name)) { if (is_file($thFolder . "/" . $template_name)) { include $thFolder . "/" . $template_name; } else { if (is_file($folder . "/" . $template_name)) { include $folder . "/" . $template_name; } } } break; //------------------------------------ // GET I18N MESSAGES //------------------------------------ //------------------------------------ // GET I18N MESSAGES //------------------------------------ case "get_i18n_messages": $refresh = false; if (isset($httpVars["lang"])) { ConfService::setLanguage($httpVars["lang"]); $refresh = true; } if (isset($httpVars["format"]) && $httpVars["format"] == "json") { HTMLWriter::charsetHeader("application/json"); echo json_encode(ConfService::getMessages($refresh)); } else { HTMLWriter::charsetHeader('text/javascript'); HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh)); } break; //------------------------------------ // DISPLAY DOC //------------------------------------ //------------------------------------ // DISPLAY DOC //------------------------------------ case "display_doc": HTMLWriter::charsetHeader(); echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($httpVars["doc_file"]))); break; //------------------------------------ // GET BOOT GUI //------------------------------------ //------------------------------------ // GET BOOT GUI //------------------------------------ case "get_boot_gui": HTMLWriter::internetExplorerMainDocumentHeader(); HTMLWriter::charsetHeader(); if (!is_file(TESTS_RESULT_FILE)) { $outputArray = array(); $testedParams = array(); $passed = AJXP_Utils::runTests($outputArray, $testedParams); if (!$passed && !isset($httpVars["ignore_tests"])) { AJXP_Utils::testResultsToTable($outputArray, $testedParams); die; } else { AJXP_Utils::testResultsToFile($outputArray, $testedParams); } } $root = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $configUrl = ConfService::getCoreConf("SERVER_URL"); if (!empty($configUrl)) { $root = '/' . ltrim(parse_url($configUrl, PHP_URL_PATH), '/'); if (strlen($root) > 1) { $root = rtrim($root, '/') . '/'; } } else { preg_match('/ws-(.)*\\/|settings|dashboard|welcome|user/', $root, $matches, PREG_OFFSET_CAPTURE); if (count($matches)) { $capture = $matches[0][1]; $root = substr($root, 0, $capture); } } $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop", "APPLICATION_ROOT" => $root, "REBASE" => $root); if (AuthService::usersEnabled()) { AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : ""); AuthService::bootSequence($START_PARAMETERS); if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) { if (AuthService::getDefaultRootId() == -1) { AuthService::disconnect(); } else { $loggedUser = AuthService::getLoggedUser(); if (!$loggedUser->canRead(ConfService::getCurrentRepositoryId()) && AuthService::getDefaultRootId() != ConfService::getCurrentRepositoryId()) { ConfService::switchRootDir(AuthService::getDefaultRootId()); } } } } AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION); $confErrors = ConfService::getErrors(); if (count($confErrors)) { $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors)); } // PRECOMPUTE BOOT CONF if (!preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) && !preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) { $preloadedBootConf = $this->computeBootConf(); AJXP_Controller::applyHook("loader.filter_boot_conf", array(&$preloadedBootConf)); $START_PARAMETERS["PRELOADED_BOOT_CONF"] = $preloadedBootConf; } // PRECOMPUTE REGISTRY if (!isset($START_PARAMETERS["FORCE_REGISTRY_RELOAD"])) { $clone = ConfService::getFilteredXMLRegistry(true, true); $clonePath = new DOMXPath($clone); $serverCallbacks = $clonePath->query("//serverCallback|hooks"); foreach ($serverCallbacks as $callback) { $callback->parentNode->removeChild($callback); } $START_PARAMETERS["PRELOADED_REGISTRY"] = AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML()); } $JSON_START_PARAMETERS = json_encode($START_PARAMETERS); $crtTheme = $this->pluginConf["GUI_THEME"]; $additionalFrameworks = $this->getFilteredOption("JS_RESOURCES_BEFORE"); $ADDITIONAL_FRAMEWORKS = ""; if (!empty($additionalFrameworks)) { $frameworkList = explode(",", $additionalFrameworks); foreach ($frameworkList as $index => $framework) { $frameworkList[$index] = '<script language="javascript" type="text/javascript" src="' . $framework . '"></script>' . "\n"; } $ADDITIONAL_FRAMEWORKS = implode("", $frameworkList); } if (ConfService::getConf("JS_DEBUG")) { if (!isset($mess)) { $mess = ConfService::getMessages(); } if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) { include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html"; } else { include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html"; } } else { if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) { $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html"); } else { $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html"); } if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT'])) { $ADDITIONAL_FRAMEWORKS = ""; } $content = str_replace("AJXP_ADDITIONAL_JS_FRAMEWORKS", $ADDITIONAL_FRAMEWORKS, $content); $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false); $content = str_replace("AJXP_REBASE", isset($START_PARAMETERS["REBASE"]) ? '<base href="' . $START_PARAMETERS["REBASE"] . '"/>' : "", $content); if ($JSON_START_PARAMETERS) { $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content); } print $content; } break; //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ case "get_boot_conf": $out = array(); AJXP_Utils::parseApplicationGetParameters($_GET, $out, $_SESSION); $config = $this->computeBootConf(); header("Content-type:application/json;charset=UTF-8"); print json_encode($config); break; default: break; } return false; }
/** * @param $action * @param $httpVars * @param $fileVars * */ public function clientChannelMethod($action, $httpVars, $fileVars) { if (!$this->msgExchanger) { return; } switch ($action) { case "client_register_channel": $this->msgExchanger->suscribeToChannel($httpVars["channel"], $httpVars["client_id"]); break; case "client_unregister_channel": $this->msgExchanger->unsuscribeFromChannel($httpVars["channel"], $httpVars["client_id"]); break; case "client_consume_channel": if (AuthService::usersEnabled()) { $user = AuthService::getLoggedUser(); if ($user == null) { AJXP_XMLWriter::header(); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); return; } $GROUP_PATH = $user->getGroupPath(); if ($GROUP_PATH == null) { $GROUP_PATH = false; } $uId = $user->getId(); } else { $GROUP_PATH = '/'; $uId = 'shared'; } $currentRepository = ConfService::getCurrentRepositoryId(); $channelRepository = str_replace("nodes:", "", $httpVars["channel"]); if ($channelRepository != $currentRepository) { AJXP_XMLWriter::header(); echo "<require_registry_reload repositoryId=\"{$currentRepository}\"/>"; AJXP_XMLWriter::close(); return; } //session_write_close(); $startTime = time(); $maxTime = $startTime + (30 - 3); // while (true) { $data = $this->msgExchanger->consumeInstantChannel($httpVars["channel"], $httpVars["client_id"], $uId, $GROUP_PATH); if (count($data)) { AJXP_XMLWriter::header(); ksort($data); foreach ($data as $messageObject) { echo $messageObject->content; } AJXP_XMLWriter::close(); } // break; // } else if (time() >= $maxTime) { // break; // } // // sleep(3); // } 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; }
/** * Main method for querying the XML registry, find an action and all its associated processors, * and apply all the callbacks. * @static * @param String $actionName * @param array $httpVars * @param array $fileVars * @param DOMNode $action * @return mixed */ public static function findActionAndApply($actionName, $httpVars, $fileVars, &$action = null) { $actionName = AJXP_Utils::sanitize($actionName, AJXP_SANITIZE_EMAILCHARS); if ($actionName == "cross_copy") { $pService = AJXP_PluginsService::getInstance(); $actives = $pService->getActivePlugins(); $accessPlug = $pService->getPluginsByType("access"); if (count($accessPlug)) { foreach ($accessPlug as $key => $objbect) { if ($actives[$objbect->getId()] === true) { call_user_func(array($pService->getPluginById($objbect->getId()), "crossRepositoryCopy"), $httpVars); break; } } } self::$lastActionNeedsAuth = true; return null; } $xPath = self::initXPath(); if ($action == null) { $actions = $xPath->query("actions/action[@name='{$actionName}']"); if (!$actions->length) { self::$lastActionNeedsAuth = true; return false; } $action = $actions->item(0); } //Check Rights if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if (AJXP_Controller::actionNeedsRight($action, $xPath, "adminOnly") && ($loggedUser == null || !$loggedUser->isAdmin())) { $mess = ConfService::getMessages(); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess[207]); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); exit(1); } if (AJXP_Controller::actionNeedsRight($action, $xPath, "read") && ($loggedUser == null || !$loggedUser->canRead(ConfService::getCurrentRepositoryId() . ""))) { AJXP_XMLWriter::header(); if ($actionName == "ls" & $loggedUser != null && $loggedUser->canWrite(ConfService::getCurrentRepositoryId() . "")) { // Special case of "write only" right : return empty listing, no auth error. AJXP_XMLWriter::close(); exit(1); } $mess = ConfService::getMessages(); AJXP_XMLWriter::sendMessage(null, $mess[208]); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); exit(1); } if (AJXP_Controller::actionNeedsRight($action, $xPath, "write") && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRepositoryId() . ""))) { $mess = ConfService::getMessages(); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $mess[207]); AJXP_XMLWriter::requireAuth(); AJXP_XMLWriter::close(); exit(1); } } $preCalls = self::getCallbackNode($xPath, $action, 'pre_processing/serverCallback', $actionName, $httpVars, $fileVars, true); $postCalls = self::getCallbackNode($xPath, $action, 'post_processing/serverCallback[not(@capture="true")]', $actionName, $httpVars, $fileVars, true); $captureCalls = self::getCallbackNode($xPath, $action, 'post_processing/serverCallback[@capture="true"]', $actionName, $httpVars, $fileVars, true); $mainCall = self::getCallbackNode($xPath, $action, "processing/serverCallback", $actionName, $httpVars, $fileVars, false); if ($mainCall != null) { self::checkParams($httpVars, $mainCall, $xPath); } if ($captureCalls !== false) { // Make sure the ShutdownScheduler has its own OB started BEFORE, as it will presumabily be // executed AFTER the end of this one. AJXP_ShutdownScheduler::getInstance(); ob_start(); $params = array("pre_processor_results" => array(), "post_processor_results" => array()); } if ($preCalls !== false) { foreach ($preCalls as $preCall) { // A Preprocessing callback can modify its input arguments (passed by ref) $preResult = self::applyCallback($preCall, $actionName, $httpVars, $fileVars); if (isset($params)) { $params["pre_processor_results"][$preCall->getAttribute("pluginId")] = $preResult; } } } if ($mainCall) { $result = self::applyCallback($mainCall, $actionName, $httpVars, $fileVars); if (isset($params)) { $params["processor_result"] = $result; } } if ($postCalls !== false) { foreach ($postCalls as $postCall) { // A Preprocessing callback can modify its input arguments (passed by ref) $postResult = self::applyCallback($postCall, $actionName, $httpVars, $fileVars); if (isset($params)) { $params["post_processor_results"][$postCall->getAttribute("pluginId")] = $postResult; } } } if ($captureCalls !== false) { $params["ob_output"] = ob_get_contents(); ob_end_clean(); foreach ($captureCalls as $captureCall) { self::applyCallback($captureCall, $actionName, $httpVars, $params); } } else { if (isset($result)) { return $result; } } return null; }
/** * Rename a user bookmark. * * @param $path String Path of the bookmark to rename. * @param $title New title to give the bookmark. * @return null or -1 on error. * @see AbstractAjxpUser#renameBookmark($path, $title) */ public function renameBookmark($path, $title) { $repId = ConfService::getCurrentRepositoryId(); if (isset($this->bookmarks) && isset($this->bookmarks[$repId]) && is_array($this->bookmarks[$repId])) { foreach ($this->bookmarks[$repId] as $k => $v) { $toCompare = ""; if (is_string($v)) { $toCompare = $v; } else { if (is_array($v)) { $toCompare = $v["PATH"]; } } if ($toCompare == trim($path)) { try { dibi::query('UPDATE [ajxp_user_bookmarks] SET ', array('path' => trim($path), 'title' => $title), 'WHERE [login] = %s AND [repo_uuid] = %s AND [title] = %s', $this->getId(), $repId, $v["TITLE"]); } catch (DibiException $e) { $this->log('BOOKMARK RENAME FAILED: Reason: ' . $e->getMessage()); return -1; } $this->bookmarks[$repId][$k] = array("PATH" => trim($path), "TITLE" => $title); } } } }
public function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } if (preg_match('/MSIE 7/', $_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::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) { $processing = $callback->parentNode->removeChild($callback); } if (isset($_GET["xPath"])) { //$regPath = new DOMXPath($regDoc); $nodes = $clonePath->query($_GET["xPath"]); AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $_GET["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"); header('Content-Type: application/xml; charset=UTF-8'); print AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->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": HTMLWriter::internetExplorerMainDocumentHeader(); HTMLWriter::charsetHeader(); if (!is_file(TESTS_RESULT_FILE)) { $outputArray = array(); $testedParams = array(); $passed = AJXP_Utils::runTests($outputArray, $testedParams); if (!$passed && !isset($_GET["ignore_tests"])) { AJXP_Utils::testResultsToTable($outputArray, $testedParams); die; } 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::getCurrentRepositoryId()) && AuthService::getDefaultRootId() != ConfService::getCurrentRepositoryId()) { ConfService::switchRootDir(AuthService::getDefaultRootId()); } } } } AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION); $confErrors = ConfService::getErrors(); if (count($confErrors)) { $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors)); } // PRECOMPUTE BOOT CONF if (!preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) && !preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) { $START_PARAMETERS["PRELOADED_BOOT_CONF"] = $this->computeBootConf(); } // PRECOMPUTE REGISTRY if (!isset($START_PARAMETERS["FORCE_REGISTRY_RELOAD"])) { $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); } $START_PARAMETERS["PRELOADED_REGISTRY"] = AJXP_XMLWriter::replaceAjxpXmlKeywords($clone->saveXML()); } $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); $content = str_replace("AJXP_REBASE", isset($START_PARAMETERS["REBASE"]) ? '<base href="' . $START_PARAMETERS["REBASE"] . '"/>' : "", $content); if ($JSON_START_PARAMETERS) { $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content); } print $content; } break; //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ //------------------------------------ // GET CONFIG FOR BOOT //------------------------------------ case "get_boot_conf": $out = array(); AJXP_Utils::parseApplicationGetParameters($_GET, $out, $_SESSION); $config = $this->computeBootConf(); header("Content-type:application/json;charset=UTF-8"); print json_encode($config); break; default: break; } return false; }