/**
  * Initialize download folder if not already done
  */
 public function initFolder()
 {
     $downloadFolder = $this->getPublicDownloadFolder();
     $downloadUrl = $this->getPublicDownloadUrl();
     if (is_file($downloadFolder . "/grid_t.png")) {
         return;
     }
     $pDir = dirname(__FILE__);
     $messages = ConfService::getMessages();
     $sTitle = sprintf($messages["action.share.1"], ConfService::getCoreConf("APPLICATION_TITLE"));
     $sLegend = $messages["action.share.20"];
     @copy($pDir . "/res/dl.png", $downloadFolder . "/dl.png");
     @copy($pDir . "/res/favi.png", $downloadFolder . "/favi.png");
     @copy($pDir . "/res/grid_t.png", $downloadFolder . "/grid_t.png");
     @copy($pDir . "/res/button_cancel.png", $downloadFolder . "/button_cancel.png");
     @copy(AJXP_INSTALL_PATH . "/server/index.html", $downloadFolder . "/index.html");
     $htaccessContent = "Order Deny,Allow\nAllow from all\n";
     $htaccessContent .= "\n<Files \".ajxp_*\">\ndeny from all\n</Files>\n";
     $path = parse_url($downloadUrl, PHP_URL_PATH);
     $htaccessContent .= '
     <IfModule mod_rewrite.c>
     RewriteEngine on
     RewriteBase ' . $path . '
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule ^([.a-zA-Z0-9_-]+)\\.php$ share.php?hash=$1 [QSA]
     RewriteRule ^([.a-zA-Z0-9_-]+)--([a-z-]+)$ share.php?hash=$1&lang=$2 [QSA]
     RewriteRule ^([.a-zA-Z0-9_-]+)$ share.php?hash=$1 [QSA]
     </IfModule>
     ';
     file_put_contents($downloadFolder . "/.htaccess", $htaccessContent);
     $content404 = file_get_contents($pDir . "/res/404.html");
     $content404 = str_replace(array("AJXP_MESSAGE_TITLE", "AJXP_MESSAGE_LEGEND"), array($sTitle, $sLegend), $content404);
     file_put_contents($downloadFolder . "/404.html", $content404);
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	CHANGE USER PASSWORD
         //------------------------------------
         case "pass_change":
             $userObject = AuthService::getLoggedUser();
             if ($userObject == null || $userObject->getId() == "guest") {
                 header("Content-Type:text/plain");
                 print "SUCCESS";
             }
             $oldPass = $httpVars["old_pass"];
             $newPass = $httpVars["new_pass"];
             $passSeed = $httpVars["pass_seed"];
             if (AuthService::checkPassword($userObject->getId(), $oldPass, false, $passSeed)) {
                 AuthService::updatePassword($userObject->getId(), $newPass);
             } else {
                 header("Content-Type:text/plain");
                 print "PASS_ERROR";
             }
             header("Content-Type:text/plain");
             print "SUCCESS";
             break;
         default:
             break;
     }
     return "";
 }
Пример #3
0
    public function initMeta($accessDriver)
    {
        $this->accessDriver = $accessDriver;
        if (!function_exists("exif_read_data")) {
            return;
        }
        $messages = ConfService::getMessages();
        $def = $this->getMetaDefinition();
        if (!count($def)) {
            return;
        }
        $cdataHead = '<div>
						<div class="panelHeader infoPanelGroup" colspan="2">' . $messages["meta.exif.1"] . '</div>
						<table class="infoPanelTable" cellspacing="0" border="0" cellpadding="0">';
        $cdataFoot = '</table></div>';
        $cdataParts = "";
        foreach ($def as $key => $label) {
            $trClass = $even ? " class=\"even\"" : "";
            $even = !$even;
            $cdataParts .= '<tr' . $trClass . '><td class="infoPanelLabel">' . $label . '</td><td class="infoPanelValue" id="ip_' . $key . '">#{' . $key . '}</td></tr>';
        }
        $selection = $this->xPath->query('registry_contributions/client_configs/component_config[@className="InfoPanel"]/infoPanelExtension');
        $contrib = $selection->item(0);
        $contrib->setAttribute("attributes", implode(",", array_keys($def)));
        $contrib->setAttribute("modifier", "ExifCellRenderer.prototype.infoPanelModifier");
        $htmlSel = $this->xPath->query('html', $contrib);
        $html = $htmlSel->item(0);
        $cdata = $this->manifestDoc->createCDATASection($cdataHead . $cdataParts . $cdataFoot);
        $html->appendChild($cdata);
        parent::init($this->options);
    }
Пример #4
0
 function bookmarkBar($allBookmarks)
 {
     //echo '<div id="bmbar_title">MyBookmarks&nbsp;&nbsp;</div>';
     $mess = ConfService::getMessages();
     foreach (array_reverse($allBookmarks) as $path) {
         if (is_array($path)) {
             $path = $path["PATH"];
         }
         echo '<div class="bm" onmouseover="this.className=\'bm_hover\';" onmouseout="this.className=\'bm\';"><img width="16" height="16" src="' . CLIENT_RESOURCES_FOLDER . '/images/crystal/mimes/16/folder.png" border="0" align="ABSMIDDLE" style="float:left;"><a href="#" class="disabled" title="' . $mess[146] . '" onclick="ajaxplorer.actionBar.removeBookmark(\'' . $path . '\'); return false;" onmouseover="$(this).addClassName(\'enabled\');" onmouseout="$(this).removeClassName(\'enabled\');"><img width="16" height="16" src="' . CLIENT_RESOURCES_FOLDER . '/images/crystal/actions/16/delete_bookmark.png" border="0" align="ABSMIDDLE" alt="' . $mess[146] . '"></a> <a href="#" onclick="ajaxplorer.goTo(\'' . $path . '\'); return false;" class="bookmark_button">' . $path . '</a></div>';
     }
 }
Пример #5
0
 public function AJXP_Exception($messageString, $messageId = false)
 {
     if ($messageId !== false && class_exists("ConfService")) {
         $messages = ConfService::getMessages();
         if (array_key_exists($messageId, $messages)) {
             $messageString = $messages[$messageId];
         } else {
             $messageString = $messageId;
         }
     }
     parent::__construct($messageString);
 }
 public function processUserAccessPoint($action, $httpVars, $fileVars)
 {
     switch ($action) {
         case "user_access_point":
             $uri = explode("/", trim($_SERVER["REQUEST_URI"], "/"));
             array_shift($uri);
             $action = array_shift($uri);
             $this->processSubAction($action, $uri);
             $_SESSION['OVERRIDE_GUI_START_PARAMETERS'] = array("REBASE" => "../../", "USER_GUI_ACTION" => $action);
             AJXP_Controller::findActionAndApply("get_boot_gui", array(), array());
             unset($_SESSION['OVERRIDE_GUI_START_PARAMETERS']);
             break;
         case "reset-password-ask":
             // This is a reset password request, generate a token and store it.
             // Find user by id
             if (AuthService::userExists($httpVars["email"])) {
                 // Send email
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($httpVars["email"]);
                 $email = $userObject->personalRole->filterParameterValue("core.conf", "email", AJXP_REPO_SCOPE_ALL, "");
                 if (!empty($email)) {
                     $uuid = AJXP_Utils::generateRandomString(48);
                     ConfService::getConfStorageImpl()->saveTemporaryKey("password-reset", $uuid, AJXP_Utils::decodeSecureMagic($httpVars["email"]), array());
                     $mailer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("mailer");
                     if ($mailer !== false) {
                         $mess = ConfService::getMessages();
                         $link = AJXP_Utils::detectServerURL() . "/user/reset-password/" . $uuid;
                         $mailer->sendMail(array($email), $mess["gui.user.1"], $mess["gui.user.7"] . "<a href=\"{$link}\">{$link}</a>");
                     } else {
                         echo 'ERROR: There is no mailer configured, please contact your administrator';
                     }
                 }
             }
             // Prune existing expired tokens
             ConfService::getConfStorageImpl()->pruneTemporaryKeys("password-reset", 20);
             echo "SUCCESS";
             break;
         case "reset-password":
             ConfService::getConfStorageImpl()->pruneTemporaryKeys("password-reset", 20);
             // This is a reset password
             if (isset($httpVars["key"]) && isset($httpVars["user_id"])) {
                 $key = ConfService::getConfStorageImpl()->loadTemporaryKey("password-reset", $httpVars["key"]);
                 if ($key != null && $key["user_id"] == $httpVars["user_id"] && AuthService::userExists($key["user_id"])) {
                     AuthService::updatePassword($key["user_id"], $httpVars["new_pass"]);
                 }
                 ConfService::getConfStorageImpl()->deleteTemporaryKey("password-reset", $httpVars["key"]);
             }
             AuthService::disconnect();
             echo 'SUCCESS';
             break;
         default:
             break;
     }
 }
