function switchAction($action, $httpVars, $filesVars)
 {
     $sessionId = "";
     $crtRep = ConfService::getRepository();
     $httpClient = $this->getRemoteConnexion($sessionId);
     //$httpClient->setDebug(true);
     if ($crtRep->getOption("USE_AUTH")) {
         $httpVars["ajxp_sessid"] = $sessionId;
     }
     $method = "get";
     if ($action == "put_content") {
         $method = "post";
     }
     if ($method == "get") {
         if ($action == "download" || $action == "image_proxy" || $action == "mp3_proxy") {
             $httpClient->directForwarding = true;
         }
         $result = $httpClient->get($crtRep->getOption("URI"), $httpVars);
     } else {
         $result = $httpClient->post($crtRep->getOption("URI"), $httpVars);
     }
     // check if session is expired
     if (strpos($httpClient->getHeader("content-type"), "text/xml") !== false && strpos($httpClient->getContent(), "require_auth") != false) {
         $httpClient = $this->getRemoteConnexion($sessionId, true);
         $httpVars["ajxp_sessid"] = $sessionId;
         $method = "get";
         if ($method == "get") {
             if ($action == "download") {
                 $httpClient->directForwarding = true;
             }
             $result = $httpClient->get($crtRep->getOption("URI"), $httpVars);
         } else {
             $result = $httpClient->post($crtRep->getOption("URI"), $httpVars);
         }
     }
     if ($result === false && isset($httpClient->errormsg)) {
         throw new Exception(SystemTextEncoding::toUTF8($httpClient->errormsg));
     }
     switch ($action) {
         case "image_proxy":
         case "download":
         case "mp3_proxy":
             session_write_close();
             exit;
             break;
         case "get_content":
             header("Content-type:text/plain");
             break;
         default:
             header("Content-type: text/xml");
             break;
     }
     print $httpClient->getContent();
     session_write_close();
     exit;
 }
 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 listRepositories()
    {
        print '<columns switchGridMode="filelist"><column messageString="Repository Label" attributeName="ajxp_label" sortType="String"/><column messageString="Access Type" attributeName="accessType" sortType="String"/></columns>';
        $repos = ConfService::getRepositoriesList();
        $repoArray = array();
        foreach ($repos as $repoIndex => $repoObject) {
            if ($repoObject->getAccessType() == "ajxp_conf") {
                continue;
            }
            $name = Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
            $repoArray[$name] = $repoIndex;
        }
        // Sort the list now by name
        ksort($repoArray);
        foreach ($repoArray as $name => $repoIndex) {
            $repoObject =& $repos[$repoIndex];
            print '<tree 				
				text="' . $name . '" 
				is_file="1" 
				repository_id="' . $repoIndex . '" 
				accessType="' . $repoObject->getAccessType() . '" 
				icon="folder_red.png" 
				openicon="folder_red.png" 
				filename="/users/' . $name . '" 
				parentname="/users" 
				src="content.php?dir=%2Fusers%2F' . $name . '" 
				ajxp_mime="repository' . ($repoObject->isWriteable() ? "_editable" : "") . '"
				/>';
        }
    }
 /**
  * @param AJXP_Node $oldNode
  * @param AJXP_Node $newNode
  * @param bool $copy
  */
 public function updateNodesIndex($oldNode = null, $newNode = null, $copy = false)
 {
     if (!dibi::isConnected()) {
         dibi::connect($this->sqlDriver);
     }
     //$this->logInfo("Syncable index", array($oldNode == null?'null':$oldNode->getUrl(), $newNode == null?'null':$newNode->getUrl()));
     try {
         if ($newNode != null && $this->excludeNode($newNode)) {
             // CREATE
             if ($oldNode == null) {
                 AJXP_Logger::debug("Ignoring " . $newNode->getUrl() . " for indexation");
                 return;
             } else {
                 AJXP_Logger::debug("Target node is excluded, see it as a deletion: " . $newNode->getUrl());
                 $newNode = null;
             }
         }
         if ($newNode == null) {
             $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser());
             // DELETE
             $this->logDebug('DELETE', $oldNode->getUrl());
             dibi::query("DELETE FROM [ajxp_index] WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
         } else {
             if ($oldNode == null || $copy) {
                 // CREATE
                 $stat = stat($newNode->getUrl());
                 $newNode->setLeaf(!($stat['mode'] & 040000));
                 $this->logDebug('INSERT', $newNode->getUrl());
                 dibi::query("INSERT INTO [ajxp_index]", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath()), "bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => $newNode->isLeaf() ? md5_file($newNode->getUrl()) : "directory", "repository_identifier" => $repoId = $this->computeIdentifier($newNode->getRepository(), $newNode->getUser())));
             } else {
                 $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser());
                 if ($oldNode->getPath() == $newNode->getPath()) {
                     // CONTENT CHANGE
                     clearstatcache();
                     $stat = stat($newNode->getUrl());
                     $this->logDebug("Content changed", "current stat size is : " . $stat["size"]);
                     $this->logDebug('UPDATE CONTENT', $newNode->getUrl());
                     dibi::query("UPDATE [ajxp_index] SET ", array("bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => md5_file($newNode->getUrl())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
                     try {
                         $rowCount = dibi::getAffectedRows();
                         if ($rowCount === 0) {
                             $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!");
                             $this->updateNodesIndex(null, $newNode, false);
                         }
                     } catch (Exception $e) {
                     }
                 } else {
                     // PATH CHANGE ONLY
                     $newNode->loadNodeInfo();
                     if ($newNode->isLeaf()) {
                         $this->logDebug('UPDATE LEAF PATH', $newNode->getUrl());
                         dibi::query("UPDATE [ajxp_index] SET ", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
                         try {
                             $rowCount = dibi::getAffectedRows();
                             if ($rowCount === 0) {
                                 $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!");
                                 $this->updateNodesIndex(null, $newNode, false);
                             }
                         } catch (Exception $e) {
                         }
                     } else {
                         $this->logDebug('UPDATE FOLDER PATH', $newNode->getUrl());
                         dibi::query("UPDATE [ajxp_index] SET [node_path]=REPLACE( REPLACE(CONCAT('\$\$\$',[node_path]), CONCAT('\$\$\$', %s), CONCAT('\$\$\$', %s)) , '\$\$\$', '') ", $oldNode->getPath(), $newNode->getPath(), "WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId);
                         try {
                             $rowCount = dibi::getAffectedRows();
                             if ($rowCount === 0) {
                                 $this->logError(__FUNCTION__, "There was an update event on a non-indexed folder (" . $newNode->getPath() . "), relaunching a recursive indexation!");
                                 AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array());
                             }
                         } catch (Exception $e) {
                         }
                     }
                 }
             }
         }
     } catch (Exception $e) {
         AJXP_Logger::error("[meta.syncable]", "Exception", $e->getTraceAsString());
         AJXP_Logger::error("[meta.syncable]", "Indexation", $e->getMessage());
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     $dir = AJXP_Utils::decodeSecureMagic($dir);
     if ($dir == "/") {
         $dir = "";
     }
     $selection->initFromHttpVars($httpVars);
     if (!$selection->isEmpty()) {
         //$this->filterUserSelectionToHidden($selection->getFiles());
     }
     $urlBase = "pydio://" . ConfService::getRepository()->getId();
     $mess = ConfService::getMessages();
     switch ($action) {
         case "monitor_compression":
             $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]);
             $percent = 0;
             if (is_file($percentFile)) {
                 $percent = intval(file_get_contents($percentFile));
             }
             if ($percent < 100) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1);
                 AJXP_XMLWriter::close();
             } else {
                 @unlink($percentFile);
                 AJXP_XMLWriter::header();
                 if ($httpVars["on_end"] == "reload") {
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 } else {
                     $archiveName = AJXP_Utils::sanitize($httpVars["archive_name"], AJXP_SANITIZE_FILENAME);
                     $archiveName = str_replace("'", "\\'", $archiveName);
                     $jsCode = "\n                            PydioApi.getClient().downloadSelection(null, \$('download_form'), 'postcompress_download', {ope_id:'" . $httpVars["ope_id"] . "',archive_name:'" . $archiveName . "'});\n                        ";
                     AJXP_XMLWriter::triggerBgJsAction($jsCode, $mess["powerfs.3"], true);
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "postcompress_download":
             $archive = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             if (is_file($archive)) {
                 if (!$fsDriver->getFilteredOption("USE_XSENDFILE", ConfService::getRepository()) && !$fsDriver->getFilteredOption("USE_XACCELREDIRECT", ConfService::getRepository())) {
                     register_shutdown_function("unlink", $archive);
                 }
                 $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true);
             } else {
                 echo "<script>alert('Cannot find archive! Is ZIP correctly installed?');</script>";
             }
             break;
         case "compress":
         case "precompress":
             $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $opeId = substr(md5(time()), 0, 10);
                 $httpVars["ope_id"] = $opeId;
                 AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars);
                 AJXP_XMLWriter::header();
                 $bgParameters = array("dir" => SystemTextEncoding::toUTF8($dir), "archive_name" => SystemTextEncoding::toUTF8($archiveName), "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId);
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir;
             $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"];
             $compressLocally = $action == "compress" ? true : false;
             // List all files
             $todo = array();
             $args = array();
             $replaceSearch = array($rootDir, "\\");
             $replaceReplace = array("", "/");
             foreach ($selection->getFiles() as $selectionFile) {
                 $baseFile = $selectionFile;
                 $args[] = escapeshellarg(substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1)));
                 $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile);
                 $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/");
                 if (is_dir($selectionFile)) {
                     $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST);
                     foreach ($objects as $name => $object) {
                         $todo[] = str_replace($replaceSearch, $replaceReplace, $name);
                     }
                 }
                 if (trim($baseFile, "/") == "") {
                     // ROOT IS SELECTED, FIX IT
                     $args = array(escapeshellarg(basename($rootDir)));
                     $rootDir = dirname($rootDir);
                     break;
                 }
             }
             $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";";
             if (!$compressLocally) {
                 $archiveName = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . $archiveName;
             }
             chdir($rootDir);
             $cmd = $this->getFilteredOption("ZIP_PATH") . " -r " . escapeshellarg($archiveName) . " " . implode(" ", $args);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             $c = $fsDriver->getConfigs();
             if ((!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) && stripos(PHP_OS, "win") === false) {
                 $cmd .= " -x .\\*";
             }
             $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED";
             $proc = popen($cmd, "r");
             $toks = array();
             $handled = array();
             $finishedEchoed = false;
             while (!feof($proc)) {
                 set_time_limit(20);
                 $results = fgets($proc, 256);
                 if (strlen($results) == 0) {
                 } else {
                     $tok = strtok($results, "\n");
                     while ($tok !== false) {
                         $toks[] = $tok;
                         if ($tok == "ZIP_FINISHED") {
                             $finishedEchoed = true;
                         } else {
                             $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches);
                             if ($test !== false) {
                                 $handled[] = $matches[2];
                             }
                         }
                         $tok = strtok("\n");
                     }
                     if ($finishedEchoed) {
                         $percent = 100;
                     } else {
                         $percent = min(round(count($handled) / count($todo) * 100), 100);
                     }
                     file_put_contents($percentFile, $percent);
                 }
                 // avoid a busy wait
                 if ($percent < 100) {
                     usleep(1);
                 }
             }
             pclose($proc);
             file_put_contents($percentFile, 100);
             break;
         default:
             break;
     }
 }
 public function uploadActions($action, $httpVars, $filesVars)
 {
     switch ($action) {
         case "trigger_remote_copy":
             if (!$this->hasFilesToCopy()) {
                 break;
             }
             $toCopy = $this->getFileNameToCopy();
             $this->logDebug("trigger_remote", $toCopy);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . $toCopy . " to remote server");
             AJXP_XMLWriter::close();
             exit(1);
             break;
         case "next_to_remote":
             if (!$this->hasFilesToCopy()) {
                 break;
             }
             $fData = $this->getNextFileToCopy();
             $nextFile = '';
             if ($this->hasFilesToCopy()) {
                 $nextFile = $this->getFileNameToCopy();
             }
             $crtRep = ConfService::getRepository();
             session_write_close();
             $secureToken = "";
             $httpClient = $this->getRemoteConnexion($secureToken);
             //$httpClient->setDebug(true);
             $postData = array("get_action" => "upload", "dir" => base64_encode($fData["destination"]), "secure_token" => $secureToken);
             $httpClient->postFile($crtRep->getOption("URI") . "?", $postData, "Filedata", $fData);
             if (strpos($httpClient->getHeader("content-type"), "text/xml") !== false && strpos($httpClient->getContent(), "require_auth") != false) {
                 $httpClient = $this->getRemoteConnexion($secureToken, true);
                 $postData["secure_token"] = $secureToken;
                 $httpClient->postFile($crtRep->getOption("URI"), $postData, "Filedata", $fData);
             }
             unlink($fData["tmp_name"]);
             $response = $httpClient->getContent();
             AJXP_XMLWriter::header();
             $this->logDebug("next_to_remote", $nextFile);
             if (intval($response) >= 400) {
                 AJXP_XMLWriter::sendMessage(null, "Error : " . intval($response));
             } else {
                 if ($nextFile != '') {
                     AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . SystemTextEncoding::toUTF8($nextFile) . " to remote server");
                 } else {
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Upload done, reloading client.");
                 }
             }
             AJXP_XMLWriter::close();
             exit(1);
             break;
         case "upload":
             $rep_source = AJXP_Utils::securePath("/" . $httpVars['dir']);
             $this->logDebug("Upload : rep_source ", array($rep_source));
             $logMessage = "";
             foreach ($filesVars as $boxName => $boxData) {
                 if (substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 $this->logDebug("Upload : rep_source ", array($rep_source));
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                     $errorCode = $err[0];
                     $errorMessage = $err[1];
                     break;
                 }
                 $boxData["destination"] = $rep_source;
                 $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($this->repository->getOption("TMP_UPLOAD"));
                 $this->logDebug("Upload : tmp upload folder", array($destCopy));
                 if (!is_dir($destCopy)) {
                     if (!@mkdir($destCopy)) {
                         $this->logDebug("Upload error : cannot create temporary folder", array($destCopy));
                         $errorCode = 413;
                         $errorMessage = "Warning, cannot create folder for temporary copy.";
                         break;
                     }
                 }
                 if (!is_writeable($destCopy)) {
                     $this->logDebug("Upload error: cannot write into temporary folder");
                     $errorCode = 414;
                     $errorMessage = "Warning, cannot write into temporary folder.";
                     break;
                 }
                 $this->logDebug("Upload : tmp upload folder", array($destCopy));
                 if (isset($boxData["input_upload"])) {
                     try {
                         $destName = tempnam($destCopy, "");
                         $this->logDebug("Begining reading INPUT stream");
                         $input = fopen("php://input", "r");
                         $output = fopen($destName, "w");
                         $sizeRead = 0;
                         while ($sizeRead < intval($boxData["size"])) {
                             $chunk = fread($input, 4096);
                             $sizeRead += strlen($chunk);
                             fwrite($output, $chunk, strlen($chunk));
                         }
                         fclose($input);
                         fclose($output);
                         $boxData["tmp_name"] = $destName;
                         $this->storeFileToCopy($boxData);
                         $this->logDebug("End reading INPUT stream");
                     } catch (Exception $e) {
                         $errorCode = 411;
                         $errorMessage = $e->getMessage();
                         break;
                     }
                 } else {
                     $destName = $destCopy . "/" . basename($boxData["tmp_name"]);
                     if ($destName == $boxData["tmp_name"]) {
                         $destName .= "1";
                     }
                     if (move_uploaded_file($boxData["tmp_name"], $destName)) {
                         $boxData["tmp_name"] = $destName;
                         $this->storeFileToCopy($boxData);
                     } else {
                         $mess = ConfService::getMessages();
                         $errorCode = 411;
                         $errorMessage = "{$mess['33']} " . $boxData["name"];
                         break;
                     }
                 }
             }
             if (isset($errorMessage)) {
                 $this->logDebug("Return error {$errorCode} {$errorMessage}");
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             } else {
                 $this->logDebug("Return success");
                 return array("SUCCESS" => true);
             }
             session_write_close();
             break;
         default:
             break;
     }
 }
 function copyOrMoveFile($destDir, $srcFile, &$error, &$success, $move = false)
 {
     $mess = ConfService::getMessages();
     $destFile = $this->repository->getOption("PATH") . $destDir . "/" . basename($srcFile);
     $realSrcFile = $this->repository->getOption("PATH") . "{$srcFile}";
     $recycle = $this->repository->getOption("RECYCLE_BIN");
     if (!file_exists($realSrcFile)) {
         $error[] = $mess[100] . $srcFile;
         return;
     }
     if (dirname($realSrcFile) == dirname($destFile)) {
         if ($move) {
             $error[] = $mess[101];
             return;
         } else {
             $base = basename($srcFile);
             $i = 1;
             if (is_file($realSrcFile)) {
                 $dotPos = strrpos($base, ".");
                 if ($dotPos > -1) {
                     $radic = substr($base, 0, $dotPos);
                     $ext = substr($base, $dotPos);
                 }
             }
             // auto rename file
             $i = 1;
             $newName = $base;
             while (file_exists($this->repository->getOption("PATH") . $destDir . "/" . $newName)) {
                 $suffix = "-{$i}";
                 if (isset($radic)) {
                     $newName = $radic . $suffix . $ext;
                 } else {
                     $newName = $base . $suffix;
                 }
                 $i++;
             }
             $destFile = $this->repository->getOption("PATH") . $destDir . "/" . $newName;
         }
     }
     if (is_dir($realSrcFile)) {
         $errors = array();
         $succFiles = array();
         if ($move) {
             if (is_file($destFile)) {
                 unlink($destFile);
             }
             $res = rename($realSrcFile, $destFile);
         } else {
             $dirRes = $this->dircopy($realSrcFile, $destFile, $errors, $succFiles);
         }
         if (count($errors) || isset($res) && $res !== true) {
             $error[] = $mess[114];
             return;
         }
     } else {
         if ($move) {
             if (is_file($destFile)) {
                 unlink($destFile);
             }
             $res = rename($realSrcFile, $destFile);
         } else {
             $res = copy($realSrcFile, $destFile);
         }
         if ($res != 1) {
             $error[] = $mess[114];
             return;
         }
     }
     if ($move) {
         // Now delete original
         // $this->deldir($realSrcFile); // both file and dir
         $messagePart = $mess[74] . " " . SystemTextEncoding::toUTF8($destDir);
         if (RecycleBinManager::recycleEnabled() && $destDir == "/" . $recycle) {
             RecycleBinManager::fileToRecycle($srcFile);
             $messagePart = $mess[123] . " " . $mess[122];
         }
         if (isset($dirRes)) {
             $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ") ";
         } else {
             $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart;
         }
     } else {
         if (RecycleBinManager::recycleEnabled() && $destDir == "/" . $this->repository->getOption("RECYCLE_BIN")) {
             RecycleBinManager::fileToRecycle($srcFile);
         }
         if (isset($dirRes)) {
             $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir) . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ")";
         } else {
             $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir);
         }
     }
 }
 /**
  * @param array $data
  * @param array $options
  * @param ShareStore $shareStore
  */
 public static function render($data, $options, $shareStore)
 {
     if (isset($data["SECURITY_MODIFIED"]) && $data["SECURITY_MODIFIED"] === true) {
         self::renderError($data, "false");
         return;
     }
     // create driver from $data
     $className = $data["DRIVER"] . "AccessDriver";
     $u = parse_url($_SERVER["REQUEST_URI"]);
     $shortHash = pathinfo(basename($u["path"]), PATHINFO_FILENAME);
     // 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();
     ConfService::setLanguage($language);
     $mess = ConfService::getMessages();
     if ($shareStore->isShareExpired($shortHash, $data)) {
         self::renderError(array(), $shortHash, $mess["share_center.165"]);
         return;
     }
     $customs = array("title", "legend", "legend_pass", "background_attributes_1", "text_color", "background_color", "textshadow_color");
     $images = array("button", "background_1");
     $confs = $options;
     $confs["CUSTOM_SHAREPAGE_BACKGROUND_ATTRIBUTES_1"] = "background-repeat:repeat;background-position:50% 50%;";
     $confs["CUSTOM_SHAREPAGE_BACKGROUND_1"] = "plugins/action.share/res/hi-res/02.jpg";
     $confs["CUSTOM_SHAREPAGE_TEXT_COLOR"] = "#ffffff";
     $confs["CUSTOM_SHAREPAGE_TEXTSHADOW_COLOR"] = "rgba(0,0,0,5)";
     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_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"])) {
             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));
     $shareStore->incrementDownloadCounter($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());
     }
 }
