예제 #1
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.
 }
 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);
 }
예제 #3
0
 public function switchAction($action, $httpVars, $postProcessData)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . "/";
     if ($action == "audio_proxy") {
         $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
         $cType = "audio/" . array_pop(explode(".", $file));
         $localName = basename($file);
         header("Content-Type: " . $cType . "; name=\"" . $localName . "\"");
         header("Content-Length: " . filesize($destStreamURL . $file));
         $stream = fopen("php://output", "a");
         call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
         fflush($stream);
         fclose($stream);
         $node = new AJXP_Node($destStreamURL . $file);
         AJXP_Controller::applyHook("node.read", array($node));
         //exit(1);
     } else {
         if ($action == "ls") {
             if (!isset($httpVars["playlist"])) {
                 // This should not happen anyway, because of the applyCondition.
                 AJXP_Controller::passProcessDataThrough($postProcessData);
                 return;
             }
             // We transform the XML into XSPF
             $xmlString = $postProcessData["ob_output"];
             $xmlDoc = new DOMDocument();
             $xmlDoc->loadXML($xmlString);
             $xElement = $xmlDoc->documentElement;
             header("Content-Type:application/xspf+xml;charset=UTF-8");
             print '<?xml version="1.0" encoding="UTF-8"?>';
             print '<playlist version="1" xmlns="http://xspf.org/ns/0/">';
             print "<trackList>";
             foreach ($xElement->childNodes as $child) {
                 $isFile = $child->getAttribute("is_file") == "true";
                 $label = $child->getAttribute("text");
                 $ar = explode(".", $label);
                 $ext = strtolower(end($ar));
                 if (!$isFile || $ext != "mp3") {
                     continue;
                 }
                 print "<track><location>" . AJXP_SERVER_ACCESS . "?secure_token=" . AuthService::getSecureToken() . "&get_action=audio_proxy&file=" . base64_encode($child->getAttribute("filename")) . "</location><title>" . $label . "</title></track>";
             }
             print "</trackList>";
             AJXP_XMLWriter::close("playlist");
         }
     }
 }
 public function 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");
     }
 }