Пример #7
0
    public function initMeta($accessDriver)
    {
        $this->accessDriver = $accessDriver;
        $messages = ConfService::getMessages();
        $def = $this->getMetaDefinition();
        $cdataHead = '<div>
						<div class="panelHeader infoPanelGroup" colspan="2">' . $messages["meta.serial.1"] . '</div>
						<table class="infoPanelTable" cellspacing="0" border="0" cellpadding="0">';
        $cdataFoot = '</table></div>';
        $cdataParts = "";
        $selection = $this->xPath->query('registry_contributions/client_configs/component_config[@className="FilesList"]/columns');
        $contrib = $selection->item(0);
        $even = false;
        $searchables = array();
        foreach ($def as $key => $label) {
            $col = $this->manifestDoc->createElement("additional_column");
            $col->setAttribute("messageString", $label);
            $col->setAttribute("attributeName", $key);
            $col->setAttribute("sortType", "String");
            if ($key == "stars_rate") {
                $col->setAttribute("modifier", "MetaCellRenderer.prototype.starsRateFilter");
                $col->setAttribute("sortType", "CellSorterValue");
            } else {
                if ($key == "css_label") {
                    $col->setAttribute("modifier", "MetaCellRenderer.prototype.cssLabelsFilter");
                    $col->setAttribute("sortType", "CellSorterValue");
                } else {
                    $searchables[$key] = $label;
                }
            }
            $contrib->appendChild($col);
            $trClass = $even ? " class=\"even\"" : "";
            $even = !$even;
            $cdataParts .= '<tr' . $trClass . '><td class="infoPanelLabel">' . $label . '</td><td class="infoPanelValue" id="ip_' . $key . '">#{' . $key . '}</td></tr>';
        }
        $selection = $this->xPath->query('registry_contributions/client_configs/component_config[@className="InfoPanel"]/infoPanelExtension');
        $contrib = $selection->item(0);
        $contrib->setAttribute("attributes", implode(",", array_keys($def)));
        if (isset($def["stars_rate"]) || isset($def["css_label"])) {
            $contrib->setAttribute("modifier", "MetaCellRenderer.prototype.infoPanelModifier");
        }
        $htmlSel = $this->xPath->query('html', $contrib);
        $html = $htmlSel->item(0);
        $cdata = $this->manifestDoc->createCDATASection($cdataHead . $cdataParts . $cdataFoot);
        $html->appendChild($cdata);
        $selection = $this->xPath->query('registry_contributions/client_configs/template_part[@ajxpClass="SearchEngine"]');
        $tag = $selection->item(0);
        $tag->setAttribute("ajxpOptions", json_encode(count($searchables) ? array("metaColumns" => $searchables) : array()));
        parent::init($this->options);
    }
Пример #8
0
 function errorToXml($mixed)
 {
     if (is_a($mixed, "AJXP_Exception")) {
         $messages = ConfService::getMessages();
         $error = "Unkown Error";
         if (isset($mixed->messageId) && array_key_exists($mixed->messageId, $messages)) {
             $error = $messages[$mixed->messageId];
         } else {
             $error = $mixed->messageId;
         }
         AJXP_XMLWriter::header();
         AJXP_XMLWriter::sendMessage(null, $error);
         AJXP_XMLWriter::close();
         exit(1);
     }
 }
 /**
  * @param AJXP_Node $node
  * @param int $newSize
  * @return mixed
  * @throws Exception
  */
 public function precheckQuotaUsage($node, $newSize = 0)
 {
     // POSITIVE DELTA ?
     if ($newSize == 0) {
         return null;
     }
     $delta = $newSize;
     $quota = $this->getAuthorized();
     $path = $this->getWorkingPath();
     $q = $this->getUsage($path);
     AJXP_Logger::debug("QUOTA : Previous usage was {$q}");
     if ($q === false) {
         $q = $this->computeDirSpace($path);
     }
     if ($q + $delta >= $quota) {
         $mess = ConfService::getMessages();
         throw new Exception($mess["meta.quota.3"] . " (" . AJXP_Utils::roundSize($quota) . ")!");
     }
 }
 /**
  * @param String $action
  * @param Array $httpVars
  * @param Array $fileVars
  * @throws Exception
  */
 public function receiveAction($action, $httpVars, $fileVars)
 {
     //VAR CREATION OUTSIDE OF ALL CONDITIONS, THEY ARE "MUST HAVE" VAR !!
     $messages = ConfService::getMessages();
     $repository = ConfService::getRepository();
     $userSelection = new UserSelection($repository, $httpVars);
     $nodes = $userSelection->buildNodes();
     $currentDirPath = AJXP_Utils::safeDirname($userSelection->getUniqueNode()->getPath());
     $currentDirPath = rtrim($currentDirPath, "/") . "/";
     $currentDirUrl = $userSelection->currentBaseUrl() . $currentDirPath;
     if (empty($httpVars["compression_id"])) {
         $compressionId = sha1(rand());
         $httpVars["compression_id"] = $compressionId;
     } else {
         $compressionId = $httpVars["compression_id"];
     }
     $progressCompressionFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressCompressionID-" . $compressionId . ".txt";
     if (empty($httpVars["extraction_id"])) {
         $extractId = sha1(rand());
         $httpVars["extraction_id"] = $extractId;
     } else {
         $extractId = $httpVars["extraction_id"];
     }
     $progressExtractFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressExtractID-" . $extractId . ".txt";
     if ($action == "compression") {
         $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
         $archiveFormat = $httpVars["type_archive"];
         $tabTypeArchive = array(".tar", ".tar.gz", ".tar.bz2");
         $acceptedExtension = false;
         foreach ($tabTypeArchive as $extensionArchive) {
             if ($extensionArchive == $archiveFormat) {
                 $acceptedExtension = true;
                 break;
             }
         }
         if ($acceptedExtension == false) {
             file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.16"]);
             throw new AJXP_Exception($messages["compression.16"]);
         }
         $typeArchive = $httpVars["type_archive"];
         //if we can run in background we do it
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             $archivePath = $currentDirPath . $archiveName;
             file_put_contents($progressCompressionFileName, $messages["compression.5"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "compression", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $messages["compression.5"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         } else {
             $maxAuthorizedSize = 4294967296;
             $currentDirUrlLength = strlen($currentDirUrl);
             $tabFolders = array();
             $tabAllRecursiveFiles = array();
             $tabFilesNames = array();
             foreach ($nodes as $node) {
                 $nodeUrl = $node->getUrl();
                 if (is_file($nodeUrl) && filesize($nodeUrl) < $maxAuthorizedSize) {
                     array_push($tabAllRecursiveFiles, $nodeUrl);
                     array_push($tabFilesNames, substr($nodeUrl, $currentDirUrlLength));
                 }
                 if (is_dir($nodeUrl)) {
                     array_push($tabFolders, $nodeUrl);
                 }
             }
             //DO A FOREACH OR IT'S GONNA HAVE SOME SAMES FILES NAMES
             foreach ($tabFolders as $value) {
                 $dossiers = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($value));
                 foreach ($dossiers as $file) {
                     if ($file->isDir()) {
                         continue;
                     }
                     array_push($tabAllRecursiveFiles, $file->getPathname());
                     array_push($tabFilesNames, substr($file->getPathname(), $currentDirUrlLength));
                 }
             }
             //WE STOP IF IT'S JUST AN EMPTY FOLDER OR NO FILES
             if (empty($tabFilesNames)) {
                 file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.17"]);
                 throw new AJXP_Exception($messages["compression.17"]);
             }
             try {
                 $tmpArchiveName = tempnam(AJXP_Utils::getAjxpTmpDir(), "tar-compression") . ".tar";
                 $archive = new PharData($tmpArchiveName);
             } catch (Exception $e) {
                 file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                 throw $e;
             }
             $counterCompression = 0;
             //THE TWO ARRAY ARE MERGED FOR THE FOREACH LOOP
             $tabAllFiles = array_combine($tabAllRecursiveFiles, $tabFilesNames);
             foreach ($tabAllFiles as $fullPath => $fileName) {
                 try {
                     $archive->addFile(AJXP_MetaStreamWrapper::getRealFSReference($fullPath), $fileName);
                     $counterCompression++;
                     file_put_contents($progressCompressionFileName, sprintf($messages["compression.6"], round($counterCompression / count($tabAllFiles) * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
                 } catch (Exception $e) {
                     unlink($tmpArchiveName);
                     file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                     throw $e;
                 }
             }
             $finalArchive = $tmpArchiveName;
             if ($typeArchive != ".tar") {
                 $archiveTypeCompress = substr(strrchr($typeArchive, "."), 1);
                 file_put_contents($progressCompressionFileName, sprintf($messages["compression.7"], strtoupper($archiveTypeCompress)));
                 if ($archiveTypeCompress == "gz") {
                     $archive->compress(Phar::GZ);
                 } elseif ($archiveTypeCompress == "bz2") {
                     $archive->compress(Phar::BZ2);
                 }
                 $finalArchive = $tmpArchiveName . "." . $archiveTypeCompress;
             }
             $destArchive = AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $archiveName);
             rename($finalArchive, $destArchive);
             AJXP_Controller::applyHook("node.before_create", array($destArchive, filesize($destArchive)));
             if (file_exists($tmpArchiveName)) {
                 unlink($tmpArchiveName);
                 unlink(substr($tmpArchiveName, 0, -4));
             }
             $newNode = new AJXP_Node($currentDirUrl . $archiveName);
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             file_put_contents($progressCompressionFileName, "SUCCESS");
         }
     } elseif ($action == "check_compression_status") {
         $archivePath = AJXP_Utils::decodeSecureMagic($httpVars["archive_path"]);
         $progressCompression = file_get_contents($progressCompressionFileName);
         $substrProgressCompression = substr($progressCompression, 0, 5);
         if ($progressCompression != "SUCCESS" && $substrProgressCompression != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $progressCompression, true, 5);
             AJXP_XMLWriter::close();
         } elseif ($progressCompression == "SUCCESS") {
             $newNode = new AJXP_Node($userSelection->currentBaseUrl() . $archivePath);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($messages["compression.8"], null);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         } elseif ($substrProgressCompression == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressCompression);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         }
     } elseif ($action == "extraction") {
         $fileArchive = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["file"]), AJXP_SANITIZE_DIRNAME);
         $fileArchive = substr(strrchr($fileArchive, DIRECTORY_SEPARATOR), 1);
         $authorizedExtension = array("tar" => 4, "gz" => 7, "bz2" => 8);
         $acceptedArchive = false;
         $extensionLength = 0;
         $counterExtract = 0;
         $currentAllPydioPath = $currentDirUrl . $fileArchive;
         $pharCurrentAllPydioPath = "phar://" . AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath);
         $pathInfoCurrentAllPydioPath = pathinfo($currentAllPydioPath, PATHINFO_EXTENSION);
         //WE TAKE ONLY TAR, TAR.GZ AND TAR.BZ2 ARCHIVES
         foreach ($authorizedExtension as $extension => $strlenExtension) {
             if ($pathInfoCurrentAllPydioPath == $extension) {
                 $acceptedArchive = true;
                 $extensionLength = $strlenExtension;
                 break;
             }
         }
         if ($acceptedArchive == false) {
             file_put_contents($progressExtractFileName, "Error : " . $messages["compression.15"]);
             throw new AJXP_Exception($messages["compression.15"]);
         }
         $onlyFileName = substr($fileArchive, 0, -$extensionLength);
         $lastPosOnlyFileName = strrpos($onlyFileName, "-");
         $tmpOnlyFileName = substr($onlyFileName, 0, $lastPosOnlyFileName);
         $counterDuplicate = substr($onlyFileName, $lastPosOnlyFileName + 1);
         if (!is_int($lastPosOnlyFileName) || !is_int($counterDuplicate)) {
             $tmpOnlyFileName = $onlyFileName;
             $counterDuplicate = 1;
         }
         while (file_exists($currentDirUrl . $onlyFileName)) {
             $onlyFileName = $tmpOnlyFileName . "-" . $counterDuplicate;
             $counterDuplicate++;
         }
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             file_put_contents($progressExtractFileName, $messages["compression.12"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "extraction", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $messages["compression.12"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         }
         mkdir($currentDirUrl . $onlyFileName, 0777, true);
         chmod(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), 0777);
         try {
             $archive = new PharData(AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath));
             $fichiersArchive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharCurrentAllPydioPath));
             foreach ($fichiersArchive as $file) {
                 $fileGetPathName = $file->getPathname();
                 if ($file->isDir()) {
                     continue;
                 }
                 $fileNameInArchive = substr(strstr($fileGetPathName, $fileArchive), strlen($fileArchive) + 1);
                 try {
                     $archive->extractTo(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), $fileNameInArchive, false);
                 } catch (Exception $e) {
                     file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
                     throw new AJXP_Exception($e);
                 }
                 $counterExtract++;
                 file_put_contents($progressExtractFileName, sprintf($messages["compression.13"], round($counterExtract / $archive->count() * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
             }
         } catch (Exception $e) {
             file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
             throw new AJXP_Exception($e);
         }
         file_put_contents($progressExtractFileName, "SUCCESS");
         $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
         AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array());
     } elseif ($action == "check_extraction_status") {
         $currentDirUrl = $httpVars["currentDirUrl"];
         $onlyFileName = $httpVars["onlyFileName"];
         $progressExtract = file_get_contents($progressExtractFileName);
         $substrProgressExtract = substr($progressExtract, 0, 5);
         if ($progressExtract != "SUCCESS" && $progressExtract != "INDEX" && $substrProgressExtract != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $progressExtract, true, 4);
             AJXP_XMLWriter::close();
         } elseif ($progressExtract == "SUCCESS") {
             $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(sprintf($messages["compression.14"], $onlyFileName), null);
             AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $newNode->getRepositoryId()), "starting indexation", true, 5);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         } elseif ($substrProgressExtract == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressExtract);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         }
     }
 }
