public function toggleDisclaimer($actionName, $httpVars, $fileVars)
 {
     $u = AuthService::getLoggedUser();
     $u->personalRole->setParameterValue("action.disclaimer", "DISCLAIMER_ACCEPTED", $httpVars["validate"] == "true" ? "yes" : "no", AJXP_REPO_SCOPE_ALL);
     if ($httpVars["validate"] == "true") {
         $u->removeLock();
         $u->save("superuser");
         AuthService::updateUser($u);
         ConfService::switchUserToActiveRepository($u);
         $force = $u->mergedRole->filterParameterValue("core.conf", "DEFAULT_START_REPOSITORY", AJXP_REPO_SCOPE_ALL, -1);
         $passId = -1;
         if ($force != "" && $u->canSwitchTo($force) && !isset($httpVars["tmp_repository_id"]) && !isset($_SESSION["PENDING_REPOSITORY_ID"])) {
             $passId = $force;
         }
         $res = ConfService::switchUserToActiveRepository($u, $passId);
         if (!$res) {
             AuthService::disconnect();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::requireAuth(true);
             AJXP_XMLWriter::close();
         }
         ConfService::getInstance()->invalidateLoadedRepositories();
     } else {
         $u->setLock("validate_disclaimer");
         $u->save("superuser");
         AuthService::disconnect();
         AJXP_XMLWriter::header();
         AJXP_XMLWriter::requireAuth(true);
         AJXP_XMLWriter::close();
     }
 }