예제 #5
0
 /**
  * @static
  * @param Array $data
  * @return void
  */
 public static function loadPubliclet($data)
 {
     // create driver from $data
     $className = $data["DRIVER"] . "AccessDriver";
     $hash = md5(serialize($data));
     $u = parse_url($_SERVER["REQUEST_URI"]);
     $shortHash = pathinfo(basename($u["path"]), PATHINFO_FILENAME);
     if ($data["EXPIRE_TIME"] && time() > $data["EXPIRE_TIME"] || $data["DOWNLOAD_LIMIT"] && $data["DOWNLOAD_LIMIT"] > 0 && $data["DOWNLOAD_LIMIT"] <= PublicletCounter::getCount($shortHash)) {
         // Remove the publiclet, it's done
         if (strstr(realpath($_SERVER["SCRIPT_FILENAME"]), realpath(ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"))) !== FALSE) {
             PublicletCounter::delete($shortHash);
             unlink($_SERVER["SCRIPT_FILENAME"]);
         }
         echo "Link is expired, sorry.";
         exit;
     }
     // Load language messages
     $language = ConfService::getLanguage();
     if (isset($_GET["lang"])) {
         $language = basename($_GET["lang"]);
     }
     $messages = array();
     if (is_file(dirname(__FILE__) . "/res/i18n/" . $language . ".php")) {
         include dirname(__FILE__) . "/res/i18n/" . $language . ".php";
     } else {
         include dirname(__FILE__) . "/res/i18n/en.php";
     }
     if (isset($mess)) {
         $messages = $mess;
     }
     $AJXP_LINK_HAS_PASSWORD = false;
     $AJXP_LINK_BASENAME = SystemTextEncoding::toUTF8(basename($data["FILE_PATH"]));
     AJXP_PluginsService::getInstance()->initActivePlugins();
     $customs = array("title", "legend", "legend_pass", "background_attributes_1", "background_attributes_2", "background_attributes_3", "text_color", "background_color", "textshadow_color");
     $images = array("button", "background_1", "background_2", "background_3");
     $shareCenter = AJXP_PluginsService::findPlugin("action", "share");
     $confs = $shareCenter->getConfigs();
     foreach ($customs as $custom) {
         $varName = "CUSTOM_SHAREPAGE_" . strtoupper($custom);
         ${$varName} = $confs[$varName];
     }
     $dlFolder = realpath(ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"));
     foreach ($images as $custom) {
         $varName = "CUSTOM_SHAREPAGE_" . strtoupper($custom);
         if (!empty($confs[$varName])) {
             if (strpos($confs[$varName], "plugins/") === 0 && is_file(AJXP_INSTALL_PATH . "/" . $confs[$varName])) {
                 $realFile = AJXP_INSTALL_PATH . "/" . $confs[$varName];
                 copy($realFile, $dlFolder . "/binary-" . basename($realFile));
                 ${$varName} = "binary-" . basename($realFile);
             } else {
                 ${$varName} = "binary-" . $confs[$varName];
                 if (is_file($dlFolder . "/binary-" . $confs[$varName])) {
                     continue;
                 }
                 $copiedImageName = $dlFolder . "/binary-" . $confs[$varName];
                 $imgFile = fopen($copiedImageName, "wb");
                 ConfService::getConfStorageImpl()->loadBinary(array(), $confs[$varName], $imgFile);
                 fclose($imgFile);
             }
         }
     }
     HTMLWriter::charsetHeader();
     // Check password
     if (strlen($data["PASSWORD"])) {
         if (!isset($_POST['password']) || $_POST['password'] != $data["PASSWORD"]) {
             //AJXP_PluginsService::getInstance()->initActivePlugins();
             $AJXP_LINK_HAS_PASSWORD = true;
             $AJXP_LINK_WRONG_PASSWORD = isset($_POST['password']) && $_POST['password'] != $data["PASSWORD"];
             include AJXP_INSTALL_PATH . "/plugins/action.share/res/public_links.php";
             $res = '<div style="position: absolute;z-index: 10000; bottom: 0; right: 0; color: #666;font-family: HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size: 13px;text-align: right;padding: 6px; line-height: 20px;text-shadow: 0px 1px 0px white;" class="no_select_bg"><br>Build your own box with Pydio : <a style="color: #000000;" target="_blank" href="http://pyd.io/">http://pyd.io/</a><br/>Community - Free non supported version © C. du Jeu 2008-2014 </div>';
             AJXP_Controller::applyHook("tpl.filter_html", array(&$res));
             echo $res;
             return;
         }
     } else {
         if (!isset($_GET["dl"])) {
             //AJXP_PluginsService::getInstance()->initActivePlugins();
             include AJXP_INSTALL_PATH . "/plugins/action.share/res/public_links.php";
             $res = '<div style="position: absolute;z-index: 10000; bottom: 0; right: 0; color: #666;font-family: HelveticaNeue-Light,Helvetica Neue Light,Helvetica Neue,Helvetica,Arial,Lucida Grande,sans-serif;font-size: 13px;text-align: right;padding: 6px; line-height: 20px;text-shadow: 0px 1px 0px white;" class="no_select_bg"><br>Build your own box with Pydio : <a style="color: #000000;" target="_blank" href="http://pyd.io/">http://pyd.io/</a><br/>Community - Free non supported version © C. du Jeu 2008-2014 </div>';
             AJXP_Controller::applyHook("tpl.filter_html", array(&$res));
             echo $res;
             return;
         }
     }
     $filePath = AJXP_INSTALL_PATH . "/plugins/access." . $data["DRIVER"] . "/class." . $className . ".php";
     if (!is_file($filePath)) {
         die("Warning, cannot find driver for conf storage! ({$className}, {$filePath})");
     }
     require_once $filePath;
     $driver = new $className($data["PLUGIN_ID"], $data["BASE_DIR"]);
     $driver->loadManifest();
     //$hash = md5(serialize($data));
     PublicletCounter::increment($shortHash);
     //AuthService::logUser($data["OWNER_ID"], "", true);
     AuthService::logTemporaryUser($data["OWNER_ID"], $shortHash);
     if (isset($data["SAFE_USER"]) && isset($data["SAFE_PASS"])) {
         // FORCE SESSION MODE
         AJXP_Safe::getInstance()->forceSessionCredentialsUsage();
         AJXP_Safe::storeCredentials($data["SAFE_USER"], $data["SAFE_PASS"]);
     }
     $repoObject = $data["REPOSITORY"];
     ConfService::switchRootDir($repoObject->getId());
     ConfService::loadRepositoryDriver();
     AJXP_PluginsService::getInstance()->initActivePlugins();
     try {
         $params = array("file" => SystemTextEncoding::toUTF8($data["FILE_PATH"]));
         if (isset($data["PLUGINS_DATA"])) {
             $params["PLUGINS_DATA"] = $data["PLUGINS_DATA"];
         }
         if (isset($_GET["ct"]) && $_GET["ct"] == "true") {
             $mime = pathinfo($params["file"], PATHINFO_EXTENSION);
             $editors = AJXP_PluginsService::searchAllManifests("//editor[contains(@mimes,'{$mime}') and @previewProvider='true']", "node", true, true, false);
             if (count($editors)) {
                 foreach ($editors as $editor) {
                     $xPath = new DOMXPath($editor->ownerDocument);
                     $callbacks = $xPath->query("//action[@contentTypedProvider]", $editor);
                     if ($callbacks->length) {
                         $data["ACTION"] = $callbacks->item(0)->getAttribute("name");
                         if ($data["ACTION"] == "audio_proxy") {
                             $params["file"] = base64_encode($params["file"]);
                         }
                         break;
                     }
                 }
             }
         }
         AJXP_Controller::findActionAndApply($data["ACTION"], $params, null);
         register_shutdown_function(array("AuthService", "clearTemporaryUser"), $shortHash);
     } catch (Exception $e) {
         AuthService::clearTemporaryUser($shortHash);
         die($e->getMessage());
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     //AJXP_Logger::logAction("DL file", $httpVars);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     if (isset($httpVars["file"])) {
         $parts = parse_url($httpVars["file"]);
         $getPath = $parts["path"];
         $basename = basename($getPath);
     }
     if (isset($httpVars["dlfile"])) {
         $dlFile = $streamData["protocol"] . "://" . $repository->getId() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]);
         $realFile = file_get_contents($dlFile);
         if (empty($realFile)) {
             throw new Exception("cannot find file {$dlFile} for download");
         }
         $parts = parse_url($realFile);
         $getPath = $parts["path"];
         $basename = basename($getPath);
     }
     switch ($action) {
         case "external_download":
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars);
                 if ($unixProcess !== null) {
                     @file_put_contents($destStreamURL . "." . $basename . ".pid", $unixProcess->getPid());
                 }
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             require_once AJXP_BIN_FOLDER . "/class.HttpClient.php";
             $mess = ConfService::getMessages();
             session_write_close();
             $client = new HttpClient($parts["host"]);
             $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => "");
             $client->setHeadersOnly(true, $collectHeaders);
             $client->setMaxRedirects(8);
             $client->setDebug(false);
             $client->get($getPath);
             $pidHiddenFileName = $destStreamURL . "." . $basename . ".pid";
             if (is_file($pidHiddenFileName)) {
                 $pid = file_get_contents($pidHiddenFileName);
                 @unlink($pidHiddenFileName);
             }
             AJXP_Logger::debug("COLLECTED HEADERS", $client->collectHeaders);
             $collectHeaders = $client->collectHeaders;
             $totalSize = -1;
             if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) {
                 $ar = explode("filename=", $collectHeaders["content-disposition"]);
                 $basename = trim(array_pop($ar));
                 $basename = str_replace("\"", "", $basename);
                 // Remove quotes
             }
             if (!empty($collectHeaders["content-length"])) {
                 $totalSize = intval($collectHeaders["content-length"]);
                 AJXP_Logger::debug("Should download {$totalSize} bytes!");
             }
             if ($totalSize != -1) {
                 $node = new AJXP_Node($destStreamURL . $basename);
                 AJXP_Controller::applyHook("node.before_create", array($node, $totalSize));
             }
             $qData = false;
             if (!empty($collectHeaders["ajxp-last-redirection"])) {
                 $newParsed = parse_url($collectHeaders["ajxp-last-redirection"]);
                 $client->host = $newParsed["host"];
                 $getPath = $newParsed["path"];
                 if (isset($newParsed["query"])) {
                     $qData = parse_url($newParsed["query"]);
                 }
             }
             $tmpFilename = $destStreamURL . $basename . ".dlpart";
             $hiddenFilename = $destStreamURL . "__" . $basename . ".ser";
             $filename = $destStreamURL . $basename;
             $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize);
             if (isset($pid)) {
                 $dlData["pid"] = $pid;
             }
             //file_put_contents($hiddenFilename, serialize($dlData));
             $fpHid = fopen($hiddenFilename, "w");
             fputs($fpHid, serialize($dlData));
             fclose($fpHid);
             $client->redirect_count = 0;
             $client->setHeadersOnly(false);
             $destStream = fopen($tmpFilename, "w");
             if ($destStream !== false) {
                 $client->writeContentToStream($destStream);
                 $client->get($getPath, $qData);
                 fclose($destStream);
             }
             rename($tmpFilename, $filename);
             unlink($hiddenFilename);
             if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) {
                 AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($dlFile)));
                 unlink($dlFile);
                 AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false));
             }
             AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]);
             AJXP_XMLWriter::close();
             exit;
             break;
         case "update_dl_data":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             header("text/plain");
             if (is_file($destStreamURL . $file)) {
                 echo filesize($destStreamURL . $file);
             } else {
                 echo "stop";
             }
             exit;
             break;
         case "stop_dl":
             $newName = "__" . str_replace(".dlpart", ".ser", $basename);
             $hiddenFilename = $destStreamURL . $newName;
             $data = @unserialize(@file_get_contents($hiddenFilename));
             header("text/plain");
             AJXP_Logger::debug("Getting {$hiddenFilename}", $data);
             if (isset($data["pid"])) {
                 $process = new UnixProcess();
                 $process->setPid($data["pid"]);
                 $process->stop();
                 unlink($hiddenFilename);
                 unlink($destStreamURL . $basename);
                 echo 'stop';
             } else {
                 echo 'failed';
             }
             exit;
             break;
         default:
             break;
     }
     return true;
 }