Пример #11
0
 /**
  * Send a <reload> XML instruction for refreshing the list
  * @static
  * @param $diffNodes
  * @param bool $print
  * @return string
  */
 public static function writeNodesDiff($diffNodes, $print = false)
 {
     /**
      * @var $ajxpNode AJXP_Node
      */
     $mess = ConfService::getMessages();
     $buffer = "<nodes_diff>";
     if (isset($diffNodes["REMOVE"]) && count($diffNodes["REMOVE"])) {
         $buffer .= "<remove>";
         foreach ($diffNodes["REMOVE"] as $nodePath) {
             $nodePath = AJXP_Utils::xmlEntities($nodePath, true);
             $buffer .= "<tree filename=\"{$nodePath}\" ajxp_im_time=\"" . time() . "\"/>";
         }
         $buffer .= "</remove>";
     }
     if (isset($diffNodes["ADD"]) && count($diffNodes["ADD"])) {
         $buffer .= "<add>";
         foreach ($diffNodes["ADD"] as $ajxpNode) {
             $ajxpNode->loadNodeInfo(false, false, "all");
             if (!empty($ajxpNode->metaData["mimestring_id"]) && array_key_exists($ajxpNode->metaData["mimestring_id"], $mess)) {
                 $ajxpNode->mergeMetadata(array("mimestring" => $mess[$ajxpNode->metaData["mimestring_id"]]));
             }
             $buffer .= self::renderAjxpNode($ajxpNode, true, false);
         }
         $buffer .= "</add>";
     }
     if (isset($diffNodes["UPDATE"]) && count($diffNodes["UPDATE"])) {
         $buffer .= "<update>";
         foreach ($diffNodes["UPDATE"] as $originalPath => $ajxpNode) {
             $ajxpNode->loadNodeInfo(false, false, "all");
             if (!empty($ajxpNode->metaData["mimestring_id"]) && array_key_exists($ajxpNode->metaData["mimestring_id"], $mess)) {
                 $ajxpNode->mergeMetadata(array("mimestring" => $mess[$ajxpNode->metaData["mimestring_id"]]));
             }
             $ajxpNode->original_path = $originalPath;
             $buffer .= self::renderAjxpNode($ajxpNode, true, false);
         }
         $buffer .= "</update>";
     }
     $buffer .= "</nodes_diff>";
     return AJXP_XMLWriter::write($buffer, $print);
     /*
     $nodePath = AJXP_Utils::xmlEntities($nodePath, true);
     $pendingSelection = AJXP_Utils::xmlEntities($pendingSelection, true);
     return AJXP_XMLWriter::write("<reload_instruction object=\"data\" node=\"$nodePath\" file=\"$pendingSelection\"/>", $print);
     */
 }
