public function postProcess($action, $httpVars, $postProcessData)
 {
     if (self::$skipDecoding) {
     }
     if (!isset($httpVars["partitionRealName"])) {
         return;
     }
     $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() . $httpVars["dir"] . "/";
     $count = intval($httpVars["partitionCount"]);
     $index = intval($httpVars["partitionIndex"]);
     $fileId = $httpVars["fileId"];
     $clientId = $httpVars["clientId"];
     AJXP_Logger::debug("Should now rebuild file!", $httpVars);
     $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w");
     for ($i = 0; $i < $count; $i++) {
         $part = fopen($destStreamURL . "{$clientId}.{$fileId}.{$i}", "r");
         while (!feof($part)) {
             fwrite($newDest, fread($part, 4096));
         }
         fclose($part);
         unlink($destStreamURL . "{$clientId}.{$fileId}.{$i}");
     }
     fclose($newDest);
 }
예제 #2
0
 public function init($options)
 {
     //parent::init($options);
     $this->options = $options;
     $this->driversDef = $this->getOption("DRIVERS");
     $this->masterSlaveMode = $this->getOption("MODE") == "MASTER_SLAVE";
     $this->masterName = $this->getOption("MASTER_DRIVER");
     $this->baseName = $this->getOption("USER_BASE_DRIVER");
     foreach ($this->driversDef as $def) {
         $name = $def["NAME"];
         $options = $def["OPTIONS"];
         $options["TRANSMIT_CLEAR_PASS"] = $this->options["TRANSMIT_CLEAR_PASS"];
         $options["LOGIN_REDIRECT"] = $this->options["LOGIN_REDIRECT"];
         $instance = AJXP_PluginsService::findPlugin("auth", $name);
         if (!is_object($instance)) {
             throw new Exception("Cannot find plugin {$name} for type 'auth'");
         }
         $instance->init($options);
         if ($name != $this->getOption("MASTER_DRIVER")) {
             $this->slaveName = $name;
         }
         $this->drivers[$name] = $instance;
     }
     if (!$this->masterSlaveMode) {
         // Enable Multiple choice login screen
         $multi = AJXP_PluginsService::getInstance()->findPluginById("authfront.multi");
         $multi->enabled = true;
         $multi->options = $this->options;
     }
     // THE "LOAD REGISTRY CONTRIBUTIONS" METHOD
     // WILL BE CALLED LATER, TO BE SURE THAT THE
     // SESSION IS ALREADY STARTED.
 }
예제 #3
0
 protected function setUp()
 {
     $pServ = AJXP_PluginsService::getInstance();
     ConfService::init();
     $confPlugin = ConfService::getInstance()->confPluginSoftLoad($pServ);
     $pServ->loadPluginsRegistry(AJXP_INSTALL_PATH . "/plugins", $confPlugin);
     ConfService::start();
 }
예제 #4
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");
         }
     }
 }
예제 #5
0
 public function init($options)
 {
     parent::init($options);
     if (!isset($this->options["FTP_LOGIN_SCREEN"]) || $this->options["FTP_LOGIN_SCREEN"] != "TRUE" || $this->options["FTP_LOGIN_SCREEN"] === false) {
         return;
     }
     // ENABLE WEBFTP LOGIN SCREEN
     $this->logDebug(__FUNCTION__, "Enabling authfront.webftp");
     AJXP_PluginsService::findPluginById("authfront.webftp")->enabled = true;
 }