예제 #7
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     //$this->logInfo("DL file", $httpVars);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $dlURL = null;
     if (isset($httpVars["file"])) {
         $parts = parse_url($httpVars["file"]);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $httpVars["file"];
     }
     if (isset($httpVars["dlfile"])) {
         $dlFile = $streamData["protocol"] . "://" . $repository->getId() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]);
         $realFile = file_get_contents($dlFile);
         if (empty($realFile)) {
             throw new Exception("cannot find file {$dlFile} for download");
         }
         $parts = parse_url($realFile);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $realFile;
     }
     switch ($action) {
         case "external_download":
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars);
                 if ($unixProcess !== null) {
                     @file_put_contents($destStreamURL . "." . $basename . ".pid", $unixProcess->getPid());
                 }
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
             session_write_close();
             $httpClient = new http_class();
             $arguments = array();
             $httpClient->GetRequestArguments($httpVars["file"], $arguments);
             $err = $httpClient->Open($arguments);
             $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => "");
             if (empty($err)) {
                 $err = $httpClient->SendRequest($arguments);
                 $httpClient->follow_redirect = true;
                 $pidHiddenFileName = $destStreamURL . "." . $basename . ".pid";
                 if (is_file($pidHiddenFileName)) {
                     $pid = file_get_contents($pidHiddenFileName);
                     @unlink($pidHiddenFileName);
                 }
                 if (empty($err)) {
                     $httpClient->ReadReplyHeaders($collectHeaders);
                     $totalSize = -1;
                     if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) {
                         $ar = explode("filename=", $collectHeaders["content-disposition"]);
                         $basename = trim(array_pop($ar));
                         $basename = str_replace("\"", "", $basename);
                         // Remove quotes
                     }
                     if (!empty($collectHeaders["content-length"])) {
                         $totalSize = intval($collectHeaders["content-length"]);
                         $this->logDebug("Should download {$totalSize} bytes!");
                     }
                     if ($totalSize != -1) {
                         $node = new AJXP_Node($destStreamURL . $basename);
                         AJXP_Controller::applyHook("node.before_create", array($node, $totalSize));
                     }
                     $tmpFilename = $destStreamURL . $basename . ".dlpart";
                     $hiddenFilename = $destStreamURL . "__" . $basename . ".ser";
                     $filename = $destStreamURL . $basename;
                     $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize);
                     if (isset($pid)) {
                         $dlData["pid"] = $pid;
                     }
                     //file_put_contents($hiddenFilename, serialize($dlData));
                     $fpHid = fopen($hiddenFilename, "w");
                     fputs($fpHid, serialize($dlData));
                     fclose($fpHid);
                     // NOW READ RESPONSE
                     $destStream = fopen($tmpFilename, "w");
                     while (true) {
                         $body = "";
                         $error = $httpClient->ReadReplyBody($body, 1000);
                         if ($error != "" || strlen($body) == 0) {
                             break;
                         }
                         fwrite($destStream, $body, strlen($body));
                     }
                     fclose($destStream);
                     rename($tmpFilename, $filename);
                     unlink($hiddenFilename);
                 }
                 $httpClient->Close();
                 if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) {
                     AJXP_Controller::applyHook("node.before_path_change", array(new AJXP_Node($dlFile)));
                     unlink($dlFile);
                     AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false));
                 }
                 $mess = ConfService::getMessages();
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false));
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]);
                 AJXP_XMLWriter::close();
             }
             break;
         case "update_dl_data":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             header("text/plain");
             if (is_file($destStreamURL . $file)) {
                 $node = new AJXP_Node($destStreamURL . $file);
                 if (method_exists($node->getDriver(), "filesystemFileSize")) {
                     $filesize = $node->getDriver()->filesystemFileSize($node->getUrl());
                 } else {
                     $filesize = filesize($node->getUrl());
                 }
                 echo $filesize;
             } else {
                 echo "stop";
             }
             break;
         case "stop_dl":
             $newName = "__" . str_replace(".dlpart", ".ser", $basename);
             $hiddenFilename = $destStreamURL . $newName;
             $data = @unserialize(@file_get_contents($hiddenFilename));
             header("text/plain");
             $this->logDebug("Getting {$hiddenFilename}", $data);
             if (isset($data["pid"])) {
                 $process = new UnixProcess();
                 $process->setPid($data["pid"]);
                 $process->stop();
                 unlink($hiddenFilename);
                 unlink($destStreamURL . $basename);
                 echo 'stop';
             } else {
                 echo 'failed';
             }
             break;
         default:
             break;
     }
     return false;
 }