예제 #2
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = 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();
     $newArgs = RecycleBinManager::filterActions($action, $selection, $dir);
     foreach ($newArgs as $argName => $argValue) {
         ${$argName} = $argValue;
     }
     // FILTER DIR PAGINATION ANCHOR
     if (isset($dir) && strstr($dir, "#") !== false) {
         $parts = explode("#", $dir);
         $dir = $parts[0];
         $page = $parts[1];
     }
     switch ($action) {
         //------------------------------------
         //	DOWNLOAD, IMAGE & MP3 PROXYS
         //------------------------------------
         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");
             if ($selection->inZip) {
                 $tmpDir = dirname($selection->getZipPath()) . "/.tmpExtractDownload";
                 $delDir = $this->getPath() . "/" . $tmpDir;
                 @mkdir($delDir);
                 register_shutdown_function(array($this, "deldir"), $delDir);
                 $this->convertSelectionToTmpFiles($tmpDir, $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
                 $loggedUser = AuthService::getLoggedUser();
                 $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpDownload.zip";
                 $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
                 if (!$zipFile) {
                     AJXP_Exception::errorToXml("Error while compressing");
                 }
                 register_shutdown_function("unlink", $file);
                 $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip";
                 $this->readFile($file, "force-download", $localName, false, false);
             } else {
                 $this->readFile($this->getPath() . "/" . $selection->getUniqueFile(), "force-download");
             }
             exit(0);
             break;
         case "compress":
             // Make a temp zip and send it as download
             if (isset($archive_name)) {
                 $localName = SystemTextEncoding::fromUTF8($archive_name);
             } else {
                 $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip";
             }
             $file = $this->getPath() . "/" . $dir . "/" . $localName;
             $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
             if (!$zipFile) {
                 AJXP_Exception::errorToXml("Error while compressing file {$localName}");
             }
             $reload_current_node = true;
             $reload_file_list = $localName;
             break;
         case "image_proxy":
             if ($split = UserSelection::detectZip(SystemTextEncoding::fromUTF8($file))) {
                 require_once "server/classes/pclzip.lib.php";
                 $zip = new PclZip($this->getPath() . $split[0]);
                 $data = $zip->extract(PCLZIP_OPT_BY_NAME, substr($split[1], 1), PCLZIP_OPT_EXTRACT_AS_STRING);
                 header("Content-Type: " . Utils::getImageMimeType(basename($split[1])) . "; name=\"" . basename($split[1]) . "\"");
                 header("Content-Length: " . strlen($data[0]["content"]));
                 header('Cache-Control: public');
                 print $data[0]["content"];
             } else {
                 if (isset($get_thumb) && $get_thumb == "true" && $this->driverConf["GENERATE_THUMBNAIL"]) {
                     require_once "server/classes/PThumb.lib.php";
                     $pThumb = new PThumb($this->driverConf["THUMBNAIL_QUALITY"]);
                     if (!$pThumb->isError()) {
                         $pThumb->use_cache = $this->driverConf["USE_THUMBNAIL_CACHE"];
                         $pThumb->cache_dir = $this->driverConf["THUMBNAIL_CACHE_DIR"];
                         $pThumb->fit_thumbnail($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), 200);
                         if ($pThumb->isError()) {
                             print_r($pThumb->error_array);
                         }
                         exit(0);
                     }
                 }
                 $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "image");
             }
             exit(0);
             break;
         case "mp3_proxy":
             if ($split = UserSelection::detectZip(SystemTextEncoding::fromUTF8($file))) {
                 require_once "server/classes/pclzip.lib.php";
                 $zip = new PclZip($this->getPath() . $split[0]);
                 $data = $zip->extract(PCLZIP_OPT_BY_NAME, substr($split[1], 1), PCLZIP_OPT_EXTRACT_AS_STRING);
                 header("Content-Type: audio/mp3; name=\"" . basename($split[1]) . "\"");
                 header("Content-Length: " . strlen($data[0]["content"]));
                 print $data[0]["content"];
             } else {
                 $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "mp3");
             }
             exit(0);
             break;
             //------------------------------------
             //	ONLINE EDIT
             //------------------------------------
         //------------------------------------
         //	ONLINE EDIT
         //------------------------------------
         case "edit":
             if (isset($save) && $save == 1 && isset($code)) {
                 // Reload "code" variable directly from POST array, do not "securePath"...
                 $code = $_POST["code"];
                 AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file)));
                 $code = stripslashes($code);
                 $code = str_replace("&lt;", "<", $code);
                 $fileName = $this->getPath() . SystemTextEncoding::fromUTF8("/{$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];
             } else {
                 $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "plain");
             }
             exit(0);
             break;
             //------------------------------------
             //	COPY / MOVE
             //------------------------------------
         //------------------------------------
         //	COPY / MOVE
         //------------------------------------
         case "copy":
         case "move":
             if ($selection->isEmpty()) {
                 $errorMessage = $mess[113];
                 break;
             }
             if ($selection->inZip()) {
                 $tmpDir = dirname($selection->getZipPath()) . "/.tmpExtractDownload";
                 @mkdir($this->getPath() . "/" . $tmpDir);
                 $this->convertSelectionToTmpFiles($tmpDir, $selection);
                 if (is_dir($tmpDir)) {
                     $this->deldir($this->getPath() . "/" . $tmpDir);
                 }
             }
             $success = $error = array();
             $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false);
             if (count($error)) {
                 $errorMessage = join("\n", $error);
             } else {
                 $logMessage = join("\n", $success);
                 AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest));
             }
             $reload_current_node = true;
             if (isset($dest_node)) {
                 $reload_dest_node = $dest_node;
             }
             $reload_file_list = true;
             break;
             //------------------------------------
             //	SUPPRIMER / DELETE
             //------------------------------------
         //------------------------------------
         //	SUPPRIMER / DELETE
         //------------------------------------
         case "delete":
             if ($selection->isEmpty()) {
                 $errorMessage = $mess[113];
                 break;
             }
             $logMessages = array();
             $errorMessage = $this->delete($selection->getFiles(), $logMessages);
             if (count($logMessages)) {
                 $logMessage = join("\n", $logMessages);
             }
             AJXP_Logger::logAction("Delete", array("files" => $selection));
             $reload_current_node = true;
             $reload_file_list = true;
             break;
             //------------------------------------
             //	RENOMMER / RENAME
             //------------------------------------
         //------------------------------------
         //	RENOMMER / RENAME
         //------------------------------------
         case "rename":
             $file = SystemTextEncoding::fromUTF8($file);
             $filename_new = SystemTextEncoding::fromUTF8($filename_new);
             $error = $this->rename($file, $filename_new);
             if ($error != null) {
                 $errorMessage = $error;
                 break;
             }
             $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new);
             $reload_current_node = true;
             $reload_file_list = basename($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 = Utils::processFileName(SystemTextEncoding::fromUTF8($dirname));
             $error = $this->mkDir($dir, $dirname);
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             $reload_file_list = $dirname;
             $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             $reload_current_node = 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 = Utils::processFileName(SystemTextEncoding::fromUTF8($filename));
             $error = $this->createEmptyFile($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;
             $reload_file_list = $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();
             foreach ($files as $fileName) {
                 $error = $this->chmod($this->getPath() . $fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles);
             }
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             //$messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] ";
             $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders";
             $reload_file_list = $dir;
             AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($changedFiles)));
             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 = SystemTextEncoding::fromUTF8($this->getPath() . $rep_source);
             if (!$this->isWriteable($destination)) {
                 global $_GET;
                 $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}.";
                 if ($fancyLoader || isset($_GET["ajxp_sessid"])) {
                     header('HTTP/1.0 412 ' . $errorMessage);
                     die('Error 412 ' . $errorMessage);
                 } else {
                     print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');";
                     break;
                 }
             }
             $logMessage = "";
             foreach ($fileVars as $boxName => $boxData) {
                 if ($boxName != "Filedata" && substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 if ($boxName == "Filedata") {
                     $fancyLoader = true;
                 }
                 $err = Utils::parseFileDataErrors($boxData, $fancyLoader);
                 if ($err != null) {
                     $errorMessage = $err;
                     break;
                 }
                 $userfile_name = $boxData["name"];
                 if ($fancyLoader) {
                     $userfile_name = SystemTextEncoding::fromUTF8($userfile_name);
                 }
                 $userfile_name = Utils::processFileName($userfile_name);
                 if (isset($auto_rename)) {
                     $userfile_name = fsDriver::autoRenameForDest($destination, $userfile_name);
                 }
                 if (!move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name)) {
                     $errorMessage = ($fancyLoader ? "411 " : "") . "{$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 ($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":
             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;
                         }
                     }
                 }
             }
             if (isset($skipZip) && $skipZip == "true") {
                 $skipZip = true;
             } else {
                 $skipZip = false;
             }
             if ($test = UserSelection::detectZip($dir)) {
                 $liste = array();
                 $zip = $this->zipListing($test[0], $test[1], $liste);
                 AJXP_XMLWriter::header();
                 $tmpDir = $this->getPath() . dirname($test[0]) . ".tmpZipExtract";
                 foreach ($liste as $zipEntry) {
                     $atts = array();
                     if (!$fileListMode && !$zipEntry["folder"]) {
                         continue;
                     }
                     $atts[] = "is_file=\"" . ($zipEntry["folder"] ? "false" : "true") . "\"";
                     $atts[] = "text=\"" . Utils::xmlEntities(basename(SystemTextEncoding::toUTF8($zipEntry["stored_filename"]))) . "\"";
                     $atts[] = "filename=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\"";
                     if ($fileListMode) {
                         $atts[] = "filesize=\"" . Utils::roundSize($zipEntry["size"]) . "\"";
                         $atts[] = "bytesize=\"" . $zipEntry["size"] . "\"";
                         $atts[] = "ajxp_modiftime=\"" . $zipEntry["mtime"] . "\"";
                         $atts[] = "mimestring=\"" . Utils::mimetype($zipEntry["stored_filename"], "mime", $zipEntry["folder"]) . "\"";
                         $atts[] = "icon=\"" . Utils::mimetype($zipEntry["stored_filename"], "image", $zipEntry["folder"]) . "\"";
                         $is_image = Utils::is_image(basename($zipEntry["stored_filename"]));
                         $atts[] = "is_image=\"" . $is_image . "\"";
                         if ($is_image) {
                             if (!is_dir($tmpDir)) {
                                 mkdir($tmpDir);
                             }
                             $currentFile = $tmpDir . "/" . basename($zipEntry["stored_filename"]);
                             $data = $zip->extract(PCLZIP_OPT_BY_NAME, $zipEntry["stored_filename"], PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_PATH, $tmpDir);
                             list($width, $height, $type, $attr) = @getimagesize($currentFile);
                             $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\"";
                             $atts[] = "image_width=\"{$width}\"";
                             $atts[] = "image_height=\"{$height}\"";
                             unlink($currentFile);
                         }
                     } else {
                         $atts[] = "icon=\"client/images/foldericon.png\"";
                         $atts[] = "openicon=\"client/images/foldericon.png\"";
                         $atts[] = "src=\"content.php?dir=" . urlencode(SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\"";
                     }
                     print "<tree " . join(" ", $atts) . "/>";
                 }
                 if (is_dir($tmpDir)) {
                     rmdir($tmpDir);
                 }
                 AJXP_XMLWriter::close();
                 exit(0);
             }
             $nom_rep = $this->initName($dir);
             AJXP_Exception::errorToXml($nom_rep);
             $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;
             }
             if ($fileListMode) {
                 $countFiles = $this->countFiles($nom_rep);
                 if ($countFiles > $threshold) {
                     $offset = 0;
                     $crtPage = 1;
                     if (isset($page)) {
                         $offset = (intval($page) - 1) * $limitPerPage;
                         $crtPage = $page;
                     }
                     $totalPages = floor($countFiles / $limitPerPage) + 1;
                     $reps = $this->listing($nom_rep, false, $offset, $limitPerPage);
                 } else {
                     $reps = $this->listing($nom_rep, $searchMode);
                 }
             } else {
                 $countFolders = $this->countFiles($nom_rep, true);
                 if ($countFolders > $threshold) {
                     AJXP_XMLWriter::header();
                     $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png";
                     $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png";
                     $attributes = "icon=\"{$icon}\"  openicon=\"{$openicon}\"";
                     print "<tree text=\"{$mess['306']} ({$countFolders})...\" {$attributes}></tree>";
                     AJXP_XMLWriter::close();
                     exit(1);
                 }
                 $reps = $this->listing($nom_rep, !$searchMode);
             }
             //$reps = $result[0];
             AJXP_XMLWriter::header();
             if (isset($totalPages) && isset($crtPage)) {
                 //print '<columns switchDisplayMode="list" switchGridMode="filelist"/>';
                 print '<pagination count="' . $countFiles . '" total="' . $totalPages . '" current="' . $crtPage . '"/>';
             }
             foreach ($reps as $repIndex => $repName) {
                 if (preg_match("/\\.zip\$/", $repName) && $skipZip) {
                     continue;
                 }
                 $attributes = "";
                 if ($searchMode) {
                     if (is_file($nom_rep . "/" . $repIndex)) {
                         $attributes = "is_file=\"true\" icon=\"{$repName}\"";
                         $repName = $repIndex;
                     }
                 } else {
                     if ($fileListMode) {
                         $currentFile = $nom_rep . "/" . $repIndex;
                         $atts = array();
                         $atts[] = "is_file=\"" . (is_file($currentFile) ? "1" : "0") . "\"";
                         $atts[] = "is_image=\"" . Utils::is_image($currentFile) . "\"";
                         $fGroup = @filegroup($currentFile) || "unknown";
                         $atts[] = "file_group=\"" . $fGroup . "\"";
                         $fOwner = @fileowner($currentFile) || "unknown";
                         $atts[] = "file_owner=\"" . $fOwner . "\"";
                         $fPerms = @fileperms($currentFile);
                         if ($fPerms !== false) {
                             $fPerms = substr(decoct($fPerms), is_file($currentFile) ? 2 : 1);
                         } else {
                             $fPerms = '0000';
                         }
                         $atts[] = "file_perms=\"" . $fPerms . "\"";
                         if (Utils::is_image($currentFile)) {
                             list($width, $height, $type, $attr) = @getimagesize($currentFile);
                             $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\"";
                             $atts[] = "image_width=\"{$width}\"";
                             $atts[] = "image_height=\"{$height}\"";
                         }
                         $atts[] = "mimestring=\"" . Utils::mimetype($currentFile, "type", is_dir($currentFile)) . "\"";
                         $datemodif = $this->date_modif($currentFile);
                         $atts[] = "ajxp_modiftime=\"" . ($datemodif ? $datemodif : "0") . "\"";
                         $bytesize = @filesize($currentFile) or 0;
                         if ($bytesize < 0) {
                             $bytesize = sprintf("%u", $bytesize);
                         }
                         $atts[] = "filesize=\"" . Utils::roundSize($bytesize) . "\"";
                         $atts[] = "bytesize=\"" . $bytesize . "\"";
                         $atts[] = "filename=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($dir . "/" . $repIndex)) . "\"";
                         $atts[] = "icon=\"" . (is_file($currentFile) ? SystemTextEncoding::toUTF8($repName) : (is_dir($currentFile) ? "folder.png" : "mime-empty.png")) . "\"";
                         $attributes = join(" ", $atts);
                         $repName = $repIndex;
                     } else {
                         $folderBaseName = Utils::xmlEntities($repName);
                         $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?dir=" . $dir . "/" . $folderBaseName);
                         $link = urlencode($link);
                         $folderFullName = Utils::xmlEntities($dir) . "/" . $folderBaseName;
                         $parentFolderName = $dir;
                         if (!$completeMode) {
                             $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png";
                             $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png";
                             if (preg_match("/\\.zip\$/", $repName)) {
                                 $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/crystal/actions/16/accessories-archiver.png";
                             }
                             $attributes = "icon=\"{$icon}\"  openicon=\"{$openicon}\" filename=\"" . SystemTextEncoding::toUTF8($folderFullName) . "\" src=\"{$link}\"";
                         }
                     }
                 }
                 print "<tree text=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($repName)) . "\" {$attributes}>";
                 print "</tree>";
             }
             // ADD RECYCLE BIN TO THE LIST
             if ($nom_rep == $this->repository->getOption("PATH") && RecycleBinManager::recycleEnabled() && !$completeMode && !$skipZip) {
                 $recycleBinOption = $this->repository->getOption("RECYCLE_BIN");
                 if (is_dir($this->repository->getOption("PATH") . "/" . $recycleBinOption)) {
                     $recycleIcon = $this->countFiles($this->repository->getOption("PATH") . "/" . $recycleBinOption, false, true) > 0 ? "trashcan_full.png" : "trashcan.png";
                     if ($fileListMode) {
                         print "<tree text=\"" . Utils::xmlEntities($mess[122]) . "\" filesize=\"-\" is_file=\"0\" is_recycle=\"1\" mimestring=\"Trashcan\" ajxp_modiftime=\"" . $this->date_modif($this->repository->getOption("PATH") . "/" . $recycleBinOption) . "\" filename=\"/" . $recycleBinOption . "\" icon=\"{$recycleIcon}\"></tree>";
                     } else {
                         print "<tree text=\"{$mess['122']}\" is_recycle=\"true\" icon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/{$recycleIcon}\"  openIcon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/{$recycleIcon}\" filename=\"/" . $recycleBinOption . "\"/>";
                     }
                 }
             }
             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($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;
 }
