예제 #1
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "post_to_server") {
         $file = base64_decode(AJXP_Utils::decodeSecureMagic($httpVars["file"]));
         $target = base64_decode($httpVars["parent_url"]) . "/plugins/editor.pixlr";
         $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file);
         $fData = array("tmp_name" => $tmp, "name" => urlencode(basename($file)), "type" => "image/jpg");
         $httpClient = new HttpClient("pixlr.com");
         //$httpClient->setDebug(true);
         $postData = array();
         $httpClient->setHandleRedirects(false);
         $params = array("referrer" => "AjaXplorer", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $target . "/fake_save_pixlr.php", "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($file)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source");
         $httpClient->postFile("/editor/", $params, "image", $fData);
         $loc = $httpClient->getHeader("location");
         header("Location:{$loc}");
     } else {
         if ($action == "retrieve_pixlr_image") {
             $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]);
             $url = $httpVars["new_url"];
             $urlParts = parse_url($url);
             $query = $urlParts["query"];
             $params = array();
             $parameters = parse_str($query, $params);
             $image = $params['image'];
             /*
             $type = $params['type'];
             $state = $params['state'];
             $filename = $params['title'];		
             */
             if (strpos($image, "pixlr.com") == 0) {
                 throw new AJXP_Exception("Invalid Referrer");
             }
             $headers = get_headers($image, 1);
             $content_type = explode("/", $headers['Content-Type']);
             if ($content_type[0] != "image") {
                 throw new AJXP_Exception("File Type");
             }
             $orig = fopen($image, "r");
             $target = fopen($destStreamURL . $file, "w");
             while (!feof($orig)) {
                 fwrite($target, fread($orig, 4096));
             }
             fclose($orig);
             fclose($target);
             header("Content-Type:text/plain");
             print $mess[115];
         }
     }
     return;
 }
예제 #2
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (!isset($this->pluginConf)) {
         $this->pluginConf = array("GENERATE_THUMBNAIL" => false);
     }
     $streamData = $repository->streamData;
     $this->streamData = $streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "preview_data_proxy") {
         $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
         if (!file_exists($destStreamURL . $file)) {
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: 0");
             return;
         }
         if (isset($httpVars["get_thumb"]) && $this->getFilteredOption("GENERATE_THUMBNAIL", $repository->getId())) {
             $dimension = 200;
             if (isset($httpVars["dimension"]) && is_numeric($httpVars["dimension"])) {
                 $dimension = $httpVars["dimension"];
             }
             $this->currentDimension = $dimension;
             $cacheItem = AJXP_Cache::getItem("diaporama_" . $dimension, $destStreamURL . $file, array($this, "generateThumbnail"));
             $data = $cacheItem->getData();
             $cId = $cacheItem->getId();
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($cId)) . "; name=\"" . basename($cId) . "\"");
             header("Content-Length: " . strlen($data));
             header('Cache-Control: public');
             header("Pragma:");
             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");
             print $data;
         } else {
             //$filesize = filesize($destStreamURL.$file);
             $node = new AJXP_Node($destStreamURL . $file);
             $fp = fopen($destStreamURL . $file, "r");
             $stat = fstat($fp);
             $filesize = $stat["size"];
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: " . $filesize);
             header('Cache-Control: public');
             header("Pragma:");
             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");
             $class = $streamData["classname"];
             $stream = fopen("php://output", "a");
             call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
             fflush($stream);
             fclose($stream);
             AJXP_Controller::applyHook("node.read", array($node));
         }
     }
 }
예제 #3
0
 public function switchAction($action, $httpVars, $postProcessData)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . "/";
     if ($action == "audio_proxy") {
         $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
         $cType = "audio/" . array_pop(explode(".", $file));
         $localName = basename($file);
         header("Content-Type: " . $cType . "; name=\"" . $localName . "\"");
         header("Content-Length: " . filesize($destStreamURL . $file));
         $stream = fopen("php://output", "a");
         call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
         fflush($stream);
         fclose($stream);
         $node = new AJXP_Node($destStreamURL . $file);
         AJXP_Controller::applyHook("node.read", array($node));
         //exit(1);
     } else {
         if ($action == "ls") {
             if (!isset($httpVars["playlist"])) {
                 // This should not happen anyway, because of the applyCondition.
                 AJXP_Controller::passProcessDataThrough($postProcessData);
                 return;
             }
             // We transform the XML into XSPF
             $xmlString = $postProcessData["ob_output"];
             $xmlDoc = new DOMDocument();
             $xmlDoc->loadXML($xmlString);
             $xElement = $xmlDoc->documentElement;
             header("Content-Type:application/xspf+xml;charset=UTF-8");
             print '<?xml version="1.0" encoding="UTF-8"?>';
             print '<playlist version="1" xmlns="http://xspf.org/ns/0/">';
             print "<trackList>";
             foreach ($xElement->childNodes as $child) {
                 $isFile = $child->getAttribute("is_file") == "true";
                 $label = $child->getAttribute("text");
                 $ar = explode(".", $label);
                 $ext = strtolower(end($ar));
                 if (!$isFile || $ext != "mp3") {
                     continue;
                 }
                 print "<track><location>" . AJXP_SERVER_ACCESS . "?secure_token=" . AuthService::getSecureToken() . "&get_action=audio_proxy&file=" . base64_encode($child->getAttribute("filename")) . "</location><title>" . $label . "</title></track>";
             }
             print "</trackList>";
             AJXP_XMLWriter::close("playlist");
         }
     }
 }
 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;
     }
 }
예제 #5
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (!isset($this->pluginConf)) {
         $this->pluginConf = array("GENERATE_THUMBNAIL" => false);
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "preview_data_proxy") {
         $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
         if (isset($httpVars["get_thumb"]) && $this->pluginConf["GENERATE_THUMBNAIL"]) {
             require_once INSTALL_PATH . "/plugins/editor.diaporama/PThumb.lib.php";
             $pThumb = new PThumb($this->pluginConf["THUMBNAIL_QUALITY"]);
             if (!$pThumb->isError()) {
                 $pThumb->remote_wrapper = $streamData["classname"];
                 $pThumb->use_cache = $this->pluginConf["USE_THUMBNAIL_CACHE"];
                 $pThumb->cache_dir = $this->pluginConf["THUMBNAIL_CACHE_DIR"];
                 $pThumb->fit_thumbnail($destStreamURL . $file, 200);
                 if ($pThumb->isError()) {
                     print_r($pThumb->error_array);
                     AJXP_Logger::logAction("error", $pThumb->error_array);
                 }
                 //exit(0);
             } else {
                 print_r($pThumb->error_array);
                 AJXP_Logger::logAction("error", $pThumb->error_array);
             }
         } else {
             $filesize = filesize($destStreamURL . $file);
             $fp = fopen($destStreamURL . $file, "r");
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: " . $filesize);
             header('Cache-Control: public');
             $class = $streamData["classname"];
             $stream = fopen("php://output", "a");
             call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
             fflush($stream);
             fclose($stream);
             //exit(1);
         }
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     switch ($action) {
         case "get_js_source":
             $jsName = AJXP_Utils::decodeSecureMagic($httpVars["object_name"]);
             $jsType = $httpVars["object_type"];
             // class or interface?
             $fName = "class." . strtolower($jsName) . ".js";
             if ($jsName == "Splitter") {
                 $fName = "splitter.js";
             }
             if (!defined("CLIENT_RESOURCES_FOLDER")) {
                 define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
             }
             // Locate the file class.ClassName.js
             if ($jsType == "class") {
                 $searchLocations = array(CLIENT_RESOURCES_FOLDER . "/js/ajaxplorer", CLIENT_RESOURCES_FOLDER . "/js/lib", AJXP_INSTALL_PATH . "/plugins/");
             } else {
                 if ($jsType == "interface") {
                     $searchLocations = array(CLIENT_RESOURCES_FOLDER . "/js/ajaxplorer/interfaces");
                 }
             }
             foreach ($searchLocations as $location) {
                 $dir_iterator = new RecursiveDirectoryIterator($location);
                 $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
                 // could use CHILD_FIRST if you so wish
                 $break = false;
                 foreach ($iterator as $file) {
                     if (strtolower(basename($file->getPathname())) == $fName) {
                         HTMLWriter::charsetHeader("text/plain", "utf-8");
                         echo file_get_contents($file->getPathname());
                         $break = true;
                         break;
                     }
                 }
                 if ($break) {
                     break;
                 }
             }
             break;
     }
 }
예제 #7
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     $wrapperClassName = $streamData["classname"];
     if (empty($httpVars["file"])) {
         return;
     }
     $file = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]);
     $mess = ConfService::getMessages();
     $node = new AJXP_Node($file);
     AJXP_Controller::applyHook("node.read", array($node));
     switch ($action) {
         case "eml_get_xml_structure":
             $params = array('include_bodies' => false, 'decode_bodies' => false, 'decode_headers' => 'UTF-8');
             $decoder = $this->getStructureDecoder($file, $wrapperClassName == "imapAccessWrapper");
             $xml = $decoder->getXML($decoder->decode($params));
             if (function_exists("imap_mime_header_decode")) {
                 $doc = new DOMDocument();
                 $doc->loadXML($xml);
                 $xPath = new DOMXPath($doc);
                 $headers = $xPath->query("//headername");
                 $changes = false;
                 foreach ($headers as $headerNode) {
                     if ($headerNode->firstChild->nodeValue == "Subject") {
                         $headerValueNode = $headerNode->nextSibling->nextSibling;
                         $value = $headerValueNode->nodeValue;
                         $elements = imap_mime_header_decode($value);
                         $decoded = "";
                         foreach ($elements as $element) {
                             $decoded .= $element->text;
                             $charset = $element->charset;
                         }
                         if ($decoded != $value) {
                             $value = SystemTextEncoding::changeCharset($charset, "UTF-8", $decoded);
                             $node = $doc->createElement("headervalue", $value);
                             $res = $headerNode->parentNode->replaceChild($node, $headerValueNode);
                             $changes = true;
                         }
                     }
                 }
                 if ($changes) {
                     $xml = $doc->saveXML();
                 }
             }
             print $xml;
             break;
         case "eml_get_bodies":
             require_once "Mail/mimeDecode.php";
             $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false);
             if ($wrapperClassName == "imapAccessWrapper") {
                 $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId"));
                 $content = $cache->getData();
             } else {
                 $content = file_get_contents($file);
             }
             $decoder = new Mail_mimeDecode($content);
             $structure = $decoder->decode($params);
             $html = $this->_findPartByCType($structure, "text", "html");
             $text = $this->_findPartByCType($structure, "text", "plain");
             if ($html != false && isset($html->ctype_parameters) && isset($html->ctype_parameters["charset"])) {
                 $charset = $html->ctype_parameters["charset"];
             }
             if (isset($charset)) {
                 header('Content-Type: text/xml; charset=' . $charset);
                 header('Cache-Control: no-cache');
                 print '<?xml version="1.0" encoding="' . $charset . '"?>';
                 print '<email_body>';
             } else {
                 AJXP_XMLWriter::header("email_body");
             }
             if ($html !== false) {
                 print '<mimepart type="html"><![CDATA[';
                 $text = $html->body;
                 print $text;
                 print "]]></mimepart>";
             }
             if ($text !== false) {
                 print '<mimepart type="plain"><![CDATA[';
                 print $text->body;
                 print "]]></mimepart>";
             }
             AJXP_XMLWriter::close("email_body");
             break;
         case "eml_dl_attachment":
             $attachId = $httpVars["attachment_id"];
             if (!isset($attachId)) {
                 break;
             }
             require_once "Mail/mimeDecode.php";
             $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false);
             if ($wrapperClassName == "imapAccessWrapper") {
                 $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId"));
                 $content = $cache->getData();
             } else {
                 $content = file_get_contents($file);
             }
             $decoder = new Mail_mimeDecode($content);
             $structure = $decoder->decode($params);
             $part = $this->_findAttachmentById($structure, $attachId);
             if ($part !== false) {
                 $fake = new fsAccessDriver("fake", "");
                 $fake->readFile($part->body, "file", $part->d_parameters['filename'], true);
                 exit;
             } else {
                 //var_dump($structure);
             }
             break;
         case "eml_cp_attachment":
             $attachId = $httpVars["attachment_id"];
             $destRep = AJXP_Utils::decodeSecureMagic($httpVars["destination"]);
             if (!isset($attachId)) {
                 AJXP_XMLWriter::sendMessage(null, "Wrong Parameters");
                 break;
             }
             require_once "Mail/mimeDecode.php";
             $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false);
             if ($wrapperClassName == "imapAccessWrapper") {
                 $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId"));
                 $content = $cache->getData();
             } else {
                 $content = file_get_contents($file);
             }
             $decoder = new Mail_mimeDecode($content);
             $structure = $decoder->decode($params);
             $part = $this->_findAttachmentById($structure, $attachId);
             AJXP_XMLWriter::header();
             if ($part !== false) {
                 if (isset($httpVars["dest_repository_id"])) {
                     $destRepoId = $httpVars["dest_repository_id"];
                     if (AuthService::usersEnabled()) {
                         $loggedUser = AuthService::getLoggedUser();
                         if (!$loggedUser->canWrite($destRepoId)) {
                             throw new Exception($mess[364]);
                         }
                     }
                     $destRepoObject = ConfService::getRepositoryById($destRepoId);
                     $destRepoAccess = $destRepoObject->getAccessType();
                     $plugin = AJXP_PluginsService::findPlugin("access", $destRepoAccess);
                     $destWrapperData = $plugin->detectStreamWrapper(true);
                     $destStreamURL = $destWrapperData["protocol"] . "://{$destRepoId}";
                 }
                 $destFile = $destStreamURL . $destRep . "/" . $part->d_parameters['filename'];
                 $fp = fopen($destFile, "w");
                 if ($fp !== false) {
                     fwrite($fp, $part->body, strlen($part->body));
                     fclose($fp);
                     AJXP_XMLWriter::sendMessage(sprintf($mess["editor.eml.7"], $part->d_parameters["filename"], $destRep), NULL);
                 } else {
                     AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.8"]);
                 }
             } else {
                 AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.9"]);
             }
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
 }
