public function resyncAction($actionName, $httpVars, $fileVars)
 {
     if (ConfService::backgroundActionsSupported() && !ConfService::currentContextIsCommandLine()) {
         AJXP_Controller::applyActionInBackground(ConfService::getRepository()->getId(), "resync_storage", $httpVars);
     } else {
         $file = $this->getResyncTimestampFile(true);
         file_put_contents($file, time());
         $this->indexIsSync();
     }
 }
 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;
     }
 }
 /**
  * @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);
             }
         }
     }
 }
 /**
  *
  * @param AJXP_Node $node
  * @param int $depth
  * @throws Exception
  */
 public function recursiveIndexation($node, $depth = 0)
 {
     $repository = $node->getRepository();
     $user = $node->getUser();
     $messages = ConfService::getMessages();
     if ($user == null && AuthService::usersEnabled()) {
         $user = AuthService::getLoggedUser();
     }
     if ($depth == 0) {
         $this->logDebug("Starting indexation - node.index.recursive.start  - " . memory_get_usage(true) . "  - " . $node->getUrl());
         $this->setIndexStatus("RUNNING", str_replace("%s", $node->getPath(), $messages["core.index.8"]), $repository, $user);
         AJXP_Controller::applyHook("node.index.recursive.start", array($node));
     } else {
         if ($this->isInterruptRequired($repository, $user)) {
             $this->logDebug("Interrupting indexation! - node.index.recursive.end - " . $node->getUrl());
             AJXP_Controller::applyHook("node.index.recursive.end", array($node));
             $this->releaseStatus($repository, $user);
             throw new Exception("User interrupted");
         }
     }
     if (!ConfService::currentContextIsCommandLine()) {
         @set_time_limit(120);
     }
     $url = $node->getUrl();
     $this->logDebug("Indexing Node parent node " . $url);
     $this->setIndexStatus("RUNNING", str_replace("%s", $node->getPath(), $messages["core.index.8"]), $repository, $user);
     try {
         AJXP_Controller::applyHook("node.index", array($node));
     } catch (Exception $e) {
         $this->logDebug("Error Indexing Node " . $url . " (" . $e->getMessage() . ")");
     }
     $handle = opendir($url);
     if ($handle !== false) {
         while (($child = readdir($handle)) != false) {
             if ($child[0] == ".") {
                 continue;
             }
             $childNode = new AJXP_Node(rtrim($url, "/") . "/" . $child);
             $childUrl = $childNode->getUrl();
             if (is_dir($childUrl)) {
                 $this->logDebug("Entering recursive indexation for " . $childUrl);
                 $this->recursiveIndexation($childNode, $depth + 1);
             } else {
                 try {
                     $this->logDebug("Indexing Node " . $childUrl);
                     AJXP_Controller::applyHook("node.index", array($childNode));
                 } catch (Exception $e) {
                     $this->logDebug("Error Indexing Node " . $childUrl . " (" . $e->getMessage() . ")");
                 }
             }
         }
         closedir($handle);
     } else {
         $this->logDebug("Cannot open {$url}!!");
     }
     if ($depth == 0) {
         $this->logDebug("End indexation - node.index.recursive.end - " . memory_get_usage(true) . "  -  " . $node->getUrl());
         $this->setIndexStatus("RUNNING", "Indexation finished, cleaning...", $repository, $user);
         AJXP_Controller::applyHook("node.index.recursive.end", array($node));
         $this->releaseStatus($repository, $user);
         $this->logDebug("End indexation - After node.index.recursive.end - " . memory_get_usage(true) . "  -  " . $node->getUrl());
     }
 }
 public function switchAction($action, $httpVars, $postProcessData)
 {
     switch ($action) {
         //------------------------------------
         // SHARING FILE OR FOLDER
         //------------------------------------
         case "scheduler_runAll":
             $tasks = AJXP_Utils::loadSerialFile($this->getDbFile(), false, "json");
             $message = "";
             $startRunning = $this->countCurrentlyRunning();
             $statuses = array();
             foreach ($tasks as $index => $task) {
                 $tasks[$index]["status"] = $this->getTaskStatus($task["task_id"]);
             }
             usort($tasks, array($this, "sortTasksByPriorityStatus"));
             foreach ($tasks as $task) {
                 if (isset($task["task_id"])) {
                     $res = $this->runTask($task["task_id"], $task["status"], $startRunning);
                     if ($res) {
                         $message .= "Running " . $task["label"] . " \n ";
                     }
                 }
             }
             if (empty($message)) {
                 $message = "Nothing to do";
             }
             if (ConfService::currentContextIsCommandLine()) {
                 print date("Y-m-d H:i:s") . "\t" . $message . "\n";
             } else {
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::sendMessage($message, null);
                 AJXP_XMLWriter::reloadDataNode();
                 AJXP_XMLWriter::close();
             }
             break;
         case "scheduler_runTask":
             $err = -1;
             $this->runTask($httpVars["task_id"], null, $err, true);
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::reloadDataNode();
             AJXP_XMLWriter::close();
             break;
         case "scheduler_generateCronExpression":
             $phpCmd = ConfService::getCoreConf("CLI_PHP");
             $rootInstall = AJXP_INSTALL_PATH . DIRECTORY_SEPARATOR . "cmd.php";
             $logFile = AJXP_CACHE_DIR . DIRECTORY_SEPARATOR . "cmd_outputs" . DIRECTORY_SEPARATOR . "cron_commands.log";
             $cronTiming = "*/5 * * * *";
             HTMLWriter::charsetHeader("text/plain", "UTF-8");
             print "{$cronTiming} {$phpCmd} {$rootInstall} -r=ajxp_conf -u=" . AuthService::getLoggedUser()->getId() . " -p=YOUR_PASSWORD_HERE -a=scheduler_runAll >> {$logFile}";
             break;
         default:
             break;
     }
 }
 function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     $dir = AJXP_Utils::securePath($dir);
     if ($dir == "/") {
         $dir = "";
     }
     $selection->initFromHttpVars($httpVars);
     if (!$selection->isEmpty()) {
         //$this->filterUserSelectionToHidden($selection->getFiles());
     }
     $urlBase = "ajxp.fs://" . 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 = $httpVars["archive_name"];
                     $jsCode = "\n                            \$('download_form').action = window.ajxpServerAccessPath;\n                            \$('download_form').secure_token.value = window.Connexion.SECURE_TOKEN;\n                            \$('download_form').select('input').each(function(input){\n                                if(input.name!='get_action' && input.name!='secure_token') input.remove();\n                            });\n                            \$('download_form').insert(new Element('input', {type:'hidden', name:'ope_id', value:'" . $httpVars["ope_id"] . "'}));\n                            \$('download_form').insert(new Element('input', {type:'hidden', name:'archive_name', value:'" . $archiveName . "'}));\n                            \$('download_form').insert(new Element('input', {type:'hidden', name:'get_action', value:'postcompress_download'}));\n                            \$('download_form').submit();\n                        ";
                     AJXP_XMLWriter::triggerBgJsAction($jsCode, "powerfs.3", true);
                     AJXP_XMLWriter::triggerBgAction("reload_node", array(), "powerfs.2", true, 2);
                 }
                 AJXP_XMLWriter::close();
             }
             break;
         case "postcompress_download":
             $archive = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["ope_id"] . "_" . $httpVars["archive_name"];
             //$fsDriver = new fsAccessDriver("fake", "");
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             $fsDriver->readFile($archive, "force-download", $httpVars["archive_name"], false, null, true);
             break;
         case "compress":
         case "precompress":
             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" => $dir, "archive_name" => $httpVars["archive_name"], "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) {
                 $args[] = '"' . 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);
                     }
                 }
             }
             $cmdSeparator = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows" ? "&" : ";";
             $archiveName = $httpVars["archive_name"];
             if (!$compressLocally) {
                 $archiveName = AJXP_Utils::getAjxpTmpDir() . "/" . $httpVars["ope_id"] . "_" . $archiveName;
             }
             chdir($rootDir);
             $cmd = "zip -r \"" . $archiveName . "\" " . implode(" ", $args);
             $fsDriver = AJXP_PluginsService::getInstance()->getUniqueActivePluginForType("access");
             $c = $fsDriver->getConfigs();
             if (!isset($c["SHOW_HIDDEN_FILES"]) || $c["SHOW_HIDDEN_FILES"] == 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, $fileVars)
 {
     //AJXP_Logger::logAction("DL file", $httpVars);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     if (isset($httpVars["file"])) {
         $parts = parse_url($httpVars["file"]);
         $getPath = $parts["path"];
         $basename = basename($getPath);
     }
     if (isset($httpVars["dlfile"])) {
         $dlFile = $streamData["protocol"] . "://" . $repository->getId() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]);
         $realFile = file_get_contents($dlFile);
         if (empty($realFile)) {
             throw new Exception("cannot find file {$dlFile} for download");
         }
         $parts = parse_url($realFile);
         $getPath = $parts["path"];
         $basename = basename($getPath);
     }
     switch ($action) {
         case "external_download":
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars);
                 if ($unixProcess !== null) {
                     @file_put_contents($destStreamURL . "." . $basename . ".pid", $unixProcess->getPid());
                 }
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             require_once AJXP_BIN_FOLDER . "/class.HttpClient.php";
             $mess = ConfService::getMessages();
             session_write_close();
             $client = new HttpClient($parts["host"]);
             $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => "");
             $client->setHeadersOnly(true, $collectHeaders);
             $client->setMaxRedirects(8);
             $client->setDebug(false);
             $client->get($getPath);
             $pidHiddenFileName = $destStreamURL . "." . $basename . ".pid";
             if (is_file($pidHiddenFileName)) {
                 $pid = file_get_contents($pidHiddenFileName);
                 @unlink($pidHiddenFileName);
             }
             AJXP_Logger::debug("COLLECTED HEADERS", $client->collectHeaders);
             $collectHeaders = $client->collectHeaders;
             $totalSize = -1;
             if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) {
                 $ar = explode("filename=", $collectHeaders["content-disposition"]);
                 $basename = trim(array_pop($ar));
                 $basename = str_replace("\"", "", $basename);
                 // Remove quotes
             }
             if (!empty($collectHeaders["content-length"])) {
                 $totalSize = intval($collectHeaders["content-length"]);
                 AJXP_Logger::debug("Should download {$totalSize} bytes!");
             }
             if ($totalSize != -1) {
                 $node = new AJXP_Node($destStreamURL . $basename);
                 AJXP_Controller::applyHook("node.before_create", array($node, $totalSize));
             }
             $qData = false;
             if (!empty($collectHeaders["ajxp-last-redirection"])) {
                 $newParsed = parse_url($collectHeaders["ajxp-last-redirection"]);
                 $client->host = $newParsed["host"];
                 $getPath = $newParsed["path"];
                 if (isset($newParsed["query"])) {
                     $qData = parse_url($newParsed["query"]);
                 }
             }
             $tmpFilename = $destStreamURL . $basename . ".dlpart";
             $hiddenFilename = $destStreamURL . "__" . $basename . ".ser";
             $filename = $destStreamURL . $basename;
             $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize);
             if (isset($pid)) {
                 $dlData["pid"] = $pid;
             }
             //file_put_contents($hiddenFilename, serialize($dlData));
             $fpHid = fopen($hiddenFilename, "w");
             fputs($fpHid, serialize($dlData));
             fclose($fpHid);
             $client->redirect_count = 0;
             $client->setHeadersOnly(false);
             $destStream = fopen($tmpFilename, "w");
             if ($destStream !== false) {
                 $client->writeContentToStream($destStream);
                 $client->get($getPath, $qData);
                 fclose($destStream);
             }
             rename($tmpFilename, $filename);
             unlink($hiddenFilename);
             if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) {
                 AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($dlFile)));
                 unlink($dlFile);
                 AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false));
             }
             AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false));
             AJXP_XMLWriter::header();
             AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]);
             AJXP_XMLWriter::close();
             exit;
             break;
         case "update_dl_data":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             header("text/plain");
             if (is_file($destStreamURL . $file)) {
                 echo filesize($destStreamURL . $file);
             } else {
                 echo "stop";
             }
             exit;
             break;
         case "stop_dl":
             $newName = "__" . str_replace(".dlpart", ".ser", $basename);
             $hiddenFilename = $destStreamURL . $newName;
             $data = @unserialize(@file_get_contents($hiddenFilename));
             header("text/plain");
             AJXP_Logger::debug("Getting {$hiddenFilename}", $data);
             if (isset($data["pid"])) {
                 $process = new UnixProcess();
                 $process->setPid($data["pid"]);
                 $process->stop();
                 unlink($hiddenFilename);
                 unlink($destStreamURL . $basename);
                 echo 'stop';
             } else {
                 echo 'failed';
             }
             exit;
             break;
         default:
             break;
     }
     return true;
 }
 public function recursiveIndexation($url)
 {
     //print("Indexing $url \n");
     $this->logDebug("Indexing content of folder " . $url);
     if (ConfService::currentContextIsCommandLine() && $this->verboseIndexation) {
         print "Indexing content of " . $url . "\n";
     }
     @set_time_limit(60);
     $handle = opendir($url);
     if ($handle !== false) {
         while (($child = readdir($handle)) != false) {
             if ($child[0] == ".") {
                 continue;
             }
             $newUrl = $url . "/" . $child;
             $this->logDebug("Indexing Node " . $newUrl);
             try {
                 $this->updateNodeIndex(null, new AJXP_Node($newUrl));
             } catch (Exception $e) {
                 $this->logDebug("Error Indexing Node " . $newUrl . " (" . $e->getMessage() . ")");
             }
         }
         closedir($handle);
     } else {
         $this->logDebug("Cannot open {$url}!!");
     }
 }
 public function switchAction($action, $httpVars, $fileVars)
 {
     //$this->logInfo("DL file", $httpVars);
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(false)) {
         return false;
     }
     $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType());
     $streamData = $plugin->detectStreamWrapper(true);
     $dir = AJXP_Utils::decodeSecureMagic($httpVars["dir"]);
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $dir . "/";
     $dlURL = null;
     if (isset($httpVars["file"])) {
         $parts = parse_url($httpVars["file"]);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $httpVars["file"];
     }
     if (isset($httpVars["dlfile"])) {
         $dlFile = $streamData["protocol"] . "://" . $repository->getId() . AJXP_Utils::decodeSecureMagic($httpVars["dlfile"]);
         $realFile = file_get_contents($dlFile);
         if (empty($realFile)) {
             throw new Exception("cannot find file {$dlFile} for download");
         }
         $parts = parse_url($realFile);
         $getPath = $parts["path"];
         $basename = basename($getPath);
         $dlURL = $realFile;
     }
     switch ($action) {
         case "external_download":
             if (!ConfService::currentContextIsCommandLine() && ConfService::backgroundActionsSupported()) {
                 $unixProcess = AJXP_Controller::applyActionInBackground($repository->getId(), "external_download", $httpVars);
                 if ($unixProcess !== null) {
                     @file_put_contents($destStreamURL . "." . $basename . ".pid", $unixProcess->getPid());
                 }
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), "Triggering DL ", true, 2);
                 AJXP_XMLWriter::close();
                 session_write_close();
                 exit;
             }
             require_once AJXP_BIN_FOLDER . "/http_class/http_class.php";
             session_write_close();
             $httpClient = new http_class();
             $arguments = array();
             $httpClient->GetRequestArguments($httpVars["file"], $arguments);
             $err = $httpClient->Open($arguments);
             $collectHeaders = array("ajxp-last-redirection" => "", "content-disposition" => "", "content-length" => "");
             if (empty($err)) {
                 $err = $httpClient->SendRequest($arguments);
                 $httpClient->follow_redirect = true;
                 $pidHiddenFileName = $destStreamURL . "." . $basename . ".pid";
                 if (is_file($pidHiddenFileName)) {
                     $pid = file_get_contents($pidHiddenFileName);
                     @unlink($pidHiddenFileName);
                 }
                 if (empty($err)) {
                     $httpClient->ReadReplyHeaders($collectHeaders);
                     $totalSize = -1;
                     if (!empty($collectHeaders["content-disposition"]) && strstr($collectHeaders["content-disposition"], "filename") !== false) {
                         $ar = explode("filename=", $collectHeaders["content-disposition"]);
                         $basename = trim(array_pop($ar));
                         $basename = str_replace("\"", "", $basename);
                         // Remove quotes
                     }
                     if (!empty($collectHeaders["content-length"])) {
                         $totalSize = intval($collectHeaders["content-length"]);
                         $this->logDebug("Should download {$totalSize} bytes!");
                     }
                     if ($totalSize != -1) {
                         $node = new AJXP_Node($destStreamURL . $basename);
                         AJXP_Controller::applyHook("node.before_create", array($node, $totalSize));
                     }
                     $tmpFilename = $destStreamURL . $basename . ".dlpart";
                     $hiddenFilename = $destStreamURL . "__" . $basename . ".ser";
                     $filename = $destStreamURL . $basename;
                     $dlData = array("sourceUrl" => $getPath, "totalSize" => $totalSize);
                     if (isset($pid)) {
                         $dlData["pid"] = $pid;
                     }
                     //file_put_contents($hiddenFilename, serialize($dlData));
                     $fpHid = fopen($hiddenFilename, "w");
                     fputs($fpHid, serialize($dlData));
                     fclose($fpHid);
                     // NOW READ RESPONSE
                     $destStream = fopen($tmpFilename, "w");
                     while (true) {
                         $body = "";
                         $error = $httpClient->ReadReplyBody($body, 1000);
                         if ($error != "" || strlen($body) == 0) {
                             break;
                         }
                         fwrite($destStream, $body, strlen($body));
                     }
                     fclose($destStream);
                     rename($tmpFilename, $filename);
                     unlink($hiddenFilename);
                 }
                 $httpClient->Close();
                 if (isset($dlFile) && isset($httpVars["delete_dlfile"]) && is_file($dlFile)) {
                     AJXP_Controller::applyHook("node.before_path_change", array(new AJXP_Node($dlFile)));
                     unlink($dlFile);
                     AJXP_Controller::applyHook("node.change", array(new AJXP_Node($dlFile), null, false));
                 }
                 $mess = ConfService::getMessages();
                 AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($filename), false));
                 AJXP_XMLWriter::header();
                 AJXP_XMLWriter::triggerBgAction("reload_node", array(), $mess["httpdownloader.8"]);
                 AJXP_XMLWriter::close();
             }
             break;
         case "update_dl_data":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             header("text/plain");
             if (is_file($destStreamURL . $file)) {
                 $node = new AJXP_Node($destStreamURL . $file);
                 if (method_exists($node->getDriver(), "filesystemFileSize")) {
                     $filesize = $node->getDriver()->filesystemFileSize($node->getUrl());
                 } else {
                     $filesize = filesize($node->getUrl());
                 }
                 echo $filesize;
             } else {
                 echo "stop";
             }
             break;
         case "stop_dl":
             $newName = "__" . str_replace(".dlpart", ".ser", $basename);
             $hiddenFilename = $destStreamURL . $newName;
             $data = @unserialize(@file_get_contents($hiddenFilename));
             header("text/plain");
             $this->logDebug("Getting {$hiddenFilename}", $data);
             if (isset($data["pid"])) {
                 $process = new UnixProcess();
                 $process->setPid($data["pid"]);
                 $process->stop();
                 unlink($hiddenFilename);
                 unlink($destStreamURL . $basename);
                 echo 'stop';
             } else {
                 echo 'failed';
             }
             break;
         default:
             break;
     }
     return false;
 }