예제 #6
0
 public function initMeta($accessDriver)
 {
     parent::initMeta($accessDriver);
     $store = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("metastore");
     if ($store === false) {
         throw new Exception("The 'meta.simple_lock' plugin requires at least one active 'metastore' plugin");
     }
     $this->metaStore = $store;
     $this->metaStore->initMeta($accessDriver);
 }
 /**
  * @return AbstractConfDriver
  */
 public function getConfImpl()
 {
     if (!isset(self::$confImpl) || isset($this->pluginConf["UNIQUE_INSTANCE_CONFIG"]["instance_name"]) && self::$confImpl->getId() != $this->pluginConf["UNIQUE_INSTANCE_CONFIG"]["instance_name"]) {
         if (isset($this->pluginConf["UNIQUE_INSTANCE_CONFIG"])) {
             self::$confImpl = ConfService::instanciatePluginFromGlobalParams($this->pluginConf["UNIQUE_INSTANCE_CONFIG"], "AbstractConfDriver");
             AJXP_PluginsService::getInstance()->setPluginUniqueActiveForType("conf", self::$confImpl->getName());
         }
     }
     return self::$confImpl;
 }
 public function initMeta($accessDriver)
 {
     parent::initMeta($accessDriver);
     $this->notificationCenter = AJXP_PluginsService::findPluginById("core.notifications");
     $store = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("metastore");
     if ($store === false) {
         throw new Exception("The 'meta.watch' plugin requires at least one active 'metastore' plugin");
     }
     $this->metaStore = $store;
     $this->metaStore->initMeta($accessDriver);
 }
 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;
     }
 }
 protected function updateMetaShort($file, $shortUrl)
 {
     $metaStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("metastore");
     if ($metaStore !== false) {
         $driver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
         $metaStore->initMeta($driver);
         $streamData = $driver->detectStreamWrapper(false);
         $baseUrl = $streamData["protocol"] . "://" . ConfService::getRepository()->getId();
         $node = new AJXP_Node($baseUrl . $file);
         $metadata = $metaStore->retrieveMetadata($node, "ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY);
         $metadata["short_form_url"] = $shortUrl;
         $metaStore->setMetadata($node, "ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY);
     }
 }
 /**
  * Static function for packing all js and css into big files
  * Auto detect /js/*_list.txt files and /css/*_list.txt files and pack them.
  */
 function pack()
 {
     // Make sure that the gui.* plugin is loaded
     $plug = AJXP_PluginsService::getInstance()->getPluginsByType("gui");
     $sList = glob(CLIENT_RESOURCES_FOLDER . "/js/*_list.txt");
     foreach ($sList as $list) {
         $scriptName = str_replace("_list.txt", ".js", $list);
         AJXP_JSPacker::concatListAndPack($list, $scriptName, "Normal");
     }
     $sList = glob(AJXP_THEME_FOLDER . "/css/*_list.txt");
     foreach ($sList as $list) {
         $scriptName = str_replace("_list.txt", ".css", $list);
         AJXP_JSPacker::concatListAndPack($list, $scriptName, "None");
     }
 }
예제 #12
0
 public function getCacheImpl()
 {
     $pluginInstance = null;
     if (!isset(self::$cacheInstance) || isset($this->pluginConf["UNIQUE_INSTANCE_CONFIG"]["instance_name"]) && self::$cacheInstance->getId() != $this->pluginConf["UNIQUE_INSTANCE_CONFIG"]["instance_name"]) {
         if (isset($this->pluginConf["UNIQUE_INSTANCE_CONFIG"])) {
             $pluginInstance = ConfService::instanciatePluginFromGlobalParams($this->pluginConf["UNIQUE_INSTANCE_CONFIG"], "AbstractCacheDriver");
             if ($pluginInstance != false) {
                 AJXP_PluginsService::getInstance()->setPluginUniqueActiveForType("cache", $pluginInstance->getName(), $pluginInstance);
             }
         }
         self::$cacheInstance = $pluginInstance;
         if ($pluginInstance !== null && is_a($pluginInstance, "AbstractCacheDriver") && $pluginInstance->supportsPatternDelete(AJXP_CACHE_SERVICE_NS_NODES)) {
             AJXP_MetaStreamWrapper::appendMetaWrapper("pydio.cache", "CacheStreamLayer");
         }
     }
     return self::$cacheInstance;
 }
 public function getChildren()
 {
     $this->children = array();
     $u = AuthService::getLoggedUser();
     if ($u != null) {
         $repos = ConfService::getAccessibleRepositories($u);
         // Refilter to make sure the driver is an AjxpWebdavProvider
         foreach ($repos as $repository) {
             $accessType = $repository->getAccessType();
             $driver = AJXP_PluginsService::getInstance()->getPluginByTypeName("access", $accessType);
             if (is_a($driver, "AjxpWrapperProvider") && $repository->getOption("AJXP_WEBDAV_DISABLED") !== true) {
                 $this->children[$repository->getSlug()] = new Sabre\DAV\SimpleCollection($repository->getSlug());
             }
         }
     }
     return $this->children;
 }
예제 #14
0
 public function switchAction($actionName, $httpVars, $fileVars)
 {
     if ($actionName == "search-cart-download") {
         // Pipe SEARCH + DOWNLOAD actions.
         $indexer = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("index");
         if ($indexer == false) {
             return;
         }
         $httpVars["return_selection"] = true;
         unset($httpVars["get_action"]);
         $res = AJXP_Controller::findActionAndApply("search", $httpVars, $fileVars);
         if (isset($res) && is_array($res)) {
             $newHttpVars = array("selection_nodes" => $res, "dir" => "__AJXP_ZIP_FLAT__/", "archive_name" => $httpVars["archive_name"]);
             AJXP_Controller::findActionAndApply("download", $newHttpVars, array());
         }
     }
 }
예제 #15
0
 protected function updateMetaShort($file, $elementId, $shortUrl)
 {
     $driver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
     $streamData = $driver->detectStreamWrapper(false);
     $baseUrl = $streamData["protocol"] . "://" . ConfService::getRepository()->getId();
     $node = new AJXP_Node($baseUrl . $file);
     if ($node->hasMetaStore()) {
         $metadata = $node->retrieveMetadata("ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY);
         if ($elementId != -1) {
             if (!is_array($metadata["element"][$elementId])) {
                 $metadata["element"][$elementId] = array();
             }
             $metadata["element"][$elementId]["short_form_url"] = $shortUrl;
         } else {
             $metadata['short_form_url'] = $shortUrl;
         }
         $node->setMetadata("ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY);
     }
 }
예제 #16
0
 public function init($options)
 {
     parent::init($options);
     // Load all enabled frontend plugins
     $fronts = AJXP_PluginsService::getInstance()->getPluginsByType("authfront");
     usort($fronts, array($this, "frontendsSort"));
     foreach ($fronts as $front) {
         if ($front->isEnabled()) {
             $configs = $front->getConfigs();
             $protocol = $configs["PROTOCOL_TYPE"];
             if ($protocol == "session_only" && !AuthService::$useSession) {
                 continue;
             }
             if ($protocol == "no_session" && AuthService::$useSession) {
                 continue;
             }
             AJXP_PluginsService::setPluginActive($front->getType(), $front->getName(), true);
         }
     }
 }
 private function orbitExtensionActive()
 {
     $confs = ConfService::getConfStorageImpl()->loadPluginConfig("gui", "ajax");
     if (!isset($confs) || !isset($confs["GUI_THEME"])) {
         $confs["GUI_THEME"] = "orbit";
     }
     if ($confs["GUI_THEME"] == "orbit") {
         $pServ = AJXP_PluginsService::getInstance();
         $activePlugs = $pServ->getActivePlugins();
         $streamWrappers = $pServ->getStreamWrapperPlugins();
         $streamActive = false;
         foreach ($streamWrappers as $sW) {
             if (array_key_exists($sW, $activePlugs) && $activePlugs[$sW] === true) {
                 $streamActive = true;
                 break;
             }
         }
         return $streamActive;
     }
     return false;
 }
 public function preProcess($action, &$httpVars, &$fileVars)
 {
     $repository = ConfService::getRepository();
     $skipDecoding = false;
     if ($repository->detectStreamWrapper(false)) {
         $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
         $streamData = $plugin->detectStreamWrapper(true);
         if ($streamData["protocol"] == "ajxp.ftp" || $streamData["protocol"] == "ajxp.remotefs") {
             AJXP_Logger::debug("Skip decoding");
             $skipDecoding = true;
         }
     }
     if (isset($fileVars["Filedata"])) {
         self::$active = true;
         AJXP_Logger::debug("Dir before base64", $httpVars);
         $httpVars["dir"] = base64_decode(urldecode($httpVars["dir"]));
         if (!$skipDecoding) {
             $fileVars["Filedata"]["name"] = SystemTextEncoding::fromUTF8($fileVars["Filedata"]["name"]);
         }
         $fileVars["userfile_0"] = $fileVars["Filedata"];
         unset($fileVars["Filedata"]);
         AJXP_Logger::debug("Setting FlexProc active");
     }
 }
예제 #19
0
 /**
  * Helpers to test SQL connection and send a test email.
  * @param $action
  * @param $httpVars
  * @param $fileVars
  * @throws Exception
  */
 public function testConnexions($action, $httpVars, $fileVars)
 {
     $data = array();
     AJXP_Utils::parseStandardFormParameters($httpVars, $data, null, "DRIVER_OPTION_");
     if ($action == "boot_test_sql_connexion") {
         $p = AJXP_Utils::cleanDibiDriverParameters($data["db_type"]);
         if ($p["driver"] == "sqlite3") {
             $dbFile = AJXP_VarsFilter::filter($p["database"]);
             if (!file_exists(dirname($dbFile))) {
                 mkdir(dirname($dbFile), 0755, true);
             }
         }
         // Should throw an exception if there was a problem.
         dibi::connect($p);
         dibi::disconnect();
         echo 'SUCCESS:Connexion established!';
     } else {
         if ($action == "boot_test_mailer") {
             $mailerPlug = AJXP_PluginsService::findPluginById("mailer.phpmailer-lite");
             $mailerPlug->loadConfigs(array("MAILER" => $data["MAILER_ENABLE"]["MAILER_SYSTEM"]));
             $mailerPlug->sendMail(array("adress" => $data["MAILER_ENABLE"]["MAILER_ADMIN"]), "Pydio Test Mail", "Body of the test", array("adress" => $data["MAILER_ENABLE"]["MAILER_ADMIN"]));
             echo 'SUCCESS:Mail sent to the admin adress, please check it is in your inbox!';
         }
     }
 }
 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);
         }
     }
 }
 protected function sendSoftLimitAlert()
 {
     $mailers = AJXP_PluginsService::getInstance()->getPluginsByType("mailer");
     if (count($mailers)) {
         $this->mailer = array_shift($mailers);
         $percent = $this->getFilteredOption("SOFT_QUOTA");
         $quota = $this->getFilteredOption("DEFAULT_QUOTA");
         $this->mailer->sendMail(array(AuthService::getLoggedUser()->getId()), "You are close to exceed your quota!", "You are currently using more than {$percent}% of your authorized quota of {$quota}!");
     }
 }
 static function filterXml(&$value)
 {
     $instance = AJXP_PluginsService::getInstance()->findPlugin("gui", "ajax");
     if ($instance === false) {
         return;
     }
     $confs = $instance->getConfigs();
     $theme = $confs["GUI_THEME"];
     if (!defined("AJXP_THEME_FOLDER")) {
         define("CLIENT_RESOURCES_FOLDER", AJXP_PLUGINS_FOLDER . "/gui.ajax/res");
         define("AJXP_THEME_FOLDER", CLIENT_RESOURCES_FOLDER . "/themes/" . $theme);
     }
     $value = str_replace(array("AJXP_CLIENT_RESOURCES_FOLDER", "AJXP_CURRENT_VERSION"), array(CLIENT_RESOURCES_FOLDER, AJXP_VERSION), $value);
     if (isset($_SESSION["AJXP_SERVER_PREFIX_URI"])) {
         $value = str_replace("AJXP_THEME_FOLDER", $_SESSION["AJXP_SERVER_PREFIX_URI"] . "plugins/gui.ajax/res/themes/" . $theme, $value);
     } else {
         $value = str_replace("AJXP_THEME_FOLDER", "plugins/gui.ajax/res/themes/" . $theme, $value);
     }
     return $value;
 }
 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)
 {
     $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
 /**
  * Write the repositories access rights in XML format
  * @static
  * @param AbstractAjxpUser|null $loggedUser * @internal param bool $details
  * @return string
  */
 public static function writeRepositoriesData($loggedUser)
 {
     $st = "<repositories>";
     $streams = ConfService::detectRepositoryStreams(false);
     $exposed = array();
     $cacheHasExposed = AJXP_PluginsService::getInstance()->loadFromPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']");
     if ($cacheHasExposed !== null && is_array($cacheHasExposed)) {
         $exposed = $cacheHasExposed;
     } else {
         $exposed_props = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'repository') and @expose='true']", "node", false, false, true);
         foreach ($exposed_props as $exposed_prop) {
             $pluginId = $exposed_prop->parentNode->parentNode->getAttribute("id");
             $paramName = $exposed_prop->getAttribute("name");
             $paramDefault = $exposed_prop->getAttribute("default");
             $exposed[] = array("PLUGIN_ID" => $pluginId, "NAME" => $paramName, "DEFAULT" => $paramDefault);
         }
         AJXP_PluginsService::getInstance()->storeToPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']", $exposed);
     }
     $accessible = ConfService::getAccessibleRepositories($loggedUser, false, false);
     $inboxStatus = 0;
     foreach ($accessible as $repoId => $repoObject) {
         if (!$repoObject->hasContentFilter()) {
             continue;
         }
         $accessStatus = $repoObject->getAccessStatus();
         if (empty($accessStatus) && $loggedUser != null) {
             $lastConnected = $loggedUser->getArrayPref("repository_last_connected", $repoId);
             if (empty($lastConnected)) {
                 $accessStatus = 1;
             }
         }
         if (!empty($accessStatus)) {
             $inboxStatus++;
         }
     }
     foreach ($accessible as $repoId => $repoObject) {
         if (!isset($_SESSION["CURRENT_MINISITE"]) && $repoObject->hasContentFilter()) {
             continue;
         }
         $accessStatus = '';
         if ($repoObject->getAccessType() == "inbox") {
             $accessStatus = $inboxStatus;
         }
         $xmlString = self::repositoryToXML($repoId, $repoObject, $exposed, $streams, $loggedUser, $accessStatus);
         $st .= $xmlString;
     }
     $st .= "</repositories>";
     return $st;
 }