예제 #3
0
파일: index.php 프로젝트: rmxcc/pydio-core
//------------------------------------------------------------
if (AuthService::usersEnabled()) {
    $loggedUser = AuthService::getLoggedUser();
    if ($action == "upload" && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRepositoryId() . "")) && isset($_FILES['Filedata'])) {
        header('HTTP/1.0 ' . '410 Not authorized');
        die('Error 410 Not authorized!');
    }
}
// THIS FIRST DRIVERS DO NOT NEED ID CHECK
//$ajxpDriver = AJXP_PluginsService::findPlugin("gui", "ajax");
$authDriver = ConfService::getAuthDriverImpl();
// DRIVERS BELOW NEED IDENTIFICATION CHECK
if (!AuthService::usersEnabled() || ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") || AuthService::getLoggedUser() != null) {
    $confDriver = ConfService::getConfStorageImpl();
    $Driver = ConfService::loadRepositoryDriver();
}
AJXP_PluginsService::getInstance()->initActivePlugins();
require_once AJXP_BIN_FOLDER . "/class.AJXP_Controller.php";
$xmlResult = AJXP_Controller::findActionAndApply($action, array_merge($_GET, $_POST), $_FILES);
if ($xmlResult !== false && $xmlResult != "") {
    AJXP_XMLWriter::header();
    print $xmlResult;
    AJXP_XMLWriter::close();
} else {
    if (isset($requireAuth) && AJXP_Controller::$lastActionNeedsAuth) {
        AJXP_XMLWriter::header();
        AJXP_XMLWriter::requireAuth();
        AJXP_XMLWriter::close();
    }
}
session_write_close();
 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 static function findActionAndApply($actionName, $httpVars, $fileVars)
 {
     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;
                 }
             }
         }
         return;
     }
     $xPath = self::initXPath();
     $actions = $xPath->query("actions/action[@name='{$actionName}']");
     if (!$actions->length) {
         return false;
     }
     $action = $actions->item(0);
     //Check Rights
     $mess = ConfService::getMessages();
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if (AJXP_Controller::actionNeedsRight($action, $xPath, "adminOnly") && ($loggedUser == null || !$loggedUser->isAdmin())) {
             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::getCurrentRootDirIndex() . ""))) {
             AJXP_XMLWriter::header();
             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::getCurrentRootDirIndex() . ""))) {
             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 ($captureCalls !== false) {
         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($xPath, $preCall, $actionName, $httpVars, $fileVars);
             if (isset($params)) {
                 $params["pre_processor_results"][$preCall->getAttribute("pluginId")] = $preResult;
             }
         }
     }
     if ($mainCall) {
         $result = self::applyCallback($xPath, $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($xPath, $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($xPath, $captureCall, $actionName, $httpVars, $params);
         }
     } else {
         if (isset($result)) {
             return $result;
         }
     }
 }