Esempio n. 9
0
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars();
     $currentFile = $selection->getUniqueFile();
     $wrapperData = $this->accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId();
     $newValues = array();
     $def = $this->getMetaDefinition();
     foreach ($def as $key => $label) {
         if (isset($httpVars[$key])) {
             $newValues[$key] = AJXP_Utils::xmlEntities(AJXP_Utils::decodeSecureMagic($httpVars[$key]));
         } else {
             if (!isset($original)) {
                 $original = array();
                 $this->loadMetaFileData($urlBase . $currentFile);
                 $base = basename($currentFile);
                 if (is_array(self::$metaCache) && array_key_exists($base, self::$metaCache)) {
                     $original = self::$metaCache[$base];
                 }
             }
             if (isset($original) && isset($original[$key])) {
                 $newValues[$key] = $original[$key];
             }
         }
     }
     $this->addMeta($urlBase . $currentFile, $newValues);
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true);
     AJXP_XMLWriter::close();
 }
Esempio n. 10
0
 /**
  * @param array $shares
  * @param String $operation
  * @param AJXP_Node $oldNode
  * @param AJXP_Node $newNode
  * @param array $collectRepositories
  * @param string|null $parentRepositoryPath
  * @return array
  * @throws Exception
  */
 public function moveSharesFromMeta($shares, $operation = "move", $oldNode, $newNode = null, &$collectRepositories = array(), $parentRepositoryPath = null)
 {
     $privateShares = array();
     $publicShares = array();
     foreach ($shares as $id => $data) {
         $type = $data["type"];
         if ($operation == "delete") {
             $this->deleteShare($type, $id, false, true);
             continue;
         }
         if ($type == "minisite") {
             $share = $this->loadShare($id);
             $repo = ConfService::getRepositoryById($share["REPOSITORY"]);
         } else {
             if ($type == "repository") {
                 $repo = ConfService::getRepositoryById($id);
             } else {
                 if ($type == "file") {
                     $publicLink = $this->loadShare($id);
                 }
             }
         }
         if (isset($repo)) {
             $oldNodeLabel = SystemTextEncoding::toUTF8($oldNode->getLabel());
             $newNodeLabel = SystemTextEncoding::toUTF8($newNode->getLabel());
             if ($newNode != null && $newNodeLabel != $oldNodeLabel && $repo->getDisplay() == $oldNodeLabel) {
                 $repo->setDisplay($newNodeLabel);
             }
             $cFilter = $repo->getContentFilter();
             $path = $repo->getOption("PATH", true);
             $save = false;
             if (isset($cFilter)) {
                 if ($parentRepositoryPath !== null) {
                     $repo->addOption("PATH", $parentRepositoryPath);
                 } else {
                     $cFilter->movePath($oldNode->getPath(), $newNode->getPath());
                     $repo->setContentFilter($cFilter);
                 }
                 $save = true;
             } else {
                 if (!empty($path)) {
                     $oldNodePath = SystemTextEncoding::toUTF8($oldNode->getPath());
                     $newNodePath = SystemTextEncoding::toUTF8($newNode->getPath());
                     $path = preg_replace("#" . preg_quote($oldNodePath, "#") . "\$#", $newNodePath, $path);
                     $repo->addOption("PATH", $path);
                     $save = true;
                     $collectRepositories[$repo->getId()] = $path;
                 }
             }
             if ($save) {
                 //ConfService::getConfStorageImpl()->saveRepository($repo, true);
                 ConfService::replaceRepository($repo->getId(), $repo);
             }
             $access = $repo->getOption("SHARE_ACCESS");
             if (!empty($access) && $access == "PUBLIC") {
                 $publicShares[$id] = $data;
             } else {
                 $privateShares[$id] = $data;
             }
         } else {
             if (isset($publicLink) && is_array($publicLink) && isset($publicLink["FILE_PATH"])) {
                 $oldNodePath = SystemTextEncoding::toUTF8($oldNode->getPath());
                 $newNodePath = SystemTextEncoding::toUTF8($newNode->getPath());
                 $publicLink["FILE_PATH"] = str_replace($oldNodePath, $newNodePath, $publicLink["FILE_PATH"]);
                 $this->deleteShare("file", $id);
                 $this->storeShare($newNode->getRepositoryId(), $publicLink, "file", $id);
                 $privateShares[$id] = $data;
             }
         }
     }
     return array($privateShares, $publicShares);
 }