예제 #8
0
 /**
  * Find the streamWrapper declared by the access driver
  * @param bool $register
  * @param array $streams
  * @return bool
  */
 public function detectStreamWrapper($register = false, &$streams = null)
 {
     $plugin = AJXP_PluginsService::findPlugin("access", $this->accessType);
     if (!$plugin) {
         return false;
     }
     $streamData = $plugin->detectStreamWrapper($register);
     if (!$register && $streamData !== false && is_array($streams)) {
         $streams[$this->accessType] = $this->accessType;
     }
     if ($streamData !== false) {
         $this->streamData = $streamData;
     }
     return $streamData !== false;
 }
 public function postProcess($action, $httpVars, $postProcessData)
 {
     if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) {
         return;
     }
     if (self::$skipDecoding) {
     }
     if (!isset($httpVars["partitionRealName"]) && !isset($httpVars["checkRelativePath"])) {
         return;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     if (isset($httpVars["partitionRealName"])) {
         $count = intval($httpVars["partitionCount"]);
         $index = intval($httpVars["partitionIndex"]);
         $fileId = $httpVars["fileId"];
         $clientId = $httpVars["ajxp_sessid"];
         AJXP_Logger::debug("Should now rebuild file!", $httpVars);
         $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w");
         AJXP_LOGGER::debug("PartitionRealName", $destStreamURL . $httpVars["partitionRealName"]);
         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);
     }
     if (isset($httpVars["checkRelativePath"])) {
         AJXP_LOGGER::debug("Now dispatching relativePath dest:", $httpVars["relativePath"]);
         $subs = explode("/", $httpVars["relativePath"]);
         $userfile_name = array_pop($subs);
         $subpath = "";
         $curDir = "";
         // remove trailing slash from current dir if we've got subdirs
         if (count($subs) > 0) {
             if (substr($curDir, -1) == "/") {
                 $curDir = substr($curDir, 0, -1);
             }
             $folderForbidden = false;
             // Create the folder tree as necessary
             foreach ($subs as $key => $spath) {
                 $messtmp = "";
                 $dirname = AJXP_Utils::decodeSecureMagic($spath, AJXP_SANITIZE_HTML_STRICT);
                 $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
                     AJXP_Logger::debug("{$curDir}/{$dirname} existing, traversing for {$userfile_name} out of", $httpVars["relativePath"]);
                     $curDir .= "/" . $dirname;
                     continue;
                 }
                 AJXP_Logger::debug($destStreamURL . $curDir);
                 $dirMode = 0775;
                 $chmodValue = $repository->getOption("CHMOD_VALUE");
                 if (isset($chmodValue) && $chmodValue != "") {
                     $dirMode = octdec(ltrim($chmodValue, "0"));
                     if ($dirMode & 0400) {
                         $dirMode |= 0100;
                     }
                     // User 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
                 }
                 $old = umask(0);
                 mkdir($destStreamURL . $curDir . "/" . $dirname, $dirMode);
                 umask($old);
                 $curDir .= "/" . $dirname;
             }
             // Now move the final file to the right folder
             // Currently the file is at the base of the current
             $relPath = AJXP_Utils::decodeSecureMagic($httpVars["relativePath"]);
             $current = $destStreamURL . basename($relPath);
             $target = $destStreamURL . $relPath;
             if (!$folderForbidden) {
                 $err = copy($current, $target);
                 if ($err !== false) {
                     unlink($current);
                 }
             } else {
                 // Remove the file, as it should not have been uploaded!
                 unlink($current);
             }
         }
     }
 }
 public function crossRepositoryCopy($httpVars)
 {
     ConfService::detectRepositoryStreams(true);
     $mess = ConfService::getMessages();
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     $files = $selection->getFiles();
     $accessType = $this->repository->getAccessType();
     $repositoryId = $this->repository->getId();
     $plugin = AJXP_PluginsService::findPlugin("access", $accessType);
     $origWrapperData = $plugin->detectStreamWrapper(true);
     $origStreamURL = $origWrapperData["protocol"] . "://{$repositoryId}";
     $destRepoId = $httpVars["dest_repository_id"];
     $destRepoObject = ConfService::getRepositoryById($destRepoId);
     $destRepoAccess = $destRepoObject->getAccessType();
     $plugin = AJXP_PluginsService::findPlugin("access", $destRepoAccess);
     $plugin->repository = $destRepoObject;
     $destWrapperData = $plugin->detectStreamWrapper(true);
     $destStreamURL = $destWrapperData["protocol"] . "://{$destRepoId}";
     // Check rights
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId) || isset($httpVars["moving_files"]) && !$loggedUser->canWrite($repositoryId)) {
             throw new Exception($mess[364]);
         }
     }
     $srcRepoData = array('base_url' => $origStreamURL, 'wrapper_name' => $origWrapperData['classname'], 'recycle' => $this->repository->getOption("RECYCLE_BIN"));
     $destRepoData = array('base_url' => $destStreamURL, 'wrapper_name' => $destWrapperData['classname'], 'chmod' => $this->repository->getOption('CHMOD'));
     $messages = array();
     $errorMessages = array();
     foreach ($files as $file) {
         $this->copyOrMoveFile(AJXP_Utils::decodeSecureMagic($httpVars["dest"]), $file, $errorMessages, $messages, isset($httpVars["moving_files"]) ? true : false, $srcRepoData, $destRepoData);
     }
     AJXP_XMLWriter::header();
     if (count($errorMessages)) {
         AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true);
     }
     AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true);
     AJXP_XMLWriter::close();
 }
예제 #11
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));
         }
     }
 }
 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 unifyChunks($action, &$httpVars, &$fileVars)
 {
     $filename = AJXP_Utils::decodeSecureMagic($httpVars["name"]);
     $tmpName = $fileVars["file"]["tmp_name"];
     $chunk = $httpVars["chunk"];
     $chunks = $httpVars["chunks"];
     //error_log("currentChunk:".$chunk."  chunks: ".$chunks);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $wrapperName = $streamData["classname"];
     $dir = AJXP_Utils::securePath($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $driver = ConfService::loadDriverForRepository($repository);
     $remote = false;
     if (method_exists($driver, "storeFileToCopy")) {
         $remote = true;
         $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($repository->getOption("TMP_UPLOAD"));
         // Make tmp folder a bit more unique using secure_token
         $tmpFolder = $destCopy . "/" . $httpVars["secure_token"];
         if (!is_dir($tmpFolder)) {
             @mkdir($tmpFolder, 0700, true);
         }
         $target = $tmpFolder . '/' . $filename;
         $fileVars["file"]["destination"] = base64_encode($dir);
     } else {
         if (call_user_func(array($wrapperName, "isRemote"))) {
             $remote = true;
             $tmpFolder = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["secure_token"];
             if (!is_dir($tmpFolder)) {
                 @mkdir($tmpFolder, 0700, true);
             }
             $target = $tmpFolder . '/' . $filename;
         } else {
             $target = $destStreamURL . $filename;
         }
     }
     //error_log("Directory: ".$dir);
     // Clean the fileName for security reasons
     //$filename = preg_replace('/[^\w\._]+/', '', $filename);
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($tmpName) && is_uploaded_file($tmpName)) {
             //error_log("tmpName: ".$tmpName);
             // Open temp file
             $out = fopen($target, $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen($tmpName, "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($tmpName);
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
             }
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
     } else {
         // Open temp file
         $out = fopen($target, $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
             }
             fclose($in);
             fclose($out);
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         }
     }
     /* we apply the hook if we are uploading the last chunk */
     if ($chunk == $chunks - 1) {
         if (!$remote) {
             AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($destStreamURL . $filename), false));
         } else {
             if (method_exists($driver, "storeFileToCopy")) {
                 $fileVars["file"]["tmp_name"] = $target;
                 $fileVars["file"]["name"] = $filename;
                 $driver->storeFileToCopy($fileVars["file"]);
                 AJXP_Controller::findActionAndApply("next_to_remote", array(), array());
             } else {
                 // Remote Driver case: copy temp file to destination
                 $node = new AJXP_Node($destStreamURL . $filename);
                 AJXP_Controller::applyHook("node.before_create", array($node, filesize($target)));
                 AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destStreamURL)));
                 $res = copy($target, $destStreamURL . $filename);
                 if ($res) {
                     @unlink($target);
                 }
                 AJXP_Controller::applyHook("node.change", array(null, $node, false));
             }
         }
     }
     // Return JSON-RPC response
     die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
 }