Beispiel #10
0
 public function switchAction($action, $httpVars, $fileVars)
 {
     if (!isset($this->actions[$action])) {
         return;
     }
     parent::accessPreprocess($action, $httpVars, $fileVars);
     $selection = new UserSelection();
     $dir = $httpVars["dir"] or "";
     if ($this->wrapperClassName == "fsAccessWrapper") {
         $dir = fsAccessWrapper::patchPathForBaseDir($dir);
     }
     $dir = AJXP_Utils::securePath($dir);
     if ($action != "upload") {
         $dir = AJXP_Utils::decodeSecureMagic($dir);
     }
     $selection->initFromHttpVars($httpVars);
     if (!$selection->isEmpty()) {
         $this->filterUserSelectionToHidden($selection->getFiles());
     }
     $mess = ConfService::getMessages();
     $newArgs = RecycleBinManager::filterActions($action, $selection, $dir, $httpVars);
     if (isset($newArgs["action"])) {
         $action = $newArgs["action"];
     }
     if (isset($newArgs["dest"])) {
         $httpVars["dest"] = SystemTextEncoding::toUTF8($newArgs["dest"]);
     }
     //Re-encode!
     // FILTER DIR PAGINATION ANCHOR
     $page = null;
     if (isset($dir) && strstr($dir, "%23") !== false) {
         $parts = explode("%23", $dir);
         $dir = $parts[0];
         $page = $parts[1];
     }
     $pendingSelection = "";
     $logMessage = null;
     $reloadContextNode = false;
     switch ($action) {
         //------------------------------------
         //	DOWNLOAD
         //------------------------------------
         case "download":
             $this->logInfo("Download", array("files" => $this->addSlugToPath($selection)));
             @set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE);
             @register_shutdown_function("restore_error_handler");
             $zip = false;
             if ($selection->isUnique()) {
                 if (is_dir($this->urlBase . $selection->getUniqueFile())) {
                     $zip = true;
                     $base = basename($selection->getUniqueFile());
                     $uniqDir = dirname($selection->getUniqueFile());
                     if (!empty($uniqDir) && $uniqDir != "/") {
                         $dir = dirname($selection->getUniqueFile());
                     }
                 } else {
                     if (!file_exists($this->urlBase . $selection->getUniqueFile())) {
                         throw new Exception("Cannot find file!");
                     }
                 }
                 $node = $selection->getUniqueNode($this);
             } else {
                 $zip = true;
             }
             if ($zip) {
                 // Make a temp zip and send it as download
                 $loggedUser = AuthService::getLoggedUser();
                 $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpDownload.zip";
                 $zipFile = $this->makeZip($selection->getFiles(), $file, empty($dir) ? "/" : $dir);
                 if (!$zipFile) {
                     throw new AJXP_Exception("Error while compressing");
                 }
                 if (!$this->getFilteredOption("USE_XSENDFILE", $this->repository->getId()) && !$this->getFilteredOption("USE_XACCELREDIRECT", $this->repository->getId())) {
                     register_shutdown_function("unlink", $file);
                 }
                 $localName = ($base == "" ? "Files" : $base) . ".zip";
                 if (isset($httpVars["archive_name"])) {
                     $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]);
                 }
                 $this->readFile($file, "force-download", $localName, false, false, true);
             } else {
                 $localName = "";
                 AJXP_Controller::applyHook("dl.localname", array($this->urlBase . $selection->getUniqueFile(), &$localName, $this->wrapperClassName));
                 $this->readFile($this->urlBase . $selection->getUniqueFile(), "force-download", $localName);
             }
             if (isset($node)) {
                 AJXP_Controller::applyHook("node.read", array(&$node));
             }
             break;
         case "prepare_chunk_dl":
             $chunkCount = intval($httpVars["chunk_count"]);
             $fileId = $this->urlBase . $selection->getUniqueFile();
             $sessionKey = "chunk_file_" . md5($fileId . time());
             $totalSize = $this->filesystemFileSize($fileId);
             $chunkSize = intval($totalSize / $chunkCount);
             $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $fileId, true);
             $chunkData = array("localname" => basename($fileId), "chunk_count" => $chunkCount, "chunk_size" => $chunkSize, "total_size" => $totalSize, "file_id" => $sessionKey);
             $_SESSION[$sessionKey] = array_merge($chunkData, array("file" => $realFile));
             HTMLWriter::charsetHeader("application/json");
             print json_encode($chunkData);
             $node = $selection->getUniqueNode($this);
             AJXP_Controller::applyHook("node.read", array(&$node));
             break;
         case "download_chunk":
             $chunkIndex = intval($httpVars["chunk_index"]);
             $chunkKey = $httpVars["file_id"];
             $sessData = $_SESSION[$chunkKey];
             $realFile = $sessData["file"];
             $chunkSize = $sessData["chunk_size"];
             $offset = $chunkSize * $chunkIndex;
             if ($chunkIndex == $sessData["chunk_count"] - 1) {
                 // Compute the last chunk real length
                 $chunkSize = $sessData["total_size"] - $chunkSize * ($sessData["chunk_count"] - 1);
                 if (call_user_func(array($this->wrapperClassName, "isRemote"))) {
                     register_shutdown_function("unlink", $realFile);
                 }
             }
             $this->readFile($realFile, "force-download", $sessData["localname"] . "." . sprintf("%03d", $chunkIndex + 1), false, false, true, $offset, $chunkSize);
             break;
         case "compress":
             // Make a temp zip and send it as download
             $loggedUser = AuthService::getLoggedUser();
             if (isset($httpVars["archive_name"])) {
                 $localName = AJXP_Utils::decodeSecureMagic($httpVars["archive_name"]);
                 $this->filterUserSelectionToHidden(array($localName));
             } else {
                 $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip";
             }
             $file = AJXP_Utils::getAjxpTmpDir() . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "_" . time() . "tmpCompression.zip";
             if (isset($httpVars["compress_flat"])) {
                 $baseDir = "__AJXP_ZIP_FLAT__/";
             } else {
                 $baseDir = $dir;
             }
             $zipFile = $this->makeZip($selection->getFiles(), $file, $baseDir);
             if (!$zipFile) {
                 throw new AJXP_Exception("Error while compressing file {$localName}");
             }
             register_shutdown_function("unlink", $file);
             $tmpFNAME = $this->urlBase . $dir . "/" . str_replace(".zip", ".tmp", $localName);
             copy($file, $tmpFNAME);
             try {
                 AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($tmpFNAME), filesize($tmpFNAME)));
             } catch (Exception $e) {
                 @unlink($tmpFNAME);
                 throw $e;
             }
             @rename($tmpFNAME, $this->urlBase . $dir . "/" . $localName);
             AJXP_Controller::applyHook("node.change", array(null, new AJXP_Node($this->urlBase . $dir . "/" . $localName), false));
             //$reloadContextNode = true;
             //$pendingSelection = $localName;
             $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $localName);
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             $nodesDiffs["ADD"][] = $newNode;
             break;
         case "stat":
             clearstatcache();
             header("Content-type:application/json");
             if ($selection->isUnique()) {
                 $stat = @stat($this->urlBase . $selection->getUniqueFile());
                 if (!$stat) {
                     print '{}';
                 } else {
                     print json_encode($stat);
                 }
             } else {
                 $files = $selection->getFiles();
                 print '{';
                 foreach ($files as $index => $path) {
                     $stat = @stat($this->urlBase . $path);
                     if (!$stat) {
                         $stat = '{}';
                     } else {
                         $stat = json_encode($stat);
                     }
                     print json_encode($path) . ':' . $stat . ($index < count($files) - 1 ? "," : "");
                 }
                 print '}';
             }
             break;
             //------------------------------------
             //	ONLINE EDIT
             //------------------------------------
         //------------------------------------
         //	ONLINE EDIT
         //------------------------------------
         case "get_content":
             $dlFile = $this->urlBase . $selection->getUniqueFile();
             $this->logInfo("Get_content", array("files" => $this->addSlugToPath($selection)));
             if (AJXP_Utils::getStreamingMimeType(basename($dlFile)) !== false) {
                 $this->readFile($this->urlBase . $selection->getUniqueFile(), "stream_content");
             } else {
                 $this->readFile($this->urlBase . $selection->getUniqueFile(), "plain");
             }
             $node = $selection->getUniqueNode($this);
             AJXP_Controller::applyHook("node.read", array(&$node));
             break;
         case "put_content":
             if (!isset($httpVars["content"])) {
                 break;
             }
             // Load "code" variable directly from POST array, do not "securePath" or "sanitize"...
             $code = $httpVars["content"];
             $file = $selection->getUniqueFile();
             $this->logInfo("Online Edition", array("file" => $this->addSlugToPath($file)));
             if (isset($httpVars["encode"]) && $httpVars["encode"] == "base64") {
                 $code = base64_decode($code);
             } else {
                 $code = str_replace("&lt;", "<", SystemTextEncoding::magicDequote($code));
             }
             $fileName = $this->urlBase . $file;
             $currentNode = new AJXP_Node($fileName);
             try {
                 AJXP_Controller::applyHook("node.before_change", array(&$currentNode, strlen($code)));
             } catch (Exception $e) {
                 header("Content-Type:text/plain");
                 print $e->getMessage();
                 return;
             }
             if (!is_file($fileName) || !$this->isWriteable($fileName, "file")) {
                 header("Content-Type:text/plain");
                 print !$this->isWriteable($fileName, "file") ? "1001" : "1002";
                 return;
             }
             $fp = fopen($fileName, "w");
             fputs($fp, $code);
             fclose($fp);
             clearstatcache(true, $fileName);
             AJXP_Controller::applyHook("node.change", array($currentNode, $currentNode, false));
             header("Content-Type:text/plain");
             print $mess[115];
             break;
             //------------------------------------
             //	COPY / MOVE
             //------------------------------------
         //------------------------------------
         //	COPY / MOVE
         //------------------------------------
         case "copy":
         case "move":
             //throw new AJXP_Exception("", 113);
             if ($selection->isEmpty()) {
                 throw new AJXP_Exception("", 113);
             }
             $loggedUser = AuthService::getLoggedUser();
             if ($loggedUser != null && !$loggedUser->canWrite(ConfService::getCurrentRepositoryId())) {
                 throw new AJXP_Exception("You are not allowed to write", 207);
             }
             $success = $error = array();
             $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]);
             $this->filterUserSelectionToHidden(array($httpVars["dest"]));
             if ($selection->inZip()) {
                 // Set action to copy anycase (cannot move from the zip).
                 $action = "copy";
                 $this->extractArchive($dest, $selection, $error, $success);
             } else {
                 $move = $action == "move" ? true : false;
                 if ($move && isset($httpVars["force_copy_delete"])) {
                     $move = false;
                 }
                 $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $move);
             }
             if (count($error)) {
                 throw new AJXP_Exception(SystemTextEncoding::toUTF8(join("\n", $error)));
             } else {
                 if (isset($httpVars["force_copy_delete"])) {
                     $errorMessage = $this->delete($selection->getFiles(), $logMessages);
                     if ($errorMessage) {
                         throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage));
                     }
                     $this->logInfo("Copy/Delete", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest)));
                 } else {
                     $this->logInfo($action == "move" ? "Move" : "Copy", array("files" => $this->addSlugToPath($selection), "destination" => $this->addSlugToPath($dest)));
                 }
                 $logMessage = join("\n", $success);
             }
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             // Assume new nodes are correctly created
             $selectedItems = $selection->getFiles();
             foreach ($selectedItems as $selectedPath) {
                 $newPath = $this->urlBase . $dest . "/" . basename($selectedPath);
                 $newNode = new AJXP_Node($newPath);
                 $nodesDiffs["ADD"][] = $newNode;
                 if ($action == "move") {
                     $nodesDiffs["REMOVE"][] = $selectedPath;
                 }
             }
             if (!(RecycleBinManager::getRelativeRecycle() == $dest && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) == true)) {
                 //$reloadDataNode = $dest;
             }
             break;
             //------------------------------------
             //	DELETE
             //------------------------------------
         //------------------------------------
         //	DELETE
         //------------------------------------
         case "delete":
             if ($selection->isEmpty()) {
                 throw new AJXP_Exception("", 113);
             }
             $logMessages = array();
             $errorMessage = $this->delete($selection->getFiles(), $logMessages);
             if (count($logMessages)) {
                 $logMessage = join("\n", $logMessages);
             }
             if ($errorMessage) {
                 throw new AJXP_Exception(SystemTextEncoding::toUTF8($errorMessage));
             }
             $this->logInfo("Delete", array("files" => $this->addSlugToPath($selection)));
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             $nodesDiffs["REMOVE"] = array_merge($nodesDiffs["REMOVE"], $selection->getFiles());
             break;
         case "purge":
             $hardPurgeTime = intval($this->repository->getOption("PURGE_AFTER")) * 3600 * 24;
             $softPurgeTime = intval($this->repository->getOption("PURGE_AFTER_SOFT")) * 3600 * 24;
             $shareCenter = AJXP_PluginsService::findPluginById('action.share');
             if (!($shareCenter && $shareCenter->isEnabled())) {
                 //action.share is disabled, don't look at the softPurgeTime
                 $softPurgeTime = 0;
             }
             if ($hardPurgeTime > 0 || $softPurgeTime > 0) {
                 $this->recursivePurge($this->urlBase, $hardPurgeTime, $softPurgeTime);
             }
             break;
             //------------------------------------
             //	RENAME
             //------------------------------------
         //------------------------------------
         //	RENAME
         //------------------------------------
         case "rename":
             $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             $filename_new = AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]);
             $dest = null;
             if (isset($httpVars["dest"])) {
                 $dest = AJXP_Utils::decodeSecureMagic($httpVars["dest"]);
                 $filename_new = "";
             }
             $this->filterUserSelectionToHidden(array($filename_new));
             $this->rename($file, $filename_new, $dest);
             $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new);
             //$reloadContextNode = true;
             //$pendingSelection = $filename_new;
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             if ($dest == null) {
                 $dest = AJXP_Utils::safeDirname($file);
             }
             $nodesDiffs["UPDATE"][$file] = new AJXP_Node($this->urlBase . $dest . "/" . $filename_new);
             $this->logInfo("Rename", array("original" => $this->addSlugToPath($file), "new" => $filename_new));
             break;
             //------------------------------------
             //	CREER UN REPERTOIRE / CREATE DIR
             //------------------------------------
         //------------------------------------
         //	CREER UN REPERTOIRE / CREATE DIR
         //------------------------------------
         case "mkdir":
             $messtmp = "";
             if (!isset($httpVars["dirname"])) {
                 $uniq = $selection->getUniqueFile();
                 $dir = AJXP_Utils::safeDirname($uniq);
                 $dirname = AJXP_Utils::safeBasename($uniq);
             } else {
                 $dirname = AJXP_Utils::decodeSecureMagic($httpVars["dirname"], AJXP_SANITIZE_FILENAME);
             }
             $dirname = substr($dirname, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
             $this->filterUserSelectionToHidden(array($dirname));
             AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($dir . "/" . $dirname), -2));
             $error = $this->mkDir($dir, $dirname, isset($httpVars["ignore_exists"]) ? true : false);
             if (isset($error)) {
                 throw new AJXP_Exception($error);
             }
             $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             //$pendingSelection = $dirname;
             //$reloadContextNode = true;
             $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $dirname);
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             array_push($nodesDiffs["ADD"], $newNode);
             $this->logInfo("Create Dir", array("dir" => $this->addSlugToPath($dir) . "/" . $dirname));
             break;
             //------------------------------------
             //	CREER UN FICHIER / CREATE FILE
             //------------------------------------
         //------------------------------------
         //	CREER UN FICHIER / CREATE FILE
         //------------------------------------
         case "mkfile":
             $messtmp = "";
             if (empty($httpVars["filename"]) && isset($httpVars["node"])) {
                 $filename = AJXP_Utils::decodeSecureMagic($httpVars["node"], AJXP_SANITIZE_FILENAME);
             } else {
                 $filename = AJXP_Utils::decodeSecureMagic($httpVars["filename"], AJXP_SANITIZE_FILENAME);
             }
             $filename = substr($filename, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
             $this->filterUserSelectionToHidden(array($filename));
             $content = "";
             if (isset($httpVars["content"])) {
                 $content = $httpVars["content"];
             }
             $error = $this->createEmptyFile($dir, $filename, $content);
             if (isset($error)) {
                 throw new AJXP_Exception($error);
             }
             $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} ";
             if ($dir == "") {
                 $messtmp .= "/";
             } else {
                 $messtmp .= SystemTextEncoding::toUTF8($dir);
             }
             $logMessage = $messtmp;
             //$reloadContextNode = true;
             //$pendingSelection = $dir."/".$filename;
             $this->logInfo("Create File", array("file" => $this->addSlugToPath($dir) . "/" . $filename));
             $newNode = new AJXP_Node($this->urlBase . $dir . "/" . $filename);
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             array_push($nodesDiffs["ADD"], $newNode);
             break;
             //------------------------------------
             //	CHANGE FILE PERMISSION
             //------------------------------------
         //------------------------------------
         //	CHANGE FILE PERMISSION
         //------------------------------------
         case "chmod":
             $files = $selection->getFiles();
             $changedFiles = array();
             $chmod_value = $httpVars["chmod_value"];
             $recursive = $httpVars["recursive"];
             $recur_apply_to = $httpVars["recur_apply_to"];
             foreach ($files as $fileName) {
                 $this->chmod($fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles);
             }
             $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders";
             $this->logInfo("Chmod", array("dir" => $this->addSlugToPath($dir), "filesCount" => count($changedFiles)));
             if (!isset($nodesDiffs)) {
                 $nodesDiffs = $this->getNodesDiffArray();
             }
             $nodesDiffs["UPDATE"] = array_merge($nodesDiffs["UPDATE"], $selection->buildNodes($this));
             break;
             //------------------------------------
             //	UPLOAD
             //------------------------------------
         //------------------------------------
         //	UPLOAD
         //------------------------------------
         case "upload":
             $repoData = array('base_url' => $this->urlBase, 'wrapper_name' => $this->wrapperClassName, 'chmod' => $this->repository->getOption('CHMOD_VALUE'), 'recycle' => $this->repository->getOption('RECYCLE_BIN'));
             $this->logDebug("Upload Files Data", $fileVars);
             $destination = $this->urlBase . AJXP_Utils::decodeSecureMagic($dir);
             $this->logDebug("Upload inside", array("destination" => $this->addSlugToPath($destination)));
             if (!$this->isWriteable($destination)) {
                 $errorCode = 412;
                 $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}.";
                 $this->logDebug("Upload error 412", array("destination" => $this->addSlugToPath($destination)));
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             }
             foreach ($fileVars as $boxName => $boxData) {
                 if (substr($boxName, 0, 9) != "userfile_") {
                     continue;
                 }
                 $err = AJXP_Utils::parseFileDataErrors($boxData);
                 if ($err != null) {
                     $errorCode = $err[0];
                     $errorMessage = $err[1];
                     break;
                 }
                 $userfile_name = $boxData["name"];
                 try {
                     $this->filterUserSelectionToHidden(array($userfile_name));
                 } catch (Exception $e) {
                     return array("ERROR" => array("CODE" => 411, "MESSAGE" => "Forbidden"));
                 }
                 $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromPostedFileName($userfile_name), AJXP_SANITIZE_FILENAME);
                 if (isset($httpVars["urlencoded_filename"])) {
                     $userfile_name = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["urlencoded_filename"])), AJXP_SANITIZE_FILENAME);
                 }
                 $this->logDebug("User filename " . $userfile_name);
                 $userfile_name = substr($userfile_name, 0, ConfService::getCoreConf("NODENAME_MAX_LENGTH"));
                 if (isset($httpVars["auto_rename"])) {
                     $userfile_name = self::autoRenameForDest($destination, $userfile_name);
                 }
                 $already_existed = false;
                 try {
                     if (file_exists($destination . "/" . $userfile_name)) {
                         $already_existed = true;
                         AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"]));
                     } else {
                         AJXP_Controller::applyHook("node.before_create", array(new AJXP_Node($destination . "/" . $userfile_name), $boxData["size"]));
                     }
                     AJXP_Controller::applyHook("node.before_change", array(new AJXP_Node($destination)));
                 } catch (Exception $e) {
                     $errorCode = 507;
                     $errorMessage = $e->getMessage();
                     break;
                 }
                 if (isset($boxData["input_upload"])) {
                     try {
                         $this->logDebug("Begining reading INPUT stream");
                         $input = fopen("php://input", "r");
                         $output = fopen("{$destination}/" . $userfile_name, "w");
                         $sizeRead = 0;
                         while ($sizeRead < intval($boxData["size"])) {
                             $chunk = fread($input, 4096);
                             $sizeRead += strlen($chunk);
                             fwrite($output, $chunk, strlen($chunk));
                         }
                         fclose($input);
                         fclose($output);
                         $this->logDebug("End reading INPUT stream");
                     } catch (Exception $e) {
                         $errorCode = 411;
                         $errorMessage = $e->getMessage();
                         break;
                     }
                 } else {
                     $result = @move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name);
                     if (!$result) {
                         $realPath = call_user_func(array($this->wrapperClassName, "getRealFSReference"), "{$destination}/" . $userfile_name);
                         $result = move_uploaded_file($boxData["tmp_name"], $realPath);
                     }
                     if (!$result) {
                         $errorCode = 411;
                         $errorMessage = "{$mess['33']} " . $userfile_name;
                         break;
                     }
                 }
                 if (isset($httpVars["appendto_urlencoded_part"])) {
                     $appendTo = AJXP_Utils::sanitize(SystemTextEncoding::fromUTF8(urldecode($httpVars["appendto_urlencoded_part"])), AJXP_SANITIZE_FILENAME);
                     if (file_exists($destination . "/" . $appendTo)) {
                         $this->logDebug("Should copy stream from {$userfile_name} to {$appendTo}");
                         $partO = fopen($destination . "/" . $userfile_name, "r");
                         $appendF = fopen($destination . "/" . $appendTo, "a+");
                         while (!feof($partO)) {
                             $buf = fread($partO, 1024);
                             fwrite($appendF, $buf, strlen($buf));
                         }
                         fclose($partO);
                         fclose($appendF);
                         $this->logDebug("Done, closing streams!");
                     }
                     @unlink($destination . "/" . $userfile_name);
                     $userfile_name = $appendTo;
                 }
                 $this->changeMode($destination . "/" . $userfile_name, $repoData);
                 $createdNode = new AJXP_Node($destination . "/" . $userfile_name);
                 //AJXP_Controller::applyHook("node.change", array(null, $createdNode, false));
                 $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}";
                 $this->logInfo("Upload File", array("file" => $this->addSlugToPath(SystemTextEncoding::fromUTF8($dir)) . "/" . $userfile_name));
             }
             if (isset($errorMessage)) {
                 $this->logDebug("Return error {$errorCode} {$errorMessage}");
                 return array("ERROR" => array("CODE" => $errorCode, "MESSAGE" => $errorMessage));
             } else {
                 $this->logDebug("Return success");
                 if ($already_existed) {
                     return array("SUCCESS" => true, "UPDATED_NODE" => $createdNode);
                 } else {
                     return array("SUCCESS" => true, "CREATED_NODE" => $createdNode);
                 }
             }
             return;
             break;
         case "lsync":
             if (!ConfService::currentContextIsCommandLine()) {
                 die("This command must be accessed via CLI only.");
             }
             $fromNode = null;
             $toNode = null;
             $copyOrMove = false;
             if (isset($httpVars["from"])) {
                 $fromNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["from"]));
             }
             if (isset($httpVars["to"])) {
                 $toNode = new AJXP_Node($this->urlBase . AJXP_Utils::decodeSecureMagic($httpVars["to"]));
             }
             if (isset($httpVars["copy"]) && $httpVars["copy"] == "true") {
                 $copyOrMove = true;
             }
             AJXP_Controller::applyHook("node.change", array($fromNode, $toNode, $copyOrMove));
             break;
             //------------------------------------
             //	XML LISTING
             //------------------------------------
         //------------------------------------
         //	XML LISTING
         //------------------------------------
         case "ls":
             if (!isset($dir) || $dir == "/") {
                 $dir = "";
             }
             $lsOptions = $this->parseLsOptions(isset($httpVars["options"]) ? $httpVars["options"] : "a");
             $startTime = microtime();
             if (isset($httpVars["file"])) {
                 $uniqueFile = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
             }
             $dir = AJXP_Utils::securePath($dir);
             $path = $this->urlBase . ($dir != "" ? ($dir[0] == "/" ? "" : "/") . $dir : "");
             $nonPatchedPath = $path;
             if ($this->wrapperClassName == "fsAccessWrapper") {
                 $nonPatchedPath = fsAccessWrapper::unPatchPathForBaseDir($path);
             }
             if ($this->getFilteredOption("REMOTE_SORTING")) {
                 $orderDirection = isset($httpVars["order_direction"]) ? strtolower($httpVars["order_direction"]) : "asc";
                 $orderField = isset($httpVars["order_column"]) ? $httpVars["order_column"] : null;
                 if ($orderField != null && !in_array($orderField, array("ajxp_label", "filesize", "ajxp_modiftime", "mimestring"))) {
                     $orderField = "ajxp_label";
                 }
             }
             if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") {
                 $max_depth = isset($httpVars["max_depth"]) ? intval($httpVars["max_depth"]) : 0;
                 $max_nodes = isset($httpVars["max_nodes"]) ? intval($httpVars["max_nodes"]) : 0;
                 $crt_depth = isset($httpVars["crt_depth"]) ? intval($httpVars["crt_depth"]) + 1 : 1;
                 $crt_nodes = isset($httpVars["crt_nodes"]) ? intval($httpVars["crt_nodes"]) : 0;
             } else {
                 $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;
                 }
             }
             $countFiles = $this->countFiles($path, !$lsOptions["f"]);
             if (isset($crt_nodes)) {
                 $crt_nodes += $countFiles;
             }
             if (isset($threshold) && isset($limitPerPage) && $countFiles > $threshold) {
                 if (isset($uniqueFile)) {
                     $originalLimitPerPage = $limitPerPage;
                     $offset = $limitPerPage = 0;
                 } else {
                     $offset = 0;
                     $crtPage = 1;
                     if (isset($page)) {
                         $offset = (intval($page) - 1) * $limitPerPage;
                         $crtPage = $page;
                     }
                     $totalPages = floor($countFiles / $limitPerPage) + 1;
                 }
             } else {
                 $offset = $limitPerPage = 0;
             }
             $metaData = array();
             if (RecycleBinManager::recycleEnabled() && $dir == "") {
                 $metaData["repo_has_recycle"] = "true";
             }
             $parentAjxpNode = new AJXP_Node($nonPatchedPath, $metaData);
             $parentAjxpNode->loadNodeInfo(false, true, $lsOptions["l"] ? "all" : "minimal");
             AJXP_Controller::applyHook("node.read", array(&$parentAjxpNode));
             if (AJXP_XMLWriter::$headerSent == "tree") {
                 AJXP_XMLWriter::renderAjxpNode($parentAjxpNode, false);
             } else {
                 AJXP_XMLWriter::renderAjxpHeaderNode($parentAjxpNode);
             }
             if (isset($totalPages) && isset($crtPage)) {
                 $remoteOptions = null;
                 if ($this->getFilteredOption("REMOTE_SORTING")) {
                     $remoteOptions = array("remote_order" => "true", "currentOrderCol" => isset($orderField) ? $orderField : "ajxp_label", "currentOrderDir" => isset($orderDirection) ? $orderDirection : "asc");
                 }
                 AJXP_XMLWriter::renderPaginationData($countFiles, $crtPage, $totalPages, $this->countFiles($path, TRUE), $remoteOptions);
                 if (!$lsOptions["f"]) {
                     AJXP_XMLWriter::close();
                     exit(1);
                 }
             }
             $cursor = 0;
             $handle = opendir($path);
             if (!$handle) {
                 throw new AJXP_Exception("Cannot open dir " . $nonPatchedPath);
             }
             closedir($handle);
             $fullList = array("d" => array(), "z" => array(), "f" => array());
             if (isset($orderField) && isset($orderDirection) && $orderField == "ajxp_label" && $orderDirection == "desc") {
                 $nodes = scandir($path, 1);
             } else {
                 $nodes = scandir($path);
             }
             if (!empty($this->driverConf["SCANDIR_RESULT_SORTFONC"])) {
                 usort($nodes, $this->driverConf["SCANDIR_RESULT_SORTFONC"]);
             }
             if (isset($orderField) && isset($orderDirection) && $orderField != "ajxp_label") {
                 $toSort = array();
                 foreach ($nodes as $node) {
                     if ($orderField == "filesize") {
                         $toSort[$node] = is_file($nonPatchedPath . "/" . $node) ? $this->filesystemFileSize($nonPatchedPath . "/" . $node) : 0;
                     } else {
                         if ($orderField == "ajxp_modiftime") {
                             $toSort[$node] = filemtime($nonPatchedPath . "/" . $node);
                         } else {
                             if ($orderField == "mimestring") {
                                 $toSort[$node] = pathinfo($node, PATHINFO_EXTENSION);
                             }
                         }
                     }
                 }
                 if ($orderDirection == "asc") {
                     asort($toSort);
                 } else {
                     arsort($toSort);
                 }
                 $nodes = array_keys($toSort);
             }
             //while (strlen($nodeName = readdir($handle)) > 0) {
             foreach ($nodes as $nodeName) {
                 if ($nodeName == "." || $nodeName == "..") {
                     continue;
                 }
                 if (isset($uniqueFile) && $nodeName != $uniqueFile) {
                     $cursor++;
                     continue;
                 }
                 if ($offset > 0 && $cursor < $offset) {
                     $cursor++;
                     continue;
                 }
                 $isLeaf = "";
                 if (!$this->filterNodeName($path, $nodeName, $isLeaf, $lsOptions)) {
                     continue;
                 }
                 if (RecycleBinManager::recycleEnabled() && $dir == "" && "/" . $nodeName == RecycleBinManager::getRecyclePath()) {
                     continue;
                 }
                 if ($limitPerPage > 0 && $cursor - $offset >= $limitPerPage) {
                     break;
                 }
                 $currentFile = $nonPatchedPath . "/" . $nodeName;
                 $meta = array();
                 if ($isLeaf != "") {
                     $meta = array("is_file" => $isLeaf ? "1" : "0");
                 }
                 $node = new AJXP_Node($currentFile, $meta);
                 $node->setLabel($nodeName);
                 $node->loadNodeInfo(false, false, $lsOptions["l"] ? "all" : "minimal");
                 if (!empty($node->metaData["nodeName"]) && $node->metaData["nodeName"] != $nodeName) {
                     $node->setUrl($nonPatchedPath . "/" . $node->metaData["nodeName"]);
                 }
                 if (!empty($node->metaData["hidden"]) && $node->metaData["hidden"] === true) {
                     continue;
                 }
                 if (!empty($node->metaData["mimestring_id"]) && array_key_exists($node->metaData["mimestring_id"], $mess)) {
                     $node->mergeMetadata(array("mimestring" => $mess[$node->metaData["mimestring_id"]]));
                 }
                 if (isset($originalLimitPerPage) && $cursor > $originalLimitPerPage) {
                     $node->mergeMetadata(array("page_position" => floor($cursor / $originalLimitPerPage) + 1));
                 }
                 $nodeType = "d";
                 if ($node->isLeaf()) {
                     if (AJXP_Utils::isBrowsableArchive($nodeName)) {
                         if ($lsOptions["f"] && $lsOptions["z"]) {
                             $nodeType = "f";
                         } else {
                             $nodeType = "z";
                         }
                     } else {
                         $nodeType = "f";
                     }
                 }
                 // There is a special sorting, cancel the reordering of files & folders.
                 if (isset($orderField) && $orderField != "ajxp_label") {
                     $nodeType = "f";
                 }
                 $fullList[$nodeType][$nodeName] = $node;
                 $cursor++;
                 if (isset($uniqueFile) && $nodeName != $uniqueFile) {
                     break;
                 }
             }
             if (isset($httpVars["recursive"]) && $httpVars["recursive"] == "true") {
                 $breakNow = false;
                 if (isset($max_depth) && $max_depth > 0 && $crt_depth >= $max_depth) {
                     $breakNow = true;
                 }
                 if (isset($max_nodes) && $max_nodes > 0 && $crt_nodes >= $max_nodes) {
                     $breakNow = true;
                 }
                 foreach ($fullList["d"] as &$nodeDir) {
                     if ($breakNow) {
                         $nodeDir->mergeMetadata(array("ajxp_has_children" => $this->countFiles($nodeDir->getUrl(), false, true) ? "true" : "false"));
                         AJXP_XMLWriter::renderAjxpNode($nodeDir, true);
                         continue;
                     }
                     $this->switchAction("ls", array("dir" => SystemTextEncoding::toUTF8($nodeDir->getPath()), "options" => $httpVars["options"], "recursive" => "true", "max_depth" => $max_depth, "max_nodes" => $max_nodes, "crt_depth" => $crt_depth, "crt_nodes" => $crt_nodes), array());
                 }
             } else {
                 array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["d"]);
             }
             array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["z"]);
             array_map(array("AJXP_XMLWriter", "renderAjxpNode"), $fullList["f"]);
             // ADD RECYCLE BIN TO THE LIST
             if ($dir == "" && !$uniqueFile && RecycleBinManager::recycleEnabled() && $this->getFilteredOption("HIDE_RECYCLE", $this->repository->getId()) !== true) {
                 $recycleBinOption = RecycleBinManager::getRelativeRecycle();
                 if (file_exists($this->urlBase . $recycleBinOption)) {
                     $recycleNode = new AJXP_Node($this->urlBase . $recycleBinOption);
                     $recycleNode->loadNodeInfo();
                     AJXP_XMLWriter::renderAjxpNode($recycleNode);
                 }
             }
             $this->logDebug("LS Time : " . intval((microtime() - $startTime) * 1000) . "ms");
             AJXP_XMLWriter::close();
             break;
     }
     $xmlBuffer = "";
     if (isset($logMessage) || isset($errorMessage)) {
         $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false);
     }
     if ($reloadContextNode) {
         if (!isset($pendingSelection)) {
             $pendingSelection = "";
         }
         $xmlBuffer .= AJXP_XMLWriter::reloadDataNode("", $pendingSelection, false);
     }
     if (isset($reloadDataNode)) {
         $xmlBuffer .= AJXP_XMLWriter::reloadDataNode($reloadDataNode, "", false);
     }
     if (isset($nodesDiffs)) {
         $xmlBuffer .= AJXP_XMLWriter::writeNodesDiff($nodesDiffs, false);
     }
     return $xmlBuffer;
 }