Пример #12
0
 public function applyActions($actionName, $httpVars, $fileVars)
 {
     $git = new VersionControl_Git($this->repoBase);
     switch ($actionName) {
         case "git_history":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $file = ltrim($file, "/");
             $res = $this->gitHistory($git, $file);
             AJXP_XMLWriter::header();
             $ic = AJXP_Utils::mimetype($file, "image", false);
             $index = count($res);
             $mess = ConfService::getMessages();
             foreach ($res as &$commit) {
                 unset($commit["DETAILS"]);
                 $commit["icon"] = $ic;
                 $commit["index"] = $index;
                 $commit["EVENT"] = $mess["meta.git." . $commit["EVENT"]];
                 $index--;
                 AJXP_XMLWriter::renderNode("/" . $commit["ID"], basename($commit["FILE"]), true, $commit);
             }
             AJXP_XMLWriter::close();
             break;
             break;
         case "git_revertfile":
             $originalFile = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]);
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $commitId = $httpVars["commit_id"];
             $command = $git->getCommand("cat-file");
             $command->setOption("s", true);
             $command->addArgument($commitId . ":" . $file);
             $size = $command->execute();
             $command = $git->getCommand("show");
             $command->addArgument($commitId . ":" . $file);
             $commandLine = $command->createCommandString();
             $outputStream = fopen($this->repoBase . $originalFile, "w");
             $this->executeCommandInStreams($git, $commandLine, $outputStream);
             fclose($outputStream);
             $this->commitChanges();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "git_getfile":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $commitId = $httpVars["commit_id"];
             $attach = $httpVars["attach"];
             $command = $git->getCommand("cat-file");
             $command->setOption("s", true);
             $command->addArgument($commitId . ":" . $file);
             $size = $command->execute();
             $command = $git->getCommand("show");
             $command->addArgument($commitId . ":" . $file);
             $commandLine = $command->createCommandString();
             if ($attach == "inline") {
                 $fileExt = substr(strrchr(basename($file), '.'), 1);
                 if (empty($fileExt)) {
                     $fileMime = "application/octet-stream";
                 } else {
                     $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i";
                     $lines = file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.browser/resources/other/mime.types");
                     foreach ($lines as $line) {
                         if (substr($line, 0, 1) == '#') {
                             continue;
                         }
                         // skip comments
                         $line = rtrim($line) . " ";
                         if (!preg_match($regex, $line, $matches)) {
                             continue;
                         }
                         // no match to the extension
                         $fileMime = $matches[1];
                     }
                 }
                 if (empty($fileMime)) {
                     $fileMime = "application/octet-stream";
                 }
                 HTMLWriter::generateInlineHeaders(basename($file), $size, $fileMime);
             } else {
                 HTMLWriter::generateAttachmentsHeader(basename($file), $size, false, false);
             }
             $outputStream = fopen("php://output", "a");
             $this->executeCommandInStreams($git, $commandLine, $outputStream);
             fclose($outputStream);
             break;
             break;
         default:
             break;
     }
 }
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
         // Force legacy theme for the moment
         $this->pluginConf["GUI_THEME"] = "oxygen";
     }
     if (!defined("AJXP_THEME_FOLDER")) {
         define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
         define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $this->pluginConf["GUI_THEME"]);
     }
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = AJXP_Utils::securePath($getValue);
     }
     if (isset($dir) && $action != "upload") {
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	GET AN HTML TEMPLATE
         //------------------------------------
         case "get_template":
             HTMLWriter::charsetHeader();
             $folder = CLIENT_RESOURCES_FOLDER . "/html";
             if (isset($httpVars["pluginName"])) {
                 $folder = AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/" . AJXP_Utils::securePath($httpVars["pluginName"]);
                 if (isset($httpVars["pluginPath"])) {
                     $folder .= "/" . AJXP_Utils::securePath($httpVars["pluginPath"]);
                 }
             }
             $crtTheme = $this->pluginConf["GUI_THEME"];
             $thFolder = AJXP_THEME_FOLDER . "/html";
             if (isset($template_name)) {
                 if (is_file($thFolder . "/" . $template_name)) {
                     include $thFolder . "/" . $template_name;
                 } else {
                     if (is_file($folder . "/" . $template_name)) {
                         include $folder . "/" . $template_name;
                     }
                 }
             }
             break;
             //------------------------------------
             //	GET I18N MESSAGES
             //------------------------------------
         //------------------------------------
         //	GET I18N MESSAGES
         //------------------------------------
         case "get_i18n_messages":
             $refresh = false;
             if (isset($httpVars["lang"])) {
                 ConfService::setLanguage($httpVars["lang"]);
                 $refresh = true;
             }
             HTMLWriter::charsetHeader('text/javascript');
             HTMLWriter::writeI18nMessagesClass(ConfService::getMessages($refresh));
             break;
             //------------------------------------
             //	SEND XML REGISTRY
             //------------------------------------
         //------------------------------------
         //	SEND XML REGISTRY
         //------------------------------------
         case "get_xml_registry":
             $regDoc = AJXP_PluginsService::getXmlRegistry();
             $changes = AJXP_Controller::filterActionsRegistry($regDoc);
             if ($changes) {
                 AJXP_PluginsService::updateXmlRegistry($regDoc);
             }
             if (isset($_GET["xPath"])) {
                 $regPath = new DOMXPath($regDoc);
                 $nodes = $regPath->query($_GET["xPath"]);
                 AJXP_XMLWriter::header("ajxp_registry_part", array("xPath" => $_GET["xPath"]));
                 if ($nodes->length) {
                     print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML($nodes->item(0)));
                 }
                 AJXP_XMLWriter::close("ajxp_registry_part");
             } else {
                 AJXP_Utils::safeIniSet("zlib.output_compression", "4096");
                 header('Content-Type: application/xml; charset=UTF-8');
                 print AJXP_XMLWriter::replaceAjxpXmlKeywords($regDoc->saveXML());
             }
             break;
             //------------------------------------
             //	DISPLAY DOC
             //------------------------------------
         //------------------------------------
         //	DISPLAY DOC
         //------------------------------------
         case "display_doc":
             HTMLWriter::charsetHeader();
             echo HTMLWriter::getDocFile(AJXP_Utils::securePath(htmlentities($_GET["doc_file"])));
             break;
             //------------------------------------
             //	GET BOOT GUI
             //------------------------------------
         //------------------------------------
         //	GET BOOT GUI
         //------------------------------------
         case "get_boot_gui":
             header("X-UA-Compatible: chrome=1");
             HTMLWriter::charsetHeader();
             if (!is_file(TESTS_RESULT_FILE)) {
                 $outputArray = array();
                 $testedParams = array();
                 $passed = AJXP_Utils::runTests($outputArray, $testedParams);
                 if (!$passed && !isset($_GET["ignore_tests"])) {
                     die(AJXP_Utils::testResultsToTable($outputArray, $testedParams));
                 } else {
                     AJXP_Utils::testResultsToFile($outputArray, $testedParams);
                 }
             }
             $START_PARAMETERS = array("BOOTER_URL" => "index.php?get_action=get_boot_conf", "MAIN_ELEMENT" => "ajxp_desktop");
             if (AuthService::usersEnabled()) {
                 AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : "");
                 AuthService::bootSequence($START_PARAMETERS);
                 if (AuthService::getLoggedUser() != null || AuthService::logUser(null, null) == 1) {
                     if (AuthService::getDefaultRootId() == -1) {
                         AuthService::disconnect();
                     } else {
                         $loggedUser = AuthService::getLoggedUser();
                         if (!$loggedUser->canRead(ConfService::getCurrentRootDirIndex()) && AuthService::getDefaultRootId() != ConfService::getCurrentRootDirIndex()) {
                             ConfService::switchRootDir(AuthService::getDefaultRootId());
                         }
                     }
                 }
             }
             AJXP_Utils::parseApplicationGetParameters($_GET, $START_PARAMETERS, $_SESSION);
             $confErrors = ConfService::getErrors();
             if (count($confErrors)) {
                 $START_PARAMETERS["ALERT"] = implode(", ", array_values($confErrors));
             }
             $JSON_START_PARAMETERS = json_encode($START_PARAMETERS);
             $crtTheme = $this->pluginConf["GUI_THEME"];
             if (ConfService::getConf("JS_DEBUG")) {
                 if (!isset($mess)) {
                     $mess = ConfService::getMessages();
                 }
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html")) {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui_debug.html";
                 } else {
                     include AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui_debug.html";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html")) {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/themes/{$crtTheme}/html/gui.html");
                 } else {
                     $content = file_get_contents(AJXP_INSTALL_PATH . "/plugins/gui.ajax/res/html/gui.html");
                 }
                 if (preg_match('/MSIE 7/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/MSIE 8/', $_SERVER['HTTP_USER_AGENT'])) {
                     $content = str_replace("ajaxplorer_boot.js", "ajaxplorer_boot_protolegacy.js", $content);
                 }
                 $content = AJXP_XMLWriter::replaceAjxpXmlKeywords($content, false);
                 if ($JSON_START_PARAMETERS) {
                     $content = str_replace("//AJXP_JSON_START_PARAMETERS", "startParameters = " . $JSON_START_PARAMETERS . ";", $content);
                 }
                 print $content;
             }
             break;
             //------------------------------------
             //	GET CONFIG FOR BOOT
             //------------------------------------
         //------------------------------------
         //	GET CONFIG FOR BOOT
         //------------------------------------
         case "get_boot_conf":
             if (isset($_GET["server_prefix_uri"])) {
                 $_SESSION["AJXP_SERVER_PREFIX_URI"] = $_GET["server_prefix_uri"];
             }
             $config = array();
             $config["ajxpResourcesFolder"] = "plugins/gui.ajax/res";
             $config["ajxpServerAccess"] = AJXP_SERVER_ACCESS;
             $config["zipEnabled"] = ConfService::zipEnabled();
             $config["multipleFilesDownloadEnabled"] = ConfService::getCoreConf("ZIP_CREATION");
             $config["customWording"] = array("welcomeMessage" => $this->pluginConf["CUSTOM_WELCOME_MESSAGE"], "title" => ConfService::getCoreConf("APPLICATION_TITLE"), "icon" => $this->pluginConf["CUSTOM_ICON"], "iconWidth" => $this->pluginConf["CUSTOM_ICON_WIDTH"], "iconHeight" => $this->pluginConf["CUSTOM_ICON_HEIGHT"], "iconOnly" => $this->pluginConf["CUSTOM_ICON_ONLY"], "titleFontSize" => $this->pluginConf["CUSTOM_FONT_SIZE"]);
             $config["usersEnabled"] = AuthService::usersEnabled();
             $config["loggedUser"] = AuthService::getLoggedUser() != null;
             $config["currentLanguage"] = ConfService::getLanguage();
             $config["session_timeout"] = intval(ini_get("session.gc_maxlifetime"));
             if (!isset($this->pluginConf["CLIENT_TIMEOUT_TIME"]) || $this->pluginConf["CLIENT_TIMEOUT_TIME"] == "") {
                 $to = $config["session_timeout"];
             } else {
                 $to = $this->pluginConf["CLIENT_TIMEOUT_TIME"];
             }
             $config["client_timeout"] = $to;
             $config["client_timeout_warning"] = $this->pluginConf["CLIENT_TIMEOUT_WARN"];
             $config["availableLanguages"] = ConfService::getConf("AVAILABLE_LANG");
             $config["usersEditable"] = ConfService::getAuthDriverImpl()->usersEditable();
             $config["ajxpVersion"] = AJXP_VERSION;
             $config["ajxpVersionDate"] = AJXP_VERSION_DATE;
             if (stristr($_SERVER["HTTP_USER_AGENT"], "msie 6")) {
                 $config["cssResources"] = array("css/pngHack/pngHack.css");
             }
             if (!empty($this->pluginConf['GOOGLE_ANALYTICS_ID'])) {
                 $config["googleAnalyticsData"] = array("id" => $this->pluginConf['GOOGLE_ANALYTICS_ID'], "domain" => $this->pluginConf['GOOGLE_ANALYTICS_DOMAIN'], "event" => $this->pluginConf['GOOGLE_ANALYTICS_EVENT']);
             }
             $config["i18nMessages"] = ConfService::getMessages();
             $config["password_min_length"] = ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth");
             $config["SECURE_TOKEN"] = AuthService::generateSecureToken();
             $config["streaming_supported"] = "true";
             $config["theme"] = $this->pluginConf["GUI_THEME"];
             header("Content-type:application/json;charset=UTF-8");
             print json_encode($config);
             break;
         default:
             break;
     }
     return false;
 }
Пример #14
0
 function roundSize($filesize)
 {
     $mess = ConfService::getMessages();
     $size_unit = $mess["byte_unit_symbol"];
     if ($filesize < 0) {
         $filesize = sprintf("%u", $filesize);
     }
     if ($filesize >= 1073741824) {
         $filesize = round($filesize / 1073741824 * 100) / 100 . " G" . $size_unit;
     } elseif ($filesize >= 1048576) {
         $filesize = round($filesize / 1048576 * 100) / 100 . " M" . $size_unit;
     } elseif ($filesize >= 1024) {
         $filesize = round($filesize / 1024 * 100) / 100 . " K" . $size_unit;
     } else {
         $filesize = $filesize . " " . $size_unit;
     }
     if ($filesize == 0) {
         $filesize = "-";
     }
     return $filesize;
 }
 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;
 }
Пример #16
0
 /**
  * @return string
  */
 public function getDescriptionLong($skipLink = false)
 {
     $mess = ConfService::getMessages();
     if (count($this->relatedNotifications)) {
         $key = "notification.tpl.group." . ($this->getNode()->isLeaf() ? "file" : "folder") . "." . $this->action;
         $tpl = $this->replaceVars($mess[$key], $mess) . ": ";
         $tpl .= "<ul>";
         foreach ($this->relatedNotifications as $relatedNotification) {
             $tpl .= "<li>" . $relatedNotification->getDescriptionLong(true) . "</li>";
         }
         $tpl .= "</ul>";
     } else {
         $tpl = $this->replaceVars($mess["notification.tpl.long." . ($this->getNode()->isLeaf() ? "file" : "folder") . "." . $this->action], $mess);
     }
     if (!$skipLink) {
         $tpl .= "<br><br>" . $this->replaceVars($mess["notification.tpl.long.ajxp_link"], $mess);
     }
     return $tpl;
 }