예제 #14
0
    if (isset($_POST["action"]) || isset($_POST["get_action"])) {
        $action = isset($_POST["get_action"]) ? $_POST["get_action"] : $_POST["action"];
    }
}
//------------------------------------------------------------
// SPECIAL HANDLING FOR FANCY UPLOADER RIGHTS FOR THIS ACTION
//------------------------------------------------------------
if (AuthService::usersEnabled()) {
    $loggedUser = AuthService::getLoggedUser();
    if ($action == "upload" && ($loggedUser == null || !$loggedUser->canWrite(ConfService::getCurrentRootDirIndex() . "")) && 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");
$ajxpDriver->init(ConfService::getRepository());
$authDriver = ConfService::getAuthDriverImpl();
// DRIVERS BELOW NEED IDENTIFICATION CHECK
if (!AuthService::usersEnabled() || ALLOW_GUEST_BROWSING || AuthService::getLoggedUser() != null) {
    $confDriver = ConfService::getConfStorageImpl();
    $Driver = ConfService::loadRepositoryDriver();
}
ConfService::initActivePlugins();
require_once INSTALL_PATH . "/server/classes/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();
    exit(1);
예제 #15
0
 /**
  * returns an instance of the AbstractLogDriver object
  *
  * @access public
  * @static
  *
  * @return AbstractLogDriver an instance of the AJXP_Logger object
  */
 public static function getInstance()
 {
     if (!isset(self::$loggerInstance)) {
         $p = AJXP_PluginsService::findPlugin("core", "log");
         if (is_object($p)) {
             $p->init(array());
         }
     }
     return self::$loggerInstance;
 }
 function crossRepositoryCopy($httpVars)
 {
     ConfService::detectRepositoryStreams(true);
     $mess = ConfService::getMessages();
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     $files = $selection->getFiles();
     $accessType = $this->repository->getAccessType();
     $repositoryId = $this->repository->getId();
     $plugin = AJXP_PluginsService::findPlugin("access", $accessType);
     $origWrapperData = $plugin->detectStreamWrapper(true);
     $origStreamURL = $origWrapperData["protocol"] . "://{$repositoryId}";
     $destRepoId = $httpVars["dest_repository_id"];
     $destRepoObject = ConfService::getRepositoryById($destRepoId);
     $destRepoAccess = $destRepoObject->getAccessType();
     $plugin = AJXP_PluginsService::findPlugin("access", $destRepoAccess);
     $destWrapperData = $plugin->detectStreamWrapper(true);
     $destStreamURL = $destWrapperData["protocol"] . "://{$destRepoId}";
     // Check rights
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId) || isset($httpVars["moving_files"]) && !$loggedUser->canWrite($repositoryId)) {
             throw new Exception($mess[364]);
         }
     }
     $messages = array();
     foreach ($files as $file) {
         $origFile = $origStreamURL . $file;
         $localName = "";
         AJXP_Controller::applyHook("dl.localname", array($origFile, &$localName, $origWrapperData["classname"]));
         $bName = basename($file);
         if ($localName != "") {
             $bName = $localName;
         }
         $destFile = $destStreamURL . SystemTextEncoding::fromUTF8($httpVars["dest"]) . "/" . $bName;
         AJXP_Logger::debug("Copying {$origFile} to {$destFile}");
         if (!is_file($origFile)) {
             throw new Exception("Cannot find {$origFile}");
         }
         $origHandler = fopen($origFile, "r");
         $destHandler = fopen($destFile, "w");
         if ($origHandler === false || $destHandler === false) {
             $errorMessages[] = AJXP_XMLWriter::sendMessage(null, $mess[114] . " ({$origFile} to {$destFile})", false);
             continue;
         }
         while (!feof($origHandler)) {
             fwrite($destHandler, fread($origHandler, 4096));
         }
         fflush($destHandler);
         fclose($origHandler);
         fclose($destHandler);
         $messages[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($origFile)) . " " . (isset($httpVars["moving_files"]) ? $mess[74] : $mess[73]) . " " . SystemTextEncoding::toUTF8($destFile);
     }
     AJXP_XMLWriter::header();
     if (count($errorMessages)) {
         AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true);
     }
     AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true);
     AJXP_XMLWriter::close();
 }
