private static function filterActionsRegistry(&$registry)
 {
     if (!AuthService::usersEnabled()) {
         return false;
     }
     $loggedUser = AuthService::getLoggedUser();
     if ($loggedUser == null) {
         return false;
     }
     $crtRepo = ConfService::getRepository();
     $crtRepoId = "ajxp.all";
     if ($crtRepo != null && is_a($crtRepo, "Repository")) {
         $crtRepoId = $crtRepo->getId();
     }
     $actionRights = $loggedUser->getSpecificActionsRights($crtRepoId);
     $changes = false;
     $xPath = new DOMXPath($registry);
     foreach ($actionRights as $actionName => $enabled) {
         if ($enabled !== false) {
             continue;
         }
         $actions = $xPath->query("actions/action[@name='{$actionName}']");
         if (!$actions->length) {
             continue;
         }
         $action = $actions->item(0);
         $action->parentNode->removeChild($action);
         $changes = true;
     }
     return $changes;
 }
예제 #2
0
 public function applyAction($actionName, $httpVars, $fileVars)
 {
     $messages = ConfService::getMessages();
     if ($actionName == "index") {
         $repository = ConfService::getRepository();
         $repositoryId = $repository->getId();
         $userSelection = new UserSelection($repository, $httpVars);
         if ($userSelection->isEmpty()) {
             $userSelection->addFile("/");
         }
         $nodes = $userSelection->buildNodes($repository->driverInstance);
         if (isset($httpVars["verbose"]) && $httpVars["verbose"] == "true") {
             $this->verboseIndexation = true;
         }
         if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
             AJXP_Controller::applyActionInBackground($repositoryId, "index", $httpVars);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $repositoryId), sprintf($messages["core.index.8"], $nodes[0]->getPath()), true, 2);
             if (!isset($httpVars["inner_apply"])) {
                 AJXP_XMLWriter::close();
             }
             return null;
         }
         // GIVE BACK THE HAND TO USER
         session_write_close();
         foreach ($nodes as $node) {
             $dir = $node->getPath() == "/" || is_dir($node->getUrl());
             // SIMPLE FILE
             if (!$dir) {
                 try {
                     $this->logDebug("Indexing - node.index " . $node->getUrl());
                     AJXP_Controller::applyHook("node.index", array($node));
                 } catch (Exception $e) {
                     $this->logDebug("Error Indexing Node " . $node->getUrl() . " (" . $e->getMessage() . ")");
                 }
             } else {
                 try {
                     $this->recursiveIndexation($node);
                 } catch (Exception $e) {
                     $this->logDebug("Indexation of " . $node->getUrl() . " interrupted by error: (" . $e->getMessage() . ")");
                 }
             }
         }
     } else {
         if ($actionName == "check_index_status") {
             $repoId = $httpVars["repository_id"];
             list($status, $message) = $this->getIndexStatus(ConfService::getRepositoryById($repoId), AuthService::getLoggedUser());
             if (!empty($status)) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("check_index_status", array("repository_id" => $repoId), $message, true, 3);
                 AJXP_XMLWriter::close();
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("info_message", array(), $messages["core.index.5"], true, 5);
                 AJXP_XMLWriter::close();
             }
         }
     }
     return null;
 }
 function init($options)
 {
     parent::init($options);
     $pServ = AJXP_PluginsService::getInstance();
     $aPlugs = $pServ->getActivePlugins();
     $accessPlugs = $pServ->getPluginsByType("access");
     $this->repository = ConfService::getRepository();
     foreach ($accessPlugs as $pId => $plug) {
         if (array_key_exists("access." . $pId, $aPlugs) && $aPlugs["access." . $pId] === true) {
             $this->accessDriver = $plug;
             if (!isset($this->accessDriver->repository)) {
                 $this->accessDriver->init($this->repository);
                 $this->accessDriver->initRepository();
                 $wrapperData = $this->accessDriver->detectStreamWrapper(true);
             } else {
                 $wrapperData = $this->accessDriver->detectStreamWrapper(false);
             }
             $this->urlBase = $wrapperData["protocol"] . "://" . $this->repository->getId();
         }
     }
     $this->metaStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("metastore");
     if ($this->metaStore !== false) {
         $this->metaStore->initMeta($this->accessDriver);
     }
 }
 public function postProcess($action, $httpVars, $postProcessData)
 {
     if (self::$skipDecoding) {
     }
     if (!isset($httpVars["partitionRealName"])) {
         return;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $httpVars["dir"] . "/";
     $count = intval($httpVars["partitionCount"]);
     $index = intval($httpVars["partitionIndex"]);
     $fileId = $httpVars["fileId"];
     $clientId = $httpVars["clientId"];
     AJXP_Logger::debug("Should now rebuild file!", $httpVars);
     $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w");
     for ($i = 0; $i < $count; $i++) {
         $part = fopen($destStreamURL . "{$clientId}.{$fileId}.{$i}", "r");
         while (!feof($part)) {
             fwrite($newDest, fread($part, 4096));
         }
         fclose($part);
         unlink($destStreamURL . "{$clientId}.{$fileId}.{$i}");
     }
     fclose($newDest);
 }
 public function unifyChunks($action, $httpVars, $fileVars)
 {
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $filename = AJXP_Utils::decodeSecureMagic($httpVars["file_name"]);
     $chunks = array();
     $index = 0;
     while (isset($httpVars["chunk_" . $index])) {
         $chunks[] = AJXP_Utils::decodeSecureMagic($httpVars["chunk_" . $index]);
         $index++;
     }
     $newDest = fopen($destStreamURL . $filename, "w");
     for ($i = 0; $i < count($chunks); $i++) {
         $part = fopen($destStreamURL . $chunks[$i], "r");
         while (!feof($part)) {
             fwrite($newDest, fread($part, 4096));
         }
         fclose($part);
         unlink($destStreamURL . $chunks[$i]);
     }
     fclose($newDest);
 }
예제 #6
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (!isset($this->pluginConf)) {
         $this->pluginConf = array("GENERATE_THUMBNAIL" => false);
     }
     $streamData = $repository->streamData;
     $this->streamData = $streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "preview_data_proxy") {
         $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
         if (!file_exists($destStreamURL . $file)) {
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: 0");
             return;
         }
         if (isset($httpVars["get_thumb"]) && $this->getFilteredOption("GENERATE_THUMBNAIL", $repository->getId())) {
             $dimension = 200;
             if (isset($httpVars["dimension"]) && is_numeric($httpVars["dimension"])) {
                 $dimension = $httpVars["dimension"];
             }
             $this->currentDimension = $dimension;
             $cacheItem = AJXP_Cache::getItem("diaporama_" . $dimension, $destStreamURL . $file, array($this, "generateThumbnail"));
             $data = $cacheItem->getData();
             $cId = $cacheItem->getId();
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($cId)) . "; name=\"" . basename($cId) . "\"");
             header("Content-Length: " . strlen($data));
             header('Cache-Control: public');
             header("Pragma:");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
             header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
             print $data;
         } else {
             //$filesize = filesize($destStreamURL.$file);
             $node = new AJXP_Node($destStreamURL . $file);
             $fp = fopen($destStreamURL . $file, "r");
             $stat = fstat($fp);
             $filesize = $stat["size"];
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: " . $filesize);
             header('Cache-Control: public');
             header("Pragma:");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
             header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
             $class = $streamData["classname"];
             $stream = fopen("php://output", "a");
             call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
             fflush($stream);
             fclose($stream);
             AJXP_Controller::applyHook("node.read", array($node));
         }
     }
 }