예제 #8
0
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars();
     $currentFile = $selection->getUniqueFile();
     $wrapperData = $this->accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId();
     $newValues = array();
     $def = $this->getMetaDefinition();
     foreach ($def as $key => $label) {
         if (isset($httpVars[$key])) {
             $newValues[$key] = AJXP_Utils::xmlEntities(AJXP_Utils::decodeSecureMagic($httpVars[$key]));
         } else {
             if (!isset($original)) {
                 $original = array();
                 $this->loadMetaFileData($urlBase . $currentFile);
                 $base = basename($currentFile);
                 if (is_array(self::$metaCache) && array_key_exists($base, self::$metaCache)) {
                     $original = self::$metaCache[$base];
                 }
             }
             if (isset($original) && isset($original[$key])) {
                 $newValues[$key] = $original[$key];
             }
         }
     }
     $this->addMeta($urlBase . $currentFile, $newValues);
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true);
     AJXP_XMLWriter::close();
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $loggedUser = AuthService::getLoggedUser();
     if (AuthService::usersEnabled() && !$loggedUser->isAdmin()) {
         return;
     }
     if (AuthService::usersEnabled()) {
         $currentBookmarks = AuthService::getLoggedUser()->getBookmarks();
         // FLATTEN
         foreach ($currentBookmarks as $bm) {
             $this->currentBookmarks[] = $bm["PATH"];
         }
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     $currentUserIsGroupAdmin = AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/";
     if ($currentUserIsGroupAdmin && ConfService::getAuthDriverImpl()->isAjxpAdmin(AuthService::getLoggedUser()->getId())) {
         $currentUserIsGroupAdmin = false;
     }
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("data" => array("LABEL" => $mess["ajxp_conf.110"], "ICON" => "user.png", "DESCRIPTION" => $mess["ajxp_conf.137"], "CHILDREN" => array("repositories" => array("AJXP_MIME" => "workspaces_zone", "LABEL" => $mess["ajxp_conf.3"], "DESCRIPTION" => $mess["ajxp_conf.138"], "ICON" => "hdd_external_unmount.png", "LIST" => "listRepositories"), "users" => array("AJXP_MIME" => "users_zone", "LABEL" => $mess["ajxp_conf.2"], "DESCRIPTION" => $mess["ajxp_conf.139"], "ICON" => "users-folder.png", "LIST" => "listUsers"), "roles" => array("AJXP_MIME" => "roles_zone", "LABEL" => $mess["ajxp_conf.69"], "DESCRIPTION" => $mess["ajxp_conf.140"], "ICON" => "user-acl.png", "LIST" => "listRoles"))), "config" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.109"], "ICON" => "preferences_desktop.png", "DESCRIPTION" => $mess["ajxp_conf.136"], "CHILDREN" => array("core" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.98"], "DESCRIPTION" => $mess["ajxp_conf.133"], "ICON" => "preferences_desktop.png", "LIST" => "listPlugins"), "plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.99"], "DESCRIPTION" => $mess["ajxp_conf.134"], "ICON" => "folder_development.png", "LIST" => "listPlugins"), "core_plugins" => array("AJXP_MIME" => "plugins_zone", "LABEL" => $mess["ajxp_conf.123"], "DESCRIPTION" => $mess["ajxp_conf.135"], "ICON" => "folder_development.png", "LIST" => "listPlugins"))), "admin" => array("LABEL" => $mess["ajxp_conf.111"], "ICON" => "toggle_log.png", "DESCRIPTION" => $mess["ajxp_conf.141"], "CHILDREN" => array("logs" => array("LABEL" => $mess["ajxp_conf.4"], "DESCRIPTION" => $mess["ajxp_conf.142"], "ICON" => "toggle_log.png", "LIST" => "listLogFiles"), "diagnostic" => array("LABEL" => $mess["ajxp_conf.5"], "DESCRIPTION" => $mess["ajxp_conf.143"], "ICON" => "susehelpcenter.png", "LIST" => "printDiagnostic"))), "developer" => array("LABEL" => $mess["ajxp_conf.144"], "ICON" => "applications_engineering.png", "DESCRIPTION" => $mess["ajxp_conf.145"], "CHILDREN" => array("actions" => array("LABEL" => $mess["ajxp_conf.146"], "DESCRIPTION" => $mess["ajxp_conf.147"], "ICON" => "book.png", "LIST" => "listActions"), "hooks" => array("LABEL" => $mess["ajxp_conf.148"], "DESCRIPTION" => $mess["ajxp_conf.149"], "ICON" => "book.png", "LIST" => "listHooks"))));
             if ($currentUserIsGroupAdmin) {
                 unset($rootNodes["config"]);
                 unset($rootNodes["admin"]);
                 unset($rootNodes["developer"]);
             }
             AJXP_Controller::applyHook("ajxp_conf.list_config_nodes", array(&$rootNodes));
             $parentName = "";
             $dir = trim(AJXP_Utils::decodeSecureMagic(isset($httpVars["dir"]) ? $httpVars["dir"] : ""), " /");
             if ($dir != "") {
                 $hash = null;
                 if (strstr(urldecode($dir), "#") !== false) {
                     list($dir, $hash) = explode("#", urldecode($dir));
                 }
                 $splits = explode("/", $dir);
                 $root = array_shift($splits);
                 if (count($splits)) {
                     $returnNodes = false;
                     if (isset($httpVars["file"])) {
                         $returnNodes = true;
                     }
                     $child = $splits[0];
                     if (isset($rootNodes[$root]["CHILDREN"][$child])) {
                         $atts = array();
                         if ($child == "users") {
                             $atts["remote_indexation"] = "admin_search";
                         }
                         $callback = $rootNodes[$root]["CHILDREN"][$child]["LIST"];
                         if (is_string($callback) && method_exists($this, $callback)) {
                             if (!$returnNodes) {
                                 AJXP_XMLWriter::header("tree", $atts);
                             }
                             $res = call_user_func(array($this, $callback), implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : '');
                             if (!$returnNodes) {
                                 AJXP_XMLWriter::close();
                             }
                         } else {
                             if (is_array($callback)) {
                                 $res = call_user_func($callback, implode("/", $splits), $root, $hash, $returnNodes, isset($httpVars["file"]) ? $httpVars["file"] : '');
                             }
                         }
                         if ($returnNodes) {
                             AJXP_XMLWriter::header("tree", $atts);
                             if (isset($res["/" . $dir . "/" . $httpVars["file"]])) {
                                 print $res["/" . $dir . "/" . $httpVars["file"]];
                             }
                             AJXP_XMLWriter::close();
                         }
                         return;
                     }
                 } else {
                     $parentName = "/" . $root . "/";
                     $nodes = $rootNodes[$root]["CHILDREN"];
                 }
             } else {
                 $parentName = "/";
                 $nodes = $rootNodes;
             }
             if (isset($httpVars["file"])) {
                 $parentName = $httpVars["dir"] . "/";
                 $nodes = array(basename($httpVars["file"]) => array("LABEL" => basename($httpVars["file"])));
             }
             if (isset($nodes)) {
                 AJXP_XMLWriter::header();
                 if (!isset($httpVars["file"])) {
                     AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="detail"><column messageId="ajxp_conf.1" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.102" attributeName="description" sortType="String"/></columns>');
                 }
                 foreach ($nodes as $key => $data) {
                     $bmString = '';
                     if (in_array($parentName . $key, $this->currentBookmarks)) {
                         $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" ';
                     }
                     if ($key == "users") {
                         $bmString .= ' remote_indexation="admin_search"';
                     }
                     if (isset($data["AJXP_MIME"])) {
                         $bmString .= ' ajxp_mime="' . $data["AJXP_MIME"] . '"';
                     }
                     if (empty($data["CHILDREN"])) {
                         print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '/>';
                     } else {
                         print '<tree text="' . AJXP_Utils::xmlEntities($data["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($data["DESCRIPTION"]) . '" icon="' . $data["ICON"] . '" filename="' . $parentName . $key . '" ' . $bmString . '>';
                         foreach ($data["CHILDREN"] as $cKey => $cData) {
                             $bmString = '';
                             if (in_array($parentName . $key . "/" . $cKey, $this->currentBookmarks)) {
                                 $bmString = ' ajxp_bookmarked="true" overlay_icon="bookmark.png" ';
                             }
                             if ($cKey == "users") {
                                 $bmString .= ' remote_indexation="admin_search"';
                             }
                             if (isset($cData["AJXP_MIME"])) {
                                 $bmString .= ' ajxp_mime="' . $cData["AJXP_MIME"] . '"';
                             }
                             print '<tree text="' . AJXP_Utils::xmlEntities($cData["LABEL"]) . '" description="' . AJXP_Utils::xmlEntities($cData["DESCRIPTION"]) . '" icon="' . $cData["ICON"] . '" filename="' . $parentName . $key . '/' . $cKey . '" ' . $bmString . '/>';
                         }
                         print '</tree>';
                     }
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             return;
             break;
         case "clear_plugins_cache":
             AJXP_XMLWriter::header();
             // Clear plugins cache if they exist
             AJXP_PluginsService::clearPluginsCache();
             ConfService::clearMessagesCache();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . (AJXP_SKIP_CACHE ? "132" : "131")], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "create_group":
             if (isset($httpVars["group_path"])) {
                 $basePath = AJXP_Utils::forwardSlashDirname($httpVars["group_path"]);
                 if (empty($basePath)) {
                     $basePath = "/";
                 }
                 $gName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic(basename($httpVars["group_path"])), AJXP_SANITIZE_ALPHANUM);
             } else {
                 $basePath = substr($httpVars["dir"], strlen("/data/users"));
                 $gName = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["group_name"]), AJXP_SANITIZE_ALPHANUM);
             }
             $gLabel = AJXP_Utils::decodeSecureMagic($httpVars["group_label"]);
             AuthService::createGroup($basePath, $gName, $gLabel);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.124"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "create_role":
             $roleId = AJXP_Utils::sanitize(SystemTextEncoding::magicDequote($httpVars["role_id"]), AJXP_SANITIZE_HTML_STRICT);
             if (!strlen($roleId)) {
                 throw new Exception($mess[349]);
             }
             if (AuthService::getRole($roleId) !== false) {
                 throw new Exception($mess["ajxp_conf.65"]);
             }
             $r = new AJXP_Role($roleId);
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                 $r->setGroupPath(AuthService::getLoggedUser()->getGroupPath());
             }
             AuthService::updateRole($r);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.66"], null);
             AJXP_XMLWriter::reloadDataNode("", $httpVars["role_id"]);
             AJXP_XMLWriter::close();
             break;
         case "edit_role":
             $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]);
             $roleGroup = false;
             $userObject = null;
             $groupLabel = null;
             if (strpos($roleId, "AJXP_GRP_") === 0) {
                 $groupPath = substr($roleId, strlen("AJXP_GRP_"));
                 $filteredGroupPath = AuthService::filterBaseGroup($groupPath);
                 $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath));
                 $key = "/" . basename($groupPath);
                 if (!array_key_exists($key, $groups)) {
                     throw new Exception("Cannot find group with this id!");
                 }
                 $roleId = "AJXP_GRP_" . $filteredGroupPath;
                 $groupLabel = $groups[$key];
                 $roleGroup = true;
             }
             if (strpos($roleId, "AJXP_USR_") === 0) {
                 $usrId = str_replace("AJXP_USR_/", "", $roleId);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cant find user!");
                 }
                 $role = $userObject->personalRole;
             } else {
                 $role = AuthService::getRole($roleId, $roleGroup);
             }
             if ($role === false) {
                 throw new Exception("Cant find role! ");
             }
             if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
                 HTMLWriter::charsetHeader("application/json");
                 $roleData = $role->getDataArray(true);
                 $allReps = ConfService::getRepositoriesList("all", false);
                 $repos = array();
                 if (!empty($userObject)) {
                     // USER
                     foreach ($allReps as $repositoryId => $repositoryObject) {
                         if (!AuthService::canAssign($repositoryObject, $userObject) || $repositoryObject->isTemplate || $repositoryObject->getAccessType() == "ajxp_conf" && !$userObject->isAdmin() || $repositoryObject->getUniqueUser() != null && $repositoryObject->getUniqueUser() != $userObject->getId()) {
                             continue;
                         }
                         $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay());
                     }
                 } else {
                     foreach ($allReps as $repositoryId => $repositoryObject) {
                         if (!AuthService::canAdministrate($repositoryObject)) {
                             continue;
                         }
                         $repos[$repositoryId] = SystemTextEncoding::toUTF8($repositoryObject->getDisplay());
                     }
                 }
                 // Make sure it's utf8
                 $data = array("ROLE" => $roleData, "ALL" => array("REPOSITORIES" => $repos));
                 if (isset($userObject)) {
                     $data["USER"] = array();
                     $data["USER"]["LOCK"] = $userObject->getLock();
                     $data["USER"]["PROFILE"] = $userObject->getProfile();
                     $data["ALL"]["PROFILES"] = array("standard|Standard", "admin|Administrator", "shared|Shared", "guest|Guest");
                     $data["USER"]["ROLES"] = array_keys($userObject->getRoles());
                     $data["ALL"]["ROLES"] = array_keys(AuthService::getRolesList(array(), true));
                     if (isset($userObject->parentRole)) {
                         $data["PARENT_ROLE"] = $userObject->parentRole->getDataArray();
                     }
                 } else {
                     if (isset($groupPath)) {
                         $data["GROUP"] = array("PATH" => $groupPath, "LABEL" => $groupLabel);
                     }
                 }
                 $scope = "role";
                 if ($roleGroup) {
                     $scope = "group";
                 } else {
                     if (isset($userObject)) {
                         $scope = "user";
                     }
                 }
                 $data["SCOPE_PARAMS"] = array();
                 $nodes = AJXP_PluginsService::getInstance()->searchAllManifests("//param[contains(@scope,'" . $scope . "')]|//global_param[contains(@scope,'" . $scope . "')]", "node", false, true, true);
                 foreach ($nodes as $node) {
                     $pId = $node->parentNode->parentNode->attributes->getNamedItem("id")->nodeValue;
                     $origName = $node->attributes->getNamedItem("name")->nodeValue;
                     $node->attributes->getNamedItem("name")->nodeValue = "AJXP_REPO_SCOPE_ALL/" . $pId . "/" . $origName;
                     $nArr = array();
                     foreach ($node->attributes as $attrib) {
                         $nArr[$attrib->nodeName] = AJXP_XMLWriter::replaceAjxpXmlKeywords($attrib->nodeValue);
                     }
                     $data["SCOPE_PARAMS"][] = $nArr;
                 }
                 echo json_encode($data);
             }
             break;
         case "post_json_role":
             $roleId = SystemTextEncoding::magicDequote($httpVars["role_id"]);
             $roleGroup = false;
             $userObject = $usrId = $filteredGroupPath = null;
             if (strpos($roleId, "AJXP_GRP_") === 0) {
                 $groupPath = substr($roleId, strlen("AJXP_GRP_"));
                 $filteredGroupPath = AuthService::filterBaseGroup($groupPath);
                 $roleId = "AJXP_GRP_" . $filteredGroupPath;
                 $groups = AuthService::listChildrenGroups(AJXP_Utils::forwardSlashDirname($groupPath));
                 $key = "/" . basename($groupPath);
                 if (!array_key_exists($key, $groups)) {
                     throw new Exception("Cannot find group with this id!");
                 }
                 $groupLabel = $groups[$key];
                 $roleGroup = true;
             }
             if (strpos($roleId, "AJXP_USR_") === 0) {
                 $usrId = str_replace("AJXP_USR_/", "", $roleId);
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($usrId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cannot post role for user " . $usrId);
                 }
                 $originalRole = $userObject->personalRole;
             } else {
                 // second param = create if not exists.
                 $originalRole = AuthService::getRole($roleId, $roleGroup);
             }
             if ($originalRole === false) {
                 throw new Exception("Cant find role! ");
             }
             $jsonData = SystemTextEncoding::magicDequote($httpVars["json_data"]);
             $data = json_decode($jsonData, true);
             $roleData = $data["ROLE"];
             $forms = $data["FORMS"];
             $binariesContext = array();
             if (isset($userObject)) {
                 $binariesContext = array("USER" => $userObject->getId());
             }
             foreach ($forms as $repoScope => $plugData) {
                 foreach ($plugData as $plugId => $formsData) {
                     $parsed = array();
                     AJXP_Utils::parseStandardFormParameters($formsData, $parsed, $userObject != null ? $usrId : null, "ROLE_PARAM_", $binariesContext, AJXP_Role::$cypheredPassPrefix);
                     $roleData["PARAMETERS"][$repoScope][$plugId] = $parsed;
                 }
             }
             $existingParameters = $originalRole->listParameters(true);
             $this->mergeExistingParameters($roleData["PARAMETERS"], $existingParameters);
             if (isset($userObject) && isset($data["USER"]) && isset($data["USER"]["PROFILE"])) {
                 $userObject->setAdmin($data["USER"]["PROFILE"] == "admin");
                 $userObject->setProfile($data["USER"]["PROFILE"]);
             }
             if (isset($data["GROUP_LABEL"]) && isset($groupLabel) && $groupLabel != $data["GROUP_LABEL"]) {
                 ConfService::getConfStorageImpl()->relabelGroup($filteredGroupPath, $data["GROUP_LABEL"]);
             }
             if ($currentUserIsGroupAdmin) {
                 // FILTER DATA FOR GROUP ADMINS
                 $params = $this->getEditableParameters(false);
                 foreach ($roleData["PARAMETERS"] as $scope => &$plugsParameters) {
                     foreach ($plugsParameters as $paramPlugin => &$parameters) {
                         foreach ($parameters as $pName => $pValue) {
                             if (!isset($params[$paramPlugin]) || !in_array($pName, $params[$paramPlugin])) {
                                 unset($parameters[$pName]);
                             }
                         }
                         if (!count($parameters)) {
                             unset($plugsParameters[$paramPlugin]);
                         }
                     }
                     if (!count($plugsParameters)) {
                         unset($roleData["PARAMETERS"][$scope]);
                     }
                 }
                 // Remerge from parent
                 $roleData["PARAMETERS"] = $originalRole->array_merge_recursive2($originalRole->listParameters(), $roleData["PARAMETERS"]);
                 // Changing Actions is not allowed
                 $roleData["ACTIONS"] = $originalRole->listActionsStates();
             }
             try {
                 $originalRole->bunchUpdate($roleData);
                 if (isset($userObject)) {
                     $userObject->personalRole = $originalRole;
                     $userObject->save("superuser");
                 } else {
                     AuthService::updateRole($originalRole);
                 }
                 $output = array("ROLE" => $originalRole->getDataArray(true), "SUCCESS" => true);
             } catch (Exception $e) {
                 $output = array("ERROR" => $e->getMessage());
             }
             HTMLWriter::charsetHeader("application/json");
             echo json_encode($output);
             break;
         case "user_set_lock":
             $userId = AJXP_Utils::decodeSecureMagic($httpVars["user_id"]);
             $lock = $httpVars["lock"] == "true" ? true : false;
             $lockType = $httpVars["lock_type"];
             if (AuthService::userExists($userId)) {
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($userId);
                 if (!AuthService::canAdministrate($userObject)) {
                     throw new Exception("Cannot update user data for " . $userId);
                 }
                 if ($lock) {
                     $userObject->setLock($lockType);
                 } else {
                     $userObject->removeLock();
                 }
                 $userObject->save("superuser");
             }
             break;
         case "create_user":
             if (!isset($httpVars["new_user_login"]) || $httpVars["new_user_login"] == "" || !isset($httpVars["new_user_pwd"]) || $httpVars["new_user_pwd"] == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $original_login = SystemTextEncoding::magicDequote($httpVars["new_user_login"]);
             $new_user_login = AJXP_Utils::sanitize($original_login, AJXP_SANITIZE_EMAILCHARS);
             if ($original_login != $new_user_login) {
                 throw new Exception(str_replace("%s", $new_user_login, $mess["ajxp_conf.127"]));
             }
             if (AuthService::userExists($new_user_login, "w") || AuthService::isReservedUserId($new_user_login)) {
                 throw new Exception($mess["ajxp_conf.43"]);
             }
             AuthService::createUser($new_user_login, $httpVars["new_user_pwd"]);
             $confStorage = ConfService::getConfStorageImpl();
             $newUser = $confStorage->createUserObject($new_user_login);
             $basePath = AuthService::getLoggedUser()->getGroupPath();
             if (empty($basePath)) {
                 $basePath = "/";
             }
             if (!empty($httpVars["group_path"])) {
                 $newUser->setGroupPath(rtrim($basePath, "/") . "/" . ltrim($httpVars["group_path"], "/"));
             } else {
                 $newUser->setGroupPath($basePath);
             }
             $newUser->save("superuser");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.44"], null);
             AJXP_XMLWriter::reloadDataNode("", $new_user_login);
             AJXP_XMLWriter::close();
             break;
         case "change_admin_right":
             $userId = $httpVars["user_id"];
             if (!AuthService::userExists($userId)) {
                 throw new Exception("Invalid user id!");
             }
             $confStorage = ConfService::getConfStorageImpl();
             $user = $confStorage->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $user->setAdmin($httpVars["right_value"] == "1" ? true : false);
             $user->save("superuser");
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.45"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "role_update_right":
             if (!isset($httpVars["role_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 break;
             }
             $rId = AJXP_Utils::sanitize($httpVars["role_id"]);
             $role = AuthService::getRole($rId);
             if ($role === false) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"] . "(" . $rId . ")");
                 AJXP_XMLWriter::close();
                 break;
             }
             $role->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM));
             AuthService::updateRole($role);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["role_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "user_update_right":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["repository_id"]) || !isset($httpVars["right"]) || !AuthService::userExists($httpVars["user_id"])) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"old\" write=\"old\"/>";
                 AJXP_XMLWriter::close();
                 return;
             }
             $confStorage = ConfService::getConfStorageImpl();
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             $user = $confStorage->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $user->personalRole->setAcl(AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM), AJXP_Utils::sanitize($httpVars["right"], AJXP_SANITIZE_ALPHANUM));
             $user->save();
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.46"] . $httpVars["user_id"], null);
             print "<update_checkboxes user_id=\"" . $httpVars["user_id"] . "\" repository_id=\"" . $httpVars["repository_id"] . "\" read=\"" . $user->canRead($httpVars["repository_id"]) . "\" write=\"" . $user->canWrite($httpVars["repository_id"]) . "\"/>";
             AJXP_XMLWriter::reloadRepositoryList();
             AJXP_XMLWriter::close();
             return;
             break;
         case "user_update_group":
             $userSelection = new UserSelection();
             $userSelection->initFromHttpVars($httpVars);
             $dir = $httpVars["dir"];
             $dest = $httpVars["dest"];
             if (isset($httpVars["group_path"])) {
                 // API Case
                 $groupPath = $httpVars["group_path"];
             } else {
                 if (strpos($dir, "/data/users", 0) !== 0 || strpos($dest, "/data/users", 0) !== 0) {
                     break;
                 }
                 $groupPath = substr($dest, strlen("/data/users"));
             }
             $confStorage = ConfService::getConfStorageImpl();
             $userId = null;
             $usersMoved = array();
             $basePath = AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getGroupPath() : "/";
             if (empty($basePath)) {
                 $basePath = "/";
             }
             if (!empty($groupPath)) {
                 $targetPath = rtrim($basePath, "/") . "/" . ltrim($groupPath, "/");
             } else {
                 $targetPath = $basePath;
             }
             foreach ($userSelection->getFiles() as $selectedUser) {
                 $userId = basename($selectedUser);
                 if (!AuthService::userExists($userId)) {
                     continue;
                 }
                 $user = $confStorage->createUserObject($userId);
                 if (!AuthService::canAdministrate($user)) {
                     continue;
                 }
                 $user->setGroupPath($targetPath, true);
                 $user->save("superuser");
                 $usersMoved[] = $user->getId();
             }
             AJXP_XMLWriter::header();
             if (count($usersMoved)) {
                 AJXP_XMLWriter::sendMessage(count($usersMoved) . " user(s) successfully moved to " . $targetPath, null);
                 AJXP_XMLWriter::reloadDataNode($dest, $userId);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage(null, "No users moved, there must have been something wrong.");
             }
             AJXP_XMLWriter::close();
             break;
         case "user_add_role":
         case "user_delete_role":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["role_id"]) || !AuthService::userExists($httpVars["user_id"]) || !AuthService::getRole($httpVars["role_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             if ($action == "user_add_role") {
                 $act = "add";
                 $messId = "73";
             } else {
                 $act = "remove";
                 $messId = "74";
             }
             $this->updateUserRole(AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS), $httpVars["role_id"], $act);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf." . $messId] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             return;
             break;
         case "user_update_role":
             $confStorage = ConfService::getConfStorageImpl();
             $selection = new UserSelection();
             $selection->initFromHttpVars($httpVars);
             $files = $selection->getFiles();
             $detectedRoles = array();
             $roleId = null;
             if (isset($httpVars["role_id"]) && isset($httpVars["update_role_action"])) {
                 $update = $httpVars["update_role_action"];
                 $roleId = $httpVars["role_id"];
                 if (AuthService::getRole($roleId) === false) {
                     throw new Exception("Invalid role id");
                 }
             }
             foreach ($files as $index => $file) {
                 $userId = basename($file);
                 if (isset($update)) {
                     $userObject = $this->updateUserRole($userId, $roleId, $update);
                 } else {
                     $userObject = $confStorage->createUserObject($userId);
                     if (!AuthService::canAdministrate($userObject)) {
                         continue;
                     }
                 }
                 if ($userObject->hasParent()) {
                     unset($files[$index]);
                     continue;
                 }
                 $userRoles = $userObject->getRoles();
                 foreach ($userRoles as $roleIndex => $bool) {
                     if (!isset($detectedRoles[$roleIndex])) {
                         $detectedRoles[$roleIndex] = 0;
                     }
                     if ($bool === true) {
                         $detectedRoles[$roleIndex]++;
                     }
                 }
             }
             $count = count($files);
             AJXP_XMLWriter::header("admin_data");
             print "<user><ajxp_roles>";
             foreach ($detectedRoles as $roleId => $roleCount) {
                 if ($roleCount < $count) {
                     continue;
                 }
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles></user>";
             print "<ajxp_roles>";
             foreach (AuthService::getRolesList(array(), !$this->listSpecialRoles) as $roleId => $roleObject) {
                 print "<role id=\"{$roleId}\"/>";
             }
             print "</ajxp_roles>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "save_custom_user_params":
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $custom = $user->getPref("CUSTOM_PARAMS");
             if (!is_array($custom)) {
                 $custom = array();
             }
             $options = $custom;
             $this->parseParameters($httpVars, $options, $userId, false, $custom);
             $custom = $options;
             $user->setPref("CUSTOM_PARAMS", $custom);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "save_repository_user_params":
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $user = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $user = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user with id " . $userId);
             }
             $wallet = $user->getPref("AJXP_WALLET");
             if (!is_array($wallet)) {
                 $wallet = array();
             }
             $repoID = $httpVars["repository_id"];
             if (!array_key_exists($repoID, $wallet)) {
                 $wallet[$repoID] = array();
             }
             $options = $wallet[$repoID];
             $existing = $options;
             $this->parseParameters($httpVars, $options, $userId, false, $existing);
             $wallet[$repoID] = $options;
             $user->setPref("AJXP_WALLET", $wallet);
             $user->save();
             if ($loggedUser->getId() == $user->getId()) {
                 AuthService::updateUser($user);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.47"] . $httpVars["user_id"], null);
             AJXP_XMLWriter::close();
             break;
         case "update_user_pwd":
             if (!isset($httpVars["user_id"]) || !isset($httpVars["user_pwd"]) || !AuthService::userExists($httpVars["user_id"]) || trim($httpVars["user_pwd"]) == "") {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             $user = ConfService::getConfStorageImpl()->createUserObject($userId);
             if (!AuthService::canAdministrate($user)) {
                 throw new Exception("Cannot update user data for " . $userId);
             }
             $res = AuthService::updatePassword($userId, $httpVars["user_pwd"]);
             AJXP_XMLWriter::header();
             if ($res === true) {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.48"] . $userId, null);
             } else {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.49"] . " : {$res}");
             }
             AJXP_XMLWriter::close();
             break;
         case "save_user_preference":
             if (!isset($httpVars["user_id"]) || !AuthService::userExists($httpVars["user_id"])) {
                 throw new Exception($mess["ajxp_conf.61"]);
             }
             $userId = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
             if ($userId == $loggedUser->getId()) {
                 $userObject = $loggedUser;
             } else {
                 $confStorage = ConfService::getConfStorageImpl();
                 $userObject = $confStorage->createUserObject($userId);
             }
             if (!AuthService::canAdministrate($userObject)) {
                 throw new Exception("Cannot update user data for " . $userId);
             }
             $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");
                 $i++;
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage("Succesfully saved user preference", null);
             AJXP_XMLWriter::close();
             break;
         case "get_drivers_definition":
             AJXP_XMLWriter::header("drivers", array("allowed" => $currentUserIsGroupAdmin ? "false" : "true"));
             print AJXP_XMLWriter::replaceAjxpXmlKeywords(ConfService::availableDriversToXML("param", "", true));
             AJXP_XMLWriter::close("drivers");
             break;
         case "get_templates_definition":
             AJXP_XMLWriter::header("repository_templates");
             $count = 0;
             $repositories = ConfService::listRepositoriesWithCriteria(array("isTemplate" => '1'), $count);
             foreach ($repositories as $repo) {
                 if (!$repo->isTemplate) {
                     continue;
                 }
                 $repoId = $repo->getUniqueId();
                 $repoLabel = SystemTextEncoding::toUTF8($repo->getDisplay());
                 $repoType = $repo->getAccessType();
                 print "<template repository_id=\"{$repoId}\" repository_label=\"{$repoLabel}\" repository_type=\"{$repoType}\">";
                 foreach ($repo->getOptionsDefined() as $optionName) {
                     print "<option name=\"{$optionName}\"/>";
                 }
                 print "</template>";
             }
             AJXP_XMLWriter::close("repository_templates");
             break;
         case "create_repository":
             $repDef = $httpVars;
             $isTemplate = isset($httpVars["sf_checkboxes_active"]);
             unset($repDef["get_action"]);
             unset($repDef["sf_checkboxes_active"]);
             if (isset($httpVars["json_data"])) {
                 $repDef = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
                 $options = $repDef["DRIVER_OPTIONS"];
             } else {
                 $options = array();
                 $this->parseParameters($repDef, $options, null, true);
             }
             if (count($options)) {
                 $repDef["DRIVER_OPTIONS"] = $options;
                 unset($repDef["DRIVER_OPTIONS"]["AJXP_GROUP_PATH_PARAMETER"]);
             }
             if (strstr($repDef["DRIVER"], "ajxp_template_") !== false) {
                 $templateId = substr($repDef["DRIVER"], 14);
                 $templateRepo = ConfService::getRepositoryById($templateId);
                 $newRep = $templateRepo->createTemplateChild($repDef["DISPLAY"], $repDef["DRIVER_OPTIONS"]);
                 if (isset($repDef["AJXP_SLUG"])) {
                     $newRep->setSlug($repDef["AJXP_SLUG"]);
                 }
             } else {
                 if ($currentUserIsGroupAdmin) {
                     throw new Exception("You are not allowed to create a workspace from a driver. Use a template instead.");
                 }
                 $pServ = AJXP_PluginsService::getInstance();
                 $driver = $pServ->getPluginByTypeName("access", $repDef["DRIVER"]);
                 $newRep = ConfService::createRepositoryFromArray(0, $repDef);
                 $testFile = $driver->getBaseDir() . "/test." . $newRep->getAccessType() . "Access.php";
                 if (!$isTemplate && is_file($testFile)) {
                     //chdir(AJXP_TESTS_FOLDER."/plugins");
                     $className = $newRep->getAccessType() . "AccessTest";
                     if (!class_exists($className)) {
                         include $testFile;
                     }
                     $class = new $className();
                     $result = $class->doRepositoryTest($newRep);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 // Apply default metasource if any
                 if ($driver != null && $driver->getConfigs() != null) {
                     $confs = $driver->getConfigs();
                     if (!empty($confs["DEFAULT_METASOURCES"])) {
                         $metaIds = AJXP_Utils::parseCSL($confs["DEFAULT_METASOURCES"]);
                         $metaSourceOptions = array();
                         foreach ($metaIds as $metaID) {
                             $metaPlug = $pServ->getPluginById($metaID);
                             if ($metaPlug == null) {
                                 continue;
                             }
                             $pNodes = $metaPlug->getManifestRawContent("//param[@default]", "nodes");
                             $defaultParams = array();
                             foreach ($pNodes as $domNode) {
                                 $defaultParams[$domNode->getAttribute("name")] = $domNode->getAttribute("default");
                             }
                             $metaSourceOptions[$metaID] = $defaultParams;
                         }
                         $newRep->addOption("META_SOURCES", $metaSourceOptions);
                     }
                 }
             }
             if ($this->repositoryExists($newRep->getDisplay())) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                 AJXP_XMLWriter::close();
                 return;
             }
             if ($isTemplate) {
                 $newRep->isTemplate = true;
             }
             if ($currentUserIsGroupAdmin) {
                 $newRep->setGroupPath(AuthService::getLoggedUser()->getGroupPath());
             } else {
                 if (!empty($options["AJXP_GROUP_PATH_PARAMETER"])) {
                     $basePath = "/";
                     if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                         $basePath = AuthService::getLoggedUser()->getGroupPath();
                     }
                     $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($options["AJXP_GROUP_PATH_PARAMETER"], "/"));
                     $newRep->setGroupPath($value);
                 }
             }
             $res = ConfService::addRepository($newRep);
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]);
             } else {
                 $loggedUser = AuthService::getLoggedUser();
                 $loggedUser->personalRole->setAcl($newRep->getUniqueId(), "rw");
                 $loggedUser->recomputeMergedRole();
                 $loggedUser->save("superuser");
                 AuthService::updateUser($loggedUser);
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.52"], null);
                 AJXP_XMLWriter::reloadDataNode("", $newRep->getUniqueId());
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "edit_repository":
             $repId = $httpVars["repository_id"];
             $repository = ConfService::getRepositoryById($repId);
             if ($repository == null) {
                 throw new Exception("Cannot find workspace with id {$repId}");
             }
             if (!AuthService::canAdministrate($repository)) {
                 throw new Exception("You are not allowed to edit this workspace!");
             }
             $pServ = AJXP_PluginsService::getInstance();
             $plug = $pServ->getPluginById("access." . $repository->accessType);
             if ($plug == null) {
                 throw new Exception("Cannot find access driver (" . $repository->accessType . ") for workspace!");
             }
             AJXP_XMLWriter::header("admin_data");
             $slug = $repository->getSlug();
             if ($slug == "" && $repository->isWriteable()) {
                 $repository->setSlug();
                 ConfService::replaceRepository($repId, $repository);
             }
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                 $rgp = $repository->getGroupPath();
                 if ($rgp == null) {
                     $rgp = "/";
                 }
                 if (strlen($rgp) < strlen(AuthService::getLoggedUser()->getGroupPath())) {
                     $repository->setWriteable(false);
                 }
             }
             $nested = array();
             $definitions = $plug->getConfigsDefinitions();
             print "<repository index=\"{$repId}\"";
             foreach ($repository as $name => $option) {
                 if (strstr($name, " ") > -1) {
                     continue;
                 }
                 if (!is_array($option)) {
                     if (is_bool($option)) {
                         $option = $option ? "true" : "false";
                     }
                     print " {$name}=\"" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($option)) . "\" ";
                 } else {
                     if (is_array($option)) {
                         $nested[] = $option;
                     }
                 }
             }
             if (count($nested)) {
                 print ">";
                 foreach ($nested as $option) {
                     foreach ($option as $key => $optValue) {
                         if (is_array($optValue) && count($optValue)) {
                             print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>";
                         } else {
                             if (is_object($optValue)) {
                                 print "<param name=\"{$key}\"><![CDATA[" . json_encode($optValue) . "]]></param>";
                             } else {
                                 if (is_bool($optValue)) {
                                     $optValue = $optValue ? "true" : "false";
                                 } else {
                                     if (isset($definitions[$key]) && $definitions[$key]["type"] == "password" && !empty($optValue)) {
                                         $optValue = "__AJXP_VALUE_SET__";
                                     }
                                 }
                                 $optValue = AJXP_Utils::xmlEntities($optValue, true);
                                 print "<param name=\"{$key}\" value=\"{$optValue}\"/>";
                             }
                         }
                     }
                 }
                 // Add SLUG
                 if (!$repository->isTemplate) {
                     print "<param name=\"AJXP_SLUG\" value=\"" . $repository->getSlug() . "\"/>";
                 }
                 if ($repository->getGroupPath() != null) {
                     $basePath = "/";
                     if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                         $basePath = AuthService::getLoggedUser()->getGroupPath();
                     }
                     $groupPath = $repository->getGroupPath();
                     if ($basePath != "/") {
                         $groupPath = substr($repository->getGroupPath(), strlen($basePath));
                     }
                     print "<param name=\"AJXP_GROUP_PATH_PARAMETER\" value=\"" . $groupPath . "\"/>";
                 }
                 print "</repository>";
             } else {
                 print "/>";
             }
             if ($repository->hasParent()) {
                 $parent = ConfService::getRepositoryById($repository->getParentId());
                 if (isset($parent) && $parent->isTemplate) {
                     $parentLabel = $parent->getDisplay();
                     $parentType = $parent->getAccessType();
                     print "<template repository_id=\"" . $repository->getParentId() . "\" repository_label=\"{$parentLabel}\" repository_type=\"{$parentType}\">";
                     foreach ($parent->getOptionsDefined() as $parentOptionName) {
                         print "<option name=\"{$parentOptionName}\"/>";
                     }
                     print "</template>";
                 }
             }
             $manifest = $plug->getManifestRawContent("server_settings/param");
             $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
             print "<ajxpdriver name=\"" . $repository->accessType . "\">{$manifest}</ajxpdriver>";
             print "<metasources>";
             $metas = $pServ->getPluginsByType("metastore");
             $metas = array_merge($metas, $pServ->getPluginsByType("meta"));
             $metas = array_merge($metas, $pServ->getPluginsByType("index"));
             foreach ($metas as $metaPlug) {
                 print "<meta id=\"" . $metaPlug->getId() . "\" label=\"" . AJXP_Utils::xmlEntities($metaPlug->getManifestLabel()) . "\">";
                 $manifest = $metaPlug->getManifestRawContent("server_settings/param");
                 $manifest = AJXP_XMLWriter::replaceAjxpXmlKeywords($manifest);
                 print $manifest;
                 print "</meta>";
             }
             print "</metasources>";
             AJXP_XMLWriter::close("admin_data");
             return;
             break;
         case "edit_repository_label":
         case "edit_repository_data":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!$repo->isWriteable()) {
                 throw new Exception("This workspace is not writeable. Please edit directly the conf/bootstrap_repositories.php file.");
             }
             $res = 0;
             if (isset($httpVars["newLabel"])) {
                 $newLabel = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["newLabel"]), AJXP_SANITIZE_HTML);
                 if ($this->repositoryExists($newLabel)) {
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.50"]);
                     AJXP_XMLWriter::close();
                     return;
                 }
                 $repo->setDisplay($newLabel);
                 $res = ConfService::replaceRepository($repId, $repo);
             } else {
                 $options = array();
                 $existing = $repo->getOptionsDefined();
                 $existingValues = array();
                 foreach ($existing as $exK) {
                     $existingValues[$exK] = $repo->getOption($exK, true);
                 }
                 $this->parseParameters($httpVars, $options, null, true, $existingValues);
                 if (count($options)) {
                     foreach ($options as $key => $value) {
                         if ($key == "AJXP_SLUG") {
                             $repo->setSlug($value);
                             continue;
                         } elseif ($key == "AJXP_GROUP_PATH_PARAMETER") {
                             $basePath = "/";
                             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != null) {
                                 $basePath = AuthService::getLoggedUser()->getGroupPath();
                             }
                             $value = AJXP_Utils::securePath(rtrim($basePath, "/") . "/" . ltrim($value, "/"));
                             $repo->setGroupPath($value);
                             continue;
                         }
                         $repo->addOption($key, $value);
                     }
                 }
                 if ($repo->getOption("DEFAULT_RIGHTS")) {
                     $gp = $repo->getGroupPath();
                     if (empty($gp) || $gp == "/") {
                         $defRole = AuthService::getRole("ROOT_ROLE");
                     } else {
                         $defRole = AuthService::getRole("AJXP_GRP_" . $gp, true);
                     }
                     if ($defRole !== false) {
                         $defRole->setAcl($repId, $repo->getOption("DEFAULT_RIGHTS"));
                         AuthService::updateRole($defRole);
                     }
                 }
                 if (is_file(AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php")) {
                     chdir(AJXP_TESTS_FOLDER . "/plugins");
                     include AJXP_TESTS_FOLDER . "/plugins/test.ajxp_" . $repo->getAccessType() . ".php";
                     $className = "ajxp_" . $repo->getAccessType();
                     $class = new $className();
                     $result = $class->doRepositoryTest($repo);
                     if (!$result) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage(null, $class->failedInfo);
                         AJXP_XMLWriter::close();
                         return;
                     }
                 }
                 ConfService::replaceRepository($repId, $repo);
             }
             AJXP_XMLWriter::header();
             if ($res == -1) {
                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.53"]);
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.54"], null);
                 if (isset($httpVars["newLabel"])) {
                     AJXP_XMLWriter::reloadDataNode("", $repId);
                 }
                 AJXP_XMLWriter::reloadRepositoryList();
             }
             AJXP_XMLWriter::close();
             break;
         case "meta_source_add":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceType = AJXP_Utils::sanitize($httpVars["new_meta_source"], AJXP_SANITIZE_ALPHANUM);
             if (isset($httpVars["json_data"])) {
                 $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
             } else {
                 $options = array();
                 $this->parseParameters($httpVars, $options, null, true);
             }
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && isset($repoOptions[$metaSourceType])) {
                 throw new Exception($mess["ajxp_conf.55"]);
             }
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             $repoOptions[$metaSourceType] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.56"], null);
             AJXP_XMLWriter::close();
             break;
         case "meta_source_delete":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $repoOptions = $repo->getOption("META_SOURCES");
             if (is_array($repoOptions) && array_key_exists($metaSourceId, $repoOptions)) {
                 unset($repoOptions[$metaSourceId]);
                 uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
                 $repo->addOption("META_SOURCES", $repoOptions);
                 ConfService::replaceRepository($repId, $repo);
             } else {
                 throw new Exception("Cannot find meta source " . $metaSourceId);
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.57"], null);
             AJXP_XMLWriter::close();
             break;
         case "meta_source_edit":
             $repId = $httpVars["repository_id"];
             $repo = ConfService::getRepositoryById($repId);
             if (!is_object($repo)) {
                 throw new Exception("Invalid workspace id! {$repId}");
             }
             $metaSourceId = $httpVars["plugId"];
             $repoOptions = $repo->getOption("META_SOURCES");
             if (!is_array($repoOptions)) {
                 $repoOptions = array();
             }
             if (isset($httpVars["json_data"])) {
                 $options = json_decode(SystemTextEncoding::magicDequote($httpVars["json_data"]), true);
             } else {
                 $options = array();
                 $this->parseParameters($httpVars, $options, null, true);
             }
             if (isset($repoOptions[$metaSourceId])) {
                 $this->mergeExistingParameters($options, $repoOptions[$metaSourceId]);
             }
             $repoOptions[$metaSourceId] = $options;
             uksort($repoOptions, array($this, "metaSourceOrderingFunction"));
             $repo->addOption("META_SOURCES", $repoOptions);
             ConfService::replaceRepository($repId, $repo);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.58"], null);
             AJXP_XMLWriter::close();
             break;
         case "delete":
             // REST API mapping
             if (isset($httpVars["data_type"])) {
                 switch ($httpVars["data_type"]) {
                     case "repository":
                         $httpVars["repository_id"] = basename($httpVars["data_id"]);
                         break;
                     case "role":
                         $httpVars["role_id"] = basename($httpVars["data_id"]);
                         break;
                     case "user":
                         $httpVars["user_id"] = basename($httpVars["data_id"]);
                         break;
                     case "group":
                         $httpVars["group"] = "/data/users" . $httpVars["data_id"];
                         break;
                     default:
                         break;
                 }
                 unset($httpVars["data_type"]);
                 unset($httpVars["data_id"]);
             }
             if (isset($httpVars["repository_id"])) {
                 $repId = $httpVars["repository_id"];
                 $repo = ConfService::getRepositoryById($repId);
                 if (!is_object($repo)) {
                     $res = -1;
                 } else {
                     $res = ConfService::deleteRepository($repId);
                 }
                 AJXP_XMLWriter::header();
                 if ($res == -1) {
                     AJXP_XMLWriter::sendMessage(null, $mess[427]);
                 } else {
                     AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::reloadRepositoryList();
                 }
                 AJXP_XMLWriter::close();
                 return;
             } else {
                 if (isset($httpVars["role_id"])) {
                     $roleId = $httpVars["role_id"];
                     if (AuthService::getRole($roleId) === false) {
                         throw new Exception($mess["ajxp_conf.67"]);
                     }
                     AuthService::deleteRole($roleId);
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage($mess["ajxp_conf.68"], null);
                     AJXP_XMLWriter::reloadDataNode();
                     AJXP_XMLWriter::close();
                 } else {
                     if (isset($httpVars["group"])) {
                         $groupPath = $httpVars["group"];
                         $basePath = substr(AJXP_Utils::forwardSlashDirname($groupPath), strlen("/data/users"));
                         $gName = basename($groupPath);
                         AuthService::deleteGroup($basePath, $gName);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.128"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     } else {
                         if (!isset($httpVars["user_id"]) || $httpVars["user_id"] == "" || AuthService::isReservedUserId($httpVars["user_id"]) || $loggedUser->getId() == $httpVars["user_id"]) {
                             AJXP_XMLWriter::header();
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.61"]);
                             AJXP_XMLWriter::close();
                         }
                         AuthService::deleteUser($httpVars["user_id"]);
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null);
                         AJXP_XMLWriter::reloadDataNode();
                         AJXP_XMLWriter::close();
                     }
                 }
             }
             break;
         case "get_plugin_manifest":
             $ajxpPlugin = AJXP_PluginsService::getInstance()->getPluginById($httpVars["plugin_id"]);
             AJXP_XMLWriter::header("admin_data");
             $fullManifest = $ajxpPlugin->getManifestRawContent("", "xml");
             $xPath = new DOMXPath($fullManifest->ownerDocument);
             $addParams = "";
             $instancesDefinitions = array();
             $pInstNodes = $xPath->query("server_settings/global_param[contains(@type, 'plugin_instance:')]");
             foreach ($pInstNodes as $pInstNode) {
                 $type = $pInstNode->getAttribute("type");
                 $instType = str_replace("plugin_instance:", "", $type);
                 $fieldName = $pInstNode->getAttribute("name");
                 $pInstNode->setAttribute("type", "group_switch:" . $fieldName);
                 $typePlugs = AJXP_PluginsService::getInstance()->getPluginsByType($instType);
                 foreach ($typePlugs as $typePlug) {
                     if ($typePlug->getId() == "auth.multi") {
                         continue;
                     }
                     $checkErrorMessage = "";
                     try {
                         $typePlug->performChecks();
                     } catch (Exception $e) {
                         $checkErrorMessage = " (Warning : " . $e->getMessage() . ")";
                     }
                     $tParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[not(@group_switch_name)]"));
                     $addParams .= '<global_param group_switch_name="' . $fieldName . '" name="instance_name" group_switch_label="' . $typePlug->getManifestLabel() . $checkErrorMessage . '" group_switch_value="' . $typePlug->getId() . '" default="' . $typePlug->getId() . '" type="hidden"/>';
                     $addParams .= str_replace("<param", "<global_param group_switch_name=\"{$fieldName}\" group_switch_label=\"" . $typePlug->getManifestLabel() . $checkErrorMessage . "\" group_switch_value=\"" . $typePlug->getId() . "\" ", $tParams);
                     $addParams .= str_replace("<param", "<global_param", AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/param[@group_switch_name]")));
                     $addParams .= AJXP_XMLWriter::replaceAjxpXmlKeywords($typePlug->getManifestRawContent("server_settings/global_param"));
                     $instancesDefs = $typePlug->getConfigsDefinitions();
                     if (!empty($instancesDefs) && is_array($instancesDefs)) {
                         foreach ($instancesDefs as $defKey => $defData) {
                             $instancesDefinitions[$fieldName . "/" . $defKey] = $defData;
                         }
                     }
                 }
             }
             $allParams = AJXP_XMLWriter::replaceAjxpXmlKeywords($fullManifest->ownerDocument->saveXML($fullManifest));
             $allParams = str_replace('type="plugin_instance:', 'type="group_switch:', $allParams);
             $allParams = str_replace("</server_settings>", $addParams . "</server_settings>", $allParams);
             echo $allParams;
             $definitions = $instancesDefinitions;
             $configsDefs = $ajxpPlugin->getConfigsDefinitions();
             if (is_array($configsDefs)) {
                 $definitions = array_merge($configsDefs, $instancesDefinitions);
             }
             $values = $ajxpPlugin->getConfigs();
             if (!is_array($values)) {
                 $values = array();
             }
             echo "<plugin_settings_values>";
             // First flatten keys
             $flattenedKeys = array();
             foreach ($values as $key => $value) {
                 $type = $definitions[$key]["type"];
                 if ((strpos($type, "group_switch:") === 0 || strpos($type, "plugin_instance:") === 0) && is_array($value)) {
                     $res = array();
                     $this->flattenKeyValues($res, $definitions, $value, $key);
                     $flattenedKeys += $res;
                     // Replace parent key by new flat value
                     $values[$key] = $flattenedKeys[$key];
                 }
             }
             $values += $flattenedKeys;
             foreach ($values as $key => $value) {
                 $attribute = true;
                 $type = $definitions[$key]["type"];
                 if ($type == "array" && is_array($value)) {
                     $value = implode(",", $value);
                 } else {
                     if ($type == "boolean") {
                         $value = $value === true || $value === "true" || $value == 1 ? "true" : "false";
                     } else {
                         if ($type == "textarea") {
                             $attribute = false;
                         } else {
                             if ($type == "password" && !empty($value)) {
                                 $value = "__AJXP_VALUE_SET__";
                             }
                         }
                     }
                 }
                 if ($attribute) {
                     echo "<param name=\"{$key}\" value=\"" . AJXP_Utils::xmlEntities($value) . "\"/>";
                 } else {
                     echo "<param name=\"{$key}\" cdatavalue=\"true\"><![CDATA[" . $value . "]]></param>";
                 }
             }
             if ($ajxpPlugin->getType() != "core") {
                 echo "<param name=\"AJXP_PLUGIN_ENABLED\" value=\"" . ($ajxpPlugin->isEnabled() ? "true" : "false") . "\"/>";
             }
             echo "</plugin_settings_values>";
             echo "<plugin_doc><![CDATA[<p>" . $ajxpPlugin->getPluginInformationHTML("Charles du Jeu", "http://pyd.io/plugins/") . "</p>";
             if (file_exists($ajxpPlugin->getBaseDir() . "/plugin_doc.html")) {
                 echo file_get_contents($ajxpPlugin->getBaseDir() . "/plugin_doc.html");
             }
             echo "]]></plugin_doc>";
             AJXP_XMLWriter::close("admin_data");
             break;
         case "run_plugin_action":
             $options = array();
             $this->parseParameters($httpVars, $options, null, true);
             $pluginId = $httpVars["action_plugin_id"];
             if (isset($httpVars["button_key"])) {
                 $options = $options[$httpVars["button_key"]];
             }
             $plugin = AJXP_PluginsService::getInstance()->softLoad($pluginId, $options);
             if (method_exists($plugin, $httpVars["action_plugin_method"])) {
                 try {
                     $res = call_user_func(array($plugin, $httpVars["action_plugin_method"]), $options);
                 } catch (Exception $e) {
                     echo "ERROR:" . $e->getMessage();
                     break;
                 }
                 echo $res;
             } else {
                 echo 'ERROR: Plugin ' . $httpVars["action_plugin_id"] . ' does not implement ' . $httpVars["action_plugin_method"] . ' method!';
             }
             break;
         case "edit_plugin_options":
             $options = array();
             $this->parseParameters($httpVars, $options, null, true);
             $confStorage = ConfService::getConfStorageImpl();
             list($pType, $pName) = explode(".", $httpVars["plugin_id"]);
             $existing = $confStorage->loadPluginConfig($pType, $pName);
             $this->mergeExistingParameters($options, $existing);
             $confStorage->savePluginConfig($httpVars["plugin_id"], $options);
             AJXP_PluginsService::clearPluginsCache();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["ajxp_conf.97"], null);
             AJXP_XMLWriter::close();
             break;
         case "generate_api_docs":
             PydioSdkGenerator::analyzeRegistry(isset($httpVars["version"]) ? $httpVars["version"] : AJXP_VERSION);
             break;
             // Action for update all Pydio's user from ldap in CLI mode
         // Action for update all Pydio's user from ldap in CLI mode
         case "cli_update_user_list":
             if (php_sapi_name() == "cli") {
                 $progressBar = new AJXP_ProgressBarCLI();
                 $countCallback = array($progressBar, "init");
                 $loopCallback = array($progressBar, "update");
                 AuthService::listUsers("/", null, -1, -1, true, true, $countCallback, $loopCallback);
             }
             break;
         default:
             break;
     }
     return;
 }
 public function unifyChunks($action, &$httpVars, &$fileVars)
 {
     $filename = AJXP_Utils::decodeSecureMagic($httpVars["name"]);
     $tmpName = $fileVars["file"]["tmp_name"];
     $chunk = $httpVars["chunk"];
     $chunks = $httpVars["chunks"];
     //error_log("currentChunk:".$chunk."  chunks: ".$chunks);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $wrapperName = $streamData["classname"];
     $dir = AJXP_Utils::securePath($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $driver = ConfService::loadDriverForRepository($repository);
     $remote = false;
     if (method_exists($driver, "storeFileToCopy")) {
         $remote = true;
         $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($repository->getOption("TMP_UPLOAD"));
         // Make tmp folder a bit more unique using secure_token
         $tmpFolder = $destCopy . "/" . $httpVars["secure_token"];
         if (!is_dir($tmpFolder)) {
             @mkdir($tmpFolder, 0700, true);
         }
         $target = $tmpFolder . '/' . $filename;
         $fileVars["file"]["destination"] = base64_encode($dir);
     } else {
         if (call_user_func(array($wrapperName, "isRemote"))) {
             $remote = true;
             $tmpFolder = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["secure_token"];
             if (!is_dir($tmpFolder)) {
                 @mkdir($tmpFolder, 0700, true);
             }
             $target = $tmpFolder . '/' . $filename;
         } else {
             $target = $destStreamURL . $filename;
         }
     }
     //error_log("Directory: ".$dir);
     // Clean the fileName for security reasons
     //$filename = preg_replace('/[^\w\._]+/', '', $filename);
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($tmpName) && is_uploaded_file($tmpName)) {
             //error_log("tmpName: ".$tmpName);
             // Open temp file
             $out = fopen($target, $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen($tmpName, "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($tmpName);
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
             }
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
     } else {
         // Open temp file
         $out = fopen($target, $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
             }
             fclose($in);
             fclose($out);
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         }
     }
     /* we apply the hook if we are uploading the last chunk */
     if ($chunk == $chunks - 1) {
         if (!$remote) {
             AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($destStreamURL . $filename), false));
         } else {
             if (method_exists($driver, "storeFileToCopy")) {
                 $fileVars["file"]["tmp_name"] = $target;
                 $fileVars["file"]["name"] = $filename;
                 $driver->storeFileToCopy($fileVars["file"]);
                 AJXP_Controller::findActionAndApply("next_to_remote", array(), array());
             } else {
                 // Remote Driver case: copy temp file to destination
                 $node = new AJXP_Node($destStreamURL . $filename);
                 AJXP_Controller::applyHook("node.before_create", array($node, filesize($target)));
                 AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destStreamURL)));
                 $res = copy($target, $destStreamURL . $filename);
                 if ($res) {
                     @unlink($target);
                 }
                 AJXP_Controller::applyHook("node.change", array(null, $node, false));
             }
         }
     }
     // Return JSON-RPC response
     die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
 }