예제 #17
0
 public static function loadMinisite($data, $hash = '', $error = null)
 {
     if (isset($data["SECURITY_MODIFIED"]) && $data["SECURITY_MODIFIED"] === true) {
         $mess = ConfService::getMessages();
         $error = $mess['share_center.164'];
     }
     $repository = $data["REPOSITORY"];
     AJXP_PluginsService::getInstance()->initActivePlugins();
     $shareCenter = AJXP_PluginsService::findPlugin("action", "share");
     $confs = $shareCenter->getConfigs();
     $minisiteLogo = "plugins/gui.ajax/PydioLogo250.png";
     if (!empty($confs["CUSTOM_MINISITE_LOGO"])) {
         $logoPath = $confs["CUSTOM_MINISITE_LOGO"];
         if (strpos($logoPath, "plugins/") === 0 && is_file(AJXP_INSTALL_PATH . "/" . $logoPath)) {
             $minisiteLogo = $logoPath;
         } else {
             $minisiteLogo = "index_shared.php?get_action=get_global_binary_param&binary_id=" . $logoPath;
         }
     }
     // Default value
     if (isset($data["AJXP_TEMPLATE_NAME"])) {
         $templateName = $data["AJXP_TEMPLATE_NAME"];
         if ($templateName == "ajxp_film_strip" && AJXP_Utils::userAgentIsMobile()) {
             $templateName = "ajxp_shared_folder";
         }
     }
     if (isset($repository)) {
         $repoObject = ConfService::getRepositoryById($repository);
         if (!is_object($repoObject)) {
             $mess = ConfService::getMessages();
             $error = $mess["share_center.166"];
             $templateName = "ajxp_unique_strip";
             $repoObject = null;
         }
     }
     if (!isset($templateName) && isset($repoObject)) {
         $filter = $repoObject->getContentFilter();
         if (!empty($filter) && count($filter->virtualPaths) == 1) {
             $templateName = "ajxp_unique_strip";
         } else {
             $templateName = "ajxp_shared_folder";
         }
     }
     if (!isset($templateName) && isset($error)) {
         $templateName = "ajxp_unique_strip";
     }
     // UPDATE TEMPLATE
     $html = file_get_contents(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/action.share/res/minisite.php");
     AJXP_Controller::applyHook("tpl.filter_html", array(&$html));
     $html = AJXP_XMLWriter::replaceAjxpXmlKeywords($html);
     $html = str_replace("AJXP_MINISITE_LOGO", $minisiteLogo, $html);
     $html = str_replace("AJXP_APPLICATION_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $html);
     $html = str_replace("PYDIO_APP_TITLE", ConfService::getCoreConf("APPLICATION_TITLE"), $html);
     if (isset($repository) && isset($repoObject)) {
         $html = str_replace("AJXP_START_REPOSITORY", $repository, $html);
         $html = str_replace("AJXP_REPOSITORY_LABEL", ConfService::getRepositoryById($repository)->getDisplay(), $html);
     }
     $html = str_replace('AJXP_HASH_LOAD_ERROR', isset($error) ? $error : '', $html);
     $html = str_replace("AJXP_TEMPLATE_NAME", $templateName, $html);
     $html = str_replace("AJXP_LINK_HASH", $hash, $html);
     $guiConfigs = AJXP_PluginsService::findPluginById("gui.ajax")->getConfigs();
     $html = str_replace("AJXP_THEME", $guiConfigs["GUI_THEME"], $html);
     if (isset($_GET["dl"]) && isset($_GET["file"])) {
         AuthService::$useSession = false;
     } else {
         session_name("AjaXplorer_Shared" . str_replace(".", "_", $hash));
         session_start();
         AuthService::disconnect();
     }
     if (!empty($data["PRELOG_USER"])) {
         AuthService::logUser($data["PRELOG_USER"], "", true);
         $html = str_replace("AJXP_PRELOGED_USER", "ajxp_preloged_user", $html);
     } else {
         if (isset($data["PRESET_LOGIN"])) {
             $_SESSION["PENDING_REPOSITORY_ID"] = $repository;
             $_SESSION["PENDING_FOLDER"] = "/";
             $html = str_replace("AJXP_PRELOGED_USER", $data["PRESET_LOGIN"], $html);
         } else {
             $html = str_replace("AJXP_PRELOGED_USER", "ajxp_legacy_minisite", $html);
         }
     }
     if (isset($hash)) {
         $_SESSION["CURRENT_MINISITE"] = $hash;
     }
     if (isset($_GET["dl"]) && isset($_GET["file"]) && (!isset($data["DOWNLOAD_DISABLED"]) || $data["DOWNLOAD_DISABLED"] === false)) {
         ConfService::switchRootDir($repository);
         ConfService::loadRepositoryDriver();
         AJXP_PluginsService::deferBuildingRegistry();
         AJXP_PluginsService::getInstance()->initActivePlugins();
         AJXP_PluginsService::flushDeferredRegistryBuilding();
         $errMessage = null;
         try {
             $params = $_GET;
             $ACTION = "download";
             if (isset($_GET["ct"])) {
                 $mime = pathinfo($params["file"], PATHINFO_EXTENSION);
                 $editors = AJXP_PluginsService::searchAllManifests("//editor[contains(@mimes,'{$mime}') and @previewProvider='true']", "node", true, true, false);
                 if (count($editors)) {
                     foreach ($editors as $editor) {
                         $xPath = new DOMXPath($editor->ownerDocument);
                         $callbacks = $xPath->query("//action[@contentTypedProvider]", $editor);
                         if ($callbacks->length) {
                             $ACTION = $callbacks->item(0)->getAttribute("name");
                             if ($ACTION == "audio_proxy") {
                                 $params["file"] = "base64encoded:" . base64_encode($params["file"]);
                             }
                             break;
                         }
                     }
                 }
             }
             AJXP_Controller::registryReset();
             AJXP_Controller::findActionAndApply($ACTION, $params, null);
         } catch (Exception $e) {
             $errMessage = $e->getMessage();
         }
         if ($errMessage == null) {
             return;
         }
         $html = str_replace('AJXP_HASH_LOAD_ERROR', $errMessage, $html);
     }
     if (isset($_GET["lang"])) {
         $loggedUser =& AuthService::getLoggedUser();
         if ($loggedUser != null) {
             $loggedUser->setPref("lang", $_GET["lang"]);
         } else {
             setcookie("AJXP_lang", $_GET["lang"]);
         }
     }
     if (!empty($data["AJXP_APPLICATION_BASE"])) {
         $tPath = $data["AJXP_APPLICATION_BASE"];
     } else {
         $tPath = !empty($data["TRAVEL_PATH_TO_ROOT"]) ? $data["TRAVEL_PATH_TO_ROOT"] : "../..";
     }
     $serverBaseUrl = AJXP_Utils::detectServerURL(true);
     // Update Host dynamically if it differ from registered one.
     $registeredHost = parse_url($tPath, PHP_URL_HOST);
     $currentHost = parse_url($serverBaseUrl, PHP_URL_HOST);
     if ($registeredHost != $currentHost) {
         $tPath = str_replace($registeredHost, $currentHost, $tPath);
     }
     // Update scheme dynamically if it differ from registered one.
     $registeredScheme = parse_url($tPath, PHP_URL_SCHEME);
     $currentScheme = parse_url($serverBaseUrl, PHP_URL_SCHEME);
     if ($registeredScheme != $currentScheme) {
         $tPath = str_replace($registeredScheme . "://", $currentScheme . "://", $tPath);
     }
     $html = str_replace("AJXP_PATH_TO_ROOT", rtrim($tPath, "/") . "/", $html);
     HTMLWriter::internetExplorerMainDocumentHeader();
     HTMLWriter::charsetHeader();
     echo $html;
 }
예제 #18
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     $wrapperClassName = $streamData["classname"];
     if (empty($httpVars["file"])) {
         return;
     }
     $file = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]);
     $mess = ConfService::getMessages();
     $node = new AJXP_Node($file);
     AJXP_Controller::applyHook("node.read", array($node));
     switch ($action) {
         case "eml_get_xml_structure":
             $params = array('include_bodies' => false, 'decode_bodies' => false, 'decode_headers' => 'UTF-8');
             $decoder = $this->getStructureDecoder($file, $wrapperClassName == "imapAccessWrapper");
             $xml = $decoder->getXML($decoder->decode($params));
             if (function_exists("imap_mime_header_decode")) {
                 $doc = new DOMDocument();
                 $doc->loadXML($xml);
                 $xPath = new DOMXPath($doc);
                 $headers = $xPath->query("//headername");
                 $changes = false;
                 foreach ($headers as $headerNode) {
                     if ($headerNode->firstChild->nodeValue == "Subject") {
                         $headerValueNode = $headerNode->nextSibling->nextSibling;
                         $value = $headerValueNode->nodeValue;
                         $elements = imap_mime_header_decode($value);
                         $decoded = "";
                         foreach ($elements as $element) {
                             $decoded .= $element->text;
                             $charset = $element->charset;
                         }
                         if ($decoded != $value) {
                             $value = SystemTextEncoding::changeCharset($charset, "UTF-8", $decoded);
                             $node = $doc->createElement("headervalue", $value);
                             $res = $headerNode->parentNode->replaceChild($node, $headerValueNode);
                             $changes = true;
                         }
                     }
                 }
                 if ($changes) {
                     $xml = $doc->saveXML();
                 }
             }
             print $xml;
             break;
         case "eml_get_bodies":
             require_once "Mail/mimeDecode.php";
             $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false);
             if ($wrapperClassName == "imapAccessWrapper") {
                 $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId"));
                 $content = $cache->getData();
             } else {
                 $content = file_get_contents($file);
             }
             $decoder = new Mail_mimeDecode($content);
             $structure = $decoder->decode($params);
             $html = $this->_findPartByCType($structure, "text", "html");
             $text = $this->_findPartByCType($structure, "text", "plain");
             if ($html != false && isset($html->ctype_parameters) && isset($html->ctype_parameters["charset"])) {
                 $charset = $html->ctype_parameters["charset"];
             }
             if (isset($charset)) {
                 header('Content-Type: text/xml; charset=' . $charset);
                 header('Cache-Control: no-cache');
                 print '<?xml version="1.0" encoding="' . $charset . '"?>';
                 print '<email_body>';
             } else {
                 AJXP_XMLWriter::header("email_body");
             }
             if ($html !== false) {
                 print '<mimepart type="html"><![CDATA[';
                 $text = $html->body;
                 print $text;
                 print "]]></mimepart>";
             }
             if ($text !== false) {
                 print '<mimepart type="plain"><![CDATA[';
                 print $text->body;
                 print "]]></mimepart>";
             }
             AJXP_XMLWriter::close("email_body");
             break;
         case "eml_dl_attachment":
             $attachId = $httpVars["attachment_id"];
             if (!isset($attachId)) {
                 break;
             }
             require_once "Mail/mimeDecode.php";
             $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false);
             if ($wrapperClassName == "imapAccessWrapper") {
                 $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId"));
                 $content = $cache->getData();
             } else {
                 $content = file_get_contents($file);
             }
             $decoder = new Mail_mimeDecode($content);
             $structure = $decoder->decode($params);
             $part = $this->_findAttachmentById($structure, $attachId);
             if ($part !== false) {
                 $fake = new fsAccessDriver("fake", "");
                 $fake->readFile($part->body, "file", $part->d_parameters['filename'], true);
                 exit;
             } else {
                 //var_dump($structure);
             }
             break;
         case "eml_cp_attachment":
             $attachId = $httpVars["attachment_id"];
             $destRep = AJXP_Utils::decodeSecureMagic($httpVars["destination"]);
             if (!isset($attachId)) {
                 AJXP_XMLWriter::sendMessage(null, "Wrong Parameters");
                 break;
             }
             require_once "Mail/mimeDecode.php";
             $params = array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => false);
             if ($wrapperClassName == "imapAccessWrapper") {
                 $cache = AJXP_Cache::getItem("eml_remote", $file, null, array("EmlParser", "computeCacheId"));
                 $content = $cache->getData();
             } else {
                 $content = file_get_contents($file);
             }
             $decoder = new Mail_mimeDecode($content);
             $structure = $decoder->decode($params);
             $part = $this->_findAttachmentById($structure, $attachId);
             AJXP_XMLWriter::header();
             if ($part !== false) {
                 if (isset($httpVars["dest_repository_id"])) {
                     $destRepoId = $httpVars["dest_repository_id"];
                     if (AuthService::usersEnabled()) {
                         $loggedUser = AuthService::getLoggedUser();
                         if (!$loggedUser->canWrite($destRepoId)) {
                             throw new Exception($mess[364]);
                         }
                     }
                     $destRepoObject = ConfService::getRepositoryById($destRepoId);
                     $destRepoAccess = $destRepoObject->getAccessType();
                     $plugin = AJXP_PluginsService::findPlugin("access", $destRepoAccess);
                     $destWrapperData = $plugin->detectStreamWrapper(true);
                     $destStreamURL = $destWrapperData["protocol"] . "://{$destRepoId}";
                 }
                 $destFile = $destStreamURL . $destRep . "/" . $part->d_parameters['filename'];
                 $fp = fopen($destFile, "w");
                 if ($fp !== false) {
                     fwrite($fp, $part->body, strlen($part->body));
                     fclose($fp);
                     AJXP_XMLWriter::sendMessage(sprintf($mess["editor.eml.7"], $part->d_parameters["filename"], $destRep), NULL);
                 } else {
                     AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.8"]);
                 }
             } else {
                 AJXP_XMLWriter::sendMessage(null, $mess["editor.eml.9"]);
             }
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
 }