예제 #7
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "post_to_server") {
         $file = base64_decode(AJXP_Utils::decodeSecureMagic($httpVars["file"]));
         $target = base64_decode($httpVars["parent_url"]) . "/plugins/editor.pixlr";
         $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file);
         $fData = array("tmp_name" => $tmp, "name" => urlencode(basename($file)), "type" => "image/jpg");
         $httpClient = new HttpClient("pixlr.com");
         //$httpClient->setDebug(true);
         $postData = array();
         $httpClient->setHandleRedirects(false);
         $params = array("referrer" => "AjaXplorer", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $target . "/fake_save_pixlr.php", "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($file)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source");
         $httpClient->postFile("/editor/", $params, "image", $fData);
         $loc = $httpClient->getHeader("location");
         header("Location:{$loc}");
     } else {
         if ($action == "retrieve_pixlr_image") {
             $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]);
             $url = $httpVars["new_url"];
             $urlParts = parse_url($url);
             $query = $urlParts["query"];
             $params = array();
             $parameters = parse_str($query, $params);
             $image = $params['image'];
             /*
             $type = $params['type'];
             $state = $params['state'];
             $filename = $params['title'];		
             */
             if (strpos($image, "pixlr.com") == 0) {
                 throw new AJXP_Exception("Invalid Referrer");
             }
             $headers = get_headers($image, 1);
             $content_type = explode("/", $headers['Content-Type']);
             if ($content_type[0] != "image") {
                 throw new AJXP_Exception("File Type");
             }
             $orig = fopen($image, "r");
             $target = fopen($destStreamURL . $file, "w");
             while (!feof($orig)) {
                 fwrite($target, fread($orig, 4096));
             }
             fclose($orig);
             fclose($target);
             header("Content-Type:text/plain");
             print $mess[115];
         }
     }
     return;
 }
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     //$urlBase = $this->accessDriver
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (!isset($this->pluginConf)) {
         $this->pluginConf = array("GENERATE_THUMBNAIL" => false);
     }
     $streamData = $repository->streamData;
     $this->streamData = $streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     switch ($actionName) {
         case "filehasher_signature":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             if (!file_exists($destStreamURL . $file)) {
                 break;
             }
             $cacheItem = AJXP_Cache::getItem("signatures", $destStreamURL . $file, array($this, "generateSignature"));
             $data = $cacheItem->getData();
             header("Content-Type:application/octet-stream");
             header("Content-Length", strlen($data));
             echo $data;
             break;
         case "filehasher_delta":
         case "filehasher_patch":
             // HANDLE UPLOAD DATA
             if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) {
                 throw new Exception("These action should find uploaded data");
             }
             $uploadedData = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-sig");
             move_uploaded_file($fileVars["userfile_0"]["tmp_name"], $uploadedData);
             $fileUrl = $destStreamURL . AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $file = call_user_func(array($this->streamData["classname"], "getRealFSReference"), $fileUrl, true);
             if ($actionName == "filehasher_delta") {
                 $signatureFile = $uploadedData;
                 $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta");
                 rsync_generate_delta($signatureFile, $file, $deltaFile);
                 header("Content-Type:application/octet-stream");
                 header("Content-Length:" . filesize($deltaFile));
                 readfile($deltaFile);
                 unlink($signatureFile);
                 unlink($deltaFile);
             } else {
                 $patched = $file . ".rdiff_patched";
                 $deltaFile = $uploadedData;
                 rsync_patch_file($file, $deltaFile, $patched);
                 rename($patched, $file);
                 header("Content-Type:text/plain");
                 unlink($deltaFile);
                 echo md5_file($file);
             }
             break;
     }
 }
예제 #9
0
 public function switchAction($action, $httpVars, $postProcessData)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . "/";
     if ($action == "audio_proxy") {
         $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
         $cType = "audio/" . array_pop(explode(".", $file));
         $localName = basename($file);
         header("Content-Type: " . $cType . "; name=\"" . $localName . "\"");
         header("Content-Length: " . filesize($destStreamURL . $file));
         $stream = fopen("php://output", "a");
         call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
         fflush($stream);
         fclose($stream);
         $node = new AJXP_Node($destStreamURL . $file);
         AJXP_Controller::applyHook("node.read", array($node));
         //exit(1);
     } else {
         if ($action == "ls") {
             if (!isset($httpVars["playlist"])) {
                 // This should not happen anyway, because of the applyCondition.
                 AJXP_Controller::passProcessDataThrough($postProcessData);
                 return;
             }
             // We transform the XML into XSPF
             $xmlString = $postProcessData["ob_output"];
             $xmlDoc = new DOMDocument();
             $xmlDoc->loadXML($xmlString);
             $xElement = $xmlDoc->documentElement;
             header("Content-Type:application/xspf+xml;charset=UTF-8");
             print '<?xml version="1.0" encoding="UTF-8"?>';
             print '<playlist version="1" xmlns="http://xspf.org/ns/0/">';
             print "<trackList>";
             foreach ($xElement->childNodes as $child) {
                 $isFile = $child->getAttribute("is_file") == "true";
                 $label = $child->getAttribute("text");
                 $ar = explode(".", $label);
                 $ext = strtolower(end($ar));
                 if (!$isFile || $ext != "mp3") {
                     continue;
                 }
                 print "<track><location>" . AJXP_SERVER_ACCESS . "?secure_token=" . AuthService::getSecureToken() . "&get_action=audio_proxy&file=" . base64_encode($child->getAttribute("filename")) . "</location><title>" . $label . "</title></track>";
             }
             print "</trackList>";
             AJXP_XMLWriter::close("playlist");
         }
     }
 }
 public function initMeta($accessDriver)
 {
     require_once "VersionControl/Git.php";
     $repo = ConfService::getRepository();
     $this->repoBase = $repo->getOption("PATH");
     if (!is_dir($this->repoBase . DIRECTORY_SEPARATOR . ".git")) {
         $git = new VersionControl_Git($this->repoBase);
         $git->initRepository();
     }
 }