예제 #11
0
 /**
  * Main callback for all share- actions.
  * @param string $action
  * @param array $httpVars
  * @param array $fileVars
  * @return null
  * @throws Exception
  */
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (strpos($action, "sharelist") === false && !isset($this->accessDriver)) {
         throw new Exception("Cannot find access driver!");
     }
     if (strpos($action, "sharelist") === false && $this->accessDriver->getId() == "access.demo") {
         $errorMessage = "This is a demo, all 'write' actions are disabled!";
         if ($httpVars["sub_action"] == "delegate_repo") {
             return AJXP_XMLWriter::sendMessage(null, $errorMessage, false);
         } else {
             print $errorMessage;
         }
         return null;
     }
     switch ($action) {
         //------------------------------------
         // SHARING FILE OR FOLDER
         //------------------------------------
         case "share":
             $subAction = isset($httpVars["sub_action"]) ? $httpVars["sub_action"] : "";
             // REST API COMPATIBILITY
             if (empty($subAction) && isset($httpVars["simple_share_type"])) {
                 $subAction = "create_minisite";
                 if (!isset($httpVars["simple_right_read"]) && !isset($httpVars["simple_right_download"])) {
                     $httpVars["simple_right_read"] = $httpVars["simple_right_download"] = "true";
                 }
                 $httpVars["create_guest_user"] = "******";
                 if ($httpVars["simple_share_type"] == "private" && !isset($httpVars["guest_user_pass"])) {
                     throw new Exception("Please provide a guest_user_pass for private link");
                 }
             }
             $userSelection = new UserSelection(ConfService::getRepository(), $httpVars);
             $ajxpNode = $userSelection->getUniqueNode();
             if (!file_exists($ajxpNode->getUrl())) {
                 throw new Exception("Cannot share a non-existing file: " . $ajxpNode->getUrl());
             }
             $this->updateToMaxAllowedValue($httpVars, "downloadlimit", "FILE_MAX_DOWNLOAD");
             $this->updateToMaxAllowedValue($httpVars, "expiration", "FILE_MAX_EXPIRATION");
             $httpHash = null;
             $originalHash = null;
             if (!isset($httpVars["share_scope"]) || !in_array($httpVars["share_scope"], array("public", "private"))) {
                 $httpVars["share_scope"] = "private";
             }
             $shareScope = $httpVars["share_scope"];
             $plainResult = 'unknown sub_action';
             if ($subAction == "delegate_repo") {
                 $auth = $this->getAuthorization("folder", "workspace");
                 if (!$auth) {
                     $mess = ConfService::getMessages();
                     throw new Exception($mess["351"]);
                 }
                 $users = array();
                 $groups = array();
                 $this->getRightsManager()->createUsersFromParameters($httpVars, $users, $groups);
                 $result = $this->createSharedRepository($httpVars, $isUpdate, $users, $groups);
                 if (is_a($result, "Repository")) {
                     if (!$isUpdate) {
                         $this->getShareStore()->storeShare($this->repository->getId(), array("REPOSITORY" => $result->getUniqueId(), "OWNER_ID" => AuthService::getLoggedUser()->getId()), "repository");
                     }
                     AJXP_Controller::applyHook($isUpdate ? "node.share.update" : "node.share.create", array('type' => 'repository', 'repository' => &$this->repository, 'accessDriver' => &$this->accessDriver, 'new_repository' => &$result));
                     if ($ajxpNode->hasMetaStore() && !$ajxpNode->isRoot()) {
                         $this->getShareStore()->getMetaManager()->addShareInMeta($ajxpNode, "repository", $result->getUniqueId(), $shareScope == "public", $originalHash);
                     }
                     $plainResult = 200;
                 } else {
                     $plainResult = $result;
                 }
             } else {
                 if ($subAction == "create_minisite") {
                     if (isset($httpVars["hash"]) && !empty($httpVars["hash"])) {
                         $httpHash = $httpVars["hash"];
                     }
                     $result = $this->createSharedMinisite($httpVars, $isUpdate);
                     if (!is_array($result)) {
                         $url = $result;
                     } else {
                         list($hash, $url) = $result;
                         if ($ajxpNode->hasMetaStore() && !$ajxpNode->isRoot()) {
                             $this->getShareStore()->getMetaManager()->addShareInMeta($ajxpNode, "minisite", $hash, $shareScope == "public", $httpHash != null && $hash != $httpHash ? $httpHash : null);
                         }
                     }
                     $plainResult = $url;
                 } else {
                     if ($subAction == "share_node") {
                         $httpVars["return_json"] = true;
                         if (isset($httpVars["hash"]) && !empty($httpVars["hash"])) {
                             $httpHash = $httpVars["hash"];
                         }
                         $ajxpNode->loadNodeInfo();
                         $results = $this->shareNode($ajxpNode, $httpVars, $isUpdate);
                         if (is_array($results) && $ajxpNode->hasMetaStore() && !$ajxpNode->isRoot()) {
                             foreach ($results as $shareObject) {
                                 if ($shareObject instanceof \Pydio\OCS\Model\TargettedLink) {
                                     $hash = $shareObject->getHash();
                                     $this->getShareStore()->getMetaManager()->addShareInMeta($ajxpNode, "ocs_remote", $hash, $shareScope == "public", $hash);
                                 } else {
                                     if (is_a($shareObject, "ShareLink")) {
                                         $hash = $shareObject->getHash();
                                         $this->getShareStore()->getMetaManager()->addShareInMeta($ajxpNode, "minisite", $hash, $shareScope == "public", $httpHash != null && $hash != $httpHash ? $httpHash : null);
                                     } else {
                                         if (is_a($shareObject, "Repository")) {
                                             $this->getShareStore()->getMetaManager()->addShareInMeta($ajxpNode, "repository", $shareObject->getUniqueId(), $shareScope == "public", null);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             AJXP_Controller::applyHook("msg.instant", array("<reload_shared_elements/>", ConfService::getRepository()->getId()));
             /*
              * Send IM to inform that node has been shared or unshared.
              * Should be done only if share scope is public.
              */
             if ($shareScope == "public") {
                 $ajxpNode->loadNodeInfo();
                 $content = AJXP_XMLWriter::writeNodesDiff(["UPDATE" => array($ajxpNode->getPath() => $ajxpNode)]);
                 AJXP_Controller::applyHook("msg.instant", array($content, $ajxpNode->getRepositoryId(), null, null, [$ajxpNode->getPath()]));
             }
             if (!isset($httpVars["return_json"])) {
                 header("Content-Type: text/plain");
                 print $plainResult;
             } else {
                 $compositeShare = $this->getShareStore()->getMetaManager()->getCompositeShareForNode($ajxpNode);
                 header("Content-type:application/json");
                 if (!empty($compositeShare)) {
                     echo json_encode($this->compositeShareToJson($compositeShare));
                 } else {
                     echo json_encode(array());
                 }
             }
             // as the result can be quite small (e.g error code), make sure it's output in case of OB active.
             flush();
             break;
         case "toggle_link_watch":
             $userSelection = new UserSelection($this->repository, $httpVars);
             $shareNode = $selectedNode = $userSelection->getUniqueNode();
             $watchValue = $httpVars["set_watch"] == "true" ? true : false;
             $folder = false;
             if (isset($httpVars["element_type"]) && $httpVars["element_type"] == "folder") {
                 $folder = true;
                 $selectedNode = new AJXP_Node("pydio://" . AJXP_Utils::sanitize($httpVars["repository_id"], AJXP_SANITIZE_ALPHANUM) . "/");
             }
             $shares = array();
             $this->getShareStore()->getMetaManager()->getSharesFromMeta($shareNode, $shares, false);
             if (!count($shares)) {
                 break;
             }
             if (isset($httpVars["element_id"]) && isset($shares[$httpVars["element_id"]])) {
                 $elementId = $httpVars["element_id"];
             } else {
                 $sKeys = array_keys($shares);
                 $elementId = $sKeys[0];
             }
             if ($this->watcher !== false) {
                 if (!$folder) {
                     if ($watchValue) {
                         $this->watcher->setWatchOnFolder($selectedNode, AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_USERS_READ, array($elementId));
                     } else {
                         $this->watcher->removeWatchFromFolder($selectedNode, AuthService::getLoggedUser()->getId(), true, $elementId);
                     }
                 } else {
                     if ($watchValue) {
                         $this->watcher->setWatchOnFolder($selectedNode, AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH);
                     } else {
                         $this->watcher->removeWatchFromFolder($selectedNode, AuthService::getLoggedUser()->getId());
                     }
                 }
             }
             $mess = ConfService::getMessages();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($mess["share_center.47"], null);
             AJXP_XMLWriter::close();
             break;
         case "load_shared_element_data":
             $node = null;
             if (isset($httpVars["hash"]) && $httpVars["element_type"] == "file") {
                 // LEGACY LINKS
                 $parsedMeta = array($httpVars["hash"] => array("type" => "file"));
                 $jsonData = array();
                 foreach ($parsedMeta as $shareId => $shareMeta) {
                     $jsonData[] = $this->shareToJson($shareId, $shareMeta, $node);
                 }
                 header("Content-type:application/json");
                 echo json_encode($jsonData);
             } else {
                 $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
                 $node = new AJXP_Node($this->urlBase . $file);
                 $loggedUser = AuthService::getLoggedUser();
                 if (isset($httpVars["owner"]) && $loggedUser->isAdmin() && $loggedUser->getGroupPath() == "/" && $loggedUser->getId() != AJXP_Utils::sanitize($httpVars["owner"], AJXP_SANITIZE_EMAILCHARS)) {
                     // Impersonate the current user
                     $node->setUser(AJXP_Utils::sanitize($httpVars["owner"], AJXP_SANITIZE_EMAILCHARS));
                 }
                 if (!file_exists($node->getUrl())) {
                     $mess = ConfService::getMessages();
                     throw new Exception(str_replace('%s', "Cannot find file " . $file, $mess["share_center.219"]));
                 }
                 if (isset($httpVars["tmp_repository_id"]) && AuthService::getLoggedUser()->isAdmin()) {
                     $compositeShare = $this->getShareStore()->getMetaManager()->getCompositeShareForNode($node, true);
                 } else {
                     $compositeShare = $this->getShareStore()->getMetaManager()->getCompositeShareForNode($node);
                 }
                 if (empty($compositeShare)) {
                     $mess = ConfService::getMessages();
                     throw new Exception(str_replace('%s', "Cannot find share for node " . $file, $mess["share_center.219"]));
                 }
                 header("Content-type:application/json");
                 $json = $this->compositeShareToJson($compositeShare);
                 echo json_encode($json);
             }
             break;
         case "unshare":
             $mess = ConfService::getMessages();
             $userSelection = new UserSelection($this->repository, $httpVars);
             if (isset($httpVars["hash"])) {
                 $sanitizedHash = AJXP_Utils::sanitize($httpVars["hash"], AJXP_SANITIZE_ALPHANUM);
                 $ajxpNode = $userSelection->isEmpty() ? null : $userSelection->getUniqueNode();
                 $result = $this->getShareStore()->deleteShare($httpVars["element_type"], $sanitizedHash, false, false, $ajxpNode);
                 if ($result !== false) {
                     AJXP_XMLWriter::header();
                     AJXP_XMLWriter::sendMessage($mess["share_center.216"], null);
                     AJXP_XMLWriter::close();
                 }
             } else {
                 $userSelection = new UserSelection($this->repository, $httpVars);
                 $ajxpNode = $userSelection->getUniqueNode();
                 $shares = array();
                 $this->getShareStore()->getMetaManager()->getSharesFromMeta($ajxpNode, $shares, false);
                 if (isset($httpVars["element_id"]) && isset($shares[$httpVars["element_id"]])) {
                     $elementId = $httpVars["element_id"];
                     if (isset($shares[$elementId])) {
                         $shares = array($elementId => $shares[$elementId]);
                     }
                 }
                 if (count($shares)) {
                     $res = true;
                     foreach ($shares as $shareId => $share) {
                         $t = isset($share["type"]) ? $share["type"] : "file";
                         try {
                             $result = $this->getShareStore()->deleteShare($t, $shareId, false, true);
                         } catch (Exception $e) {
                             if ($e->getMessage() == "repo-not-found") {
                                 $result = true;
                             } else {
                                 throw $e;
                             }
                         }
                         $this->getShareStore()->getMetaManager()->removeShareFromMeta($ajxpNode, $shareId);
                         $res = $result && $res;
                     }
                     if ($res !== false) {
                         AJXP_XMLWriter::header();
                         AJXP_XMLWriter::sendMessage($mess["share_center.216"], null);
                         AJXP_XMLWriter::close();
                         AJXP_Controller::applyHook("msg.instant", array("<reload_shared_elements/>", ConfService::getRepository()->getId()));
                         if (isset($httpVars["share_scope"]) && $httpVars["share_scope"] == "public") {
                             $ajxpNode->loadNodeInfo();
                             $content = AJXP_XMLWriter::writeNodesDiff(["UPDATE" => [$ajxpNode->getPath() => $ajxpNode]]);
                             AJXP_Controller::applyHook("msg.instant", array($content, $ajxpNode->getRepositoryId(), null, null, [$ajxpNode->getPath()]));
                         }
                     }
                 }
             }
             break;
         case "reset_counter":
             if (isset($httpVars["hash"])) {
                 $userId = AuthService::getLoggedUser()->getId();
                 if (isset($httpVars["owner_id"]) && $httpVars["owner_id"] != $userId) {
                     if (!AuthService::getLoggedUser()->isAdmin()) {
                         throw new Exception("You are not allowed to access this resource");
                     }
                     $userId = $httpVars["owner_id"];
                 }
                 $this->getShareStore()->resetDownloadCounter($httpVars["hash"], $userId);
             } else {
                 $userSelection = new UserSelection($this->repository, $httpVars);
                 $ajxpNode = $userSelection->getUniqueNode();
                 $metadata = $this->getShareStore()->getMetaManager()->getNodeMeta($ajxpNode);
                 if (!isset($metadata["shares"]) || !is_array($metadata["shares"])) {
                     return null;
                 }
                 if (isset($httpVars["element_id"]) && isset($metadata["shares"][$httpVars["element_id"]])) {
                     $this->getShareStore()->resetDownloadCounter($httpVars["element_id"], $httpVars["owner_id"]);
                 } else {
                     $keys = array_keys($metadata["shares"]);
                     foreach ($keys as $key) {
                         $this->getShareStore()->resetDownloadCounter($key, null);
                     }
                 }
             }
             break;
         case "update_shared_element_data":
             if (!in_array($httpVars["p_name"], array("counter", "tags"))) {
                 return null;
             }
             $hash = AJXP_Utils::decodeSecureMagic($httpVars["element_id"]);
             $userSelection = new UserSelection($this->repository, $httpVars);
             $ajxpNode = $userSelection->getUniqueNode();
             if ($this->getShareStore()->shareIsLegacy($hash)) {
                 // Store in metadata
                 $metadata = $this->getShareStore()->getMetaManager()->getNodeMeta($ajxpNode);
                 if (isset($metadata["shares"][$httpVars["element_id"]])) {
                     if (!is_array($metadata["shares"][$httpVars["element_id"]])) {
                         $metadata["shares"][$httpVars["element_id"]] = array();
                     }
                     $metadata["shares"][$httpVars["element_id"]][$httpVars["p_name"]] = $httpVars["p_value"];
                     // Set Private=true by default.
                     $this->getShareStore()->getMetaManager()->setNodeMeta($ajxpNode, $metadata, true);
                 }
             } else {
                 // TODO: testUserCanEditShare ?
                 $this->getShareStore()->updateShareProperty($hash, $httpVars["p_name"], $httpVars["p_value"]);
             }
             break;
         case "sharelist-load":
             $parentRepoId = isset($httpVars["parent_repository_id"]) ? $httpVars["parent_repository_id"] : "";
             $userContext = $httpVars["user_context"];
             $currentUser = true;
             if ($userContext == "global" && AuthService::getLoggedUser()->isAdmin()) {
                 $currentUser = false;
             } else {
                 if ($userContext == "user" && AuthService::getLoggedUser()->isAdmin() && !empty($httpVars["user_id"])) {
                     $currentUser = AJXP_Utils::sanitize($httpVars["user_id"], AJXP_SANITIZE_EMAILCHARS);
                 }
             }
             $nodes = $this->listSharesAsNodes("/data/repositories/{$parentRepoId}/shares", $currentUser, $parentRepoId);
             AJXP_XMLWriter::header();
             if ($userContext == "current") {
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns template_name="ajxp_user.shares">
                 <column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/>
                 <column messageId="share_center.132" attributeName="shared_element_parent_repository_label" sortType="String"/>
                 <column messageId="3" attributeName="share_type_readable" sortType="String"/>
                 </columns>');
             } else {
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.repositories">
                 <column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/>
                 <column messageId="share_center.159" attributeName="owner" sortType="String"/>
                 <column messageId="3" attributeName="share_type_readable" sortType="String"/>
                 <column messageId="share_center.52" attributeName="share_data" sortType="String"/>
                 </columns>');
             }
             foreach ($nodes as $node) {
                 AJXP_XMLWriter::renderAjxpNode($node);
             }
             AJXP_XMLWriter::close();
             break;
         case "sharelist-clearExpired":
             $accessType = ConfService::getRepository()->getAccessType();
             $currentUser = $accessType != "ajxp_conf" && $accessType != "ajxp_admin";
             $count = $this->getShareStore()->clearExpiredFiles($currentUser);
             AJXP_XMLWriter::header();
             if ($count) {
                 AJXP_XMLWriter::sendMessage("Removed " . count($count) . " expired links", null);
             } else {
                 AJXP_XMLWriter::sendMessage("Nothing to do", null);
             }
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     return null;
 }
예제 #12
0
 /**
  * Utilitary to pass some parameters directly at startup :
  * + repository_id / folder
  * + compile & skipDebug
  * + update_i18n, extract, create
  * + external_selector_type
  * + skipIOS
  * + gui
  * @static
  * @param $parameters
  * @param $output
  * @param $session
  * @return void
  */
 public static function parseApplicationGetParameters($parameters, &$output, &$session)
 {
     $output["EXT_REP"] = "/";
     if (isset($parameters["repository_id"]) && isset($parameters["folder"]) || isset($parameters["goto"])) {
         if (isset($parameters["goto"])) {
             $explode = explode("/", ltrim($parameters["goto"], "/"));
             $repoId = array_shift($explode);
             $parameters["folder"] = str_replace($repoId, "", ltrim($parameters["goto"], "/"));
         } else {
             $repoId = $parameters["repository_id"];
         }
         $repository = ConfService::getRepositoryById($repoId);
         if ($repository == null) {
             $repository = ConfService::getRepositoryByAlias($repoId);
             if ($repository != null) {
                 $parameters["repository_id"] = $repository->getId();
             }
         } else {
             $parameters["repository_id"] = $repository->getId();
         }
         require_once AJXP_BIN_FOLDER . "/class.SystemTextEncoding.php";
         if (AuthService::usersEnabled()) {
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser != null && $loggedUser->canSwitchTo($parameters["repository_id"])) {
                 $output["FORCE_REGISTRY_RELOAD"] = true;
                 $output["EXT_REP"] = SystemTextEncoding::toUTF8(urldecode($parameters["folder"]));
                 $loggedUser->setArrayPref("history", "last_repository", $parameters["repository_id"]);
                 $loggedUser->setPref("pending_folder", SystemTextEncoding::toUTF8(AJXP_Utils::decodeSecureMagic($parameters["folder"])));
                 $loggedUser->save("user");
                 AuthService::updateUser($loggedUser);
             } else {
                 $session["PENDING_REPOSITORY_ID"] = $parameters["repository_id"];
                 $session["PENDING_FOLDER"] = SystemTextEncoding::toUTF8(AJXP_Utils::decodeSecureMagic($parameters["folder"]));
             }
         } else {
             ConfService::switchRootDir($parameters["repository_id"]);
             $output["EXT_REP"] = SystemTextEncoding::toUTF8(urldecode($parameters["folder"]));
         }
     }
     if (isset($parameters["skipDebug"])) {
         ConfService::setConf("JS_DEBUG", false);
     }
     if (ConfService::getConf("JS_DEBUG") && isset($parameters["compile"])) {
         require_once AJXP_BIN_FOLDER . "/class.AJXP_JSPacker.php";
         AJXP_JSPacker::pack();
     }
     if (ConfService::getConf("JS_DEBUG") && isset($parameters["update_i18n"])) {
         if (isset($parameters["extract"])) {
             self::extractConfStringsFromManifests();
         }
         self::updateAllI18nLibraries(isset($parameters["create"]) ? $parameters["create"] : "");
     }
     if (ConfService::getConf("JS_DEBUG") && isset($parameters["clear_plugins_cache"])) {
         @unlink(AJXP_PLUGINS_CACHE_FILE);
         @unlink(AJXP_PLUGINS_REQUIRES_FILE);
     }
     if (AJXP_SERVER_DEBUG && isset($parameters["extract_application_hooks"])) {
         self::extractHooksToDoc();
     }
     if (isset($parameters["external_selector_type"])) {
         $output["SELECTOR_DATA"] = array("type" => $parameters["external_selector_type"], "data" => $parameters);
     }
     if (isset($parameters["skipIOS"])) {
         setcookie("SKIP_IOS", "true");
     }
     if (isset($parameters["skipANDROID"])) {
         setcookie("SKIP_ANDROID", "true");
     }
     if (isset($parameters["gui"])) {
         setcookie("AJXP_GUI", $parameters["gui"]);
         if ($parameters["gui"] == "light") {
             $session["USE_EXISTING_TOKEN_IF_EXISTS"] = true;
         }
     } else {
         if (isset($session["USE_EXISTING_TOKEN_IF_EXISTS"])) {
             unset($session["USE_EXISTING_TOKEN_IF_EXISTS"]);
         }
         setcookie("AJXP_GUI", null);
     }
     if (isset($session["OVERRIDE_GUI_START_PARAMETERS"])) {
         $output = array_merge($output, $session["OVERRIDE_GUI_START_PARAMETERS"]);
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     //AJXP_Logger::logAction("DL file", $httpVars);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     if (isset($httpVars["file"])) {
         $parts = parse_url($httpVars["file"]);
         $getPath = $parts["path"];
         $basename = basename($getPath);
     }
     if (isset($httpVars["dlfile"])) {
         $dlFile = $streamData["protocol"] . "://" . $repository->getId() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]);
         $realFile = file_get_contents($dlFile);
         if (empty($realFile)) {
             throw new Exception("cannot find file {$dlFile} for download");
         }
         $parts = parse_url($realFile);
         $getPath = $parts["path"];
         $basename = basename($getPath);
     }
     switch ($action) {
         case "external_download":
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars);
                 if ($unixProcess !== null) {
                     @file_put_contents($destStreamURL . "." . $basename . ".pid", $unixProcess->getPid());
                 }
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             require_once AJXP_BIN_FOLDER . "/class.HttpClient.php";
             $mess = ConfService::getMessages();
             session_write_close();
             $client = new HttpClient($parts["host"]);
             $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => "");
             $client->setHeadersOnly(true, $collectHeaders);
             $client->setMaxRedirects(8);
             $client->setDebug(false);
             $client->get($getPath);
             $pidHiddenFileName = $destStreamURL . "." . $basename . ".pid";
             if (is_file($pidHiddenFileName)) {
                 $pid = file_get_contents($pidHiddenFileName);
                 @unlink($pidHiddenFileName);
             }
             AJXP_Logger::debug("COLLECTED HEADERS", $client->collectHeaders);
             $collectHeaders = $client->collectHeaders;
             $totalSize = -1;
             if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) {
                 $ar = explode("filename=", $collectHeaders["content-disposition"]);
                 $basename = trim(array_pop($ar));
                 $basename = str_replace("\"", "", $basename);
                 // Remove quotes
             }
             if (!empty($collectHeaders["content-length"])) {
                 $totalSize = intval($collectHeaders["content-length"]);
                 AJXP_Logger::debug("Should download {$totalSize} bytes!");
             }
             if ($totalSize != -1) {
                 $node = new AJXP_Node($destStreamURL . $basename);
                 AJXP_Controller::applyHook("node.before_create", array($node, $totalSize));
             }
             $qData = false;
             if (!empty($collectHeaders["ajxp-last-redirection"])) {
                 $newParsed = parse_url($collectHeaders["ajxp-last-redirection"]);
                 $client->host = $newParsed["host"];
                 $getPath = $newParsed["path"];
                 if (isset($newParsed["query"])) {
                     $qData = parse_url($newParsed["query"]);
                 }
             }
             $tmpFilename = $destStreamURL . $basename . ".dlpart";
             $hiddenFilename = $destStreamURL . "__" . $basename . ".ser";
             $filename = $destStreamURL . $basename;
             $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize);
             if (isset($pid)) {
                 $dlData["pid"] = $pid;
             }
             //file_put_contents($hiddenFilename, serialize($dlData));
             $fpHid = fopen($hiddenFilename, "w");
             fputs($fpHid, serialize($dlData));
             fclose($fpHid);
             $client->redirect_count = 0;
             $client->setHeadersOnly(false);
             $destStream = fopen($tmpFilename, "w");
             if ($destStream !== false) {
                 $client->writeContentToStream($destStream);
                 $client->get($getPath, $qData);
                 fclose($destStream);
             }
             rename($tmpFilename, $filename);
             unlink($hiddenFilename);
             if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) {
                 AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($dlFile)));
                 unlink($dlFile);
                 AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false));
             }
             AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]);
             AJXP_XMLWriter::close();
             exit;
             break;
         case "update_dl_data":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             header("text/plain");
             if (is_file($destStreamURL . $file)) {
                 echo filesize($destStreamURL . $file);
             } else {
                 echo "stop";
             }
             exit;
             break;
         case "stop_dl":
             $newName = "__" . str_replace(".dlpart", ".ser", $basename);
             $hiddenFilename = $destStreamURL . $newName;
             $data = @unserialize(@file_get_contents($hiddenFilename));
             header("text/plain");
             AJXP_Logger::debug("Getting {$hiddenFilename}", $data);
             if (isset($data["pid"])) {
                 $process = new UnixProcess();
                 $process->setPid($data["pid"]);
                 $process->stop();
                 unlink($hiddenFilename);
                 unlink($destStreamURL . $basename);
                 echo 'stop';
             } else {
                 echo 'failed';
             }
             exit;
             break;
         default:
             break;
     }
     return true;
 }
