public function parseSpecificContributions(&$contribNode) { parent::parseSpecificContributions($contribNode); if ($contribNode->nodeName != "actions") { return; } $actionXpath = new DOMXPath($contribNode->ownerDocument); $paramList = $actionXpath->query('action[@name="scheduler_addTask"]/processing/standardFormDefinition/param[@name="repository_id"]', $contribNode); if (!$paramList->length) { return; } $paramNode = $paramList->item(0); $sVals = array(); $repos = ConfService::getRepositoriesList("all"); foreach ($repos as $repoId => $repoObject) { $sVals[] = $repoId . "|" . AJXP_Utils::xmlEntities($repoObject->getDisplay()); } $sVals[] = "*|All Repositories"; $paramNode->attributes->getNamedItem("choices")->nodeValue = implode(",", $sVals); if (!AuthService::usersEnabled() || AuthService::getLoggedUser() == null) { return; } $paramList = $actionXpath->query('action[@name="scheduler_addTask"]/processing/standardFormDefinition/param[@name="user_id"]', $contribNode); if (!$paramList->length) { return; } $paramNode = $paramList->item(0); $paramNode->attributes->getNamedItem("default")->nodeValue = AuthService::getLoggedUser()->getId(); }
/** * Write the repositories access rights in XML format * @static * @param AbstractAjxpUser|null $loggedUser * @internal param bool $details * @return string */ public static function writeRepositoriesData($loggedUser) { $st = "<repositories>"; $streams = ConfService::detectRepositoryStreams(false); $exposed = array(); $cacheHasExposed = AJXP_PluginsService::getInstance()->loadFromPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']"); if ($cacheHasExposed !== null && is_array($cacheHasExposed)) { $exposed = $cacheHasExposed; } else { $exposed_props = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'repository') and @expose='true']", "node", false, false, true); foreach ($exposed_props as $exposed_prop) { $pluginId = $exposed_prop->parentNode->parentNode->getAttribute("id"); $paramName = $exposed_prop->getAttribute("name"); $paramDefault = $exposed_prop->getAttribute("default"); $exposed[] = array("PLUGIN_ID" => $pluginId, "NAME" => $paramName, "DEFAULT" => $paramDefault); } AJXP_PluginsService::getInstance()->storeToPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']", $exposed); } $accessible = ConfService::getAccessibleRepositories($loggedUser, false, false); foreach ($accessible as $repoId => $repoObject) { $rightString = ""; $streamString = ""; if (in_array($repoObject->accessType, $streams)) { $streamString = "allowCrossRepositoryCopy=\"true\""; } if ($repoObject->getUniqueUser()) { $streamString .= " user_editable_repository=\"true\" "; } $slugString = ""; $slug = $repoObject->getSlug(); if (!empty($slug)) { $slugString = "repositorySlug=\"{$slug}\""; } $isSharedString = ""; if ($repoObject->hasOwner()) { $uId = $repoObject->getOwner(); $uObject = ConfService::getConfStorageImpl()->createUserObject($uId); $label = $uObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $uId); if (empty($label)) { $label = $uId; } $isSharedString = 'owner="' . AJXP_Utils::xmlEntities($label) . '"'; } $descTag = ""; $public = false; if (!empty($_SESSION["CURRENT_MINISITE"])) { $public = true; } $description = $repoObject->getDescription($public); if (!empty($description)) { $descTag = '<description>' . AJXP_Utils::xmlEntities($description, true) . '</description>'; } $roleString = ""; if ($loggedUser != null) { $merged = $loggedUser->mergedRole; $params = array(); foreach ($exposed as $exposed_prop) { $metaOptions = $repoObject->getOption("META_SOURCES"); if (!isset($metaOptions[$exposed_prop["PLUGIN_ID"]])) { continue; } $value = $exposed_prop["DEFAULT"]; if (isset($metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]])) { $value = $metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]]; } $value = $merged->filterParameterValue($exposed_prop["PLUGIN_ID"], $exposed_prop["NAME"], $repoId, $value); if ($value !== null) { if ($value === true || $value === false) { $value = $value === true ? "true" : "false"; } $params[] = '<repository_plugin_param plugin_id="' . $exposed_prop["PLUGIN_ID"] . '" name="' . $exposed_prop["NAME"] . '" value="' . AJXP_Utils::xmlEntities($value) . '"/>'; $roleString .= str_replace(".", "_", $exposed_prop["PLUGIN_ID"]) . "_" . $exposed_prop["NAME"] . '="' . AJXP_Utils::xmlEntities($value) . '" '; } } $roleString .= 'acl="' . $merged->getAcl($repoId) . '"'; if ($merged->hasMask($repoId)) { $roleString .= ' hasMask="true" '; } } $st .= "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$rightString} {$streamString} {$slugString} {$isSharedString} {$roleString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label>" . $descTag . $repoObject->getClientSettings() . "</repo>"; } $st .= "</repositories>"; return $st; }
public static function upgradeFrom324($oldLocation, $dryRun = true) { $mess = ConfService::getMessages(); $logFile = AJXP_CACHE_DIR . "/import_from_324.log"; if ($dryRun) { print "<b>" . $mess["updater.10"] . "</b><br><br>"; } $itemsToCopy = array(array("mask" => "public/*.php", "target" => "data/public"), array("mask" => "public/.ajxp_publiclet_counters.ser", "target" => "data/public"), array("mask" => "server/logs/*.txt", "target" => "data/logs"), array("mask" => "server/conf/repo.ser", "target" => "data/plugins/conf.serial"), array("mask" => "server/conf/aliases.ser", "target" => "data/plugins/conf.serial"), array("mask" => "server/users/*", "target" => "data/plugins/auth.serial")); $configToPluginsConf = array(array("type" => "constant", "name" => "ENABLE_USERS", "target" => "core.auth/ENABLE_USERS"), array("type" => "constant", "name" => "ALLOW_GUEST_BROWSING", "target" => "core.auth/ALLOW_GUEST_BROWSING"), array("type" => "constant", "name" => "AJXP_PASSWORD_MINLENGTH", "target" => "core.auth/PASSWORD_MINLENGTH"), array("type" => "variable", "name" => "AJXP_SESSION_SET_CREDENTIALS", "target" => "core.auth/SESSION_SET_CREDENTIALS"), array("type" => "constant", "name" => "PUBLIC_DOWNLOAD_FOLDER", "target" => "core.ajaxplorer/PUBLIC_DOWNLOAD_FOLDER"), array("type" => "constant", "name" => "PUBLIC_DOWNLOAD_URL", "target" => "core.ajaxplorer/PUBLIC_DOWNLOAD_URL"), array("type" => "variable", "name" => "default_language", "target" => "core.ajaxplorer/DEFAULT_LANGUAGE"), array("type" => "constant", "name" => "GZIP_DOWNLOAD", "target" => "core.ajaxplorer/GZIP_COMPRESSION"), array("type" => "constant", "name" => "GZIP_LIMIT", "target" => "core.ajaxplorer/GZIP_LIMIT"), array("type" => "constant", "name" => "DISABLE_ZIP_CREATION", "target" => "core.ajaxplorer/ZIP_CREATION", "modifier" => "NOT"), array("type" => "constant", "name" => "AJXP_WEBDAV_ENABLE", "target" => "core.ajaxplorer/WEBDAV_ENABLE"), array("type" => "constant", "name" => "AJXP_WEBDAV_BASEURI", "target" => "core.ajaxplorer/WEBDAV_BASEURI"), array("type" => "constant", "name" => "AJXP_WEBDAV_BASEHOST", "target" => "core.ajaxplorer/WEBDAV_BASEHOST"), array("type" => "constant", "name" => "AJXP_WEBDAV_DIGESTREALM", "target" => "core.ajaxplorer/WEBDAV_DIGESTREALM"), array("type" => "variable", "name" => "webmaster_email", "target" => "core.ajaxplorer/WEBMASTER_EMAIL"), array("type" => "variable", "name" => "max_caracteres", "target" => "core.ajaxplorer/NODENAME_MAX_LENGTH"), array("type" => "variable", "name" => "customTitle", "target" => "core.ajaxplorer/APPLICATION_TITLE"), array("type" => "constant", "name" => "HTTPS_POLICY_FILE", "target" => "uploader.flex/HTTPS_POLICY_FILE"), array("type" => "variable", "name" => "upload_max_number", "target" => "core.uploader/UPLOAD_MAX_NUMBER"), array("type" => "variable", "name" => "upload_max_size_per_file", "target" => "core.uploader/UPLOAD_MAX_SIZE"), array("type" => "variable", "name" => "upload_max_size_total", "target" => "core.uploader/UPLOAD_MAX_SIZE_TOTAL"), array("type" => "constant", "name" => "AJXP_CLIENT_TIMEOUT_TIME", "target" => "gui.ajax/CLIENT_TIMEOUT_TIME"), array("type" => "constant", "name" => "AJXP_CLIENT_TIMEOUT_WARN_BEFORE", "target" => "gui.ajax/CLIENT_TIMEOUT_WARN"), array("type" => "constant", "name" => "GOOGLE_ANALYTICS_ID", "target" => "gui.ajax/GOOGLE_ANALYTICS_ID"), array("type" => "constant", "name" => "GOOGLE_ANALYTICS_DOMAIN", "target" => "gui.ajax/GOOGLE_ANALYTICS_DOMAIN"), array("type" => "constant", "name" => "GOOGLE_ANALYTICS_EVENT", "target" => "gui.ajax/GOOGLE_ANALYTICS_EVENT"), array("type" => "variable", "name" => "customTitleFontSize", "target" => "gui.ajax/CUSTOM_FONT_SIZE"), array("type" => "variable", "name" => "customIcon", "target" => "gui.ajax/CUSTOM_ICON"), array("type" => "variable", "name" => "customIconWidth", "target" => "gui.ajax/CUSTOM_ICON_WIDTH"), array("type" => "variable", "name" => "welcomeCustomMessage", "target" => "gui.ajax/CUSTOM_WELCOME_MESSAGE")); if (!$dryRun) { $logFileHandle = fopen($logFile, "w"); } foreach ($itemsToCopy as $item) { $files = glob($oldLocation . "/" . $item["mask"]); if ($files === false) { continue; } foreach ($files as $fileOrFolder) { $target = AJXP_INSTALL_PATH . "/" . $item["target"]; if (is_file($fileOrFolder)) { $l = "Copy {$fileOrFolder} to " . $target . "/" . basename($fileOrFolder) . "\n"; if ($dryRun) { print nl2br($l); } else { copy($fileOrFolder, $target . "/" . basename($fileOrFolder)); fwrite($logFileHandle, $l); } } else { $l = "Copy recursively " . $fileOrFolder . " to " . $target . "/" . basename($fileOrFolder) . "\n"; if ($dryRun) { print nl2br($l); } else { self::copy_r($fileOrFolder, $target . "/" . basename($fileOrFolder)); fwrite($logFileHandle, $l); } } } } // FILTER THE CONF FILE TO REMOVE ALL CONSTANTS $originalConfdir = $oldLocation . "/server/conf"; $lines = file($originalConfdir . "/conf.php"); $filteredLines = array(); $mutedConstants = array(); foreach ($lines as $line) { if (preg_match('/define\\("(.*)", (.*)\\);/', $line, $matches)) { //var_dump($matches); $value = trim($matches[2]); if (!empty($value)) { if ($value[0] == "\"") { $strValue = substr($value, 1, strlen($value) - 2); if (!empty($strValue)) { $mutedConstants[$matches[1]] = $strValue; } } else { if ($value == "true") { $mutedConstants[$matches[1]] = true; } else { if ($value == "false") { $mutedConstants[$matches[1]] = false; } else { if (is_numeric($value)) { $mutedConstants[$matches[1]] = intval($value); } else { eval("\$res = {$value};"); $mutedConstants[$matches[1]] = $res; } } } } } $filteredLines[] = "//" . $line; } else { $filteredLines[] = $line; } } if (!$dryRun) { fwrite($logFileHandle, "Writing alternate version of conf.php without constants."); } file_put_contents($originalConfdir . "/muted_conf.php", implode("", $filteredLines)); // NOW IMPORT THE MODIFIED CONF FILE AND GATHER ALL DATA include $originalConfdir . "/muted_conf.php"; $allOptions = array(); foreach ($configToPluginsConf as $localConfig) { $localConfigName = $localConfig["name"]; if ($localConfig["type"] == "constant" && isset($mutedConstants[$localConfigName])) { $localConfig["value"] = $mutedConstants[$localConfigName]; } else { if ($localConfig["type"] == "variable" && isset(${$localConfigName})) { $localConfig["value"] = ${$localConfigName}; } } if (!isset($localConfig["value"]) || empty($localConfig["value"])) { continue; } $l = "Should set " . $localConfig["target"] . " to value " . $localConfig["value"] . "\n"; if ($dryRun) { $value = AJXP_Utils::xmlEntities($localConfig["value"]); list($pluginId, $pluginOptionName) = explode("/", $localConfig["target"]); $plug = AJXP_PluginsService::getInstance()->getPluginById($pluginId); $options = $plug->getConfigs(); $options[$pluginOptionName] = $value; print nl2br($l); } else { list($pluginId, $pluginOptionName) = explode("/", $localConfig["target"]); $confStorage = ConfService::getConfStorageImpl(); $value = AJXP_Utils::xmlEntities($localConfig["value"]); if (!isset($allOptions[$pluginId])) { $plug = AJXP_PluginsService::getInstance()->getPluginById($pluginId); $allOptions[$pluginId] = $plug->getConfigs(); } else { $allOptions[$pluginId][$pluginOptionName] = $value; } fwrite($logFileHandle, $l); } } if (!$dryRun && count($allOptions)) { foreach ($allOptions as $pId => $pOptions) { $confStorage->savePluginConfig($pId, $pOptions); } @unlink(AJXP_PLUGINS_CACHE_FILE); @unlink(AJXP_PLUGINS_REQUIRES_FILE); @unlink(AJXP_PLUGINS_MESSAGES_FILE); } foreach ($REPOSITORIES as $localRepoKey => $localRepoDef) { $localRepoString = '$REPOSITORIES[' . (is_numeric($localRepoKey) ? $localRepoKey : '"' . $localRepoKey . '"') . '] = ' . str_replace(array("'", "\\\\"), array("\"", "\\"), var_export($localRepoDef, true)) . ';'; $l = "Will print this to bootstrap_repositories : \n" . $localRepoString; if ($dryRun) { print nl2br($l); } else { file_put_contents($originalConfdir . "/bootstrap_repositories.php", $localRepoString); fwrite($logFileHandle, $l); } } if (!$dryRun) { fclose($logFileHandle); print "<b>The operation is finished, all actions are logged in {$logFile}. Nothing was touch on your previous installation, please note that the repositories are not moved.<br>You should now logout, clear your browser cache, and refresh this page. Then you will log in with your previous users ids.</b>"; } }
public function editMeta($actionName, $httpVars, $fileVars) { if (!isset($this->actions[$actionName])) { return; } if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection(); $selection->initFromHttpVars(); $currentFile = $selection->getUniqueFile(); $wrapperData = $this->accessDriver->detectStreamWrapper(false); $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId(); $newValues = array(); $def = $this->getMetaDefinition(); foreach ($def as $key => $label) { if (isset($httpVars[$key])) { $newValues[$key] = AJXP_Utils::xmlEntities(AJXP_Utils::decodeSecureMagic($httpVars[$key])); } else { if (!isset($original)) { $original = array(); $this->loadMetaFileData($urlBase . $currentFile); $base = basename($currentFile); if (is_array(self::$metaCache) && array_key_exists($base, self::$metaCache)) { $original = self::$metaCache[$base]; } } if (isset($original) && isset($original[$key])) { $newValues[$key] = $original[$key]; } } } $this->addMeta($urlBase . $currentFile, $newValues); AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true); AJXP_XMLWriter::close(); }
/** * Get a log in XML format. * * @param String $date Date in m-d-y format. * @param String $nodeName The name of the node to use for each log item. * @return null */ public function xmlLogs($parentDir, $date, $nodeName = "log", $rootPath = "/logs") { $fName = $this->storageDir . "log_" . $date . ".txt"; if (!is_file($fName) || !is_readable($fName)) { return; } $res = ""; $lines = file($fName); foreach ($lines as $line) { $line = AJXP_Utils::xmlEntities($line); $matches = explode("\t", $line, 6); if (count($matches) == 6) { $fileName = $parentDir . "/" . $matches[0]; foreach ($matches as $key => $match) { $match = AJXP_Utils::xmlEntities($match); $match = str_replace("\"", "'", $match); $matches[$key] = $match; } if (count($matches) < 3) { continue; } // rebuild timestamp $date = $matches[0]; list($m, $d, $Y, $h, $i, $s) = sscanf($date, "%i-%i-%i %i:%i:%i"); $tStamp = mktime($h, $i, $s, $m, $d, $Y); print SystemTextEncoding::toUTF8("<{$nodeName} is_file=\"1\" ajxp_modiftime=\"{$tStamp}\" filename=\"{$fileName}\" ajxp_mime=\"log\" date=\"{$matches['0']}\" ip=\"{$matches['1']}\" level=\"{$matches['2']}\" user=\"{$matches['3']}\" action=\"{$matches['4']}\" params=\"{$matches['5']}\" icon=\"toggle_log.png\" />", false); } } return; }
function listRepositories() { $repos = ConfService::getRepositoriesList(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/></columns>'); $repoArray = array(); foreach ($repos as $repoIndex => $repoObject) { if ($repoObject->getAccessType() == "ajxp_conf") { continue; } $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay())); $repoArray[$name] = $repoIndex; } // Sort the list now by name ksort($repoArray); foreach ($repoArray as $name => $repoIndex) { $repoObject =& $repos[$repoIndex]; $metaData = array("repository_id" => $repoIndex, "accessType" => $repoObject->getAccessType(), "icon" => "folder_red.png", "openicon" => "folder_red.png", "parentname" => "/repositories", "ajxp_mime" => "repository" . ($repoObject->isWriteable() ? "_editable" : "")); AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData); } }
/** * Get a log in XML format. * * @param String $date Date in m-d-y format. * @param String $nodeName The name of the node to use for each log item. * @return null */ function xmlLogs($parentDir, $date, $nodeName = "log") { $fName = $this->storageDir . "log_" . $date . ".txt"; if (!is_file($fName) || !is_readable($fName)) { return; } $res = ""; $lines = file($fName); foreach ($lines as $line) { $line = AJXP_Utils::xmlEntities($line); $matches = array(); if (preg_match("/(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\$/", $line, $matches) !== false) { $fileName = $parentDir . "/" . $matches[1]; foreach ($matches as $key => $match) { $match = AJXP_Utils::xmlEntities($match); $match = str_replace("\"", "'", $match); $matches[$key] = $match; } print SystemTextEncoding::toUTF8("<{$nodeName} is_file=\"1\" filename=\"{$fileName}\" ajxp_mime=\"log\" date=\"{$matches['1']}\" ip=\"{$matches['2']}\" level=\"{$matches['3']}\" user=\"{$matches['4']}\" action=\"{$matches['5']}\" params=\"{$matches['6']}\" icon=\"toggle_log.png\" />"); } } return; }
public function extractExif($actionName, $httpVars, $fileVars) { $repo = $this->accessDriver->repository; $userSelection = new UserSelection($this->accessDriver->repository, $httpVars); $repo->detectStreamWrapper(true); $selectedNode = $userSelection->getUniqueNode(); $realFile = AJXP_MetaStreamWrapper::getRealFSReference($selectedNode->getUrl()); AJXP_Utils::safeIniSet('exif.encode_unicode', 'UTF-8'); $exifData = @exif_read_data($realFile, 0, TRUE); if ($exifData === false || !is_array($exifData)) { return; } if ($exifData !== false && isset($exifData["GPS"])) { $exifData["COMPUTED_GPS"] = $this->convertGPSData($exifData); } $iptc = $this->extractIPTC($realFile); if (count($iptc)) { $exifData["IPTC"] = $iptc; } $excludeTags = array(); // array("componentsconfiguration", "filesource", "scenetype", "makernote", "datadump"); $format = "xml"; if (isset($httpVars["format"]) && $httpVars["format"] == "json") { $format = "json"; } $filteredData = array(); foreach ($exifData as $section => $data) { $filteredData[$section] = array(); foreach ($data as $key => $value) { if (is_array($value)) { $value = implode(",", $value); } if (in_array(strtolower($key), $excludeTags)) { continue; } if (strpos($key, "UndefinedTag:") === 0) { continue; } $value = preg_replace('/[^[:print:]]/', '', $value); $filteredData[$section][$key] = SystemTextEncoding::toUTF8($value); } } if ($format == "xml") { AJXP_XMLWriter::header("metadata", array("file" => $selectedNode->getPath(), "type" => "EXIF")); foreach ($filteredData as $section => $data) { print "<exifSection name='{$section}'>"; foreach ($data as $key => $value) { print "<exifTag name=\"{$key}\">" . AJXP_Utils::xmlEntities($value) . "</exifTag>"; } print "</exifSection>"; } AJXP_XMLWriter::close("metadata"); } else { HTMLWriter::charsetHeader("application/json"); echo json_encode($filteredData); } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $selection = new UserSelection(); $dir = $httpVars["dir"] or ""; $dir = AJXP_Utils::securePath($dir); if ($action != "upload") { $dir = SystemTextEncoding::fromPostedFileName($dir); } $selection->initFromHttpVars($httpVars); $mess = ConfService::getMessages(); $newArgs = RecycleBinManager::filterActions($action, $selection, $dir); if (isset($newArgs["action"])) { $action = $newArgs["action"]; } if (isset($newArgs["dest"])) { $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]); } //Re-encode! // FILTER DIR PAGINATION ANCHOR $page = null; if (isset($dir) && strstr($dir, "#") !== false) { $parts = explode("#", $dir); $dir = $parts[0]; $page = $parts[1]; } $pendingSelection = ""; $logMessage = null; $reloadContextNode = false; switch ($action) { //------------------------------------ // DOWNLOAD //------------------------------------ case "download": AJXP_Logger::logAction("Download", array("files" => $selection)); @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE); @register_shutdown_function("restore_error_handler"); $zip = false; if ($selection->isUnique()) { if (is_dir($this->urlBase . $selection->getUniqueFile())) { $zip = true; $base = basename($selection->getUniqueFile()); $dir .= "/" . dirname($selection->getUniqueFile()); } } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpDownload.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing"); } register_shutdown_function("unlink", $file); $localName = ($base == "" ? "Files" : $base) . ".zip"; $this->readFile($file, "force-download", $localName, false, false, true); } else { $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download"); } exit(0); break; case "compress": // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); if (isset($httpVars["archive_name"])) { $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]); } else { $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip"; } $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpCompression.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { throw new AJXP_Exception("Error while compressing file {$localName}"); } register_shutdown_function("unlink", $file); copy($file, $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName)); @rename($this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName), $this->urlBase . $dir . "/" . $localName); $reloadContextNode = true; $pendingSelection = $localName; break; case "stat": clearstatcache(); $stat = @stat($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["file"])); header("Content-type:application/json"); if (!$stat) { print '{}'; } else { print json_encode($stat); } exit(1); break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "get_content": $this->readFile($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["file"]), "plain"); exit(0); break; case "put_content": if (!isset($httpVars["content"])) { break; } // Reload "code" variable directly from POST array, do not "securePath"... $code = $httpVars["content"]; $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); AJXP_Logger::logAction("Online Edition", array("file" => $file)); if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") { $code = base64_decode($code); } else { $code = stripslashes($code); $code = str_replace("<", "<", $code); } $fileName = $this->urlBase . $file; if (!is_file($fileName) || !is_writable($fileName)) { header("Content-Type:text/plain"); print !is_writable($fileName) ? "1001" : "1002"; exit(1); } $fp = fopen($fileName, "w"); fputs($fp, $code); fclose($fp); header("Content-Type:text/plain"); print $mess[115]; exit(0); break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $success = $error = array(); $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); if ($selection->inZip()) { // Set action to copy anycase (cannot move from the zip). $action = "copy"; } $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false); if (count($error)) { throw new AJXP_Exception(join("\n", $error)); } else { $logMessage = join("\n", $success); AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest)); } $reloadContextNode = true; $reloadDataNode = $dest; break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { throw new AJXP_Exception("", 113); } $logMessages = array(); $errorMessage = $this->delete($selection->getFiles(), $logMessages); if (count($logMessages)) { $logMessage = join("\n", $logMessages); } if ($errorMessage) { throw new AJXP_Exception($errorMessage); } AJXP_Logger::logAction("Delete", array("files" => $selection)); $reloadContextNode = true; break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "rename": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]); $this->rename($file, $filename_new); $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); $reloadContextNode = true; $pendingSelection = $filename_new; AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; $dirname = AJXP_Utils::processFileName(SystemTextEncoding::fromUTF8($httpVars["dirname"])); $error = $this->mkDir($dir, $dirname); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $pendingSelection = $dirname; $reloadContextNode = true; AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; $filename = AJXP_Utils::processFileName(SystemTextEncoding::fromUTF8($httpVars["filename"])); $error = $this->createEmptyFile($dir, $filename); if (isset($error)) { throw new AJXP_Exception($error); } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reloadContextNode = true; $pendingSelection = $dir . "/" . $filename; AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename)); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $messtmp = ""; $files = $selection->getFiles(); $changedFiles = array(); $chmod_value = $httpVars["chmod_value"]; $recursive = $httpVars["recursive"]; $recur_apply_to = $httpVars["recur_apply_to"]; foreach ($files as $fileName) { $error = $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles); } if (isset($error)) { throw new AJXP_Exception($error); } //$messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] "; $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders"; $reloadContextNode = true; AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($changedFiles))); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": AJXP_Logger::debug("Upload Files Data", $fileVars); $destination = $this->urlBase . SystemTextEncoding::fromPostedFileName($dir); AJXP_Logger::debug("Upload inside", array("destination" => $destination)); if (!$this->isWriteable($destination)) { $errorCode = 412; $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}."; AJXP_Logger::debug("Upload error 412", array("destination" => $destination)); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } foreach ($fileVars as $boxName => $boxData) { if (substr($boxName, 0, 9) != "userfile_") { continue; } $err = AJXP_Utils::parseFileDataErrors($boxData); if ($err != null) { $errorCode = $err[0]; $errorMessage = $err[1]; break; } $userfile_name = $boxData["name"]; $userfile_name = AJXP_Utils::processFileName($userfile_name); if (isset($httpVars["auto_rename"])) { $userfile_name = self::autoRenameForDest($destination, $userfile_name); } if (isset($boxData["input_upload"])) { try { AJXP_Logger::debug("Begining reading INPUT stream"); $input = fopen("php://input", "r"); $output = fopen("{$destination}/" . $userfile_name, "w"); $sizeRead = 0; while ($sizeRead < intval($boxData["size"])) { $chunk = fread($input, 4096); $sizeRead += strlen($chunk); fwrite($output, $chunk, strlen($chunk)); } fclose($input); fclose($output); AJXP_Logger::debug("End reading INPUT stream"); } catch (Exception $e) { $errorCode = 411; $errorMessage = $e->getMessage(); break; } } else { if (!move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name)) { $errorCode = 411; $errorMessage = "{$mess['33']} " . $userfile_name; break; } } $this->changeMode($destination . "/" . $userfile_name); $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; AJXP_Logger::logAction("Upload File", array("file" => SystemTextEncoding::fromUTF8($dir) . "/" . $userfile_name)); } if (isset($errorMessage)) { AJXP_Logger::debug("Return error {$errorCode} {$errorMessage}"); return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage)); } else { AJXP_Logger::debug("Return success"); return array("SUCCESS" => true); } return; break; //------------------------------------ // Public URL //------------------------------------ //------------------------------------ // Public URL //------------------------------------ case "public_url": $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $url = $this->makePubliclet($file, $httpVars["password"], $httpVars["expiration"]); header("Content-type:text/plain"); echo $url; exit(1); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a"); $startTime = microtime(); $dir = AJXP_Utils::securePath(SystemTextEncoding::magicDequote($dir)); $path = $this->urlBase . ($dir != "" ? "/" . $dir : ""); $threshold = $this->repository->getOption("PAGINATION_THRESHOLD"); if (!isset($threshold) || intval($threshold) == 0) { $threshold = 500; } $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER"); if (!isset($limitPerPage) || intval($limitPerPage) == 0) { $limitPerPage = 200; } $countFiles = $this->countFiles($path, !$lsOptions["f"]); if ($countFiles > $threshold) { $offset = 0; $crtPage = 1; if (isset($page)) { $offset = (intval($page) - 1) * $limitPerPage; $crtPage = $page; } $totalPages = floor($countFiles / $limitPerPage) + 1; } else { $offset = $limitPerPage = 0; } $metaData = array(); $crtLabel = AJXP_Utils::xmlEntities(basename($dir), true); if (RecycleBinManager::recycleEnabled()) { if (RecycleBinManager::currentLocationIsRecycle($dir)) { $metaData["ajxp_mime"] = "ajxp_recycle"; $crtLabel = AJXP_Utils::xmlEntities($mess[122]); } else { if ($dir == "") { $metaData["repo_has_recycle"] = "true"; } } } AJXP_XMLWriter::renderHeaderNode(AJXP_Utils::xmlEntities($dir, true), $crtLabel, false, $metaData); if (isset($totalPages) && isset($crtPage)) { AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages); if (!$lsOptions["f"]) { AJXP_XMLWriter::close(); exit(1); } } $cursor = 0; $handle = opendir($path); if (!$handle) { throw new AJXP_Exception("Cannot open dir " . $path); } $fullList = array("d" => array(), "z" => array(), "f" => array()); while (strlen($nodeName = readdir($handle)) > 0) { if ($nodeName == "." || $nodeName == "..") { continue; } $isLeaf = is_file($path . "/" . $nodeName) || AJXP_Utils::isBrowsableArchive($nodeName); if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) { continue; } if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) { continue; } $nodeType = "d"; if ($isLeaf) { if (AJXP_Utils::isBrowsableArchive($nodeName)) { if ($lsOptions["f"] && $lsOptions["z"]) { // See archives as files $nodeType = "f"; } else { $nodeType = "z"; } } else { $nodeType = "f"; } } if ($offset > 0 && $cursor < $offset) { $cursor++; continue; } if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) { break; } $metaData = array(); $currentFile = $path . "/" . $nodeName; $metaData["is_file"] = $isLeaf ? "1" : "0"; $metaData["filename"] = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($dir . "/" . $nodeName)); $metaData["icon"] = AJXP_Utils::mimetype($nodeName, "image", !$isLeaf); if ($metaData["icon"] == "folder.png") { $metaData["openicon"] = "folder_open.png"; } if (!is_file($currentFile) || AJXP_Utils::isBrowsableArchive($nodeName)) { $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?get_action=ls&options=dz&dir=" . $dir . "/" . $nodeName); $link = urlencode($link); $metaData["src"] = $link; } if ($lsOptions["l"]) { $metaData["file_group"] = @filegroup($currentFile) || "unknown"; $metaData["file_owner"] = @fileowner($currentFile) || "unknown"; $fPerms = @fileperms($currentFile); if ($fPerms !== false) { $fPerms = substr(decoct($fPerms), $isLeaf ? 2 : 1); } else { $fPerms = '0000'; } $metaData["file_perms"] = $fPerms; $metaData["mimestring"] = AJXP_Utils::mimetype($currentFile, "type", !$isLeaf); $datemodif = $this->date_modif($currentFile); $metaData["ajxp_modiftime"] = $datemodif ? $datemodif : "0"; $metaData["bytesize"] = 0; if ($isLeaf) { $metaData["bytesize"] = filesize($currentFile); } $metaData["filesize"] = AJXP_Utils::roundSize($metaData["bytesize"]); if (AJXP_Utils::isBrowsableArchive($nodeName)) { $metaData["ajxp_mime"] = "ajxp_browsable_archive"; } $realFile = null; // A reference to the real file. AJXP_Controller::applyHook("ls.metadata", array($currentFile, &$metaData, $this->wrapperClassName, &$realFile)); } $attributes = ""; foreach ($metaData as $key => $value) { $attributes .= "{$key}=\"{$value}\" "; } $renderNodeData = array(AJXP_Utils::xmlEntities($dir . "/" . $nodeName, true), AJXP_Utils::xmlEntities($nodeName, true), $isLeaf, $metaData); $fullList[$nodeType][$nodeName] = $renderNodeData; $cursor++; } foreach ($fullList as $key => $list) { uksort($list, 'strnatcasecmp'); $fullList[$key] = $list; } $allNodes = array_merge($fullList["d"], $fullList["z"], $fullList["f"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["d"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["z"]); array_map(array("AJXP_XMLWriter", "renderNodeArray"), $fullList["f"]); // ADD RECYCLE BIN TO THE LIST if ($dir == "" && RecycleBinManager::recycleEnabled()) { $recycleBinOption = RecycleBinManager::getRelativeRecycle(); if (file_exists($this->urlBase . $recycleBinOption)) { $recycleIcon = $this->countFiles($this->urlBase . $recycleBinOption, false, true) > 0 ? "trashcan_full.png" : "trashcan.png"; AJXP_XMLWriter::renderNode($recycleBinOption, AJXP_Utils::xmlEntities($mess[122]), false, array("ajxp_modiftime" => $this->date_modif($this->urlBase . $recycleBinOption), "mimestring" => AJXP_Utils::xmlEntities($mess[122]), "icon" => "{$recycleIcon}", "filesize" => "-", "ajxp_mime" => "ajxp_recycle")); } } AJXP_Logger::debug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms"); AJXP_XMLWriter::close(); return; break; } $xmlBuffer = ""; if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if ($reloadContextNode) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false); } return $xmlBuffer; }
function printDiagnostic() { $outputArray = array(); $testedParams = array(); $passed = AJXP_Utils::runTests($outputArray, $testedParams); AJXP_Utils::testResultsToFile($outputArray, $testedParams); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="fileList" template_name="ajxp_conf.diagnostic" defaultWidth="20%"><column messageId="ajxp_conf.23" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.24" attributeName="data" sortType="String"/></columns>'); if (is_file(TESTS_RESULT_FILE)) { include_once TESTS_RESULT_FILE; if (isset($diagResults)) { foreach ($diagResults as $id => $value) { $value = AJXP_Utils::xmlEntities($value); print "<tree icon=\"susehelpcenter.png\" is_file=\"1\" filename=\"{$id}\" text=\"{$id}\" data=\"{$value}\" ajxp_mime=\"testResult\"/>"; } } } }
public function listRepositories() { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="user_dash.9" attributeName="parent_label" sortType="String"/><column messageId="user_dash.9" attributeName="repo_accesses" sortType="String"/></columns>'); $repoArray = array(); $loggedUser = AuthService::getLoggedUser(); $count = 0; $repos = ConfService::listRepositoriesWithCriteria(array("owner_user_id" => $loggedUser->getId()), $count); $searchAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf"); $displayAll = ConfService::getCoreConf("CROSSUSERS_ALLGROUPS_DISPLAY", "conf"); if ($searchAll || $displayAll) { $baseGroup = "/"; } else { $baseGroup = AuthService::filterBaseGroup("/"); } AuthService::setGroupFiltering(false); $users = AuthService::listUsers($baseGroup); $minisites = $this->listSharedFiles("minisites"); foreach ($repos as $repoIndex => $repoObject) { if ($repoObject->getAccessType() == "ajxp_conf") { continue; } if (!$repoObject->hasOwner() || $repoObject->getOwner() != $loggedUser->getId()) { continue; } if (is_numeric($repoIndex)) { $repoIndex = "" . $repoIndex; } $name = (isset($minisites[$repoIndex]) ? "[Minisite] " : "") . AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay())); $repoArray[$name] = $repoIndex; } // Sort the list now by name ksort($repoArray); foreach ($repoArray as $name => $repoIndex) { $repoObject =& $repos[$repoIndex]; $repoAccesses = array(); foreach ($users as $userId => $userObject) { if ($userObject->getId() == $loggedUser->getId()) { continue; } $label = $userObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userId); if (empty($label)) { $label = $userId; } $acl = $userObject->mergedRole->getAcl($repoObject->getId()); if (!empty($acl)) { $repoAccesses[] = $label . " (" . $acl . ")"; } } $parent = $repoObject->getParentId(); $parentRepo =& $repos[$parent]; $parentLabel = $this->metaIcon("folder-open") . $parentRepo->getDisplay(); $repoPath = $repoObject->getOption("PATH"); $parentPath = $parentRepo->getOption("PATH"); $parentLabel .= " (" . str_replace($parentPath, "", $repoPath) . ")"; $metaData = array("repository_id" => $repoIndex, "icon" => "document_open_remote.png", "openicon" => "document_open_remote.png", "parentname" => "/repositories", "parent_label" => $parentLabel, "repo_accesses" => count($repoAccesses) ? $this->metaIcon("share-sign") . implode(", ", $repoAccesses) : "", "ajxp_mime" => "shared_repository"); AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData); } }
public function switchAction($action, $httpVars, $fileVars) { $repo = ConfService::getRepository(); if (!isset($this->actions[$action])) { return; } parent::accessPreprocess($action, $httpVars, $fileVars); $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath($getValue); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); if (isset($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); } // FILTER DIR PAGINATION ANCHOR if (isset($dir) && strstr($dir, "%23") !== false) { $parts = explode("%23", $dir); $dir = $parts[0]; $page = $parts[1]; } if (isset($dest)) { $dest = SystemTextEncoding::fromUTF8($dest); } $mess = ConfService::getMessages(); switch ($action) { //------------------------------------ // ONLINE EDIT //------------------------------------ case "edit_record": $isNew = false; if (isset($record_is_new) && $record_is_new == "true") { $isNew = true; } $tableName = $_POST["table_name"]; $pkName = $_POST["pk_name"]; $query = ""; $arrValues = array(); foreach ($_POST as $key => $value) { if (substr($key, 0, strlen("ajxp_mysql_")) == "ajxp_mysql_") { $newKey = substr($key, strlen("ajxp_mysql_")); $arrValues[$newKey] = $value; } } if ($isNew) { $string = ""; $index = 0; foreach ($arrValues as $k => $v) { // CHECK IF AUTO KEY!!! $string .= "'" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'"; if ($index < count($arrValues) - 1) { $string .= ","; } $index++; } $query = "INSERT INTO {$tableName} VALUES ({$string})"; } else { $string = ""; $index = 0; foreach ($arrValues as $k => $v) { if ($k == $pkName) { $pkValue = $v; } else { $string .= $k . "='" . addslashes(SystemTextEncoding::fromUTF8($v)) . "'"; if ($index < count($arrValues) - 1) { $string .= ","; } } $index++; } $query = "UPDATE {$tableName} SET {$string} WHERE {$pkName}='{$pkValue}'"; } $link = $this->createDbLink(); $res = $this->execQuery($query); $this->closeDbLink($link); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } break; //------------------------------------ // CHANGE COLUMNS OR CREATE TABLE //------------------------------------ //------------------------------------ // CHANGE COLUMNS OR CREATE TABLE //------------------------------------ case "edit_table": $link = $this->createDbLink(); if (isset($httpVars["current_table"])) { if (isset($httpVars["delete_column"])) { $query = "ALTER TABLE " . $httpVars["current_table"] . " DROP COLUMN " . $httpVars["delete_column"]; $res = $this->execQuery($query); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; } if (isset($httpVars["add_column"])) { $defString = $this->makeColumnDef($httpVars, "add_field_"); $query = "ALTER TABLE " . $httpVars["current_table"] . " ADD COLUMN ({$defString})"; if (isset($httpVars["add_field_pk"]) && $httpVars["add_field_pk"] == "1") { $query .= ", ADD PRIMARY KEY (" . $httpVars["add_field_name"] . ")"; } if (isset($httpVars["add_field_index"]) && $httpVars["add_field_index"] == "1") { $query .= ", ADD INDEX (" . $httpVars["add_field_name"] . ")"; } if (isset($httpVars["add_field_uniq"]) && $httpVars["add_field_uniq"] == "1") { $query .= ", ADD UNIQUE (" . $httpVars["add_field_name"] . ")"; } $res = $this->execQuery($query); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; } } $fields = array("origname", "name", "default", "null", "size", "type", "flags", "pk", "index", "uniq"); $rows = array(); foreach ($httpVars as $k => $val) { $split = explode("_", $k); if (count($split) == 3 && $split[0] == "field" && is_numeric($split[2]) && in_array($split[1], $fields)) { if (!isset($rows[intval($split[2])])) { $rows[intval($split[2])] = array(); } $rows[intval($split[2])][$split[1]] = $val; } else { if (count($split) == 2 && $split[0] == "field" && in_array($split[1], $fields)) { if (!isset($rows[0])) { $rows[0] = array(); } $rows[0][$split[1]] = $val; } } } if (isset($current_table)) { $qMessage = ''; foreach ($rows as $row) { $sizeString = $row["size"] != "" ? "(" . $row["size"] . ")" : ""; $defString = $row["default"] != "" ? " DEFAULT " . $row["default"] . "" : ""; $query = "ALTER TABLE {$current_table} CHANGE " . $row["origname"] . " " . $row["name"] . " " . $row["type"] . $sizeString . $defString . " " . $row["null"]; $res = $this->execQuery(trim($query)); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; $this->closeDbLink($link); break; } else { $qMessage .= $query; $reload_file_list = true; } } $logMessage = $qMessage; } else { if (isset($new_table)) { $fieldsDef = array(); $pks = array(); $indexes = array(); $uniqs = array(); foreach ($rows as $index => $row) { $fieldsDef[] = $this->makeColumnDef($row); // Analyse keys if ($row["pk"] == "1") { $pks[] = $row["name"]; } if ($row["index"] == "1") { $indexes[] = $row["name"]; } if ($row["uniq"] == "1") { $uniqs[] = $row["name"]; } } $fieldsDef = implode(",", $fieldsDef); if (count($pks)) { $fieldsDef .= ",PRIMARY KEY (" . implode(",", $pks) . ")"; } if (count($indexes)) { $fieldsDef .= ",INDEX (" . implode(",", $indexes) . ")"; } if (count($uniqs)) { $fieldsDef .= ",UNIQUE (" . implode(",", $uniqs) . ")"; } $query = "CREATE TABLE {$new_table} ({$fieldsDef})"; $res = $this->execQuery(trim($query)); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; $reload_current_node = true; } } } $this->closeDbLink($link); break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete_table": case "delete_record": $dir = basename($dir); $link = $this->createDbLink(); if (trim($dir) == "") { // ROOT NODE => DROP TABLES $tables = $selection->getFiles(); $query = "DROP TABLE"; foreach ($tables as $index => $tableName) { $tables[$index] = basename($tableName); } $query .= " " . implode(",", $tables); $res = $this->execQuery($query); $reload_current_node = true; } else { // TABLE NODE => DELETE RECORDS $tableName = $dir; $pks = $selection->getFiles(); foreach ($pks as $key => $pkString) { $parts = explode(".", $pkString); array_pop($parts); // remove .pk extension array_shift($parts); // remove record prefix foreach ($parts as $index => $pkPart) { $parts[$index] = str_replace("__", "='", $pkPart) . "'"; } $pks[$key] = "(" . implode(" AND ", $parts) . ")"; } $query = "DELETE FROM {$tableName} WHERE " . implode(" OR ", $pks); $res = $this->execQuery($query); } //AJXP_Exception::errorToXml($res); if (is_a($res, "AJXP_Exception")) { $errorMessage = $res->messageId; } else { $logMessage = $query; $reload_file_list = true; } $this->closeDbLink($link); break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "set_query": $query = $httpVars["query"]; $_SESSION["LAST_SQL_QUERY"] = $query; print "<tree store=\"true\"></tree>"; break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $searchMode = $fileListMode = $completeMode = false; if (isset($mode)) { if ($mode == "search") { $searchMode = true; } else { if ($mode == "file_list") { $fileListMode = true; } else { if ($mode == "complete") { $completeMode = true; } } } } $link = $this->createDbLink(); //AJXP_Exception::errorToXml($link); if ($dir == "") { AJXP_XMLWriter::header(); $tables = $this->listTables(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist"><column messageString="Table Name" attributeName="ajxp_label" sortType="String"/><column messageString="Byte Size" attributeName="bytesize" sortType="NumberKo"/><column messageString="Count" attributeName="count" sortType="Number"/></columns>'); $icon = $mode == "file_list" ? "sql_images/mimes/ICON_SIZE/table_empty.png" : "sql_images/mimes/ICON_SIZE/table_empty_tree.png"; foreach ($tables as $tableName) { $size = $this->getSize($tableName); $count = $this->getCount($tableName); print "<tree is_file=\"0\" text=\"{$tableName}\" filename=\"/{$tableName}\" bytesize=\"{$size}\" count=\"{$count}\" icon=\"{$icon}\" ajxp_mime=\"table\" />"; } print "<tree is_file=\"0\" text=\"Search Results\" ajxp_node=\"true\" filename=\"/ajxpmysqldriver_searchresults\" bytesize=\"-\" count=\"-\" icon=\"search.png\"/>"; AJXP_XMLWriter::close(); } else { $tableName = basename($dir); if (isset($page)) { $currentPage = $page; } else { $currentPage = 1; } $query = "SELECT * FROM {$tableName}"; $searchQuery = false; if ($tableName == "ajxpmysqldriver_searchresults") { if (isset($_SESSION["LAST_SQL_QUERY"])) { $query = $_SESSION["LAST_SQL_QUERY"]; $matches = array(); if (preg_match("/SELECT [\\S, ]* FROM (\\S*).*/i", $query, $matches) !== false) { $tableName = $matches[1]; $searchQuery = true; } else { break; } } else { break; } } if (isset($order_column)) { $query .= " ORDER BY {$order_column} " . strtoupper($order_direction); if (!isset($_SESSION["AJXP_ORDER_DATA"])) { $_SESSION["AJXP_ORDER_DATA"] = array(); } $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName] = array("column" => $order_column, "dir" => $order_direction); } else { if (isset($_SESSION["AJXP_ORDER_DATA"])) { if (isset($_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName])) { $order_column = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["column"]; $order_direction = $_SESSION["AJXP_ORDER_DATA"][$this->repository->getUniqueId() . "_" . $tableName]["dir"]; $query .= " ORDER BY {$order_column} " . strtoupper($order_direction); } } } try { $result = $this->showRecords($query, $tableName, $currentPage); } catch (AJXP_Exception $ex) { unset($_SESSION["LAST_SQL_QUERY"]); throw $ex; } AJXP_XMLWriter::header(); $blobCols = array(); $columnsString = '<columns switchDisplayMode="list" switchGridMode="grid">'; foreach ($result["COLUMNS"] as $col) { $columnsString .= "<column messageString=\"" . $col["NAME"] . "\" attributeName=\"" . $col["NAME"] . "\" field_name=\"" . $col["NAME"] . "\" field_type=\"" . $col["TYPE"] . "\" field_size=\"" . $col["LENGTH"] . "\" field_flags=\"" . $this->cleanFlagString($col["FLAGS"]) . "\" field_pk=\"" . (preg_match("/primary/", $col["FLAGS"]) ? "1" : "0") . "\" field_null=\"" . (preg_match("/not_null/", $col["FLAGS"]) ? "NOT_NULL" : "NULL") . "\" sortType=\"" . $this->sqlTypeToSortType($col["TYPE"]) . "\" field_default=\"" . $col["DEFAULT"] . "\"/>"; if (stristr($col["TYPE"], "blob") !== false && ($col["FLAGS"] != "" && stristr($col["FLAGS"], "binary"))) { $blobCols[] = $col["NAME"]; } } $columnsString .= '</columns>'; AJXP_XMLWriter::sendFilesListComponentConfig($columnsString); //print '<pagination total="'.$result["TOTAL_PAGES"].'" current="'.$currentPage.'" remote_order="true" currentOrderCol="'.$order_column.'" currentOrderDir="'.$order_direction.'"/>'; if ($result["TOTAL_PAGES"] > 1) { AJXP_XMLWriter::renderPaginationData($count, $currentPage, $result["TOTAL_PAGES"]); } foreach ($result["ROWS"] as $arbitIndex => $row) { print '<tree '; $pkString = ""; foreach ($row as $key => $value) { if (in_array($key, $blobCols)) { $sizeStr = " - NULL"; if (strlen($value)) { $sizeStr = " - " . AJXP_Utils::roundSize(strlen($value)); } print "{$key}=\"BLOB{$sizeStr}\" "; } else { $value = str_replace("\"", "", $value); $value = AJXP_Utils::xmlEntities($value); print $key . '="' . SystemTextEncoding::toUTF8($value) . '" '; if ($result["HAS_PK"] > 0) { if (in_array($key, $result["PK_FIELDS"])) { $pkString .= $key . "__" . $value . "."; } } } } if ($result["HAS_PK"] > 0) { print 'filename="record.' . $pkString . 'pk" '; print 'is_file="1" ajxp_mime="pk"/>'; } else { print 'filename="record_' . $arbitIndex . '.no_pk" '; print 'is_file="1" ajxp_mime="row"/>'; } } AJXP_XMLWriter::close(); } $this->closeDbLink($link); exit(1); break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } if (isset($reload_current_node) && $reload_current_node == "true" || isset($reload_file_list)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", "", false); } return $xmlBuffer; }
function writeRepositoriesData($loggedUser, $details = false) { $st = ""; $st .= "<repositories>"; $streams = ConfService::detectRepositoryStreams(false); foreach (ConfService::getRepositoriesList() as $rootDirIndex => $rootDirObject) { $toLast = false; if ($rootDirObject->getAccessType() == "ajxp_conf") { if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) { continue; } else { $toLast = true; } } if ($loggedUser == null || $loggedUser->canRead($rootDirIndex) || $details) { $rightString = ""; if ($details) { $rightString = " r=\"" . ($loggedUser->canRead($rootDirIndex) ? "1" : "0") . "\" w=\"" . ($loggedUser->canWrite($rootDirIndex) ? "1" : "0") . "\""; } $streamString = ""; if (in_array($rootDirObject->accessType, $streams)) { $streamString = "allowCrossRepositoryCopy=\"true\""; } if ($toLast) { $lastString = "<repo access_type=\"" . $rootDirObject->accessType . "\" id=\"" . $rootDirIndex . "\"{$rightString} {$streamString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($rootDirObject->getDisplay())) . "</label>" . $rootDirObject->getClientSettings() . "</repo>"; } else { $st .= "<repo access_type=\"" . $rootDirObject->accessType . "\" id=\"" . $rootDirIndex . "\"{$rightString} {$streamString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($rootDirObject->getDisplay())) . "</label>" . $rootDirObject->getClientSettings() . "</repo>"; } } } if (isset($lastString)) { $st .= $lastString; } $st .= "</repositories>"; return $st; }
/** * Format a table row into an xml list of nodes for the log reader * * @param String $node Name of the xml node * @param String $icon Icon to use for the list item * @param String $dateattrib * @param String $filename Source of the list, usually a filename * @param String $remote_ip Client IP that was logged * @param String $log_level Log level of the item * @param String $user User who was logged in * @param String $action The action the user performed. * @param String $params Parameters to the action * @param Integer $is_file 0|1 to indicate whether this list item is a file or not. * * @return String Formatted XML node for insertion into the log reader */ public function formatXmlLogItem($node, $icon, $dateattrib, $filename, $remote_ip, $log_level, $user, $source, $action, $params, $rootPath = "/logs") { $remote_ip = $this->inet_dtop($remote_ip); $log_unixtime = strtotime($dateattrib); $log_datetime = date("m-d-y", $log_unixtime) . " " . date("G:i:s", $log_unixtime); $log_year = date('Y', $log_unixtime); $log_month = date('m', $log_unixtime); $log_date = date("m-d-y", $log_unixtime); // Some actions or parameters can contain characters that need to be encoded, especially when a piece of code raises a notification or error. $action = AJXP_Utils::xmlEntities($action); $params = AJXP_Utils::xmlEntities($params); $source = AJXP_Utils::xmlEntities($source); return "<{$node} icon=\"{$icon}\" date=\"{$log_datetime}\" ajxp_modiftime=\"{$log_unixtime}\" is_file=\"true\" filename=\"{$rootPath}/{$log_year}/{$log_month}/{$log_date}/{$log_datetime}\" ajxp_mime=\"log\" ip=\"{$remote_ip}\" level=\"{$log_level}\" user=\"{$user}\" action=\"{$action}\" source=\"{$source}\" params=\"{$params}\"/>"; }
/** * Send repositories access for given role as XML * * @param AjxpRole $role * @return string */ static function writeRoleRepositoriesData($role) { $st = "<repositories>"; foreach (ConfService::getRepositoriesList() as $repoId => $repoObject) { $toLast = false; if ($repoObject->getAccessType() == "ajxp_conf") { continue; } if ($repoObject->getAccessType() == "ajxp_shared" && !AuthService::usersEnabled()) { continue; } $rightString = " r=\"" . ($role->canRead($repoId) ? "1" : "0") . "\" w=\"" . ($role->canWrite($repoId) ? "1" : "0") . "\""; $string = "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$rightString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label></repo>"; if ($toLast) { $lastString = $string; } else { $st .= $string; } } if (isset($lastString)) { $st .= $lastString; } $st .= "</repositories>"; $st .= "<actions_rights>"; foreach ($role->getSpecificActionsRights("ajxp.all") as $actionId => $actionValue) { $st .= "<action name=\"{$actionId}\" value=\"" . ($actionValue ? "true" : "false") . "\"/>"; } $st .= "</actions_rights>"; return $st; }
public function mimeExtractorCallback($masterFile, $targetFile) { $metadata = array(); require_once "Mail/mimeDecode.php"; $params = array('include_bodies' => true, 'decode_bodies' => false, 'decode_headers' => 'UTF-8'); $mess = ConfService::getMessages(); $content = file_get_contents($masterFile); $decoder = new Mail_mimeDecode($content); $structure = $decoder->decode($params); $allowedHeaders = array("to", "from", "subject", "message-id", "mime-version", "date", "return-path"); foreach ($structure->headers as $hKey => $hValue) { if (!in_array($hKey, $allowedHeaders)) { continue; } if (is_array($hValue)) { $hValue = implode(", ", $hValue); } if ($hKey == "date") { $date = strtotime($hValue); $metadata["eml_time"] = $date; } $metadata["eml_" . $hKey] = AJXP_Utils::xmlEntities(@htmlentities($hValue, ENT_COMPAT, "UTF-8")); //$this->logDebug($hKey." - ".$hValue. " - ".$metadata["eml_".$hKey]); if ($metadata["eml_" . $hKey] == "") { $metadata["eml_" . $hKey] = AJXP_Utils::xmlEntities(@htmlentities($hValue)); if (!SystemTextEncoding::isUtf8($metadata["eml_" . $hKey])) { $metadata["eml_" . $hKey] = SystemTextEncoding::toUTF8($metadata["eml_" . $hKey]); } } $metadata["eml_" . $hKey] = str_replace("&", "&", $metadata["eml_" . $hKey]); } $metadata["eml_attachments"] = 0; $parts = $structure->parts; if (!empty($parts)) { foreach ($parts as $mimePart) { if (!empty($mimePart->disposition) && $mimePart->disposition == "attachment") { $metadata["eml_attachments"]++; } } } $metadata["icon"] = "eml_images/ICON_SIZE/mail_mime.png"; file_put_contents($targetFile, serialize($metadata)); }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = AJXP_Utils::securePath(SystemTextEncoding::magicDequote($getValue)); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); if (isset($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); } if (isset($dest)) { $dest = SystemTextEncoding::fromUTF8($dest); } $mess = ConfService::getMessages(); $recycleBinOption = $this->repository->getOption("RECYCLE_BIN"); // FILTER ACTION FOR DELETE if ($recycleBinOption != "" && $action == "delete" && $dir != "/" . $recycleBinOption) { $action = "move"; $dest = "/" . $recycleBinOption; $dest_node = "AJAXPLORER_RECYCLE_NODE"; } // FILTER ACTION FOR RESTORE if ($recycleBinOption != "" && $action == "restore" && $dir == "/" . $recycleBinOption) { $originalRep = RecycleBinManager::getFileOrigin($selection->getUniqueFile()); if ($originalRep != "") { $action = "move"; $dest = $originalRep; } } switch ($action) { //------------------------------------ // DOWNLOAD, IMAGE & MP3 PROXYS //------------------------------------ case "download": AJXP_Logger::logAction("Download", array("files" => $selection)); $zip = false; if ($selection->isUnique()) { if (is_dir($this->getPath() . "/" . $selection->getUniqueFile())) { $zip = true; $dir .= "/" . basename($selection->getUniqueFile()); } } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $this->downFile($this->makeName($selection->getFiles()), "force-download", "archive.zip"); } else { $this->downFile($this->makeName($selection->getUniqueFile()), "force-download", $selection->getUniqueFile()); } exit(0); break; case "image_proxy": $this->downFile($this->makeName($file), "image", $file); exit(0); break; case "mp3_proxy": $this->downFile($this->makeName($file), "mp3", $file); exit(0); break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "put_content": AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file))); $code = stripslashes($code); $code = str_replace("<", "<", $content); $this->SSHOperation->setRemoteContent($this->makeName($file), $code); echo $mess[115]; exit(0); break; case "get_content": $this->sendFile($this->SSHOperation->getRemoteContent($this->makeName($file)), "plain", $file); exit(0); break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } $result = ""; if ($action == "move") { $result = $this->SSHOperation->moveFile($this->makeName($selection->getFiles()), $this->makeName($dest)); } else { $result = $this->SSHOperation->copyFile($this->makeName($selection->getFiles()), $this->makeName($dest)); } $mess = ConfService::getMessages(); if (strlen($result)) { $errorMessage = $mess[114]; } else { foreach ($selection->getFiles() as $files) { $logMessage .= $mess[34] . " " . SystemTextEncoding::toUTF8(basename($file)) . " " . $mess[$action == "move" ? 74 : 73] . " " . SystemTextEncoding::toUTF8($dest) . "\n"; } AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest)); } $reloadContextNode = true; $reloadDataNode = SystemTextEncoding::fromUTF8($dest); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $messtmp = ""; $changedFiles = array(); $value = "0" . decoct(octdec(ltrim($chmod_value, "0"))); // On error, the command will fail $result = $this->SSHOperation->chmodFile($this->makeName($selection->getFiles()), $chmod_value); $mess = ConfService::getMessages(); if (strlen($result)) { $errorMessage = $mess[114]; } else { $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($selection->getFiles()) . " files or folders"; AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($selection->getFiles()))); $reloadContextNode = true; } break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } $logMessages = array(); $result = $this->SSHOperation->deleteFile($this->makeName($selection->getFiles())); if (strlen($result)) { $mess = ConfService::getMessages(); $errorMessage = $mess[120]; } else { $mess = ConfService::getMessages(); foreach ($selection->getFiles() as $file) { $logMessages[] = "{$mess['34']} " . SystemTextEncoding::toUTF8($file) . " {$mess['44']}."; } $logMessage = join("\n", $logMessages); } AJXP_Logger::logAction("Delete", array("files" => $selection)); $reloadContextNode = true; break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "rename": $filename_new = $dir . "/" . $filename_new; $error = $this->SSHOperation->moveFile($this->makeName($file), $this->makeName($filename_new)); if ($error != null) { $errorMessage = $error; break; } $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); $reloadContextNode = true; $pendingSelection = SystemTextEncoding::fromUTF8($filename_new); AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; $dirname = AJXP_Utils::processFileName($dirname); $error = $this->SSHOperation->createRemoteDirectory($this->makeName($dir . "/" . $dirname)); if (isset($error)) { $errorMessage = $error; break; } $pendingSelection = $dir . "/" . $dirname; $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reloadContextNode = true; AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; $filename = AJXP_Utils::processFileName($filename); $error = $this->SSHOperation->setRemoteContent($this->makeName($dir . "/" . $filename), ""); if (isset($error)) { $errorMessage = $error; break; } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $pendingSelection = $filename; $reloadContextNode = true; AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename)); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": $fancyLoader = false; if (isset($fileVars["Filedata"])) { $fancyLoader = true; if ($dir != "") { $dir = "/" . base64_decode($dir); } } if ($dir != "") { $rep_source = "/{$dir}"; } else { $rep_source = ""; } $destination = $rep_source; $logMessage = ""; //$fancyLoader = false; foreach ($fileVars as $boxName => $boxData) { if ($boxName != "Filedata" && substr($boxName, 0, 9) != "userfile_") { continue; } if ($boxName == "Filedata") { $fancyLoader = true; } $err = AJXP_Utils::parseFileDataErrors($boxData, $fancyLoader); if ($err != null) { $errorMessage = $err; break; } $userfile_name = $boxData["name"]; $userfile_name = AJXP_Utils::processFileName($userfile_name); if (!$this->SSHOperation->uploadFile($boxData["tmp_name"], $this->makeName($destination . "/" . $userfile_name))) { $errorMessage = ($fancyLoader ? "411 " : "") . "{$mess['33']} " . $userfile_name; break; } $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; AJXP_Logger::logAction("Upload File", array("file" => $dir . "/" . $userfile_name)); } if ($fancyLoader) { if (isset($errorMessage)) { header('HTTP/1.0 ' . $errorMessage); die('Error ' . $errorMessage); } else { header('HTTP/1.0 200 OK'); die("200 OK"); } } else { print "<html><script language=\"javascript\">\n"; if (isset($errorMessage)) { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');"; } else { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext();"; } print "</script></html>"; } exit; break; //------------------------------------ // Public URL //------------------------------------ //------------------------------------ // Public URL //------------------------------------ case "public_url": $file = SystemTextEncoding::fromUTF8($file); $url = $this->makePubliclet($file, $password, $expiration); header("Content-type:text/plain"); echo $url; exit(1); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": // BACKWARD COMPATIBILTY if (isset($httpVars["options"])) { if ($httpVars["options"] == "al") { $mode = "file_list"; } else { if ($httpVars["options"] == "a") { $mode = "search"; } else { if ($httpVars["options"] == "d") { $skipZip = "true"; } } } // skip "complete" mode that was in fact quite the same as standard tree listing (dz) } if (!isset($dir) || $dir == "/") { $dir = ""; } $searchMode = $fileListMode = $completeMode = false; if (isset($mode)) { if ($mode == "search") { $searchMode = true; } else { if ($mode == "file_list") { $fileListMode = true; } else { if ($mode == "complete") { $completeMode = true; } } } } $nom_rep = $dir; //AJXP_Exception::errorToXml($nom_rep); $result = $this->SSHOperation->listFilesIn($nom_rep); $metaData = array(); if (RecycleBinManager::recycleEnabled() && RecycleBinManager::currentLocationIsRecycle($dir)) { $metaData["ajxp_mime"] = "ajxp_recycle"; } AJXP_XMLWriter::renderHeaderNode(AJXP_Utils::xmlEntities($dir, true), AJXP_Utils::xmlEntities(basename($dir), true), false, $metaData); foreach ($result as $file) { $attributes = ""; $fileName = SystemTextEncoding::toUTF8($file["name"]); $icon = AJXP_Utils::mimetype($fileName, "image", $file["isDir"] == 1); if ($searchMode) { if ($file["isDir"] == 0) { $attributes = "is_file=\"true\" icon=\"" . SystemTextEncoding::toUTF8($icon) . "\""; } } else { if ($fileListMode) { $atts = array(); $atts[] = "is_file=\"" . (1 - $file["isDir"]) . "\""; $atts[] = "is_image=\"" . AJXP_Utils::is_image($fileName) . "\""; $atts[] = "mimestring=\"" . AJXP_Utils::mimetype($fileName, "type", $file["isDir"] == 1) . "\""; $atts[] = "ajxp_modiftime=\"" . $this->dateModif($file["time"]) . "\""; $atts[] = "filesize=\"" . AJXP_Utils::roundSize($file["size"]) . "\""; $atts[] = "bytesize=\"" . $file["size"] . "\""; $atts[] = "filename=\"" . str_replace("&", "&", $dir . "/" . $fileName) . "\""; $atts[] = "icon=\"" . ($file["isDir"] == 1 ? "folder.png" : SystemTextEncoding::toUTF8($icon)) . "\""; $attributes = join(" ", $atts); } else { if ($file["isDir"] == 1) { $link = SERVER_ACCESS . "?dir=" . $dir . "/" . $fileName; $link = urlencode($link); $folderBaseName = str_replace("&", "&", $fileName); $folderFullName = "{$dir}/" . $folderBaseName; $parentFolderName = $dir; if (!$completeMode) { $icon = "folder.png"; $openicon = "folder_open.png"; if (preg_match("/\\.zip\$/", $file["name"])) { $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/actions/16/accessories-archiver.png"; } $attributes = "icon=\"{$icon}\" openicon=\"{$openicon}\" filename=\"" . $folderFullName . "\" src=\"{$link}\""; } } } } if (strlen($attributes) > 0) { print "<tree text=\"" . str_replace("&", "&", SystemTextEncoding::toUTF8($this->SSHOperation->unescapeFileName($file["name"]))) . "\" {$attributes}>"; print "</tree>"; } } AJXP_XMLWriter::close(); exit(1); break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } if (isset($reloadContextNode)) { if (!isset($pendingSelection)) { $pendingSelection = ""; } $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false); } if (isset($reloadDataNode)) { $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false); } if (isset($reload_current_node) && $reload_current_node == "true") { $xmlBuffer .= AJXP_XMLWriter::reloadCurrentNode(false); } if (isset($reload_dest_node) && $reload_dest_node != "") { $xmlBuffer .= AJXP_XMLWriter::reloadNode($reload_dest_node, false); } if (isset($reload_file_list)) { $xmlBuffer .= AJXP_XMLWriter::reloadFileList($reload_file_list, false); } return $xmlBuffer; }
public function wsAuthenticate($action, $httpVars, $fileVars) { $this->logDebug("Entering wsAuthenticate"); $configs = $this->getConfigs(); if (!isset($httpVars["key"]) || $httpVars["key"] != $configs["WS_SERVER_ADMIN"]) { throw new Exception("Cannot authentify admin key"); } $user = AuthService::getLoggedUser(); if ($user == null) { $this->logDebug("Error Authenticating through WebSocket (not logged)"); throw new Exception("You must be logged in"); } $xml = AJXP_XMLWriter::getUserXML($user); // add groupPath if ($user->getGroupPath() != null) { $groupString = "groupPath=\"" . AJXP_Utils::xmlEntities($user->getGroupPath()) . "\""; $xml = str_replace("<user id=", "<user {$groupString} id=", $xml); } $this->logDebug("Authenticating user " . $user->id . " through WebSocket"); AJXP_XMLWriter::header(); echo $xml; AJXP_XMLWriter::close(); }
function listRepositories() { $repos = ConfService::getRepositoriesList(); AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/><column messageId="ajxp_shared.9" attributeName="repo_accesses" sortType="String"/></columns>'); $repoArray = array(); $childRepos = array(); $loggedUser = AuthService::getLoggedUser(); $users = AuthService::listUsers(); foreach ($repos as $repoIndex => $repoObject) { if ($repoObject->getAccessType() == "ajxp_conf") { continue; } if (!$repoObject->hasOwner() || $repoObject->getOwner() != $loggedUser->getId()) { continue; } if (is_numeric($repoIndex)) { $repoIndex = "" . $repoIndex; } $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay())); $repoArray[$name] = $repoIndex; } // Sort the list now by name ksort($repoArray); // Append child repositories $sortedArray = array(); foreach ($repoArray as $name => $repoIndex) { $sortedArray[$name] = $repoIndex; if (isset($childRepos[$repoIndex]) && is_array($childRepos[$repoIndex])) { foreach ($childRepos[$repoIndex] as $childData) { $sortedArray[$childData["name"]] = $childData["index"]; } } } foreach ($sortedArray as $name => $repoIndex) { $repoObject =& $repos[$repoIndex]; $repoAccesses = array(); foreach ($users as $userId => $userObject) { if (!$userObject->hasParent()) { continue; } if ($userObject->canWrite($repoIndex)) { $repoAccesses[] = $userId . " (rw)"; } else { if ($userObject->canRead($repoIndex)) { $repoAccesses[] = $userId . " (r)"; } } } $metaData = array("repository_id" => $repoIndex, "accessType" => $repoObject->getAccessType(), "icon" => "document_open_remote.png", "openicon" => "document_open_remote.png", "parentname" => "/repositories", "repo_accesses" => implode(", ", $repoAccesses), "ajxp_mime" => "shared_repository"); AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData); } }
public function printDiagnostic($dir, $root = NULL, $hash = null, $returnNodes = false) { $outputArray = array(); $testedParams = array(); $allNodes = array(); AJXP_Utils::runTests($outputArray, $testedParams); AJXP_Utils::testResultsToFile($outputArray, $testedParams); if (!$returnNodes) { AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="fileList" template_name="ajxp_conf.diagnostic" defaultWidth="20%"><column messageId="ajxp_conf.23" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.24" attributeName="data" sortType="String"/></columns>'); } if (is_file(TESTS_RESULT_FILE)) { include_once TESTS_RESULT_FILE; if (isset($diagResults)) { foreach ($diagResults as $id => $value) { $value = AJXP_Utils::xmlEntities($value); $xml = "<tree icon=\"susehelpcenter.png\" is_file=\"1\" filename=\"/{$dir}/{$id}\" text=\"{$id}\" data=\"{$value}\" ajxp_mime=\"testResult\"/>"; if (!$returnNodes) { print $xml; } else { $allNodes["/{$dir}/{$id}"] = $xml; } } } } return $allNodes; }
/** * @param string $repoId * @param Repository $repoObject * @param array $exposed * @param array $streams * @param AbstractAjxpUser $loggedUser * @param string $accessStatus * @return string * @throws Exception */ public static function repositoryToXML($repoId, $repoObject, $exposed, $streams, $loggedUser, $accessStatus = "") { $statusString = " repository_type=\"" . $repoObject->getRepositoryType() . "\""; if (empty($accessStatus)) { $accessStatus = $repoObject->getAccessStatus(); } if (!empty($accessStatus)) { $statusString .= " access_status=\"{$accessStatus}\" "; } else { if ($loggedUser != null) { $lastConnected = $loggedUser->getArrayPref("repository_last_connected", $repoId); if (!empty($lastConnected)) { $statusString .= " last_connection=\"{$lastConnected}\" "; } } } $streamString = ""; if (in_array($repoObject->accessType, $streams)) { $streamString = "allowCrossRepositoryCopy=\"true\""; } if ($repoObject->getUniqueUser()) { $streamString .= " user_editable_repository=\"true\" "; } if ($repoObject->hasContentFilter()) { $streamString .= " hasContentFilter=\"true\""; } $slugString = ""; $slug = $repoObject->getSlug(); if (!empty($slug)) { $slugString = "repositorySlug=\"{$slug}\""; } $isSharedString = ""; $currentUserIsOwner = false; $ownerLabel = null; if ($repoObject->hasOwner()) { $uId = $repoObject->getOwner(); if (AuthService::usersEnabled() && AuthService::getLoggedUser()->getId() == $uId) { $currentUserIsOwner = true; } $label = ConfService::getUserPersonalParameter("USER_DISPLAY_NAME", $uId, "core.conf", $uId); $ownerLabel = $label; $isSharedString = 'owner="' . AJXP_Utils::xmlEntities($label) . '"'; } if ($repoObject->securityScope() == "USER" || $currentUserIsOwner) { $streamString .= " userScope=\"true\""; } $descTag = ""; $public = false; if (!empty($_SESSION["CURRENT_MINISITE"])) { $public = true; } $description = $repoObject->getDescription($public, $ownerLabel); if (!empty($description)) { $descTag = '<description>' . AJXP_Utils::xmlEntities($description, true) . '</description>'; } $roleString = ""; if ($loggedUser != null) { $merged = $loggedUser->mergedRole; $params = array(); foreach ($exposed as $exposed_prop) { $metaOptions = $repoObject->getOption("META_SOURCES"); if (!isset($metaOptions[$exposed_prop["PLUGIN_ID"]])) { continue; } $value = $exposed_prop["DEFAULT"]; if (isset($metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]])) { $value = $metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]]; } $value = $merged->filterParameterValue($exposed_prop["PLUGIN_ID"], $exposed_prop["NAME"], $repoId, $value); if ($value !== null) { if ($value === true || $value === false) { $value = $value === true ? "true" : "false"; } $params[] = '<repository_plugin_param plugin_id="' . $exposed_prop["PLUGIN_ID"] . '" name="' . $exposed_prop["NAME"] . '" value="' . AJXP_Utils::xmlEntities($value) . '"/>'; $roleString .= str_replace(".", "_", $exposed_prop["PLUGIN_ID"]) . "_" . $exposed_prop["NAME"] . '="' . AJXP_Utils::xmlEntities($value) . '" '; } } $roleString .= 'acl="' . $merged->getAcl($repoId) . '"'; if ($merged->hasMask($repoId)) { $roleString .= ' hasMask="true" '; } } return "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$statusString} {$streamString} {$slugString} {$isSharedString} {$roleString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label>" . $descTag . $repoObject->getClientSettings() . "</repo>"; }
/** * Write the repositories access rights in XML format * @static * @param AbstractAjxpUser|null $loggedUser * @param bool $details * @return string */ public static function writeRepositoriesData($loggedUser, $details = false) { $st = "<repositories>"; $streams = ConfService::detectRepositoryStreams(false); foreach (ConfService::getAccessibleRepositories($loggedUser, $details, false) as $repoId => $repoObject) { $toLast = false; if ($repoObject->getAccessType() == "ajxp_conf") { if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) { continue; } $toLast = true; } $rightString = ""; if ($details) { $rightString = " r=\"" . ($loggedUser->canRead($repoId) ? "1" : "0") . "\" w=\"" . ($loggedUser->canWrite($repoId) ? "1" : "0") . "\""; } $streamString = ""; if (in_array($repoObject->accessType, $streams)) { $streamString = "allowCrossRepositoryCopy=\"true\""; } if ($repoObject->getUniqueUser()) { $streamString .= " user_editable_repository=\"true\" "; } $slugString = ""; $slug = $repoObject->getSlug(); if (!empty($slug)) { $slugString = "repositorySlug=\"{$slug}\""; } $isSharedString = ""; if ($repoObject->hasOwner()) { $uId = $repoObject->getOwner(); $uObject = ConfService::getConfStorageImpl()->createUserObject($uId); $label = $uObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $uId); if (empty($label)) { $label = $uId; } $isSharedString = 'owner="' . AJXP_Utils::xmlEntities($label) . '"'; } $descTag = ""; $description = $repoObject->getDescription(); if (!empty($description)) { $descTag = '<description>' . AJXP_Utils::xmlEntities($description, true) . '</description>'; } $xmlString = "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$rightString} {$streamString} {$slugString} {$isSharedString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label>" . $descTag . $repoObject->getClientSettings() . "</repo>"; if ($toLast) { $lastString = $xmlString; } else { $st .= $xmlString; } } if (isset($lastString)) { $st .= $lastString; } $st .= "</repositories>"; return $st; }