예제 #11
0
 /**
  * Check the current user "specificActionsRights" and filter the full registry actions with these.
  * @static
  * @param DOMDocument $registry
  * @return bool
  */
 public static function filterRegistryFromRole(&$registry)
 {
     if (!AuthService::usersEnabled()) {
         return false;
     }
     $loggedUser = AuthService::getLoggedUser();
     if ($loggedUser == null) {
         return false;
     }
     $crtRepo = ConfService::getRepository();
     $crtRepoId = AJXP_REPO_SCOPE_ALL;
     // "ajxp.all";
     if ($crtRepo != null && is_a($crtRepo, "Repository")) {
         $crtRepoId = $crtRepo->getId();
     }
     $actionRights = $loggedUser->mergedRole->listActionsStatesFor($crtRepo);
     $changes = false;
     $xPath = new DOMXPath($registry);
     foreach ($actionRights as $pluginName => $actions) {
         foreach ($actions as $actionName => $enabled) {
             if ($enabled !== false) {
                 continue;
             }
             $actions = $xPath->query("actions/action[@name='{$actionName}']");
             if (!$actions->length) {
                 continue;
             }
             $action = $actions->item(0);
             $action->parentNode->removeChild($action);
             $changes = true;
         }
     }
     $parameters = $loggedUser->mergedRole->listParameters();
     foreach ($parameters as $scope => $paramsPlugs) {
         if ($scope == AJXP_REPO_SCOPE_ALL || $scope == $crtRepoId || $crtRepo != null && $crtRepo->hasParent() && $scope == AJXP_REPO_SCOPE_SHARED) {
             foreach ($paramsPlugs as $plugId => $params) {
                 foreach ($params as $name => $value) {
                     // Search exposed plugin_configs, replace if necessary.
                     $searchparams = $xPath->query("plugins/*[@id='{$plugId}']/plugin_configs/property[@name='{$name}']");
                     if (!$searchparams->length) {
                         continue;
                     }
                     $param = $searchparams->item(0);
                     $newCdata = $registry->createCDATASection(json_encode($value));
                     $param->removeChild($param->firstChild);
                     $param->appendChild($newCdata);
                 }
             }
         }
     }
     return $changes;
 }
 protected function updateMetaShort($file, $shortUrl)
 {
     $metaStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("metastore");
     if ($metaStore !== false) {
         $driver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
         $metaStore->initMeta($driver);
         $streamData = $driver->detectStreamWrapper(false);
         $baseUrl = $streamData["protocol"] . "://" . ConfService::getRepository()->getId();
         $node = new AJXP_Node($baseUrl . $file);
         $metadata = $metaStore->retrieveMetadata($node, "ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY);
         $metadata["short_form_url"] = $shortUrl;
         $metaStore->setMetadata($node, "ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY);
     }
 }
예제 #13
0
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     require_once AJXP_BIN_FOLDER . "/dibi.compact.php";
     dibi::connect($this->sqlDriver);
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $res = dibi::query("SELECT\n                [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n                FROM [ajxp_changes]\n                LEFT JOIN [ajxp_index]\n                    ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n                WHERE [ajxp_changes].[repository_identifier] = %s AND [seq] > %i\n                ORDER BY [ajxp_changes].[node_id], [seq] ASC", $this->computeIdentifier(ConfService::getRepository()), AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     echo '{"changes":[';
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if ($row->node_id == $previousNodeId) {
             $previousRow->target = $row->target;
             $previousRow->seq = $row->seq;
             if ($order[$row->type] > $order[$previousRow->type]) {
                 $previousRow->type = $row->type;
             }
         } else {
             if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                 echo json_encode($previousRow) . ",";
             }
             $previousRow = $row;
             $previousNodeId = $row->node_id;
         }
         $lastSeq = $row->seq;
         flush();
     }
     if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
         echo json_encode($previousRow);
     }
     if (isset($lastSeq)) {
         echo '], "last_seq":' . $lastSeq . '}';
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         echo '], "last_seq":' . $lastSeq . '}';
     }
 }
예제 #14
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (!isset($this->pluginConf)) {
         $this->pluginConf = array("GENERATE_THUMBNAIL" => false);
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "preview_data_proxy") {
         $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
         if (isset($httpVars["get_thumb"]) && $this->pluginConf["GENERATE_THUMBNAIL"]) {
             require_once INSTALL_PATH . "/plugins/editor.diaporama/PThumb.lib.php";
             $pThumb = new PThumb($this->pluginConf["THUMBNAIL_QUALITY"]);
             if (!$pThumb->isError()) {
                 $pThumb->remote_wrapper = $streamData["classname"];
                 $pThumb->use_cache = $this->pluginConf["USE_THUMBNAIL_CACHE"];
                 $pThumb->cache_dir = $this->pluginConf["THUMBNAIL_CACHE_DIR"];
                 $pThumb->fit_thumbnail($destStreamURL . $file, 200);
                 if ($pThumb->isError()) {
                     print_r($pThumb->error_array);
                     AJXP_Logger::logAction("error", $pThumb->error_array);
                 }
                 //exit(0);
             } else {
                 print_r($pThumb->error_array);
                 AJXP_Logger::logAction("error", $pThumb->error_array);
             }
         } else {
             $filesize = filesize($destStreamURL . $file);
             $fp = fopen($destStreamURL . $file, "r");
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: " . $filesize);
             header('Cache-Control: public');
             $class = $streamData["classname"];
             $stream = fopen("php://output", "a");
             call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
             fflush($stream);
             fclose($stream);
             //exit(1);
         }
     }
 }
 public function __construct($repository)
 {
     $repositoryId = $repository->isWriteable() ? $repository->getUniqueId() : $repository->getId();
     ConfService::switchRootDir($repositoryId);
     $this->repository = ConfService::getRepository();
     $this->options = new ezcWebdavFileBackendOptions();
     $this->options['noLock'] = false;
     $this->options['waitForLock'] = 200000;
     $this->options['lockTimeout'] = 2;
     $this->options['lockFileName'] = '.ezc_lock';
     $this->options['propertyStoragePath'] = '.ezc';
     $this->options['directoryMode'] = 0755;
     $this->options['fileMode'] = 0644;
     $this->options['useMimeExts'] = false;
     $this->options['hideDotFiles'] = true;
 }
 public function initPath($ajxpPath)
 {
     if (empty(self::$dropbox)) {
         $repo = ConfService::getRepository();
         $consumerKey = $repo->getOption('CONSUMER_KEY');
         $consumerSecret = $repo->getOption('CONSUMER_SECRET');
         $email = $repo->getOption('USER');
         $pass = $repo->getOption("PASS");
         self::$oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);
         self::$oauth->setToken($_SESSION["OAUTH_DROPBOX_TOKENS"]);
         self::$dropbox = new Dropbox_API(self::$oauth);
     }
     $path = parse_url($ajxpPath, PHP_URL_PATH);
     if ($path == "") {
         return "/";
     }
     return $path;
 }