예제 #14
0
 /**
  * @param Array $httpVars
  * @param Repository $repository
  * @param AbstractAccessDriver $accessDriver
  * @param null $uniqueUser
  * @throws Exception
  * @return int|Repository
  */
 public function createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser = null)
 {
     // ERRORS
     // 100 : missing args
     // 101 : repository label already exists
     // 102 : user already exists
     // 103 : current user is not allowed to share
     // SUCCESS
     // 200
     if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") {
         return 100;
     }
     $foldersharing = $this->getFilteredOption("ENABLE_FOLDER_SHARING", $this->repository->getId());
     if (isset($foldersharing) && $foldersharing === false) {
         return 103;
     }
     $loggedUser = AuthService::getLoggedUser();
     $actRights = $loggedUser->mergedRole->listActionsStatesFor($repository);
     if (isset($actRights["share"]) && $actRights["share"] === false) {
         return 103;
     }
     $users = array();
     $uRights = array();
     $uPasses = array();
     $groups = array();
     $index = 0;
     $prefix = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId());
     while (isset($httpVars["user_" . $index])) {
         $eType = $httpVars["entry_type_" . $index];
         $rightString = ($httpVars["right_read_" . $index] == "true" ? "r" : "") . ($httpVars["right_write_" . $index] == "true" ? "w" : "");
         if ($this->watcher !== false) {
             $uWatch = $httpVars["right_watch_" . $index] == "true" ? true : false;
         }
         if (empty($rightString)) {
             $index++;
             continue;
         }
         if ($eType == "user") {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index], AJXP_SANITIZE_EMAILCHARS);
             if (!AuthService::userExists($u) && !isset($httpVars["user_pass_" . $index])) {
                 $index++;
                 continue;
             } else {
                 if (AuthService::userExists($u) && isset($httpVars["user_pass_" . $index])) {
                     throw new Exception("User {$u} already exists, please choose another name.");
                 }
             }
             if (!AuthService::userExists($u, "r") && !empty($prefix) && strpos($u, $prefix) !== 0) {
                 $u = $prefix . $u;
             }
             $users[] = $u;
         } else {
             $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index]);
             if (strpos($u, "/AJXP_TEAM/") === 0) {
                 $confDriver = ConfService::getConfStorageImpl();
                 if (method_exists($confDriver, "teamIdToUsers")) {
                     $teamUsers = $confDriver->teamIdToUsers(str_replace("/AJXP_TEAM/", "", $u));
                     foreach ($teamUsers as $userId) {
                         $users[] = $userId;
                         $uRights[$userId] = $rightString;
                         if ($this->watcher !== false) {
                             $uWatches[$userId] = $uWatch;
                         }
                     }
                 }
                 $index++;
                 continue;
             } else {
                 $groups[] = $u;
             }
         }
         $uRights[$u] = $rightString;
         $uPasses[$u] = isset($httpVars["user_pass_" . $index]) ? $httpVars["user_pass_" . $index] : "";
         if ($this->watcher !== false) {
             $uWatches[$u] = $uWatch;
         }
         $index++;
     }
     $label = AJXP_Utils::decodeSecureMagic($httpVars["repo_label"]);
     $description = AJXP_Utils::decodeSecureMagic($httpVars["repo_description"]);
     if (isset($httpVars["repository_id"])) {
         $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]);
     }
     // CHECK USER & REPO DOES NOT ALREADY EXISTS
     if ($this->getFilteredOption("AVOID_SHARED_FOLDER_SAME_LABEL", $this->repository->getId()) == true) {
         $repos = ConfService::getRepositoriesList();
         foreach ($repos as $obj) {
             if ($obj->getDisplay() == $label && (!isset($editingRepo) || $editingRepo != $obj)) {
                 return 101;
             }
         }
     }
     $confDriver = ConfService::getConfStorageImpl();
     foreach ($users as $userName) {
         if (AuthService::userExists($userName)) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
             if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) {
                 return 102;
             }
         } else {
             if ($httpVars["create_guest_user"] != "true" && !ConfService::getCoreConf("USER_CREATE_USERS", "conf") || AuthService::isReservedUserId($userName)) {
                 return 102;
             }
             if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") {
                 return 100;
             }
         }
     }
     // CREATE SHARED OPTIONS
     $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository);
     $customData = array();
     foreach ($httpVars as $key => $value) {
         if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") {
             $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value;
         }
     }
     if (count($customData)) {
         $options["PLUGINS_DATA"] = $customData;
     }
     if (isset($editingRepo)) {
         $newRepo = $editingRepo;
         if ($editingRepo->getDisplay() != $label) {
             $newRepo->setDisplay($label);
             ConfService::replaceRepository($httpVars["repository_id"], $newRepo);
         }
         $editingRepo->setDescription($description);
     } else {
         if ($repository->getOption("META_SOURCES")) {
             $options["META_SOURCES"] = $repository->getOption("META_SOURCES");
             foreach ($options["META_SOURCES"] as $index => $data) {
                 if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) {
                     $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString();
                 }
             }
         }
         $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null);
         $gPath = $loggedUser->getGroupPath();
         if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
             $newRepo->setGroupPath($gPath);
         }
         $newRepo->setDescription($description);
         ConfService::addRepository($newRepo);
     }
     $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
     if (isset($editingRepo)) {
         $currentRights = $this->computeSharedRepositoryAccessRights($httpVars["repository_id"], false, $this->urlBase . $file);
         $originalUsers = array_keys($currentRights["USERS"]);
         $removeUsers = array_diff($originalUsers, $users);
         if (count($removeUsers)) {
             foreach ($removeUsers as $user) {
                 if (AuthService::userExists($user)) {
                     $userObject = $confDriver->createUserObject($user);
                     $userObject->personalRole->setAcl($newRepo->getUniqueId(), "");
                     $userObject->save("superuser");
                 }
             }
         }
         $originalGroups = array_keys($currentRights["GROUPS"]);
         $removeGroups = array_diff($originalGroups, $groups);
         if (count($removeGroups)) {
             foreach ($removeGroups as $groupId) {
                 $role = AuthService::getRole("AJXP_GRP_" . AuthService::filterBaseGroup($groupId));
                 if ($role !== false) {
                     $role->setAcl($newRepo->getUniqueId(), "");
                     AuthService::updateRole($role);
                 }
             }
         }
     }
     foreach ($users as $userName) {
         if (AuthService::userExists($userName, "r")) {
             // check that it's a child user
             $userObject = $confDriver->createUserObject($userName);
         } else {
             if (ConfService::getAuthDriverImpl()->getOption("TRANSMIT_CLEAR_PASS")) {
                 $pass = $uPasses[$userName];
             } else {
                 $pass = md5($uPasses[$userName]);
             }
             $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, "");
             if (!empty($limit) && intval($limit) > 0) {
                 $count = count(ConfService::getConfStorageImpl()->getUserChildren($loggedUser->getId()));
                 if ($count >= $limit) {
                     $mess = ConfService::getMessages();
                     throw new Exception($mess['483']);
                 }
             }
             AuthService::createUser($userName, $pass);
             $userObject = $confDriver->createUserObject($userName);
             $userObject->personalRole->clearAcls();
             $userObject->setParent($loggedUser->id);
             $userObject->setGroupPath($loggedUser->getGroupPath());
             $userObject->setProfile("shared");
             if (isset($httpVars["minisite"])) {
                 $mess = ConfService::getMessages();
                 $userObject->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", "[" . $mess["share_center.109"] . "] " . $newRepo->getDisplay());
             }
             AJXP_Controller::applyHook("user.after_create", array($userObject));
         }
         // CREATE USER WITH NEW REPO RIGHTS
         $userObject->personalRole->setAcl($newRepo->getUniqueId(), $uRights[$userName]);
         if (isset($httpVars["minisite"])) {
             $newRole = new AJXP_Role("AJXP_SHARED-" . $newRepo->getUniqueId());
             $r = AuthService::getRole("MINISITE");
             if (is_a($r, "AJXP_Role")) {
                 if ($httpVars["disable_download"]) {
                     $f = AuthService::getRole("MINISITE_NODOWNLOAD");
                     if (is_a($f, "AJXP_Role")) {
                         $r = $f->override($r);
                     }
                 }
                 $allData = $r->getDataArray();
                 $newData = $newRole->getDataArray();
                 if (isset($allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["ACTIONS"][$newRepo->getUniqueId()] = $allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 if (isset($allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED])) {
                     $newData["PARAMETERS"][$newRepo->getUniqueId()] = $allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED];
                 }
                 $newRole->bunchUpdate($newData);
                 AuthService::updateRole($newRole);
                 $userObject->addRole($newRole);
             }
         }
         $userObject->save("superuser");
         if ($this->watcher !== false) {
             // Register a watch on the current folder for shared user
             if ($uWatches[$userName] == "true") {
                 $this->watcher->setWatchOnFolder(new AJXP_Node($this->urlBase . $file), $userName, MetaWatchRegister::$META_WATCH_USERS_CHANGE, array(AuthService::getLoggedUser()->getId()));
             } else {
                 $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $userName, true);
             }
         }
     }
     if ($this->watcher !== false) {
         // Register a watch on the new repository root for current user
         if ($httpVars["self_watch_folder"] == "true") {
             $this->watcher->setWatchOnFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH);
         } else {
             $this->watcher->removeWatchFromFolder(new AJXP_Node($this->baseProtocol . "://" . $newRepo->getUniqueId() . "/"), AuthService::getLoggedUser()->getId());
         }
     }
     foreach ($groups as $group) {
         $grRole = AuthService::getRole("AJXP_GRP_" . AuthService::filterBaseGroup($group), true);
         $grRole->setAcl($newRepo->getUniqueId(), $uRights[$group]);
         AuthService::updateRole($grRole);
     }
     if (array_key_exists("minisite", $httpVars) && $httpVars["minisite"] != true) {
         AJXP_Controller::applyHook("node.share.create", array('type' => 'repository', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'new_repository' => &$newRepo));
     }
     return $newRepo;
 }