Esempio n. 11
0
 /**
  * Get a log in XML format.
  *
  * @param String $date Date in m-d-y format.
  * @param String $nodeName The name of the node to use for each log item.
  * @return null
  */
 public function xmlLogs($parentDir, $date, $nodeName = "log", $rootPath = "/logs")
 {
     $fName = $this->storageDir . "log_" . $date . ".txt";
     if (!is_file($fName) || !is_readable($fName)) {
         return;
     }
     $res = "";
     $lines = file($fName);
     foreach ($lines as $line) {
         $line = AJXP_Utils::xmlEntities($line);
         $matches = explode("\t", $line, 6);
         if (count($matches) == 6) {
             $fileName = $parentDir . "/" . $matches[0];
             foreach ($matches as $key => $match) {
                 $match = AJXP_Utils::xmlEntities($match);
                 $match = str_replace("\"", "'", $match);
                 $matches[$key] = $match;
             }
             if (count($matches) < 3) {
                 continue;
             }
             // rebuild timestamp
             $date = $matches[0];
             list($m, $d, $Y, $h, $i, $s) = sscanf($date, "%i-%i-%i %i:%i:%i");
             $tStamp = mktime($h, $i, $s, $m, $d, $Y);
             print SystemTextEncoding::toUTF8("<{$nodeName} is_file=\"1\" ajxp_modiftime=\"{$tStamp}\" filename=\"{$fileName}\" ajxp_mime=\"log\" date=\"{$matches['0']}\" ip=\"{$matches['1']}\" level=\"{$matches['2']}\" user=\"{$matches['3']}\" action=\"{$matches['4']}\" params=\"{$matches['5']}\" icon=\"toggle_log.png\" />", false);
         }
     }
     return;
 }
 public function listRepositories($root, $child, $hashValue = null, $returnNodes = false)
 {
     $REPOS_PER_PAGE = 50;
     $allNodes = array();
     if ($hashValue == null) {
         $hashValue = 1;
     }
     $offset = ($hashValue - 1) * $REPOS_PER_PAGE;
     $count = null;
     // Load all repositories = normal, templates, and templates children
     $currentUserIsGroupAdmin = AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/";
     if ($currentUserIsGroupAdmin) {
         $repos = ConfService::listRepositoriesWithCriteria(array("owner_user_id" => AJXP_FILTER_EMPTY, "groupPath" => "regexp:/^" . str_replace("/", "\\/", AuthService::getLoggedUser()->getGroupPath()) . '/', "ORDERBY" => array("KEY" => "display", "DIR" => "ASC"), "CURSOR" => array("OFFSET" => $offset, "LIMIT" => $REPOS_PER_PAGE)), $count);
     } else {
         $repos = ConfService::listRepositoriesWithCriteria(array("parent_uuid" => AJXP_FILTER_EMPTY, "ORDERBY" => array("KEY" => "display", "DIR" => "ASC"), "CURSOR" => array("OFFSET" => $offset, "LIMIT" => $REPOS_PER_PAGE)), $count);
     }
     if (!$returnNodes) {
         var_dump($count);
         AJXP_XMLWriter::renderPaginationData($count, $hashValue, ceil($count / $REPOS_PER_PAGE));
         AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchDisplayMode="list" switchGridMode="filelist" template_name="ajxp_conf.repositories">
             <column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/>
             <column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/>
             <column messageId="ajxp_conf.125" attributeName="slug" sortType="String"/>
         </columns>');
     }
     foreach ($repos as $repoIndex => $repoObject) {
         if ($repoObject->getAccessType() == "ajxp_conf" || $repoObject->getAccessType() == "ajxp_shared") {
             continue;
         }
         if (!AuthService::canAdministrate($repoObject)) {
             continue;
         }
         if (is_numeric($repoIndex)) {
             $repoIndex = "" . $repoIndex;
         }
         $icon = "hdd_external_unmount.png";
         $editable = $repoObject->isWriteable();
         if ($repoObject->isTemplate) {
             $icon = "hdd_external_mount.png";
             if (AuthService::getLoggedUser() != null && AuthService::getLoggedUser()->getGroupPath() != "/") {
                 $editable = false;
             }
         }
         $meta = array("repository_id" => $repoIndex, "accessType" => ($repoObject->isTemplate ? "Template for " : "") . $repoObject->getAccessType(), "icon" => $icon, "owner" => $repoObject->hasOwner() ? $repoObject->getOwner() : "", "openicon" => $icon, "slug" => $repoObject->getSlug(), "parentname" => "/repositories", "ajxp_mime" => "repository" . ($editable ? "_editable" : ""));
         $nodeKey = "/data/repositories/{$repoIndex}";
         if (in_array($nodeKey, $this->currentBookmarks)) {
             $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png"));
         }
         $xml = AJXP_XMLWriter::renderNode($nodeKey, AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay())), true, $meta, true, false);
         if ($returnNodes) {
             $allNodes[$nodeKey] = $xml;
         } else {
             print $xml;
         }
         if ($repoObject->isTemplate) {
             // Now Load children for template repositories
             $children = ConfService::listRepositoriesWithCriteria(array("parent_uuid" => $repoIndex . ""), $count);
             foreach ($children as $childId => $childObject) {
                 if (!AuthService::canAdministrate($childObject)) {
                     continue;
                 }
                 if (is_numeric($childId)) {
                     $childId = "" . $childId;
                 }
                 $meta = array("repository_id" => $childId, "accessType" => $childObject->getAccessType(), "icon" => "repo_child.png", "owner" => $childObject->hasOwner() ? $childObject->getOwner() : "", "openicon" => "repo_child.png", "parentname" => "/repositories", "ajxp_mime" => "repository_editable");
                 $cNodeKey = "/data/repositories/{$childId}";
                 if (in_array($cNodeKey, $this->currentBookmarks)) {
                     $meta = array_merge($meta, array("ajxp_bookmarked" => "true", "overlay_icon" => "bookmark.png"));
                 }
                 $xml = AJXP_XMLWriter::renderNode($cNodeKey, AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($childObject->getDisplay())), true, $meta, true, false);
                 if ($returnNodes) {
                     $allNodes[$cNodeKey] = $xml;
                 } else {
                     print $xml;
                 }
             }
         }
     }
 }
