/**
  * @param string $action
  * @param array $httpVars
  * @param array $fileVars
  */
 public function applyChangeLock($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars();
     $currentFile = $selection->getUniqueFile();
     $wrapperData = $this->accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId();
     $unlock = isset($httpVars["unlock"]) ? true : false;
     $ajxpNode = new AJXP_Node($urlBase . $currentFile);
     if ($unlock) {
         $this->metaStore->removeMetadata($ajxpNode, self::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL);
     } else {
         $this->metaStore->setMetadata($ajxpNode, SimpleLockManager::METADATA_LOCK_NAMESPACE, array("lock_user" => AuthService::getLoggedUser()->getId()), false, AJXP_METADATA_SCOPE_GLOBAL);
     }
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode();
     AJXP_XMLWriter::close();
 }
 public function 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;
 }
 public function switchAction($action, $httpVars, $filesVars)
 {
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (!isset($this->pluginConf)) {
         $this->pluginConf = array("GENERATE_THUMBNAIL" => false);
     }
     $selection = new UserSelection($repository, $httpVars);
     $destStreamURL = $selection->currentBaseUrl();
     if ($action == "preview_data_proxy") {
         $file = $selection->getUniqueFile();
         if (!file_exists($destStreamURL . $file) || !is_readable($destStreamURL . $file)) {
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: 0");
             return;
         }
         $this->logInfo('Preview', 'Preview content of ' . $file, array("files" => $selection->getUniqueFile()));
         if (isset($httpVars["get_thumb"]) && $httpVars["get_thumb"] == "true" && $this->getFilteredOption("GENERATE_THUMBNAIL", $repository->getId())) {
             $dimension = 200;
             if (isset($httpVars["dimension"]) && is_numeric($httpVars["dimension"])) {
                 $dimension = $httpVars["dimension"];
             }
             $this->currentDimension = $dimension;
             $cacheItem = AJXP_Cache::getItem("diaporama_" . $dimension, $destStreamURL . $file, array($this, "generateThumbnail"));
             $data = $cacheItem->getData();
             $cId = $cacheItem->getId();
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($cId)) . "; name=\"" . basename($cId) . "\"");
             header("Content-Length: " . strlen($data));
             header('Cache-Control: public');
             header("Pragma:");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
             header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
             print $data;
         } else {
             //$filesize = filesize($destStreamURL.$file);
             $node = new AJXP_Node($destStreamURL . $file);
             $fp = fopen($destStreamURL . $file, "r");
             $stat = fstat($fp);
             $filesize = $stat["size"];
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: " . $filesize);
             header('Cache-Control: public');
             header("Pragma:");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
             header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
             $stream = fopen("php://output", "a");
             AJXP_MetaStreamWrapper::copyFileInStream($destStreamURL . $file, $stream);
             fflush($stream);
             fclose($stream);
             AJXP_Controller::applyHook("node.read", array($node));
         }
     }
 }
 /**
  * @param string $action
  * @param array $httpVars
  * @param array $fileVars
  */
 public function applyChangeLock($actionName, $httpVars, $fileVars)
 {
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection($repo, $httpVars);
     $unlock = isset($httpVars["unlock"]) ? true : false;
     if ($unlock) {
         $this->metaStore->removeMetadata($selection->getUniqueNode(), self::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL);
     } else {
         $this->metaStore->setMetadata($selection->getUniqueNode(), SimpleLockManager::METADATA_LOCK_NAMESPACE, array("lock_user" => AuthService::getLoggedUser()->getId()), false, AJXP_METADATA_SCOPE_GLOBAL);
     }
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode();
     AJXP_XMLWriter::close();
 }
 /**
  * @param UserSelection $userSelection
  */
 function filterUserSelection(&$userSelection)
 {
     if ($userSelection->isEmpty()) {
         foreach ($this->filters as $path => $virtual) {
             $userSelection->addFile($path);
         }
     } else {
         $newFiles = array();
         foreach ($userSelection->getFiles() as $f) {
             if (isset($this->virtualPaths[$f])) {
                 $newFiles[] = $this->virtualPaths[$f];
             } else {
                 $testB = base64_decode($f);
                 if (isset($this->virtualPaths[$testB])) {
                     $newFiles[] = $this->virtualPaths[$testB];
                 }
             }
         }
         $userSelection->setFiles($newFiles);
     }
 }
 protected function initDirAndSelection($httpVars, $additionnalPathes = array(), $testRecycle = false)
 {
     $userSelection = new UserSelection();
     $userSelection->initFromHttpVars($httpVars);
     $repo = $this->accessDriver->repository;
     $repo->detectStreamWrapper();
     $wrapperData = $repo->streamData;
     $urlBase = $wrapperData["protocol"] . "://" . $repo->getId();
     $result = array();
     if ($testRecycle) {
         $recycle = $repo->getOption("RECYCLE_BIN");
         if ($recycle != "") {
             RecycleBinManager::init($urlBase, "/" . $recycle);
             $result["RECYCLE"] = RecycleBinManager::filterActions($httpVars["get_action"], $userSelection, $httpVars["dir"], $httpVars);
             // if necessary, check recycle was checked.
             // We could use a hook instead here? Maybe the full recycle system
             // could be turned into a plugin
             $sessionKey = "AJXP_SVN_" . $repo->getId() . "_RECYCLE_CHECKED";
             if (isset($_SESSION[$sessionKey])) {
                 $file = RecycleBinManager::getRelativeRecycle() . "/" . RecycleBinManager::getCacheFileName();
                 $realFile = call_user_func(array($wrapperData["classname"], "getRealFSReference"), $urlBase . $file);
                 $this->addIfNotVersionned($file, $realFile);
                 $_SESSION[$sessionKey] = true;
             }
         }
     }
     $result["DIR"] = call_user_func(array($wrapperData["classname"], "getRealFSReference"), $urlBase . AJXP_Utils::decodeSecureMagic($httpVars["dir"]));
     $result["ORIGINAL_SELECTION"] = $userSelection;
     $result["SELECTION"] = array();
     if (!$userSelection->isEmpty()) {
         $files = $userSelection->getFiles();
         foreach ($files as $selected) {
             $result["SELECTION"][] = call_user_func(array($wrapperData["classname"], "getRealFSReference"), $urlBase . $selected);
         }
     }
     foreach ($additionnalPathes as $parameter => $path) {
         $result[$parameter] = call_user_func(array($wrapperData["classname"], "getRealFSReference"), $urlBase . $path);
     }
     return $result;
 }
 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 preProcessMove($actionName, &$httpVars, &$fileVars)
 {
     $destO = AJXP_Utils::decodeSecureMagic($httpVars["dest"]);
     $dest = substr($destO, 1, strpos(ltrim($destO, "/"), "/"));
     if (empty($dest)) {
         $dest = ltrim($destO, "/");
     }
     $userSelection = new UserSelection();
     $userSelection->initFromHttpVars($httpVars);
     if (!$userSelection->isEmpty()) {
         $testFileO = $userSelection->getUniqueFile();
         $testFile = substr($testFileO, 1, strpos(ltrim($testFileO, "/"), "/"));
         if (empty($testFile)) {
             $testFile = ltrim($testFileO, "/");
         }
         if ($actionName == "move") {
             if (strstr($dest, "ENCFS_CLEAR_") != false && strstr($testFile, "ENCFS_CLEAR_") === false || strstr($dest, "ENCFS_CLEAR_") === false && strstr($testFile, "ENCFS_CLEAR_") !== false || strstr($dest, "ENCFS_CLEAR_") != false && strstr($testFile, "ENCFS_CLEAR_") !== false && $testFile != $dest) {
                 $httpVars["force_copy_delete"] = "true";
                 $this->logDebug("One mount to another, copy/delete instead of move ({$dest}, {$testFile})");
             }
         } else {
             if ($actionName == "delete" && RecycleBinManager::recycleEnabled()) {
                 if (strstr($testFile, "ENCFS_CLEAR_") !== false) {
                     $httpVars["force_copy_delete"] = "true";
                     $this->logDebug("One mount to another, copy/delete instead of move");
                 }
             } else {
                 if ($actionName == "restore") {
                     if (strstr(RecycleBinManager::getFileOrigin($testFile), "ENCFS_CLEAR_")) {
                         $httpVars["force_copy_delete"] = "true";
                         $this->logDebug("One mount to another, copy/delete instead of move");
                     }
                 }
             }
         }
     }
 }
 /**
  * Transform delete/restore actions into move actino
  * @static
  * @param string $action
  * @param UserSelection $selection
  * @param string $currentLocation
  * @param array $httpVars
  * @return array
  */
 public static function filterActions($action, $selection, $currentLocation, $httpVars = array())
 {
     if (!self::recycleEnabled()) {
         return array();
     }
     $newArgs = array();
     // FILTER ACTION FOR DELETE
     if ($action == "delete" && !self::currentLocationIsRecycle($currentLocation) && !isset($httpVars["force_deletion"])) {
         $newArgs["action"] = "move";
         $newArgs["dest"] = self::$rbmRelativeRecycle;
     }
     // FILTER ACTION FOR RESTORE
     if ($action == "restore" && self::currentLocationIsRecycle($currentLocation)) {
         $originalRep = self::getFileOrigin($selection->getUniqueFile());
         if ($originalRep != "") {
             $newArgs["action"] = "move";
             $newArgs["dest"] = $originalRep;
             // CHECK UTF8 HANDLING HERE
         }
     }
     return $newArgs;
 }
 public function switchAction($action, $httpVars, $filesVars)
 {
     $repository = ConfService::getRepositoryById($httpVars["repository_id"]);
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if ($loggedUser === null && ConfService::getCoreConf("ALLOW_GUEST_BROWSING", "auth")) {
             AuthService::logUser("guest", null);
             $loggedUser = AuthService::getLoggedUser();
         }
         if (!$loggedUser->canSwitchTo($repository->getId())) {
             echo "You do not have permissions to access this resource";
             return false;
         }
     }
     $selection = new UserSelection($repository, $httpVars);
     if ($action == "open_file") {
         $selectedNode = $selection->getUniqueNode();
         $selectedNodeUrl = $selectedNode->getUrl();
         if (!file_exists($selectedNodeUrl) || !is_readable($selectedNodeUrl)) {
             echo "File does not exist";
             return false;
         }
         $filesize = filesize($selectedNodeUrl);
         $fp = fopen($selectedNodeUrl, "rb");
         $fileMime = "application/octet-stream";
         //Get mimetype with fileinfo PECL extension
         if (class_exists("finfo")) {
             $finfo = new finfo(FILEINFO_MIME);
             $fileMime = $finfo->buffer(fread($fp, 2000));
         }
         //Get mimetype with (deprecated) mime_content_type
         if (strpos($fileMime, "application/octet-stream") === 0 && function_exists("mime_content_type")) {
             $fileMime = @mime_content_type($fp);
         }
         //Guess mimetype based on file extension
         if (strpos($fileMime, "application/octet-stream") === 0) {
             $fileExt = substr(strrchr(basename($selectedNodeUrl), '.'), 1);
             if (empty($fileExt)) {
                 $fileMime = "application/octet-stream";
             } else {
                 $regex = "/^([\\w\\+\\-\\.\\/]+)\\s+(\\w+\\s)*({$fileExt}\\s)/i";
                 $lines = file($this->getBaseDir() . "/resources/other/mime.types");
                 foreach ($lines as $line) {
                     if (substr($line, 0, 1) == '#') {
                         continue;
                     }
                     // skip comments
                     $line = rtrim($line) . " ";
                     if (!preg_match($regex, $line, $matches)) {
                         continue;
                     }
                     // no match to the extension
                     $fileMime = $matches[1];
                 }
             }
         }
         fclose($fp);
         // If still no mimetype, give up and serve application/octet-stream
         if (empty($fileMime)) {
             $fileMime = "application/octet-stream";
         }
         //Send headers
         HTMLWriter::generateInlineHeaders(basename($selectedNodeUrl), $filesize, $fileMime);
         $stream = fopen("php://output", "a");
         AJXP_MetaStreamWrapper::copyFileInStream($selectedNodeUrl, $stream);
         fflush($stream);
         fclose($stream);
         AJXP_Controller::applyHook("node.read", array($selectedNode));
         $this->logInfo('Download', 'Read content of ' . $selectedNodeUrl, array("files" => $selectedNodeUrl));
     }
 }
 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;
 }
 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 switchActions($actionName, $httpVars, $fileVars)
 {
     switch ($actionName) {
         case "toggle_watch":
             $us = new UserSelection();
             $us->initFromHttpVars($httpVars);
             $node = $us->getUniqueNode($this->accessDriver);
             $node->loadNodeInfo();
             $cmd = $httpVars["watch_action"];
             $meta = $this->metaStore->retrieveMetadata($node, self::$META_WATCH_NAMESPACE, false, AJXP_METADATA_SCOPE_REPOSITORY);
             $userId = AuthService::getLoggedUser() != null ? AuthService::getLoggedUser()->getId() : "shared";
             if ($cmd == "watch_stop" && isset($meta) && isset($meta[$userId])) {
                 unset($meta[$userId]);
                 $this->metaStore->removeMetadata($node, self::$META_WATCH_NAMESPACE, false, AJXP_METADATA_SCOPE_REPOSITORY);
             } else {
                 switch ($cmd) {
                     case "watch_change":
                         $type = self::$META_WATCH_CHANGE;
                         break;
                     case "watch_read":
                         $type = self::$META_WATCH_READ;
                         break;
                     case "watch_both":
                         $type = self::$META_WATCH_BOTH;
                         break;
                     default:
                         break;
                 }
                 $meta[$userId] = $type;
                 $this->metaStore->setMetadata($node, self::$META_WATCH_NAMESPACE, $meta, false, AJXP_METADATA_SCOPE_REPOSITORY);
             }
             AJXP_XMLWriter::header();
             $node->metadata = array();
             $node->loadNodeInfo(true, false, "all");
             $this->enrichNode($node);
             AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => array($node->getPath() => $node)), true);
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
 }
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $loggedUser = AuthService::getLoggedUser();
     if (!ENABLE_USERS) {
         return;
     }
     if ($action == "edit") {
         if (isset($httpVars["sub_action"])) {
             $action = $httpVars["sub_action"];
         }
     }
     $mess = ConfService::getMessages();
     switch ($action) {
         //------------------------------------
         //	BASIC LISTING
         //------------------------------------
         case "ls":
             $rootNodes = array("files" => array("LABEL" => $mess["ajxp_shared.3"], "ICON" => "html.png", "DESCRIPTION" => $mess["ajxp_shared.28"]), "repositories" => array("LABEL" => $mess["ajxp_shared.2"], "ICON" => "document_open_remote.png", "DESCRIPTION" => $mess["ajxp_shared.29"]), "users" => array("LABEL" => $mess["ajxp_shared.1"], "ICON" => "user_shared.png", "DESCRIPTION" => $mess["ajxp_shared.30"]));
             $dir = isset($httpVars["dir"]) ? $httpVars["dir"] : "";
             $splits = explode("/", $dir);
             if (count($splits)) {
                 if ($splits[0] == "") {
                     array_shift($splits);
                 }
                 if (count($splits)) {
                     $strippedDir = strtolower(urldecode($splits[0]));
                 } else {
                     $strippedDir = "";
                 }
             }
             if (array_key_exists($strippedDir, $rootNodes)) {
                 AJXP_XMLWriter::header();
                 if ($strippedDir == "users") {
                     $this->listUsers();
                 } else {
                     if ($strippedDir == "repositories") {
                         $this->listRepositories();
                     } else {
                         if ($strippedDir == "files") {
                             $this->listSharedFiles();
                         }
                     }
                 }
                 AJXP_XMLWriter::close();
                 exit(1);
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendFilesListComponentConfig('<columns switchGridMode="filelist"><column messageId="ajxp_shared.8" attributeName="ajxp_label" sortType="String"/><column messageId="ajxp_shared.31" attributeName="description" sortType="String"/></columns>');
                 foreach ($rootNodes as $key => $data) {
                     print '<tree text="' . $data["LABEL"] . '" icon="' . $data["ICON"] . '" filename="/' . $key . '" parentname="/" description="' . $data["DESCRIPTION"] . '" />';
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "stat":
             header("Content-type:application/json");
             print '{"mode":true}';
             break;
         case "delete":
             $mime = $httpVars["ajxp_mime"];
             $selection = new UserSelection();
             $selection->initFromHttpVars();
             $files = $selection->getFiles();
             AJXP_XMLWriter::header();
             foreach ($files as $index => $element) {
                 $element = basename($element);
                 if ($mime == "shared_repository") {
                     $repo = ConfService::getRepositoryById($element);
                     if (!$repo->hasOwner() || $repo->getOwner() != $loggedUser->getId()) {
                         AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]);
                         break;
                     } else {
                         $res = ConfService::deleteRepository($element);
                         if ($res == -1) {
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_conf.51"]);
                             break;
                         } else {
                             if ($index == count($files) - 1) {
                                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.59"], null);
                                 AJXP_XMLWriter::reloadDataNode();
                             }
                         }
                     }
                 } else {
                     if ($mime == "shared_user") {
                         $confDriver = ConfService::getConfStorageImpl();
                         $object = $confDriver->createUserObject($element);
                         if (!$object->hasParent() || $object->getParent() != $loggedUser->getId()) {
                             AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]);
                             break;
                         } else {
                             $res = AuthService::deleteUser($element);
                             if ($index == count($files) - 1) {
                                 AJXP_XMLWriter::sendMessage($mess["ajxp_conf.60"], null);
                                 AJXP_XMLWriter::reloadDataNode();
                             }
                         }
                     } else {
                         if ($mime == "shared_file") {
                             $publicletData = $this->loadPublicletData(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php");
                             if (isset($publicletData["OWNER_ID"]) && $publicletData["OWNER_ID"] == $loggedUser->getId()) {
                                 require_once INSTALL_PATH . "/server/classes/class.PublicletCounter.php";
                                 PublicletCounter::delete($element);
                                 unlink(PUBLIC_DOWNLOAD_FOLDER . "/" . $element . ".php");
                                 if ($index == count($files) - 1) {
                                     AJXP_XMLWriter::sendMessage($mess["ajxp_shared.13"], null);
                                     AJXP_XMLWriter::reloadDataNode();
                                 }
                             } else {
                                 AJXP_XMLWriter::sendMessage(null, $mess["ajxp_shared.12"]);
                                 break;
                             }
                         }
                     }
                 }
             }
             AJXP_XMLWriter::close();
             break;
         case "clear_expired":
             $deleted = $this->clearExpiredFiles();
             AJXP_XMLWriter::header();
             if (count($deleted)) {
                 AJXP_XMLWriter::sendMessage(sprintf($mess["ajxp_shared.23"], count($deleted) . ""), null);
                 AJXP_XMLWriter::reloadDataNode();
             } else {
                 AJXP_XMLWriter::sendMessage($mess["ajxp_shared.24"], null);
             }
             AJXP_XMLWriter::close();
             break;
         case "reset_download_counter":
             $selection = new UserSelection();
             $selection->initFromHttpVars();
             $elements = $selection->getFiles();
             require_once INSTALL_PATH . "/server/classes/class.PublicletCounter.php";
             foreach ($elements as $element) {
                 PublicletCounter::reset(str_replace(".php", "", basename($element)));
             }
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         default:
             break;
     }
     return;
 }
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!AuthService::usersEnabled() && $user != null && !$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection($repo, $httpVars);
     $nodes = $selection->buildNodes();
     $nodesDiffs = array();
     $def = $this->getMetaDefinition();
     foreach ($nodes as $ajxpNode) {
         $newValues = array();
         //$ajxpNode->setDriver($this->accessDriver);
         AJXP_Controller::applyHook("node.before_change", array(&$ajxpNode));
         foreach ($def as $key => $data) {
             if (isset($httpVars[$key])) {
                 $newValues[$key] = AJXP_Utils::decodeSecureMagic($httpVars[$key]);
                 if ($data["type"] == "tags") {
                     $this->updateTags(AJXP_Utils::decodeSecureMagic($httpVars[$key]));
                 }
             } else {
                 if (!isset($original)) {
                     $original = $ajxpNode->retrieveMetadata("users_meta", false, AJXP_METADATA_SCOPE_GLOBAL);
                 }
                 if (isset($original) && isset($original[$key])) {
                     $newValues[$key] = $original[$key];
                 }
             }
         }
         $ajxpNode->setMetadata("users_meta", $newValues, false, AJXP_METADATA_SCOPE_GLOBAL);
         AJXP_Controller::applyHook("node.meta_change", array($ajxpNode));
         $nodesDiffs[$ajxpNode->getPath()] = $ajxpNode;
     }
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::writeNodesDiff(array("UPDATE" => $nodesDiffs), true);
     AJXP_XMLWriter::close();
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     $mess = ConfService::getMessages();
     $timestamp_url = $this->getFilteredOption("TIMESTAMP_URL");
     $timestamp_login = $this->getFilteredOption("USER");
     $timestamp_password = $this->getFilteredOption("PASS");
     //Check if the configuration has been initiated
     if (empty($timestamp_url) || empty($timestamp_login) || !empty($timestamp_password)) {
         throw new AJXP_Exception($mess["timestamp.4"]);
         $this->logError("Config", "TimeStamp : configuration is needed");
         return false;
     }
     //Check if after being initiated, conf. fields have some values
     if (strlen($timestamp_url) < 2 || strlen($timestamp_login) < 2 || strlen($timestamp_password) < 2) {
         throw new AJXP_Exception($mess["timestamp.4"]);
         $this->logError("Config", "TimeStamp : configuration is incorrect");
         return false;
     }
     //Get active repository
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $selection = new UserSelection($repository, $httpVars);
     $destStreamURL = $selection->currentBaseUrl();
     $fileName = $selection->getUniqueFile();
     $fileUrl = $destStreamURL . $fileName;
     $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true);
     //Hash the file, to send it to Universign
     $hashedDataToTimestamp = hash_file('sha256', $file);
     //Check that a tokken is not going to be timestamped !
     if (substr("{$file}", -4) != '.ers') {
         if (file_exists($file . '.ers')) {
             throw new AJXP_Exception($mess["timestamp.1"]);
             return false;
         } else {
             //Prepare the query that will be sent to Universign
             $dataToSend = array('hashAlgo' => 'SHA256', 'withCert' => 'true', 'hashValue' => $hashedDataToTimestamp);
             $dataQuery = http_build_query($dataToSend);
             //Check if allow_url_fopen is allowed on the server. If not, it will use cUrl
             if (ini_get('allow_url_fopen')) {
                 $context_options = array('http' => array('method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($dataQuery) . "\r\n" . "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password) . "\r\n", 'content' => $dataQuery));
                 //Get the result from Universign
                 $context = stream_context_create($context_options);
                 $fp = fopen($timestamp_url, 'r', false, $context);
                 $tsp = stream_get_contents($fp);
             } else {
                 $timestamp_header = array("Content-type: application/x-www-form-urlencoded", "Content-Length: " . strlen($dataQuery), "Authorization: Basic " . base64_encode($timestamp_login . ':' . $timestamp_password));
                 $timeout = 5;
                 $ch = curl_init($timestamp_url);
                 curl_setopt($ch, CURLOPT_POSTFIELDS, $dataQuery);
                 curl_setopt($ch, CURLOPT_HTTPHEADER, $timestamp_header);
                 curl_setopt($ch, CURLOPT_POST, 1);
                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                 //Get the result from Universign
                 $tsp = curl_exec($ch);
                 curl_close($ch);
             }
             //Save the result to a file
             file_put_contents($file . '.ers', $tsp);
             //Send the succesful message
             $this->logInfo("TimeStamp", array("files" => $file, "destination" => $file . '.ers'));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::sendMessage($mess["timestamp.3"] . $fileName, null);
             AJXP_XMLWriter::close();
         }
     } else {
         throw new AJXP_Exception($mess["timestamp.2"]);
         return false;
     }
 }
 public function editMeta($actionName, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$actionName])) {
         return;
     }
     if (is_a($this->accessDriver, "demoAccessDriver")) {
         throw new Exception("Write actions are disabled in demo mode!");
     }
     $repo = $this->accessDriver->repository;
     $user = AuthService::getLoggedUser();
     if (!$user->canWrite($repo->getId())) {
         throw new Exception("You have no right on this action.");
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars();
     $currentFile = $selection->getUniqueFile();
     $wrapperData = $this->accessDriver->detectStreamWrapper(false);
     $urlBase = $wrapperData["protocol"] . "://" . $this->accessDriver->repository->getId();
     $newValues = array();
     $def = $this->getMetaDefinition();
     foreach ($def as $key => $label) {
         if (isset($httpVars[$key])) {
             $newValues[$key] = AJXP_Utils::xmlEntities(AJXP_Utils::decodeSecureMagic($httpVars[$key]));
         } else {
             if (!isset($original)) {
                 $original = array();
                 $this->loadMetaFileData($urlBase . $currentFile);
                 $base = basename($currentFile);
                 if (is_array(self::$metaCache) && array_key_exists($base, self::$metaCache)) {
                     $original = self::$metaCache[$base];
                 }
             }
             if (isset($original) && isset($original[$key])) {
                 $newValues[$key] = $original[$key];
             }
         }
     }
     $this->addMeta($urlBase . $currentFile, $newValues);
     AJXP_XMLWriter::header();
     AJXP_XMLWriter::reloadDataNode("", SystemTextEncoding::toUTF8($currentFile), true);
     AJXP_XMLWriter::close();
 }
 function crossRepositoryCopy($httpVars)
 {
     ConfService::detectRepositoryStreams(true);
     $mess = ConfService::getMessages();
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     $files = $selection->getFiles();
     $accessType = $this->repository->getAccessType();
     $repositoryId = $this->repository->getId();
     $origStreamURL = "ajxp.{$accessType}://{$repositoryId}";
     $destRepoId = $httpVars["dest_repository_id"];
     $destRepoObject = ConfService::getRepositoryById($destRepoId);
     $destRepoAccess = $destRepoObject->getAccessType();
     $destStreamURL = "ajxp.{$destRepoAccess}://{$destRepoId}";
     // Check rights
     if (AuthService::usersEnabled()) {
         $loggedUser = AuthService::getLoggedUser();
         if (!$loggedUser->canRead($repositoryId) || !$loggedUser->canWrite($destRepoId)) {
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::sendMessage(null, "You do not have the right to access one of the repositories!");
             AJXP_XMLWriter::close();
             exit(1);
         }
     }
     $messages = array();
     foreach ($files as $file) {
         $origFile = $origStreamURL . $file;
         $destFile = $destStreamURL . $httpVars["dest"] . "/" . basename($file);
         $origHandler = fopen($origFile, "r");
         $destHandler = fopen($destFile, "w");
         if ($origHandler === false || $destHandler === false) {
             $errorMessages[] = AJXP_XMLWriter::sendMessage(null, $mess[114] . " ({$origFile} to {$destFile})", false);
             continue;
         }
         while (!feof($origHandler)) {
             fwrite($destHandler, fread($origHandler, 4096));
         }
         fflush($destHandler);
         fclose($origHandler);
         fclose($destHandler);
         $messages[] = $mess[34] . " " . SystemTextEncoding::toUTF8(basename($origFile)) . " " . $mess[73] . " " . SystemTextEncoding::toUTF8($destFile);
     }
     AJXP_XMLWriter::header();
     if (count($errorMessages)) {
         AJXP_XMLWriter::sendMessage(null, join("\n", $errorMessages), true);
     }
     AJXP_XMLWriter::sendMessage(join("\n", $messages), null, true);
     AJXP_XMLWriter::close();
     exit(0);
 }
 /**
  * Initialize the stream from the given path. 
  *
  * @param string $path
  * @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path
  */
 protected static function initPath($path, $streamType, $storeOpenContext = false, $skipZip = false)
 {
     $path = self::unPatchPathForBaseDir($path);
     $url = parse_url($path);
     $repoId = $url["host"];
     if (isset($url["fragment"]) && strlen($url["fragment"]) > 0) {
         $url["path"] .= "#" . $url["fragment"];
     }
     $repoObject = ConfService::getRepositoryById($repoId);
     if (!isset($repoObject)) {
         throw new Exception("Cannot find repository with id " . $repoId);
     }
     $split = UserSelection::detectZip($url["path"]);
     $insideZip = false;
     if ($split && $streamType == "file" && $split[1] != "/") {
         $insideZip = true;
     }
     if ($split && $streamType == "dir") {
         $insideZip = true;
     }
     if ($skipZip) {
         $insideZip = false;
     }
     //var_dump($path);
     //var_dump($skipZip);
     // Inside a zip : copy the file to a tmp file and return a reference to it
     if ($insideZip) {
         $zipPath = $split[0];
         $localPath = $split[1];
         require_once AJXP_BIN_FOLDER . "/pclzip.lib.php";
         //print($streamType.$path);
         if ($streamType == "file") {
             if (self::$crtZip == null || !is_array(self::$currentListingKeys)) {
                 $tmpDir = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . md5(time() - rand());
                 mkdir($tmpDir);
                 $tmpFileName = $tmpDir . DIRECTORY_SEPARATOR . basename($localPath);
                 AJXP_Logger::debug("Tmp file {$tmpFileName}");
                 register_shutdown_function(array("fsAccessWrapper", "removeTmpFile"), $tmpDir, $tmpFileName);
                 $crtZip = new PclZip(AJXP_Utils::securePath(realpath($repoObject->getOption("PATH")) . $zipPath));
                 $content = $crtZip->listContent();
                 foreach ($content as $item) {
                     $fName = AJXP_Utils::securePath($item["stored_filename"]);
                     if ($fName == $localPath || "/" . $fName == $localPath) {
                         $localPath = $fName;
                         break;
                     }
                 }
                 $res = $crtZip->extract(PCLZIP_OPT_BY_NAME, $localPath, PCLZIP_OPT_PATH, $tmpDir, PCLZIP_OPT_REMOVE_ALL_PATH);
                 AJXP_Logger::debug("Extracted " . $path . " to " . dirname($localPath));
                 if ($storeOpenContext) {
                     self::$crtZip = $crtZip;
                 }
                 return $tmpFileName;
             } else {
                 $key = basename($localPath);
                 if (array_key_exists($key, self::$currentListing)) {
                     self::$currentFileKey = $key;
                     return -1;
                 } else {
                     throw new AJXP_Exception("Cannot find key");
                 }
             }
         } else {
             $crtZip = new PclZip(AJXP_Utils::securePath(realpath($repoObject->getOption("PATH")) . $zipPath));
             $liste = $crtZip->listContent();
             if ($storeOpenContext) {
                 self::$crtZip = $crtZip;
             }
             $folders = array();
             $files = array();
             $builtFolders = array();
             if ($localPath[strlen($localPath) - 1] != "/") {
                 $localPath .= "/";
             }
             foreach ($liste as $item) {
                 $stored = $item["stored_filename"];
                 if ($stored[0] != "/") {
                     $stored = "/" . $stored;
                 }
                 $pathPos = strpos($stored, $localPath);
                 if ($pathPos !== false) {
                     $afterPath = substr($stored, $pathPos + strlen($localPath));
                     if ($afterPath != "" && substr_count($afterPath, "/") < 2) {
                         $statValue = array();
                         if (substr_count($afterPath, "/") == 0) {
                             $statValue[2] = $statValue["mode"] = $item["folder"] ? "00040000" : "0100000";
                             $statValue[7] = $statValue["size"] = $item["size"];
                             $statValue[8] = $statValue["atime"] = $item["mtime"];
                             $statValue[9] = $statValue["mtime"] = $item["mtime"];
                             $statValue[10] = $statValue["ctime"] = $item["mtime"];
                             if (strpos($afterPath, "/") == strlen($afterPath) - 1) {
                                 $afterPath = substr($afterPath, 0, strlen($afterPath) - 1);
                             }
                             //$statValue["filename"] = $zipPath.$localPath.$afterPath;
                             if ($item["folder"]) {
                                 $folders[$afterPath] = $statValue;
                             } else {
                                 $files[$afterPath] = $statValue;
                             }
                         } else {
                             $arr = explode("/", $afterPath);
                             $afterPath = array_shift($arr);
                             if (isset($folders[$afterPath]) || isset($builtFolders[$afterPath])) {
                                 continue;
                             }
                             $statValue[2] = $statValue["mode"] = "00040000";
                             $statValue[7] = $statValue["size"] = 0;
                             $statValue[8] = $statValue["atime"] = $item["mtime"];
                             $statValue[9] = $statValue["mtime"] = $item["mtime"];
                             $statValue[10] = $statValue["ctime"] = $item["mtime"];
                             $builtFolders[$afterPath] = $statValue;
                         }
                     }
                 }
             }
             self::$currentListing = array_merge($folders, $builtFolders, $files);
             self::$currentListingKeys = array_keys(self::$currentListing);
             self::$currentListingIndex = 0;
             return -1;
         }
     } else {
         return realpath($repoObject->getOption("PATH")) . $url["path"];
     }
 }
 /**
  * @param ShareCenter $shareCenter
  * @param ShareStore $shareStore
  * @param ShareRightsManager $shareRightManager
  */
 public static function migrateLegacyMeta($shareCenter, $shareStore, $shareRightManager, $dryRun = true)
 {
     $metaStoreDir = AJXP_DATA_PATH . "/plugins/metastore.serial";
     $publicFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER");
     $metastores = glob($metaStoreDir . "/ajxp_meta_0");
     if ($dryRun) {
         print "RUNNING A DRY RUN FOR META MIGRATION";
     }
     foreach ($metastores as $store) {
         if (strpos($store, ".bak") !== false) {
             continue;
         }
         // Backup store
         if (!$dryRun) {
             copy($store, $store . ".bak");
         }
         $data = unserialize(file_get_contents($store));
         foreach ($data as $filePath => &$metadata) {
             foreach ($metadata as $userName => &$meta) {
                 if (!AuthService::userExists($userName)) {
                     continue;
                 }
                 $userObject = ConfService::getConfStorageImpl()->createUserObject($userName);
                 if (isset($meta["ajxp_shared"]) && isset($meta["ajxp_shared"]["element"])) {
                     print "\n\nItem {$filePath} requires upgrade :";
                     $share = $meta["ajxp_shared"];
                     $element = $meta["ajxp_shared"]["element"];
                     if (is_array($element)) {
                         $element = array_shift(array_keys($element));
                     }
                     // Take the first one only
                     $legacyLinkFile = $publicFolder . "/" . $element . ".php";
                     if (file_exists($legacyLinkFile)) {
                         // Load file, move it to DB and move the meta
                         $publiclet = $shareStore->loadShare($element);
                         rename($legacyLinkFile, $legacyLinkFile . ".migrated");
                         if (isset($share["minisite"])) {
                             print "\n--Migrate legacy minisite to new minisite?";
                             try {
                                 $sharedRepoId = $publiclet["REPOSITORY"];
                                 $sharedRepo = ConfService::getRepositoryById($sharedRepoId);
                                 if ($sharedRepo == null) {
                                     print "\n--ERROR: Cannot find repository with id " . $sharedRepoId;
                                     continue;
                                 }
                                 $shareLink = new ShareLink($shareStore, $publiclet);
                                 $user = $shareLink->getUniqueUser();
                                 if (AuthService::userExists($user)) {
                                     $userObject = ConfService::getConfStorageImpl()->createUserObject($user);
                                     $userObject->setHidden(true);
                                     print "\n--Should set existing user {$user} as hidden";
                                     if (!$dryRun) {
                                         $userObject->save();
                                     }
                                 }
                                 $shareLink->parseHttpVars(["custom_handle" => $element]);
                                 $shareLink->setParentRepositoryId($sharedRepo->getParentId());
                                 print "\n--Creating the following share object";
                                 print_r($shareLink->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $shareLink->save();
                                 }
                                 $meta["ajxp_shared"] = ["shares" => [$element => ["type" => "minisite"], $sharedRepoId => ["type" => "repository"]]];
                             } catch (Exception $e) {
                                 print "\n-- Error " . $e->getMessage();
                             }
                         } else {
                             print "\n--Should migrate legacy link to new minisite with ContentFilter";
                             try {
                                 $link = new ShareLink($shareStore);
                                 $link->setOwnerId($userName);
                                 $parameters = array("custom_handle" => $element, "simple_right_download" => true);
                                 if (isset($publiclet["EXPIRE_TIME"])) {
                                     $parameters["expiration"] = $publiclet["EXPIRE_TIME"];
                                 }
                                 if (isset($publiclet["DOWNLOAD_LIMIT"])) {
                                     $parameters["downloadlimit"] = $publiclet["DOWNLOAD_LIMIT"];
                                 }
                                 $link->parseHttpVars($parameters);
                                 $parentRepositoryObject = $publiclet["REPOSITORY"];
                                 $driverInstance = AJXP_PluginsService::findPlugin("access", $parentRepositoryObject->getAccessType());
                                 if (empty($driverInstance)) {
                                     print "\n-- ERROR: Cannot find driver instance!";
                                     continue;
                                 }
                                 $options = $driverInstance->makeSharedRepositoryOptions(["file" => "/"], $parentRepositoryObject);
                                 $options["SHARE_ACCESS"] = "private";
                                 $newRepo = $parentRepositoryObject->createSharedChild(basename($filePath), $options, $parentRepositoryObject->getId(), $userObject->getId(), null);
                                 $gPath = $userObject->getGroupPath();
                                 if (!empty($gPath) && !ConfService::getCoreConf("CROSSUSERS_ALLGROUPS", "conf")) {
                                     $newRepo->setGroupPath($gPath);
                                 }
                                 $newRepo->setDescription("");
                                 // Smells like dirty hack!
                                 $newRepo->options["PATH"] = SystemTextEncoding::fromStorageEncoding($newRepo->options["PATH"]);
                                 $newRepo->setContentFilter(new ContentFilter([new AJXP_Node("pydio://" . $parentRepositoryObject->getId() . $filePath)]));
                                 if (!$dryRun) {
                                     ConfService::addRepository($newRepo);
                                 }
                                 $hiddenUserEntry = $shareRightManager->prepareSharedUserEntry(["simple_right_read" => true, "simple_right_download" => true], $link, false, null);
                                 $selection = new UserSelection($parentRepositoryObject, []);
                                 $selection->addFile($filePath);
                                 if (!$dryRun) {
                                     $shareRightManager->assignSharedRepositoryPermissions($parentRepositoryObject, $newRepo, false, [$hiddenUserEntry["ID"] => $hiddenUserEntry], [], $selection);
                                 }
                                 $link->setParentRepositoryId($parentRepositoryObject->getId());
                                 $link->attachToRepository($newRepo->getId());
                                 print "\n-- Should save following LINK: ";
                                 print_r($link->getJsonData($shareCenter->getPublicAccessManager(), ConfService::getMessages()));
                                 if (!$dryRun) {
                                     $hash = $link->save();
                                 }
                                 // UPDATE METADATA
                                 $meta["ajxp_shared"] = ["shares" => [$element => array("type" => "minisite")]];
                             } catch (Exception $e) {
                                 print "\n-- ERROR: " . $e->getMessage();
                             }
                         }
                         if ($dryRun) {
                             rename($legacyLinkFile . ".migrated", $legacyLinkFile);
                         }
                         continue;
                     } else {
                         //
                         // File does not exists, remove meta
                         //
                         unset($meta["ajxp_shared"]);
                     }
                     $repo = ConfService::getRepositoryById($element);
                     if ($repo !== null) {
                         print "\n--Shared repository: just metadata";
                         // Shared repo, migrating the meta should be enough
                         $meta["ajxp_shared"] = array("shares" => [$element => array("type" => "repository")]);
                     }
                 }
             }
         }
         print "\n\n SHOULD NOW UPDATE METADATA WITH FOLLOWING :";
         print_r($data);
         if (!$dryRun) {
             file_put_contents($store, serialize($data));
         }
     }
 }
 public function extractExif($actionName, $httpVars, $fileVars)
 {
     $repo = $this->accessDriver->repository;
     $userSelection = new UserSelection($this->accessDriver->repository, $httpVars);
     $repo->detectStreamWrapper(true);
     $selectedNode = $userSelection->getUniqueNode();
     $realFile = AJXP_MetaStreamWrapper::getRealFSReference($selectedNode->getUrl());
     AJXP_Utils::safeIniSet('exif.encode_unicode', 'UTF-8');
     $exifData = @exif_read_data($realFile, 0, TRUE);
     if ($exifData === false || !is_array($exifData)) {
         return;
     }
     if ($exifData !== false && isset($exifData["GPS"])) {
         $exifData["COMPUTED_GPS"] = $this->convertGPSData($exifData);
     }
     $iptc = $this->extractIPTC($realFile);
     if (count($iptc)) {
         $exifData["IPTC"] = $iptc;
     }
     $excludeTags = array();
     // array("componentsconfiguration", "filesource", "scenetype", "makernote", "datadump");
     $format = "xml";
     if (isset($httpVars["format"]) && $httpVars["format"] == "json") {
         $format = "json";
     }
     $filteredData = array();
     foreach ($exifData as $section => $data) {
         $filteredData[$section] = array();
         foreach ($data as $key => $value) {
             if (is_array($value)) {
                 $value = implode(",", $value);
             }
             if (in_array(strtolower($key), $excludeTags)) {
                 continue;
             }
             if (strpos($key, "UndefinedTag:") === 0) {
                 continue;
             }
             $value = preg_replace('/[^[:print:]]/', '', $value);
             $filteredData[$section][$key] = SystemTextEncoding::toUTF8($value);
         }
     }
     if ($format == "xml") {
         AJXP_XMLWriter::header("metadata", array("file" => $selectedNode->getPath(), "type" => "EXIF"));
         foreach ($filteredData as $section => $data) {
             print "<exifSection name='{$section}'>";
             foreach ($data as $key => $value) {
                 print "<exifTag name=\"{$key}\">" . AJXP_Utils::xmlEntities($value) . "</exifTag>";
             }
             print "</exifSection>";
         }
         AJXP_XMLWriter::close("metadata");
     } else {
         HTMLWriter::charsetHeader("application/json");
         echo json_encode($filteredData);
     }
 }
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $xmlBuffer = "";
     foreach ($httpVars as $getName => $getValue) {
         ${$getName} = Utils::securePath(SystemTextEncoding::magicDequote($getValue));
     }
     $selection = new UserSelection();
     $selection->initFromHttpVars($httpVars);
     if (isset($dir) && $action != "upload") {
         $safeDir = $dir;
         $dir = SystemTextEncoding::fromUTF8($dir);
     }
     if (isset($dest)) {
         $dest = SystemTextEncoding::fromUTF8($dest);
     }
     $mess = ConfService::getMessages();
     $newArgs = RecycleBinManager::filterActions($action, $selection, $dir);
     foreach ($newArgs as $argName => $argValue) {
         ${$argName} = $argValue;
     }
     // FILTER DIR PAGINATION ANCHOR
     if (isset($dir) && strstr($dir, "#") !== false) {
         $parts = explode("#", $dir);
         $dir = $parts[0];
         $page = $parts[1];
     }
     switch ($action) {
         //------------------------------------
         //	DOWNLOAD, IMAGE & MP3 PROXYS
         //------------------------------------
         case "download":
             AJXP_Logger::logAction("Download", array("files" => $selection));
             set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE);
             register_shutdown_function("restore_error_handler");
             if ($selection->inZip) {
                 $tmpDir = dirname($selection->getZipPath()) . "/.tmpExtractDownload";
                 $delDir = $this->getPath() . "/" . $tmpDir;
                 @mkdir($delDir);
                 register_shutdown_function(array($this, "deldir"), $delDir);
                 $this->convertSelectionToTmpFiles($tmpDir, $selection);
             }
             $zip = false;
             if ($selection->isUnique()) {
                 if (is_dir($this->getPath() . "/" . $selection->getUniqueFile())) {
                     $zip = true;
                     $dir .= "/" . basename($selection->getUniqueFile());
                 }
             } else {
                 $zip = true;
             }
             if ($zip) {
                 // Make a temp zip and send it as download
                 $loggedUser = AuthService::getLoggedUser();
                 $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpDownload.zip";
                 $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
                 if (!$zipFile) {
                     AJXP_Exception::errorToXml("Error while compressing");
                 }
                 register_shutdown_function("unlink", $file);
                 $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip";
                 $this->readFile($file, "force-download", $localName, false, false);
             } else {
                 $this->readFile($this->getPath() . "/" . $selection->getUniqueFile(), "force-download");
             }
             exit(0);
             break;
         case "compress":
             // Make a temp zip and send it as download
             if (isset($archive_name)) {
                 $localName = SystemTextEncoding::fromUTF8($archive_name);
             } else {
                 $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip";
             }
             $file = $this->getPath() . "/" . $dir . "/" . $localName;
             $zipFile = $this->makeZip($selection->getFiles(), $file, $dir);
             if (!$zipFile) {
                 AJXP_Exception::errorToXml("Error while compressing file {$localName}");
             }
             $reload_current_node = true;
             $reload_file_list = $localName;
             break;
         case "image_proxy":
             if ($split = UserSelection::detectZip(SystemTextEncoding::fromUTF8($file))) {
                 require_once "server/classes/pclzip.lib.php";
                 $zip = new PclZip($this->getPath() . $split[0]);
                 $data = $zip->extract(PCLZIP_OPT_BY_NAME, substr($split[1], 1), PCLZIP_OPT_EXTRACT_AS_STRING);
                 header("Content-Type: " . Utils::getImageMimeType(basename($split[1])) . "; name=\"" . basename($split[1]) . "\"");
                 header("Content-Length: " . strlen($data[0]["content"]));
                 header('Cache-Control: public');
                 print $data[0]["content"];
             } else {
                 if (isset($get_thumb) && $get_thumb == "true" && $this->driverConf["GENERATE_THUMBNAIL"]) {
                     require_once "server/classes/PThumb.lib.php";
                     $pThumb = new PThumb($this->driverConf["THUMBNAIL_QUALITY"]);
                     if (!$pThumb->isError()) {
                         $pThumb->use_cache = $this->driverConf["USE_THUMBNAIL_CACHE"];
                         $pThumb->cache_dir = $this->driverConf["THUMBNAIL_CACHE_DIR"];
                         $pThumb->fit_thumbnail($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), 200);
                         if ($pThumb->isError()) {
                             print_r($pThumb->error_array);
                         }
                         exit(0);
                     }
                 }
                 $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "image");
             }
             exit(0);
             break;
         case "mp3_proxy":
             if ($split = UserSelection::detectZip(SystemTextEncoding::fromUTF8($file))) {
                 require_once "server/classes/pclzip.lib.php";
                 $zip = new PclZip($this->getPath() . $split[0]);
                 $data = $zip->extract(PCLZIP_OPT_BY_NAME, substr($split[1], 1), PCLZIP_OPT_EXTRACT_AS_STRING);
                 header("Content-Type: audio/mp3; name=\"" . basename($split[1]) . "\"");
                 header("Content-Length: " . strlen($data[0]["content"]));
                 print $data[0]["content"];
             } else {
                 $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "mp3");
             }
             exit(0);
             break;
             //------------------------------------
             //	ONLINE EDIT
             //------------------------------------
         //------------------------------------
         //	ONLINE EDIT
         //------------------------------------
         case "edit":
             if (isset($save) && $save == 1 && isset($code)) {
                 // Reload "code" variable directly from POST array, do not "securePath"...
                 $code = $_POST["code"];
                 AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file)));
                 $code = stripslashes($code);
                 $code = str_replace("&lt;", "<", $code);
                 $fileName = $this->getPath() . SystemTextEncoding::fromUTF8("/{$file}");
                 if (!is_file($fileName) || !is_writable($fileName)) {
                     header("Content-Type:text/plain");
                     print !is_writable($fileName) ? "1001" : "1002";
                     exit(1);
                 }
                 $fp = fopen($fileName, "w");
                 fputs($fp, $code);
                 fclose($fp);
                 header("Content-Type:text/plain");
                 print $mess[115];
             } else {
                 $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "plain");
             }
             exit(0);
             break;
             //------------------------------------
             //	COPY / MOVE
             //------------------------------------
         //------------------------------------
         //	COPY / MOVE
         //------------------------------------
         case "copy":
         case "move":
             if ($selection->isEmpty()) {
                 $errorMessage = $mess[113];
                 break;
             }
             if ($selection->inZip()) {
                 $tmpDir = dirname($selection->getZipPath()) . "/.tmpExtractDownload";
                 @mkdir($this->getPath() . "/" . $tmpDir);
                 $this->convertSelectionToTmpFiles($tmpDir, $selection);
                 if (is_dir($tmpDir)) {
                     $this->deldir($this->getPath() . "/" . $tmpDir);
                 }
             }
             $success = $error = array();
             $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false);
             if (count($error)) {
                 $errorMessage = join("\n", $error);
             } else {
                 $logMessage = join("\n", $success);
                 AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest));
             }
             $reload_current_node = true;
             if (isset($dest_node)) {
                 $reload_dest_node = $dest_node;
             }
             $reload_file_list = true;
             break;
             //------------------------------------
             //	SUPPRIMER / DELETE
             //------------------------------------
         //------------------------------------
         //	SUPPRIMER / DELETE
         //------------------------------------
         case "delete":
             if ($selection->isEmpty()) {
                 $errorMessage = $mess[113];
                 break;
             }
             $logMessages = array();
             $errorMessage = $this->delete($selection->getFiles(), $logMessages);
             if (count($logMessages)) {
                 $logMessage = join("\n", $logMessages);
             }
             AJXP_Logger::logAction("Delete", array("files" => $selection));
             $reload_current_node = true;
             $reload_file_list = true;
             break;
             //------------------------------------
             //	RENOMMER / RENAME
             //------------------------------------
         //------------------------------------
         //	RENOMMER / RENAME
         //------------------------------------
         case "rename":
             $file = SystemTextEncoding::fromUTF8($file);
             $filename_new = SystemTextEncoding::fromUTF8($filename_new);
             $error = $this->rename($file, $filename_new);
             if ($error != null) {
                 $errorMessage = $error;
                 break;
             }
             $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new);
             $reload_current_node = true;
             $reload_file_list = basename($filename_new);
             AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new));
             break;
             //------------------------------------
             //	CREER UN REPERTOIRE / CREATE DIR
             //------------------------------------
         //------------------------------------
         //	CREER UN REPERTOIRE / CREATE DIR
         //------------------------------------
         case "mkdir":
             $messtmp = "";
             $dirname = Utils::processFileName(SystemTextEncoding::fromUTF8($dirname));
             $error = $this->mkDir($dir, $dirname);
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             $reload_file_list = $dirname;
             $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             $reload_current_node = true;
             AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname));
             break;
             //------------------------------------
             //	CREER UN FICHIER / CREATE FILE
             //------------------------------------
         //------------------------------------
         //	CREER UN FICHIER / CREATE FILE
         //------------------------------------
         case "mkfile":
             $messtmp = "";
             $filename = Utils::processFileName(SystemTextEncoding::fromUTF8($filename));
             $error = $this->createEmptyFile($dir, $filename);
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             $reload_file_list = $filename;
             AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename));
             break;
             //------------------------------------
             //	CHANGE FILE PERMISSION
             //------------------------------------
         //------------------------------------
         //	CHANGE FILE PERMISSION
         //------------------------------------
         case "chmod":
             $messtmp = "";
             $files = $selection->getFiles();
             $changedFiles = array();
             foreach ($files as $fileName) {
                 $error = $this->chmod($this->getPath() . $fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles);
             }
             if (isset($error)) {
                 $errorMessage = $error;
                 break;
             }
             //$messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] ";
             $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders";
             $reload_file_list = $dir;
             AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($changedFiles)));
             break;
             //------------------------------------
             //	UPLOAD
             //------------------------------------
         //------------------------------------
         //	UPLOAD
         //------------------------------------
         case "upload":
             $fancyLoader = false;
             if (isset($fileVars["Filedata"])) {
                 $fancyLoader = true;
                 if ($dir != "") {
                     $dir = "/" . base64_decode($dir);
                 }
             }
             if ($dir != "") {
                 $rep_source = "/{$dir}";
             } else {
                 $rep_source = "";
             }
             $destination = SystemTextEncoding::fromUTF8($this->getPath() . $rep_source);
             if (!$this->isWriteable($destination)) {
                 global $_GET;
                 $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}.";
                 if ($fancyLoader || isset($_GET["ajxp_sessid"])) {
                     header('HTTP/1.0 412 ' . $errorMessage);
                     die('Error 412 ' . $errorMessage);
                 } else {
                     print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');";
                     break;
                 }
             }
             $logMessage = "";
             foreach ($fileVars as $boxName => $boxData) {
                 if ($boxName != "Filedata" && substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 if ($boxName == "Filedata") {
                     $fancyLoader = true;
                 }
                 $err = Utils::parseFileDataErrors($boxData, $fancyLoader);
                 if ($err != null) {
                     $errorMessage = $err;
                     break;
                 }
                 $userfile_name = $boxData["name"];
                 if ($fancyLoader) {
                     $userfile_name = SystemTextEncoding::fromUTF8($userfile_name);
                 }
                 $userfile_name = Utils::processFileName($userfile_name);
                 if (isset($auto_rename)) {
                     $userfile_name = fsDriver::autoRenameForDest($destination, $userfile_name);
                 }
                 if (!move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name)) {
                     $errorMessage = ($fancyLoader ? "411 " : "") . "{$mess['33']} " . $userfile_name;
                     break;
                 }
                 $this->changeMode($destination . "/" . $userfile_name);
                 $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}";
                 AJXP_Logger::logAction("Upload File", array("file" => SystemTextEncoding::fromUTF8($dir) . "/" . $userfile_name));
             }
             if ($fancyLoader) {
                 if (isset($errorMessage)) {
                     header('HTTP/1.0 ' . $errorMessage);
                     die('Error ' . $errorMessage);
                 } else {
                     header('HTTP/1.0 200 OK');
                     die("200 OK");
                 }
             } else {
                 print "<html><script language=\"javascript\">\n";
                 if (isset($errorMessage)) {
                     print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');";
                 } else {
                     print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext();";
                 }
                 print "</script></html>";
             }
             exit;
             break;
             //------------------------------------
             // Public URL
             //------------------------------------
         //------------------------------------
         // Public URL
         //------------------------------------
         case "public_url":
             $file = SystemTextEncoding::fromUTF8($file);
             $url = $this->makePubliclet($file, $password, $expiration);
             header("Content-type:text/plain");
             echo $url;
             exit(1);
             break;
             //------------------------------------
             //	XML LISTING
             //------------------------------------
         //------------------------------------
         //	XML LISTING
         //------------------------------------
         case "ls":
             if (!isset($dir) || $dir == "/") {
                 $dir = "";
             }
             $searchMode = $fileListMode = $completeMode = false;
             if (isset($mode)) {
                 if ($mode == "search") {
                     $searchMode = true;
                 } else {
                     if ($mode == "file_list") {
                         $fileListMode = true;
                     } else {
                         if ($mode == "complete") {
                             $completeMode = true;
                         }
                     }
                 }
             }
             if (isset($skipZip) && $skipZip == "true") {
                 $skipZip = true;
             } else {
                 $skipZip = false;
             }
             if ($test = UserSelection::detectZip($dir)) {
                 $liste = array();
                 $zip = $this->zipListing($test[0], $test[1], $liste);
                 AJXP_XMLWriter::header();
                 $tmpDir = $this->getPath() . dirname($test[0]) . ".tmpZipExtract";
                 foreach ($liste as $zipEntry) {
                     $atts = array();
                     if (!$fileListMode && !$zipEntry["folder"]) {
                         continue;
                     }
                     $atts[] = "is_file=\"" . ($zipEntry["folder"] ? "false" : "true") . "\"";
                     $atts[] = "text=\"" . Utils::xmlEntities(basename(SystemTextEncoding::toUTF8($zipEntry["stored_filename"]))) . "\"";
                     $atts[] = "filename=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\"";
                     if ($fileListMode) {
                         $atts[] = "filesize=\"" . Utils::roundSize($zipEntry["size"]) . "\"";
                         $atts[] = "bytesize=\"" . $zipEntry["size"] . "\"";
                         $atts[] = "ajxp_modiftime=\"" . $zipEntry["mtime"] . "\"";
                         $atts[] = "mimestring=\"" . Utils::mimetype($zipEntry["stored_filename"], "mime", $zipEntry["folder"]) . "\"";
                         $atts[] = "icon=\"" . Utils::mimetype($zipEntry["stored_filename"], "image", $zipEntry["folder"]) . "\"";
                         $is_image = Utils::is_image(basename($zipEntry["stored_filename"]));
                         $atts[] = "is_image=\"" . $is_image . "\"";
                         if ($is_image) {
                             if (!is_dir($tmpDir)) {
                                 mkdir($tmpDir);
                             }
                             $currentFile = $tmpDir . "/" . basename($zipEntry["stored_filename"]);
                             $data = $zip->extract(PCLZIP_OPT_BY_NAME, $zipEntry["stored_filename"], PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_PATH, $tmpDir);
                             list($width, $height, $type, $attr) = @getimagesize($currentFile);
                             $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\"";
                             $atts[] = "image_width=\"{$width}\"";
                             $atts[] = "image_height=\"{$height}\"";
                             unlink($currentFile);
                         }
                     } else {
                         $atts[] = "icon=\"client/images/foldericon.png\"";
                         $atts[] = "openicon=\"client/images/foldericon.png\"";
                         $atts[] = "src=\"content.php?dir=" . urlencode(SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\"";
                     }
                     print "<tree " . join(" ", $atts) . "/>";
                 }
                 if (is_dir($tmpDir)) {
                     rmdir($tmpDir);
                 }
                 AJXP_XMLWriter::close();
                 exit(0);
             }
             $nom_rep = $this->initName($dir);
             AJXP_Exception::errorToXml($nom_rep);
             $threshold = $this->repository->getOption("PAGINATION_THRESHOLD");
             if (!isset($threshold) || intval($threshold) == 0) {
                 $threshold = 500;
             }
             $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER");
             if (!isset($limitPerPage) || intval($limitPerPage) == 0) {
                 $limitPerPage = 200;
             }
             if ($fileListMode) {
                 $countFiles = $this->countFiles($nom_rep);
                 if ($countFiles > $threshold) {
                     $offset = 0;
                     $crtPage = 1;
                     if (isset($page)) {
                         $offset = (intval($page) - 1) * $limitPerPage;
                         $crtPage = $page;
                     }
                     $totalPages = floor($countFiles / $limitPerPage) + 1;
                     $reps = $this->listing($nom_rep, false, $offset, $limitPerPage);
                 } else {
                     $reps = $this->listing($nom_rep, $searchMode);
                 }
             } else {
                 $countFolders = $this->countFiles($nom_rep, true);
                 if ($countFolders > $threshold) {
                     AJXP_XMLWriter::header();
                     $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png";
                     $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png";
                     $attributes = "icon=\"{$icon}\"  openicon=\"{$openicon}\"";
                     print "<tree text=\"{$mess['306']} ({$countFolders})...\" {$attributes}></tree>";
                     AJXP_XMLWriter::close();
                     exit(1);
                 }
                 $reps = $this->listing($nom_rep, !$searchMode);
             }
             //$reps = $result[0];
             AJXP_XMLWriter::header();
             if (isset($totalPages) && isset($crtPage)) {
                 //print '<columns switchDisplayMode="list" switchGridMode="filelist"/>';
                 print '<pagination count="' . $countFiles . '" total="' . $totalPages . '" current="' . $crtPage . '"/>';
             }
             foreach ($reps as $repIndex => $repName) {
                 if (preg_match("/\\.zip\$/", $repName) && $skipZip) {
                     continue;
                 }
                 $attributes = "";
                 if ($searchMode) {
                     if (is_file($nom_rep . "/" . $repIndex)) {
                         $attributes = "is_file=\"true\" icon=\"{$repName}\"";
                         $repName = $repIndex;
                     }
                 } else {
                     if ($fileListMode) {
                         $currentFile = $nom_rep . "/" . $repIndex;
                         $atts = array();
                         $atts[] = "is_file=\"" . (is_file($currentFile) ? "1" : "0") . "\"";
                         $atts[] = "is_image=\"" . Utils::is_image($currentFile) . "\"";
                         $fGroup = @filegroup($currentFile) || "unknown";
                         $atts[] = "file_group=\"" . $fGroup . "\"";
                         $fOwner = @fileowner($currentFile) || "unknown";
                         $atts[] = "file_owner=\"" . $fOwner . "\"";
                         $fPerms = @fileperms($currentFile);
                         if ($fPerms !== false) {
                             $fPerms = substr(decoct($fPerms), is_file($currentFile) ? 2 : 1);
                         } else {
                             $fPerms = '0000';
                         }
                         $atts[] = "file_perms=\"" . $fPerms . "\"";
                         if (Utils::is_image($currentFile)) {
                             list($width, $height, $type, $attr) = @getimagesize($currentFile);
                             $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\"";
                             $atts[] = "image_width=\"{$width}\"";
                             $atts[] = "image_height=\"{$height}\"";
                         }
                         $atts[] = "mimestring=\"" . Utils::mimetype($currentFile, "type", is_dir($currentFile)) . "\"";
                         $datemodif = $this->date_modif($currentFile);
                         $atts[] = "ajxp_modiftime=\"" . ($datemodif ? $datemodif : "0") . "\"";
                         $bytesize = @filesize($currentFile) or 0;
                         if ($bytesize < 0) {
                             $bytesize = sprintf("%u", $bytesize);
                         }
                         $atts[] = "filesize=\"" . Utils::roundSize($bytesize) . "\"";
                         $atts[] = "bytesize=\"" . $bytesize . "\"";
                         $atts[] = "filename=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($dir . "/" . $repIndex)) . "\"";
                         $atts[] = "icon=\"" . (is_file($currentFile) ? SystemTextEncoding::toUTF8($repName) : (is_dir($currentFile) ? "folder.png" : "mime-empty.png")) . "\"";
                         $attributes = join(" ", $atts);
                         $repName = $repIndex;
                     } else {
                         $folderBaseName = Utils::xmlEntities($repName);
                         $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?dir=" . $dir . "/" . $folderBaseName);
                         $link = urlencode($link);
                         $folderFullName = Utils::xmlEntities($dir) . "/" . $folderBaseName;
                         $parentFolderName = $dir;
                         if (!$completeMode) {
                             $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png";
                             $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png";
                             if (preg_match("/\\.zip\$/", $repName)) {
                                 $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/crystal/actions/16/accessories-archiver.png";
                             }
                             $attributes = "icon=\"{$icon}\"  openicon=\"{$openicon}\" filename=\"" . SystemTextEncoding::toUTF8($folderFullName) . "\" src=\"{$link}\"";
                         }
                     }
                 }
                 print "<tree text=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($repName)) . "\" {$attributes}>";
                 print "</tree>";
             }
             // ADD RECYCLE BIN TO THE LIST
             if ($nom_rep == $this->repository->getOption("PATH") && RecycleBinManager::recycleEnabled() && !$completeMode && !$skipZip) {
                 $recycleBinOption = $this->repository->getOption("RECYCLE_BIN");
                 if (is_dir($this->repository->getOption("PATH") . "/" . $recycleBinOption)) {
                     $recycleIcon = $this->countFiles($this->repository->getOption("PATH") . "/" . $recycleBinOption, false, true) > 0 ? "trashcan_full.png" : "trashcan.png";
                     if ($fileListMode) {
                         print "<tree text=\"" . Utils::xmlEntities($mess[122]) . "\" filesize=\"-\" is_file=\"0\" is_recycle=\"1\" mimestring=\"Trashcan\" ajxp_modiftime=\"" . $this->date_modif($this->repository->getOption("PATH") . "/" . $recycleBinOption) . "\" filename=\"/" . $recycleBinOption . "\" icon=\"{$recycleIcon}\"></tree>";
                     } else {
                         print "<tree text=\"{$mess['122']}\" is_recycle=\"true\" icon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/{$recycleIcon}\"  openIcon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/{$recycleIcon}\" filename=\"/" . $recycleBinOption . "\"/>";
                     }
                 }
             }
             AJXP_XMLWriter::close();
             exit(1);
             break;
     }
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if (isset($requireAuth)) {
         $xmlBuffer .= AJXP_XMLWriter::requireAuth(false);
     }
     if (isset($reload_current_node) && $reload_current_node == "true") {
         $xmlBuffer .= AJXP_XMLWriter::reloadCurrentNode(false);
     }
     if (isset($reload_dest_node) && $reload_dest_node != "") {
         $xmlBuffer .= AJXP_XMLWriter::reloadNode($reload_dest_node, false);
     }
     if (isset($reload_file_list)) {
         $xmlBuffer .= AJXP_XMLWriter::reloadFileList($reload_file_list, false);
     }
     return $xmlBuffer;
 }
 /**
  * @param String $actionName
  * @param Array $httpVars
  * @param Array $fileVars
  */
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     $userSelection = new UserSelection($this->accessDriver->repository, $httpVars);
     $uniqNode = $userSelection->getUniqueNode();
     $feedStore = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("feed");
     $existingFeed = $uniqNode->retrieveMetadata(AJXP_META_SPACE_COMMENTS, false);
     if ($existingFeed == null) {
         $existingFeed = array();
     }
     $mess = ConfService::getMessages();
     switch ($actionName) {
         case "post_comment":
             $uId = AuthService::getLoggedUser()->getId();
             $limit = $this->getFilteredOption("COMMENT_SIZE_LIMIT");
             if (!empty($limit)) {
                 $content = substr(AJXP_Utils::decodeSecureMagic($httpVars["content"]), 0, $limit);
             } else {
                 $content = AJXP_Utils::decodeSecureMagic($httpVars["content"]);
             }
             $com = array("date" => time(), "author" => $uId, "content" => $content);
             $existingFeed[] = $com;
             if ($feedStore !== false) {
                 $feedStore->persistMetaObject($uniqNode->getPath(), base64_encode($content), $uniqNode->getRepositoryId(), $uniqNode->getRepository()->securityScope(), $uniqNode->getRepository()->getOwner(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath());
             } else {
                 $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false);
                 $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $existingFeed, false);
             }
             HTMLWriter::charsetHeader("application/json");
             $com["hdate"] = AJXP_Utils::relativeDate($com["date"], $mess);
             $com["path"] = $uniqNode->getPath();
             echo json_encode($com);
             break;
         case "load_comments_feed":
             HTMLWriter::charsetHeader("application/json");
             if ($feedStore !== false) {
                 $sortBy = isset($httpVars["sort_by"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_by"]) : "date";
                 $sortDir = isset($httpVars["sort_dir"]) ? AJXP_Utils::decodeSecureMagic($httpVars["sort_dir"]) : "asc";
                 $offset = isset($httpVars["offset"]) ? intval($httpVars["offset"]) : 0;
                 $limit = isset($httpVars["limit"]) ? intval($httpVars["limit"]) : 100;
                 $uniqNode->loadNodeInfo();
                 $data = $feedStore->findMetaObjectsByIndexPath($this->accessDriver->repository->getId(), $uniqNode->getPath(), AuthService::getLoggedUser()->getId(), AuthService::getLoggedUser()->getGroupPath(), $offset, $limit, $sortBy, $sortDir, !$uniqNode->isLeaf());
                 $theFeed = array();
                 foreach ($data as $stdObject) {
                     $rPath = substr($stdObject->path, strlen($uniqNode->getPath()));
                     if ($rPath == false && $stdObject->path == $uniqNode->getPath()) {
                         $rPath = "";
                     }
                     $rPath = ltrim($rPath, "/");
                     $newItem = array("date" => $stdObject->date, "hdate" => AJXP_Utils::relativeDate($stdObject->date, $mess), "author" => $stdObject->author, "content" => base64_decode($stdObject->content), "path" => $stdObject->path, "rpath" => $rPath, "uuid" => $stdObject->uuid);
                     if (isset($previous) && $previous["author"] == $newItem["author"] && $previous["path"] == $newItem["path"] && $previous["hdate"] == $newItem["hdate"]) {
                         $theFeed[count($theFeed) - 1]["content"] .= '<br>' . $newItem["content"];
                     } else {
                         $theFeed[] = $newItem;
                     }
                     $previous = $newItem;
                 }
                 echo json_encode($theFeed);
             } else {
                 foreach ($existingFeed as &$item) {
                     $item["hdate"] = AJXP_Utils::relativeDate($item["date"], $mess);
                 }
                 echo json_encode($existingFeed);
             }
             break;
         case "delete_comment":
             $data = json_decode($httpVars["comment_data"], true);
             if ($feedStore === false) {
                 $reFeed = array();
                 if ($data["author"] != AuthService::getLoggedUser()->getId()) {
                     break;
                 }
                 foreach ($existingFeed as $fElement) {
                     if ($fElement["date"] == $data["date"] && $fElement["author"] == $data["author"] && $fElement["content"] == $data["content"]) {
                         continue;
                     }
                     $fElement["hdate"] = AJXP_Utils::relativeDate($fElement["date"], $mess);
                     $reFeed[] = $fElement;
                 }
                 $uniqNode->removeMetadata(AJXP_META_SPACE_COMMENTS, false);
                 $uniqNode->setMetadata(AJXP_META_SPACE_COMMENTS, $reFeed, false);
                 HTMLWriter::charsetHeader("application/json");
                 echo json_encode($reFeed);
             } else {
                 $feedStore->dismissAlertById($data["uuid"], 1);
             }
             break;
         default:
             break;
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     $dir = AJXP_Utils::decodeSecureMagic($dir);
     if ($dir == "/") {
         $dir = "";
     }
     $selection->initFromHttpVars($httpVars);
     if (!$selection->isEmpty()) {
         //$this->filterUserSelectionToHidden($selection->getFiles());
     }
     $urlBase = "pydio://" . ConfService::getRepository()->getId();
     $mess = ConfService::getMessages();
     switch ($action) {
         case "monitor_compression":
             $percentFile = fsAccessWrapper::getRealFSReference($urlBase . $dir . "/.zip_operation_" . $httpVars["ope_id"]);
             $percent = 0;
             if (is_file($percentFile)) {
                 $percent = intval(file_get_contents($percentFile));
             }
             if ($percent < 100) {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $httpVars, $mess["powerfs.1"] . " ({$percent}%)", true, 1);
                 AJXP_XMLWriter::close();
             } else {
                 @unlink($percentFile);
                 AJXP_XMLWriter::header();
                 if ($httpVars["on_end"] == "reload") {
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 } else {
                     $archiveName = AJXP_Utils::sanitize($httpVars["archive_name"], AJXP_SANITIZE_FILENAME);
                     $archiveName = str_replace("'", "\\'", $archiveName);
                     $jsCode = "\n                            PydioApi.getClient().downloadSelection(null, \$('download_form'), 'postcompress_download', {ope_id:'" . $httpVars["ope_id"] . "',archive_name:'" . $archiveName . "'});\n                        ";
                     AJXP_XMLWriter::triggerBgJsAction($jsCode, $mess["powerfs.3"], true);
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "postcompress_download":
             $archive = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             if (is_file($archive)) {
                 if (!$fsDriver->getFilteredOption("USE_XSENDFILE", ConfService::getRepository()) && !$fsDriver->getFilteredOption("USE_XACCELREDIRECT", ConfService::getRepository())) {
                     register_shutdown_function("unlink", $archive);
                 }
                 $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true);
             } else {
                 echo "<script>alert('Cannot find archive! Is ZIP correctly installed?');</script>";
             }
             break;
         case "compress":
         case "precompress":
             $archiveName = AJXP_Utils::sanitize(AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]), AJXP_SANITIZE_FILENAME);
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $opeId = substr(md5(time()), 0, 10);
                 $httpVars["ope_id"] = $opeId;
                 AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), $action, $httpVars);
                 AJXP_XMLWriter::header();
                 $bgParameters = array("dir" => SystemTextEncoding::toUTF8($dir), "archive_name" => SystemTextEncoding::toUTF8($archiveName), "on_end" => isset($httpVars["on_end"]) ? $httpVars["on_end"] : "reload", "ope_id" => $opeId);
                 AJXP_XMLWriter::triggerBgAction("monitor_compression", $bgParameters, $mess["powerfs.1"] . " (0%)", true);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             $rootDir = fsAccessWrapper::getRealFSReference($urlBase) . $dir;
             $percentFile = $rootDir . "/.zip_operation_" . $httpVars["ope_id"];
             $compressLocally = $action == "compress" ? true : false;
             // List all files
             $todo = array();
             $args = array();
             $replaceSearch = array($rootDir, "\\");
             $replaceReplace = array("", "/");
             foreach ($selection->getFiles() as $selectionFile) {
                 $baseFile = $selectionFile;
                 $args[] = escapeshellarg(substr($selectionFile, strlen($dir) + ($dir == "/" ? 0 : 1)));
                 $selectionFile = fsAccessWrapper::getRealFSReference($urlBase . $selectionFile);
                 $todo[] = ltrim(str_replace($replaceSearch, $replaceReplace, $selectionFile), "/");
                 if (is_dir($selectionFile)) {
                     $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($selectionFile), RecursiveIteratorIterator::SELF_FIRST);
                     foreach ($objects as $name => $object) {
                         $todo[] = str_replace($replaceSearch, $replaceReplace, $name);
                     }
                 }
                 if (trim($baseFile, "/") == "") {
                     // ROOT IS SELECTED, FIX IT
                     $args = array(escapeshellarg(basename($rootDir)));
                     $rootDir = dirname($rootDir);
                     break;
                 }
             }
             $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";";
             if (!$compressLocally) {
                 $archiveName = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . $httpVars["ope_id"] . "_" . $archiveName;
             }
             chdir($rootDir);
             $cmd = $this->getFilteredOption("ZIP_PATH") . " -r " . escapeshellarg($archiveName) . " " . implode(" ", $args);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             $c = $fsDriver->getConfigs();
             if ((!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == false) && stripos(PHP_OS, "win") === false) {
                 $cmd .= " -x .\\*";
             }
             $cmd .= " " . $cmdSeparator . " echo ZIP_FINISHED";
             $proc = popen($cmd, "r");
             $toks = array();
             $handled = array();
             $finishedEchoed = false;
             while (!feof($proc)) {
                 set_time_limit(20);
                 $results = fgets($proc, 256);
                 if (strlen($results) == 0) {
                 } else {
                     $tok = strtok($results, "\n");
                     while ($tok !== false) {
                         $toks[] = $tok;
                         if ($tok == "ZIP_FINISHED") {
                             $finishedEchoed = true;
                         } else {
                             $test = preg_match('/(\\w+): (.*) \\(([^\\(]+)\\) \\(([^\\(]+)\\)/', $tok, $matches);
                             if ($test !== false) {
                                 $handled[] = $matches[2];
                             }
                         }
                         $tok = strtok("\n");
                     }
                     if ($finishedEchoed) {
                         $percent = 100;
                     } else {
                         $percent = min(round(count($handled) / count($todo) * 100), 100);
                     }
                     file_put_contents($percentFile, $percent);
                 }
                 // avoid a busy wait
                 if ($percent < 100) {
                     usleep(1);
                 }
             }
             pclose($proc);
             file_put_contents($percentFile, 100);
             break;
         default:
             break;
     }
 }
 public function switchAction($action, $httpVars, $postProcessData)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . "/";
     if ($action == "audio_proxy") {
         $selection = new UserSelection($repository, $httpVars);
         // Backward compat
         $file = $selection->getUniqueFile();
         if (!file_exists($destStreamURL . $file) && strpos($httpVars["file"], "base64encoded:") === false) {
             // May be a backward compatibility problem, try to base64decode the filepath
             $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
             if (!file_exists($destStreamURL . $file)) {
                 throw new Exception("Cannot find file!");
             }
         }
         $cType = "audio/" . array_pop(explode(".", $file));
         $localName = basename($file);
         $node = new AJXP_Node($destStreamURL . $file);
         if (method_exists($node->getDriver(), "filesystemFileSize")) {
             $size = $node->getDriver()->filesystemFileSize($node->getUrl());
         } else {
             $size = filesize($node->getUrl());
         }
         header("Content-Type: " . $cType . "; name=\"" . $localName . "\"");
         header("Content-Length: " . $size);
         $stream = fopen("php://output", "a");
         call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
         fflush($stream);
         fclose($stream);
         AJXP_Controller::applyHook("node.read", array($node));
         $this->logInfo('Preview', 'Read content of ' . $node->getUrl());
         //exit(1);
     } else {
         if ($action == "ls") {
             if (!isset($httpVars["playlist"])) {
                 // This should not happen anyway, because of the applyCondition.
                 AJXP_Controller::passProcessDataThrough($postProcessData);
                 return;
             }
             // We transform the XML into XSPF
             $xmlString = $postProcessData["ob_output"];
             $xmlDoc = new DOMDocument();
             $xmlDoc->loadXML($xmlString);
             $xElement = $xmlDoc->documentElement;
             header("Content-Type:application/xspf+xml;charset=UTF-8");
             print '<?xml version="1.0" encoding="UTF-8"?>';
             print '<playlist version="1" xmlns="http://xspf.org/ns/0/">';
             print "<trackList>";
             foreach ($xElement->childNodes as $child) {
                 $isFile = $child->getAttribute("is_file") == "true";
                 $label = $child->getAttribute("text");
                 $ar = explode(".", $label);
                 $ext = strtolower(end($ar));
                 if (!$isFile || $ext != "mp3") {
                     continue;
                 }
                 print "<track><location>" . AJXP_SERVER_ACCESS . "?secure_token=" . AuthService::getSecureToken() . "&get_action=audio_proxy&file=" . base64_encode($child->getAttribute("filename")) . "</location><title>" . $label . "</title></track>";
             }
             print "</trackList>";
             AJXP_XMLWriter::close("playlist");
         }
     }
 }
 /**
  * @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);
             }
         }
     }
 }
 public function switchAction($action, $httpVars, $filesVars)
 {
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $selection = new UserSelection($repository, $httpVars);
     $selectedNode = $selection->getUniqueNode();
     $selectedNodeUrl = $selectedNode->getUrl();
     if ($action == "post_to_server") {
         // Backward compat
         if (strpos($httpVars["file"], "base64encoded:") !== 0) {
             $legacyFilePath = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
             $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $legacyFilePath);
             $selectedNodeUrl = $selectedNode->getUrl();
         }
         $target = rtrim(base64_decode($httpVars["parent_url"]), '/') . "/plugins/editor.pixlr";
         $tmp = AJXP_MetaStreamWrapper::getRealFSReference($selectedNodeUrl);
         $tmp = SystemTextEncoding::fromUTF8($tmp);
         $this->logInfo('Preview', 'Sending content of ' . $selectedNodeUrl . ' to Pixlr server.', array("files" => $selectedNodeUrl));
         AJXP_Controller::applyHook("node.read", array($selectedNode));
         $saveTarget = $target . "/fake_save_pixlr.php";
         if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) {
             $saveTarget = $target . "/fake_save_pixlr_" . md5($httpVars["secure_token"]) . ".php";
         }
         $params = array("referrer" => "Pydio", "method" => "get", "loc" => ConfService::getLanguage(), "target" => $saveTarget, "exit" => $target . "/fake_close_pixlr.php", "title" => urlencode(basename($selectedNodeUrl)), "locktarget" => "false", "locktitle" => "true", "locktype" => "source");
         require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
         $arguments = array();
         $httpClient = new http_class();
         $httpClient->request_method = "POST";
         $httpClient->GetRequestArguments("https://pixlr.com/editor/", $arguments);
         $arguments["PostValues"] = $params;
         $arguments["PostFiles"] = array("image" => array("FileName" => $tmp, "Content-Type" => "automatic/name"));
         $err = $httpClient->Open($arguments);
         if (empty($err)) {
             $err = $httpClient->SendRequest($arguments);
             if (empty($err)) {
                 $response = "";
                 while (true) {
                     $header = array();
                     $error = $httpClient->ReadReplyHeaders($header, 1000);
                     if ($error != "" || $header != null) {
                         break;
                     }
                     $response .= $header;
                 }
             }
         }
         header("Location: {$header['location']}");
         //$response");
     } else {
         if ($action == "retrieve_pixlr_image") {
             $file = AJXP_Utils::decodeSecureMagic($httpVars["original_file"]);
             $selectedNode = new AJXP_Node($selection->currentBaseUrl() . $file);
             $selectedNode->loadNodeInfo();
             $this->logInfo('Edit', 'Retrieving content of ' . $file . ' from Pixlr server.', array("files" => $file));
             AJXP_Controller::applyHook("node.before_change", array(&$selectedNode));
             $url = $httpVars["new_url"];
             $urlParts = parse_url($url);
             $query = $urlParts["query"];
             if ($this->getFilteredOption("CHECK_SECURITY_TOKEN", $repository->getId())) {
                 $scriptName = basename($urlParts["path"]);
                 $token = str_replace(array("fake_save_pixlr_", ".php"), "", $scriptName);
                 if ($token != md5($httpVars["secure_token"])) {
                     throw new AJXP_Exception("Invalid Token, this could mean some security problem!");
                 }
             }
             $params = array();
             parse_str($query, $params);
             $image = $params['image'];
             $headers = get_headers($image, 1);
             $content_type = explode("/", $headers['Content-Type']);
             if ($content_type[0] != "image") {
                 throw new AJXP_Exception("Invalid File Type");
             }
             $content_length = intval($headers["Content-Length"]);
             if ($content_length != 0) {
                 AJXP_Controller::applyHook("node.before_change", array(&$selectedNode, $content_length));
             }
             $orig = fopen($image, "r");
             $target = fopen($selectedNode->getUrl(), "w");
             if (is_resource($orig) && is_resource($target)) {
                 while (!feof($orig)) {
                     fwrite($target, fread($orig, 4096));
                 }
                 fclose($orig);
                 fclose($target);
             }
             clearstatcache(true, $selectedNode->getUrl());
             $selectedNode->loadNodeInfo(true);
             AJXP_Controller::applyHook("node.change", array(&$selectedNode, &$selectedNode));
         }
     }
 }
 public function switchActions($actionName, $httpVars, $fileVars)
 {
     //$urlBase = $this->accessDriver
     $repository = $this->accessDriver->repository;
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $selection = new UserSelection($repository, $httpVars);
     switch ($actionName) {
         case "filehasher_signature":
             $file = $selection->getUniqueNode();
             if (!file_exists($file->getUrl())) {
                 break;
             }
             $cacheItem = AJXP_Cache::getItem("signatures", $file->getUrl(), array($this, "generateSignature"));
             $data = $cacheItem->getData();
             header("Content-Type:application/octet-stream");
             header("Content-Length", strlen($data));
             echo $data;
             break;
         case "filehasher_delta":
         case "filehasher_patch":
             // HANDLE UPLOAD DATA
             $this->logDebug("Received signature file, should compute delta now");
             if (!isset($fileVars) && !is_array($fileVars["userfile_0"])) {
                 throw new Exception("These action should find uploaded data");
             }
             $signature_delta_file = $fileVars["userfile_0"]["tmp_name"];
             $fileUrl = $selection->getUniqueNode()->getUrl();
             $file = AJXP_MetaStreamWrapper::getRealFSReference($fileUrl, true);
             if ($actionName == "filehasher_delta") {
                 $deltaFile = tempnam(AJXP_Utils::getAjxpTmpDir(), $actionName . "-delta");
                 $this->logDebug("Received signature file, should compute delta now");
                 rsync_generate_delta($signature_delta_file, $file, $deltaFile);
                 $this->logDebug("Computed delta file, size is " . filesize($deltaFile));
                 header("Content-Type:application/octet-stream");
                 header("Content-Length:" . filesize($deltaFile));
                 readfile($deltaFile);
                 unlink($deltaFile);
             } else {
                 $patched = $file . ".rdiff_patched";
                 rsync_patch_file($file, $signature_delta_file, $patched);
                 rename($patched, $file);
                 $node = $selection->getUniqueNode();
                 AJXP_Controller::applyHook("node.change", array($node, $node, false));
                 header("Content-Type:text/plain");
                 echo md5_file($file);
             }
             break;
         case "stat_hash":
             clearstatcache();
             header("Content-type:application/json");
             if ($selection->isUnique()) {
                 $node = $selection->getUniqueNode();
                 $stat = @stat($node->getUrl());
                 if (!$stat || !is_readable($node->getUrl())) {
                     print '{}';
                 } else {
                     if (is_file($node->getUrl())) {
                         if (isset($_SERVER["HTTP_RANGE"])) {
                             $fullSize = floatval($stat['size']);
                             $ranges = explode('=', $_SERVER["HTTP_RANGE"]);
                             $offsets = explode('-', $ranges[1]);
                             $offset = floatval($offsets[0]);
                             $length = floatval($offsets[1]) - $offset;
                             if (!$length) {
                                 $length = $fullSize - $offset;
                             }
                             if ($length + $offset > $fullSize || $length < 0) {
                                 $length = $fullSize - $offset;
                             }
                             $hash = $this->getPartialHash($node, $offset, $length);
                         } else {
                             $hash = $this->getFileHash($selection->getUniqueNode());
                         }
                     } else {
                         $hash = 'directory';
                     }
                     $stat[13] = $stat["hash"] = $hash;
                     print json_encode($stat);
                 }
             } else {
                 $files = $selection->getFiles();
                 print '{';
                 foreach ($files as $index => $path) {
                     $node = new AJXP_Node($selection->currentBaseUrl() . $path);
                     $stat = @stat($selection->currentBaseUrl() . $path);
                     if (!$stat || !is_readable($node->getUrl())) {
                         $stat = '{}';
                     } else {
                         if (!is_dir($node->getUrl())) {
                             $hash = $this->getFileHash($node);
                         } else {
                             $hash = 'directory';
                         }
                         $stat[13] = $stat["hash"] = $hash;
                         $stat = json_encode($stat);
                     }
                     print json_encode(SystemTextEncoding::toUTF8($path)) . ':' . $stat . ($index < count($files) - 1 ? "," : "");
                 }
                 print '}';
             }
             break;
             break;
     }
 }
Exemple #29
0
    }
}
$loggedUser = AuthService::getLoggedUser();
if ($loggedUser != null) {
    if ($loggedUser->getPref("lang") != "") {
        ConfService::setLanguage($loggedUser->getPref("lang"));
    }
}
$mess = ConfService::getMessages();
foreach ($_GET as $getName => $getValue) {
    ${$getName} = Utils::securePath($getValue);
}
foreach ($_POST as $getName => $getValue) {
    ${$getName} = Utils::securePath($getValue);
}
$selection = new UserSelection();
$selection->initFromHttpVars();
if (isset($action) || isset($get_action)) {
    $action = isset($get_action) ? $get_action : $action;
} else {
    $action = "";
}
if (isset($dir) && $action != "upload") {
    $dir = SystemTextEncoding::fromUTF8($dir);
}
if (isset($dest)) {
    $dest = SystemTextEncoding::fromUTF8($dest);
}
//------------------------------------------------------------
// SPECIAL HANDLING FOR FANCY UPLOADER RIGHTS FOR THIS ACTION
//------------------------------------------------------------
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     $streamData = $repository->streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "post_to_zohoserver") {
         $sheetExt = explode(",", "xls,xlsx,ods,sxc,csv,tsv");
         $presExt = explode(",", "ppt,pps,odp,sxi");
         $docExt = explode(",", "doc,docx,rtf,odt,sxw");
         require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
         $selection = new UserSelection($repository, $httpVars);
         // Backward compat
         if (strpos($httpVars["file"], "base64encoded:") !== 0) {
             $file = AJXP_Utils::decodeSecureMagic(base64_decode($httpVars["file"]));
         } else {
             $file = $selection->getUniqueFile();
         }
         $target = base64_decode($httpVars["parent_url"]);
         $tmp = call_user_func(array($streamData["classname"], "getRealFSReference"), $destStreamURL . $file);
         $tmp = SystemTextEncoding::fromUTF8($tmp);
         $node = new AJXP_Node($destStreamURL . $file);
         AJXP_Controller::applyHook("node.read", array($node));
         $this->logInfo('Preview', 'Posting content of ' . $file . ' to Zoho server');
         $extension = strtolower(pathinfo(urlencode(basename($file)), PATHINFO_EXTENSION));
         $httpClient = new http_class();
         $httpClient->request_method = "POST";
         $secureToken = $httpVars["secure_token"];
         $_SESSION["ZOHO_CURRENT_EDITED"] = $destStreamURL . $file;
         $_SESSION["ZOHO_CURRENT_UUID"] = md5(rand() . "-" . microtime());
         if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) {
             $saveUrl = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId());
         } else {
             $saveUrl = $target . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/save_zoho.php";
         }
         $b64Sig = $this->signID($_SESSION["ZOHO_CURRENT_UUID"]);
         $params = array('id' => $_SESSION["ZOHO_CURRENT_UUID"], 'apikey' => $this->getFilteredOption("ZOHO_API_KEY", $repository->getId()), 'output' => 'url', 'lang' => "en", 'filename' => urlencode(basename($file)), 'persistence' => 'false', 'format' => $extension, 'mode' => 'normaledit', 'saveurl' => $saveUrl . "?signature=" . $b64Sig);
         $service = "exportwriter";
         if (in_array($extension, $sheetExt)) {
             $service = "sheet";
         } else {
             if (in_array($extension, $presExt)) {
                 $service = "show";
             } else {
                 if (in_array($extension, $docExt)) {
                     $service = "exportwriter";
                 }
             }
         }
         $arguments = array();
         $httpClient->GetRequestArguments("https://" . $service . ".zoho.com/remotedoc.im", $arguments);
         $arguments["PostValues"] = $params;
         $arguments["PostFiles"] = array("content" => array("FileName" => $tmp, "Content-Type" => "automatic/name"));
         $err = $httpClient->Open($arguments);
         if (empty($err)) {
             $err = $httpClient->SendRequest($arguments);
             if (empty($err)) {
                 $response = "";
                 while (true) {
                     $body = "";
                     $error = $httpClient->ReadReplyBody($body, 1000);
                     if ($error != "" || strlen($body) == 0) {
                         break;
                     }
                     $response .= $body;
                 }
                 $result = trim($response);
                 $matchlines = explode("\n", $result);
                 $resultValues = array();
                 foreach ($matchlines as $line) {
                     list($key, $val) = explode("=", $line, 2);
                     $resultValues[$key] = $val;
                 }
                 if ($resultValues["RESULT"] == "TRUE" && isset($resultValues["URL"])) {
                     header("Location: " . $resultValues["URL"]);
                 } else {
                     echo "Zoho API Error " . $resultValues["ERROR_CODE"] . " : " . $resultValues["WARNING"];
                     echo "<script>window.parent.setTimeout(function(){parent.hideLightBox();}, 2000);</script>";
                 }
             }
             $httpClient->Close();
         }
     } else {
         if ($action == "retrieve_from_zohoagent") {
             $targetFile = $_SESSION["ZOHO_CURRENT_EDITED"];
             $id = $_SESSION["ZOHO_CURRENT_UUID"];
             $ext = pathinfo($targetFile, PATHINFO_EXTENSION);
             $node = new AJXP_Node($targetFile);
             $node->loadNodeInfo();
             AJXP_Controller::applyHook("node.before_change", array(&$node));
             $b64Sig = $this->signID($id);
             if ($this->getFilteredOption("USE_ZOHO_AGENT", $repository->getId())) {
                 $url = $this->getFilteredOption("ZOHO_AGENT_URL", $repository->getId()) . "?ajxp_action=get_file&name=" . $id . "&ext=" . $ext . "&signature=" . $b64Sig;
                 $data = AJXP_Utils::getRemoteContent($url);
                 if (strlen($data)) {
                     file_put_contents($targetFile, $data);
                     echo "MODIFIED";
                 }
             } else {
                 if (is_file(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext)) {
                     copy(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext, $targetFile);
                     unlink(AJXP_INSTALL_PATH . "/" . AJXP_PLUGINS_FOLDER . "/editor.zoho/agent/files/" . $id . "." . $ext);
                     echo "MODIFIED";
                 }
             }
             $this->logInfo('Edit', 'Retrieved content of ' . $node->getUrl());
             AJXP_Controller::applyHook("node.change", array(null, &$node));
         }
     }
 }