예제 #15
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     //$this->logInfo("DL file", $httpVars);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $dlURL = null;
     if (isset($httpVars["file"])) {
         $parts = parse_url($httpVars["file"]);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $httpVars["file"];
     }
     if (isset($httpVars["dlfile"])) {
         $dlFile = $streamData["protocol"] . "://" . $repository->getId() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]);
         $realFile = file_get_contents($dlFile);
         if (empty($realFile)) {
             throw new Exception("cannot find file {$dlFile} for download");
         }
         $parts = parse_url($realFile);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $realFile;
     }
     switch ($action) {
         case "external_download":
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars);
                 if ($unixProcess !== null) {
                     @file_put_contents($destStreamURL . "." . $basename . ".pid", $unixProcess->getPid());
                 }
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
             session_write_close();
             $httpClient = new http_class();
             $arguments = array();
             $httpClient->GetRequestArguments($httpVars["file"], $arguments);
             $err = $httpClient->Open($arguments);
             $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => "");
             if (empty($err)) {
                 $err = $httpClient->SendRequest($arguments);
                 $httpClient->follow_redirect = true;
                 $pidHiddenFileName = $destStreamURL . "." . $basename . ".pid";
                 if (is_file($pidHiddenFileName)) {
                     $pid = file_get_contents($pidHiddenFileName);
                     @unlink($pidHiddenFileName);
                 }
                 if (empty($err)) {
                     $httpClient->ReadReplyHeaders($collectHeaders);
                     $totalSize = -1;
                     if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) {
                         $ar = explode("filename=", $collectHeaders["content-disposition"]);
                         $basename = trim(array_pop($ar));
                         $basename = str_replace("\"", "", $basename);
                         // Remove quotes
                     }
                     if (!empty($collectHeaders["content-length"])) {
                         $totalSize = intval($collectHeaders["content-length"]);
                         $this->logDebug("Should download {$totalSize} bytes!");
                     }
                     if ($totalSize != -1) {
                         $node = new AJXP_Node($destStreamURL . $basename);
                         AJXP_Controller::applyHook("node.before_create", array($node, $totalSize));
                     }
                     $tmpFilename = $destStreamURL . $basename . ".dlpart";
                     $hiddenFilename = $destStreamURL . "__" . $basename . ".ser";
                     $filename = $destStreamURL . $basename;
                     $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize);
                     if (isset($pid)) {
                         $dlData["pid"] = $pid;
                     }
                     //file_put_contents($hiddenFilename, serialize($dlData));
                     $fpHid = fopen($hiddenFilename, "w");
                     fputs($fpHid, serialize($dlData));
                     fclose($fpHid);
                     // NOW READ RESPONSE
                     $destStream = fopen($tmpFilename, "w");
                     while (true) {
                         $body = "";
                         $error = $httpClient->ReadReplyBody($body, 1000);
                         if ($error != "" || strlen($body) == 0) {
                             break;
                         }
                         fwrite($destStream, $body, strlen($body));
                     }
                     fclose($destStream);
                     rename($tmpFilename, $filename);
                     unlink($hiddenFilename);
                 }
                 $httpClient->Close();
                 if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) {
                     AJXP_Controller::applyHook("node.before_path_change", array(new AJXP_Node($dlFile)));
                     unlink($dlFile);
                     AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false));
                 }
                 $mess = ConfService::getMessages();
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false));
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]);
                 AJXP_XMLWriter::close();
             }
             break;
         case "update_dl_data":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             header("text/plain");
             if (is_file($destStreamURL . $file)) {
                 $node = new AJXP_Node($destStreamURL . $file);
                 if (method_exists($node->getDriver(), "filesystemFileSize")) {
                     $filesize = $node->getDriver()->filesystemFileSize($node->getUrl());
                 } else {
                     $filesize = filesize($node->getUrl());
                 }
                 echo $filesize;
             } else {
                 echo "stop";
             }
             break;
         case "stop_dl":
             $newName = "__" . str_replace(".dlpart", ".ser", $basename);
             $hiddenFilename = $destStreamURL . $newName;
             $data = @unserialize(@file_get_contents($hiddenFilename));
             header("text/plain");
             $this->logDebug("Getting {$hiddenFilename}", $data);
             if (isset($data["pid"])) {
                 $process = new UnixProcess();
                 $process->setPid($data["pid"]);
                 $process->stop();
                 unlink($hiddenFilename);
                 unlink($destStreamURL . $basename);
                 echo 'stop';
             } else {
                 echo 'failed';
             }
             break;
         default:
             break;
     }
     return false;
 }