Esempio n. 13
0
/**
 * Executes an SVN command.
 * @param string $cmd Command to execute
 * @param string $switch Switches to be applied for the given command
 * @param string $arg Arguments of the command
 * @return array Result array containing commandline (idx = IDX_CMDLINE),
 * 	standard out array (idx = IDX_STDOUT),	error array (idx = IDX_ERROUT),
 *  and return code of the command (idx = IDX_CMD_RC).
 *
 * @since v1.0.0
 */
function &ExecSvnCmd($cmd, $arg = '', $switches = '')
{
    $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
    set_time_limit(100);
    $cwd = NULL;
    //'/tmp';
    $pipes = NULL;
    if (is_array($arg)) {
        $arg = implode(" ", array_map("escapeshellarg", $arg));
    } else {
        $arg = escapeshellarg(SystemTextEncoding::toUTF8($arg));
    }
    $cmdline = (SVNLIB_PATH != "" ? SVNLIB_PATH . "/" : "") . $cmd . " " . $switches . " " . $arg;
    /*
    $output = shell_exec($cmdline);
    $result = array();
    
    $result[IDX_CMDLINE] = $cmdline;
    if (strpos($switches, "xml")) {
        $result[IDX_STDOUT] = $output;
    } else {
        $result[IDX_STDOUT] = explode("\n", $output);
    }
    $result[IDX_ERROUT] = "";
    return $result;
    */
    $env = null;
    if (defined('AJXP_LOCALE')) {
        $env = array("LC_ALL" => AJXP_LOCALE);
    }
    $process = proc_open($cmdline, $descriptorspec, $pipes, NULL, $env, array("bypass_shell" => false));
    $result = array();
    $result[IDX_CMDLINE] = $cmdline;
    $result[IDX_STDOUT] = array();
    $result[IDX_ERROUT] = array();
    $result[IDX_CMD_RC] = -1;
    if (is_resource($process)) {
        // $pipes now looks like this:
        // 0 => writeable handle connected to child stdin
        // 1 => readable handle connected to child stdout
        // 2 => readable handle connected to child errout
        fclose($pipes[0]);
        $result = array();
        $result[IDX_CMDLINE] = $cmdline;
        if (strpos($switches, "xml")) {
            $result[IDX_STDOUT] = GetLineString($pipes[1]);
        } else {
            $result[IDX_STDOUT] = GetLineArray($pipes[1]);
        }
        fclose($pipes[1]);
        $result[IDX_ERROUT] = GetLineArray($pipes[2]);
        fclose($pipes[2]);
        // It is important that you close any pipes before calling
        // proc_close in order to avoid a deadlock
        $result[IDX_CMD_RC] = proc_close($process);
        //		echo "CMD: $cmdline<br/>";
        //		PrintDebugArray($result, "Result");
    }
    if (is_array($result[IDX_ERROUT]) && count($result[IDX_ERROUT])) {
        $join = trim(implode("", $result[IDX_ERROUT]));
        if ($join != "") {
            throw new Exception($join);
        }
    }
    return $result;
}
Esempio n. 14
0
 public function extractMeta($currentFile, &$metadata, $wrapperClassName, &$realFile)
 {
     if (isset($_SESSION["SVN_COMMAND_RUNNING"]) && $_SESSION["SVN_COMMAND_RUNNING"] === true) {
         return;
     }
     $realDir = dirname(call_user_func(array($wrapperClassName, "getRealFSReference"), $currentFile));
     if (SvnManager::$svnListDir == $realDir) {
         $entries = SvnManager::$svnListCache;
     } else {
         SvnManager::$svnListDir = $realDir;
         $entries = $this->svnListNode($realDir);
         SvnManager::$svnListCache = $entries;
     }
     $fileId = SystemTextEncoding::toUTF8(basename($currentFile));
     if (isset($entries[$fileId])) {
         $metadata = array_merge($metadata, $entries[$fileId]);
     }
 }
Esempio n. 15
0
 /**
  * @param array $httpVars
  * @param AJXP_Node $ajxpNode
  */
 public function filterHttpVarsFromUniqueNode(&$httpVars, $ajxpNode)
 {
     $httpVars["minisite"] = true;
     $httpVars["selection"] = true;
     if ($ajxpNode->isLeaf()) {
         $httpVars["filter_nodes"] = [$ajxpNode];
         $httpVars["file"] = "/";
         $httpVars["nodes"] = array("/");
     }
     if (!isset($httpVars["repo_label"])) {
         $httpVars["repo_label"] = SystemTextEncoding::toUTF8($ajxpNode->getLabel());
     }
 }