예제 #6
0
 /**
  * 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;
 }
예제 #7
0
 /**
  * @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;
     }
 }
예제 #8
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = 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 "edit":
             if (isset($save) && $save == 1) {
                 AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file)));
                 $code = stripslashes($code);
                 $code = str_replace("&lt;", "<", $code);
                 $this->SSHOperation->setRemoteContent($this->makeName($file), $code);
                 echo $mess[115];
             } else {
                 $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));
             }
             $reload_current_node = true;
             if (isset($dest_node)) {
                 $reload_dest_node = $dest_node;
             }
             $reload_file_list = true;
             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())));
                 $reload_file_list = $dir;
             }
             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));
             $reload_current_node = true;
             $reload_file_list = 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);
             $reload_current_node = true;
             $reload_file_list = basename($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 = Utils::processFileName($dirname);
             $error = $this->SSHOperation->createRemoteDirectory($this->makeName($dir . "/" . $dirname));
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             $reload_file_list = $dirname;
             $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             $reload_current_node = 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 = 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;
             $reload_file_list = $filename;
             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 = Utils::parseFileDataErrors($boxData, $fancyLoader);
                 if ($err != null) {
                     $errorMessage = $err;
                     break;
                 }
                 $userfile_name = $boxData["name"];
                 $userfile_name = 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":
             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);
             AJXP_XMLWriter::header();
             foreach ($result as $file) {
                 $attributes = "";
                 $fileName = SystemTextEncoding::toUTF8($file["name"]);
                 $icon = 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=\"" . Utils::is_image($fileName) . "\"";
                         $atts[] = "mimestring=\"" . Utils::mimetype($fileName, "type", $file["isDir"] == 1) . "\"";
                         $atts[] = "ajxp_modiftime=\"" . $this->dateModif($file["time"]) . "\"";
                         $atts[] = "filesize=\"" . Utils::roundSize($file["size"]) . "\"";
                         $atts[] = "bytesize=\"" . $file["size"] . "\"";
                         $atts[] = "filename=\"" . str_replace("&", "&amp;", $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("&", "&amp;", $fileName);
                             $folderFullName = "{$dir}/" . $folderBaseName;
                             $parentFolderName = $dir;
                             if (!$completeMode) {
                                 $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png";
                                 $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png";
                                 if (preg_match("/\\.zip\$/", $file["name"])) {
                                     $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/crystal/actions/16/accessories-archiver.png";
                                 }
                                 $attributes = "icon=\"{$icon}\"  openicon=\"{$openicon}\" filename=\"" . $folderFullName . "\" src=\"{$link}\"";
                             }
                         }
                     }
                 }
                 if (strlen($attributes) > 0) {
                     print "<tree text=\"" . str_replace("&", "&amp;", 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($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;
 }
예제 #9
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	SWITCH THE ROOT REPOSITORY
         //------------------------------------
         case "switch_root_dir":
             if (!isset($root_dir_index)) {
                 break;
             }
             $dirList = ConfService::getRootDirsList();
             if (!isset($dirList[$root_dir_index])) {
                 $errorMessage = "Trying to switch to an unkown folder!";
                 break;
             }
             ConfService::switchRootDir($root_dir_index);
             $logMessage = "Successfully Switched!";
             AJXP_Logger::logAction("Switch Repository", array("rep. id" => $root_dir_index));
             break;
             //------------------------------------
             //	GET AN HTML TEMPLATE
             //------------------------------------
         //------------------------------------
         //	GET AN HTML TEMPLATE
         //------------------------------------
         case "get_template":
             header("Content-type:text/html; charset:UTF-8");
             if (isset($template_name) && is_file(CLIENT_RESOURCES_FOLDER . "/html/" . $template_name)) {
                 if ($template_name == "gui_tpl.html") {
                     include CLIENT_RESOURCES_FOLDER . "/html/usertemplate_top.html";
                 }
                 include CLIENT_RESOURCES_FOLDER . "/html/" . $template_name;
                 if ($template_name == "gui_tpl.html") {
                     include CLIENT_RESOURCES_FOLDER . "/html/usertemplate_bottom.html";
                 }
             }
             exit(0);
             break;
             //------------------------------------
             //	GET I18N MESSAGES
             //------------------------------------
         //------------------------------------
         //	GET I18N MESSAGES
         //------------------------------------
         case "get_i18n_messages":
             header("Content-type:text/javascript");
             HTMLWriter::writeI18nMessagesClass(ConfService::getMessages());
             exit(0);
             break;
             //------------------------------------
             //	BOOKMARK BAR
             //------------------------------------
         //------------------------------------
         //	BOOKMARK BAR
         //------------------------------------
         case "get_bookmarks":
             $bmUser = null;
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser = AuthService::getLoggedUser();
             } else {
                 if (!AuthService::usersEnabled()) {
                     $confStorage = ConfService::getConfStorageImpl();
                     $bmUser = $confStorage->createUserObject("shared");
                 }
             }
             if ($bmUser == null) {
                 exit(1);
             }
             if (isset($_GET["bm_action"]) && isset($_GET["bm_path"])) {
                 if ($_GET["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($_GET["title"])) {
                         $title = $_GET["title"];
                     }
                     if ($title == "" && $_GET["bm_path"] == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark($_GET["bm_path"], $title);
                 } else {
                     if ($_GET["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($_GET["bm_path"]);
                     } else {
                         if ($_GET["bm_action"] == "rename_bookmark" && isset($_GET["bm_title"])) {
                             $bmUser->renameBookmark($_GET["bm_path"], $_GET["bm_title"]);
                         }
                     }
                 }
             }
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser->save();
                 AuthService::updateUser($bmUser);
             } else {
                 if (!AuthService::usersEnabled()) {
                     $bmUser->save();
                 }
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks());
             AJXP_XMLWriter::close();
             exit(1);
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "save_user_pref":
             $userObject = AuthService::getLoggedUser();
             if ($userObject == null) {
                 exit(1);
             }
             $i = 0;
             while (isset($_GET["pref_name_" . $i]) && isset($_GET["pref_value_" . $i])) {
                 $prefName = $_GET["pref_name_" . $i];
                 $prefValue = $_GET["pref_value_" . $i];
                 if ($prefName != "password") {
                     $userObject->setPref($prefName, $prefValue);
                     $userObject->save();
                     AuthService::updateUser($userObject);
                     setcookie("AJXP_{$prefName}", $prefValue);
                 } else {
                     if (isset($_GET["crt"]) && AuthService::checkPassword($userObject->getId(), $_GET["crt"], false, $_GET["pass_seed"])) {
                         AuthService::updatePassword($userObject->getId(), $prefValue);
                     } else {
                         //$errorMessage = "Wrong password!";
                         header("Content-Type:text/plain");
                         print "PASS_ERROR";
                         exit(1);
                     }
                 }
                 $i++;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             exit(1);
             break;
             //------------------------------------
             //	DISPLAY DOC
             //------------------------------------
         //------------------------------------
         //	DISPLAY DOC
         //------------------------------------
         case "display_doc":
             header("Content-type:text/html; charset:UTF-8");
             echo HTMLWriter::getDocFile(htmlentities($_GET["doc_file"]));
             exit(1);
             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);
     }
     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;
 }
예제 #10
0
 /**
  * @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) {
                     //throw new Exception("You must be logged in");
                     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';
             }
             //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;
     }
 }
예제 #11
0
 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 switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	SWITCH THE ROOT REPOSITORY
         //------------------------------------
         case "switch_repository":
             if (!isset($repository_id)) {
                 break;
             }
             $dirList = ConfService::getRepositoriesList();
             /** @var $repository_id string */
             if (!isset($dirList[$repository_id])) {
                 $errorMessage = "Trying to switch to an unkown repository!";
                 break;
             }
             ConfService::switchRootDir($repository_id);
             // Load try to init the driver now, to trigger an exception
             // if it's not loading right.
             ConfService::loadRepositoryDriver();
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $user = AuthService::getLoggedUser();
                 $activeRepId = ConfService::getCurrentRootDirIndex();
                 $user->setArrayPref("history", "last_repository", $activeRepId);
                 $user->save("user");
             }
             //$logMessage = "Successfully Switched!";
             AJXP_Logger::logAction("Switch Repository", array("rep. id" => $repository_id));
             break;
             //------------------------------------
             //	BOOKMARK BAR
             //------------------------------------
         //------------------------------------
         //	BOOKMARK BAR
         //------------------------------------
         case "get_bookmarks":
             $bmUser = null;
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser = AuthService::getLoggedUser();
             } else {
                 if (!AuthService::usersEnabled()) {
                     $confStorage = ConfService::getConfStorageImpl();
                     $bmUser = $confStorage->createUserObject("shared");
                 }
             }
             if ($bmUser == null) {
                 exit(1);
             }
             if (isset($httpVars["bm_action"]) && isset($httpVars["bm_path"])) {
                 if ($httpVars["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($httpVars["bm_title"])) {
                         $title = $httpVars["bm_title"];
                     }
                     if ($title == "" && $httpVars["bm_path"] == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark(SystemTextEncoding::magicDequote($httpVars["bm_path"]), SystemTextEncoding::magicDequote($title));
                 } else {
                     if ($httpVars["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($httpVars["bm_path"]);
                     } else {
                         if ($httpVars["bm_action"] == "rename_bookmark" && isset($httpVars["bm_title"])) {
                             $bmUser->renameBookmark($httpVars["bm_path"], $httpVars["bm_title"]);
                         }
                     }
                 }
             }
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser->save("user");
                 AuthService::updateUser($bmUser);
             } else {
                 if (!AuthService::usersEnabled()) {
                     $bmUser->save("user");
                 }
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks());
             AJXP_XMLWriter::close();
             exit(1);
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "save_user_pref":
             $userObject = AuthService::getLoggedUser();
             $i = 0;
             while (isset($httpVars["pref_name_" . $i]) && isset($httpVars["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($httpVars["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && $userObject == null) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save("user");
                 AuthService::updateUser($userObject);
                 //setcookie("AJXP_$prefName", $prefValue);
                 $i++;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             exit(1);
             break;
             //------------------------------------
             // WEBDAV PREFERENCES
             //------------------------------------
         //------------------------------------
         // WEBDAV PREFERENCES
         //------------------------------------
         case "webdav_preferences":
             $userObject = AuthService::getLoggedUser();
             $webdavActive = false;
             $passSet = false;
             // Detect http/https and host
             if (ConfService::getCoreConf("WEBDAV_BASEHOST") != "") {
                 $baseURL = ConfService::getCoreConf("WEBDAV_BASEHOST");
             } else {
                 $baseURL = AJXP_Utils::detectServerURL();
             }
             $webdavBaseUrl = $baseURL . ConfService::getCoreConf("WEBDAV_BASEURI") . "/";
             if (isset($httpVars["activate"]) || isset($httpVars["webdav_pass"])) {
                 $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
                 if (!empty($httpVars["activate"])) {
                     $activate = $httpVars["activate"] == "true" ? true : false;
                     if (empty($davData)) {
                         $davData = array();
                     }
                     $davData["ACTIVE"] = $activate;
                 }
                 if (!empty($httpVars["webdav_pass"])) {
                     $password = $httpVars["webdav_pass"];
                     if (function_exists('mcrypt_encrypt')) {
                         $user = $userObject->getId();
                         $secret = defined("AJXP_SECRET_KEY") ? AJXP_SAFE_SECRET_KEY : "CDAFx¨op#";
                         $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
                         $password = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($user . $secret), $password, MCRYPT_MODE_ECB, $iv));
                     }
                     $davData["PASS"] = $password;
                 }
                 $userObject->setPref("AJXP_WEBDAV_DATA", $davData);
                 $userObject->save("user");
             }
             $davData = $userObject->getPref("AJXP_WEBDAV_DATA");
             if (!empty($davData)) {
                 $webdavActive = isset($davData["ACTIVE"]) && $davData["ACTIVE"] === true;
                 $passSet = isset($davData["PASS"]);
             }
             $repoList = ConfService::getRepositoriesList();
             $davRepos = array();
             $loggedUser = AuthService::getLoggedUser();
             foreach ($repoList as $repoIndex => $repoObject) {
                 $accessType = $repoObject->getAccessType();
                 $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType);
                 if (is_a($driver, "AjxpWebdavProvider") && ($loggedUser->canRead($repoIndex) || $loggedUser->canWrite($repoIndex))) {
                     $davRepos[$repoIndex] = $webdavBaseUrl . "" . ($repoObject->getSlug() == null ? $repoObject->getId() : $repoObject->getSlug());
                 }
             }
             $prefs = array("webdav_active" => $webdavActive, "password_set" => $passSet, "webdav_base_url" => $webdavBaseUrl, "webdav_repositories" => $davRepos);
             HTMLWriter::charsetHeader("application/json");
             print json_encode($prefs);
             break;
         case "get_user_template_logo":
             $tplId = $httpVars["template_id"];
             $iconFormat = $httpVars["icon_format"];
             $repo = ConfService::getRepositoryById($tplId);
             $logo = $repo->getOption("TPL_ICON_" . strtoupper($iconFormat));
             if (isset($logo) && is_file(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo)) {
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_DATA_PATH . "/plugins/core.conf/tpl_logos/" . $logo);
             } else {
                 $logo = "default_template_logo-" . ($iconFormat == "small" ? 16 : 22) . ".png";
                 header("Content-Type: " . AJXP_Utils::getImageMimeType($logo) . "; name=\"" . $logo . "\"");
                 header("Content-Length: " . filesize(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo));
                 header('Pragma:');
                 header('Cache-Control: public');
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 readfile(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/core.conf/" . $logo);
             }
             break;
         case "get_user_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $repositories = ConfService::getRepositoriesList();
             $pServ = AJXP_PluginsService::getInstance();
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 if (!$repo->getOption("TPL_USER_CAN_CREATE")) {
                     continue;
                 }
                 $repoId = $repo->getUniqueId();
                 $repoLabel = $repo->getDisplay();
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 $driverPlug = $pServ->getPluginByTypeName("access", $repoType);
                 $params = $driverPlug->getManifestRawContent("//param", "node");
                 $tplDefined = $repo->getOptionsDefined();
                 $defaultLabel = '';
                 foreach ($params as $paramNode) {
                     $name = $paramNode->getAttribute("name");
                     if (strpos($name, "TPL_") === 0) {
                         if ($name == "TPL_DEFAULT_LABEL") {
                             $defaultLabel = str_replace("AJXP_USER", AuthService::getLoggedUser()->getId(), $repo->getOption($name));
                         }
                         continue;
                     }
                     if (in_array($paramNode->getAttribute("name"), $tplDefined)) {
                         continue;
                     }
                     if ($paramNode->getAttribute('no_templates') == 'true') {
                         continue;
                     }
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($paramNode->ownerDocument->saveXML($paramNode));
                 }
                 // ADD LABEL
                 echo '<param name="DISPLAY" type="string" label="' . $mess[359] . '" description="' . $mess[429] . '" mandatory="true" default="' . $defaultLabel . '"/>';
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "user_create_repository":
             $tplId = $httpVars["template_id"];
             $tplRepo = ConfService::getRepositoryById($tplId);
             $options = array();
             self::parseParameters($httpVars, $options);
             $newRep = $tplRepo->createTemplateChild(AJXP_Utils::sanitize($httpVars["DISPLAY"]), $options, null, AuthService::getLoggedUser()->getId());
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[426]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 // Make sure we do not overwrite otherwise loaded rights.
                 $loggedUser->load();
                 $loggedUser->setRight($newRep->getUniqueId(), "rw");
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[425], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "user_delete_repository":
             $repoId = $httpVars["repository_id"];
             $repository = ConfService::getRepositoryById($repoId);
             if (!$repository->getUniqueUser() || $repository->getUniqueUser() != AuthService::getLoggedUser()->getId()) {
                 throw new Exception("You are not allowed to perform this operation!");
             }
             $res = ConfService::deleteRepository($repoId);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess[427]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 // Make sure we do not override remotely set rights
                 $loggedUser->load();
                 $loggedUser->removeRights($repoId);
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess[428], null);
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if (isset($requireAuth)) {
         $xmlBuffer .= AJXP_XMLWriter::requireAuth(false);
     }
     return $xmlBuffer;
 }
 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::getRootDirsList();
             if (!isset($dirList[$repository_id])) {
                 $errorMessage = "Trying to switch to an unkown repository!";
                 break;
             }
             ConfService::switchRootDir($repository_id);
             // Load try to init the driver now, to trigger an exception
             // if it's not loading right.
             ConfService::loadRepositoryDriver();
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $user = AuthService::getLoggedUser();
                 $activeRepId = ConfService::getCurrentRootDirIndex();
                 $user->setArrayPref("history", "last_repository", $activeRepId);
                 $user->save();
             }
             //$logMessage = "Successfully Switched!";
             AJXP_Logger::logAction("Switch Repository", array("rep. id" => $repository_id));
             break;
             //------------------------------------
             //	BOOKMARK BAR
             //------------------------------------
         //------------------------------------
         //	BOOKMARK BAR
         //------------------------------------
         case "get_bookmarks":
             $bmUser = null;
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser = AuthService::getLoggedUser();
             } else {
                 if (!AuthService::usersEnabled()) {
                     $confStorage = ConfService::getConfStorageImpl();
                     $bmUser = $confStorage->createUserObject("shared");
                 }
             }
             if ($bmUser == null) {
                 exit(1);
             }
             if (isset($_GET["bm_action"]) && isset($_GET["bm_path"])) {
                 if ($_GET["bm_action"] == "add_bookmark") {
                     $title = "";
                     if (isset($_GET["bm_title"])) {
                         $title = $_GET["bm_title"];
                     }
                     if ($title == "" && $_GET["bm_path"] == "/") {
                         $title = ConfService::getCurrentRootDirDisplay();
                     }
                     $bmUser->addBookMark(SystemTextEncoding::magicDequote($_GET["bm_path"]), SystemTextEncoding::magicDequote($title));
                 } else {
                     if ($_GET["bm_action"] == "delete_bookmark") {
                         $bmUser->removeBookmark($_GET["bm_path"]);
                     } else {
                         if ($_GET["bm_action"] == "rename_bookmark" && isset($_GET["bm_title"])) {
                             $bmUser->renameBookmark($_GET["bm_path"], $_GET["bm_title"]);
                         }
                     }
                 }
             }
             if (AuthService::usersEnabled() && AuthService::getLoggedUser() != null) {
                 $bmUser->save();
                 AuthService::updateUser($bmUser);
             } else {
                 if (!AuthService::usersEnabled()) {
                     $bmUser->save();
                 }
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::writeBookmarks($bmUser->getBookmarks());
             AJXP_XMLWriter::close();
             exit(1);
             break;
             //------------------------------------
             //	SAVE USER PREFERENCE
             //------------------------------------
         //------------------------------------
         //	SAVE USER PREFERENCE
         //------------------------------------
         case "save_user_pref":
             $userObject = AuthService::getLoggedUser();
             $i = 0;
             while (isset($_GET["pref_name_" . $i]) && isset($_GET["pref_value_" . $i])) {
                 $prefName = AJXP_Utils::sanitize($_GET["pref_name_" . $i], AJXP_SANITIZE_ALPHANUM);
                 $prefValue = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($_GET["pref_value_" . $i]));
                 if ($prefName == "password") {
                     continue;
                 }
                 if ($prefName != "pending_folder" && ($userObject == null || $userObject->getId() == "guest")) {
                     $i++;
                     continue;
                 }
                 $userObject->setPref($prefName, $prefValue);
                 $userObject->save();
                 AuthService::updateUser($userObject);
                 //setcookie("AJXP_$prefName", $prefValue);
                 $i++;
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             exit(1);
             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;
 }