Пример #17
0
 /**
  * @param ShareCenter $shareCenter
  * @param ShareStore $shareStore
  * @param ShareRightsManager $shareRightManager
  */
 public static function migrateLegacyMeta($shareCenter, $shareStore, $shareRightManager, $dryRun = true)
 {
     $metaStoreDir = AJXP_DATA_PATH . "/plugins/metastore.serial";
     $publicFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER");
     $metastores = glob($metaStoreDir . "/ajxp_meta_0");
     if ($dryRun) {
         print "RUNNING A DRY RUN FOR META MIGRATION";
     }
     foreach ($metastores as $store) {
         if (strpos($store, ".bak") !== false) {
             continue;
         }
         // Backup store
         if (!$dryRun) {
             copy($store, $store . ".bak");
         }
         $data = unserialize(file_get_contents($store));
         foreach ($data as $filePath => &$metadata) {
             foreach ($metadata as $userName => &$meta) {
                 if (!AuthService::userExists($userName)) {
                     continue;
                 }
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($userName);
                 if (isset($meta["ajxp_shared"]) && isset($meta["ajxp_shared"]["element"])) {
                     print "\n\nItem {$filePath} requires upgrade :";
                     $share = $meta["ajxp_shared"];
                     $element = $meta["ajxp_shared"]["element"];
                     if (is_array($element)) {
                         $element = array_shift(array_keys($element));
                     }
                     // Take the first one only
                     $legacyLinkFile = $publicFolder . "/" . $element . ".php";
                     if (file_exists($legacyLinkFile)) {
                         // Load file, move it to DB and move the meta
                         $publiclet = $shareStore->loadShare($element);
                         rename($legacyLinkFile, $legacyLinkFile . ".migrated");
                         if (isset($share["minisite"])) {
                             print "\n--Migrate legacy minisite to new minisite?";
                             try {
                                 $sharedRepoId = $publiclet["REPOSITORY"];
                                 $sharedRepo = ConfService::getRepositoryById($sharedRepoId);
                                 if ($sharedRepo == null) {
                                     print "\n--ERROR: Cannot find repository with id " . $sharedRepoId;
                                     continue;
                                 }
                                 $shareLink = new ShareLink($shareStore, $publiclet);
                                 $user = $shareLink->getUniqueUser();
                                 if (AuthService::userExists($user)) {
                                     $userObject = ConfService::getConfStorageImpl()->createUserObject($user);
                                     $userObject->setHidden(true);
                                     print "\n--Should set existing user {$user} as hidden";
                                     if (!$dryRun) {
                                         $userObject->save();
                                     }
                                 }
                                 $shareLink->parseHttpVars(["custom_handle" => $element]);
                                 $shareLink->setParentRepositoryId($sharedRepo->getParentId());
                                 print "\n--Creating the following share object";
                                 print_r($shareLink->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $shareLink->save();
                                 }
                                 $meta["ajxp_shared"] = ["shares" => [$element => ["type" => "minisite"], $sharedRepoId => ["type" => "repository"]]];
                             } catch (Exception $e) {
                                 print "\n-- Error " . $e->getMessage();
                             }
                         } else {
                             print "\n--Should migrate legacy link to new minisite with ContentFilter";
                             try {
                                 $link = new ShareLink($shareStore);
                                 $link->setOwnerId($userName);
                                 $parameters = array("custom_handle" => $element, "simple_right_download" => true);
                                 if (isset($publiclet["EXPIRE_TIME"])) {
                                     $parameters["expiration"] = $publiclet["EXPIRE_TIME"];
                                 }
                                 if (isset($publiclet["DOWNLOAD_LIMIT"])) {
                                     $parameters["downloadlimit"] = $publiclet["DOWNLOAD_LIMIT"];
                                 }
                                 $link->parseHttpVars($parameters);
                                 $parentRepositoryObject = $publiclet["REPOSITORY"];
                                 $driverInstance = AJXP_PluginsService::findPlugin("access", $parentRepositoryObject->getAccessType());
                                 if (empty($driverInstance)) {
                                     print "\n-- ERROR: Cannot find driver instance!";
                                     continue;
                                 }
                                 $options = $driverInstance->makeSharedRepositoryOptions(["file" => "/"], $parentRepositoryObject);
                                 $options["SHARE_ACCESS"] = "private";
                                 $newRepo = $parentRepositoryObject->createSharedChild(basename($filePath), $options, $parentRepositoryObject->getId(), $userObject->getId(), null);
                                 $gPath = $userObject->getGroupPath();
                                 if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
                                     $newRepo->setGroupPath($gPath);
                                 }
                                 $newRepo->setDescription("");
                                 // Smells like dirty hack!
                                 $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
                                 $newRepo->setContentFilter(new ContentFilter([new AJXP_Node("pydio://" . $parentRepositoryObject->getId() . $filePath)]));
                                 if (!$dryRun) {
                                     ConfService::addRepository($newRepo);
                                 }
                                 $hiddenUserEntry = $shareRightManager->prepareSharedUserEntry(["simple_right_read" => true, "simple_right_download" => true], $link, false, null);
                                 $selection = new UserSelection($parentRepositoryObject, []);
                                 $selection->addFile($filePath);
                                 if (!$dryRun) {
                                     $shareRightManager->assignSharedRepositoryPermissions($parentRepositoryObject, $newRepo, false, [$hiddenUserEntry["ID"] => $hiddenUserEntry], [], $selection);
                                 }
                                 $link->setParentRepositoryId($parentRepositoryObject->getId());
                                 $link->attachToRepository($newRepo->getId());
                                 print "\n-- Should save following LINK: ";
                                 print_r($link->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $hash = $link->save();
                                 }
                                 // UPDATE METADATA
                                 $meta["ajxp_shared"] = ["shares" => [$element => array("type" => "minisite")]];
                             } catch (Exception $e) {
                                 print "\n-- ERROR: " . $e->getMessage();
                             }
                         }
                         if ($dryRun) {
                             rename($legacyLinkFile . ".migrated", $legacyLinkFile);
                         }
                         continue;
                     } else {
                         //
                         // File does not exists, remove meta
                         //
                         unset($meta["ajxp_shared"]);
                     }
                     $repo = ConfService::getRepositoryById($element);
                     if ($repo !== null) {
                         print "\n--Shared repository: just metadata";
                         // Shared repo, migrating the meta should be enough
                         $meta["ajxp_shared"] = array("shares" => [$element => array("type" => "repository")]);
                     }
                 }
             }
         }
         print "\n\n SHOULD NOW UPDATE METADATA WITH FOLLOWING :";
         print_r($data);
         if (!$dryRun) {
             file_put_contents($store, serialize($data));
         }
     }
 }
Пример #18
0
 /**
  * Display a human readable string for a bytesize (1MB, 2,3Go, etc)
  * @static
  * @param $filesize
  * @param bool $phpConfig
  * @return string
  */
 public static function roundSize($filesize, $phpConfig = false)
 {
     if (self::$sizeUnit == null) {
         $mess = ConfService::getMessages();
         self::$sizeUnit = $mess["byte_unit_symbol"];
     }
     if ($filesize < 0) {
         $filesize = sprintf("%u", $filesize);
     }
     if ($filesize >= 1073741824) {
         $filesize = round($filesize / 1073741824 * 100) / 100 . ($phpConfig ? "G" : " G" . self::$sizeUnit);
     } elseif ($filesize >= 1048576) {
         $filesize = round($filesize / 1048576 * 100) / 100 . ($phpConfig ? "M" : " M" . self::$sizeUnit);
     } elseif ($filesize >= 1024) {
         $filesize = round($filesize / 1024 * 100) / 100 . ($phpConfig ? "K" : " K" . self::$sizeUnit);
     } else {
         $filesize = $filesize . " " . self::$sizeUnit;
     }
     if ($filesize == 0) {
         $filesize = "-";
     }
     return $filesize;
 }
    function listUsers()
    {
        AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.6" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_shared.10" attributeName="repo_accesses" sortType="String"/></columns>');
        if (!ENABLE_USERS) {
            return;
        }
        $users = AuthService::listUsers();
        $mess = ConfService::getMessages();
        $loggedUser = AuthService::getLoggedUser();
        $repoList = ConfService::getRepositoriesList();
        $userArray = array();
        foreach ($users as $userIndex => $userObject) {
            $label = $userObject->getId();
            if (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->getId()) {
                continue;
            }
            if ($userObject->hasParent()) {
                $label = $userObject->getParent() . "000" . $label;
            }
            $userArray[$label] = $userObject;
        }
        ksort($userArray);
        foreach ($userArray as $userObject) {
            $isAdmin = $userObject->isAdmin();
            $userId = AJXP_Utils::xmlEntities($userObject->getId());
            $repoAccesses = array();
            foreach ($repoList as $repoObject) {
                if ($repoObject->hasOwner() && $repoObject->getOwner() == $loggedUser->getId()) {
                    if ($userObject->canWrite($repoObject->getId())) {
                        $repoAccesses[] = $repoObject->getDisplay() . " (rw)";
                    } else {
                        if ($userObject->canRead($repoObject->getId())) {
                            $repoAccesses[] = $repoObject->getDisplay() . " (r)";
                        }
                    }
                }
            }
            print '<tree 
				text="' . $userId . '"
				isAdmin="' . $mess[$isAdmin ? "ajxp_conf.14" : "ajxp_conf.15"] . '" 
				icon="user_shared.png" 
				openicon="user_shared.png" 
				filename="/users/' . $userId . '" 
				repo_accesses="' . implode(", ", $repoAccesses) . '"
				parentname="/users" 
				is_file="1" 
				ajxp_mime="shared_user"
				/>';
        }
    }
Пример #20
0
 function replaceAjxpXmlKeywords($xml)
 {
     $messages = ConfService::getMessages();
     $matches = array();
     $xml = str_replace("AJXP_CLIENT_RESOURCES_FOLDER", CLIENT_RESOURCES_FOLDER, $xml);
     $xml = str_replace("AJXP_SERVER_ACCESS", SERVER_ACCESS, $xml);
     $xml = str_replace("AJXP_MIMES_EDITABLE", Utils::getAjxpMimes("editable"), $xml);
     $xml = str_replace("AJXP_MIMES_IMAGE", Utils::getAjxpMimes("image"), $xml);
     $xml = str_replace("AJXP_MIMES_AUDIO", Utils::getAjxpMimes("audio"), $xml);
     $xml = str_replace("AJXP_MIMES_ZIP", Utils::getAjxpMimes("zip"), $xml);
     if (preg_match_all("/AJXP_MESSAGE(\\[.*?\\])/", $xml, $matches, PREG_SET_ORDER)) {
         foreach ($matches as $match) {
             $messId = str_replace("]", "", str_replace("[", "", $match[1]));
             $xml = str_replace("AJXP_MESSAGE[{$messId}]", $messages[$messId], $xml);
         }
     }
     return $xml;
 }