예제 #19
0
 public function switchAction($actionName, $httpVars, $fileVars)
 {
     $this->baseURL = rtrim($this->getFilteredOption("ETHERPAD_SERVER"), "/");
     $this->apiKey = $this->getFilteredOption("ETHERPAD_APIKEY");
     $userSelection = new UserSelection(ConfService::getRepository(), $httpVars);
     if ($userSelection->isEmpty()) {
         throw new Exception("Empty selection");
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $selectedNode = $userSelection->getUniqueNode($plugin);
     $selectedNode->loadNodeInfo();
     if (!$selectedNode->isLeaf()) {
         throw new Exception("Cannot handle folders, please select a file!");
     }
     $nodeExtension = strtolower(pathinfo($selectedNode->getPath(), PATHINFO_EXTENSION));
     // Determine pad ID
     if ($nodeExtension == "pad") {
         $padID = file_get_contents($selectedNode->getUrl());
     } else {
         // TRY TO LOAD PAD ID FROM NODE SHARED METADATA
         $metadata = $selectedNode->retrieveMetadata("etherpad", AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         if (isset($metadata["pad_id"])) {
             $padID = $metadata["pad_id"];
         } else {
             $padID = AJXP_Utils::generateRandomString();
             $selectedNode->setMetadata("etherpad", array("pad_id" => $padID), AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         }
     }
     require_once "etherpad-client/etherpad-lite-client.php";
     $client = new EtherpadLiteClient($this->apiKey, $this->baseURL . "/api");
     $loggedUser = AuthService::getLoggedUser();
     $userName = $loggedUser->getId();
     $userLabel = $loggedUser->mergedRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userName);
     $res = $client->createAuthorIfNotExistsFor($userName, $userLabel);
     $authorID = $res->authorID;
     $res2 = $client->createGroupIfNotExistsFor($loggedUser->getGroupPath());
     $groupID = $res2->groupID;
     $fullId = $groupID . "\$" . $padID;
     if ($actionName == "etherpad_create") {
         $resP = $client->listPads($groupID);
         $currentContent = file_get_contents($selectedNode->getUrl());
         if ($nodeExtension == "html" && strpos($currentContent, "<html>") === false) {
             $currentContent = "<html><head></head><body>{$currentContent}</body></html>";
         }
         if (!in_array($fullId, $resP->padIDs)) {
             $client->createGroupPad($groupID, $padID, null);
             if ($nodeExtension == "html" && !empty($currentContent)) {
                 $client->setHTML($fullId, $currentContent);
             } else {
                 if ($nodeExtension != "pad") {
                     $client->setText($fullId, $currentContent);
                 }
             }
         } else {
             if ($nodeExtension != "pad") {
                 // If someone is already connected, do not override.
                 $existingAuthors = $client->listAuthorsOfPad($fullId);
                 if (!count($existingAuthors->authorIDs)) {
                     if ($nodeExtension == "html" && !empty($currentContent)) {
                         $client->setHTML($fullId, $currentContent);
                     } else {
                         $client->setText($fullId, $currentContent);
                     }
                 }
             }
         }
         $res4 = $client->createSession($groupID, $authorID, time() + 14400);
         $sessionID = $res4->sessionID;
         setcookie('sessionID', $sessionID, null, "/");
         $padID = $groupID . '$' . $padID;
         $data = array("url" => $this->baseURL . "/p/" . $padID, "padID" => $padID, "sessionID" => $sessionID);
         HTMLWriter::charsetHeader('application/json');
         echo json_encode($data);
     } else {
         if ($actionName == "etherpad_save") {
             $padID = $httpVars["pad_id"];
             if ($nodeExtension == "html" || $nodeExtension == "pad") {
                 $res = $client->getHTML($padID);
                 $content = $res->html;
             } else {
                 $res = $client->getText($padID);
                 $content = $res->text;
             }
             if ($nodeExtension == "pad") {
                 // Create a new file and save the content in it.
                 $origUrl = $selectedNode->getUrl();
                 $mess = ConfService::getMessages();
                 $dateStamp = date(" Y-m-d H:i", time());
                 $startUrl = preg_replace('"\\.pad$"', $dateStamp . '.html', $origUrl);
                 $newNode = new AJXP_Node($startUrl);
                 AJXP_Controller::applyHook("node.before_create", array($newNode, strlen($content)));
                 file_put_contents($newNode->getUrl(), $content);
                 AJXP_Controller::applyHook("node.change", array(null, $newNode));
             } else {
                 AJXP_Controller::applyHook("node.before_change", array($selectedNode, strlen($content)));
                 file_put_contents($selectedNode->getUrl(), $content);
                 clearstatcache(true, $selectedNode->getUrl());
                 $selectedNode->loadNodeInfo(true);
                 AJXP_Controller::applyHook("node.change", array($selectedNode, $selectedNode));
             }
         } else {
             if ($actionName == "etherpad_close") {
                 // WE SHOULD DETECT IF THERE IS NOBODY CONNECTED ANYMORE, AND DELETE THE PAD.
                 // BUT SEEMS LIKE THERE'S NO WAY TO PROPERLY REMOVE AN AUTHOR VIA API
                 $sessionID = $httpVars["session_id"];
                 $client->deleteSession($sessionID);
             } else {
                 if ($actionName == "etherpad_proxy_api") {
                     if ($httpVars["api_action"] == "list_pads") {
                         $res = $client->listPads($groupID);
                     } else {
                         if ($httpVars["api_action"] == "list_authors_for_pad") {
                             $res = $client->listAuthorsOfPad($httpVars["pad_id"]);
                         }
                     }
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($res);
                 } else {
                     if ($actionName == "etherpad_get_content") {
                         HTMLWriter::charsetHeader("text/plain");
                         echo $client->getText($httpVars["pad_id"])->text;
                     }
                 }
             }
         }
     }
     return null;
 }
예제 #20
0
 public function unifyChunks($action, &$httpVars, &$fileVars)
 {
     $filename = SystemTextEncoding::fromUTF8($httpVars["name"]);
     $tmpName = $fileVars["file"]["tmp_name"];
     $chunk = $httpVars["chunk"];
     $chunks = $httpVars["chunks"];
     //error_log("currentChunk:".$chunk."  chunks: ".$chunks);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = $httpVars["dir"];
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     //error_log("Directory: ".$dir);
     // Clean the fileName for security reasons
     //$filename = preg_replace('/[^\w\._]+/', '', $filename);
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($tmpName) && is_uploaded_file($tmpName)) {
             //error_log("tmpName: ".$tmpName);
             // Open temp file
             $out = fopen($destStreamURL . $filename, $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen($tmpName, "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($tmpName);
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
             }
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
     } else {
         // Open temp file
         $out = fopen($destStreamURL . $filename, $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
             }
             fclose($in);
             fclose($out);
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         }
     }
     /* we apply the hook if we are uploading the last chunk */
     if ($chunk == $chunks - 1) {
         AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($destStreamURL . $filename), false));
     }
     // Return JSON-RPC response
     die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
 }