예제 #17
0
 protected function updateMetaShort($file, $elementId, $shortUrl)
 {
     $driver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
     $streamData = $driver->detectStreamWrapper(false);
     $baseUrl = $streamData["protocol"] . "://" . ConfService::getRepository()->getId();
     $node = new AJXP_Node($baseUrl . $file);
     if ($node->hasMetaStore()) {
         $metadata = $node->retrieveMetadata("ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY);
         if ($elementId != -1) {
             if (!is_array($metadata["element"][$elementId])) {
                 $metadata["element"][$elementId] = array();
             }
             $metadata["element"][$elementId]["short_form_url"] = $shortUrl;
         } else {
             $metadata['short_form_url'] = $shortUrl;
         }
         $node->setMetadata("ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY);
     }
 }
 public function mountFS()
 {
     list($user, $password) = $this->getCredentials();
     AJXP_Logger::debug("FSMounter::mountFS Should mount" . $user);
     $repo = ConfService::getRepository();
     $MOUNT_TYPE = $this->options["FILESYSTEM_TYPE"];
     $MOUNT_SUDO = $this->options["MOUNT_SUDO"];
     $MOUNT_POINT = $this->getOption("MOUNT_POINT", $user, $password);
     $MOUNT_POINT_ROOT = $this->getOption("MOUNT_POINT", "", "");
     $create = $repo->getOption("CREATE");
     if ($MOUNT_POINT != $MOUNT_POINT_ROOT && !is_dir($MOUNT_POINT_ROOT) && $create) {
         @mkdir($MOUNT_POINT_ROOT, 0755);
     }
     $recycle = false;
     if (!is_dir($MOUNT_POINT) && $create) {
         @mkdir($MOUNT_POINT, 0755);
     } else {
         if ($repo->getOption("RECYCLE_BIN") != "") {
             // Make sure the recycle bin was not mounted inside the mount point!
             $recycle = $repo->getOption("PATH") . "/" . $repo->getOption("RECYCLE_BIN");
             if (@is_dir($recycle)) {
                 @rmdir($recycle);
             }
         }
     }
     $UNC_PATH = $this->getOption("UNC_PATH", $user, $password);
     $MOUNT_OPTIONS = $this->getOption("MOUNT_OPTIONS", $user, $password);
     $cmd = ($MOUNT_SUDO ? "sudo" : "") . " mount -t " . $MOUNT_TYPE . " " . $UNC_PATH . " " . $MOUNT_POINT . " -o " . $MOUNT_OPTIONS;
     shell_exec($cmd);
     // Check it is correctly mounted now!
     $cmd = ($MOUNT_SUDO ? "sudo" : "") . " mount | grep " . escapeshellarg($MOUNT_POINT);
     $output = shell_exec($cmd);
     if ($output == null || trim($output) == "") {
         throw new Exception("Error while mounting file system - Test was " . $cmd);
     } else {
         if (!is_file($MOUNT_POINT . "/.ajxp_mount")) {
             @file_put_contents($MOUNT_POINT . "/.ajxp_mount", "");
         }
         if ($recycle !== false && !is_dir($recycle)) {
             @mkdir($recycle, 0755);
         }
     }
 }
 function svnDownload($actionName, $httpVars, $filesVars)
 {
     $sessionId = "";
     $crtRep = ConfService::getRepository();
     $httpClient = $this->getRemoteConnexion($sessionId);
     $httpVars["ajxp_sessid"] = $sessionId;
     $method = "get";
     if ($method == "get") {
         $httpClient->get($crtRep->getOption("URI"), $httpVars);
     } else {
         $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") {
             $httpClient->get($crtRep->getOption("URI"), $httpVars);
         } else {
             $httpClient->post($crtRep->getOption("URI"), $httpVars);
         }
     }
     $size = strlen($httpClient->content);
     $filePath = $httpVars["file"];
     $svnFileName = $httpClient->getHeader("AjaXplorer-SvnFileName");
     header("Content-Type: application/force-download; name=\"" . $svnFileName . "\"");
     header("Content-Transfer-Encoding: binary");
     header("Content-Length: " . $size);
     header("Content-Disposition: attachment; filename=\"" . $svnFileName . "\"");
     header("Expires: 0");
     header("Cache-Control: no-cache, must-revalidate");
     header("Pragma: no-cache");
     // For SSL websites, bug with IE see article KB 323308
     if (ConfService::getConf("USE_HTTPS") == 1 && preg_match('/ MSIE /', $_SERVER['HTTP_USER_AGENT'])) {
         header("Cache-Control:");
         header("Pragma:");
     }
     print $httpClient->getContent();
     session_write_close();
     exit;
 }
예제 #20
0
 public function initPath($ajxpPath)
 {
     $repo = ConfService::getRepository();
     if (empty(self::$dropbox)) {
         $consumerKey = $repo->getOption('CONSUMER_KEY');
         $consumerSecret = $repo->getOption('CONSUMER_SECRET');
         self::$oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret);
         self::$oauth->setToken($_SESSION["OAUTH_DROPBOX_TOKENS"]);
         self::$dropbox = new Dropbox_API(self::$oauth);
     }
     $basePath = $repo->getOption("PATH");
     if (empty($basePath)) {
         $basePath = "";
     }
     $parts = AJXP_Utils::safeParseUrl($ajxpPath);
     $path = $basePath . "/" . ltrim($parts["path"], "/");
     if ($path == "") {
         return "/";
     }
     return $path;
 }