예제 #16
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $selection = new UserSelection($repository, $httpVars);
     $selectedNode = $selection->getUniqueNode();
     $selectedNodeUrl = $selectedNode->getUrl();
     if ($action == "post_to_server") {
         // Backward compat
         if (strpos($httpVars["file"], "base64encoded:") !== 0) {
             $legacyFilePath = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
             $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $legacyFilePath);
             $selectedNodeUrl = $selectedNode->getUrl();
         }
         $target = rtrim(base64_decode($httpVars["parent_url"]), '/') . "/plugins/editor.pixlr";
         $tmp = AJXP_MetaStreamWrapper::getRealFSReference($selectedNodeUrl);
         $tmp = SystemTextEncoding::fromUTF8($tmp);
         $this->logInfo('Preview', 'Sending content of ' . $selectedNodeUrl . ' to Pixlr server.', array("files" => $selectedNodeUrl));
         AJXP_Controller::applyHook("node.read", array($selectedNode));
         $saveTarget = $target . "/fake_save_pixlr.php";
         if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) {
             $saveTarget = $target . "/fake_save_pixlr_" . md5($httpVars["secure_token"]) . ".php";
         }
         $params = array("referrer" => "Pydio", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $saveTarget, "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($selectedNodeUrl)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source");
         require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
         $arguments = array();
         $httpClient = new http_class();
         $httpClient->request_method = "POST";
         $httpClient->GetRequestArguments("https://pixlr.com/editor/", $arguments);
         $arguments["PostValues"] = $params;
         $arguments["PostFiles"] = array("image" => array("FileName" => $tmp, "Content-Type" => "automatic/name"));
         $err = $httpClient->Open($arguments);
         if (empty($err)) {
             $err = $httpClient->SendRequest($arguments);
             if (empty($err)) {
                 $response = "";
                 while (true) {
                     $header = array();
                     $error = $httpClient->ReadReplyHeaders($header, 1000);
                     if ($error != "" || $header != null) {
                         break;
                     }
                     $response .= $header;
                 }
             }
         }
         header("Location: {$header['location']}");
         //$response");
     } else {
         if ($action == "retrieve_pixlr_image") {
             $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]);
             $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $file);
             $selectedNode->loadNodeInfo();
             $this->logInfo('Edit', 'Retrieving content of ' . $file . ' from Pixlr server.', array("files" => $file));
             AJXP_Controller::applyHook("node.before_change", array(&$selectedNode));
             $url = $httpVars["new_url"];
             $urlParts = parse_url($url);
             $query = $urlParts["query"];
             if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) {
                 $scriptName = basename($urlParts["path"]);
                 $token = str_replace(array("fake_save_pixlr_", ".php"), "", $scriptName);
                 if ($token != md5($httpVars["secure_token"])) {
                     throw new AJXP_Exception("Invalid Token, this could mean some security problem!");
                 }
             }
             $params = array();
             parse_str($query, $params);
             $image = $params['image'];
             $headers = get_headers($image, 1);
             $content_type = explode("/", $headers['Content-Type']);
             if ($content_type[0] != "image") {
                 throw new AJXP_Exception("Invalid File Type");
             }
             $content_length = intval($headers["Content-Length"]);
             if ($content_length != 0) {
                 AJXP_Controller::applyHook("node.before_change", array(&$selectedNode, $content_length));
             }
             $orig = fopen($image, "r");
             $target = fopen($selectedNode->getUrl(), "w");
             if (is_resource($orig) && is_resource($target)) {
                 while (!feof($orig)) {
                     fwrite($target, fread($orig, 4096));
                 }
                 fclose($orig);
                 fclose($target);
             }
             clearstatcache(true, $selectedNode->getUrl());
             $selectedNode->loadNodeInfo(true);
             AJXP_Controller::applyHook("node.change", array(&$selectedNode, &$selectedNode));
         }
     }
 }
 /**
  * Returns UTF8 encoded path
  * @param bool $decode
  * @return String
  */
 function getZipLocalPath($decode = false)
 {
     if ($decode) {
         return AJXP_Utils::decodeSecureMagic($this->localZipPath);
     } else {
         return $this->localZipPath;
     }
 }