예제 #21
0
 public function initUniquePluginImplInst($key, $plugType)
 {
     $name = $this->configs["PLUGINS"][$key]["NAME"];
     $options = $this->configs["PLUGINS"][$key]["OPTIONS"];
     $instance = AJXP_PluginsService::findPlugin($plugType, $name);
     if (!is_object($instance)) {
         throw new Exception("Cannot find plugin {$key} for type {$plugType}");
     }
     $instance->init($options);
     $this->configs[$key] = $instance;
     $pServ = AJXP_PluginsService::getInstance();
     $pServ->setPluginUniqueActiveForType($plugType, $name);
 }
 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);
         }
     }
 }
예제 #23
0
 public function switchAction($actionName, $httpVars, $fileVars)
 {
     $this->baseURL = rtrim($this->getFilteredOption("ETHERPAD_SERVER"), "/");
     $this->apiKey = $this->getFilteredOption("ETHERPAD_APIKEY");
     if (isset($httpVars["file"])) {
         $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() . "/";
         $filename = $destStreamURL . AJXP_Utils::securePath($httpVars["file"]);
         if (!is_file($filename)) {
             throw new Exception("Cannot find file!");
         }
     }
     require_once "etherpad-client/etherpad-lite-client.php";
     $client = new EtherpadLiteClient($this->apiKey, $this->baseURL . "/api");
     $userName = AuthService::getLoggedUser()->getId();
     $res = $client->createAuthorIfNotExistsFor($userName, $userName);
     $authorID = $res->authorID;
     $res2 = $client->createGroupIfNotExistsFor("ajaxplorer");
     $groupID = $res2->groupID;
     if ($actionName == "etherpad_create") {
         if (isset($httpVars["pad_name"])) {
             $padID = $httpVars["pad_name"];
             $startContent = "";
             if ($httpVars["pad_type"] && $httpVars["pad_type"] == 'free') {
                 $padID = "FREEPAD__" . $padID;
             }
         } else {
             if (isset($httpVars["file"])) {
                 $startContent = file_get_contents($filename);
                 if (strtolower(pathinfo($filename, PATHINFO_EXTENSION)) == "html") {
                     $startContentHTML = $startContent;
                 }
                 $padID = AJXP_Utils::slugify($httpVars["file"]);
             }
         }
         $resP = $client->listPads($res2->groupID);
         $pads = $resP->padIDs;
         if (!in_array($groupID . '$' . $padID, $pads)) {
             $res3 = $client->createGroupPad($groupID, $padID, null);
             if (isset($startContentHTML)) {
                 $client->setHTML($groupID . '$' . $padID, $startContentHTML);
             } else {
                 if (!empty($startContent)) {
                     $client->setText($groupID . '$' . $padID, $startContent);
                 }
             }
         } else {
             // Check if content needs relaunch!
             $test = $client->getText($groupID . '$' . $padID);
             if (!empty($startContent) && $test->text != $startContent) {
                 if (isset($startContentHTML)) {
                     $client->setHTML($groupID . '$' . $padID, $startContentHTML);
                 } else {
                     $client->setText($groupID . '$' . $padID, $startContent);
                 }
             }
         }
         $res4 = $client->createSession($groupID, $authorID, time() + 14400);
         $sessionID = $res4->sessionID;
         setcookie('sessionID', $sessionID, null, "/");
         $padID = $groupID . '$' . $padID;
         $data = array("url" => $this->baseURL . "/p/" . $padID, "padID" => $padID, "sessionID" => $sessionID);
         HTMLWriter::charsetHeader('application/json');
         echo json_encode($data);
     } else {
         if ($actionName == "etherpad_save") {
             $node = new AJXP_Node($filename);
             $padID = $httpVars["pad_id"];
             if (isset($startContentHTML)) {
                 $res = $client->getHTML($padID);
             } else {
                 $res = $client->getText($padID);
             }
             AJXP_Controller::applyHook("node.before_change", array($node, strlen($res->text)));
             file_put_contents($filename, $res->text);
             AJXP_Controller::applyHook("node.change", array($node, $node));
         } else {
             if ($actionName == "etherpad_close") {
                 // WE SHOULD DETECT IF THERE IS NOBODY CONNECTED ANYMORE, AND DELETE THE PAD.
                 $sessionID = $httpVars["session_id"];
                 $client->deleteSession($sessionID);
             } else {
                 if ($actionName == "etherpad_proxy_api") {
                     if ($httpVars["api_action"] == "list_pads") {
                         $res = $client->listPads($groupID);
                     } else {
                         if ($httpVars["api_action"] == "list_authors_for_pad") {
                             $res = $client->listAuthorsOfPad($httpVars["pad_id"]);
                         }
                     }
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($res);
                 }
             }
         }
     }
 }