예제 #26
0
 /**
  * @param ShareCenter $shareCenter
  * @param ShareStore $shareStore
  * @param ShareRightsManager $shareRightManager
  */
 public static function migrateLegacyMeta($shareCenter, $shareStore, $shareRightManager, $dryRun = true)
 {
     $metaStoreDir = AJXP_DATA_PATH . "/plugins/metastore.serial";
     $publicFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER");
     $metastores = glob($metaStoreDir . "/ajxp_meta_0");
     if ($dryRun) {
         print "RUNNING A DRY RUN FOR META MIGRATION";
     }
     foreach ($metastores as $store) {
         if (strpos($store, ".bak") !== false) {
             continue;
         }
         // Backup store
         if (!$dryRun) {
             copy($store, $store . ".bak");
         }
         $data = unserialize(file_get_contents($store));
         foreach ($data as $filePath => &$metadata) {
             foreach ($metadata as $userName => &$meta) {
                 if (!AuthService::userExists($userName)) {
                     continue;
                 }
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($userName);
                 if (isset($meta["ajxp_shared"]) && isset($meta["ajxp_shared"]["element"])) {
                     print "\n\nItem {$filePath} requires upgrade :";
                     $share = $meta["ajxp_shared"];
                     $element = $meta["ajxp_shared"]["element"];
                     if (is_array($element)) {
                         $element = array_shift(array_keys($element));
                     }
                     // Take the first one only
                     $legacyLinkFile = $publicFolder . "/" . $element . ".php";
                     if (file_exists($legacyLinkFile)) {
                         // Load file, move it to DB and move the meta
                         $publiclet = $shareStore->loadShare($element);
                         rename($legacyLinkFile, $legacyLinkFile . ".migrated");
                         if (isset($share["minisite"])) {
                             print "\n--Migrate legacy minisite to new minisite?";
                             try {
                                 $sharedRepoId = $publiclet["REPOSITORY"];
                                 $sharedRepo = ConfService::getRepositoryById($sharedRepoId);
                                 if ($sharedRepo == null) {
                                     print "\n--ERROR: Cannot find repository with id " . $sharedRepoId;
                                     continue;
                                 }
                                 $shareLink = new ShareLink($shareStore, $publiclet);
                                 $user = $shareLink->getUniqueUser();
                                 if (AuthService::userExists($user)) {
                                     $userObject = ConfService::getConfStorageImpl()->createUserObject($user);
                                     $userObject->setHidden(true);
                                     print "\n--Should set existing user {$user} as hidden";
                                     if (!$dryRun) {
                                         $userObject->save();
                                     }
                                 }
                                 $shareLink->parseHttpVars(["custom_handle" => $element]);
                                 $shareLink->setParentRepositoryId($sharedRepo->getParentId());
                                 print "\n--Creating the following share object";
                                 print_r($shareLink->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $shareLink->save();
                                 }
                                 $meta["ajxp_shared"] = ["shares" => [$element => ["type" => "minisite"], $sharedRepoId => ["type" => "repository"]]];
                             } catch (Exception $e) {
                                 print "\n-- Error " . $e->getMessage();
                             }
                         } else {
                             print "\n--Should migrate legacy link to new minisite with ContentFilter";
                             try {
                                 $link = new ShareLink($shareStore);
                                 $link->setOwnerId($userName);
                                 $parameters = array("custom_handle" => $element, "simple_right_download" => true);
                                 if (isset($publiclet["EXPIRE_TIME"])) {
                                     $parameters["expiration"] = $publiclet["EXPIRE_TIME"];
                                 }
                                 if (isset($publiclet["DOWNLOAD_LIMIT"])) {
                                     $parameters["downloadlimit"] = $publiclet["DOWNLOAD_LIMIT"];
                                 }
                                 $link->parseHttpVars($parameters);
                                 $parentRepositoryObject = $publiclet["REPOSITORY"];
                                 $driverInstance = AJXP_PluginsService::findPlugin("access", $parentRepositoryObject->getAccessType());
                                 if (empty($driverInstance)) {
                                     print "\n-- ERROR: Cannot find driver instance!";
                                     continue;
                                 }
                                 $options = $driverInstance->makeSharedRepositoryOptions(["file" => "/"], $parentRepositoryObject);
                                 $options["SHARE_ACCESS"] = "private";
                                 $newRepo = $parentRepositoryObject->createSharedChild(basename($filePath), $options, $parentRepositoryObject->getId(), $userObject->getId(), null);
                                 $gPath = $userObject->getGroupPath();
                                 if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
                                     $newRepo->setGroupPath($gPath);
                                 }
                                 $newRepo->setDescription("");
                                 // Smells like dirty hack!
                                 $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
                                 $newRepo->setContentFilter(new ContentFilter([new AJXP_Node("pydio://" . $parentRepositoryObject->getId() . $filePath)]));
                                 if (!$dryRun) {
                                     ConfService::addRepository($newRepo);
                                 }
                                 $hiddenUserEntry = $shareRightManager->prepareSharedUserEntry(["simple_right_read" => true, "simple_right_download" => true], $link, false, null);
                                 $selection = new UserSelection($parentRepositoryObject, []);
                                 $selection->addFile($filePath);
                                 if (!$dryRun) {
                                     $shareRightManager->assignSharedRepositoryPermissions($parentRepositoryObject, $newRepo, false, [$hiddenUserEntry["ID"] => $hiddenUserEntry], [], $selection);
                                 }
                                 $link->setParentRepositoryId($parentRepositoryObject->getId());
                                 $link->attachToRepository($newRepo->getId());
                                 print "\n-- Should save following LINK: ";
                                 print_r($link->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $hash = $link->save();
                                 }
                                 // UPDATE METADATA
                                 $meta["ajxp_shared"] = ["shares" => [$element => array("type" => "minisite")]];
                             } catch (Exception $e) {
                                 print "\n-- ERROR: " . $e->getMessage();
                             }
                         }
                         if ($dryRun) {
                             rename($legacyLinkFile . ".migrated", $legacyLinkFile);
                         }
                         continue;
                     } else {
                         //
                         // File does not exists, remove meta
                         //
                         unset($meta["ajxp_shared"]);
                     }
                     $repo = ConfService::getRepositoryById($element);
                     if ($repo !== null) {
                         print "\n--Shared repository: just metadata";
                         // Shared repo, migrating the meta should be enough
                         $meta["ajxp_shared"] = array("shares" => [$element => array("type" => "repository")]);
                     }
                 }
             }
         }
         print "\n\n SHOULD NOW UPDATE METADATA WITH FOLLOWING :";
         print_r($data);
         if (!$dryRun) {
             file_put_contents($store, serialize($data));
         }
     }
 }
 /**
  * Singleton method
  *
  * @return AJXP_PluginsService the service instance
  */
 public static function getInstance()
 {
     if (!isset(self::$instance)) {
         $c = __CLASS__;
         self::$instance = new $c();
     }
     return self::$instance;
 }