예제 #21
0
 protected function updateMetaShort($file, $elementId, $shortUrl)
 {
     $context = new UserSelection(ConfService::getRepository());
     $baseUrl = $context->currentBaseUrl();
     $node = new AJXP_Node($baseUrl . $file);
     if ($node->hasMetaStore()) {
         $metadata = $node->retrieveMetadata("ajxp_shared", true, AJXP_METADATA_SCOPE_REPOSITORY);
         if ($elementId != -1) {
             if (!is_array($metadata["element"][$elementId])) {
                 $metadata["element"][$elementId] = array();
             }
             $metadata["element"][$elementId]["short_form_url"] = $shortUrl;
         } else {
             if (isset($metadata["shares"])) {
                 $key = array_pop(array_keys($metadata["shares"]));
                 $metadata["shares"][$key]["short_form_url"] = $shortUrl;
             } else {
                 $metadata['short_form_url'] = $shortUrl;
             }
         }
         $node->setMetadata("ajxp_shared", $metadata, true, AJXP_METADATA_SCOPE_REPOSITORY);
     }
 }
 public function preProcess($action, &$httpVars, &$fileVars)
 {
     $repository = ConfService::getRepository();
     $skipDecoding = false;
     if ($repository->detectStreamWrapper(false)) {
         $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
         $streamData = $plugin->detectStreamWrapper(true);
         if ($streamData["protocol"] == "ajxp.ftp" || $streamData["protocol"] == "ajxp.remotefs") {
             AJXP_Logger::debug("Skip decoding");
             $skipDecoding = true;
         }
     }
     if (isset($fileVars["Filedata"])) {
         self::$active = true;
         AJXP_Logger::debug("Dir before base64", $httpVars);
         $httpVars["dir"] = base64_decode(urldecode($httpVars["dir"]));
         if (!$skipDecoding) {
             $fileVars["Filedata"]["name"] = SystemTextEncoding::fromUTF8($fileVars["Filedata"]["name"]);
         }
         $fileVars["userfile_0"] = $fileVars["Filedata"];
         unset($fileVars["Filedata"]);
         AJXP_Logger::debug("Setting FlexProc active");
     }
 }
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     if ($actionName != "changes" || !isset($httpVars["seq_id"])) {
         return false;
     }
     if (!dibi::isConnected()) {
         dibi::connect($this->sqlDriver);
     }
     $filter = null;
     $masks = array();
     $currentRepo = $this->accessDriver->repository;
     AJXP_Controller::applyHook("role.masks", array($currentRepo->getId(), &$masks, AJXP_Permission::READ));
     $recycle = $currentRepo->getOption("RECYCLE_BIN");
     $recycle = !empty($recycle) ? $recycle : false;
     if ($this->options["OBSERVE_STORAGE_CHANGES"] === true) {
         // Do it every XX minutes
         $minutes = 5;
         if (isset($this->options["OBSERVE_STORAGE_EVERY"])) {
             $minutes = intval($this->options["OBSERVE_STORAGE_EVERY"]);
         }
         $file = $this->getResyncTimestampFile();
         $last = 0;
         if (is_file($file)) {
             $last = intval(file_get_contents($file));
         }
         if (time() - $last > $minutes * 60) {
             $this->resyncAction("resync_storage", array(), array());
         }
     }
     if ($this->options["REQUIRES_INDEXATION"]) {
         if (ConfService::backgroundActionsSupported()) {
             AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), "index", array());
         } else {
             AJXP_Controller::findActionAndApply("index", array(), array());
         }
         // Unset the REQUIRES_INDEXATION FLAG
         $meta = $currentRepo->getOption("META_SOURCES");
         unset($meta["meta.syncable"]["REQUIRES_INDEXATION"]);
         $currentRepo->addOption("META_SOURCES", $meta);
         ConfService::replaceRepository($currentRepo->getId(), $currentRepo);
     }
     HTMLWriter::charsetHeader('application/json', 'UTF-8');
     $stream = isset($httpVars["stream"]);
     $separator = $stream ? "\n" : ",";
     $veryLastSeq = intval(dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle());
     $seqId = intval(AJXP_Utils::sanitize($httpVars["seq_id"], AJXP_SANITIZE_ALPHANUM));
     if ($veryLastSeq > 0 && $seqId > $veryLastSeq) {
         // This is not normal! Send a signal reload all changes from start.
         if (!$stream) {
             echo json_encode(array('changes' => array(), 'last_seq' => 1));
         } else {
             echo 'LAST_SEQ:1';
         }
         return null;
     }
     $ands = array();
     $ands[] = array("[ajxp_changes].[repository_identifier] = %s", $this->computeIdentifier($currentRepo));
     $ands[] = array("[seq] > %i", $seqId);
     if (isset($httpVars["filter"])) {
         $filter = AJXP_Utils::decodeSecureMagic($httpVars["filter"]);
         $filterLike = rtrim($filter, "/") . "/";
         $ands[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
     }
     if (count($masks)) {
         $ors = array();
         foreach ($masks as $mask) {
             $filterLike = rtrim($mask, "/") . "/";
             $ors[] = array("[source] LIKE %like~ OR [target] LIKE %like~", $filterLike, $filterLike);
         }
         if (count($ors)) {
             $ands[] = array("%or", $ors);
         }
     }
     $res = dibi::query("SELECT\n            [seq] , [ajxp_changes].[repository_identifier] , [ajxp_changes].[node_id] , [type] , [source] ,  [target] , [ajxp_index].[bytesize], [ajxp_index].[md5], [ajxp_index].[mtime], [ajxp_index].[node_path]\n            FROM [ajxp_changes]\n            LEFT JOIN [ajxp_index]\n                ON [ajxp_changes].[node_id] = [ajxp_index].[node_id]\n            WHERE %and\n            ORDER BY [ajxp_changes].[node_id], [seq] ASC", $ands);
     if (!$stream) {
         echo '{"changes":[';
     }
     $previousNodeId = -1;
     $previousRow = null;
     $order = array("path" => 0, "content" => 1, "create" => 2, "delete" => 3);
     $relocateAttrs = array("bytesize", "md5", "mtime", "node_path", "repository_identifier");
     $valuesSent = false;
     foreach ($res as $row) {
         $row->node = array();
         foreach ($relocateAttrs as $att) {
             $row->node[$att] = $row->{$att};
             unset($row->{$att});
         }
         if (!empty($recycle)) {
             $this->cancelRecycleNodes($row, $recycle);
         }
         if (!isset($httpVars["flatten"]) || $httpVars["flatten"] == "false") {
             if (!$this->filterMasks($row, $masks) && !$this->filterRow($row, $filter)) {
                 if ($valuesSent) {
                     echo $separator;
                 }
                 echo json_encode($row);
                 $valuesSent = true;
             }
         } else {
             if ($row->node_id == $previousNodeId) {
                 $previousRow->target = $row->target;
                 $previousRow->seq = $row->seq;
                 if ($order[$row->type] > $order[$previousRow->type]) {
                     $previousRow->type = $row->type;
                 }
             } else {
                 if (isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content")) {
                     if ($this->filterMasks($previousRow, $masks) || $this->filterRow($previousRow, $filter)) {
                         $previousRow = $row;
                         $previousNodeId = $row->node_id;
                         $lastSeq = $row->seq;
                         continue;
                     }
                     if ($valuesSent) {
                         echo $separator;
                     }
                     echo json_encode($previousRow);
                     $valuesSent = true;
                 }
                 $previousRow = $row;
                 $previousNodeId = $row->node_id;
             }
             $lastSeq = $row->seq;
             flush();
         }
         //CODES HERE HAVE BEEN MOVE OUT OF THE LOOP
     }
     /**********RETURN TO SENDER************/
     // is 'not NULL' included in isSet()?
     if ($previousRow && isset($previousRow) && ($previousRow->source != $previousRow->target || $previousRow->type == "content") && !$this->filterRow($previousRow, $filter)) {
         if ($valuesSent) {
             echo $separator;
         }
         echo json_encode($previousRow);
         if ($previousRow->seq > $lastSeq) {
             $lastSeq = $previousRow->seq;
         }
         $valuesSent = true;
     }
     /*************************************/
     if (isset($lastSeq)) {
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     } else {
         $lastSeq = dibi::query("SELECT MAX([seq]) FROM [ajxp_changes]")->fetchSingle();
         if (empty($lastSeq)) {
             $lastSeq = 1;
         }
         if ($stream) {
             echo "\nLAST_SEQ:" . $lastSeq;
         } else {
             echo '], "last_seq":' . $lastSeq . '}';
         }
     }
     return null;
 }