Пример #21
0
 function copyOrMoveFile($destDir, $srcFile, &$error, &$success, $move = false)
 {
     $mess = ConfService::getMessages();
     $destFile = $this->repository->getOption("PATH") . $destDir . "/" . basename($srcFile);
     $realSrcFile = $this->repository->getOption("PATH") . "{$srcFile}";
     $recycle = $this->repository->getOption("RECYCLE_BIN");
     if (!file_exists($realSrcFile)) {
         $error[] = $mess[100] . $srcFile;
         return;
     }
     if (dirname($realSrcFile) == dirname($destFile)) {
         if ($move) {
             $error[] = $mess[101];
             return;
         } else {
             $base = basename($srcFile);
             $i = 1;
             if (is_file($realSrcFile)) {
                 $dotPos = strrpos($base, ".");
                 if ($dotPos > -1) {
                     $radic = substr($base, 0, $dotPos);
                     $ext = substr($base, $dotPos);
                 }
             }
             // auto rename file
             $i = 1;
             $newName = $base;
             while (file_exists($this->repository->getOption("PATH") . $destDir . "/" . $newName)) {
                 $suffix = "-{$i}";
                 if (isset($radic)) {
                     $newName = $radic . $suffix . $ext;
                 } else {
                     $newName = $base . $suffix;
                 }
                 $i++;
             }
             $destFile = $this->repository->getOption("PATH") . $destDir . "/" . $newName;
         }
     }
     if (is_dir($realSrcFile)) {
         $errors = array();
         $succFiles = array();
         if ($move) {
             if (is_file($destFile)) {
                 unlink($destFile);
             }
             $res = rename($realSrcFile, $destFile);
         } else {
             $dirRes = $this->dircopy($realSrcFile, $destFile, $errors, $succFiles);
         }
         if (count($errors) || isset($res) && $res !== true) {
             $error[] = $mess[114];
             return;
         }
     } else {
         if ($move) {
             if (is_file($destFile)) {
                 unlink($destFile);
             }
             $res = rename($realSrcFile, $destFile);
         } else {
             $res = copy($realSrcFile, $destFile);
         }
         if ($res != 1) {
             $error[] = $mess[114];
             return;
         }
     }
     if ($move) {
         // Now delete original
         // $this->deldir($realSrcFile); // both file and dir
         $messagePart = $mess[74] . " " . SystemTextEncoding::toUTF8($destDir);
         if (RecycleBinManager::recycleEnabled() && $destDir == "/" . $recycle) {
             RecycleBinManager::fileToRecycle($srcFile);
             $messagePart = $mess[123] . " " . $mess[122];
         }
         if (isset($dirRes)) {
             $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ") ";
         } else {
             $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart;
         }
     } else {
         if (RecycleBinManager::recycleEnabled() && $destDir == "/" . $this->repository->getOption("RECYCLE_BIN")) {
             RecycleBinManager::fileToRecycle($srcFile);
         }
         if (isset($dirRes)) {
             $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir) . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ")";
         } else {
             $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir);
         }
     }
 }
Пример #22
0
 /**
  * @param String $type
  * @param String $element
  * @throws Exception
  * @return bool
  */
 public function deleteShare($type, $element)
 {
     $mess = ConfService::getMessages();
     AJXP_Logger::debug(__CLASS__, __FILE__, "Deleting shared element " . $type . "-" . $element);
     if ($type == "repository") {
         if (strpos($element, "repo-") === 0) {
             $element = str_replace("repo-", "", $element);
         }
         $repo = ConfService::getRepositoryById($element);
         if ($repo == null) {
             // Maybe a share has
             $share = $this->loadShare($element);
             if (is_array($share) && isset($share["REPOSITORY"])) {
                 $repo = ConfService::getRepositoryById($share["REPOSITORY"]);
             }
             if ($repo == null) {
                 throw new Exception("Cannot find associated share");
             }
             $element = $share["REPOSITORY"];
         }
         $this->testUserCanEditShare($repo->getOwner());
         $res = ConfService::deleteRepository($element);
         if ($res == -1) {
             throw new Exception($mess[427]);
         }
         if ($this->sqlSupported) {
             if (isset($share)) {
                 $this->confStorage->simpleStoreClear("share", $element);
             } else {
                 $shares = self::findSharesForRepo($element);
                 if (count($shares)) {
                     $keys = array_keys($shares);
                     $this->confStorage->simpleStoreClear("share", $keys[0]);
                 }
             }
         }
     } else {
         if ($type == "minisite") {
             $minisiteData = $this->loadShare($element);
             $repoId = $minisiteData["REPOSITORY"];
             $repo = ConfService::getRepositoryById($repoId);
             if ($repo == null) {
                 return false;
             }
             $this->testUserCanEditShare($repo->getOwner());
             $res = ConfService::deleteRepository($repoId);
             if ($res == -1) {
                 throw new Exception($mess[427]);
             }
             // Silently delete corresponding role if it exists
             AuthService::deleteRole("AJXP_SHARED-" . $repoId);
             // If guest user created, remove it now.
             if (isset($minisiteData["PRELOG_USER"]) && AuthService::userExists($minisiteData["PRELOG_USER"])) {
                 AuthService::deleteUser($minisiteData["PRELOG_USER"]);
             }
             // If guest user created, remove it now.
             if (isset($minisiteData["PRESET_LOGIN"]) && AuthService::userExists($minisiteData["PRESET_LOGIN"])) {
                 AuthService::deleteUser($minisiteData["PRESET_LOGIN"]);
             }
             if (isset($minisiteData["PUBLICLET_PATH"]) && is_file($minisiteData["PUBLICLET_PATH"])) {
                 unlink($minisiteData["PUBLICLET_PATH"]);
             } else {
                 if ($this->sqlSupported) {
                     $this->confStorage->simpleStoreClear("share", $element);
                 }
             }
         } else {
             if ($type == "user") {
                 $this->testUserCanEditShare($element);
                 AuthService::deleteUser($element);
             } else {
                 if ($type == "file") {
                     $publicletData = $this->loadShare($element);
                     if (isset($publicletData["OWNER_ID"]) && $this->testUserCanEditShare($publicletData["OWNER_ID"])) {
                         PublicletCounter::delete($element);
                         if (isset($publicletData["PUBLICLET_PATH"]) && is_file($publicletData["PUBLICLET_PATH"])) {
                             unlink($publicletData["PUBLICLET_PATH"]);
                         } else {
                             if ($this->sqlSupported) {
                                 $this->confStorage->simpleStoreClear("share", $element);
                             }
                         }
                     } else {
                         throw new Exception($mess["share_center.160"]);
                     }
                 }
             }
         }
     }
 }
 /**
  * @param AJXP_Node $node
  * @param int $newSize
  * @return mixed
  * @throws Exception
  */
 public function precheckQuotaUsage($node, $newSize = 0)
 {
     // POSITIVE DELTA ?
     if ($newSize == 0) {
         return null;
     }
     $delta = $newSize;
     $quota = $this->getAuthorized();
     $soft = $this->getSoftLimit();
     $q = $this->getUsage();
     $this->logDebug("QUOTA : Previous usage was {$q}");
     if ($q + $delta >= $quota) {
         $mess = ConfService::getMessages();
         throw new Exception($mess["meta.quota.3"] . " (" . AJXP_Utils::roundSize($quota) . ")!");
     } else {
         if ($soft !== false && $q + $delta >= $soft && $q <= $soft) {
             $this->sendSoftLimitAlert();
         }
     }
 }