예제 #28
0
 /**
  * Search the manifests declaring ajxpdriver as their root node. Remove ajxp_conf & ajxp_shared
  * @static
  * @param string $filterByTagName
  * @param string $filterByDriverName
  * @param bool $limitToEnabledPlugins
  * @return string
  */
 public static function availableDriversToXML($filterByTagName = "", $filterByDriverName = "", $limitToEnabledPlugins = false)
 {
     $nodeList = AJXP_PluginsService::searchAllManifests("//ajxpdriver", "node", false, $limitToEnabledPlugins);
     $xmlBuffer = "";
     foreach ($nodeList as $node) {
         $dName = $node->getAttribute("name");
         if ($filterByDriverName != "" && $dName != $filterByDriverName) {
             continue;
         }
         if ($dName == "ajxp_conf" || $dName == "ajxp_shared") {
             continue;
         }
         if ($filterByTagName == "") {
             $xmlBuffer .= $node->ownerDocument->saveXML($node);
             continue;
         }
         $q = new DOMXPath($node->ownerDocument);
         $cNodes = $q->query("//" . $filterByTagName, $node);
         $nodeAttr = $node->attributes;
         $xmlBuffer .= "<ajxpdriver ";
         foreach ($node->attributes as $attr) {
             $xmlBuffer .= " {$attr->name}=\"{$attr->value}\" ";
         }
         $xmlBuffer .= ">";
         foreach ($cNodes as $child) {
             $xmlBuffer .= $child->ownerDocument->saveXML($child);
         }
         $xmlBuffer .= "</ajxpdriver>";
     }
     return $xmlBuffer;
 }
 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