Esempio n. 16
0
 function applyAction($actionName, $httpVars, $filesVar)
 {
     if ($actionName == "get_driver_actions") {
         AJXP_XMLWriter::header();
         $this->sendActionsToClient(false, null, null);
         AJXP_XMLWriter::close();
         exit(1);
     }
     if (isset($this->actions[$actionName])) {
         // use callback;
         $action = $this->actions[$actionName];
         $callBack = $action["callback"];
         try {
             return call_user_func(array(&$this, $callBack), $actionName, $httpVars, $filesVar);
         } catch (Exception $e) {
             return AJXP_XMLWriter::sendMessage(null, SystemTextEncoding::toUTF8($e->getMessage()) . " (" . basename($e->getFile()) . " - L." . $e->getLine() . ")", false);
         }
     }
 }
 function crossRepositoryCopy($httpVars)
 {
     ConfService::detectRepositoryStreams(true);
     $mess = ConfService::getMessages();
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     $files = $selection->getFiles();
     $accessType = $this->repository->getAccessType();
     $repositoryId = $this->repository->getId();
     $origStreamURL = "ajxp.{$accessType}://{$repositoryId}";
     $destRepoId = $httpVars["dest_repository_id"];
     $destRepoObject = ConfService::getRepositoryById($destRepoId);
     $destRepoAccess = $destRepoObject->getAccessType();
     $destStreamURL = "ajxp.{$destRepoAccess}://{$destRepoId}";
     // Check rights
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId)) {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, "You do not have the right to access one of the repositories!");
             AJXP_XMLWriter::close();
             exit(1);
         }
     }
     $messages = array();
     foreach ($files as $file) {
         $origFile = $origStreamURL . $file;
         $destFile = $destStreamURL . $httpVars["dest"] . "/" . basename($file);
         $origHandler = fopen($origFile, "r");
         $destHandler = fopen($destFile, "w");
         if ($origHandler === false || $destHandler === false) {
             $errorMessages[] = AJXP_XMLWriter::sendMessage(null, $mess[114] . " ({$origFile} to {$destFile})", false);
             continue;
         }
         while (!feof($origHandler)) {
             fwrite($destHandler, fread($origHandler, 4096));
         }
         fflush($destHandler);
         fclose($origHandler);
         fclose($destHandler);
         $messages[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($origFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destFile);
     }
     AJXP_XMLWriter::header();
     if (count($errorMessages)) {
         AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true);
     }
     AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true);
     AJXP_XMLWriter::close();
     exit(0);
 }
 public function uploadActions($action, $httpVars, $filesVars)
 {
     switch ($action) {
         case "trigger_remote_copy":
             if (!$this->hasFilesToCopy()) {
                 break;
             }
             $toCopy = $this->getFileNameToCopy();
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . $toCopy . " to ftp server");
             AJXP_XMLWriter::close();
             exit(1);
             break;
         case "next_to_remote":
             if (!$this->hasFilesToCopy()) {
                 break;
             }
             $fData = $this->getNextFileToCopy();
             $nextFile = '';
             if ($this->hasFilesToCopy()) {
                 $nextFile = $this->getFileNameToCopy();
             }
             $this->logDebug("Base64 : ", array("from" => $fData["destination"], "to" => base64_decode($fData['destination'])));
             $destPath = $this->urlBase . base64_decode($fData['destination']) . "/" . $fData['name'];
             //$destPath = AJXP_Utils::decodeSecureMagic($destPath);
             // DO NOT "SANITIZE", THE URL IS ALREADY IN THE FORM ajxp.ftp://repoId/filename
             $destPath = SystemTextEncoding::fromPostedFileName($destPath);
             $node = new AJXP_Node($destPath);
             $this->logDebug("Copying file to server", array("from" => $fData["tmp_name"], "to" => $destPath, "name" => $fData["name"]));
             try {
                 AJXP_Controller::applyHook("node.before_create", array(&$node));
                 $fp = fopen($destPath, "w");
                 $fSource = fopen($fData["tmp_name"], "r");
                 while (!feof($fSource)) {
                     fwrite($fp, fread($fSource, 4096));
                 }
                 fclose($fSource);
                 $this->logDebug("Closing target : begin ftp copy");
                 // Make sur the script does not time out!
                 @set_time_limit(240);
                 fclose($fp);
                 $this->logDebug("FTP Upload : end of ftp copy");
                 @unlink($fData["tmp_name"]);
                 AJXP_Controller::applyHook("node.change", array(null, &$node));
             } catch (Exception $e) {
                 $this->logDebug("Error during ftp copy", array($e->getMessage(), $e->getTrace()));
             }
             $this->logDebug("FTP Upload : shoud trigger next or reload nextFile={$nextFile}");
             AJXP_XMLWriter::header();
             if ($nextFile != '') {
                 AJXP_XMLWriter::triggerBgAction("next_to_remote", array(), "Copying file " . SystemTextEncoding::toUTF8($nextFile) . " to remote server");
             } else {
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Upload done, reloading client.");
             }
             AJXP_XMLWriter::close();
             exit(1);
             break;
         case "upload":
             $rep_source = AJXP_Utils::securePath("/" . $httpVars['dir']);
             $this->logDebug("Upload : rep_source ", array($rep_source));
             $logMessage = "";
             foreach ($filesVars as $boxName => $boxData) {
                 if (substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 $this->logDebug("Upload : rep_source ", array($rep_source));
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                     $errorCode = $err[0];
                     $errorMessage = $err[1];
                     break;
                 }
                 if (isset($httpVars["auto_rename"])) {
                     $destination = $this->urlBase . $rep_source;
                     $boxData["name"] = fsAccessDriver::autoRenameForDest($destination, $boxData["name"]);
                 }
                 $boxData["destination"] = base64_encode($rep_source);
                 $destCopy = AJXP_XMLWriter::replaceAjxpXmlKeywords($this->repository->getOption("TMP_UPLOAD"));
                 $this->logDebug("Upload : tmp upload folder", array($destCopy));
                 if (!is_dir($destCopy)) {
                     if (!@mkdir($destCopy)) {
                         $this->logDebug("Upload error : cannot create temporary folder", array($destCopy));
                         $errorCode = 413;
                         $errorMessage = "Warning, cannot create folder for temporary copy.";
                         break;
                     }
                 }
                 if (!$this->isWriteable($destCopy)) {
                     $this->logDebug("Upload error: cannot write into temporary folder");
                     $errorCode = 414;
                     $errorMessage = "Warning, cannot write into temporary folder.";
                     break;
                 }
                 $this->logDebug("Upload : tmp upload folder", array($destCopy));
                 if (isset($boxData["input_upload"])) {
                     try {
                         $destName = tempnam($destCopy, "");
                         $this->logDebug("Begining reading INPUT stream");
                         $input = fopen("php://input", "r");
                         $output = fopen($destName, "w");
                         $sizeRead = 0;
                         while ($sizeRead < intval($boxData["size"])) {
                             $chunk = fread($input, 4096);
                             $sizeRead += strlen($chunk);
                             fwrite($output, $chunk, strlen($chunk));
                         }
                         fclose($input);
                         fclose($output);
                         $boxData["tmp_name"] = $destName;
                         $this->storeFileToCopy($boxData);
                         $this->logDebug("End reading INPUT stream");
                     } catch (Exception $e) {
                         $errorCode = 411;
                         $errorMessage = $e->getMessage();
                         break;
                     }
                 } else {
                     $destName = $destCopy . "/" . basename($boxData["tmp_name"]);
                     if ($destName == $boxData["tmp_name"]) {
                         $destName .= "1";
                     }
                     if (move_uploaded_file($boxData["tmp_name"], $destName)) {
                         $boxData["tmp_name"] = $destName;
                         $this->storeFileToCopy($boxData);
                     } else {
                         $mess = ConfService::getMessages();
                         $errorCode = 411;
                         $errorMessage = "{$mess['33']} " . $boxData["name"];
                         break;
                     }
                 }
             }
             if (isset($errorMessage)) {
                 $this->logDebug("Return error {$errorCode} {$errorMessage}");
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             } else {
                 $this->logDebug("Return success");
                 return array("SUCCESS" => true, "PREVENT_NOTIF" => true);
             }
             break;
         default:
             break;
     }
     session_write_close();
     exit;
 }
 function listRepositories()
 {
     $repos = ConfService::getRepositoriesList();
     AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_conf.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_conf.9" attributeName="accessType" sortType="String"/><column messageId="ajxp_shared.9" attributeName="repo_accesses" sortType="String"/></columns>');
     $repoArray = array();
     $childRepos = array();
     $loggedUser = AuthService::getLoggedUser();
     $users = AuthService::listUsers();
     foreach ($repos as $repoIndex => $repoObject) {
         if ($repoObject->getAccessType() == "ajxp_conf") {
             continue;
         }
         if (!$repoObject->hasOwner() || $repoObject->getOwner() != $loggedUser->getId()) {
             continue;
         }
         if (is_numeric($repoIndex)) {
             $repoIndex = "" . $repoIndex;
         }
         $name = AJXP_Utils::xmlEntities(SystemTextEncoding::toUTF8($repoObject->getDisplay()));
         $repoArray[$name] = $repoIndex;
     }
     // Sort the list now by name
     ksort($repoArray);
     // Append child repositories
     $sortedArray = array();
     foreach ($repoArray as $name => $repoIndex) {
         $sortedArray[$name] = $repoIndex;
         if (isset($childRepos[$repoIndex]) && is_array($childRepos[$repoIndex])) {
             foreach ($childRepos[$repoIndex] as $childData) {
                 $sortedArray[$childData["name"]] = $childData["index"];
             }
         }
     }
     foreach ($sortedArray as $name => $repoIndex) {
         $repoObject =& $repos[$repoIndex];
         $repoAccesses = array();
         foreach ($users as $userId => $userObject) {
             if (!$userObject->hasParent()) {
                 continue;
             }
             if ($userObject->canWrite($repoIndex)) {
                 $repoAccesses[] = $userId . " (rw)";
             } else {
                 if ($userObject->canRead($repoIndex)) {
                     $repoAccesses[] = $userId . " (r)";
                 }
             }
         }
         $metaData = array("repository_id" => $repoIndex, "accessType" => $repoObject->getAccessType(), "icon" => "document_open_remote.png", "openicon" => "document_open_remote.png", "parentname" => "/repositories", "repo_accesses" => implode(", ", $repoAccesses), "ajxp_mime" => "shared_repository");
         AJXP_XMLWriter::renderNode("/repositories/{$repoIndex}", $name, true, $metaData);
     }
 }
 /**
  * Write the repositories access rights in XML format
  * @static
  * @param AbstractAjxpUser|null $loggedUser * @internal param bool $details
  * @return string
  */
 public static function writeRepositoriesData($loggedUser)
 {
     $st = "<repositories>";
     $streams = ConfService::detectRepositoryStreams(false);
     $exposed = array();
     $cacheHasExposed = AJXP_PluginsService::getInstance()->loadFromPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']");
     if ($cacheHasExposed !== null && is_array($cacheHasExposed)) {
         $exposed = $cacheHasExposed;
     } else {
         $exposed_props = AJXP_PluginsService::searchAllManifests("//server_settings/param[contains(@scope,'repository') and @expose='true']", "node", false, false, true);
         foreach ($exposed_props as $exposed_prop) {
             $pluginId = $exposed_prop->parentNode->parentNode->getAttribute("id");
             $paramName = $exposed_prop->getAttribute("name");
             $paramDefault = $exposed_prop->getAttribute("default");
             $exposed[] = array("PLUGIN_ID" => $pluginId, "NAME" => $paramName, "DEFAULT" => $paramDefault);
         }
         AJXP_PluginsService::getInstance()->storeToPluginQueriesCache("//server_settings/param[contains(@scope,'repository') and @expose='true']", $exposed);
     }
     $accessible = ConfService::getAccessibleRepositories($loggedUser, false, false);
     foreach ($accessible as $repoId => $repoObject) {
         $rightString = "";
         $streamString = "";
         if (in_array($repoObject->accessType, $streams)) {
             $streamString = "allowCrossRepositoryCopy=\"true\"";
         }
         if ($repoObject->getUniqueUser()) {
             $streamString .= " user_editable_repository=\"true\" ";
         }
         $slugString = "";
         $slug = $repoObject->getSlug();
         if (!empty($slug)) {
             $slugString = "repositorySlug=\"{$slug}\"";
         }
         $isSharedString = "";
         if ($repoObject->hasOwner()) {
             $uId = $repoObject->getOwner();
             $uObject = ConfService::getConfStorageImpl()->createUserObject($uId);
             $label = $uObject->personalRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $uId);
             if (empty($label)) {
                 $label = $uId;
             }
             $isSharedString = 'owner="' . AJXP_Utils::xmlEntities($label) . '"';
         }
         $descTag = "";
         $public = false;
         if (!empty($_SESSION["CURRENT_MINISITE"])) {
             $public = true;
         }
         $description = $repoObject->getDescription($public);
         if (!empty($description)) {
             $descTag = '<description>' . AJXP_Utils::xmlEntities($description, true) . '</description>';
         }
         $roleString = "";
         if ($loggedUser != null) {
             $merged = $loggedUser->mergedRole;
             $params = array();
             foreach ($exposed as $exposed_prop) {
                 $metaOptions = $repoObject->getOption("META_SOURCES");
                 if (!isset($metaOptions[$exposed_prop["PLUGIN_ID"]])) {
                     continue;
                 }
                 $value = $exposed_prop["DEFAULT"];
                 if (isset($metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]])) {
                     $value = $metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]];
                 }
                 $value = $merged->filterParameterValue($exposed_prop["PLUGIN_ID"], $exposed_prop["NAME"], $repoId, $value);
                 if ($value !== null) {
                     if ($value === true || $value === false) {
                         $value = $value === true ? "true" : "false";
                     }
                     $params[] = '<repository_plugin_param plugin_id="' . $exposed_prop["PLUGIN_ID"] . '" name="' . $exposed_prop["NAME"] . '" value="' . AJXP_Utils::xmlEntities($value) . '"/>';
                     $roleString .= str_replace(".", "_", $exposed_prop["PLUGIN_ID"]) . "_" . $exposed_prop["NAME"] . '="' . AJXP_Utils::xmlEntities($value) . '" ';
                 }
             }
             $roleString .= 'acl="' . $merged->getAcl($repoId) . '"';
             if ($merged->hasMask($repoId)) {
                 $roleString .= ' hasMask="true" ';
             }
         }
         $st .= "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$rightString} {$streamString} {$slugString} {$isSharedString} {$roleString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label>" . $descTag . $repoObject->getClientSettings() . "</repo>";
     }
     $st .= "</repositories>";
     return $st;
 }
 /**
  * Get a log in XML format.
  *
  * @param String $date Date in m-d-y format.
  * @param String $nodeName The name of the node to use for each log item.
  * @return null
  */
 function xmlLogs($parentDir, $date, $nodeName = "log")
 {
     $fName = $this->storageDir . "log_" . $date . ".txt";
     if (!is_file($fName) || !is_readable($fName)) {
         return;
     }
     $res = "";
     $lines = file($fName);
     foreach ($lines as $line) {
         $line = AJXP_Utils::xmlEntities($line);
         $matches = array();
         if (preg_match("/(.*)\t(.*)\t(.*)\t(.*)\t(.*)\t(.*)\$/", $line, $matches) !== false) {
             $fileName = $parentDir . "/" . $matches[1];
             foreach ($matches as $key => $match) {
                 $match = AJXP_Utils::xmlEntities($match);
                 $match = str_replace("\"", "'", $match);
                 $matches[$key] = $match;
             }
             print SystemTextEncoding::toUTF8("<{$nodeName} is_file=\"1\" filename=\"{$fileName}\" ajxp_mime=\"log\" date=\"{$matches['1']}\" ip=\"{$matches['2']}\" level=\"{$matches['3']}\" user=\"{$matches['4']}\" action=\"{$matches['5']}\" params=\"{$matches['6']}\" icon=\"toggle_log.png\" />");
         }
     }
     return;
 }