예제 #24
0
 public function switchAction($actionName, $httpVars, $fileVars)
 {
     $this->baseURL = rtrim($this->getFilteredOption("ETHERPAD_SERVER"), "/");
     $this->apiKey = $this->getFilteredOption("ETHERPAD_APIKEY");
     $userSelection = new UserSelection(ConfService::getRepository(), $httpVars);
     if ($userSelection->isEmpty()) {
         throw new Exception("Empty selection");
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $selectedNode = $userSelection->getUniqueNode();
     $selectedNode->loadNodeInfo();
     if (!$selectedNode->isLeaf()) {
         throw new Exception("Cannot handle folders, please select a file!");
     }
     $nodeExtension = strtolower(pathinfo($selectedNode->getPath(), PATHINFO_EXTENSION));
     // Determine pad ID
     if ($nodeExtension == "pad") {
         $padID = file_get_contents($selectedNode->getUrl());
     } else {
         // TRY TO LOAD PAD ID FROM NODE SHARED METADATA
         $metadata = $selectedNode->retrieveMetadata("etherpad", AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         if (isset($metadata["pad_id"])) {
             $padID = $metadata["pad_id"];
         } else {
             $padID = AJXP_Utils::generateRandomString();
             $selectedNode->setMetadata("etherpad", array("pad_id" => $padID), AJXP_METADATA_ALLUSERS, AJXP_METADATA_SCOPE_GLOBAL, false);
         }
     }
     require_once "etherpad-client/etherpad-lite-client.php";
     $client = new EtherpadLiteClient($this->apiKey, $this->baseURL . "/api");
     $loggedUser = AuthService::getLoggedUser();
     $userName = $loggedUser->getId();
     $userLabel = $loggedUser->mergedRole->filterParameterValue("core.conf", "USER_DISPLAY_NAME", AJXP_REPO_SCOPE_ALL, $userName);
     $res = $client->createAuthorIfNotExistsFor($userName, $userLabel);
     $authorID = $res->authorID;
     $res2 = $client->createGroupIfNotExistsFor($loggedUser->getGroupPath());
     $groupID = $res2->groupID;
     $fullId = $groupID . "\$" . $padID;
     if ($actionName == "etherpad_create") {
         $resP = $client->listPads($groupID);
         $currentContent = file_get_contents($selectedNode->getUrl());
         if ($nodeExtension == "html" && strpos($currentContent, "<html>") === false) {
             $currentContent = "<html><head></head><body>{$currentContent}</body></html>";
         }
         if (!in_array($fullId, $resP->padIDs)) {
             $client->createGroupPad($groupID, $padID, null);
             if ($nodeExtension == "html" && !empty($currentContent)) {
                 $client->setHTML($fullId, $currentContent);
             } else {
                 if ($nodeExtension != "pad") {
                     $client->setText($fullId, $currentContent);
                 }
             }
         } else {
             if ($nodeExtension != "pad") {
                 // If someone is already connected, do not override.
                 $existingAuthors = $client->listAuthorsOfPad($fullId);
                 if (!count($existingAuthors->authorIDs)) {
                     if ($nodeExtension == "html" && !empty($currentContent)) {
                         $client->setHTML($fullId, $currentContent);
                     } else {
                         $client->setText($fullId, $currentContent);
                     }
                 }
             }
         }
         $res4 = $client->createSession($groupID, $authorID, time() + 14400);
         $sessionID = $res4->sessionID;
         setcookie('sessionID', $sessionID, null, "/");
         $padID = $groupID . '$' . $padID;
         $data = array("url" => $this->baseURL . "/p/" . $padID, "padID" => $padID, "sessionID" => $sessionID);
         HTMLWriter::charsetHeader('application/json');
         echo json_encode($data);
     } else {
         if ($actionName == "etherpad_save") {
             $padID = $httpVars["pad_id"];
             if ($nodeExtension == "html" || $nodeExtension == "pad") {
                 $res = $client->getHTML($padID);
                 $content = $res->html;
             } else {
                 $res = $client->getText($padID);
                 $content = $res->text;
             }
             if ($nodeExtension == "pad") {
                 // Create a new file and save the content in it.
                 $origUrl = $selectedNode->getUrl();
                 $mess = ConfService::getMessages();
                 $dateStamp = date(" Y-m-d H:i", time());
                 $startUrl = preg_replace('"\\.pad$"', $dateStamp . '.html', $origUrl);
                 $newNode = new AJXP_Node($startUrl);
                 AJXP_Controller::applyHook("node.before_create", array($newNode, strlen($content)));
                 file_put_contents($newNode->getUrl(), $content);
                 AJXP_Controller::applyHook("node.change", array(null, $newNode));
             } else {
                 AJXP_Controller::applyHook("node.before_change", array($selectedNode, strlen($content)));
                 file_put_contents($selectedNode->getUrl(), $content);
                 clearstatcache(true, $selectedNode->getUrl());
                 $selectedNode->loadNodeInfo(true);
                 AJXP_Controller::applyHook("node.change", array($selectedNode, $selectedNode));
             }
         } else {
             if ($actionName == "etherpad_close") {
                 // WE SHOULD DETECT IF THERE IS NOBODY CONNECTED ANYMORE, AND DELETE THE PAD.
                 // BUT SEEMS LIKE THERE'S NO WAY TO PROPERLY REMOVE AN AUTHOR VIA API
                 $sessionID = $httpVars["session_id"];
                 $client->deleteSession($sessionID);
             } else {
                 if ($actionName == "etherpad_proxy_api") {
                     if ($httpVars["api_action"] == "list_pads") {
                         $res = $client->listPads($groupID);
                     } else {
                         if ($httpVars["api_action"] == "list_authors_for_pad") {
                             $res = $client->listAuthorsOfPad($httpVars["pad_id"]);
                         }
                     }
                     HTMLWriter::charsetHeader("application/json");
                     echo json_encode($res);
                 } else {
                     if ($actionName == "etherpad_get_content") {
                         HTMLWriter::charsetHeader("text/plain");
                         echo $client->getText($httpVars["pad_id"])->text;
                     }
                 }
             }
         }
     }
     return null;
 }
 /**
  * @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);
             }
         }
     }
 }
예제 #26
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $convert = $this->getFilteredOption("IMAGE_MAGICK_CONVERT");
     if (empty($convert)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     $flyThreshold = 1024 * 1024 * intval($this->getFilteredOption("ONTHEFLY_THRESHOLD", $repository->getId()));
     $selection = new UserSelection($repository);
     $selection->initFromHttpVars($httpVars);
     if ($action == "imagick_data_proxy") {
         $this->extractAll = false;
         if (isset($httpVars["all"])) {
             $this->extractAll = true;
         }
         $file = $selection->getUniqueFile();
         if (($size = filesize($destStreamURL . $file)) === false) {
             return false;
         } else {
             if ($size > $flyThreshold) {
                 $this->useOnTheFly = true;
             } else {
                 $this->useOnTheFly = false;
             }
         }
         if ($this->extractAll) {
             $node = new AJXP_Node($destStreamURL . $file);
             AJXP_Controller::applyHook("node.read", array($node));
         }
         $cache = AJXP_Cache::getItem("imagick_" . ($this->extractAll ? "full" : "thumb"), $destStreamURL . $file, array($this, "generateJpegsCallback"));
         $cacheData = $cache->getData();
         if (!$this->useOnTheFly && $this->extractAll) {
             // extract all on first view
             $ext = pathinfo($file, PATHINFO_EXTENSION);
             $prefix = str_replace(".{$ext}", "", $cache->getId());
             $files = $this->listExtractedJpg($destStreamURL . $file, $prefix);
             header("Content-Type: application/json");
             print json_encode($files);
             return false;
         } else {
             if ($this->extractAll) {
                 // on the fly extract mode
                 $ext = pathinfo($file, PATHINFO_EXTENSION);
                 $prefix = str_replace(".{$ext}", "", $cache->getId());
                 $files = $this->listPreviewFiles($destStreamURL . $file, $prefix);
                 header("Content-Type: application/json");
                 print json_encode($files);
                 return false;
             } else {
                 header("Content-Type: image/jpeg; name=\"" . basename($file) . "\"");
                 header("Content-Length: " . strlen($cacheData));
                 header('Cache-Control: public');
                 header("Pragma:");
                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
                 print $cacheData;
                 return false;
             }
         }
     } else {
         if ($action == "get_extracted_page" && isset($httpVars["file"])) {
             $file = (defined('AJXP_SHARED_CACHE_DIR') ? AJXP_SHARED_CACHE_DIR : AJXP_CACHE_DIR) . "/imagick_full/" . AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             if (!is_file($file)) {
                 $srcfile = AJXP_Utils::decodeSecureMagic($httpVars["src_file"]);
                 if ($repository->hasContentFilter()) {
                     $contentFilter = $repository->getContentFilter();
                     $srcfile = $contentFilter->filterExternalPath($srcfile);
                 }
                 $size = filesize($destStreamURL . "/" . $srcfile);
                 if ($size > $flyThreshold) {
                     $this->useOnTheFly = true;
                 } else {
                     $this->useOnTheFly = false;
                 }
                 if ($this->useOnTheFly) {
                     $this->onTheFly = true;
                 }
                 $this->generateJpegsCallback($destStreamURL . $srcfile, $file);
             }
             if (!is_file($file)) {
                 return false;
             }
             header("Content-Type: image/jpeg; name=\"" . basename($file) . "\"");
             header("Content-Length: " . filesize($file));
             header('Cache-Control: public');
             readfile($file);
             exit(1);
         } else {
             if ($action == "delete_imagick_data" && !$selection->isEmpty()) {
                 /*
                 $files = $this->listExtractedJpg(AJXP_CACHE_DIR."/".$httpVars["file"]);
                 foreach ($files as $file) {
                     if(is_file(AJXP_CACHE_DIR."/".$file["file"])) unlink(AJXP_CACHE_DIR."/".$file["file"]);
                 }
                 */
             }
         }
     }
 }
 public function 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;
     }
 }
 /**
  * @return HttpClient
  */
 public function getRemoteConnexion(&$remoteSecureToken, $refreshSessId = false, $repository = null)
 {
     require_once AJXP_BIN_FOLDER . "/class.HttpClient.php";
     if ($repository != null) {
         $crtRep = $repository;
     } else {
         $crtRep = ConfService::getRepository();
     }
     $httpClient = new HttpClient($crtRep->getOption("HOST"));
     $httpClient->cookie_host = $crtRep->getOption("HOST");
     $httpClient->timeout = 10;
     if (isset($_SESSION["AJXP_REMOTE_SESSION"]) && is_array($_SESSION["AJXP_REMOTE_SESSION"])) {
         $httpClient->setCookies($_SESSION["AJXP_REMOTE_SESSION"]);
     }
     //$httpClient->setDebug(true);
     if (!isset($_SESSION["AJXP_REMOTE_SECURE_TOKEN"])) {
         $httpClient->get($crtRep->getOption("URI") . "?get_action=get_secure_token");
         $remoteSecureToken = $httpClient->getContent();
         $_SESSION["AJXP_REMOTE_SECURE_TOKEN"] = $remoteSecureToken;
     } else {
         $remoteSecureToken = $_SESSION["AJXP_REMOTE_SECURE_TOKEN"];
     }
     if (!$crtRep->getOption("USE_AUTH")) {
         return $httpClient;
     }
     $uri = "";
     if ($crtRep->getOption("AUTH_URI") != "") {
         $httpClient->setAuthorization($crtRep->getOption("AUTH_USER"), $crtRep->getOption("AUTH_PASS"));
         $uri = $crtRep->getOption("AUTH_URI") . "?secure_token={$remoteSecureToken}";
     }
     if (!isset($_SESSION["AJXP_REMOTE_SESSION"]) || !is_array($_SESSION["AJXP_REMOTE_SESSION"]) || $refreshSessId) {
         if ($uri == "") {
             $this->logDebug("Remote_fs : relog necessary");
             // Retrieve a seed!
             $httpClient->get($crtRep->getOption("URI") . "?get_action=get_seed&secure_token={$remoteSecureToken}");
             $seed = $httpClient->getContent();
             $cookies = $httpClient->getCookies();
             if (isset($cookies["AjaXplorer"])) {
                 $_SESSION["AJXP_REMOTE_SESSION"] = $cookies;
             }
             $user = $crtRep->getOption("AUTH_USER");
             $pass = $crtRep->getOption("AUTH_PASS");
             $pass = md5(md5($pass) . $seed);
             $uri = $crtRep->getOption("URI") . "?get_action=login&userid=" . $user . "&password="******"&login_seed={$seed}&secure_token={$remoteSecureToken}";
             $httpClient->get($uri);
             $content = $httpClient->getContent();
             $matches = array();
             if (preg_match_all('#.*?secure_token="(.*?)".*?#s', $content, $matches)) {
                 $remoteSecureToken = $matches[1][0];
                 $_SESSION["AJXP_REMOTE_SECURE_TOKEN"] = $remoteSecureToken;
             }
             $httpClient->setHeadersOnly(false);
         } else {
             $httpClient->setHeadersOnly(true);
             $httpClient->get($uri);
             $httpClient->setHeadersOnly(false);
         }
         $cookies = $httpClient->getCookies();
         $_SESSION["AJXP_REMOTE_SESSION"] = $httpClient->getCookies();
     } else {
         $httpClient->setCookies($_SESSION["AJXP_REMOTE_SESSION"]);
     }
     return $httpClient;
 }
 public function postProcess($action, $httpVars, $postProcessData)
 {
     if (isset($httpVars["simple_uploader"]) || isset($httpVars["xhr_uploader"])) {
         return;
     }
     /* If set resumeFileId and resumePartitionIndex, cross-session resume is requested. */
     if (isset($httpVars["resumeFileId"]) && isset($httpVars["resumePartitionIndex"])) {
         header("HTTP/1.1 200 OK");
         print "fileId: " . $httpVars["resumeFileId"] . "\n";
         print "partitionIndex: " . $httpVars["resumePartitionIndex"];
         return;
     }
     /*if (self::$skipDecoding) {
     
             }*/
     if (isset($postProcessData["processor_result"]["ERROR"])) {
         if (isset($httpVars["lastPartition"]) && isset($httpVars["partitionCount"])) {
             /* we get the stream url (where all the partitions have been uploaded so far) */
             $repository = ConfService::getRepository();
             $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
             $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
             $streamData = $plugin->detectStreamWrapper(true);
             $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
             if ($httpVars["partitionCount"] > 1) {
                 /* we fetch the information that help us to construct the temp files name */
                 $fileId = $httpVars["fileId"];
                 $fileHash = md5($httpVars["fileName"]);
                 /* deletion of all the partitions that have been uploaded */
                 for ($i = 0; $i < $httpVars["partitionCount"]; $i++) {
                     if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) {
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
             } else {
                 $fileName = $httpVars["fileName"];
                 unlink($destStreamURL . $fileName);
             }
         }
         echo "Error: " . $postProcessData["processor_result"]["ERROR"]["MESSAGE"];
         return;
     }
     if (!isset($httpVars["partitionRealName"]) && !isset($httpVars["lastPartition"])) {
         return;
     }
     $repository = ConfService::getRepository();
     $driver = ConfService::loadDriverForRepository($repository);
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     if ($httpVars["lastPartition"]) {
         $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
         $streamData = $plugin->detectStreamWrapper(true);
         $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
         $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
         /* we check if the current file has a relative path (aka we want to upload an entire directory) */
         $this->logDebug("Now dispatching relativePath dest:", $httpVars["relativePath"]);
         $subs = explode("/", $httpVars["relativePath"]);
         $userfile_name = array_pop($subs);
         $folderForbidden = false;
         $all_in_place = true;
         $partitions_length = 0;
         $fileId = $httpVars["fileId"];
         $fileHash = md5($userfile_name);
         $partitionCount = $httpVars["partitionCount"];
         $fileLength = $_POST["fileLength"];
         /*
          *
          * Now, we supposed that access driver has already saved uploaded file in to
          * folderServer with file name is md5 relativePath value.
          * We try to copy this file to right location in recovery his name.
          *
          */
         $userfile_name = md5($httpVars["relativePath"]);
         if (self::$remote) {
             $partitions = array();
             $newPartitions = array();
             $index_first_partition = -1;
             $i = 0;
             do {
                 $currentFileName = $driver->getFileNameToCopy();
                 $partitions[] = $driver->getNextFileToCopy();
                 if ($index_first_partition < 0 && strstr($currentFileName, $fileHash) != false) {
                     $index_first_partition = $i;
                 } else {
                     if ($index_first_partition < 0) {
                         $newPartitions[] = array_pop($partitions);
                     }
                 }
             } while ($driver->hasFilesToCopy());
         }
         /* if partitionned */
         if ($partitionCount > 1) {
             if (self::$remote) {
                 for ($i = 0; $all_in_place && $i < $partitionCount; $i++) {
                     $partition_file = "{$fileHash}.{$fileId}.{$i}";
                     if (strstr($partitions[$i]["name"], $partition_file) != false) {
                         $partitions_length += filesize($partitions[$i]["tmp_name"]);
                     } else {
                         $all_in_place = false;
                     }
                 }
             } else {
                 for ($i = 0; $all_in_place && $i < $partitionCount; $i++) {
                     $partition_file = $destStreamURL . "{$fileHash}.{$fileId}.{$i}";
                     if (file_exists($partition_file)) {
                         $partitions_length += filesize($partition_file);
                     } else {
                         $all_in_place = false;
                     }
                 }
             }
         } else {
             if (self::$remote) {
                 if (strstr($newPartitions[count($newPartitions) - 1]["name"], $userfile_name) != false) {
                     $partitions_length += filesize($newPartitions[count($newPartitions) - 1]["tmp_name"]);
                 }
             } else {
                 if (file_exists($destStreamURL . $userfile_name)) {
                     $partitions_length += filesize($destStreamURL . $userfile_name);
                 }
             }
         }
         if (!$all_in_place || $partitions_length != floatval($fileLength)) {
             echo "Error: Upload validation error!";
             /* we delete all the uploaded partitions */
             if ($httpVars["partitionCount"] > 1) {
                 for ($i = 0; $i < $partitionCount; $i++) {
                     if (file_exists($destStreamURL . "{$fileHash}.{$fileId}.{$i}")) {
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
             } else {
                 $fileName = $httpVars["partitionRealName"];
                 unlink($destStreamURL . $fileName);
             }
             return;
         }
         if (count($subs) > 0 && !self::$remote) {
             $curDir = "";
             if (substr($curDir, -1) == "/") {
                 $curDir = substr($curDir, 0, -1);
             }
             // Create the folder tree as necessary
             foreach ($subs as $key => $spath) {
                 $messtmp = "";
                 $dirname = AJXP_Utils::decodeSecureMagic($spath, AJXP_SANITIZE_FILENAME);
                 $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
                 //$this->filterUserSelectionToHidden(array($dirname));
                 if (AJXP_Utils::isHidden($dirname)) {
                     $folderForbidden = true;
                     break;
                 }
                 if (file_exists($destStreamURL . "{$curDir}/{$dirname}")) {
                     // if the folder exists, traverse
                     $this->logDebug("{$curDir}/{$dirname} existing, traversing for {$userfile_name} out of", $httpVars["relativePath"]);
                     $curDir .= "/" . $dirname;
                     continue;
                 }
                 $this->logDebug($destStreamURL . $curDir);
                 $dirMode = 0775;
                 $chmodValue = $repository->getOption("CHMOD_VALUE");
                 if (isset($chmodValue) && $chmodValue != "") {
                     $dirMode = octdec(ltrim($chmodValue, "0"));
                     if ($dirMode & 0400) {
                         $dirMode |= 0100;
                     }
                     // Owner is allowed to read, allow to list the directory
                     if ($dirMode & 040) {
                         $dirMode |= 010;
                     }
                     // Group is allowed to read, allow to list the directory
                     if ($dirMode & 04) {
                         $dirMode |= 01;
                     }
                     // Other are allowed to read, allow to list the directory
                 }
                 $url = $destStreamURL . $curDir . "/" . $dirname;
                 $old = umask(0);
                 mkdir($url, $dirMode);
                 umask($old);
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($url), false));
                 $curDir .= "/" . $dirname;
             }
         }
         if (!$folderForbidden) {
             $fileId = $httpVars["fileId"];
             $this->logDebug("Should now rebuild file!", $httpVars);
             // Now move the final file to the right folder
             // Currently the file is at the base of the current
             $this->logDebug("PartitionRealName", $destStreamURL . $httpVars["partitionRealName"]);
             // Get file by name (md5 value)
             $relPath_md5 = AJXP_Utils::decodeSecureMagic(md5($httpVars["relativePath"]));
             // original file name
             $relPath = AJXP_Utils::decodeSecureMagic($httpVars["relativePath"]);
             $target = $destStreamURL;
             $target .= self::$remote ? basename($relPath) : $relPath;
             /*
              *   $current is uploaded file with md5 value as his name
              *   we copy to $relPath and delete md5 file
              */
             $current = $destStreamURL . basename($relPath_md5);
             if ($httpVars["partitionCount"] > 1) {
                 if (self::$remote) {
                     $test = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"];
                     $newDest = fopen(AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"], "w");
                     $newFile = array();
                     $length = 0;
                     for ($i = 0, $count = count($partitions); $i < $count; $i++) {
                         $currentFile = $partitions[$i];
                         $currentFileName = $currentFile["tmp_name"];
                         $part = fopen($currentFileName, "r");
                         while (!feof($part)) {
                             $length += fwrite($newDest, fread($part, 4096));
                         }
                         fclose($part);
                         unlink($currentFileName);
                     }
                     $newFile["type"] = $partitions[0]["type"];
                     $newFile["name"] = $httpVars["partitionRealName"];
                     $newFile["error"] = 0;
                     $newFile["size"] = $length;
                     $newFile["tmp_name"] = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["partitionRealName"];
                     $newFile["destination"] = $partitions[0]["destination"];
                     $newPartitions[] = $newFile;
                 } else {
                     $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w");
                     $fileHash = md5($httpVars["partitionRealName"]);
                     for ($i = 0; $i < $httpVars["partitionCount"]; $i++) {
                         $part = fopen($destStreamURL . "{$fileHash}.{$fileId}.{$i}", "r");
                         while (!feof($part)) {
                             fwrite($newDest, fread($part, 4096));
                         }
                         fclose($part);
                         unlink($destStreamURL . "{$fileHash}.{$fileId}.{$i}");
                     }
                 }
                 fclose($newDest);
             }
             if (!self::$remote && (!self::$wrapperIsRemote || $relPath != $httpVars["partitionRealName"])) {
                 $err = copy($current, $target);
             } else {
                 for ($i = 0, $count = count($newPartitions); $i < $count; $i++) {
                     $driver->storeFileToCopy($newPartitions[$i]);
                 }
             }
             if ($err !== false) {
                 if (!self::$remote) {
                     unlink($current);
                 }
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false));
             } else {
                 if ($current == $target) {
                     AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($target), false));
                 }
             }
         } else {
             // Remove the file, as it should not have been uploaded!
             //if(!self::$remote) unlink($current);
         }
     }
 }
 /**
  * @param String $file URL of the file to commit (probably a metadata)
  * @param AJXP_Node $ajxpNode Optionnal node to commit along.
  */
 public function commitFile($file, $ajxpNode = null)
 {
     $repo = ConfService::getRepository();
     $repo->detectStreamWrapper();
     $wrapperData = $repo->streamData;
     $realFile = call_user_func(array($wrapperData["classname"], "getRealFSReference"), $file);
     $res = ExecSvnCmd("svn status ", $realFile);
     if (count($res[IDX_STDOUT]) && substr($res[IDX_STDOUT][0], 0, 1) == "?") {
         $res2 = ExecSvnCmd("svn add", "{$realFile}");
     }
     if ($ajxpNode != null) {
         $nodeRealFile = call_user_func(array($wrapperData["classname"], "getRealFSReference"), $ajxpNode->getUrl());
         try {
             ExecSvnCmd("svn propset metachange " . time(), $nodeRealFile);
         } catch (Exception $e) {
             $this->commitChanges("COMMIT_META", $realFile, array());
             return;
         }
         // WILL COMMIT BOTH AT ONCE
         $command = "svn commit";
         $user = AuthService::getLoggedUser()->getId();
         $switches = "-m \"AjaXplorer||{$user}||COMMIT_META||file:" . escapeshellarg($file) . "\"";
         ExecSvnCmd($command, array($realFile, $nodeRealFile), $switches);
         ExecSvnCmd('svn update', dirname($nodeRealFile), '');
     } else {
         $this->commitChanges("COMMIT_META", $realFile, array());
     }
 }