Пример #24
0
        AJXP_XMLWriter::header();
        if (isset($loggingResult)) {
            AJXP_XMLWriter::loggingResult($loggingResult, $rememberLogin, $rememberPass);
        }
        AJXP_XMLWriter::sendUserData();
        AJXP_XMLWriter::close();
        exit(1);
    }
}
$loggedUser = AuthService::getLoggedUser();
if ($loggedUser != null) {
    if ($loggedUser->getPref("lang") != "") {
        ConfService::setLanguage($loggedUser->getPref("lang"));
    }
}
$mess = ConfService::getMessages();
foreach ($_GET as $getName => $getValue) {
    ${$getName} = Utils::securePath($getValue);
}
foreach ($_POST as $getName => $getValue) {
    ${$getName} = Utils::securePath($getValue);
}
$selection = new UserSelection();
$selection->initFromHttpVars();
if (isset($action) || isset($get_action)) {
    $action = isset($get_action) ? $get_action : $action;
} else {
    $action = "";
}
if (isset($dir) && $action != "upload") {
    $dir = SystemTextEncoding::fromUTF8($dir);
 public function uploadActions($action, $httpVars, $filesVars)
 {
     switch ($action) {
         case "trigger_remote_copy":
             if (!$this->hasFilesToCopy()) {
                 break;
             }
             $toCopy = $this->getFileNameToCopy();
             $this->logDebug("trigger_remote", $toCopy);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . $toCopy . " to remote server");
             AJXP_XMLWriter::close();
             exit(1);
             break;
         case "next_to_remote":
             if (!$this->hasFilesToCopy()) {
                 break;
             }
             $fData = $this->getNextFileToCopy();
             $nextFile = '';
             if ($this->hasFilesToCopy()) {
                 $nextFile = $this->getFileNameToCopy();
             }
             $crtRep = ConfService::getRepository();
             session_write_close();
             $secureToken = "";
             $httpClient = $this->getRemoteConnexion($secureToken);
             //$httpClient->setDebug(true);
             $postData = array("get_action" => "upload", "dir" => base64_encode($fData["destination"]), "secure_token" => $secureToken);
             $httpClient->postFile($crtRep->getOption("URI") . "?", $postData, "Filedata", $fData);
             if (strpos($httpClient->getHeader("content-type"), "text/xml") !== false && strpos($httpClient->getContent(), "require_auth") != false) {
                 $httpClient = $this->getRemoteConnexion($secureToken, true);
                 $postData["secure_token"] = $secureToken;
                 $httpClient->postFile($crtRep->getOption("URI"), $postData, "Filedata", $fData);
             }
             unlink($fData["tmp_name"]);
             $response = $httpClient->getContent();
             AJXP_XMLWriter::header();
             $this->logDebug("next_to_remote", $nextFile);
             if (intval($response) >= 400) {
                 AJXP_XMLWriter::sendMessage(null, "Error : " . intval($response));
             } else {
                 if ($nextFile != '') {
                     AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . SystemTextEncoding::toUTF8($nextFile) . " to remote server");
                 } else {
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Upload done, reloading client.");
                 }
             }
             AJXP_XMLWriter::close();
             exit(1);
             break;
         case "upload":
             $rep_source = AJXP_Utils::securePath("/" . $httpVars['dir']);
             $this->logDebug("Upload : rep_source ", array($rep_source));
             $logMessage = "";
             foreach ($filesVars as $boxName => $boxData) {
                 if (substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 $this->logDebug("Upload : rep_source ", array($rep_source));
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                     $errorCode = $err[0];
                     $errorMessage = $err[1];
                     break;
                 }
                 $boxData["destination"] = $rep_source;
                 $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($this->repository->getOption("TMP_UPLOAD"));
                 $this->logDebug("Upload : tmp upload folder", array($destCopy));
                 if (!is_dir($destCopy)) {
                     if (!@mkdir($destCopy)) {
                         $this->logDebug("Upload error : cannot create temporary folder", array($destCopy));
                         $errorCode = 413;
                         $errorMessage = "Warning, cannot create folder for temporary copy.";
                         break;
                     }
                 }
                 if (!is_writeable($destCopy)) {
                     $this->logDebug("Upload error: cannot write into temporary folder");
                     $errorCode = 414;
                     $errorMessage = "Warning, cannot write into temporary folder.";
                     break;
                 }
                 $this->logDebug("Upload : tmp upload folder", array($destCopy));
                 if (isset($boxData["input_upload"])) {
                     try {
                         $destName = tempnam($destCopy, "");
                         $this->logDebug("Begining reading INPUT stream");
                         $input = fopen("php://input", "r");
                         $output = fopen($destName, "w");
                         $sizeRead = 0;
                         while ($sizeRead < intval($boxData["size"])) {
                             $chunk = fread($input, 4096);
                             $sizeRead += strlen($chunk);
                             fwrite($output, $chunk, strlen($chunk));
                         }
                         fclose($input);
                         fclose($output);
                         $boxData["tmp_name"] = $destName;
                         $this->storeFileToCopy($boxData);
                         $this->logDebug("End reading INPUT stream");
                     } catch (Exception $e) {
                         $errorCode = 411;
                         $errorMessage = $e->getMessage();
                         break;
                     }
                 } else {
                     $destName = $destCopy . "/" . basename($boxData["tmp_name"]);
                     if ($destName == $boxData["tmp_name"]) {
                         $destName .= "1";
                     }
                     if (move_uploaded_file($boxData["tmp_name"], $destName)) {
                         $boxData["tmp_name"] = $destName;
                         $this->storeFileToCopy($boxData);
                     } else {
                         $mess = ConfService::getMessages();
                         $errorCode = 411;
                         $errorMessage = "{$mess['33']} " . $boxData["name"];
                         break;
                     }
                 }
             }
             if (isset($errorMessage)) {
                 $this->logDebug("Return error {$errorCode} {$errorMessage}");
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             } else {
                 $this->logDebug("Return success");
                 return array("SUCCESS" => true);
             }
             session_write_close();
             break;
         default:
             break;
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     $mess = ConfService::getMessages();
     $timestamp_url = $this->getFilteredOption("TIMESTAMP_URL");
     $timestamp_login = $this->getFilteredOption("USER");
     $timestamp_password = $this->getFilteredOption("PASS");
     //Check if the configuration has been initiated
     if (empty($timestamp_url) || empty($timestamp_login) || !empty($timestamp_password)) {
         throw new AJXP_Exception($mess["timestamp.4"]);
         $this->logError("Config", "TimeStamp : configuration is needed");
         return false;
     }
     //Check if after being initiated, conf. fields have some values
     if (strlen($timestamp_url) < 2 || strlen($timestamp_login) < 2 || strlen($timestamp_password) < 2) {
         throw new AJXP_Exception($mess["timestamp.4"]);
         $this->logError("Config", "TimeStamp : configuration is incorrect");
         return false;
     }
     //Get active repository
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $selection = new UserSelection($repository, $httpVars);
     $destStreamURL = $selection->currentBaseUrl();
     $fileName = $selection->getUniqueFile();
     $fileUrl = $destStreamURL . $fileName;
     $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true);
     //Hash the file, to send it to Universign
     $hashedDataToTimestamp = hash_file('sha256', $file);
     //Check that a tokken is not going to be timestamped !
     if (substr("{$file}", -4) != '.ers') {
         if (file_exists($file . '.ers')) {
             throw new AJXP_Exception($mess["timestamp.1"]);
             return false;
         } else {
             //Prepare the query that will be sent to Universign
             $dataToSend = array('hashAlgo' => 'SHA256', 'withCert' => 'true', 'hashValue' => $hashedDataToTimestamp);
             $dataQuery = http_build_query($dataToSend);
             //Check if allow_url_fopen is allowed on the server. If not, it will use cUrl
             if (ini_get('allow_url_fopen')) {
                 $context_options = array('http' => array('method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($dataQuery) . "\r\n" . "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password) . "\r\n", 'content' => $dataQuery));
                 //Get the result from Universign
                 $context = stream_context_create($context_options);
                 $fp = fopen($timestamp_url, 'r', false, $context);
                 $tsp = stream_get_contents($fp);
             } else {
                 $timestamp_header = array("Content-type: application/x-www-form-urlencoded", "Content-Length: " . strlen($dataQuery), "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password));
                 $timeout = 5;
                 $ch = curl_init($timestamp_url);
                 curl_setopt($ch, CURLOPT_POSTFIELDS, $dataQuery);
                 curl_setopt($ch, CURLOPT_HTTPHEADER, $timestamp_header);
                 curl_setopt($ch, CURLOPT_POST, 1);
                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                 //Get the result from Universign
                 $tsp = curl_exec($ch);
                 curl_close($ch);
             }
             //Save the result to a file
             file_put_contents($file . '.ers', $tsp);
             //Send the succesful message
             $this->logInfo("TimeStamp", array("files" => $file, "destination" => $file . '.ers'));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::sendMessage($mess["timestamp.3"] . $fileName, null);
             AJXP_XMLWriter::close();
         }
     } else {
         throw new AJXP_Exception($mess["timestamp.2"]);
         return false;
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     $dir = AJXP_Utils::decodeSecureMagic($dir);
     if ($dir == "/") {
         $dir = "";
     }
     $selection->initFromHttpVars($httpVars);
     if (!$selection->isEmpty()) {
         //$this->filterUserSelectionToHidden($selection->getFiles());
     }
     $urlBase = "pydio://" . ConfService::getRepository()->getId();
     $mess = ConfService::getMessages();
     switch ($action) {
         case "monitor_compression":
             $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]);
             $percent = 0;
             if (is_file($percentFile)) {
                 $percent = intval(file_get_contents($percentFile));
             }
             if ($percent < 100) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1);
                 AJXP_XMLWriter::close();
             } else {
                 @unlink($percentFile);
                 AJXP_XMLWriter::header();
                 if ($httpVars["on_end"] == "reload") {
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 } else {
                     $archiveName = AJXP_Utils::sanitize($httpVars["archive_name"], AJXP_SANITIZE_FILENAME);
                     $archiveName = str_replace("'", "\\'", $archiveName);
                     $jsCode = "\n                            PydioApi.getClient().downloadSelection(null, \$('download_form'), 'postcompress_download', {ope_id:'" . $httpVars["ope_id"] . "',archive_name:'" . $archiveName . "'});\n                        ";
                     AJXP_XMLWriter::triggerBgJsAction($jsCode, $mess["powerfs.3"], true);
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "postcompress_download":
             $archive = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             if (is_file($archive)) {
                 if (!$fsDriver->getFilteredOption("USE_XSENDFILE", ConfService::getRepository()) && !$fsDriver->getFilteredOption("USE_XACCELREDIRECT", ConfService::getRepository())) {
                     register_shutdown_function("unlink", $archive);
                 }
                 $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true);
             } else {
                 echo "<script>alert('Cannot find archive! Is ZIP correctly installed?');</script>";
             }
             break;
         case "compress":
         case "precompress":
             $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $opeId = substr(md5(time()), 0, 10);
                 $httpVars["ope_id"] = $opeId;
                 AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars);
                 AJXP_XMLWriter::header();
                 $bgParameters = array("dir" => SystemTextEncoding::toUTF8($dir), "archive_name" => SystemTextEncoding::toUTF8($archiveName), "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId);
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir;
             $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"];
             $compressLocally = $action == "compress" ? true : false;
             // List all files
             $todo = array();
             $args = array();
             $replaceSearch = array($rootDir, "\\");
             $replaceReplace = array("", "/");
             foreach ($selection->getFiles() as $selectionFile) {
                 $baseFile = $selectionFile;
                 $args[] = escapeshellarg(substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1)));
                 $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile);
                 $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/");
                 if (is_dir($selectionFile)) {
                     $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST);
                     foreach ($objects as $name => $object) {
                         $todo[] = str_replace($replaceSearch, $replaceReplace, $name);
                     }
                 }
                 if (trim($baseFile, "/") == "") {
                     // ROOT IS SELECTED, FIX IT
                     $args = array(escapeshellarg(basename($rootDir)));
                     $rootDir = dirname($rootDir);
                     break;
                 }
             }
             $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";";
             if (!$compressLocally) {
                 $archiveName = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . $archiveName;
             }
             chdir($rootDir);
             $cmd = $this->getFilteredOption("ZIP_PATH") . " -r " . escapeshellarg($archiveName) . " " . implode(" ", $args);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             $c = $fsDriver->getConfigs();
             if ((!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) && stripos(PHP_OS, "win") === false) {
                 $cmd .= " -x .\\*";
             }
             $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED";
             $proc = popen($cmd, "r");
             $toks = array();
             $handled = array();
             $finishedEchoed = false;
             while (!feof($proc)) {
                 set_time_limit(20);
                 $results = fgets($proc, 256);
                 if (strlen($results) == 0) {
                 } else {
                     $tok = strtok($results, "\n");
                     while ($tok !== false) {
                         $toks[] = $tok;
                         if ($tok == "ZIP_FINISHED") {
                             $finishedEchoed = true;
                         } else {
                             $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches);
                             if ($test !== false) {
                                 $handled[] = $matches[2];
                             }
                         }
                         $tok = strtok("\n");
                     }
                     if ($finishedEchoed) {
                         $percent = 100;
                     } else {
                         $percent = min(round(count($handled) / count($todo) * 100), 100);
                     }
                     file_put_contents($percentFile, $percent);
                 }
                 // avoid a busy wait
                 if ($percent < 100) {
                     usleep(1);
                 }
             }
             pclose($proc);
             file_put_contents($percentFile, 100);
             break;
         default:
             break;
     }
 }
 /**
  * Create a user
  * @static
  * @throws Exception
  * @param $userId
  * @param $userPass
  * @param bool $isAdmin
  * @return null
  * @todo the minlength check is probably causing problem with the bridges
  */
 static function createUser($userId, $userPass, $isAdmin = false)
 {
     $userId = AuthService::filterUserSensitivity($userId);
     AJXP_Controller::applyHook("user.before_create", array($userId, $userPass, $isAdmin));
     if (!ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") && $userId == "guest") {
         throw new Exception("Reserved user id");
     }
     if (strlen($userPass) < ConfService::getCoreConf("PASSWORD_MINLENGTH", "auth") && $userId != "guest") {
         $messages = ConfService::getMessages();
         throw new Exception($messages[378]);
     }
     $authDriver = ConfService::getAuthDriverImpl();
     $confDriver = ConfService::getConfStorageImpl();
     $authDriver->createUser($userId, $userPass);
     if ($isAdmin) {
         $user = $confDriver->createUserObject($userId);
         $user->setAdmin(true);
         $user->save("superuser");
     }
     AJXP_Controller::applyHook("user.after_create", array($user));
     AJXP_Logger::logAction("Create User", array("user_id" => $userId));
     return null;
 }