예제 #18
0
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection($repo, $httpVars);
     $nodes = $selection->buildNodes();
     $nodesDiffs = array();
     $def = $this->getMetaDefinition();
     foreach ($nodes as $ajxpNode) {
         $newValues = array();
         //$ajxpNode->setDriver($this->accessDriver);
         AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode));
         foreach ($def as $key => $data) {
             if (isset($httpVars[$key])) {
                 $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]);
                 if ($data["type"] == "tags") {
                     $this->updateTags(AJXP_Utils::decodeSecureMagic($httpVars[$key]));
                 }
             } else {
                 if (!isset($original)) {
                     $original = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL);
                 }
                 if (isset($original) && isset($original[$key])) {
                     $newValues[$key] = $original[$key];
                 }
             }
         }
         $ajxpNode->setMetadata("users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL);
         AJXP_Controller::applyHook("node.meta_change", array($ajxpNode));
         $nodesDiffs[$ajxpNode->getPath()] = $ajxpNode;
     }
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => $nodesDiffs), true);
     AJXP_XMLWriter::close();
 }
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars();
     $currentFile = $selection->getUniqueFile();
     $wrapperData = $this->accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId();
     $newValues = array();
     $def = $this->getMetaDefinition();
     $ajxpNode = new AJXP_Node($urlBase . $currentFile);
     AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode));
     foreach ($def as $key => $label) {
         if (isset($httpVars[$key])) {
             $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]);
         } else {
             if (!isset($original)) {
                 $original = $this->metaStore->retrieveMetadata($ajxpNode, "users_meta", false, AJXP_METADATA_SCOPE_GLOBAL);
             }
             if (isset($original) && isset($original[$key])) {
                 $newValues[$key] = $original[$key];
             }
         }
     }
     $this->metaStore->setMetadata($ajxpNode, "users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL);
     AJXP_Controller::applyHook("node.change", array(null, &$ajxpNode));
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true);
     AJXP_XMLWriter::close();
 }
예제 #20
0
 public function copyOrMoveSelection($actionName, &$httpVars, $filesVars)
 {
     if ($actionName != "rename") {
         $init = $this->initDirAndSelection($httpVars, array("DEST_DIR" => AJXP_Utils::decodeSecureMagic($httpVars["dest"])));
         $this->commitMessageParams = "To:" . $httpVars["dest"] . ";items:";
     } else {
         $init = $this->initDirAndSelection($httpVars, array(), true);
     }
     $this->logDebug("Entering SVN MAnager for action {$actionName}", $init);
     $action = 'copy';
     if ($actionName == "move" || $actionName == "rename") {
         $action = 'move';
     }
     foreach ($init["SELECTION"] as $selectedFile) {
         if ($actionName == "rename") {
             $destFile = dirname($selectedFile) . "/" . AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]);
             $this->commitMessageParams = "To:" . $httpVars["filename_new"] . ";item:" . $httpVars["file"];
         } else {
             $destFile = $init["DEST_DIR"] . "/" . basename($selectedFile);
         }
         $this->addIfNotVersionned(str_replace($init["DIR"], "", $selectedFile), $selectedFile);
         $res = ExecSvnCmd("svn {$action}", array($selectedFile, $destFile), '');
     }
     if ($actionName != "rename") {
         $this->commitMessageParams .= "[" . implode(",", $init["SELECTION"]) . "]";
     }
     $this->commitChanges($actionName, $httpVars, $filesVars);
     if ($actionName != "rename") {
         $this->commitChanges($actionName, array("dir" => $httpVars["dest"]), $filesVars);
     }
     $this->logInfo("CopyMove/Rename (svn delegate)", array("files" => $init["SELECTION"]));
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::sendMessage("The selected files/folders have been copied/moved (by SVN)", null);
     AJXP_XMLWriter::reloadDataNode();
     AJXP_XMLWriter::close();
 }
 /**
  * @param String $actionName
  * @param Array $httpVars
  * @param Array $fileVars
  */
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     $userSelection = new UserSelection($this->accessDriver->repository, $httpVars);
     $uniqNode = $userSelection->getUniqueNode();
     $feedStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("feed");
     $existingFeed = $uniqNode->retrieveMetadata(AJXP_META_SPACE_COMMENTS, false);
     if ($existingFeed == null) {
         $existingFeed = array();
     }
     $mess = ConfService::getMessages();
     switch ($actionName) {
         case "post_comment":
             $uId = AuthService::getLoggedUser()->getId();
             $limit = $this->getFilteredOption("COMMENT_SIZE_LIMIT");
             if (!empty($limit)) {
                 $content = substr(AJXP_Utils::decodeSecureMagic($httpVars["content"]), 0, $limit);
             } else {
                 $content = AJXP_Utils::decodeSecureMagic($httpVars["content"]);
             }
             $com = array("date" => time(), "author" => $uId, "content" => $content);
             $existingFeed[] = $com;
             if ($feedStore !== false) {
                 $feedStore->persistMetaObject($uniqNode->getPath(), base64_encode($content), $uniqNode->getRepositoryId(), $uniqNode->getRepository()->securityScope(), $uniqNode->getRepository()->getOwner(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath());
             } else {
                 $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false);
                 $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $existingFeed, false);
             }
             HTMLWriter::charsetHeader("application/json");
             $com["hdate"] = AJXP_Utils::relativeDate($com["date"], $mess);
             $com["path"] = $uniqNode->getPath();
             echo json_encode($com);
             break;
         case "load_comments_feed":
             HTMLWriter::charsetHeader("application/json");
             if ($feedStore !== false) {
                 $sortBy = isset($httpVars["sort_by"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_by"]) : "date";
                 $sortDir = isset($httpVars["sort_dir"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_dir"]) : "asc";
                 $offset = isset($httpVars["offset"]) ? intval($httpVars["offset"]) : 0;
                 $limit = isset($httpVars["limit"]) ? intval($httpVars["limit"]) : 100;
                 $uniqNode->loadNodeInfo();
                 $data = $feedStore->findMetaObjectsByIndexPath($this->accessDriver->repository->getId(), $uniqNode->getPath(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath(), $offset, $limit, $sortBy, $sortDir, !$uniqNode->isLeaf());
                 $theFeed = array();
                 foreach ($data as $stdObject) {
                     $rPath = substr($stdObject->path, strlen($uniqNode->getPath()));
                     if ($rPath == false && $stdObject->path == $uniqNode->getPath()) {
                         $rPath = "";
                     }
                     $rPath = ltrim($rPath, "/");
                     $newItem = array("date" => $stdObject->date, "hdate" => AJXP_Utils::relativeDate($stdObject->date, $mess), "author" => $stdObject->author, "content" => base64_decode($stdObject->content), "path" => $stdObject->path, "rpath" => $rPath, "uuid" => $stdObject->uuid);
                     if (isset($previous) && $previous["author"] == $newItem["author"] && $previous["path"] == $newItem["path"] && $previous["hdate"] == $newItem["hdate"]) {
                         $theFeed[count($theFeed) - 1]["content"] .= '<br>' . $newItem["content"];
                     } else {
                         $theFeed[] = $newItem;
                     }
                     $previous = $newItem;
                 }
                 echo json_encode($theFeed);
             } else {
                 foreach ($existingFeed as &$item) {
                     $item["hdate"] = AJXP_Utils::relativeDate($item["date"], $mess);
                 }
                 echo json_encode($existingFeed);
             }
             break;
         case "delete_comment":
             $data = json_decode($httpVars["comment_data"], true);
             if ($feedStore === false) {
                 $reFeed = array();
                 if ($data["author"] != AuthService::getLoggedUser()->getId()) {
                     break;
                 }
                 foreach ($existingFeed as $fElement) {
                     if ($fElement["date"] == $data["date"] && $fElement["author"] == $data["author"] && $fElement["content"] == $data["content"]) {
                         continue;
                     }
                     $fElement["hdate"] = AJXP_Utils::relativeDate($fElement["date"], $mess);
                     $reFeed[] = $fElement;
                 }
                 $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false);
                 $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $reFeed, false);
                 HTMLWriter::charsetHeader("application/json");
                 echo json_encode($reFeed);
             } else {
                 $feedStore->dismissAlertById($data["uuid"], 1);
             }
             break;
         default:
             break;
     }
 }
 /**
  * @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);
             }
         }
     }
 }
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     if (!dibi::isConnected()) {
         dibi::connect($this->sqlDriver);
     }
     $filter = null;
     $masks = array();
     $currentRepo = $this->accessDriver->repository;
     AJXP_Controller::applyHook("role.masks", array($currentRepo->getId(), &$masks, AJXP_Permission::READ));
     $recycle = $currentRepo->getOption("RECYCLE_BIN");
     $recycle = !empty($recycle) ? $recycle : false;
     if ($this->options["OBSERVE_STORAGE_CHANGES"] === true) {
         // Do it every XX minutes
         $minutes = 5;
         if (isset($this->options["OBSERVE_STORAGE_EVERY"])) {
             $minutes = intval($this->options["OBSERVE_STORAGE_EVERY"]);
         }
         $file = $this->getResyncTimestampFile();
         $last = 0;
         if (is_file($file)) {
             $last = intval(file_get_contents($file));
         }
         if (time() - $last > $minutes * 60) {
             $this->resyncAction("resync_storage", array(), array());
         }
     }
     if ($this->options["REQUIRES_INDEXATION"]) {
         if (ConfService::backgroundActionsSupported()) {
             AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), "index", array());
         } else {
             AJXP_Controller::findActionAndApply("index", array(), array());
         }
         // Unset the REQUIRES_INDEXATION FLAG
         $meta = $currentRepo->getOption("META_SOURCES");
         unset($meta["meta.syncable"]["REQUIRES_INDEXATION"]);
         $currentRepo->addOption("META_SOURCES", $meta);
         ConfService::replaceRepository($currentRepo->getId(), $currentRepo);
     }
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $stream = isset($httpVars["stream"]);
     $separator = $stream ? "\n" : ",";
     $veryLastSeq = intval(dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle());
     $seqId = intval(AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     if ($veryLastSeq > 0 && $seqId > $veryLastSeq) {
         // This is not normal! Send a signal reload all changes from start.
         if (!$stream) {
             echo json_encode(array('changes' => array(), 'last_seq' => 1));
         } else {
             echo 'LAST_SEQ:1';
         }
         return null;
     }
     $ands = array();
     $ands[] = array("[ajxp_changes].[repository_identifier] = %s", $this->computeIdentifier($currentRepo));
     $ands[] = array("[seq] > %i", $seqId);
     if (isset($httpVars["filter"])) {
         $filter = AJXP_Utils::decodeSecureMagic($httpVars["filter"]);
         $filterLike = rtrim($filter, "/") . "/";
         $ands[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
     }
     if (count($masks)) {
         $ors = array();
         foreach ($masks as $mask) {
             $filterLike = rtrim($mask, "/") . "/";
             $ors[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
         }
         if (count($ors)) {
             $ands[] = array("%or", $ors);
         }
     }
     $res = dibi::query("SELECT\n            [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n            FROM [ajxp_changes]\n            LEFT JOIN [ajxp_index]\n                ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n            WHERE %and\n            ORDER BY [ajxp_changes].[node_id], [seq] ASC", $ands);
     if (!$stream) {
         echo '{"changes":[';
     }
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     $valuesSent = false;
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if (!empty($recycle)) {
             $this->cancelRecycleNodes($row, $recycle);
         }
         if (!isset($httpVars["flatten"]) || $httpVars["flatten"] == "false") {
             if (!$this->filterMasks($row, $masks) && !$this->filterRow($row, $filter)) {
                 if ($valuesSent) {
                     echo $separator;
                 }
                 echo json_encode($row);
                 $valuesSent = true;
             }
         } else {
             if ($row->node_id == $previousNodeId) {
                 $previousRow->target = $row->target;
                 $previousRow->seq = $row->seq;
                 if ($order[$row->type] > $order[$previousRow->type]) {
                     $previousRow->type = $row->type;
                 }
             } else {
                 if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                     if ($this->filterMasks($previousRow, $masks) || $this->filterRow($previousRow, $filter)) {
                         $previousRow = $row;
                         $previousNodeId = $row->node_id;
                         $lastSeq = $row->seq;
                         continue;
                     }
                     if ($valuesSent) {
                         echo $separator;
                     }
                     echo json_encode($previousRow);
                     $valuesSent = true;
                 }
                 $previousRow = $row;
                 $previousNodeId = $row->node_id;
             }
             $lastSeq = $row->seq;
             flush();
         }
         //CODES HERE HAVE BEEN MOVE OUT OF THE LOOP
     }
     /**********RETURN TO SENDER************/
     // is 'not NULL' included in isSet()?
     if ($previousRow && isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content") && !$this->filterRow($previousRow, $filter)) {
         if ($valuesSent) {
             echo $separator;
         }
         echo json_encode($previousRow);
         if ($previousRow->seq > $lastSeq) {
             $lastSeq = $previousRow->seq;
         }
         $valuesSent = true;
     }
     /*************************************/
     if (isset($lastSeq)) {
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     }
     return null;
 }
 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;
     }
 }