Esempio n. 22
0
 public function mimeExtractorCallback($masterFile, $targetFile)
 {
     $metadata = array();
     require_once "Mail/mimeDecode.php";
     $params = array('include_bodies' => true, 'decode_bodies' => false, 'decode_headers' => 'UTF-8');
     $mess = ConfService::getMessages();
     $content = file_get_contents($masterFile);
     $decoder = new Mail_mimeDecode($content);
     $structure = $decoder->decode($params);
     $allowedHeaders = array("to", "from", "subject", "message-id", "mime-version", "date", "return-path");
     foreach ($structure->headers as $hKey => $hValue) {
         if (!in_array($hKey, $allowedHeaders)) {
             continue;
         }
         if (is_array($hValue)) {
             $hValue = implode(", ", $hValue);
         }
         if ($hKey == "date") {
             $date = strtotime($hValue);
             $metadata["eml_time"] = $date;
         }
         $metadata["eml_" . $hKey] = AJXP_Utils::xmlEntities(@htmlentities($hValue, ENT_COMPAT, "UTF-8"));
         //$this->logDebug($hKey." - ".$hValue. " - ".$metadata["eml_".$hKey]);
         if ($metadata["eml_" . $hKey] == "") {
             $metadata["eml_" . $hKey] = AJXP_Utils::xmlEntities(@htmlentities($hValue));
             if (!SystemTextEncoding::isUtf8($metadata["eml_" . $hKey])) {
                 $metadata["eml_" . $hKey] = SystemTextEncoding::toUTF8($metadata["eml_" . $hKey]);
             }
         }
         $metadata["eml_" . $hKey] = str_replace("&amp;", "&", $metadata["eml_" . $hKey]);
     }
     $metadata["eml_attachments"] = 0;
     $parts = $structure->parts;
     if (!empty($parts)) {
         foreach ($parts as $mimePart) {
             if (!empty($mimePart->disposition) && $mimePart->disposition == "attachment") {
                 $metadata["eml_attachments"]++;
             }
         }
     }
     $metadata["icon"] = "eml_images/ICON_SIZE/mail_mime.png";
     file_put_contents($targetFile, serialize($metadata));
 }
