/** * Creates a new file in the directory * * Data will either be supplied as a stream resource, or in certain cases * as a string. Keep in mind that you may have to support either. * * After succesful creation of the file, you may choose to return the ETag * of the new file here. * * The returned ETag must be surrounded by double-quotes (The quotes should * be part of the actual string). * * If you cannot accurately determine the ETag, you should not return it. * If you don't store the file exactly as-is (you're transforming it * somehow) you should also not return an ETag. * * This means that if a subsequent GET to this new file does not exactly * return the same contents of what was submitted here, you are strongly * recommended to omit the ETag. * * @param string $name Name of the file * @param resource|string $data Initial payload * @return null|string */ public function createFile($name, $data = null) { try { $name = ltrim($name, "/"); AJXP_Logger::debug("CREATE FILE {$name}"); AJXP_Controller::findActionAndApply("mkfile", array("dir" => $this->path, "filename" => $name), array()); if ($data != null && is_file($this->getUrl() . "/" . $name)) { $p = $this->path . "/" . $name; $this->getAccessDriver()->nodeWillChange($p, intval($_SERVER["CONTENT_LENGTH"])); //AJXP_Logger::debug("Should now copy stream or string in ".$this->getUrl()."/".$name); if (is_resource($data)) { $stream = fopen($this->getUrl() . "/" . $name, "w"); stream_copy_to_stream($data, $stream); fclose($stream); } else { if (is_string($data)) { file_put_contents($data, $this->getUrl() . "/" . $name); } } $toto = null; $this->getAccessDriver()->nodeChanged($toto, $p); } $node = new AJXP_Sabre_NodeLeaf($this->path . "/" . $name, $this->repository, $this->getAccessDriver()); if (isset($this->children)) { $this->children = null; } return $node->getETag(); } catch (Exception $e) { AJXP_Logger::debug("Error " . $e->getMessage(), $e->getTraceAsString()); return null; } }
public function postProcess($action, $httpVars, $postProcessData) { if (!isset($httpVars["simple_uploader"]) && !isset($httpVars["xhr_uploader"])) { return false; } AJXP_Logger::debug("SimpleUploadProc is active"); $result = $postProcessData["processor_result"]; if (isset($httpVars["simple_uploader"])) { print "<html><script language=\"javascript\">\n"; if (isset($result["ERROR"])) { $message = $result["ERROR"]["MESSAGE"] . " (" . $result["ERROR"]["CODE"] . ")"; print "\n if(parent.ajaxplorer.actionBar.multi_selector) parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $message) . "');"; } else { print "\n if(parent.ajaxplorer.actionBar.multi_selector) parent.ajaxplorer.actionBar.multi_selector.submitNext();"; } print "</script></html>"; } else { if (isset($result["ERROR"])) { $message = $result["ERROR"]["MESSAGE"] . " (" . $result["ERROR"]["CODE"] . ")"; exit($message); } else { exit("OK"); } } }
protected function parseSpecificContributions(&$contribNode) { parent::parseSpecificContributions($contribNode); if (isset($this->actions["share"])) { $disableSharing = false; $downloadFolder = ConfService::getCoreConf("PUBLIC_DOWNLOAD_FOLDER"); if ($downloadFolder == "") { $disableSharing = true; } else { if (!is_dir($downloadFolder) || !is_writable($downloadFolder)) { AJXP_Logger::debug("Disabling Public links, {$downloadFolder} is not writeable!", array("folder" => $downloadFolder, "is_dir" => is_dir($downloadFolder), "is_writeable" => is_writable($downloadFolder))); $disableSharing = true; } else { if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && AuthService::isReservedUserId($loggedUser->getId())) { $disableSharing = true; } } else { $disableSharing = true; } } } if ($disableSharing) { unset($this->actions["share"]); $actionXpath = new DOMXPath($contribNode->ownerDocument); $publicUrlNodeList = $actionXpath->query('action[@name="share"]', $contribNode); $publicUrlNode = $publicUrlNodeList->item(0); $contribNode->removeChild($publicUrlNode); } } }
/** Construction. This kills the current session if any started, and restart the given session */ public function __construct($name, $killPreviousSession = false, $loadPreviousSession = false, $saveHandlerType = "files", $saveHandlerData = null) { AJXP_Logger::debug("Switching to session " . $name); if (session_id() == "") { if (isset($saveHandlerData)) { session_set_save_handler($saveHandlerData["open"], $saveHandlerData["close"], $saveHandlerData["read"], $saveHandlerData["write"], $saveHandlerData["destroy"], $saveHandlerData["gc"]); } else { if (ini_get("session.save_handler") != $saveHandlerType) { ini_set('session.save_handler', $saveHandlerType); } } // Start a default session and save on the handler session_start(); SessionSwitcher::$sessionArray[] = array('id' => session_id(), 'name' => session_name()); session_write_close(); } else { SessionSwitcher::$sessionArray[] = array('id' => session_id(), 'name' => session_name()); } // Please note that there is no start here, session might be already started if (session_id() != "") { // There was a previous session if ($killPreviousSession) { if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 42000, '/'); } session_destroy(); } AJXP_Logger::debug("Closing previous session " . session_name() . " / " . session_id()); session_write_close(); session_regenerate_id(false); $_SESSION = array(); } if (isset($saveHandlerData)) { session_set_save_handler($saveHandlerData["open"], $saveHandlerData["close"], $saveHandlerData["read"], $saveHandlerData["write"], $saveHandlerData["destroy"], $saveHandlerData["gc"]); } else { if (ini_get("session.save_handler") != $saveHandlerType) { ini_set('session.save_handler', $saveHandlerType); } } if ($loadPreviousSession) { AJXP_Logger::debug("Restoring previous session" . SessionSwitcher::$sessionArray[0]['id']); session_id(SessionSwitcher::$sessionArray[0]['id']); } else { $newId = md5(SessionSwitcher::$sessionArray[0]['id'] . $name); session_id($newId); } session_name($name); session_start(); AJXP_Logger::debug("Restarted session " . session_name() . " / " . session_id(), $_SESSION); }
function initRepository() { if (is_array($this->pluginConf)) { $this->driverConf = $this->pluginConf; } else { $this->driverConf = array(); } $wrapperData = $this->detectStreamWrapper(true); AJXP_Logger::debug("Detected wrapper data", $wrapperData); $this->wrapperClassName = $wrapperData["classname"]; $this->urlBase = $wrapperData["protocol"] . "://" . $this->repository->getId(); $consumerKey = $this->repository->getOption("CONSUMER_KEY"); $consumerSecret = $this->repository->getOption("CONSUMER_SECRET"); $oauth = new Dropbox_OAuth_PEAR($consumerKey, $consumerSecret); // TOKENS IN SESSION? if (!empty($_SESSION["OAUTH_DROPBOX_TOKENS"])) { return; } // TOKENS IN FILE ? $tokens = $this->getTokens($this->repository->getId()); if (!empty($tokens)) { $_SESSION["OAUTH_DROPBOX_TOKENS"] = $tokens; return; } // OAUTH NEGOCIATION if (isset($_SESSION['DROPBOX_NEGOCIATION_STATE'])) { $state = $_SESSION['DROPBOX_NEGOCIATION_STATE']; } else { $state = 1; } switch ($state) { case 1: $tokens = $oauth->getRequestToken(); //print_r($tokens); // Note that if you want the user to automatically redirect back, you can // add the 'callback' argument to getAuthorizeUrl. //echo "Step 2: You must now redirect the user to:\n"; $_SESSION['DROPBOX_NEGOCIATION_STATE'] = 2; $_SESSION['oauth_tokens'] = $tokens; throw new Exception("Please go to <a style=\"text-decoration:underline;\" target=\"_blank\" href=\"" . $oauth->getAuthorizeUrl() . "\">" . $oauth->getAuthorizeUrl() . "</a> to authorize the access to your dropbox. Then try again to switch to this repository."); case 2: $oauth->setToken($_SESSION['oauth_tokens']); $tokens = $oauth->getAccessToken(); $_SESSION['DROPBOX_NEGOCIATION_STATE'] = 3; $_SESSION['OAUTH_DROPBOX_TOKENS'] = $tokens; $this->setTokens($this->repository->getId(), $tokens); return; } throw new Exception("Impossible to find the tokens for accessing the dropbox repository"); }
/** * Initialize the stream from the given path. * Concretely, transform ajxp.webdav:// into webdav:// * * @param string $path * @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path */ protected static function initPath($path, $streamType, $storeOpenContext = false, $skipZip = false) { $url = AJXP_Utils::safeParseUrl($path); $repoId = $url["host"]; $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { $e = new Exception("Cannot find repository with id " . $repoId); self::$lastException = $e; throw $e; } $path = $url["path"]; $host = $repoObject->getOption("HOST"); $hostParts = parse_url($host); if ($hostParts["scheme"] == "https" && !extension_loaded("openssl")) { $e = new Exception("Warning you must have the openssl PHP extension loaded to connect an https server!"); self::$lastException = $e; throw $e; } $credentials = AJXP_Safe::tryLoadingCredentialsFromSources($hostParts, $repoObject); $user = $credentials["user"]; $password = $credentials["password"]; if ($user != null && $password != null) { $host = ($hostParts["scheme"] == "https" ? "webdavs" : "webdav") . "://{$user}:{$password}@" . $hostParts["host"]; if (isset($hostParts["port"])) { $host .= ":" . $hostParts["port"]; } } else { $host = str_replace(array("http", "https"), array("webdav", "webdavs"), $host); } // MAKE SURE THERE ARE NO // OR PROBLEMS LIKE THAT... $basePath = $repoObject->getOption("PATH"); if ($basePath[strlen($basePath) - 1] == "/") { $basePath = substr($basePath, 0, -1); } if ($basePath[0] != "/") { $basePath = "/{$basePath}"; } $path = AJXP_Utils::securePath($path); if ($path[0] == "/") { $path = substr($path, 1); } // SHOULD RETURN webdav://host_server/uri/to/webdav/folder AJXP_Logger::debug(__CLASS__, __FUNCTION__, $host . $basePath . "/" . $path); return $host . $basePath . "/" . $path; }
public function postProcess($action, $httpVars, $postProcessData) { if (!self::$active) { return false; } AJXP_Logger::debug("FlexProc is active=" . self::$active, $postProcessData); $result = $postProcessData["processor_result"]; if (isset($result["SUCCESS"]) && $result["SUCCESS"] === true) { header('HTTP/1.0 200 OK'); //die("200 OK"); } else { if (isset($result["ERROR"]) && is_array($result["ERROR"])) { $code = $result["ERROR"]["CODE"]; $message = $result["ERROR"]["MESSAGE"]; //header("HTTP/1.0 $code $message"); die("Error {$code} {$message}"); } } }
function makeZip($src, $dest, $basedir) { @set_time_limit(0); require_once AJXP_BIN_FOLDER . "/pclzip.lib.php"; $filePaths = array(); foreach ($src as $item) { $realFile = call_user_func(array($this->wrapperClassName, "getRealFSReference"), $this->urlBase . "/" . AJXP_Utils::securePath($item)); $basedir = trim(dirname($realFile)); $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $realFile, PCLZIP_ATT_FILE_NEW_SHORT_NAME => basename($item)); } AJXP_Logger::debug("Pathes", $filePaths); AJXP_Logger::debug("Basedir", array($basedir)); self::$filteringDriverInstance = $this; $archive = new PclZip($dest); $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_PATH, $basedir, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_ADD_TEMP_FILE_ON); if (!$vList) { throw new Exception("Zip creation error : ({$dest}) " . $archive->errorInfo(true)); } self::$filteringDriverInstance = null; return $vList; }
public function init($options) { parent::init($options); if (!extension_loaded("openssl")) { return; } $keyFile = $this->getPluginWorkDir(true) . "/agent.pem"; if (file_exists($keyFile)) { return; } $config = array("digest_alg" => "sha1", "private_key_bits" => 1024, "private_key_type" => OPENSSL_KEYTYPE_RSA); // Create the private and public key $res = openssl_pkey_new($config); if ($res === false) { AJXP_Logger::error(__CLASS__, __FUNCTION__, "Warning, OpenSSL is active but could not correctly generate a key for Zoho Editor. Please make sure the openssl.cnf file is correctly set up."); while ($message = openssl_error_string()) { AJXP_Logger::debug(__CLASS__, __FUNCTION__, "Open SSL Error: " . $message); } } else { openssl_pkey_export_to_file($res, $keyFile); } }
/** Construction. This kills the current session if any started, and restart the given session */ public function __construct($name, $cleanPreviousSession = false) { if (session_id() == "") { // Mysterious fix, necessary for joomla. ini_set('session.save_handler', 'files'); // Start a default session and save on the handler session_start(); SessionSwitcher::$sessionArray[] = array('id' => session_id(), 'name' => session_name()); AJXP_Logger::debug("Session switching 1: ", SessionSwitcher::$sessionArray); session_write_close(); } else { SessionSwitcher::$sessionArray[] = array('id' => session_id(), 'name' => session_name()); } // Please note that there is no start here, session might be already started if (session_id() != "") { // There was a previous session if ($cleanPreviousSession) { if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 42000, '/'); } session_destroy(); } // Close the session session_write_close(); session_regenerate_id(false); $_SESSION = array(); // Need to generate a new session id } // Mysterious fix, necessary for joomla. ini_set('session.save_handler', 'files'); $newId = md5(SessionSwitcher::$sessionArray[0]['id'] . $name); AJXP_Logger::debug("Session switching new id: ", $newId); session_id($newId); session_name($name); session_start(); }
public function copyOrMoveSelection($actionName, &$httpVars, $filesVars) { if ($actionName != "rename") { $init = $this->initDirAndSelection($httpVars, array("DEST_DIR" => AJXP_Utils::decodeSecureMagic($httpVars["dest"]))); $this->commitMessageParams = "To:" . $httpVars["dest"] . ";items:"; } else { $init = $this->initDirAndSelection($httpVars, array(), true); } AJXP_Logger::debug("Entering SVN MAnager for action {$actionName}", $init); $action = 'copy'; if ($actionName == "move" || $actionName == "rename") { $action = 'move'; } foreach ($init["SELECTION"] as $selectedFile) { if ($actionName == "rename") { $destFile = dirname($selectedFile) . "/" . AJXP_Utils::decodeSecureMagic($httpVars["filename_new"]); $this->commitMessageParams = "To:" . $httpVars["filename_new"] . ";item:" . $httpVars["file"]; } else { $destFile = $init["DEST_DIR"] . "/" . basename($selectedFile); } $this->addIfNotVersionned(str_replace($init["DIR"], "", $selectedFile), $selectedFile); $res = ExecSvnCmd("svn {$action}", array($selectedFile, $destFile), ''); } if ($actionName != "rename") { $this->commitMessageParams .= "[" . implode(",", $init["SELECTION"]) . "]"; } $this->commitChanges($actionName, $httpVars, $filesVars); if ($actionName != "rename") { $this->commitChanges($actionName, array("dir" => $httpVars["dest"]), $filesVars); } AJXP_Logger::logAction("CopyMove/Rename (svn delegate)", array("files" => $init["SELECTION"])); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage("The selected files/folders have been copied/moved (by SVN)", null); AJXP_XMLWriter::reloadDataNode(); AJXP_XMLWriter::close(); }
$requestUri = $_SERVER["REQUEST_URI"]; $end = trim(substr($requestUri, strlen($baseURI . "/"))); $rId = null; if ((!empty($end) || $end === "0") && $end[0] != "?") { $parts = explode("/", $end); $pathBase = $parts[0]; $repositoryId = $pathBase; $repository = ConfService::getRepositoryById($repositoryId); if ($repository == null) { $repository = ConfService::getRepositoryByAlias($repositoryId); if ($repository != null) { $repositoryId = $repository->getId(); } } if ($repository == null) { AJXP_Logger::debug("not found, dying {$repositoryId}"); die('You are not allowed to access this service'); } $rId = $repositoryId; $rootDir = new AJXP_Sabre_Collection("/", $repository, null); $server = new Sabre\DAV\Server($rootDir); $server->setBaseUri($baseURI . "/" . $pathBase); } else { $rootDir = new AJXP_Sabre_RootCollection("root"); $server = new Sabre\DAV\Server($rootDir); $server->setBaseUri($baseURI); } if ((AJXP_Sabre_AuthBackendBasic::detectBasicHeader() || ConfService::getCoreConf("WEBDAV_FORCE_BASIC")) && ConfService::getAuthDriverImpl()->getOption("TRANSMIT_CLEAR_PASS")) { $authBackend = new AJXP_Sabre_AuthBackendBasic($rId); } else { $authBackend = new AJXP_Sabre_AuthBackendDigest($rId);
public function checkPassword($login, $pass, $seed) { if (!extension_loaded('radius')) { AJXP_Logger::logAction("RADIUS: php radius extension is missing, please install it."); return false; } $res = radius_auth_open(); $this->prepareRequest($res, $login, $pass, $seed); $req = radius_send_request($res); if (!$req) { AJXP_Logger::debug(__CLASS__, __FUNCTION__, "RADIUS: Could not send request (" . radius_strerror($res) . ")"); return false; } switch ($req) { case RADIUS_ACCESS_ACCEPT: AJXP_Logger::debug(__CLASS__, __FUNCTION__, "RADIUS: authentication for user \"" . $login . "\" successful"); radius_close($res); return true; case RADIUS_ACCESS_REJECT: AJXP_Logger::logAction("RADIUS: authentication for user \"" . $login . "\" failed"); break; default: AJXP_Logger::debug(__CLASS__, __FUNCTION__, "RADIUS: unknwon return value " . $req); break; } radius_close($res); return false; }
/** * Determines whether the user is try to make many attemps * @static * @param $loginArray * @return bool */ static function checkBruteForceLogin(&$loginArray) { $serverAddress = ""; if (isset($_SERVER['REMOTE_ADDR'])) { $serverAddress = $_SERVER['REMOTE_ADDR']; } else { $serverAddress = $_SERVER['SERVER_ADDR']; } $login = null; if (isset($loginArray[$serverAddress])) { $login = $loginArray[$serverAddress]; } if (is_array($login)) { $login["count"]++; } else { $login = array("count" => 1, "time" => time()); } $loginArray[$serverAddress] = $login; if ($login["count"] > 3) { if (AJXP_SERVER_DEBUG) { AJXP_Logger::debug("DEBUG : IGNORING BRUTE FORCE ATTEMPTS!"); return true; } return FALSE; } return TRUE; }
/** * @param $cmd * @param $logFile * @return UnixProcess|null */ public static function runCommandInBackground($cmd, $logFile) { if (PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows") { if (AJXP_SERVER_DEBUG) { $cmd .= " > " . $logFile; } if (class_exists("COM") && ConfService::getCoreConf("CLI_USE_COM")) { $WshShell = new COM("WScript.Shell"); $oExec = $WshShell->Run("cmd /C {$cmd}", 0, false); } else { $basePath = str_replace("/", DIRECTORY_SEPARATOR, AJXP_INSTALL_PATH); $tmpBat = implode(DIRECTORY_SEPARATOR, array($basePath, "data", "tmp", md5(time()) . ".bat")); $cmd = "@chcp 1252 > nul \r\n" . $cmd; $cmd .= "\n DEL " . chr(34) . $tmpBat . chr(34); AJXP_Logger::debug("Writing file {$cmd} to {$tmpBat}"); file_put_contents($tmpBat, $cmd); pclose(popen('start /b "CLI" "' . $tmpBat . '"', 'r')); } } else { $process = new UnixProcess($cmd, AJXP_SERVER_DEBUG ? $logFile : null); AJXP_Logger::debug("Starting process and sending output dev null"); return $process; } }
/** * @param AJXP_Node $node */ public function checkFileLock($node) { AJXP_Logger::debug("SHOULD CHECK LOCK METADATA FOR ", $node->getLabel()); $lock = $this->metaStore->retrieveMetadata($node, SimpleLockManager::METADATA_LOCK_NAMESPACE, false, AJXP_METADATA_SCOPE_GLOBAL); if (is_array($lock) && array_key_exists("lock_user", $lock) && $lock["lock_user"] != AuthService::getLoggedUser()->getId()) { $mess = ConfService::getMessages(); throw new Exception($mess["meta.simple_lock.5"]); } }
public function umountFS() { AJXP_Logger::debug("FSMounter::unmountFS"); list($user, $password) = $this->getCredentials(); $MOUNT_POINT = $this->getOption("MOUNT_POINT", $user, $password); $MOUNT_SUDO = $this->options["MOUNT_SUDO"]; system(($MOUNT_SUDO ? "sudo" : "") . " umount " . $MOUNT_POINT); return true; }
/** * Build the current server URL * @param bool $withURI * @static * @return string */ public static function detectServerURL($withURI = false) { $setUrl = ConfService::getCoreConf("SERVER_URL"); if (!empty($setUrl)) { return $setUrl; } if (php_sapi_name() == "cli") { AJXP_Logger::debug("WARNING, THE SERVER_URL IS NOT SET, WE CANNOT BUILD THE MAIL ADRESS WHEN WORKING IN CLI"); } $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http'; $port = $protocol === 'http' && $_SERVER['SERVER_PORT'] == 80 || $protocol === 'https' && $_SERVER['SERVER_PORT'] == 443 ? "" : ":" . $_SERVER['SERVER_PORT']; $name = $_SERVER["SERVER_NAME"]; if (!$withURI) { return "{$protocol}://{$name}{$port}"; } else { $uri = dirname($_SERVER["REQUEST_URI"]); $api = ConfService::currentContextIsRestAPI(); if (!empty($api)) { // Keep only before api base $explode = explode("/" . $api . "/", $uri); $uri = array_shift($explode); } return "{$protocol}://{$name}{$port}" . $uri; } }
function storeFileToCopy($fileData) { $user = AuthService::getLoggedUser(); $files = $user->getTemporaryData("tmp_upload"); $files[] = $fileData; AJXP_Logger::debug("Storing data", $fileData); $user->saveTemporaryData("tmp_upload", $files); if (strpos($_SERVER["HTTP_USER_AGENT"], "ajaxplorer-ios-client") !== false || strpos($_SERVER["HTTP_USER_AGENT"], "Apache-HttpClient") !== false) { AJXP_Logger::logAction("Up from " . $_SERVER["HTTP_USER_AGENT"] . " - direct triger of next to remote"); $this->uploadActions("next_to_remote", array(), array()); } }
/** * Initialize and return the HttpClient * * @return HttpClient */ protected function createHttpClient() { require_once INSTALL_PATH . "/server/classes/class.HttpClient.php"; $httpClient = new HttpClient($this->host); $httpClient->cookie_host = $this->host; $httpClient->timeout = 50; AJXP_Logger::debug("Creating Http client", array()); //$httpClient->setDebug(true); if (!$this->use_auth) { return $httpClient; } $uri = ""; if ($this->auth_path != "") { $httpClient->setAuthorization($this->user, $this->password); $uri = $this->auth_path; } if (!isset($_SESSION["AJXP_REMOTE_SESSION"])) { if ($uri == "") { // Retrieve a seed! $httpClient->get($this->path . "?get_action=get_seed"); $seed = $httpClient->getContent(); $user = $this->user; $pass = $this->password; $pass = md5(md5($pass) . $seed); $uri = $this->path . "?get_action=login&userid=" . $user . "&password="******"&login_seed={$seed}"; } $httpClient->setHeadersOnly(true); $httpClient->get($uri); $httpClient->setHeadersOnly(false); $cookies = $httpClient->getCookies(); if (isset($cookies["AjaXplorer"])) { $_SESSION["AJXP_REMOTE_SESSION"] = $cookies["AjaXplorer"]; $remoteSessionId = $cookies["AjaXplorer"]; } } else { $remoteSessionId = $_SESSION["AJXP_REMOTE_SESSION"]; $httpClient->setCookies(array("AjaXplorer" => $remoteSessionId)); } AJXP_Logger::debug("Http Client created", array()); return $httpClient; }
/** * @return zipfile */ function makeZip($src, $dest, $basedir) { @set_time_limit(60); require_once SERVER_RESOURCES_FOLDER . "/pclzip.lib.php"; $filePaths = array(); $uniqid = uniqid(); $uniqfolder = '/tmp/ajaxplorer-zip-' . $uniqid; mkdir($uniqfolder); foreach ($src as $item) { $basedir = trim(dirname($item)); $basename = basename($item); $uniqpath = $uniqfolder . '/' . $basename; $this->full_copy($this->urlBase . $item, $uniqpath); $filePaths[] = array(PCLZIP_ATT_FILE_NAME => $uniqpath, PCLZIP_ATT_FILE_NEW_SHORT_NAME => $basename); } AJXP_Logger::debug("Pathes", $filePaths); AJXP_Logger::debug("Basedir", array($basedir)); $archive = new PclZip($dest); $vList = $archive->create($filePaths, PCLZIP_OPT_REMOVE_PATH, $uniqfolder, PCLZIP_OPT_NO_COMPRESSION); $this->recursiveRmdir($uniqfolder); if (!$vList) { throw new Exception("Zip creation error : ({$dest}) " . $archive->errorInfo(true)); } return $vList; }
protected function createFTPLink() { // If connexion exist and is still connected if (is_array($_SESSION["FTP_CONNEXIONS"]) && array_key_exists($this->repositoryId, $_SESSION["FTP_CONNEXIONS"]) && @ftp_systype($_SESSION["FTP_CONNEXIONS"][$this->repositoryId])) { AJXP_Logger::debug("Using stored FTP Session"); return $_SESSION["FTP_CONNEXIONS"][$this->repositoryId]; } AJXP_Logger::debug("Creating new FTP Session"); $link = FALSE; //Connects to the FTP. if ($this->secure) { $link = @ftp_ssl_connect($this->host, $this->port); } else { $link = @ftp_connect($this->host, $this->port); } if (!$link) { throw new AJXP_Exception("Cannot connect to FTP server!"); } //register_shutdown_function('ftp_close', $link); @ftp_set_option($link, FTP_TIMEOUT_SEC, 10); if (!@ftp_login($link, $this->user, $this->password)) { throw new AJXP_Exception("Cannot login to FTP server with user {$this->user}"); } if (!$this->ftpActive) { @ftp_pasv($link, true); global $_SESSION; $_SESSION["ftpPasv"] = "true"; } if (!is_array($_SESSION["FTP_CONNEXIONS"])) { $_SESSION["FTP_CONNEXIONS"] = array(); } $_SESSION["FTP_CONNEXIONS"][$this->repositoryId] = $link; return $link; }
/** * Initialize the stream from the given path. * * @param string $path * @return mixed Real path or -1 if currentListing contains the listing : original path converted to real path */ protected static function initPath($path, $streamType, $storeOpenContext = false, $skipZip = false) { $path = self::unPatchPathForBaseDir($path); $url = parse_url($path); $repoId = $url["host"]; if (isset($url["fragment"]) && strlen($url["fragment"]) > 0) { $url["path"] .= "#" . $url["fragment"]; } $repoObject = ConfService::getRepositoryById($repoId); if (!isset($repoObject)) { throw new Exception("Cannot find repository with id " . $repoId); } $split = UserSelection::detectZip($url["path"]); $insideZip = false; if ($split && $streamType == "file" && $split[1] != "/") { $insideZip = true; } if ($split && $streamType == "dir") { $insideZip = true; } if ($skipZip) { $insideZip = false; } //var_dump($path); //var_dump($skipZip); // Inside a zip : copy the file to a tmp file and return a reference to it if ($insideZip) { $zipPath = $split[0]; $localPath = $split[1]; require_once AJXP_BIN_FOLDER . "/pclzip.lib.php"; //print($streamType.$path); if ($streamType == "file") { if (self::$crtZip == null || !is_array(self::$currentListingKeys)) { $tmpDir = AJXP_Utils::getAjxpTmpDir() . DIRECTORY_SEPARATOR . md5(time() - rand()); mkdir($tmpDir); $tmpFileName = $tmpDir . DIRECTORY_SEPARATOR . basename($localPath); AJXP_Logger::debug("Tmp file {$tmpFileName}"); register_shutdown_function(array("fsAccessWrapper", "removeTmpFile"), $tmpDir, $tmpFileName); $crtZip = new PclZip(AJXP_Utils::securePath(realpath($repoObject->getOption("PATH")) . $zipPath)); $content = $crtZip->listContent(); foreach ($content as $item) { $fName = AJXP_Utils::securePath($item["stored_filename"]); if ($fName == $localPath || "/" . $fName == $localPath) { $localPath = $fName; break; } } $res = $crtZip->extract(PCLZIP_OPT_BY_NAME, $localPath, PCLZIP_OPT_PATH, $tmpDir, PCLZIP_OPT_REMOVE_ALL_PATH); AJXP_Logger::debug("Extracted " . $path . " to " . dirname($localPath)); if ($storeOpenContext) { self::$crtZip = $crtZip; } return $tmpFileName; } else { $key = basename($localPath); if (array_key_exists($key, self::$currentListing)) { self::$currentFileKey = $key; return -1; } else { throw new AJXP_Exception("Cannot find key"); } } } else { $crtZip = new PclZip(AJXP_Utils::securePath(realpath($repoObject->getOption("PATH")) . $zipPath)); $liste = $crtZip->listContent(); if ($storeOpenContext) { self::$crtZip = $crtZip; } $folders = array(); $files = array(); $builtFolders = array(); if ($localPath[strlen($localPath) - 1] != "/") { $localPath .= "/"; } foreach ($liste as $item) { $stored = $item["stored_filename"]; if ($stored[0] != "/") { $stored = "/" . $stored; } $pathPos = strpos($stored, $localPath); if ($pathPos !== false) { $afterPath = substr($stored, $pathPos + strlen($localPath)); if ($afterPath != "" && substr_count($afterPath, "/") < 2) { $statValue = array(); if (substr_count($afterPath, "/") == 0) { $statValue[2] = $statValue["mode"] = $item["folder"] ? "00040000" : "0100000"; $statValue[7] = $statValue["size"] = $item["size"]; $statValue[8] = $statValue["atime"] = $item["mtime"]; $statValue[9] = $statValue["mtime"] = $item["mtime"]; $statValue[10] = $statValue["ctime"] = $item["mtime"]; if (strpos($afterPath, "/") == strlen($afterPath) - 1) { $afterPath = substr($afterPath, 0, strlen($afterPath) - 1); } //$statValue["filename"] = $zipPath.$localPath.$afterPath; if ($item["folder"]) { $folders[$afterPath] = $statValue; } else { $files[$afterPath] = $statValue; } } else { $arr = explode("/", $afterPath); $afterPath = array_shift($arr); if (isset($folders[$afterPath]) || isset($builtFolders[$afterPath])) { continue; } $statValue[2] = $statValue["mode"] = "00040000"; $statValue[7] = $statValue["size"] = 0; $statValue[8] = $statValue["atime"] = $item["mtime"]; $statValue[9] = $statValue["mtime"] = $item["mtime"]; $statValue[10] = $statValue["ctime"] = $item["mtime"]; $builtFolders[$afterPath] = $statValue; } } } } self::$currentListing = array_merge($folders, $builtFolders, $files); self::$currentListingKeys = array_keys(self::$currentListing); self::$currentListingIndex = 0; return -1; } } else { return realpath($repoObject->getOption("PATH")) . $url["path"]; } }
function debug($msg, $object = false) { if ($this->debug) { $st = '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> ' . $msg; if ($object) { ob_start(); print_r($object); $content = htmlentities(ob_get_contents()); ob_end_clean(); $st .= '<pre>' . $content . '</pre>'; } $st .= '</div>'; AJXP_Logger::debug($msg . ($object !== false ? " - " . print_r($object, true) : "")); } }
// For example, for basic_http auth. AuthService::preLogUser(isset($httpVars["remote_session"]) ? $httpVars["remote_session"] : ""); $loggedUser = AuthService::getLoggedUser(); if ($loggedUser == null) { $requireAuth = true; } } if ($loggedUser != null) { $res = ConfService::switchUserToActiveRepository($loggedUser, isset($httpVars["tmp_repository_id"]) ? $httpVars["tmp_repository_id"] : "-1"); if (!$res) { AuthService::disconnect(); $requireAuth = true; } } } else { AJXP_Logger::debug(ConfService::getCurrentRepositoryId()); } //Set language $loggedUser = AuthService::getLoggedUser(); if ($loggedUser != null && $loggedUser->getPref("lang") != "") { ConfService::setLanguage($loggedUser->getPref("lang")); } else { if (isset($_COOKIE["AJXP_lang"])) { ConfService::setLanguage($_COOKIE["AJXP_lang"]); } } //------------------------------------------------------------ // SPECIAL HANDLING FOR FANCY UPLOADER RIGHTS FOR THIS ACTION //------------------------------------------------------------ if (AuthService::usersEnabled()) { $loggedUser = AuthService::getLoggedUser();
/** * @param String $type * @param String $element * @throws Exception * @return bool */ public function deleteShare($type, $element) { $mess = ConfService::getMessages(); AJXP_Logger::debug(__CLASS__, __FILE__, "Deleting shared element " . $type . "-" . $element); if ($type == "repository") { if (strpos($element, "repo-") === 0) { $element = str_replace("repo-", "", $element); } $repo = ConfService::getRepositoryById($element); if ($repo == null) { // Maybe a share has $share = $this->loadShare($element); if (is_array($share) && isset($share["REPOSITORY"])) { $repo = ConfService::getRepositoryById($share["REPOSITORY"]); } if ($repo == null) { throw new Exception("Cannot find associated share"); } $element = $share["REPOSITORY"]; } $this->testUserCanEditShare($repo->getOwner()); $res = ConfService::deleteRepository($element); if ($res == -1) { throw new Exception($mess[427]); } if ($this->sqlSupported) { if (isset($share)) { $this->confStorage->simpleStoreClear("share", $element); } else { $shares = self::findSharesForRepo($element); if (count($shares)) { $keys = array_keys($shares); $this->confStorage->simpleStoreClear("share", $keys[0]); } } } } else { if ($type == "minisite") { $minisiteData = $this->loadShare($element); $repoId = $minisiteData["REPOSITORY"]; $repo = ConfService::getRepositoryById($repoId); if ($repo == null) { return false; } $this->testUserCanEditShare($repo->getOwner()); $res = ConfService::deleteRepository($repoId); if ($res == -1) { throw new Exception($mess[427]); } // Silently delete corresponding role if it exists AuthService::deleteRole("AJXP_SHARED-" . $repoId); // If guest user created, remove it now. if (isset($minisiteData["PRELOG_USER"]) && AuthService::userExists($minisiteData["PRELOG_USER"])) { AuthService::deleteUser($minisiteData["PRELOG_USER"]); } // If guest user created, remove it now. if (isset($minisiteData["PRESET_LOGIN"]) && AuthService::userExists($minisiteData["PRESET_LOGIN"])) { AuthService::deleteUser($minisiteData["PRESET_LOGIN"]); } if (isset($minisiteData["PUBLICLET_PATH"]) && is_file($minisiteData["PUBLICLET_PATH"])) { unlink($minisiteData["PUBLICLET_PATH"]); } else { if ($this->sqlSupported) { $this->confStorage->simpleStoreClear("share", $element); } } } else { if ($type == "user") { $this->testUserCanEditShare($element); AuthService::deleteUser($element); } else { if ($type == "file") { $publicletData = $this->loadShare($element); if (isset($publicletData["OWNER_ID"]) && $this->testUserCanEditShare($publicletData["OWNER_ID"])) { PublicletCounter::delete($element); if (isset($publicletData["PUBLICLET_PATH"]) && is_file($publicletData["PUBLICLET_PATH"])) { unlink($publicletData["PUBLICLET_PATH"]); } else { if ($this->sqlSupported) { $this->confStorage->simpleStoreClear("share", $element); } } } else { throw new Exception($mess["share_center.160"]); } } } } } }
public function postProcess($action, $httpVars, $postProcessData) { if (self::$skipDecoding) { } if (!isset($httpVars["partitionRealName"])) { return; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(false)) { return false; } $plugin = AJXP_PluginsService::findPlugin("access", $repository->getAccessType()); $streamData = $plugin->detectStreamWrapper(true); $destStreamURL = $streamData["protocol"] . "://" . $repository->getId() . $httpVars["dir"] . "/"; $count = intval($httpVars["partitionCount"]); $index = intval($httpVars["partitionIndex"]); $fileId = $httpVars["fileId"]; $clientId = $httpVars["clientId"]; AJXP_Logger::debug("Should now rebuild file!", $httpVars); $newDest = fopen($destStreamURL . $httpVars["partitionRealName"], "w"); for ($i = 0; $i < $count; $i++) { $part = fopen($destStreamURL . "{$clientId}.{$fileId}.{$i}", "r"); while (!feof($part)) { fwrite($newDest, fread($part, 4096)); } fclose($part); unlink($destStreamURL . "{$clientId}.{$fileId}.{$i}"); } fclose($newDest); }
/** * Loader used by the generic loader. * @param string $hash */ public static function loadShareByHash($hash) { AJXP_Logger::debug(__CLASS__, __FUNCTION__, "Do something"); AJXP_PluginsService::getInstance()->initActivePlugins(); if (isset($_GET["lang"])) { ConfService::setLanguage($_GET["lang"]); } $shareCenter = self::getShareCenter(); $data = $shareCenter->getShareStore()->loadShare($hash); $mess = ConfService::getMessages(); if ($shareCenter->getShareStore()->isShareExpired($hash, $data)) { AuthService::disconnect(); self::loadMinisite($data, $hash, $mess["share_center.165"]); return; } if (!empty($data) && is_array($data)) { if (isset($data["SECURITY_MODIFIED"]) && $data["SECURITY_MODIFIED"] === true) { header("HTTP/1.0 401 Not allowed, script was modified"); exit; } if ($data["SHARE_TYPE"] == "minisite") { self::loadMinisite($data, $hash); } else { self::loadPubliclet($data); } } else { $setUrl = ConfService::getCoreConf("SERVER_URL"); $data = array(); if (!empty($setUrl)) { $data["AJXP_APPLICATION_BASE"] = $setUrl; } self::loadMinisite($data, $hash, $mess["share_center.166"]); } }
/** * @param AJXP_Node $oldNode * @param AJXP_Node $newNode * @param bool $copy */ public function updateNodesIndex($oldNode = null, $newNode = null, $copy = false) { if (!dibi::isConnected()) { dibi::connect($this->sqlDriver); } //$this->logInfo("Syncable index", array($oldNode == null?'null':$oldNode->getUrl(), $newNode == null?'null':$newNode->getUrl())); try { if ($newNode != null && $this->excludeNode($newNode)) { // CREATE if ($oldNode == null) { AJXP_Logger::debug("Ignoring " . $newNode->getUrl() . " for indexation"); return; } else { AJXP_Logger::debug("Target node is excluded, see it as a deletion: " . $newNode->getUrl()); $newNode = null; } } if ($newNode == null) { $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser()); // DELETE $this->logDebug('DELETE', $oldNode->getUrl()); dibi::query("DELETE FROM [ajxp_index] WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); } else { if ($oldNode == null || $copy) { // CREATE $stat = stat($newNode->getUrl()); $newNode->setLeaf(!($stat['mode'] & 040000)); $this->logDebug('INSERT', $newNode->getUrl()); dibi::query("INSERT INTO [ajxp_index]", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath()), "bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => $newNode->isLeaf() ? md5_file($newNode->getUrl()) : "directory", "repository_identifier" => $repoId = $this->computeIdentifier($newNode->getRepository(), $newNode->getUser()))); } else { $repoId = $this->computeIdentifier($oldNode->getRepository(), $oldNode->getUser()); if ($oldNode->getPath() == $newNode->getPath()) { // CONTENT CHANGE clearstatcache(); $stat = stat($newNode->getUrl()); $this->logDebug("Content changed", "current stat size is : " . $stat["size"]); $this->logDebug('UPDATE CONTENT', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET ", array("bytesize" => $stat["size"], "mtime" => $stat["mtime"], "md5" => md5_file($newNode->getUrl())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!"); $this->updateNodesIndex(null, $newNode, false); } } catch (Exception $e) { } } else { // PATH CHANGE ONLY $newNode->loadNodeInfo(); if ($newNode->isLeaf()) { $this->logDebug('UPDATE LEAF PATH', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET ", array("node_path" => SystemTextEncoding::toUTF8($newNode->getPath())), "WHERE [node_path] = %s AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed node (" . $newNode->getPath() . "), creating index entry!"); $this->updateNodesIndex(null, $newNode, false); } } catch (Exception $e) { } } else { $this->logDebug('UPDATE FOLDER PATH', $newNode->getUrl()); dibi::query("UPDATE [ajxp_index] SET [node_path]=REPLACE( REPLACE(CONCAT('\$\$\$',[node_path]), CONCAT('\$\$\$', %s), CONCAT('\$\$\$', %s)) , '\$\$\$', '') ", $oldNode->getPath(), $newNode->getPath(), "WHERE [node_path] LIKE %like~ AND [repository_identifier] = %s", SystemTextEncoding::toUTF8($oldNode->getPath()), $repoId); try { $rowCount = dibi::getAffectedRows(); if ($rowCount === 0) { $this->logError(__FUNCTION__, "There was an update event on a non-indexed folder (" . $newNode->getPath() . "), relaunching a recursive indexation!"); AJXP_Controller::findActionAndApply("index", array("file" => $newNode->getPath()), array()); } } catch (Exception $e) { } } } } } } catch (Exception $e) { AJXP_Logger::error("[meta.syncable]", "Exception", $e->getTraceAsString()); AJXP_Logger::error("[meta.syncable]", "Indexation", $e->getMessage()); } }
function drupal_remote_auth($host, $uri, $login, $pass, $formId = "") { $client = new HttpClient($host); $client->setHandleRedirects(false); $res = $client->get($uri); $content = $client->getContent(); $xmlDoc = DOMDocument::loadHTML($content); $xPath = new DOMXPath($xmlDoc); if ($formId == "") { $formId = "user-login-form"; } $nodes = $xPath->query('//form[@id="' . $formId . '"]'); if (!$nodes->length) { return ""; } $form = $nodes->item(0); $postUri = $form->getAttribute("action"); $hiddens = $xPath->query('//input[@type="hidden"]', $form); AJXP_Logger::debug("Carry on Drupal hiddens " . $hiddens->length); $postData = array("name" => $login, "pass" => $pass, "Submit" => "Log in"); foreach ($hiddens as $hiddenNode) { $postData[$hiddenNode->getAttribute("name")] = $hiddenNode->getAttribute("value"); } $client->setHandleRedirects(false); $client->setHeadersOnly(true); $client->setCookies(extractResponseCookies($client)); $res2 = $client->post($postUri, $postData); $newCookies = extractResponseCookies($client); if (isset($newCookies["AjaXplorer"])) { return $newCookies["AjaXplorer"]; } return ""; }