Пример #29
0
 public function switchAction($actionName, $httpVars, $fileVars)
 {
     $this->baseURL = rtrim($this->getFilteredOption("ETHERPAD_SERVER"), "/");
     $this->apiKey = $this->getFilteredOption("ETHERPAD_APIKEY");
     $userSelection = new UserSelection(ConfService::getRepository(), $httpVars);
     if ($userSelection->isEmpty()) {
         throw new Exception("Empty selection");
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $selectedNode = $userSelection->getUniqueNode();
     $selectedNode->loadNodeInfo();
     if (!$selectedNode->isLeaf()) {
         throw new Exception("Cannot handle folders, please select a file!");
     }
     $nodeExtension = strtolower(pathinfo($selectedNode->getPath(), PATHINFO_EXTENSION));
     // Determine pad ID
     if ($nodeExtension == "pad") {
         $padID = file_get_contents($selectedNode->getUrl());
     } else {
         // TRY TO LOAD PAD ID FROM NODE SHARED METADATA
         $metadata = $selectedNode->retrieveMetadata("etherpad", AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         if (isset($metadata["pad_id"])) {
             $padID = $metadata["pad_id"];
         } else {
             $padID = AJXP_Utils::generateRandomString();
             $selectedNode->setMetadata("etherpad", array("pad_id" => $padID), AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         }
     }
     require_once "etherpad-client/etherpad-lite-client.php";
     $client = new EtherpadLiteClient($this->apiKey, $this->baseURL . "/api");
     $loggedUser = AuthService::getLoggedUser();
     $userName = $loggedUser->getId();
     $userLabel = $loggedUser->mergedRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userName);
     $res = $client->createAuthorIfNotExistsFor($userName, $userLabel);
     $authorID = $res->authorID;
     $res2 = $client->createGroupIfNotExistsFor($loggedUser->getGroupPath());
     $groupID = $res2->groupID;
     $fullId = $groupID . "\$" . $padID;
     if ($actionName == "etherpad_create") {
         $resP = $client->listPads($groupID);
         $currentContent = file_get_contents($selectedNode->getUrl());
         if ($nodeExtension == "html" && strpos($currentContent, "<html>") === false) {
             $currentContent = "<html><head></head><body>{$currentContent}</body></html>";
         }
         if (!in_array($fullId, $resP->padIDs)) {
             $client->createGroupPad($groupID, $padID, null);
             if ($nodeExtension == "html" && !empty($currentContent)) {
                 $client->setHTML($fullId, $currentContent);
             } else {
                 if ($nodeExtension != "pad") {
                     $client->setText($fullId, $currentContent);
                 }
             }
         } else {
             if ($nodeExtension != "pad") {
                 // If someone is already connected, do not override.
                 $existingAuthors = $client->listAuthorsOfPad($fullId);
                 if (!count($existingAuthors->authorIDs)) {
                     if ($nodeExtension == "html" && !empty($currentContent)) {
                         $client->setHTML($fullId, $currentContent);
                     } else {
                         $client->setText($fullId, $currentContent);
                     }
                 }
             }
         }
         $res4 = $client->createSession($groupID, $authorID, time() + 14400);
         $sessionID = $res4->sessionID;
         setcookie('sessionID', $sessionID, null, "/");
         $padID = $groupID . '$' . $padID;
         $data = array("url" => $this->baseURL . "/p/" . $padID, "padID" => $padID, "sessionID" => $sessionID);
         HTMLWriter::charsetHeader('application/json');
         echo json_encode($data);
     } else {
         if ($actionName == "etherpad_save") {
             $padID = $httpVars["pad_id"];
             if ($nodeExtension == "html" || $nodeExtension == "pad") {
                 $res = $client->getHTML($padID);
                 $content = $res->html;
             } else {
                 $res = $client->getText($padID);
                 $content = $res->text;
             }
             if ($nodeExtension == "pad") {
                 // Create a new file and save the content in it.
                 $origUrl = $selectedNode->getUrl();
                 $mess = ConfService::getMessages();
                 $dateStamp = date(" Y-m-d H:i", time());
                 $startUrl = preg_replace('"\\.pad$"', $dateStamp . '.html', $origUrl);
                 $newNode = new AJXP_Node($startUrl);
                 AJXP_Controller::applyHook("node.before_create", array($newNode, strlen($content)));
                 file_put_contents($newNode->getUrl(), $content);
                 AJXP_Controller::applyHook("node.change", array(null, $newNode));
             } else {
                 AJXP_Controller::applyHook("node.before_change", array($selectedNode, strlen($content)));
                 file_put_contents($selectedNode->getUrl(), $content);
                 clearstatcache(true, $selectedNode->getUrl());
                 $selectedNode->loadNodeInfo(true);
                 AJXP_Controller::applyHook("node.change", array($selectedNode, $selectedNode));
             }
         } else {
             if ($actionName == "etherpad_close") {
                 // WE SHOULD DETECT IF THERE IS NOBODY CONNECTED ANYMORE, AND DELETE THE PAD.
                 // BUT SEEMS LIKE THERE'S NO WAY TO PROPERLY REMOVE AN AUTHOR VIA API
                 $sessionID = $httpVars["session_id"];
                 $client->deleteSession($sessionID);
             } else {
                 if ($actionName == "etherpad_proxy_api") {
                     if ($httpVars["api_action"] == "list_pads") {
                         $res = $client->listPads($groupID);
                     } else {
                         if ($httpVars["api_action"] == "list_authors_for_pad") {
                             $res = $client->listAuthorsOfPad($httpVars["pad_id"]);
                         }
                     }
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($res);
                 } else {
                     if ($actionName == "etherpad_get_content") {
                         HTMLWriter::charsetHeader("text/plain");
                         echo $client->getText($httpVars["pad_id"])->text;
                     }
                 }
             }
         }
     }
     return null;
 }
Пример #30
0
 function crossRepositoryCopy($httpVars)
 {
     ConfService::detectRepositoryStreams(true);
     $mess = ConfService::getMessages();
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     $files = $selection->getFiles();
     $accessType = $this->repository->getAccessType();
     $repositoryId = $this->repository->getId();
     $origStreamURL = "ajxp.{$accessType}://{$repositoryId}";
     $destRepoId = $httpVars["dest_repository_id"];
     $destRepoObject = ConfService::getRepositoryById($destRepoId);
     $destRepoAccess = $destRepoObject->getAccessType();
     $destStreamURL = "ajxp.{$destRepoAccess}://{$destRepoId}";
     // Check rights
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId)) {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, "You do not have the right to access one of the repositories!");
             AJXP_XMLWriter::close();
             exit(1);
         }
     }
     $messages = array();
     foreach ($files as $file) {
         $origFile = $origStreamURL . $file;
         $destFile = $destStreamURL . $httpVars["dest"] . "/" . basename($file);
         $origHandler = fopen($origFile, "r");
         $destHandler = fopen($destFile, "w");
         if ($origHandler === false || $destHandler === false) {
             $errorMessages[] = AJXP_XMLWriter::sendMessage(null, $mess[114] . " ({$origFile} to {$destFile})", false);
             continue;
         }
         while (!feof($origHandler)) {
             fwrite($destHandler, fread($origHandler, 4096));
         }
         fflush($destHandler);
         fclose($origHandler);
         fclose($destHandler);
         $messages[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($origFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destFile);
     }
     AJXP_XMLWriter::header();
     if (count($errorMessages)) {
         AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true);
     }
     AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true);
     AJXP_XMLWriter::close();
     exit(0);
 }