Esempio n. 23
0
 /**
  * @param string $repoId
  * @param Repository $repoObject
  * @param array $exposed
  * @param array $streams
  * @param AbstractAjxpUser $loggedUser
  * @param string $accessStatus
  * @return string
  * @throws Exception
  */
 public static function repositoryToXML($repoId, $repoObject, $exposed, $streams, $loggedUser, $accessStatus = "")
 {
     $statusString = " repository_type=\"" . $repoObject->getRepositoryType() . "\"";
     if (empty($accessStatus)) {
         $accessStatus = $repoObject->getAccessStatus();
     }
     if (!empty($accessStatus)) {
         $statusString .= " access_status=\"{$accessStatus}\" ";
     } else {
         if ($loggedUser != null) {
             $lastConnected = $loggedUser->getArrayPref("repository_last_connected", $repoId);
             if (!empty($lastConnected)) {
                 $statusString .= " last_connection=\"{$lastConnected}\" ";
             }
         }
     }
     $streamString = "";
     if (in_array($repoObject->accessType, $streams)) {
         $streamString = "allowCrossRepositoryCopy=\"true\"";
     }
     if ($repoObject->getUniqueUser()) {
         $streamString .= " user_editable_repository=\"true\" ";
     }
     if ($repoObject->hasContentFilter()) {
         $streamString .= " hasContentFilter=\"true\"";
     }
     $slugString = "";
     $slug = $repoObject->getSlug();
     if (!empty($slug)) {
         $slugString = "repositorySlug=\"{$slug}\"";
     }
     $isSharedString = "";
     $currentUserIsOwner = false;
     $ownerLabel = null;
     if ($repoObject->hasOwner()) {
         $uId = $repoObject->getOwner();
         if (AuthService::usersEnabled() && AuthService::getLoggedUser()->getId() == $uId) {
             $currentUserIsOwner = true;
         }
         $label = ConfService::getUserPersonalParameter("USER_DISPLAY_NAME", $uId, "core.conf", $uId);
         $ownerLabel = $label;
         $isSharedString = 'owner="' . AJXP_Utils::xmlEntities($label) . '"';
     }
     if ($repoObject->securityScope() == "USER" || $currentUserIsOwner) {
         $streamString .= " userScope=\"true\"";
     }
     $descTag = "";
     $public = false;
     if (!empty($_SESSION["CURRENT_MINISITE"])) {
         $public = true;
     }
     $description = $repoObject->getDescription($public, $ownerLabel);
     if (!empty($description)) {
         $descTag = '<description>' . AJXP_Utils::xmlEntities($description, true) . '</description>';
     }
     $roleString = "";
     if ($loggedUser != null) {
         $merged = $loggedUser->mergedRole;
         $params = array();
         foreach ($exposed as $exposed_prop) {
             $metaOptions = $repoObject->getOption("META_SOURCES");
             if (!isset($metaOptions[$exposed_prop["PLUGIN_ID"]])) {
                 continue;
             }
             $value = $exposed_prop["DEFAULT"];
             if (isset($metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]])) {
                 $value = $metaOptions[$exposed_prop["PLUGIN_ID"]][$exposed_prop["NAME"]];
             }
             $value = $merged->filterParameterValue($exposed_prop["PLUGIN_ID"], $exposed_prop["NAME"], $repoId, $value);
             if ($value !== null) {
                 if ($value === true || $value === false) {
                     $value = $value === true ? "true" : "false";
                 }
                 $params[] = '<repository_plugin_param plugin_id="' . $exposed_prop["PLUGIN_ID"] . '" name="' . $exposed_prop["NAME"] . '" value="' . AJXP_Utils::xmlEntities($value) . '"/>';
                 $roleString .= str_replace(".", "_", $exposed_prop["PLUGIN_ID"]) . "_" . $exposed_prop["NAME"] . '="' . AJXP_Utils::xmlEntities($value) . '" ';
             }
         }
         $roleString .= 'acl="' . $merged->getAcl($repoId) . '"';
         if ($merged->hasMask($repoId)) {
             $roleString .= ' hasMask="true" ';
         }
     }
     return "<repo access_type=\"" . $repoObject->accessType . "\" id=\"" . $repoId . "\"{$statusString} {$streamString} {$slugString} {$isSharedString} {$roleString}><label>" . SystemTextEncoding::toUTF8(AJXP_Utils::xmlEntities($repoObject->getDisplay())) . "</label>" . $descTag . $repoObject->getClientSettings() . "</repo>";
 }
 public function extractExif($actionName, $httpVars, $fileVars)
 {
     $repo = $this->accessDriver->repository;
     $userSelection = new UserSelection($this->accessDriver->repository, $httpVars);
     $repo->detectStreamWrapper(true);
     $selectedNode = $userSelection->getUniqueNode();
     $realFile = AJXP_MetaStreamWrapper::getRealFSReference($selectedNode->getUrl());
     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");
     $format = "xml";
     if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
         $format = "json";
     }
     $filteredData = array();
     foreach ($exifData as $section => $data) {
         $filteredData[$section] = array();
         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);
             $filteredData[$section][$key] = SystemTextEncoding::toUTF8($value);
         }
     }
     if ($format == "xml") {
         AJXP_XMLWriter::header("metadata", array("file" => $selectedNode->getPath(), "type" => "EXIF"));
         foreach ($filteredData as $section => $data) {
             print "<exifSection name='{$section}'>";
             foreach ($data as $key => $value) {
                 print "<exifTag name=\"{$key}\">" . AJXP_Utils::xmlEntities($value) . "</exifTag>";
             }
             print "</exifSection>";
         }
         AJXP_XMLWriter::close("metadata");
     } else {
         HTMLWriter::charsetHeader("application/json");
         echo json_encode($filteredData);
     }
 }
 /**
  * @param String $action
  * @param Array $httpVars
  * @param Array $fileVars
  * @throws Exception
  */
 public function receiveAction($action, $httpVars, $fileVars)
 {
     //VAR CREATION OUTSIDE OF ALL CONDITIONS, THEY ARE "MUST HAVE" VAR !!
     $messages = ConfService::getMessages();
     $repository = ConfService::getRepository();
     $userSelection = new UserSelection($repository, $httpVars);
     $nodes = $userSelection->buildNodes();
     $currentDirPath = AJXP_Utils::safeDirname($userSelection->getUniqueNode()->getPath());
     $currentDirPath = rtrim($currentDirPath, "/") . "/";
     $currentDirUrl = $userSelection->currentBaseUrl() . $currentDirPath;
     if (empty($httpVars["compression_id"])) {
         $compressionId = sha1(rand());
         $httpVars["compression_id"] = $compressionId;
     } else {
         $compressionId = $httpVars["compression_id"];
     }
     $progressCompressionFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressCompressionID-" . $compressionId . ".txt";
     if (empty($httpVars["extraction_id"])) {
         $extractId = sha1(rand());
         $httpVars["extraction_id"] = $extractId;
     } else {
         $extractId = $httpVars["extraction_id"];
     }
     $progressExtractFileName = $this->getPluginCacheDir(false, true) . DIRECTORY_SEPARATOR . "progressExtractID-" . $extractId . ".txt";
     if ($action == "compression") {
         $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
         $archiveFormat = $httpVars["type_archive"];
         $tabTypeArchive = array(".tar", ".tar.gz", ".tar.bz2");
         $acceptedExtension = false;
         foreach ($tabTypeArchive as $extensionArchive) {
             if ($extensionArchive == $archiveFormat) {
                 $acceptedExtension = true;
                 break;
             }
         }
         if ($acceptedExtension == false) {
             file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.16"]);
             throw new AJXP_Exception($messages["compression.16"]);
         }
         $typeArchive = $httpVars["type_archive"];
         //if we can run in background we do it
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             $archivePath = $currentDirPath . $archiveName;
             file_put_contents($progressCompressionFileName, $messages["compression.5"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "compression", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $messages["compression.5"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         } else {
             $maxAuthorizedSize = 4294967296;
             $currentDirUrlLength = strlen($currentDirUrl);
             $tabFolders = array();
             $tabAllRecursiveFiles = array();
             $tabFilesNames = array();
             foreach ($nodes as $node) {
                 $nodeUrl = $node->getUrl();
                 if (is_file($nodeUrl) && filesize($nodeUrl) < $maxAuthorizedSize) {
                     array_push($tabAllRecursiveFiles, $nodeUrl);
                     array_push($tabFilesNames, substr($nodeUrl, $currentDirUrlLength));
                 }
                 if (is_dir($nodeUrl)) {
                     array_push($tabFolders, $nodeUrl);
                 }
             }
             //DO A FOREACH OR IT'S GONNA HAVE SOME SAMES FILES NAMES
             foreach ($tabFolders as $value) {
                 $dossiers = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($value));
                 foreach ($dossiers as $file) {
                     if ($file->isDir()) {
                         continue;
                     }
                     array_push($tabAllRecursiveFiles, $file->getPathname());
                     array_push($tabFilesNames, substr($file->getPathname(), $currentDirUrlLength));
                 }
             }
             //WE STOP IF IT'S JUST AN EMPTY FOLDER OR NO FILES
             if (empty($tabFilesNames)) {
                 file_put_contents($progressCompressionFileName, "Error : " . $messages["compression.17"]);
                 throw new AJXP_Exception($messages["compression.17"]);
             }
             try {
                 $tmpArchiveName = tempnam(AJXP_Utils::getAjxpTmpDir(), "tar-compression") . ".tar";
                 $archive = new PharData($tmpArchiveName);
             } catch (Exception $e) {
                 file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                 throw $e;
             }
             $counterCompression = 0;
             //THE TWO ARRAY ARE MERGED FOR THE FOREACH LOOP
             $tabAllFiles = array_combine($tabAllRecursiveFiles, $tabFilesNames);
             foreach ($tabAllFiles as $fullPath => $fileName) {
                 try {
                     $archive->addFile(AJXP_MetaStreamWrapper::getRealFSReference($fullPath), $fileName);
                     $counterCompression++;
                     file_put_contents($progressCompressionFileName, sprintf($messages["compression.6"], round($counterCompression / count($tabAllFiles) * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
                 } catch (Exception $e) {
                     unlink($tmpArchiveName);
                     file_put_contents($progressCompressionFileName, "Error : " . $e->getMessage());
                     throw $e;
                 }
             }
             $finalArchive = $tmpArchiveName;
             if ($typeArchive != ".tar") {
                 $archiveTypeCompress = substr(strrchr($typeArchive, "."), 1);
                 file_put_contents($progressCompressionFileName, sprintf($messages["compression.7"], strtoupper($archiveTypeCompress)));
                 if ($archiveTypeCompress == "gz") {
                     $archive->compress(Phar::GZ);
                 } elseif ($archiveTypeCompress == "bz2") {
                     $archive->compress(Phar::BZ2);
                 }
                 $finalArchive = $tmpArchiveName . "." . $archiveTypeCompress;
             }
             $destArchive = AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $archiveName);
             rename($finalArchive, $destArchive);
             AJXP_Controller::applyHook("node.before_create", array($destArchive, filesize($destArchive)));
             if (file_exists($tmpArchiveName)) {
                 unlink($tmpArchiveName);
                 unlink(substr($tmpArchiveName, 0, -4));
             }
             $newNode = new AJXP_Node($currentDirUrl . $archiveName);
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             file_put_contents($progressCompressionFileName, "SUCCESS");
         }
     } elseif ($action == "check_compression_status") {
         $archivePath = AJXP_Utils::decodeSecureMagic($httpVars["archive_path"]);
         $progressCompression = file_get_contents($progressCompressionFileName);
         $substrProgressCompression = substr($progressCompression, 0, 5);
         if ($progressCompression != "SUCCESS" && $substrProgressCompression != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_compression_status", array("repository_id" => $repository->getId(), "compression_id" => $compressionId, "archive_path" => SystemTextEncoding::toUTF8($archivePath)), $progressCompression, true, 5);
             AJXP_XMLWriter::close();
         } elseif ($progressCompression == "SUCCESS") {
             $newNode = new AJXP_Node($userSelection->currentBaseUrl() . $archivePath);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage($messages["compression.8"], null);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         } elseif ($substrProgressCompression == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressCompression);
             AJXP_XMLWriter::close();
             if (file_exists($progressCompressionFileName)) {
                 unlink($progressCompressionFileName);
             }
         }
     } elseif ($action == "extraction") {
         $fileArchive = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["file"]), AJXP_SANITIZE_DIRNAME);
         $fileArchive = substr(strrchr($fileArchive, DIRECTORY_SEPARATOR), 1);
         $authorizedExtension = array("tar" => 4, "gz" => 7, "bz2" => 8);
         $acceptedArchive = false;
         $extensionLength = 0;
         $counterExtract = 0;
         $currentAllPydioPath = $currentDirUrl . $fileArchive;
         $pharCurrentAllPydioPath = "phar://" . AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath);
         $pathInfoCurrentAllPydioPath = pathinfo($currentAllPydioPath, PATHINFO_EXTENSION);
         //WE TAKE ONLY TAR, TAR.GZ AND TAR.BZ2 ARCHIVES
         foreach ($authorizedExtension as $extension => $strlenExtension) {
             if ($pathInfoCurrentAllPydioPath == $extension) {
                 $acceptedArchive = true;
                 $extensionLength = $strlenExtension;
                 break;
             }
         }
         if ($acceptedArchive == false) {
             file_put_contents($progressExtractFileName, "Error : " . $messages["compression.15"]);
             throw new AJXP_Exception($messages["compression.15"]);
         }
         $onlyFileName = substr($fileArchive, 0, -$extensionLength);
         $lastPosOnlyFileName = strrpos($onlyFileName, "-");
         $tmpOnlyFileName = substr($onlyFileName, 0, $lastPosOnlyFileName);
         $counterDuplicate = substr($onlyFileName, $lastPosOnlyFileName + 1);
         if (!is_int($lastPosOnlyFileName) || !is_int($counterDuplicate)) {
             $tmpOnlyFileName = $onlyFileName;
             $counterDuplicate = 1;
         }
         while (file_exists($currentDirUrl . $onlyFileName)) {
             $onlyFileName = $tmpOnlyFileName . "-" . $counterDuplicate;
             $counterDuplicate++;
         }
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             file_put_contents($progressExtractFileName, $messages["compression.12"]);
             AJXP_Controller::applyActionInBackground($repository->getId(), "extraction", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $messages["compression.12"], true, 2);
             AJXP_XMLWriter::close();
             return null;
         }
         mkdir($currentDirUrl . $onlyFileName, 0777, true);
         chmod(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), 0777);
         try {
             $archive = new PharData(AJXP_MetaStreamWrapper::getRealFSReference($currentAllPydioPath));
             $fichiersArchive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharCurrentAllPydioPath));
             foreach ($fichiersArchive as $file) {
                 $fileGetPathName = $file->getPathname();
                 if ($file->isDir()) {
                     continue;
                 }
                 $fileNameInArchive = substr(strstr($fileGetPathName, $fileArchive), strlen($fileArchive) + 1);
                 try {
                     $archive->extractTo(AJXP_MetaStreamWrapper::getRealFSReference($currentDirUrl . $onlyFileName), $fileNameInArchive, false);
                 } catch (Exception $e) {
                     file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
                     throw new AJXP_Exception($e);
                 }
                 $counterExtract++;
                 file_put_contents($progressExtractFileName, sprintf($messages["compression.13"], round($counterExtract / $archive->count() * 100, 0, PHP_ROUND_HALF_DOWN) . " %"));
             }
         } catch (Exception $e) {
             file_put_contents($progressExtractFileName, "Error : " . $e->getMessage());
             throw new AJXP_Exception($e);
         }
         file_put_contents($progressExtractFileName, "SUCCESS");
         $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
         AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array());
     } elseif ($action == "check_extraction_status") {
         $currentDirUrl = $httpVars["currentDirUrl"];
         $onlyFileName = $httpVars["onlyFileName"];
         $progressExtract = file_get_contents($progressExtractFileName);
         $substrProgressExtract = substr($progressExtract, 0, 5);
         if ($progressExtract != "SUCCESS" && $progressExtract != "INDEX" && $substrProgressExtract != "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_extraction_status", array("repository_id" => $repository->getId(), "extraction_id" => $extractId, "currentDirUrl" => $currentDirUrl, "onlyFileName" => $onlyFileName), $progressExtract, true, 4);
             AJXP_XMLWriter::close();
         } elseif ($progressExtract == "SUCCESS") {
             $newNode = new AJXP_Node($currentDirUrl . $onlyFileName);
             $nodesDiffs = array("ADD" => array($newNode), "REMOVE" => array(), "UPDATE" => array());
             AJXP_Controller::applyHook("node.change", array(null, $newNode, false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(sprintf($messages["compression.14"], $onlyFileName), null);
             AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $newNode->getRepositoryId()), "starting indexation", true, 5);
             AJXP_XMLWriter::writeNodesDiff($nodesDiffs, true);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         } elseif ($substrProgressExtract == "Error") {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, $progressExtract);
             AJXP_XMLWriter::close();
             if (file_exists($progressExtractFileName)) {
                 unlink($progressExtractFileName);
             }
         }
     }
 }