예제 #25
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $convert = $this->getFilteredOption("IMAGE_MAGICK_CONVERT");
     if (empty($convert)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     $flyThreshold = 1024 * 1024 * intval($this->getFilteredOption("ONTHEFLY_THRESHOLD", $repository->getId()));
     $selection = new UserSelection($repository);
     $selection->initFromHttpVars($httpVars);
     if ($action == "imagick_data_proxy") {
         $this->extractAll = false;
         if (isset($httpVars["all"])) {
             $this->extractAll = true;
         }
         $file = $selection->getUniqueFile();
         if (($size = filesize($destStreamURL . $file)) === false) {
             return false;
         } else {
             if ($size > $flyThreshold) {
                 $this->useOnTheFly = true;
             } else {
                 $this->useOnTheFly = false;
             }
         }
         if ($this->extractAll) {
             $node = new AJXP_Node($destStreamURL . $file);
             AJXP_Controller::applyHook("node.read", array($node));
         }
         $cache = AJXP_Cache::getItem("imagick_" . ($this->extractAll ? "full" : "thumb"), $destStreamURL . $file, array($this, "generateJpegsCallback"));
         $cacheData = $cache->getData();
         if (!$this->useOnTheFly && $this->extractAll) {
             // extract all on first view
             $ext = pathinfo($file, PATHINFO_EXTENSION);
             $prefix = str_replace(".{$ext}", "", $cache->getId());
             $files = $this->listExtractedJpg($destStreamURL . $file, $prefix);
             header("Content-Type: application/json");
             print json_encode($files);
             return false;
         } else {
             if ($this->extractAll) {
                 // on the fly extract mode
                 $ext = pathinfo($file, PATHINFO_EXTENSION);
                 $prefix = str_replace(".{$ext}", "", $cache->getId());
                 $files = $this->listPreviewFiles($destStreamURL . $file, $prefix);
                 header("Content-Type: application/json");
                 print json_encode($files);
                 return false;
             } else {
                 header("Content-Type: image/jpeg; name=\"" . basename($file) . "\"");
                 header("Content-Length: " . strlen($cacheData));
                 header('Cache-Control: public');
                 header("Pragma:");
                 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");
                 print $cacheData;
                 return false;
             }
         }
     } else {
         if ($action == "get_extracted_page" && isset($httpVars["file"])) {
             $file = (defined('AJXP_SHARED_CACHE_DIR') ? AJXP_SHARED_CACHE_DIR : AJXP_CACHE_DIR) . "/imagick_full/" . AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             if (!is_file($file)) {
                 $srcfile = AJXP_Utils::decodeSecureMagic($httpVars["src_file"]);
                 if ($repository->hasContentFilter()) {
                     $contentFilter = $repository->getContentFilter();
                     $srcfile = $contentFilter->filterExternalPath($srcfile);
                 }
                 $size = filesize($destStreamURL . "/" . $srcfile);
                 if ($size > $flyThreshold) {
                     $this->useOnTheFly = true;
                 } else {
                     $this->useOnTheFly = false;
                 }
                 if ($this->useOnTheFly) {
                     $this->onTheFly = true;
                 }
                 $this->generateJpegsCallback($destStreamURL . $srcfile, $file);
             }
             if (!is_file($file)) {
                 return false;
             }
             header("Content-Type: image/jpeg; name=\"" . basename($file) . "\"");
             header("Content-Length: " . filesize($file));
             header('Cache-Control: public');
             readfile($file);
             exit(1);
         } else {
             if ($action == "delete_imagick_data" && !$selection->isEmpty()) {
                 /*
                 $files = $this->listExtractedJpg(AJXP_CACHE_DIR."/".$httpVars["file"]);
                 foreach ($files as $file) {
                     if(is_file(AJXP_CACHE_DIR."/".$file["file"])) unlink(AJXP_CACHE_DIR."/".$file["file"]);
                 }
                 */
             }
         }
     }
 }
 public function postProcess($action, $httpVars, $postProcessData)
 {
     if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) {
         return;
     }
     /* If set resumeFileId and resumePartitionIndex, cross-session resume is requested. */
     if (isset($httpVars["resumeFileId"]) && isset($httpVars["resumePartitionIndex"])) {
         header("HTTP/1.1 200 OK");
         print "fileId: " . $httpVars["resumeFileId"] . "\n";
         print "partitionIndex: " . $httpVars["resumePartitionIndex"];
         return;
     }
     /*if (self::$skipDecoding) {
     
             }*/
     if (isset($postProcessData["processor_result"]["ERROR"])) {
         if (isset($httpVars["lastPartition"]) && isset($httpVars["partitionCount"])) {
             /* we get the stream url (where all the partitions have been uploaded so far) */
             $repository = ConfService::getRepository();
             $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
             $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
             $streamData = $plugin->detectStreamWrapper(true);
             $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
             if ($httpVars["partitionCount"] > 1) {
                 /* we fetch the information that help us to construct the temp files name */
                 $fileId = $httpVars["fileId"];
                 $fileHash = md5($httpVars["fileName"]);
                 /* deletion of all the partitions that have been uploaded */
                 for ($i = 0; $i < $httpVars["partitionCount"]; $i++) {
                     if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) {
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
             } else {
                 $fileName = $httpVars["fileName"];
                 unlink($destStreamURL . $fileName);
             }
         }
         echo "Error: " . $postProcessData["processor_result"]["ERROR"]["MESSAGE"];
         return;
     }
     if (!isset($httpVars["partitionRealName"]) && !isset($httpVars["lastPartition"])) {
         return;
     }
     $repository = ConfService::getRepository();
     $driver = ConfService::loadDriverForRepository($repository);
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     if ($httpVars["lastPartition"]) {
         $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
         $streamData = $plugin->detectStreamWrapper(true);
         $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
         $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
         /* we check if the current file has a relative path (aka we want to upload an entire directory) */
         $this->logDebug("Now dispatching relativePath dest:", $httpVars["relativePath"]);
         $subs = explode("/", $httpVars["relativePath"]);
         $userfile_name = array_pop($subs);
         $folderForbidden = false;
         $all_in_place = true;
         $partitions_length = 0;
         $fileId = $httpVars["fileId"];
         $fileHash = md5($userfile_name);
         $partitionCount = $httpVars["partitionCount"];
         $fileLength = $_POST["fileLength"];
         /*
          *
          * Now, we supposed that access driver has already saved uploaded file in to
          * folderServer with file name is md5 relativePath value.
          * We try to copy this file to right location in recovery his name.
          *
          */
         $userfile_name = md5($httpVars["relativePath"]);
         if (self::$remote) {
             $partitions = array();
             $newPartitions = array();
             $index_first_partition = -1;
             $i = 0;
             do {
                 $currentFileName = $driver->getFileNameToCopy();
                 $partitions[] = $driver->getNextFileToCopy();
                 if ($index_first_partition < 0 && strstr($currentFileName, $fileHash) != false) {
                     $index_first_partition = $i;
                 } else {
                     if ($index_first_partition < 0) {
                         $newPartitions[] = array_pop($partitions);
                     }
                 }
             } while ($driver->hasFilesToCopy());
         }
         /* if partitionned */
         if ($partitionCount > 1) {
             if (self::$remote) {
                 for ($i = 0; $all_in_place && $i < $partitionCount; $i++) {
                     $partition_file = "{$fileHash}.{$fileId}.{$i}";
                     if (strstr($partitions[$i]["name"], $partition_file) != false) {
                         $partitions_length += filesize($partitions[$i]["tmp_name"]);
                     } else {
                         $all_in_place = false;
                     }
                 }
             } else {
                 for ($i = 0; $all_in_place && $i < $partitionCount; $i++) {
                     $partition_file = $destStreamURL . "{$fileHash}.{$fileId}.{$i}";
                     if (file_exists($partition_file)) {
                         $partitions_length += filesize($partition_file);
                     } else {
                         $all_in_place = false;
                     }
                 }
             }
         } else {
             if (self::$remote) {
                 if (strstr($newPartitions[count($newPartitions) - 1]["name"], $userfile_name) != false) {
                     $partitions_length += filesize($newPartitions[count($newPartitions) - 1]["tmp_name"]);
                 }
             } else {
                 if (file_exists($destStreamURL . $userfile_name)) {
                     $partitions_length += filesize($destStreamURL . $userfile_name);
                 }
             }
         }
         if (!$all_in_place || $partitions_length != floatval($fileLength)) {
             echo "Error: Upload validation error!";
             /* we delete all the uploaded partitions */
             if ($httpVars["partitionCount"] > 1) {
                 for ($i = 0; $i < $partitionCount; $i++) {
                     if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) {
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
             } else {
                 $fileName = $httpVars["partitionRealName"];
                 unlink($destStreamURL . $fileName);
             }
             return;
         }
         if (count($subs) > 0 && !self::$remote) {
             $curDir = "";
             if (substr($curDir, -1) == "/") {
                 $curDir = substr($curDir, 0, -1);
             }
             // Create the folder tree as necessary
             foreach ($subs as $key => $spath) {
                 $messtmp = "";
                 $dirname = AJXP_Utils::decodeSecureMagic($spath, AJXP_SANITIZE_FILENAME);
                 $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
                 //$this->filterUserSelectionToHidden(array($dirname));
                 if (AJXP_Utils::isHidden($dirname)) {
                     $folderForbidden = true;
                     break;
                 }
                 if (file_exists($destStreamURL . "{$curDir}/{$dirname}")) {
                     // if the folder exists, traverse
                     $this->logDebug("{$curDir}/{$dirname} existing, traversing for {$userfile_name} out of", $httpVars["relativePath"]);
                     $curDir .= "/" . $dirname;
                     continue;
                 }
                 $this->logDebug($destStreamURL . $curDir);
                 $dirMode = 0775;
                 $chmodValue = $repository->getOption("CHMOD_VALUE");
                 if (isset($chmodValue) && $chmodValue != "") {
                     $dirMode = octdec(ltrim($chmodValue, "0"));
                     if ($dirMode & 0400) {
                         $dirMode |= 0100;
                     }
                     // Owner is allowed to read, allow to list the directory
                     if ($dirMode & 040) {
                         $dirMode |= 010;
                     }
                     // Group is allowed to read, allow to list the directory
                     if ($dirMode & 04) {
                         $dirMode |= 01;
                     }
                     // Other are allowed to read, allow to list the directory
                 }
                 $url = $destStreamURL . $curDir . "/" . $dirname;
                 $old = umask(0);
                 mkdir($url, $dirMode);
                 umask($old);
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($url), false));
                 $curDir .= "/" . $dirname;
             }
         }
         if (!$folderForbidden) {
             $fileId = $httpVars["fileId"];
             $this->logDebug("Should now rebuild file!", $httpVars);
             // Now move the final file to the right folder
             // Currently the file is at the base of the current
             $this->logDebug("PartitionRealName", $destStreamURL . $httpVars["partitionRealName"]);
             // Get file by name (md5 value)
             $relPath_md5 = AJXP_Utils::decodeSecureMagic(md5($httpVars["relativePath"]));
             // original file name
             $relPath = AJXP_Utils::decodeSecureMagic($httpVars["relativePath"]);
             $target = $destStreamURL;
             $target .= self::$remote ? basename($relPath) : $relPath;
             /*
              *   $current is uploaded file with md5 value as his name
              *   we copy to $relPath and delete md5 file
              */
             $current = $destStreamURL . basename($relPath_md5);
             if ($httpVars["partitionCount"] > 1) {
                 if (self::$remote) {
                     $test = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"];
                     $newDest = fopen(AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"], "w");
                     $newFile = array();
                     $length = 0;
                     for ($i = 0, $count = count($partitions); $i < $count; $i++) {
                         $currentFile = $partitions[$i];
                         $currentFileName = $currentFile["tmp_name"];
                         $part = fopen($currentFileName, "r");
                         while (!feof($part)) {
                             $length += fwrite($newDest, fread($part, 4096));
                         }
                         fclose($part);
                         unlink($currentFileName);
                     }
                     $newFile["type"] = $partitions[0]["type"];
                     $newFile["name"] = $httpVars["partitionRealName"];
                     $newFile["error"] = 0;
                     $newFile["size"] = $length;
                     $newFile["tmp_name"] = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"];
                     $newFile["destination"] = $partitions[0]["destination"];
                     $newPartitions[] = $newFile;
                 } else {
                     $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w");
                     $fileHash = md5($httpVars["partitionRealName"]);
                     for ($i = 0; $i < $httpVars["partitionCount"]; $i++) {
                         $part = fopen($destStreamURL . "{$fileHash}.{$fileId}.{$i}", "r");
                         while (!feof($part)) {
                             fwrite($newDest, fread($part, 4096));
                         }
                         fclose($part);
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
                 fclose($newDest);
             }
             if (!self::$remote && (!self::$wrapperIsRemote || $relPath != $httpVars["partitionRealName"])) {
                 $err = copy($current, $target);
             } else {
                 for ($i = 0, $count = count($newPartitions); $i < $count; $i++) {
                     $driver->storeFileToCopy($newPartitions[$i]);
                 }
             }
             if ($err !== false) {
                 if (!self::$remote) {
                     unlink($current);
                 }
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false));
             } else {
                 if ($current == $target) {
                     AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false));
                 }
             }
         } else {
             // Remove the file, as it should not have been uploaded!
             //if(!self::$remote) unlink($current);
         }
     }
 }
예제 #27
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;
     }
 }
 public function unifyChunks($action, $httpVars, $fileVars)
 {
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $filename = AJXP_Utils::decodeSecureMagic($httpVars["file_name"]);
     $chunks = array();
     $index = 0;
     while (isset($httpVars["chunk_" . $index])) {
         $chunks[] = AJXP_Utils::decodeSecureMagic($httpVars["chunk_" . $index]);
         $index++;
     }
     $newDest = fopen($destStreamURL . $filename, "w");
     for ($i = 0; $i < count($chunks); $i++) {
         $part = fopen($destStreamURL . $chunks[$i], "r");
         while (!feof($part)) {
             fwrite($newDest, fread($part, 4096));
         }
         fclose($part);
         unlink($destStreamURL . $chunks[$i]);
     }
     fclose($newDest);
     AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($newDest), false));
 }
 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;
 }
예제 #30
-1
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "post_to_zohoserver") {
         $sheetExt = explode(",", "xls,xlsx,ods,sxc,csv,tsv");
         $presExt = explode(",", "ppt,pps,odp,sxi");
         $docExt = explode(",", "doc,docx,rtf,odt,sxw");
         require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
         $selection = new UserSelection($repository, $httpVars);
         // Backward compat
         if (strpos($httpVars["file"], "base64encoded:") !== 0) {
             $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
         } else {
             $file = $selection->getUniqueFile();
         }
         $target = base64_decode($httpVars["parent_url"]);
         $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file);
         $tmp = SystemTextEncoding::fromUTF8($tmp);
         $node = new AJXP_Node($destStreamURL . $file);
         AJXP_Controller::applyHook("node.read", array($node));
         $this->logInfo('Preview', 'Posting content of ' . $file . ' to Zoho server');
         $extension = strtolower(pathinfo(urlencode(basename($file)), PATHINFO_EXTENSION));
         $httpClient = new http_class();
         $httpClient->request_method = "POST";
         $secureToken = $httpVars["secure_token"];
         $_SESSION["ZOHO_CURRENT_EDITED"] = $destStreamURL . $file;
         $_SESSION["ZOHO_CURRENT_UUID"] = md5(rand() . "-" . microtime());
         if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) {
             $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId());
         } else {
             $saveUrl = $target . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/save_zoho.php";
         }
         $b64Sig = $this->signID($_SESSION["ZOHO_CURRENT_UUID"]);
         $params = array('id' => $_SESSION["ZOHO_CURRENT_UUID"], 'apikey' => $this->getFilteredOption("ZOHO_API_KEY", $repository->getId()), 'output' => 'url', 'lang' => "en", 'filename' => urlencode(basename($file)), 'persistence' => 'false', 'format' => $extension, 'mode' => 'normaledit', 'saveurl' => $saveUrl . "?signature=" . $b64Sig);
         $service = "exportwriter";
         if (in_array($extension, $sheetExt)) {
             $service = "sheet";
         } else {
             if (in_array($extension, $presExt)) {
                 $service = "show";
             } else {
                 if (in_array($extension, $docExt)) {
                     $service = "exportwriter";
                 }
             }
         }
         $arguments = array();
         $httpClient->GetRequestArguments("https://" . $service . ".zoho.com/remotedoc.im", $arguments);
         $arguments["PostValues"] = $params;
         $arguments["PostFiles"] = array("content" => array("FileName" => $tmp, "Content-Type" => "automatic/name"));
         $err = $httpClient->Open($arguments);
         if (empty($err)) {
             $err = $httpClient->SendRequest($arguments);
             if (empty($err)) {
                 $response = "";
                 while (true) {
                     $body = "";
                     $error = $httpClient->ReadReplyBody($body, 1000);
                     if ($error != "" || strlen($body) == 0) {
                         break;
                     }
                     $response .= $body;
                 }
                 $result = trim($response);
                 $matchlines = explode("\n", $result);
                 $resultValues = array();
                 foreach ($matchlines as $line) {
                     list($key, $val) = explode("=", $line, 2);
                     $resultValues[$key] = $val;
                 }
                 if ($resultValues["RESULT"] == "TRUE" && isset($resultValues["URL"])) {
                     header("Location: " . $resultValues["URL"]);
                 } else {
                     echo "Zoho API Error " . $resultValues["ERROR_CODE"] . " : " . $resultValues["WARNING"];
                     echo "<script>window.parent.setTimeout(function(){parent.hideLightBox();}, 2000);</script>";
                 }
             }
             $httpClient->Close();
         }
     } else {
         if ($action == "retrieve_from_zohoagent") {
             $targetFile = $_SESSION["ZOHO_CURRENT_EDITED"];
             $id = $_SESSION["ZOHO_CURRENT_UUID"];
             $ext = pathinfo($targetFile, PATHINFO_EXTENSION);
             $node = new AJXP_Node($targetFile);
             $node->loadNodeInfo();
             AJXP_Controller::applyHook("node.before_change", array(&$node));
             $b64Sig = $this->signID($id);
             if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) {
                 $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()) . "?ajxp_action=get_file&name=" . $id . "&ext=" . $ext . "&signature=" . $b64Sig;
                 $data = AJXP_Utils::getRemoteContent($url);
                 if (strlen($data)) {
                     file_put_contents($targetFile, $data);
                     echo "MODIFIED";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext)) {
                     copy(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext, $targetFile);
                     unlink(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext);
                     echo "MODIFIED";
                 }
             }
             $this->logInfo('Edit', 'Retrieved content of ' . $node->getUrl());
             AJXP_Controller::applyHook("node.change", array(null, &$node));
         }
     }
 }