예제 #14
0
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = 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();
     if (class_exists("RecycleBinManager")) {
         $newArgs = RecycleBinManager::filterActions($action, $selection, $dir);
         foreach ($newArgs as $argName => $argValue) {
             ${$argName} = $argValue;
         }
     }
     switch ($action) {
         //------------------------------------
         //	DOWNLOAD, IMAGE & MP3 PROXYS
         //------------------------------------
         case "download":
         case "image_proxy":
         case "mp3_proxy":
             AJXP_Logger::logAction("Download", array("files" => $selection));
             $this->sendRemoteFile($selection->files[0], $action == "download");
             exit(0);
             break;
             //------------------------------------
             //	ONLINE EDIT
             //------------------------------------
         //------------------------------------
         //	ONLINE EDIT
         //------------------------------------
         case "edit":
             $file_name = basename($file);
             $this->ftp_get_contents($file);
             if (isset($save) && $save == 1 && isset($code)) {
                 // Reload "code" variable directly from POST array, do not "securePath"...
                 $code = $_POST["code"];
                 AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file_name)));
                 $code = stripslashes($code);
                 $code = str_replace("&lt;", "<", $code);
                 $fp = fopen("files/" . SystemTextEncoding::fromUTF8("{$file_name}"), "w");
                 fputs($fp, $code);
                 fclose($fp);
                 echo $mess[115];
                 ftp_put($this->connect, $this->secureFtpPath($this->getPath() . $file), "files/" . SystemTextEncoding::fromUTF8($file_name), FTP_BINARY);
                 $this->ftpRemoveFileTmp("files/" . SystemTextEncoding::fromUTF8("{$file_name}"));
                 $reload_current_node = true;
             } else {
                 $this->readFile("files/" . SystemTextEncoding::fromUTF8($file_name), "plain");
             }
             exit(0);
             break;
             //------------------------------------
             //	COPY / MOVE
             //------------------------------------
         //------------------------------------
         //	COPY / MOVE
         //------------------------------------
         case "copy":
         case "move":
             if ($selection->isEmpty()) {
                 $errorMessage = $mess[113];
                 break;
             }
             $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false);
             if (count($error)) {
                 $errorMessage = join("\n", $error);
             } else {
                 $logMessage = join("\n", $success);
             }
             $reload_current_node = true;
             if (isset($dest_node)) {
                 $reload_dest_node = $dest_node;
             }
             $reload_file_list = true;
             break;
             //------------------------------------
             //	SUPPRIMER / DELETE
             //------------------------------------
         //------------------------------------
         //	SUPPRIMER / DELETE
         //------------------------------------
         case "delete":
             if ($selection->isEmpty()) {
                 $errorMessage = $mess[113];
                 break;
             }
             $logMessages = array();
             $errorMessage = $this->delete($selection->getFiles(), $logMessages, $dir);
             if (count($logMessages)) {
                 $logMessage = join("\n", $logMessages);
             }
             AJXP_Logger::logAction("Delete", array("files" => $selection));
             $reload_current_node = true;
             $reload_file_list = true;
             break;
             //------------------------------------
             //	RENOMMER / RENAME
             //------------------------------------
         //------------------------------------
         //	RENOMMER / RENAME
         //------------------------------------
         case "rename":
             $file = SystemTextEncoding::fromUTF8($file);
             $filename_new = SystemTextEncoding::fromUTF8($filename_new);
             $error = $this->rename($file, $filename_new);
             if ($error != null) {
                 $errorMessage = $error;
                 break;
             }
             $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new);
             $reload_current_node = true;
             $reload_file_list = basename($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 = Utils::processFileName(SystemTextEncoding::fromUTF8($dirname));
             $error = $this->mkDir($dir, $dirname);
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             $reload_file_list = $dirname;
             $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             $reload_current_node = 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 = Utils::processFileName(SystemTextEncoding::fromUTF8($filename));
             $error = $this->createEmptyFile($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;
             $reload_file_list = $filename;
             AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename));
             break;
             //------------------------------------
             //	CHANGE FILE PERMISSION
             //------------------------------------
         //------------------------------------
         //	CHANGE FILE PERMISSION
         //------------------------------------
         case "chmod":
             $files = $selection->getFiles();
             if (@ftp_chmod($this->connect, $chmod_value, $this->getPath() . $files[0]) === false) {
                 $error = "Error chmod";
             }
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             $logMessage = "Successfully changed permission to " . $chmod_value . " for " . $files[0];
             $reload_file_list = $dir;
             AJXP_Logger::logAction("Chmod", array("dir" => $dir, "file" => $files[0]));
             break;
             //------------------------------------
             //	UPLOAD
             //------------------------------------
         //------------------------------------
         //	UPLOAD
         //------------------------------------
         case "upload":
             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":
             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;
                         }
                     }
                 }
             }
             if (isset($skipZip) && $skipZip == "true") {
                 $skipZip = true;
             } else {
                 $skipZip = false;
             }
             if ($test = UserSelection::detectZip($dir)) {
                 $liste = array();
                 $zip = $this->zipListing($test[0], $test[1], $liste);
                 AJXP_XMLWriter::header();
                 $tmpDir = $this->getPath() . dirname($test[0]) . ".tmpZipExtract";
                 foreach ($liste as $zipEntry) {
                     $atts = array();
                     if (!$fileListMode && !$zipEntry["folder"]) {
                         continue;
                     }
                     $atts[] = "is_file=\"" . ($zipEntry["folder"] ? "false" : "true") . "\"";
                     $atts[] = "text=\"" . str_replace("&", "&amp;", basename(SystemTextEncoding::toUTF8($zipEntry["stored_filename"]))) . "\"";
                     $atts[] = "filename=\"" . str_replace("&", "&amp;", SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\"";
                     if ($fileListMode) {
                         $atts[] = "filesize=\"" . Utils::roundSize($zipEntry["size"]) . "\"";
                         $atts[] = "bytesize=\"" . $zipEntry["size"] . "\"";
                         $atts[] = "ajxp_modiftime=\"" . $zipEntry["mtime"] . "\"";
                         $atts[] = "mimestring=\"" . Utils::mimetype($zipEntry["stored_filename"], "mime", $zipEntry["folder"]) . "\"";
                         $atts[] = "icon=\"" . Utils::mimetype($zipEntry["stored_filename"], "image", $zipEntry["folder"]) . "\"";
                         $is_image = Utils::is_image(basename($zipEntry["stored_filename"]));
                         $atts[] = "is_image=\"" . $is_image . "\"";
                         if ($is_image) {
                             if (!is_dir($tmpDir)) {
                                 mkdir($tmpDir);
                             }
                             $currentFile = $tmpDir . "/" . basename($zipEntry["stored_filename"]);
                             $data = $zip->extract(PCLZIP_OPT_BY_NAME, $zipEntry["stored_filename"], PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_PATH, $tmpDir);
                             list($width, $height, $type, $attr) = @getimagesize($currentFile);
                             $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\"";
                             $atts[] = "image_width=\"{$width}\"";
                             $atts[] = "image_height=\"{$height}\"";
                             unlink($currentFile);
                         }
                     } else {
                         $atts[] = "icon=\"client/images/foldericon.png\"";
                         $atts[] = "openicon=\"client/images/foldericon.png\"";
                         $atts[] = "src=\"content.php?dir=" . urlencode(SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\"";
                     }
                     print "<tree " . join(" ", $atts) . "/>";
                     if (is_dir($tmpDir)) {
                         rmdir($tmpDir);
                     }
                 }
                 AJXP_XMLWriter::close();
                 exit(0);
             }
             $nom_rep = $this->initName($dir);
             AJXP_Exception::errorToXml($nom_rep);
             $result = $this->listing($nom_rep, !($searchMode || $fileListMode));
             $this->fileListData = $result[0];
             $reps = $result[0];
             AJXP_XMLWriter::header();
             if (!is_array($reps)) {
                 AJXP_XMLWriter::close();
                 exit(1);
             }
             foreach ($reps as $repIndex => $repName) {
                 if (is_string($repName) && (preg_match("/\\.zip\$/", $repName) && $skipZip)) {
                     continue;
                 }
                 $attributes = "";
                 if ($searchMode) {
                     if (is_file($nom_rep . "/" . $repIndex)) {
                         $attributes = "is_file=\"true\" icon=\"{$repName}\"";
                         $repName = $repIndex;
                     }
                 } else {
                     if ($fileListMode) {
                         $currentFile = $nom_rep . "/" . $repName['name'];
                         $atts = array();
                         $atts[] = "is_file=\"" . ($repName['isDir'] ? "0" : "1") . "\"";
                         $atts[] = "is_image=\"" . Utils::is_image($currentFile) . "\"";
                         $atts[] = "file_group=\"" . $repName['group'] . "\"";
                         $atts[] = "file_owner=\"" . $repName['owner'] . "\"";
                         $atts[] = "file_perms=\"" . $repName['chmod1'] . "\"";
                         if (Utils::is_image($currentFile)) {
                             list($width, $height, $type, $attr) = $this->getimagesize($currentFile);
                             $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\"";
                             $atts[] = "image_width=\"{$width}\"";
                             $atts[] = "image_height=\"{$height}\"";
                         }
                         $atts[] = "mimestring=\"" . $repName['type'] . "\"";
                         $datemodif = $repName['modifTime'];
                         $atts[] = "ajxp_modiftime=\"" . ($datemodif ? $datemodif : "0") . "\"";
                         $bytesize = $repName['size'] or 0;
                         if ($bytesize < 0) {
                             $bytesize = sprintf("%u", $bytesize);
                         }
                         $atts[] = "filesize=\"" . Utils::roundSize($bytesize) . "\"";
                         $atts[] = "bytesize=\"" . $bytesize . "\"";
                         $atts[] = "filename=\"" . str_replace("&", "&amp;", SystemTextEncoding::toUTF8($dir . "/" . $repIndex)) . "\"";
                         $atts[] = "icon=\"" . $repName['icon'] . "\"";
                         $attributes = join(" ", $atts);
                         $repName = $repIndex;
                     } else {
                         //Menu treeview repertoire
                         $folderBaseName = str_replace("&", "&amp;", $repName['name']);
                         $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?dir=" . $dir . "/" . $folderBaseName);
                         $link = urlencode($link);
                         $folderFullName = str_replace("&", "&amp;", $dir) . "/" . $folderBaseName;
                         $parentFolderName = $dir;
                         $repName = $repIndex;
                         if (!$completeMode) {
                             $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png";
                             $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png";
                             if (preg_match("/\\.zip\$/", $repName)) {
                                 $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/crystal/actions/16/accessories-archiver.png";
                             }
                             $attributes = "icon=\"{$icon}\"  openicon=\"{$openicon}\" filename=\"" . SystemTextEncoding::toUTF8($folderFullName) . "\" src=\"{$link}\"";
                         }
                     }
                 }
                 print "<tree text=\"" . str_replace("&", "&amp;", SystemTextEncoding::toUTF8($repName)) . "\" {$attributes}>";
                 print "</tree>";
             }
             // ADD RECYCLE BIN TO THE LIST
             if ($nom_rep == $this->repository->getOption("PATH") && RecycleBinManager::recycleEnabled() && !$completeMode && !$skipZip) {
                 $recycleBinOption = $this->repository->getOption("RECYCLE_BIN");
                 if ($fileListMode) {
                     print "<tree text=\"" . Utils::xmlEntities($mess[122]) . "\" filesize=\"-\" is_file=\"0\" is_recycle=\"1\" mimestring=\"Trashcan\" ajxp_modiftime=\"\" filename=\"/" . $recycleBinOption . "\" icon=\"trashcan.png\"></tree>";
                 } else {
                     print "<tree text=\"{$mess['122']}\" is_recycle=\"true\" icon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/trashcan.png\"  openIcon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/trashcan.png\" filename=\"/" . $recycleBinOption . "\"/>";
                 }
             }
             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($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 postVerificationCode($action, $httpVars, $fileVars)
 {
     if ($action != "duo_post_verification_code") {
         return;
     }
     $u = AuthService::getLoggedUser();
     if ($u == null) {
         return;
     }
     $sigResponse = $httpVars["sig_response"];
     require_once $this->getBaseDir() . "/duo_php/duo_web.php";
     $appUnique = $this->getFilteredOption("DUO_AUTH_AKEY");
     $iKey = $this->getFilteredOption("DUO_AUTH_IKEY");
     $sKey = $this->getFilteredOption("DUO_AUTH_SKEY");
     $verif = Duo::verifyResponse($iKey, $sKey, $appUnique, $sigResponse);
     if ($verif != null && $verif == $u->getId()) {
         $u->removeLock();
         $u->save("superuser");
         $u->recomputeMergedRole();
         AuthService::updateUser($u);
         ConfService::switchUserToActiveRepository($u);
         $force = $u->mergedRole->filterParameterValue("core.conf", "DEFAULT_START_REPOSITORY", AJXP_REPO_SCOPE_ALL, -1);
         $passId = -1;
         if ($force != "" && $u->canSwitchTo($force) && !isset($httpVars["tmp_repository_id"]) && !isset($_SESSION["PENDING_REPOSITORY_ID"])) {
             $passId = $force;
         }
         $res = ConfService::switchUserToActiveRepository($u, $passId);
         if (!$res) {
             AuthService::disconnect();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::requireAuth(true);
             AJXP_XMLWriter::close();
         }
     } else {
         AuthService::disconnect();
         AJXP_XMLWriter::header();
         AJXP_XMLWriter::requireAuth(true);
         AJXP_XMLWriter::close();
     }
 }
 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) {
         //------------------------------------
         //	GET AN HTML TEMPLATE
         //------------------------------------
         case "get_template":
             HTMLWriter::charsetHeader();
             $folder = CLIENT_RESOURCES_FOLDER . "/html";
             if (isset($httpVars["pluginName"])) {
                 $folder = "plugins/" . $httpVars["pluginName"];
                 if (isset($httpVars["pluginPath"])) {
                     $folder .= "/" . $httpVars["pluginPath"];
                 }
             }
             if (isset($template_name) && is_file($folder . "/" . $template_name)) {
                 include $folder . "/" . $template_name;
             }
             exit(0);
             break;
             //------------------------------------
             //	GET I18N MESSAGES
             //------------------------------------
         //------------------------------------
         //	GET I18N MESSAGES
         //------------------------------------
         case "get_i18n_messages":
             HTMLWriter::charsetHeader('text/javascript');
             HTMLWriter::writeI18nMessagesClass(ConfService::getMessages());
             exit(0);
             break;
             //------------------------------------
             //	SEND XML REGISTRY
             //------------------------------------
         //------------------------------------
         //	SEND XML REGISTRY
         //------------------------------------
         case "get_xml_registry":
             $regDoc = AJXP_PluginsService::getXmlRegistry();
             if (isset($_GET["xPath"])) {
                 $regPath = new DOMXPath($regDoc);
                 $nodes = $regPath->query($_GET["xPath"]);
                 AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $_GET["xPath"]));
                 if ($nodes->length) {
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML($nodes->item(0)));
                 }
                 AJXP_XMLWriter::close("ajxp_registry_part");
             } else {
                 header('Content-Type: application/xml; charset=UTF-8');
                 print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML());
             }
             exit(0);
             break;
             //------------------------------------
             //	DISPLAY DOC
             //------------------------------------
         //------------------------------------
         //	DISPLAY DOC
         //------------------------------------
         case "display_doc":
             HTMLWriter::charsetHeader();
             echo HTMLWriter::getDocFile(htmlentities($_GET["doc_file"]));
             exit(1);
             break;
             //------------------------------------
             //	CHECK UPDATE
             //------------------------------------
         //------------------------------------
         //	CHECK UPDATE
         //------------------------------------
         case "check_software_update":
             $content = @file_get_contents(SOFTWARE_UPDATE_SITE . "last_version.txt");
             $message = $mess["345"];
             if (isset($content) && $content != "") {
                 $last_version = floatval($content);
                 $currrent_version = floatval(AJXP_VERSION);
                 if ($last_version == $currrent_version) {
                     $message = $mess["346"];
                 } else {
                     if ($last_version > $currrent_version) {
                         $message = sprintf($mess["347"], $content, '<a href="http://www.ajaxplorer.info/">http://www.ajaxplorer.info/</a>');
                     }
                 }
             }
             HTMLWriter::charsetHeader("text/plain");
             print $message;
             exit(1);
             break;
             //------------------------------------
             //	GET CONFIG FOR BOOT
             //------------------------------------
         //------------------------------------
         //	GET CONFIG FOR BOOT
         //------------------------------------
         case "get_boot_conf":
             if (isset($_GET["server_prefix_uri"])) {
                 $_SESSION["AJXP_SERVER_PREFIX_URI"] = $_GET["server_prefix_uri"];
             }
             $config = array();
             $config["ajxpResourcesFolder"] = AJXP_THEME_FOLDER;
             $config["ajxpServerAccess"] = SERVER_ACCESS;
             $config["zipEnabled"] = ConfService::zipEnabled();
             $config["multipleFilesDownloadEnabled"] = !DISABLE_ZIP_CREATION;
             $config["flashUploaderEnabled"] = ConfService::getConf("UPLOAD_ENABLE_FLASH");
             $welcomeCustom = ConfService::getConf("WELCOME_CUSTOM_MSG");
             if ($welcomeCustom != "") {
                 $config["customWelcomeMessage"] = $welcomeCustom;
             }
             if (!ConfService::getConf("UPLOAD_ENABLE_FLASH")) {
                 $UploadMaxSize = AJXP_Utils::convertBytes(ini_get('upload_max_filesize'));
                 $confMaxSize = ConfService::getConf("UPLOAD_MAX_FILE");
                 if ($confMaxSize != 0 && $confMaxSize < $UploadMaxSize) {
                     $UploadMaxSize = $confMaxSize;
                 }
                 $confTotalNumber = ConfService::getConf("UPLOAD_MAX_NUMBER");
                 $config["htmlMultiUploaderOptions"] = array("282" => $UploadMaxSize, "284" => $confTotalNumber);
             }
             $config["usersEnabled"] = AuthService::usersEnabled();
             $config["loggedUser"] = AuthService::getLoggedUser() != null;
             $config["currentLanguage"] = ConfService::getLanguage();
             $config["userChangePassword"] = AuthService::changePasswordEnabled();
             $config["availableLanguages"] = ConfService::getConf("AVAILABLE_LANG");
             $config["ajxpVersion"] = AJXP_VERSION;
             $config["ajxpVersionDate"] = AJXP_VERSION_DATE;
             if (stristr($_SERVER["HTTP_USER_AGENT"], "msie 6")) {
                 $config["cssResources"] = array("css/pngHack/pngHack.css");
             }
             if (defined("GOOGLE_ANALYTICS_ID") && GOOGLE_ANALYTICS_ID != "") {
                 $config["googleAnalyticsData"] = array("id" => GOOGLE_ANALYTICS_ID, "domain" => GOOGLE_ANALYTICS_DOMAIN, "event" => GOOGLE_ANALYTICS_EVENT);
             }
             $config["i18nMessages"] = ConfService::getMessages();
             header("Content-type:application/json;charset=UTF-8");
             print json_encode($config);
             exit(1);
             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);
     }
     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;
 }