Esempio n. 26
0
ConfService::init();
ConfService::start();
$confStorageDriver = ConfService::getConfStorageImpl();
require_once $confStorageDriver->getUserClassFileName();
//session_name("AjaXplorer");
//session_start();
$optArgs = array();
$options = array();
$regex = '/^-(-?)([a-zA-z0-9_]*)=(.*)/';
foreach ($argv as $key => $argument) {
    //echo("$key => $argument \n");
    if (preg_match($regex, $argument, $matches)) {
        if ($matches[1] == "-") {
            $optArgs[trim($matches[2])] = SystemTextEncoding::toUTF8(trim($matches[3]));
        } else {
            $options[trim($matches[2])] = SystemTextEncoding::toUTF8(trim($matches[3]));
        }
    }
}
$optUser = $options["u"];
if (!empty($optUser)) {
    if (isset($options["p"])) {
        $optPass = $options["p"];
    } else {
        // Consider "u" is a crypted version of u:p
        $optToken = $options["t"];
        $cKey = ConfService::getCoreConf("AJXP_CLI_SECRET_KEY", "conf");
        if (empty($cKey)) {
            $cKey = "CDAFx¨op#";
        }
        $optUser = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($optToken . $cKey), base64_decode($optUser), MCRYPT_MODE_ECB), "");
Esempio n. 27
0
 /**
  *
  * @param AJXP_Node $ajxpNode
  */
 public function extractMeta(&$ajxpNode)
 {
     //if(isSet($_SESSION["SVN_COMMAND_RUNNING"]) && $_SESSION["SVN_COMMAND_RUNNING"] === true) return ;
     $realDir = dirname($ajxpNode->getRealFile());
     if (SvnManager::$svnListDir == $realDir) {
         $entries = SvnManager::$svnListCache;
     } else {
         try {
             SvnManager::$svnListDir = $realDir;
             $entries = $this->svnListNode($realDir);
             SvnManager::$svnListCache = $entries;
         } catch (Exception $e) {
             $this->logError("ExtractMeta", $e->getMessage());
         }
     }
     $fileId = SystemTextEncoding::toUTF8(basename($ajxpNode->getUrl()));
     if (isset($entries[$fileId])) {
         $ajxpNode->mergeMetadata($entries[$fileId]);
     }
 }
 /**
  * We have to override the standard copyOrMoveFile, as feof() does
  * not seem to work with ssh2.ftp stream... 
  * Maybe something to search hear http://www.mail-archive.com/php-general@lists.php.net/msg169992.html?
  *
  * @param string $destDir
  * @param string $srcFile
  * @param array $error
  * @param array $success
  * @param boolean $move
  */
 function copyOrMoveFile($destDir, $srcFile, &$error, &$success, $move = false)
 {
     $mess = ConfService::getMessages();
     $destFile = $this->urlBase . $destDir . "/" . basename($srcFile);
     $realSrcFile = $this->urlBase . $srcFile;
     if (!file_exists($realSrcFile)) {
         $error[] = $mess[100] . $srcFile;
         return;
     }
     if (dirname($realSrcFile) == dirname($destFile)) {
         if ($move) {
             $error[] = $mess[101];
             return;
         } else {
             $base = basename($srcFile);
             $i = 1;
             if (is_file($realSrcFile)) {
                 $dotPos = strrpos($base, ".");
                 if ($dotPos > -1) {
                     $radic = substr($base, 0, $dotPos);
                     $ext = substr($base, $dotPos);
                 }
             }
             // auto rename file
             $i = 1;
             $newName = $base;
             while (file_exists($this->urlBase . $destDir . "/" . $newName)) {
                 $suffix = "-{$i}";
                 if (isset($radic)) {
                     $newName = $radic . $suffix . $ext;
                 } else {
                     $newName = $base . $suffix;
                 }
                 $i++;
             }
             $destFile = $this->urlBase . $destDir . "/" . $newName;
         }
     }
     if (!is_file($realSrcFile)) {
         $errors = array();
         $succFiles = array();
         if ($move) {
             if (file_exists($destFile)) {
                 $this->deldir($destFile);
             }
             $res = rename($realSrcFile, $destFile);
         } else {
             $dirRes = $this->dircopy($realSrcFile, $destFile, $errors, $succFiles);
         }
         if (count($errors) || isset($res) && $res !== true) {
             $error[] = $mess[114];
             return;
         }
     } else {
         if ($move) {
             if (file_exists($destFile)) {
                 unlink($destFile);
             }
             $res = rename($realSrcFile, $destFile);
             AJXP_Controller::applyHook("move.metadata", array($realSrcFile, $destFile, false));
         } else {
             try {
                 // BEGIN OVERRIDING
                 list($connection, $remote_base_path) = sftpAccessWrapper::getSshConnection($realSrcFile);
                 $remoteSrc = $remote_base_path . $srcFile;
                 $remoteDest = $remote_base_path . $destDir;
                 AJXP_Logger::debug("SSH2 CP", array("cmd" => 'cp ' . $remoteSrc . ' ' . $remoteDest));
                 ssh2_exec($connection, 'cp ' . $remoteSrc . ' ' . $remoteDest);
                 AJXP_Controller::applyHook("move.metadata", array($realSrcFile, $destFile, true));
                 // END OVERRIDING
             } catch (Exception $e) {
                 $error[] = $e->getMessage();
                 return;
             }
         }
     }
     if ($move) {
         // Now delete original
         // $this->deldir($realSrcFile); // both file and dir
         $messagePart = $mess[74] . " " . SystemTextEncoding::toUTF8($destDir);
         if (RecycleBinManager::recycleEnabled() && $destDir == RecycleBinManager::getRelativeRecycle()) {
             RecycleBinManager::fileToRecycle($srcFile);
             $messagePart = $mess[123] . " " . $mess[122];
         }
         if (isset($dirRes)) {
             $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ") ";
         } else {
             $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $messagePart;
         }
     } else {
         if (RecycleBinManager::recycleEnabled() && $destDir == "/" . $this->repository->getOption("RECYCLE_BIN")) {
             RecycleBinManager::fileToRecycle($srcFile);
         }
         if (isset($dirRes)) {
             $success[] = $mess[117] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir) . " (" . SystemTextEncoding::toUTF8($dirRes) . " " . $mess[116] . ")";
         } else {
             $success[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($srcFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destDir);
         }
     }
 }
Esempio n. 29
0
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     //$urlBase = $this->accessDriver
     $repository = $this->accessDriver->repository;
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $selection = new UserSelection($repository, $httpVars);
     switch ($actionName) {
         case "filehasher_signature":
             $file = $selection->getUniqueNode();
             if (!file_exists($file->getUrl())) {
                 break;
             }
             $cacheItem = AJXP_Cache::getItem("signatures", $file->getUrl(), 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");
             }
             $signature_delta_file = $fileVars["userfile_0"]["tmp_name"];
             $fileUrl = $selection->getUniqueNode()->getUrl();
             $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true);
             if ($actionName == "filehasher_delta") {
                 $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta");
                 $this->logDebug("Received signature file, should compute delta now");
                 rsync_generate_delta($signature_delta_file, $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($deltaFile);
             } else {
                 $patched = $file . ".rdiff_patched";
                 rsync_patch_file($file, $signature_delta_file, $patched);
                 rename($patched, $file);
                 $node = $selection->getUniqueNode();
                 AJXP_Controller::applyHook("node.change", array($node, $node, false));
                 header("Content-Type:text/plain");
                 echo md5_file($file);
             }
             break;
         case "stat_hash":
             clearstatcache();
             header("Content-type:application/json");
             if ($selection->isUnique()) {
                 $node = $selection->getUniqueNode();
                 $stat = @stat($node->getUrl());
                 if (!$stat || !is_readable($node->getUrl())) {
                     print '{}';
                 } else {
                     if (is_file($node->getUrl())) {
                         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());
                         }
                     } 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($selection->currentBaseUrl() . $path);
                     $stat = @stat($selection->currentBaseUrl() . $path);
                     if (!$stat || !is_readable($node->getUrl())) {
                         $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(SystemTextEncoding::toUTF8($path)) . ':' . $stat . ($index < count($files) - 1 ? "," : "");
                 }
                 print '}';
             }
             break;
             break;
     }
 }
Esempio n. 30
0
 /**
  * Replace specific chars by their XML Entities, for use inside attributes value
  * @static
  * @param $string
  * @param bool $toUtf8
  * @return mixed|string
  */
 public static function xmlContentEntities($string, $toUtf8 = false)
 {
     $xmlSafe = str_replace(array("&", "<", ">", "\""), array("&amp;", "&lt;", "&gt;", "&quot;"), $string);
     if ($toUtf8) {
         return SystemTextEncoding::toUTF8($xmlSafe);
     } else {
         return $xmlSafe;
     }
 }