0
파일: index.php 프로젝트: rmxcc/pydio-core
//------------------------------------------------------------
if (AuthService::usersEnabled()) {
    $loggedUser = AuthService::getLoggedUser();
    if ($action == "upload" && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRepositoryId() . "")) && isset($_FILES['Filedata'])) {
        header('HTTP/1.0 ' . '410 Not authorized');
        die('Error 410 Not authorized!');
    }
}
// THIS FIRST DRIVERS DO NOT NEED ID CHECK
//$ajxpDriver = AJXP_PluginsService::findPlugin("gui", "ajax");
$authDriver = ConfService::getAuthDriverImpl();
// DRIVERS BELOW NEED IDENTIFICATION CHECK
if (!AuthService::usersEnabled() || ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth") || AuthService::getLoggedUser() != null) {
    $confDriver = ConfService::getConfStorageImpl();
    $Driver = ConfService::loadRepositoryDriver();
}
AJXP_PluginsService::getInstance()->initActivePlugins();
require_once AJXP_BIN_FOLDER . "/class.AJXP_Controller.php";
$xmlResult = AJXP_Controller::findActionAndApply($action, array_merge($_GET, $_POST), $_FILES);
if ($xmlResult !== false && $xmlResult != "") {
    AJXP_XMLWriter::header();
    print $xmlResult;
    AJXP_XMLWriter::close();
} else {
    if (isset($requireAuth) && AJXP_Controller::$lastActionNeedsAuth) {
        AJXP_XMLWriter::header();
        AJXP_XMLWriter::requireAuth();
        AJXP_XMLWriter::close();
    }
}
session_write_close();