public function switchAction($action, $httpVars, $filesVars) { $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } if (!isset($this->pluginConf)) { $this->pluginConf = array("GENERATE_THUMBNAIL" => false); } $selection = new UserSelection($repository, $httpVars); $destStreamURL = $selection->currentBaseUrl(); if ($action == "preview_data_proxy") { $file = $selection->getUniqueFile(); if (!file_exists($destStreamURL . $file) || !is_readable($destStreamURL . $file)) { header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\""); header("Content-Length: 0"); return; } $this->logInfo('Preview', 'Preview content of ' . $file, array("files" => $selection->getUniqueFile())); if (isset($httpVars["get_thumb"]) && $httpVars["get_thumb"] == "true" && $this->getFilteredOption("GENERATE_THUMBNAIL", $repository->getId())) { $dimension = 200; if (isset($httpVars["dimension"]) && is_numeric($httpVars["dimension"])) { $dimension = $httpVars["dimension"]; } $this->currentDimension = $dimension; $cacheItem = AJXP_Cache::getItem("diaporama_" . $dimension, $destStreamURL . $file, array($this, "generateThumbnail")); $data = $cacheItem->getData(); $cId = $cacheItem->getId(); header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($cId)) . "; name=\"" . basename($cId) . "\""); header("Content-Length: " . strlen($data)); header('Cache-Control: public'); header("Pragma:"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); print $data; } else { //$filesize = filesize($destStreamURL.$file); $node = new AJXP_Node($destStreamURL . $file); $fp = fopen($destStreamURL . $file, "r"); $stat = fstat($fp); $filesize = $stat["size"]; header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\""); header("Content-Length: " . $filesize); header('Cache-Control: public'); header("Pragma:"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); $stream = fopen("php://output", "a"); AJXP_MetaStreamWrapper::copyFileInStream($destStreamURL . $file, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($node)); } } }
/** * @param string $action * @param array $httpVars * @param array $fileVars */ public function applyChangeLock($actionName, $httpVars, $fileVars) { if (!isset($this->actions[$actionName])) { return; } if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection(); $selection->initFromHttpVars(); $currentFile = $selection->getUniqueFile(); $wrapperData = $this->accessDriver->detectStreamWrapper(false); $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId(); $unlock = isset($httpVars["unlock"]) ? true : false; $ajxpNode = new AJXP_Node($urlBase . $currentFile); if ($unlock) { $this->metaStore->removeMetadata($ajxpNode, self::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL); } else { $this->metaStore->setMetadata($ajxpNode, SimpleLockManager::METADATA_LOCK_NAMESPACE, array("lock_user" => AuthService::getLoggedUser()->getId()), false, AJXP_METADATA_SCOPE_GLOBAL); } AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); }
public function preProcessMove($actionName, &$httpVars, &$fileVars) { $destO = AJXP_Utils::decodeSecureMagic($httpVars["dest"]); $dest = substr($destO, 1, strpos(ltrim($destO, "/"), "/")); if (empty($dest)) { $dest = ltrim($destO, "/"); } $userSelection = new UserSelection(); $userSelection->initFromHttpVars($httpVars); if (!$userSelection->isEmpty()) { $testFileO = $userSelection->getUniqueFile(); $testFile = substr($testFileO, 1, strpos(ltrim($testFileO, "/"), "/")); if (empty($testFile)) { $testFile = ltrim($testFileO, "/"); } if ($actionName == "move") { if (strstr($dest, "ENCFS_CLEAR_") != false && strstr($testFile, "ENCFS_CLEAR_") === false || strstr($dest, "ENCFS_CLEAR_") === false && strstr($testFile, "ENCFS_CLEAR_") !== false || strstr($dest, "ENCFS_CLEAR_") != false && strstr($testFile, "ENCFS_CLEAR_") !== false && $testFile != $dest) { $httpVars["force_copy_delete"] = "true"; $this->logDebug("One mount to another, copy/delete instead of move ({$dest}, {$testFile})"); } } else { if ($actionName == "delete" && RecycleBinManager::recycleEnabled()) { if (strstr($testFile, "ENCFS_CLEAR_") !== false) { $httpVars["force_copy_delete"] = "true"; $this->logDebug("One mount to another, copy/delete instead of move"); } } else { if ($actionName == "restore") { if (strstr(RecycleBinManager::getFileOrigin($testFile), "ENCFS_CLEAR_")) { $httpVars["force_copy_delete"] = "true"; $this->logDebug("One mount to another, copy/delete instead of move"); } } } } } }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepositoryById($httpVars["repository_id"]); if (!$repository->detectStreamWrapper(true)) { return false; } if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) { AuthService::logUser("guest", null); $loggedUser = AuthService::getLoggedUser(); } if (!$loggedUser->canSwitchTo($repository->getId())) { echo "You do not have permissions to access this resource"; return false; } } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); $selection = new UserSelection($repository, $httpVars); if ($action == "open_file") { $file = $selection->getUniqueFile(); if (!file_exists($destStreamURL . $file)) { echo "File does not exist"; return false; } $node = new AJXP_Node($destStreamURL . $file); if (method_exists($node->getDriver(), "filesystemFileSize")) { $filesize = $node->getDriver()->filesystemFileSize($node->getUrl()); } else { $filesize = filesize($node->getUrl()); } $fp = fopen($destStreamURL . $file, "rb"); $fileMime = "application/octet-stream"; //Get mimetype with fileinfo PECL extension if (class_exists("finfo")) { $finfo = new finfo(FILEINFO_MIME); $fileMime = $finfo->buffer(fread($fp, 100)); } //Get mimetype with (deprecated) mime_content_type if (strpos($fileMime, "application/octet-stream") === 0 && function_exists("mime_content_type")) { $fileMime = @mime_content_type($fp); } //Guess mimetype based on file extension if (strpos($fileMime, "application/octet-stream") === 0) { $fileExt = substr(strrchr(basename($file), '.'), 1); if (empty($fileExt)) { $fileMime = "application/octet-stream"; } else { $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i"; $lines = file($this->getBaseDir() . "/resources/other/mime.types"); foreach ($lines as $line) { if (substr($line, 0, 1) == '#') { continue; } // skip comments $line = rtrim($line) . " "; if (!preg_match($regex, $line, $matches)) { continue; } // no match to the extension $fileMime = $matches[1]; } } } fclose($fp); // If still no mimetype, give up and serve application/octet-stream if (empty($fileMime)) { $fileMime = "application/octet-stream"; } //Send headers HTMLWriter::generateInlineHeaders(basename($file), $filesize, $fileMime); $class = $streamData["classname"]; $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)); $this->logInfo('Download', 'Read content of ' . $node->getUrl()); } }
public function editMeta($actionName, $httpVars, $fileVars) { if (!isset($this->actions[$actionName])) { return; } if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection(); $selection->initFromHttpVars(); $currentFile = $selection->getUniqueFile(); $wrapperData = $this->accessDriver->detectStreamWrapper(false); $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId(); $newValues = array(); $def = $this->getMetaDefinition(); $ajxpNode = new AJXP_Node($urlBase . $currentFile); AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode)); foreach ($def as $key => $label) { if (isset($httpVars[$key])) { $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]); } else { if (!isset($original)) { $original = $this->metaStore->retrieveMetadata($ajxpNode, "users_meta", false, AJXP_METADATA_SCOPE_GLOBAL); } if (isset($original) && isset($original[$key])) { $newValues[$key] = $original[$key]; } } } $this->metaStore->setMetadata($ajxpNode, "users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL); AJXP_Controller::applyHook("node.change", array(null, &$ajxpNode)); AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true); AJXP_XMLWriter::close(); }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = Utils::securePath(SystemTextEncoding::magicDequote($getValue)); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); if (isset($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); } if (isset($dest)) { $dest = SystemTextEncoding::fromUTF8($dest); } $mess = ConfService::getMessages(); $recycleBinOption = $this->repository->getOption("RECYCLE_BIN"); // FILTER ACTION FOR DELETE if ($recycleBinOption != "" && $action == "delete" && $dir != "/" . $recycleBinOption) { $action = "move"; $dest = "/" . $recycleBinOption; $dest_node = "AJAXPLORER_RECYCLE_NODE"; } // FILTER ACTION FOR RESTORE if ($recycleBinOption != "" && $action == "restore" && $dir == "/" . $recycleBinOption) { $originalRep = RecycleBinManager::getFileOrigin($selection->getUniqueFile()); if ($originalRep != "") { $action = "move"; $dest = $originalRep; } } switch ($action) { //------------------------------------ // DOWNLOAD, IMAGE & MP3 PROXYS //------------------------------------ case "download": AJXP_Logger::logAction("Download", array("files" => $selection)); $zip = false; if ($selection->isUnique()) { if (is_dir($this->getPath() . "/" . $selection->getUniqueFile())) { $zip = true; $dir .= "/" . basename($selection->getUniqueFile()); } } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $this->downFile($this->makeName($selection->getFiles()), "force-download", "archive.zip"); } else { $this->downFile($this->makeName($selection->getUniqueFile()), "force-download", $selection->getUniqueFile()); } exit(0); break; case "image_proxy": $this->downFile($this->makeName($file), "image", $file); exit(0); break; case "mp3_proxy": $this->downFile($this->makeName($file), "mp3", $file); exit(0); break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "edit": if (isset($save) && $save == 1) { AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file))); $code = stripslashes($code); $code = str_replace("<", "<", $code); $this->SSHOperation->setRemoteContent($this->makeName($file), $code); echo $mess[115]; } else { $this->sendFile($this->SSHOperation->getRemoteContent($this->makeName($file)), "plain", $file); } exit(0); break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } $result = ""; if ($action == "move") { $result = $this->SSHOperation->moveFile($this->makeName($selection->getFiles()), $this->makeName($dest)); } else { $result = $this->SSHOperation->copyFile($this->makeName($selection->getFiles()), $this->makeName($dest)); } $mess = ConfService::getMessages(); if (strlen($result)) { $errorMessage = $mess[114]; } else { foreach ($selection->getFiles() as $files) { $logMessage .= $mess[34] . " " . SystemTextEncoding::toUTF8(basename($file)) . " " . $mess[$action == "move" ? 74 : 73] . " " . SystemTextEncoding::toUTF8($dest) . "\n"; } AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest)); } $reload_current_node = true; if (isset($dest_node)) { $reload_dest_node = $dest_node; } $reload_file_list = true; break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $messtmp = ""; $changedFiles = array(); $value = "0" . decoct(octdec(ltrim($chmod_value, "0"))); // On error, the command will fail $result = $this->SSHOperation->chmodFile($this->makeName($selection->getFiles()), $chmod_value); $mess = ConfService::getMessages(); if (strlen($result)) { $errorMessage = $mess[114]; } else { $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($selection->getFiles()) . " files or folders"; AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($selection->getFiles()))); $reload_file_list = $dir; } break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } $logMessages = array(); $result = $this->SSHOperation->deleteFile($this->makeName($selection->getFiles())); if (strlen($result)) { $mess = ConfService::getMessages(); $errorMessage = $mess[120]; } else { $mess = ConfService::getMessages(); foreach ($selection->getFiles() as $file) { $logMessages[] = "{$mess['34']} " . SystemTextEncoding::toUTF8($file) . " {$mess['44']}."; } $logMessage = join("\n", $logMessages); } AJXP_Logger::logAction("Delete", array("files" => $selection)); $reload_current_node = true; $reload_file_list = true; break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "rename": $filename_new = $dir . "/" . $filename_new; $error = $this->SSHOperation->moveFile($this->makeName($file), $this->makeName($filename_new)); if ($error != null) { $errorMessage = $error; break; } $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); $reload_current_node = true; $reload_file_list = basename($filename_new); AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; $dirname = Utils::processFileName($dirname); $error = $this->SSHOperation->createRemoteDirectory($this->makeName($dir . "/" . $dirname)); if (isset($error)) { $errorMessage = $error; break; } $reload_file_list = $dirname; $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reload_current_node = true; AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; $filename = Utils::processFileName($filename); $error = $this->SSHOperation->setRemoteContent($this->makeName($dir . "/" . $filename), ""); if (isset($error)) { $errorMessage = $error; break; } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reload_file_list = $filename; AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename)); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": $fancyLoader = false; if (isset($fileVars["Filedata"])) { $fancyLoader = true; if ($dir != "") { $dir = "/" . base64_decode($dir); } } if ($dir != "") { $rep_source = "/{$dir}"; } else { $rep_source = ""; } $destination = $rep_source; $logMessage = ""; //$fancyLoader = false; foreach ($fileVars as $boxName => $boxData) { if ($boxName != "Filedata" && substr($boxName, 0, 9) != "userfile_") { continue; } if ($boxName == "Filedata") { $fancyLoader = true; } $err = Utils::parseFileDataErrors($boxData, $fancyLoader); if ($err != null) { $errorMessage = $err; break; } $userfile_name = $boxData["name"]; $userfile_name = Utils::processFileName($userfile_name); if (!$this->SSHOperation->uploadFile($boxData["tmp_name"], $this->makeName($destination . "/" . $userfile_name))) { $errorMessage = ($fancyLoader ? "411 " : "") . "{$mess['33']} " . $userfile_name; break; } $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; AJXP_Logger::logAction("Upload File", array("file" => $dir . "/" . $userfile_name)); } if ($fancyLoader) { if (isset($errorMessage)) { header('HTTP/1.0 ' . $errorMessage); die('Error ' . $errorMessage); } else { header('HTTP/1.0 200 OK'); die("200 OK"); } } else { print "<html><script language=\"javascript\">\n"; if (isset($errorMessage)) { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');"; } else { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext();"; } print "</script></html>"; } exit; break; //------------------------------------ // Public URL //------------------------------------ //------------------------------------ // Public URL //------------------------------------ case "public_url": $file = SystemTextEncoding::fromUTF8($file); $url = $this->makePubliclet($file, $password, $expiration); header("Content-type:text/plain"); echo $url; exit(1); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $searchMode = $fileListMode = $completeMode = false; if (isset($mode)) { if ($mode == "search") { $searchMode = true; } else { if ($mode == "file_list") { $fileListMode = true; } else { if ($mode == "complete") { $completeMode = true; } } } } $nom_rep = $dir; AJXP_Exception::errorToXml($nom_rep); $result = $this->SSHOperation->listFilesIn($nom_rep); AJXP_XMLWriter::header(); foreach ($result as $file) { $attributes = ""; $fileName = SystemTextEncoding::toUTF8($file["name"]); $icon = Utils::mimetype($fileName, "image", $file["isDir"] == 1); if ($searchMode) { if ($file["isDir"] == 0) { $attributes = "is_file=\"true\" icon=\"" . SystemTextEncoding::toUTF8($icon) . "\""; } } else { if ($fileListMode) { $atts = array(); $atts[] = "is_file=\"" . (1 - $file["isDir"]) . "\""; $atts[] = "is_image=\"" . Utils::is_image($fileName) . "\""; $atts[] = "mimestring=\"" . Utils::mimetype($fileName, "type", $file["isDir"] == 1) . "\""; $atts[] = "ajxp_modiftime=\"" . $this->dateModif($file["time"]) . "\""; $atts[] = "filesize=\"" . Utils::roundSize($file["size"]) . "\""; $atts[] = "bytesize=\"" . $file["size"] . "\""; $atts[] = "filename=\"" . str_replace("&", "&", $dir . "/" . $fileName) . "\""; $atts[] = "icon=\"" . ($file["isDir"] == 1 ? "folder.png" : SystemTextEncoding::toUTF8($icon)) . "\""; $attributes = join(" ", $atts); } else { if ($file["isDir"] == 1) { $link = SERVER_ACCESS . "?dir=" . $dir . "/" . $fileName; $link = urlencode($link); $folderBaseName = str_replace("&", "&", $fileName); $folderFullName = "{$dir}/" . $folderBaseName; $parentFolderName = $dir; if (!$completeMode) { $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png"; $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png"; if (preg_match("/\\.zip\$/", $file["name"])) { $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/crystal/actions/16/accessories-archiver.png"; } $attributes = "icon=\"{$icon}\" openicon=\"{$openicon}\" filename=\"" . $folderFullName . "\" src=\"{$link}\""; } } } } if (strlen($attributes) > 0) { print "<tree text=\"" . str_replace("&", "&", SystemTextEncoding::toUTF8($this->SSHOperation->unescapeFileName($file["name"]))) . "\" {$attributes}>"; print "</tree>"; } } AJXP_XMLWriter::close(); exit(1); break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } if (isset($reload_current_node) && $reload_current_node == "true") { $xmlBuffer .= AJXP_XMLWriter::reloadCurrentNode(false); } if (isset($reload_dest_node) && $reload_dest_node != "") { $xmlBuffer .= AJXP_XMLWriter::reloadNode($reload_dest_node, false); } if (isset($reload_file_list)) { $xmlBuffer .= AJXP_XMLWriter::reloadFileList($reload_file_list, false); } return $xmlBuffer; }
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"]; $selection = new UserSelection($repository, $httpVars); if ($selection->isEmpty()) { return; } $file = $destStreamURL . $selection->getUniqueFile(); $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; } }
public function preProcess($action, $httpVars, $fileVars) { if (!is_array($this->pluginConf)) { throw new Exception("Cannot find configuration for plugin notify.phpmail-lite! Make sur that you have filled the options in the GUI, or that the .inc file was dropped inside the /conf/ folder!"); } if ($action == "upload" && !isset($httpVars["dir"])) { return; } require "lib/class.phpmailer-lite.php"; // Parse options if (is_string($this->pluginConf["FROM"])) { $this->pluginConf["FROM"] = $this->parseStringOption($this->pluginConf["FROM"]); } if (is_string($this->pluginConf["TO"]) && $this->pluginConf["TO"] != "") { $froms = explode(",", $this->pluginConf["TO"]); $this->pluginConf["TO"] = array_map(array($this, "parseStringOption"), $froms); } $recipients = $this->pluginConf["TO"]; if ($this->pluginConf["SHARE"]) { if (isset($httpVars["PLUGINS_DATA"])) { $pData = $httpVars["PLUGINS_DATA"]; } else { $repo = ConfService::getRepository(); $pData = $repo->getOption("PLUGINS_DATA"); } if ($pData != null && isset($pData["SHARE_NOTIFICATION_ACTIVE"]) && isset($pData["SHARE_NOTIFICATION_EMAIL"]) && $pData["SHARE_NOTIFICATION_ACTIVE"] == "on") { $emails = array_map(array($this, "parseStringOption"), explode(",", $pData["SHARE_NOTIFICATION_EMAIL"])); if (is_array($recipients)) { $recipients = array_merge($recipients, $emails); } else { $recipients = $emails; } } } if ($recipients == "" || !count($recipients)) { return; } // NOW IF THERE ARE RECIPIENTS FOR ANY REASON, GO $mail = new PHPMailerLite(true); $mail->Mailer = $this->pluginConf["MAILER"]; $mail->SetFrom($this->pluginConf["FROM"]["address"], $this->pluginConf["FROM"]["name"]); foreach ($recipients as $address) { $mail->AddAddress($address["address"], $address["name"]); } $mail->WordWrap = 50; // set word wrap to 50 characters $mail->IsHTML(true); // set email format to HTML $userSelection = new UserSelection(); $userSelection->initFromHttpVars($httpVars); if ($action == "upload" && !isset($httpVars["simple_uploader"]) && !isset($httpVars["xhr_uploader"])) { // FLEX UPLOADER, BASE64 DECODE! if (isset($fileVars["userfile_0"])) { $file = $fileVars["userfile_0"]["name"]; } else { if (isset($httpVars["Filename"])) { $file = $httpVars["Filename"]; } } $folder = base64_decode($httpVars["dir"]); } else { $folder = $httpVars["dir"]; $file = ""; if (!$userSelection->isEmpty()) { $file = implode(",", array_map("basename", $userSelection->getFiles())); if ($folder == null) { $folder = dirname($userSelection->getUniqueFile()); } } if ($action == "upload" && isset($fileVars["userfile_0"])) { $file = $fileVars["userfile_0"]["name"]; } } $subject = array("%user", "AJXP_USER", "AJXP_FILE", "AJXP_FOLDER", "AJXP_ACTION", "AJXP_REPOSITORY"); $replace = array(AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getId(), $file, $folder, $action, ConfService::getRepository()->getDisplay()); $body = str_replace($subject, $replace, $this->pluginConf["BODY"]); $mail->Subject = str_replace($subject, $replace, $this->pluginConf["SUBJECT"]); $mail->Body = nl2br($body); $mail->AltBody = strip_tags($mail->Body); if (!$mail->Send()) { $message = "Message could not be sent. <p>"; $message .= "Mailer Error: " . $mail->ErrorInfo; throw new Exception($message); } }
public function switchAction($action, $httpVars, $fileVars) { $mess = ConfService::getMessages(); $timestamp_url = $this->getFilteredOption("TIMESTAMP_URL"); $timestamp_login = $this->getFilteredOption("USER"); $timestamp_password = $this->getFilteredOption("PASS"); //Check if the configuration has been initiated if (empty($timestamp_url) || empty($timestamp_login) || !empty($timestamp_password)) { throw new AJXP_Exception($mess["timestamp.4"]); $this->logError("Config", "TimeStamp : configuration is needed"); return false; } //Check if after being initiated, conf. fields have some values if (strlen($timestamp_url) < 2 || strlen($timestamp_login) < 2 || strlen($timestamp_password) < 2) { throw new AJXP_Exception($mess["timestamp.4"]); $this->logError("Config", "TimeStamp : configuration is incorrect"); return false; } //Get active repository $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $selection = new UserSelection($repository, $httpVars); $destStreamURL = $selection->currentBaseUrl(); $fileName = $selection->getUniqueFile(); $fileUrl = $destStreamURL . $fileName; $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true); //Hash the file, to send it to Universign $hashedDataToTimestamp = hash_file('sha256', $file); //Check that a tokken is not going to be timestamped ! if (substr("{$file}", -4) != '.ers') { if (file_exists($file . '.ers')) { throw new AJXP_Exception($mess["timestamp.1"]); return false; } else { //Prepare the query that will be sent to Universign $dataToSend = array('hashAlgo' => 'SHA256', 'withCert' => 'true', 'hashValue' => $hashedDataToTimestamp); $dataQuery = http_build_query($dataToSend); //Check if allow_url_fopen is allowed on the server. If not, it will use cUrl if (ini_get('allow_url_fopen')) { $context_options = array('http' => array('method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($dataQuery) . "\r\n" . "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password) . "\r\n", 'content' => $dataQuery)); //Get the result from Universign $context = stream_context_create($context_options); $fp = fopen($timestamp_url, 'r', false, $context); $tsp = stream_get_contents($fp); } else { $timestamp_header = array("Content-type: application/x-www-form-urlencoded", "Content-Length: " . strlen($dataQuery), "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password)); $timeout = 5; $ch = curl_init($timestamp_url); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataQuery); curl_setopt($ch, CURLOPT_HTTPHEADER, $timestamp_header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Get the result from Universign $tsp = curl_exec($ch); curl_close($ch); } //Save the result to a file file_put_contents($file . '.ers', $tsp); //Send the succesful message $this->logInfo("TimeStamp", array("files" => $file, "destination" => $file . '.ers')); AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::sendMessage($mess["timestamp.3"] . $fileName, null); AJXP_XMLWriter::close(); } } else { throw new AJXP_Exception($mess["timestamp.2"]); return false; } }
public function extractExif($actionName, $httpVars, $fileVars) { $userSelection = new UserSelection(); $userSelection->initFromHttpVars($httpVars); $repo = $this->accessDriver->repository; $repo->detectStreamWrapper(); $wrapperData = $repo->streamData; $urlBase = $wrapperData["protocol"] . "://" . $repo->getId(); $selection = new UserSelection($repo, $httpVars); $decoded = $selection->getUniqueFile(); $realFile = call_user_func(array($wrapperData["classname"], "getRealFSReference"), $urlBase . $decoded); AJXP_Utils::safeIniSet('exif.encode_unicode', 'UTF-8'); $exifData = @exif_read_data($realFile, 0, TRUE); if ($exifData === false || !is_array($exifData)) { return; } if ($exifData !== false && isset($exifData["GPS"])) { $exifData["COMPUTED_GPS"] = $this->convertGPSData($exifData); } $iptc = $this->extractIPTC($realFile); if (count($iptc)) { $exifData["IPTC"] = $iptc; } $excludeTags = array(); // array("componentsconfiguration", "filesource", "scenetype", "makernote", "datadump"); AJXP_XMLWriter::header("metadata", array("file" => $decoded, "type" => "EXIF")); foreach ($exifData as $section => $data) { print "<exifSection name='{$section}'>"; foreach ($data as $key => $value) { if (is_array($value)) { $value = implode(",", $value); } if (in_array(strtolower($key), $excludeTags)) { continue; } if (strpos($key, "UndefinedTag:") === 0) { continue; } $value = preg_replace('/[^[:print:]]/', '', $value); print "<exifTag name=\"{$key}\">" . SystemTextEncoding::toUTF8($value) . "</exifTag>"; } print "</exifSection>"; } AJXP_XMLWriter::close("metadata"); }
public function switchActions($actionName, $httpVars, $fileVars) { //$urlBase = $this->accessDriver $repository = $this->accessDriver->repository; if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $this->streamData = $streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); $selection = new UserSelection($repository, $httpVars); switch ($actionName) { case "filehasher_signature": $file = $selection->getUniqueFile(); if (!file_exists($destStreamURL . $file)) { break; } $cacheItem = AJXP_Cache::getItem("signatures", $destStreamURL . $file, array($this, "generateSignature")); $data = $cacheItem->getData(); header("Content-Type:application/octet-stream"); header("Content-Length", strlen($data)); echo $data; break; case "filehasher_delta": case "filehasher_patch": // HANDLE UPLOAD DATA $this->logDebug("Received signature file, should compute delta now"); if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) { throw new Exception("These action should find uploaded data"); } $uploadedData = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-sig"); move_uploaded_file($fileVars["userfile_0"]["tmp_name"], $uploadedData); $fileUrl = $destStreamURL . $selection->getUniqueFile(); $file = call_user_func(array($this->streamData["classname"], "getRealFSReference"), $fileUrl, true); if ($actionName == "filehasher_delta") { $signatureFile = $uploadedData; $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta"); $this->logDebug("Received signature file, should compute delta now"); rsync_generate_delta($signatureFile, $file, $deltaFile); $this->logDebug("Computed delta file, size is " . filesize($deltaFile)); header("Content-Type:application/octet-stream"); header("Content-Length:" . filesize($deltaFile)); readfile($deltaFile); unlink($signatureFile); unlink($deltaFile); } else { $patched = $file . ".rdiff_patched"; $deltaFile = $uploadedData; rsync_patch_file($file, $deltaFile, $patched); rename($patched, $file); unlink($deltaFile); $node = $selection->getUniqueNode($this->accessDriver); AJXP_Controller::applyHook("node.change", array($node, $node, false)); header("Content-Type:text/plain"); echo md5_file($file); } break; case "stat_hash": $selection = new UserSelection(); $selection->initFromArray($httpVars); clearstatcache(); header("Content-type:application/json"); if ($selection->isUnique()) { $node = $selection->getUniqueNode($this->accessDriver); $stat = @stat($node->getUrl()); if (!$stat) { print '{}'; } else { if ($node->isLeaf()) { if (isset($_SERVER["HTTP_RANGE"])) { $fullSize = floatval($stat['size']); $ranges = explode('=', $_SERVER["HTTP_RANGE"]); $offsets = explode('-', $ranges[1]); $offset = floatval($offsets[0]); $length = floatval($offsets[1]) - $offset; if (!$length) { $length = $fullSize - $offset; } if ($length + $offset > $fullSize || $length < 0) { $length = $fullSize - $offset; } $hash = $this->getPartialHash($node, $offset, $length); } else { $hash = $this->getFileHash($selection->getUniqueNode($this->accessDriver)); } } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; print json_encode($stat); } } else { $files = $selection->getFiles(); print '{'; foreach ($files as $index => $path) { $node = new AJXP_Node($destStreamURL . $path); $stat = @stat($destStreamURL . $path); if (!$stat) { $stat = '{}'; } else { if (!is_dir($node->getUrl())) { $hash = $this->getFileHash($node); } else { $hash = 'directory'; } $stat[13] = $stat["hash"] = $hash; $stat = json_encode($stat); } print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : ""); } print '}'; } break; break; } }
/** * Transform delete/restore actions into move actino * @static * @param string $action * @param UserSelection $selection * @param string $currentLocation * @param array $httpVars * @return array */ public static function filterActions($action, $selection, $currentLocation, $httpVars = array()) { if (!self::recycleEnabled()) { return array(); } $newArgs = array(); // FILTER ACTION FOR DELETE if ($action == "delete" && !self::currentLocationIsRecycle($currentLocation) && !isset($httpVars["force_deletion"])) { $newArgs["action"] = "move"; $newArgs["dest"] = self::$rbmRelativeRecycle; } // FILTER ACTION FOR RESTORE if ($action == "restore" && self::currentLocationIsRecycle($currentLocation)) { $originalRep = self::getFileOrigin($selection->getUniqueFile()); if ($originalRep != "") { $newArgs["action"] = "move"; $newArgs["dest"] = $originalRep; // CHECK UTF8 HANDLING HERE } } return $newArgs; }
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(); $selection = new UserSelection($repository, $httpVars); if ($action == "post_to_server") { // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); } else { $file = $selection->getUniqueFile(); } $target = base64_decode($httpVars["parent_url"]) . "/plugins/editor.pixlr"; $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file); $tmp = SystemTextEncoding::fromUTF8($tmp); $fData = array("tmp_name" => $tmp, "name" => urlencode(basename($file)), "type" => "image/jpg"); //var_dump($fData); $node = new AJXP_Node($destStreamURL . $file); $this->logInfo('Preview', 'Sending content of ' . $file . ' to Pixlr server.'); AJXP_Controller::applyHook("node.read", array($node)); $httpClient = new HttpClient("apps.pixlr.com"); //$httpClient->setDebug(true); $postData = array(); $httpClient->setHandleRedirects(false); $saveTarget = $target . "/fake_save_pixlr.php"; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $saveTarget = $target . "/fake_save_pixlr_" . md5($httpVars["secure_token"]) . ".php"; } $params = array("referrer" => "Pydio", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $saveTarget, "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($file)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source"); $httpClient->postFile("/editor/", $params, "image", $fData); $loc = $httpClient->getHeader("location"); header("Location:{$loc}"); } else { if ($action == "retrieve_pixlr_image") { $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]); $node = new AJXP_Node($destStreamURL . $file); $node->loadNodeInfo(); $this->logInfo('Edit', 'Retrieving content of ' . $file . ' from Pixlr server.'); AJXP_Controller::applyHook("node.before_change", array(&$node)); $url = $httpVars["new_url"]; $urlParts = parse_url($url); $query = $urlParts["query"]; if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) { $scriptName = basename($urlParts["path"]); $token = str_replace(array("fake_save_pixlr_", ".php"), "", $scriptName); if ($token != md5($httpVars["secure_token"])) { throw new AJXP_Exception("Invalid Token, this could mean some security problem!"); } } $params = array(); parse_str($query, $params); $image = $params['image']; $headers = get_headers($image, 1); $content_type = explode("/", $headers['Content-Type']); if ($content_type[0] != "image") { throw new AJXP_Exception("Invalid File Type"); } $content_length = intval($headers["Content-Length"]); if ($content_length != 0) { AJXP_Controller::applyHook("node.before_change", array(&$node, $content_length)); } $orig = fopen($image, "r"); $target = fopen($destStreamURL . $file, "w"); if (is_resource($orig) && is_resource($target)) { while (!feof($orig)) { fwrite($target, fread($orig, 4096)); } fclose($orig); fclose($target); } clearstatcache(true, $node->getUrl()); $node->loadNodeInfo(true); AJXP_Controller::applyHook("node.change", array(&$node, &$node)); //header("Content-Type:text/plain"); //print($mess[115]); } } return; }
public function editMeta($actionName, $httpVars, $fileVars) { if (!isset($this->actions[$actionName])) { return; } if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection(); $selection->initFromHttpVars(); $currentFile = $selection->getUniqueFile(); $wrapperData = $this->accessDriver->detectStreamWrapper(false); $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId(); $newValues = array(); $def = $this->getMetaDefinition(); foreach ($def as $key => $label) { if (isset($httpVars[$key])) { $newValues[$key] = AJXP_Utils::xmlEntities(AJXP_Utils::decodeSecureMagic($httpVars[$key])); } else { if (!isset($original)) { $original = array(); $this->loadMetaFileData($urlBase . $currentFile); $base = basename($currentFile); if (is_array(self::$metaCache) && array_key_exists($base, self::$metaCache)) { $original = self::$metaCache[$base]; } } if (isset($original) && isset($original[$key])) { $newValues[$key] = $original[$key]; } } } $this->addMeta($urlBase . $currentFile, $newValues); AJXP_XMLWriter::header(); AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true); AJXP_XMLWriter::close(); }
public function editMeta($actionName, $httpVars, $fileVars) { if (!isset($this->actions[$actionName])) { return; } if (is_a($this->accessDriver, "demoAccessDriver")) { throw new Exception("Write actions are disabled in demo mode!"); } $repo = $this->accessDriver->repository; $user = AuthService::getLoggedUser(); if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) { throw new Exception("You have no right on this action."); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); $currentFile = $selection->getUniqueFile(); $nodes = $selection->buildNodes($this->accessDriver); $nodesDiffs = array(); $def = $this->getMetaDefinition(); foreach ($nodes as $ajxpNode) { $newValues = array(); //$ajxpNode->setDriver($this->accessDriver); AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode)); foreach ($def as $key => $data) { if (isset($httpVars[$key])) { $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]); } else { if (!isset($original)) { $original = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL); } if (isset($original) && isset($original[$key])) { $newValues[$key] = $original[$key]; } } } $ajxpNode->setMetadata("users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL); AJXP_Controller::applyHook("node.meta_change", array($ajxpNode)); $nodesDiffs[$ajxpNode->getPath()] = $ajxpNode; } /* $urlBase = $this->accessDriver->getResourceUrl($currentFile); $ajxpNode = new AJXP_Node($urlBase); $newValues = array(); $def = $this->getMetaDefinition(); $ajxpNode->setDriver($this->accessDriver); AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode)); foreach ($def as $key => $data) { if (isSet($httpVars[$key])) { $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]); } else { if (!isset($original)) { $original = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL); } if (isSet($original) && isset($original[$key])) { $newValues[$key] = $original[$key]; } } } $ajxpNode->setMetadata("users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL); AJXP_Controller::applyHook("node.meta_change", array($ajxpNode)); */ AJXP_XMLWriter::header(); AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => $nodesDiffs), true); AJXP_XMLWriter::close(); }
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") { $selection = new UserSelection($repository, $httpVars); // Backward compat $file = $selection->getUniqueFile(); if (!file_exists($destStreamURL . $file) && strpos($httpVars["file"], "base64encoded:") === false) { // May be a backward compatibility problem, try to base64decode the filepath $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); if (!file_exists($destStreamURL . $file)) { throw new Exception("Cannot find file!"); } } $cType = "audio/" . array_pop(explode(".", $file)); $localName = basename($file); $node = new AJXP_Node($destStreamURL . $file); if (method_exists($node->getDriver(), "filesystemFileSize")) { $size = $node->getDriver()->filesystemFileSize($node->getUrl()); } else { $size = filesize($node->getUrl()); } header("Content-Type: " . $cType . "; name=\"" . $localName . "\""); header("Content-Length: " . $size); $stream = fopen("php://output", "a"); call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream); fflush($stream); fclose($stream); AJXP_Controller::applyHook("node.read", array($node)); $this->logInfo('Preview', 'Read content of ' . $node->getUrl()); //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 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(); $selection = new UserSelection($repository, $httpVars); if ($action == "read_video_data") { $this->logDebug("Reading video"); $file = $selection->getUniqueFile(); $node = new AJXP_Node($destStreamURL . $file); session_write_close(); $filesize = filesize($destStreamURL . $file); $filename = $destStreamURL . $file; //$fp = fopen($destStreamURL.$file, "r"); if (preg_match("/\\.ogv\$/", $file)) { header("Content-Type: video/ogg; name=\"" . basename($file) . "\""); } else { if (preg_match("/\\.mp4\$/", $file)) { header("Content-Type: video/mp4; name=\"" . basename($file) . "\""); } else { if (preg_match("/\\.m4v\$/", $file)) { header("Content-Type: video/x-m4v; name=\"" . basename($file) . "\""); } else { if (preg_match("/\\.webm\$/", $file)) { header("Content-Type: video/webm; name=\"" . basename($file) . "\""); } } } } if (isset($_SERVER['HTTP_RANGE']) && $filesize != 0) { $this->logDebug("Http range", array($_SERVER['HTTP_RANGE'])); // multiple ranges, which can become pretty complex, so ignore it for now $ranges = explode('=', $_SERVER['HTTP_RANGE']); $offsets = explode('-', $ranges[1]); $offset = floatval($offsets[0]); $length = floatval($offsets[1]) - $offset; if (!$length) { $length = $filesize - $offset; } if ($length + $offset > $filesize || $length < 0) { $length = $filesize - $offset; } header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length - 1) . '/' . $filesize); header('Accept-Ranges:bytes'); header("Content-Length: " . $length); $file = fopen($filename, 'rb'); fseek($file, 0); $relOffset = $offset; while ($relOffset > 2000000000.0) { // seek to the requested offset, this is 0 if it's not a partial content request fseek($file, 2000000000, SEEK_CUR); $relOffset -= 2000000000; // This works because we never overcome the PHP 32 bit limit } fseek($file, $relOffset, SEEK_CUR); while (ob_get_level()) { ob_end_flush(); } $readSize = 0.0; while (!feof($file) && $readSize < $length && connection_status() == 0) { echo fread($file, 2048); $readSize += 2048.0; flush(); } fclose($file); } else { $fp = fopen($filename, "rb"); header("Content-Length: " . $filesize); header("Content-Range: bytes 0-" . ($filesize - 1) . "/" . $filesize . ";"); header('Cache-Control: public'); $class = $streamData["classname"]; $stream = fopen("php://output", "a"); call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream); fflush($stream); fclose($stream); } AJXP_Controller::applyHook("node.read", array($node)); } else { if ($action == "get_sess_id") { HTMLWriter::charsetHeader("text/plain"); print session_id(); } } }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $convert = $this->getFilteredOption("IMAGE_MAGICK_CONVERT"); if (empty($convert)) { return false; } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); $flyThreshold = 1024 * 1024 * intval($this->getFilteredOption("ONTHEFLY_THRESHOLD", $repository->getId())); $selection = new UserSelection($repository); $selection->initFromHttpVars($httpVars); if ($action == "imagick_data_proxy") { $this->extractAll = false; if (isset($httpVars["all"])) { $this->extractAll = true; } $file = $selection->getUniqueFile(); if (($size = filesize($destStreamURL . $file)) === false) { return false; } else { if ($size > $flyThreshold) { $this->useOnTheFly = true; } else { $this->useOnTheFly = false; } } if ($this->extractAll) { $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); } $cache = AJXP_Cache::getItem("imagick_" . ($this->extractAll ? "full" : "thumb"), $destStreamURL . $file, array($this, "generateJpegsCallback")); $cacheData = $cache->getData(); if (!$this->useOnTheFly && $this->extractAll) { // extract all on first view $ext = pathinfo($file, PATHINFO_EXTENSION); $prefix = str_replace(".{$ext}", "", $cache->getId()); $files = $this->listExtractedJpg($destStreamURL . $file, $prefix); header("Content-Type: application/json"); print json_encode($files); return false; } else { if ($this->extractAll) { // on the fly extract mode $ext = pathinfo($file, PATHINFO_EXTENSION); $prefix = str_replace(".{$ext}", "", $cache->getId()); $files = $this->listPreviewFiles($destStreamURL . $file, $prefix); header("Content-Type: application/json"); print json_encode($files); return false; } else { header("Content-Type: image/jpeg; name=\"" . basename($file) . "\""); header("Content-Length: " . strlen($cacheData)); header('Cache-Control: public'); header("Pragma:"); header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT"); print $cacheData; return false; } } } else { if ($action == "get_extracted_page" && isset($httpVars["file"])) { $file = (defined('AJXP_SHARED_CACHE_DIR') ? AJXP_SHARED_CACHE_DIR : AJXP_CACHE_DIR) . "/imagick_full/" . AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (!is_file($file)) { $srcfile = AJXP_Utils::decodeSecureMagic($httpVars["src_file"]); if ($repository->hasContentFilter()) { $contentFilter = $repository->getContentFilter(); $srcfile = $contentFilter->filterExternalPath($srcfile); } $size = filesize($destStreamURL . "/" . $srcfile); if ($size > $flyThreshold) { $this->useOnTheFly = true; } else { $this->useOnTheFly = false; } if ($this->useOnTheFly) { $this->onTheFly = true; } $this->generateJpegsCallback($destStreamURL . $srcfile, $file); } if (!is_file($file)) { return false; } header("Content-Type: image/jpeg; name=\"" . basename($file) . "\""); header("Content-Length: " . filesize($file)); header('Cache-Control: public'); readfile($file); exit(1); } else { if ($action == "delete_imagick_data" && !$selection->isEmpty()) { /* $files = $this->listExtractedJpg(AJXP_CACHE_DIR."/".$httpVars["file"]); foreach ($files as $file) { if(is_file(AJXP_CACHE_DIR."/".$file["file"])) unlink(AJXP_CACHE_DIR."/".$file["file"]); } */ } } } }
/** * @param Array $httpVars * @param Repository $repository * @param AbstractAccessDriver $accessDriver * @param null $uniqueUser * @throws Exception * @return int|Repository */ public function createSharedRepository($httpVars, $repository, $accessDriver, $uniqueUser = null) { // ERRORS // 100 : missing args // 101 : repository label already exists // 102 : user already exists // 103 : current user is not allowed to share // SUCCESS // 200 if (!isset($httpVars["repo_label"]) || $httpVars["repo_label"] == "") { return 100; } /* // FILE IS ALWAYS THE PARENT FOLDER SO WE NOW CHECK FOLDER_SHARING AT A HIGHER LEVEL $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); $foldersharing = $this->getFilteredOption("ENABLE_FOLDER_SHARING", $this->repository->getId()); $foldersharingDisabled = isset($foldersharing) && ($foldersharing === false || (is_string($foldersharing) && $foldersharing == "disable")); if (is_dir($this->urlBase.$file) && $foldersharingDisabled) { return 103; } */ $loggedUser = AuthService::getLoggedUser(); $actRights = $loggedUser->mergedRole->listActionsStatesFor($repository); if (isset($actRights["share"]) && $actRights["share"] === false) { return 103; } $users = array(); $uRights = array(); $uPasses = array(); $groups = array(); $uWatches = array(); $index = 0; $prefix = $this->getFilteredOption("SHARED_USERS_TMP_PREFIX", $this->repository->getId()); while (isset($httpVars["user_" . $index])) { $eType = $httpVars["entry_type_" . $index]; $uWatch = false; $rightString = ($httpVars["right_read_" . $index] == "true" ? "r" : "") . ($httpVars["right_write_" . $index] == "true" ? "w" : ""); if ($this->watcher !== false) { $uWatch = $httpVars["right_watch_" . $index] == "true" ? true : false; } if (empty($rightString)) { $index++; continue; } if ($eType == "user") { $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index], AJXP_SANITIZE_EMAILCHARS); if (!AuthService::userExists($u) && !isset($httpVars["user_pass_" . $index])) { $index++; continue; } else { if (AuthService::userExists($u, "w") && isset($httpVars["user_pass_" . $index])) { throw new Exception("User {$u} already exists, please choose another name."); } } if (!AuthService::userExists($u, "r") && !empty($prefix) && strpos($u, $prefix) !== 0) { $u = $prefix . $u; } $users[] = $u; } else { $u = AJXP_Utils::decodeSecureMagic($httpVars["user_" . $index]); if (strpos($u, "/AJXP_TEAM/") === 0) { $confDriver = ConfService::getConfStorageImpl(); if (method_exists($confDriver, "teamIdToUsers")) { $teamUsers = $confDriver->teamIdToUsers(str_replace("/AJXP_TEAM/", "", $u)); foreach ($teamUsers as $userId) { $users[] = $userId; $uRights[$userId] = $rightString; if ($this->watcher !== false) { $uWatches[$userId] = $uWatch; } } } $index++; continue; } else { $groups[] = $u; } } $uRights[$u] = $rightString; $uPasses[$u] = isset($httpVars["user_pass_" . $index]) ? $httpVars["user_pass_" . $index] : ""; if ($this->watcher !== false) { $uWatches[$u] = $uWatch; } $index++; } $label = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_label"]), AJXP_SANITIZE_HTML); $description = AJXP_Utils::sanitize(AJXP_Utils::securePath($httpVars["repo_description"]), AJXP_SANITIZE_HTML); if (isset($httpVars["repository_id"])) { $editingRepo = ConfService::getRepositoryById($httpVars["repository_id"]); } // CHECK USER & REPO DOES NOT ALREADY EXISTS if ($this->getFilteredOption("AVOID_SHARED_FOLDER_SAME_LABEL", $this->repository->getId()) == true) { $count = 0; $similarLabelRepos = ConfService::listRepositoriesWithCriteria(array("display" => $label), $count); if ($count && !isset($editingRepo)) { return 101; } if ($count && isset($editingRepo)) { foreach ($similarLabelRepos as $slr) { if ($slr->getUniqueId() != $editingRepo->getUniqueId()) { return 101; } } } /* $repos = ConfService::getRepositoriesList(); foreach ($repos as $obj) { if ($obj->getDisplay() == $label && (!isSet($editingRepo) || $editingRepo != $obj)) { } } */ } $confDriver = ConfService::getConfStorageImpl(); foreach ($users as $userName) { if (AuthService::userExists($userName)) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); if (ConfService::getCoreConf("ALLOW_CROSSUSERS_SHARING", "conf") != true && (!$userObject->hasParent() || $userObject->getParent() != $loggedUser->id)) { return 102; } } else { if ($httpVars["create_guest_user"] != "true" && !ConfService::getCoreConf("USER_CREATE_USERS", "conf") || AuthService::isReservedUserId($userName)) { return 102; } if (!isset($httpVars["shared_pass"]) || $httpVars["shared_pass"] == "") { return 100; } } } // CREATE SHARED OPTIONS $options = $accessDriver->makeSharedRepositoryOptions($httpVars, $repository); $customData = array(); foreach ($httpVars as $key => $value) { if (substr($key, 0, strlen("PLUGINS_DATA_")) == "PLUGINS_DATA_") { $customData[substr($key, strlen("PLUGINS_DATA_"))] = $value; } } if (count($customData)) { $options["PLUGINS_DATA"] = $customData; } if (isset($editingRepo)) { $this->getShareStore()->testUserCanEditShare($editingRepo->getOwner()); $newRepo = $editingRepo; $replace = false; if ($editingRepo->getDisplay() != $label) { $newRepo->setDisplay($label); $replace = true; } if ($editingRepo->getDescription() != $description) { $newRepo->setDescription($description); $replace = true; } if ($replace) { ConfService::replaceRepository($httpVars["repository_id"], $newRepo); } } else { if ($repository->getOption("META_SOURCES")) { $options["META_SOURCES"] = $repository->getOption("META_SOURCES"); foreach ($options["META_SOURCES"] as $index => &$data) { if (isset($data["USE_SESSION_CREDENTIALS"]) && $data["USE_SESSION_CREDENTIALS"] === true) { $options["META_SOURCES"][$index]["ENCODED_CREDENTIALS"] = AJXP_Safe::getEncodedCredentialString(); } if ($index == "meta.syncable" && (!isset($data["REPO_SYNCABLE"]) || $data["REPO_SYNCABLE"] === true)) { $data["REQUIRES_INDEXATION"] = true; } } } $newRepo = $repository->createSharedChild($label, $options, $repository->id, $loggedUser->id, null); $gPath = $loggedUser->getGroupPath(); if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) { $newRepo->setGroupPath($gPath); } $newRepo->setDescription($description); $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]); if (isset($httpVars["filter_nodes"])) { $newRepo->setContentFilter(new ContentFilter($httpVars["filter_nodes"])); } ConfService::addRepository($newRepo); if (!isset($httpVars["minisite"])) { $this->getShareStore()->storeShare($repository->getId(), array("REPOSITORY" => $newRepo->getUniqueId(), "OWNER_ID" => $loggedUser->getId()), "repository"); } } $sel = new UserSelection($this->repository, $httpVars); $file = $sel->getUniqueFile(); $newRepoUniqueId = $newRepo->getUniqueId(); if (isset($editingRepo)) { $currentRights = $this->computeSharedRepositoryAccessRights($httpVars["repository_id"], false, $this->urlBase . $file); $originalUsers = array_keys($currentRights["USERS"]); $removeUsers = array_diff($originalUsers, $users); if (count($removeUsers)) { foreach ($removeUsers as $user) { if (AuthService::userExists($user)) { $userObject = $confDriver->createUserObject($user); $userObject->personalRole->setAcl($newRepoUniqueId, ""); $userObject->save("superuser"); } if ($this->watcher !== false) { $this->watcher->removeWatchFromFolder(new AJXP_Node($this->urlBase . $file), $user, true); } } } $originalGroups = array_keys($currentRights["GROUPS"]); $removeGroups = array_diff($originalGroups, $groups); if (count($removeGroups)) { foreach ($removeGroups as $groupId) { $role = AuthService::getRole($groupId); if ($role !== false) { $role->setAcl($newRepoUniqueId, ""); AuthService::updateRole($role); } } } } foreach ($users as $userName) { if (AuthService::userExists($userName, "r")) { // check that it's a child user $userObject = $confDriver->createUserObject($userName); } else { if (ConfService::getAuthDriverImpl()->getOptionAsBool("TRANSMIT_CLEAR_PASS")) { $pass = $uPasses[$userName]; } else { $pass = md5($uPasses[$userName]); } if (!isset($httpVars["minisite"])) { // This is an explicit user creation - check possible limits AJXP_Controller::applyHook("user.before_create", array($userName, null, false, false)); $limit = $loggedUser->personalRole->filterParameterValue("core.conf", "USER_SHARED_USERS_LIMIT", AJXP_REPO_SCOPE_ALL, ""); if (!empty($limit) && intval($limit) > 0) { $count = count(ConfService::getConfStorageImpl()->getUserChildren($loggedUser->getId())); if ($count >= $limit) { $mess = ConfService::getMessages(); throw new Exception($mess['483']); } } } AuthService::createUser($userName, $pass, false, isset($httpVars["minisite"])); $userObject = $confDriver->createUserObject($userName); $userObject->personalRole->clearAcls(); $userObject->setParent($loggedUser->id); $userObject->setGroupPath($loggedUser->getGroupPath()); $userObject->setProfile("shared"); if (isset($httpVars["minisite"])) { $mess = ConfService::getMessages(); $userObject->setHidden(true); $userObject->personalRole->setParameterValue("core.conf", "USER_DISPLAY_NAME", "[" . $mess["share_center.109"] . "] " . AJXP_Utils::sanitize($newRepo->getDisplay(), AJXP_SANITIZE_EMAILCHARS)); } AJXP_Controller::applyHook("user.after_create", array($userObject)); } // CREATE USER WITH NEW REPO RIGHTS $userObject->personalRole->setAcl($newRepoUniqueId, $uRights[$userName]); // FORK MASK IF THERE IS ANY if ($file != "/" && $loggedUser->mergedRole->hasMask($repository->getId())) { $parentTree = $loggedUser->mergedRole->getMask($repository->getId())->getTree(); // Try to find a branch on the current selection $parts = explode("/", trim($file, "/")); while (($next = array_shift($parts)) !== null) { if (isset($parentTree[$next])) { $parentTree = $parentTree[$next]; } else { $parentTree = null; break; } } if ($parentTree != null) { $newMask = new AJXP_PermissionMask(); $newMask->updateTree($parentTree); } if (isset($newMask)) { $userObject->personalRole->setMask($newRepoUniqueId, $newMask); } } if (isset($httpVars["minisite"])) { if (isset($editingRepo)) { try { AuthService::deleteRole("AJXP_SHARED-" . $newRepoUniqueId); } catch (Exception $e) { } } $newRole = new AJXP_Role("AJXP_SHARED-" . $newRepoUniqueId); $r = AuthService::getRole("MINISITE"); if (is_a($r, "AJXP_Role")) { if ($httpVars["disable_download"]) { $f = AuthService::getRole("MINISITE_NODOWNLOAD"); if (is_a($f, "AJXP_Role")) { $r = $f->override($r); } } $allData = $r->getDataArray(); $newData = $newRole->getDataArray(); if (isset($allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED])) { $newData["ACTIONS"][$newRepoUniqueId] = $allData["ACTIONS"][AJXP_REPO_SCOPE_SHARED]; } if (isset($allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED])) { $newData["PARAMETERS"][$newRepoUniqueId] = $allData["PARAMETERS"][AJXP_REPO_SCOPE_SHARED]; } $newRole->bunchUpdate($newData); AuthService::updateRole($newRole); $userObject->addRole($newRole); } } $userObject->save("superuser"); if ($this->watcher !== false) { // Register a watch on the current folder for shared user if ($uWatches[$userName]) { $this->watcher->setWatchOnFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), $userName, MetaWatchRegister::$META_WATCH_USERS_CHANGE, array(AuthService::getLoggedUser()->getId())); } else { $this->watcher->removeWatchFromFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), $userName, true); } } } if ($this->watcher !== false) { // Register a watch on the new repository root for current user if ($httpVars["self_watch_folder"] == "true") { $this->watcher->setWatchOnFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), AuthService::getLoggedUser()->getId(), MetaWatchRegister::$META_WATCH_BOTH); } else { $this->watcher->removeWatchFromFolder(new AJXP_Node("pydio://" . $newRepoUniqueId . "/"), AuthService::getLoggedUser()->getId()); } } foreach ($groups as $group) { $r = $uRights[$group]; /*if($group == "AJXP_GRP_/") { $group = "ROOT_ROLE"; }*/ $grRole = AuthService::getRole($group, true); $grRole->setAcl($newRepoUniqueId, $r); AuthService::updateRole($grRole); } if (array_key_exists("minisite", $httpVars) && $httpVars["minisite"] != true) { AJXP_Controller::applyHook(isset($editingRepo) ? "node.share.update" : "node.share.create", array('type' => 'repository', 'repository' => &$repository, 'accessDriver' => &$accessDriver, 'new_repository' => &$newRepo)); } return $newRepo; }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); if ($action == "post_to_zohoserver") { $sheetExt = explode(",", "xls,xlsx,ods,sxc,csv,tsv"); $presExt = explode(",", "ppt,pps,odp,sxi"); $docExt = explode(",", "doc,docx,rtf,odt,sxw"); require_once AJXP_BIN_FOLDER . "/http_class/http_class.php"; $selection = new UserSelection($repository, $httpVars); // Backward compat if (strpos($httpVars["file"], "base64encoded:") !== 0) { $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"])); } else { $file = $selection->getUniqueFile(); } $target = base64_decode($httpVars["parent_url"]); $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file); $tmp = SystemTextEncoding::fromUTF8($tmp); $node = new AJXP_Node($destStreamURL . $file); AJXP_Controller::applyHook("node.read", array($node)); $this->logInfo('Preview', 'Posting content of ' . $file . ' to Zoho server'); $extension = strtolower(pathinfo(urlencode(basename($file)), PATHINFO_EXTENSION)); $httpClient = new http_class(); $httpClient->request_method = "POST"; $secureToken = $httpVars["secure_token"]; $_SESSION["ZOHO_CURRENT_EDITED"] = $destStreamURL . $file; $_SESSION["ZOHO_CURRENT_UUID"] = md5(rand() . "-" . microtime()); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) { $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()); } else { $saveUrl = $target . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/save_zoho.php"; } $b64Sig = $this->signID($_SESSION["ZOHO_CURRENT_UUID"]); $params = array('id' => $_SESSION["ZOHO_CURRENT_UUID"], 'apikey' => $this->getFilteredOption("ZOHO_API_KEY", $repository->getId()), 'output' => 'url', 'lang' => "en", 'filename' => urlencode(basename($file)), 'persistence' => 'false', 'format' => $extension, 'mode' => 'normaledit', 'saveurl' => $saveUrl . "?signature=" . $b64Sig); $service = "exportwriter"; if (in_array($extension, $sheetExt)) { $service = "sheet"; } else { if (in_array($extension, $presExt)) { $service = "show"; } else { if (in_array($extension, $docExt)) { $service = "exportwriter"; } } } $arguments = array(); $httpClient->GetRequestArguments("https://" . $service . ".zoho.com/remotedoc.im", $arguments); $arguments["PostValues"] = $params; $arguments["PostFiles"] = array("content" => array("FileName" => $tmp, "Content-Type" => "automatic/name")); $err = $httpClient->Open($arguments); if (empty($err)) { $err = $httpClient->SendRequest($arguments); if (empty($err)) { $response = ""; while (true) { $body = ""; $error = $httpClient->ReadReplyBody($body, 1000); if ($error != "" || strlen($body) == 0) { break; } $response .= $body; } $result = trim($response); $matchlines = explode("\n", $result); $resultValues = array(); foreach ($matchlines as $line) { list($key, $val) = explode("=", $line, 2); $resultValues[$key] = $val; } if ($resultValues["RESULT"] == "TRUE" && isset($resultValues["URL"])) { header("Location: " . $resultValues["URL"]); } else { echo "Zoho API Error " . $resultValues["ERROR_CODE"] . " : " . $resultValues["WARNING"]; echo "<script>window.parent.setTimeout(function(){parent.hideLightBox();}, 2000);</script>"; } } $httpClient->Close(); } } else { if ($action == "retrieve_from_zohoagent") { $targetFile = $_SESSION["ZOHO_CURRENT_EDITED"]; $id = $_SESSION["ZOHO_CURRENT_UUID"]; $ext = pathinfo($targetFile, PATHINFO_EXTENSION); $node = new AJXP_Node($targetFile); $node->loadNodeInfo(); AJXP_Controller::applyHook("node.before_change", array(&$node)); $b64Sig = $this->signID($id); if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) { $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()) . "?ajxp_action=get_file&name=" . $id . "&ext=" . $ext . "&signature=" . $b64Sig; $data = AJXP_Utils::getRemoteContent($url); if (strlen($data)) { file_put_contents($targetFile, $data); echo "MODIFIED"; } } else { if (is_file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext)) { copy(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext, $targetFile); unlink(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext); echo "MODIFIED"; } } $this->logInfo('Edit', 'Retrieved content of ' . $node->getUrl()); AJXP_Controller::applyHook("node.change", array(null, &$node)); } } }