public function authenticate(Sabre\DAV\Server $server, $realm) { //AJXP_Logger::debug("Try authentication on $realm", $server); try { $success = parent::authenticate($server, $realm); } catch (Exception $e) { $success = 0; $errmsg = $e->getMessage(); if ($errmsg != "No digest authentication headers were found") { $success = false; } } if ($success) { $res = AuthService::logUser($this->currentUser, null, true); if ($res < 1) { throw new Sabre\DAV\Exception\NotAuthenticated(); } $this->updateCurrentUserRights(AuthService::getLoggedUser()); if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { $webdavData = AuthService::getLoggedUser()->getPref("AJXP_WEBDAV_DATA"); AJXP_Safe::storeCredentials($this->currentUser, $this->_decodePassword($webdavData["PASS"], $this->currentUser)); } } else { if ($success === false) { AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => $this->currentUser, "error" => "Invalid WebDAV user or password")); } throw new Sabre\DAV\Exception\NotAuthenticated($errmsg); } ConfService::switchRootDir($this->repositoryId); return true; }
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); } } }
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"); } } }
/** * 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 authenticate(Sabre\DAV\Server $server, $realm) { $auth = new Sabre\HTTP\BasicAuth(); $auth->setHTTPRequest($server->httpRequest); $auth->setHTTPResponse($server->httpResponse); $auth->setRealm($realm); $userpass = $auth->getUserPass(); if (!$userpass) { $auth->requireLogin(); throw new Sabre\DAV\Exception\NotAuthenticated('No basic authentication headers were found'); } // Authenticates the user //AJXP_Logger::info(__CLASS__,"authenticate",$userpass[0]); $confDriver = ConfService::getConfStorageImpl(); $userObject = $confDriver->createUserObject($userpass[0]); $webdavData = $userObject->getPref("AJXP_WEBDAV_DATA"); if (empty($webdavData) || !isset($webdavData["ACTIVE"]) || $webdavData["ACTIVE"] !== true) { AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => $userpass[0], "error" => "WebDAV user not found or disabled")); throw new Sabre\DAV\Exception\NotAuthenticated(); } // check if there are cached credentials. prevents excessive authentication calls to external // auth mechanism. $cachedPasswordValid = 0; $secret = defined("AJXP_SECRET_KEY") ? AJXP_SECRET_KEY : "CDAFx¨op#"; $encryptedPass = md5($userpass[1] . $secret . date('YmdHi')); if (isset($webdavData["TMP_PASS"]) && $encryptedPass == $webdavData["TMP_PASS"]) { $cachedPasswordValid = true; //AJXP_Logger::debug("Using Cached Password"); } if (!$cachedPasswordValid && !$this->validateUserPass($userpass[0], $userpass[1])) { AJXP_Logger::warning(__CLASS__, "Login failed", array("user" => $userpass[0], "error" => "Invalid WebDAV user or password")); $auth->requireLogin(); throw new Sabre\DAV\Exception\NotAuthenticated('Username or password does not match'); } $this->currentUser = $userpass[0]; $res = AuthService::logUser($this->currentUser, $userpass[1], true); if ($res < 1) { throw new Sabre\DAV\Exception\NotAuthenticated(); } $this->updateCurrentUserRights(AuthService::getLoggedUser()); if (ConfService::getCoreConf("SESSION_SET_CREDENTIALS", "auth")) { AJXP_Safe::storeCredentials($this->currentUser, $userpass[1]); } if (isset($this->repositoryId) && ConfService::getRepositoryById($this->repositoryId)->getOption("AJXP_WEBDAV_DISABLED") === true) { throw new Sabre\DAV\Exception\NotAuthenticated('You are not allowed to access this workspace'); } ConfService::switchRootDir($this->repositoryId); // the method used here will invalidate the cached password every minute on the minute if (!$cachedPasswordValid) { $webdavData["TMP_PASS"] = $encryptedPass; $userObject->setPref("AJXP_WEBDAV_DATA", $webdavData); $userObject->save("user"); AuthService::updateUser($userObject); } return true; }
public function init($options) { parent::init($options); self::$globalOptions = $this->pluginConf; $this->pluginInstance = ConfService::instanciatePluginFromGlobalParams($this->pluginConf["UNIQUE_PLUGIN_INSTANCE"], "AbstractLogDriver"); if ($this->pluginInstance != false) { AJXP_PluginsService::getInstance()->setPluginUniqueActiveForType("log", $this->pluginInstance->getName(), $this->pluginInstance); } self::$loggerInstance = $this->pluginInstance; }
function catchError($code, $message, $fichier, $ligne, $context) { if (error_reporting() == 0) { return; } $message = "{$code} : {$message} in {$fichier} (l.{$ligne})"; AJXP_Logger::logAction("error", array("message" => $message)); AJXP_XMLWriter::header(); AJXP_XMLWriter::sendMessage(null, $message, true); AJXP_XMLWriter::close(); exit(1); }
/** 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"); }
public function switchAction($action, $httpVars, $filesVars) { if (!isset($this->actions[$action])) { return false; } $repository = ConfService::getRepository(); if (!$repository->detectStreamWrapper(true)) { return false; } if (!isset($this->pluginConf)) { $this->pluginConf = array("GENERATE_THUMBNAIL" => false); } $streamData = $repository->streamData; $destStreamURL = $streamData["protocol"] . "://" . $repository->getId(); if ($action == "preview_data_proxy") { $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]); if (isset($httpVars["get_thumb"]) && $this->pluginConf["GENERATE_THUMBNAIL"]) { require_once INSTALL_PATH . "/plugins/editor.diaporama/PThumb.lib.php"; $pThumb = new PThumb($this->pluginConf["THUMBNAIL_QUALITY"]); if (!$pThumb->isError()) { $pThumb->remote_wrapper = $streamData["classname"]; $pThumb->use_cache = $this->pluginConf["USE_THUMBNAIL_CACHE"]; $pThumb->cache_dir = $this->pluginConf["THUMBNAIL_CACHE_DIR"]; $pThumb->fit_thumbnail($destStreamURL . $file, 200); if ($pThumb->isError()) { print_r($pThumb->error_array); AJXP_Logger::logAction("error", $pThumb->error_array); } //exit(0); } else { print_r($pThumb->error_array); AJXP_Logger::logAction("error", $pThumb->error_array); } } else { $filesize = filesize($destStreamURL . $file); $fp = fopen($destStreamURL . $file, "r"); header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\""); header("Content-Length: " . $filesize); header('Cache-Control: public'); $class = $streamData["classname"]; $stream = fopen("php://output", "a"); call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream); fflush($stream); fclose($stream); //exit(1); } } }
/** * Opens the stream * Diff with parent class : do not "securePath", as it removes double slash * * @param String $path Maybe in the form "ajxp.fs://repositoryId/pathToFile" * @param String $mode * @param unknown_type $options * @param unknown_type $opened_path * @return unknown */ public function stream_open($path, $mode, $options, &$context) { try { $this->realPath = $this->initPath($path, "file"); } catch (Exception $e) { AJXP_Logger::error(__CLASS__, "stream_open", "Error while opening stream {$path}"); return false; } if ($this->realPath == -1) { $this->fp = -1; return true; } else { $this->fp = fopen($this->realPath, $mode, $options, self::$cloudContext); return $this->fp !== false; } }
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 postProcess($action, $httpVars, $params) { $url = $params["ob_output"]; if (!isset($this->pluginConf["BITLY_USER"]) || !isset($this->pluginConf["BITLY_APIKEY"])) { print $url; AJXP_Logger::logAction("error", "Bitly Shortener : you must drop the conf.shorten.bitly.inc file inside conf.php and set the login/api key!"); return; } $bitly_login = $this->pluginConf["BITLY_USER"]; $bitly_api = $this->pluginConf["BITLY_APIKEY"]; $format = 'json'; $version = '2.0.1'; $bitly = 'http://api.bit.ly/shorten?version=' . $version . '&longUrl=' . urlencode($url) . '&login='******'&apiKey=' . $bitly_api . '&format=' . $format; $response = AJXP_Utils::getRemoteContent($bitly); $json = json_decode($response, true); if (isset($json['results'][$url]['shortUrl'])) { print $json['results'][$url]['shortUrl']; $this->updateMetaShort($httpVars["file"], $json['results'][$url]['shortUrl']); } else { print $url; } }
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(); }
function listLogFiles($dir) { $logger = AJXP_Logger::getInstance(); $parts = explode("/", $dir); if (count($parts) > 4) { print '<columns switchDisplayMode="list" switchGridMode="grid"> <column messageString="Date" attributeName="date" sortType="Date" width="10%"/> <column messageString="I.P." attributeName="ip" sortType="String"/> <column messageString="Level" attributeName="level" sortType="String"/> <column messageString="User" attributeName="user" sortType="String"/> <column messageString="Action" attributeName="action" sortType="String"/> <column messageString="Params" attributeName="params" sortType="String"/> </columns>'; $date = $parts[count($parts) - 1]; $logger->xmlLogs($date, "tree"); } else { print '<columns switchGridMode="filelist"><column messageString="File Date" attributeName="ajxp_label" sortType="String"/></columns>'; $logger->xmlListLogFiles("tree", count($parts) > 2 ? $parts[2] : null, count($parts) > 3 ? $parts[3] : null); } }
/** * @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()); } }
/** * Save Temporary Data. * Implementation uses serialised files because of the overhead incurred with a full db implementation. * * @param $key String key of data to save. * @param $value Value to save */ public function saveTemporaryData($key, $value) { $dirPath = $this->storage->getOption("USERS_DIRPATH"); if ($dirPath == "") { $dirPath = AJXP_INSTALL_PATH . "/data/users"; AJXP_Logger::info(__CLASS__, "setTemporaryData", array("Warning" => "The conf.sql driver is missing a mandatory option USERS_DIRPATH!")); } $id = AuthService::ignoreUserCase() ? strtolower($this->getId()) : $this->getId(); AJXP_Utils::saveSerialFile($dirPath . "/" . $id . "/temp-" . $key . ".ser", $value); }
public function upgradeDB() { $confDriver = ConfService::getConfStorageImpl(); $authDriver = ConfService::getAuthDriverImpl(); $logger = AJXP_Logger::getInstance(); if (is_a($confDriver, "sqlConfDriver")) { $conf = AJXP_Utils::cleanDibiDriverParameters($confDriver->getOption("SQL_DRIVER")); if (!is_array($conf) || !isset($conf["driver"])) { return "Nothing to do"; } switch ($conf["driver"]) { case "sqlite": case "sqlite3": $ext = ".sqlite"; break; case "postgre": $ext = ".pgsql"; break; case "mysql": $ext = is_file($this->workingFolder . "/" . $this->dbUpgrade . ".mysql") ? ".mysql" : ".sql"; break; default: return "ERROR!, DB driver " . $conf["driver"] . " not supported yet in __FUNCTION__"; } $file = $this->dbUpgrade . $ext; if (!is_file($this->workingFolder . "/" . $file)) { return "Nothing to do."; } $sqlInstructions = file_get_contents($this->workingFolder . "/" . $file); $parts = array_map("trim", explode("/* SEPARATOR */", $sqlInstructions)); $results = array(); $errors = array(); dibi::connect($conf); dibi::begin(); foreach ($parts as $sqlPart) { if (empty($sqlPart)) { continue; } try { dibi::nativeQuery($sqlPart); $results[] = $sqlPart; } catch (DibiException $e) { $errors[] = $sqlPart . " (" . $e->getMessage() . ")"; } } dibi::commit(); dibi::disconnect(); if (!count($errors)) { return "Database successfully upgraded"; } else { return "Database upgrade failed. <br>The following statements were executed : <br>" . implode("<br>", $results) . ",<br><br> The following statements failed : <br>" . implode("<br>", $errors) . "<br><br> You should manually upgrade your DB."; } } }
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; }
/** * Error Catcher for PHP errors. Depending on the SERVER_DEBUG config * shows the file/line info or not. * @static * @param $code * @param $message * @param $fichier * @param $ligne * @param $context */ public static function catchError($code, $message, $fichier, $ligne, $context) { if (error_reporting() == 0) { return; } AJXP_Logger::error(basename($fichier), "error l.{$ligne}", array("message" => $message)); if (ConfService::getConf("SERVER_DEBUG")) { $stack = debug_backtrace(); $stackLen = count($stack); for ($i = 1; $i < $stackLen; $i++) { $entry = $stack[$i]; $func = $entry['function'] . '('; $argsLen = count($entry['args']); for ($j = 0; $j < $argsLen; $j++) { $s = $entry['args'][$j]; if (is_string($s)) { $func .= $s; } else { if (is_object($s)) { $func .= get_class($s); } } if ($j < $argsLen - 1) { $func .= ', '; } } $func .= ')'; $message .= "\n" . str_replace(dirname(__FILE__), '', $entry['file']) . ':' . $entry['line'] . ' - ' . $func . PHP_EOL; } } if (!headers_sent()) { AJXP_XMLWriter::header(); } if (!empty($context) && is_object($context) && is_a($context, "AJXP_PromptException")) { AJXP_XMLWriter::write("<prompt type=\"" . $context->getPromptType() . "\"><message>" . $message . "</message><data><![CDATA[" . json_encode($context->getPromptData()) . "]]></data></prompt>", true); } else { AJXP_XMLWriter::sendMessage(null, SystemTextEncoding::toUTF8($message), true); } AJXP_XMLWriter::close(); exit(1); }
/** * Opens the stream * Diff with parent class : do not "securePath", as it removes double slash * * @param String $path Maybe in the form "ajxp.fs://repositoryId/pathToFile" * @param String $mode * @param unknown_type $options * @param unknown_type $opened_path * @return unknown */ public function stream_open($path, $mode, $options, &$context) { try { $this->realPath = $this->initPath($path, "file"); } catch (Exception $e) { AJXP_Logger::error(__CLASS__, "stream_open", "Error while opening stream {$path}"); return false; } if ($this->realPath == -1) { $this->fp = -1; return true; } else { $this->fp = fopen($this->realPath, $mode, $options); //AJXP_Logger::debug(__CLASS__,__FUNCTION__,"I opened an smb stream."); return $this->fp !== false; } }
function switchAction($action, $httpVars, $fileVars) { if (!isset($this->actions[$action])) { return; } $xmlBuffer = ""; foreach ($httpVars as $getName => $getValue) { ${$getName} = Utils::securePath(SystemTextEncoding::magicDequote($getValue)); } $selection = new UserSelection(); $selection->initFromHttpVars($httpVars); if (isset($dir) && $action != "upload") { $safeDir = $dir; $dir = SystemTextEncoding::fromUTF8($dir); } if (isset($dest)) { $dest = SystemTextEncoding::fromUTF8($dest); } $mess = ConfService::getMessages(); $newArgs = RecycleBinManager::filterActions($action, $selection, $dir); foreach ($newArgs as $argName => $argValue) { ${$argName} = $argValue; } // FILTER DIR PAGINATION ANCHOR if (isset($dir) && strstr($dir, "#") !== false) { $parts = explode("#", $dir); $dir = $parts[0]; $page = $parts[1]; } switch ($action) { //------------------------------------ // DOWNLOAD, IMAGE & MP3 PROXYS //------------------------------------ case "download": AJXP_Logger::logAction("Download", array("files" => $selection)); set_error_handler(array("HTMLWriter", "javascriptErrorHandler"), E_ALL & ~E_NOTICE); register_shutdown_function("restore_error_handler"); if ($selection->inZip) { $tmpDir = dirname($selection->getZipPath()) . "/.tmpExtractDownload"; $delDir = $this->getPath() . "/" . $tmpDir; @mkdir($delDir); register_shutdown_function(array($this, "deldir"), $delDir); $this->convertSelectionToTmpFiles($tmpDir, $selection); } $zip = false; if ($selection->isUnique()) { if (is_dir($this->getPath() . "/" . $selection->getUniqueFile())) { $zip = true; $dir .= "/" . basename($selection->getUniqueFile()); } } else { $zip = true; } if ($zip) { // Make a temp zip and send it as download $loggedUser = AuthService::getLoggedUser(); $file = USERS_DIR . "/" . ($loggedUser ? $loggedUser->getId() : "shared") . "/" . time() . "tmpDownload.zip"; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { AJXP_Exception::errorToXml("Error while compressing"); } register_shutdown_function("unlink", $file); $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip"; $this->readFile($file, "force-download", $localName, false, false); } else { $this->readFile($this->getPath() . "/" . $selection->getUniqueFile(), "force-download"); } exit(0); break; case "compress": // Make a temp zip and send it as download if (isset($archive_name)) { $localName = SystemTextEncoding::fromUTF8($archive_name); } else { $localName = (basename($dir) == "" ? "Files" : basename($dir)) . ".zip"; } $file = $this->getPath() . "/" . $dir . "/" . $localName; $zipFile = $this->makeZip($selection->getFiles(), $file, $dir); if (!$zipFile) { AJXP_Exception::errorToXml("Error while compressing file {$localName}"); } $reload_current_node = true; $reload_file_list = $localName; break; case "image_proxy": if ($split = UserSelection::detectZip(SystemTextEncoding::fromUTF8($file))) { require_once "server/classes/pclzip.lib.php"; $zip = new PclZip($this->getPath() . $split[0]); $data = $zip->extract(PCLZIP_OPT_BY_NAME, substr($split[1], 1), PCLZIP_OPT_EXTRACT_AS_STRING); header("Content-Type: " . Utils::getImageMimeType(basename($split[1])) . "; name=\"" . basename($split[1]) . "\""); header("Content-Length: " . strlen($data[0]["content"])); header('Cache-Control: public'); print $data[0]["content"]; } else { if (isset($get_thumb) && $get_thumb == "true" && $this->driverConf["GENERATE_THUMBNAIL"]) { require_once "server/classes/PThumb.lib.php"; $pThumb = new PThumb($this->driverConf["THUMBNAIL_QUALITY"]); if (!$pThumb->isError()) { $pThumb->use_cache = $this->driverConf["USE_THUMBNAIL_CACHE"]; $pThumb->cache_dir = $this->driverConf["THUMBNAIL_CACHE_DIR"]; $pThumb->fit_thumbnail($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), 200); if ($pThumb->isError()) { print_r($pThumb->error_array); } exit(0); } } $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "image"); } exit(0); break; case "mp3_proxy": if ($split = UserSelection::detectZip(SystemTextEncoding::fromUTF8($file))) { require_once "server/classes/pclzip.lib.php"; $zip = new PclZip($this->getPath() . $split[0]); $data = $zip->extract(PCLZIP_OPT_BY_NAME, substr($split[1], 1), PCLZIP_OPT_EXTRACT_AS_STRING); header("Content-Type: audio/mp3; name=\"" . basename($split[1]) . "\""); header("Content-Length: " . strlen($data[0]["content"])); print $data[0]["content"]; } else { $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "mp3"); } exit(0); break; //------------------------------------ // ONLINE EDIT //------------------------------------ //------------------------------------ // ONLINE EDIT //------------------------------------ case "edit": if (isset($save) && $save == 1 && isset($code)) { // Reload "code" variable directly from POST array, do not "securePath"... $code = $_POST["code"]; AJXP_Logger::logAction("Online Edition", array("file" => SystemTextEncoding::fromUTF8($file))); $code = stripslashes($code); $code = str_replace("<", "<", $code); $fileName = $this->getPath() . SystemTextEncoding::fromUTF8("/{$file}"); if (!is_file($fileName) || !is_writable($fileName)) { header("Content-Type:text/plain"); print !is_writable($fileName) ? "1001" : "1002"; exit(1); } $fp = fopen($fileName, "w"); fputs($fp, $code); fclose($fp); header("Content-Type:text/plain"); print $mess[115]; } else { $this->readFile($this->getPath() . "/" . SystemTextEncoding::fromUTF8($file), "plain"); } exit(0); break; //------------------------------------ // COPY / MOVE //------------------------------------ //------------------------------------ // COPY / MOVE //------------------------------------ case "copy": case "move": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } if ($selection->inZip()) { $tmpDir = dirname($selection->getZipPath()) . "/.tmpExtractDownload"; @mkdir($this->getPath() . "/" . $tmpDir); $this->convertSelectionToTmpFiles($tmpDir, $selection); if (is_dir($tmpDir)) { $this->deldir($this->getPath() . "/" . $tmpDir); } } $success = $error = array(); $this->copyOrMove($dest, $selection->getFiles(), $error, $success, $action == "move" ? true : false); if (count($error)) { $errorMessage = join("\n", $error); } else { $logMessage = join("\n", $success); AJXP_Logger::logAction($action == "move" ? "Move" : "Copy", array("files" => $selection, "destination" => $dest)); } $reload_current_node = true; if (isset($dest_node)) { $reload_dest_node = $dest_node; } $reload_file_list = true; break; //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ //------------------------------------ // SUPPRIMER / DELETE //------------------------------------ case "delete": if ($selection->isEmpty()) { $errorMessage = $mess[113]; break; } $logMessages = array(); $errorMessage = $this->delete($selection->getFiles(), $logMessages); if (count($logMessages)) { $logMessage = join("\n", $logMessages); } AJXP_Logger::logAction("Delete", array("files" => $selection)); $reload_current_node = true; $reload_file_list = true; break; //------------------------------------ // RENOMMER / RENAME //------------------------------------ //------------------------------------ // RENOMMER / RENAME //------------------------------------ case "rename": $file = SystemTextEncoding::fromUTF8($file); $filename_new = SystemTextEncoding::fromUTF8($filename_new); $error = $this->rename($file, $filename_new); if ($error != null) { $errorMessage = $error; break; } $logMessage = SystemTextEncoding::toUTF8($file) . " {$mess['41']} " . SystemTextEncoding::toUTF8($filename_new); $reload_current_node = true; $reload_file_list = basename($filename_new); AJXP_Logger::logAction("Rename", array("original" => $file, "new" => $filename_new)); break; //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ //------------------------------------ // CREER UN REPERTOIRE / CREATE DIR //------------------------------------ case "mkdir": $messtmp = ""; $dirname = Utils::processFileName(SystemTextEncoding::fromUTF8($dirname)); $error = $this->mkDir($dir, $dirname); if (isset($error)) { $errorMessage = $error; break; } $reload_file_list = $dirname; $messtmp .= "{$mess['38']} " . SystemTextEncoding::toUTF8($dirname) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reload_current_node = true; AJXP_Logger::logAction("Create Dir", array("dir" => $dir . "/" . $dirname)); break; //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ //------------------------------------ // CREER UN FICHIER / CREATE FILE //------------------------------------ case "mkfile": $messtmp = ""; $filename = Utils::processFileName(SystemTextEncoding::fromUTF8($filename)); $error = $this->createEmptyFile($dir, $filename); if (isset($error)) { $errorMessage = $error; break; } $messtmp .= "{$mess['34']} " . SystemTextEncoding::toUTF8($filename) . " {$mess['39']} "; if ($dir == "") { $messtmp .= "/"; } else { $messtmp .= SystemTextEncoding::toUTF8($dir); } $logMessage = $messtmp; $reload_file_list = $filename; AJXP_Logger::logAction("Create File", array("file" => $dir . "/" . $filename)); break; //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ //------------------------------------ // CHANGE FILE PERMISSION //------------------------------------ case "chmod": $messtmp = ""; $files = $selection->getFiles(); $changedFiles = array(); foreach ($files as $fileName) { $error = $this->chmod($this->getPath() . $fileName, $chmod_value, $recursive == "on", $recursive == "on" ? $recur_apply_to : "both", $changedFiles); } if (isset($error)) { $errorMessage = $error; break; } //$messtmp.="$mess[34] ".SystemTextEncoding::toUTF8($filename)." $mess[39] "; $logMessage = "Successfully changed permission to " . $chmod_value . " for " . count($changedFiles) . " files or folders"; $reload_file_list = $dir; AJXP_Logger::logAction("Chmod", array("dir" => $dir, "filesCount" => count($changedFiles))); break; //------------------------------------ // UPLOAD //------------------------------------ //------------------------------------ // UPLOAD //------------------------------------ case "upload": $fancyLoader = false; if (isset($fileVars["Filedata"])) { $fancyLoader = true; if ($dir != "") { $dir = "/" . base64_decode($dir); } } if ($dir != "") { $rep_source = "/{$dir}"; } else { $rep_source = ""; } $destination = SystemTextEncoding::fromUTF8($this->getPath() . $rep_source); if (!$this->isWriteable($destination)) { global $_GET; $errorMessage = "{$mess['38']} " . SystemTextEncoding::toUTF8($dir) . " {$mess['99']}."; if ($fancyLoader || isset($_GET["ajxp_sessid"])) { header('HTTP/1.0 412 ' . $errorMessage); die('Error 412 ' . $errorMessage); } else { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');"; break; } } $logMessage = ""; foreach ($fileVars as $boxName => $boxData) { if ($boxName != "Filedata" && substr($boxName, 0, 9) != "userfile_") { continue; } if ($boxName == "Filedata") { $fancyLoader = true; } $err = Utils::parseFileDataErrors($boxData, $fancyLoader); if ($err != null) { $errorMessage = $err; break; } $userfile_name = $boxData["name"]; if ($fancyLoader) { $userfile_name = SystemTextEncoding::fromUTF8($userfile_name); } $userfile_name = Utils::processFileName($userfile_name); if (isset($auto_rename)) { $userfile_name = fsDriver::autoRenameForDest($destination, $userfile_name); } if (!move_uploaded_file($boxData["tmp_name"], "{$destination}/" . $userfile_name)) { $errorMessage = ($fancyLoader ? "411 " : "") . "{$mess['33']} " . $userfile_name; break; } $this->changeMode($destination . "/" . $userfile_name); $logMessage .= "{$mess['34']} " . SystemTextEncoding::toUTF8($userfile_name) . " {$mess['35']} {$dir}"; AJXP_Logger::logAction("Upload File", array("file" => SystemTextEncoding::fromUTF8($dir) . "/" . $userfile_name)); } if ($fancyLoader) { if (isset($errorMessage)) { header('HTTP/1.0 ' . $errorMessage); die('Error ' . $errorMessage); } else { header('HTTP/1.0 200 OK'); die("200 OK"); } } else { print "<html><script language=\"javascript\">\n"; if (isset($errorMessage)) { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext('" . str_replace("'", "\\'", $errorMessage) . "');"; } else { print "\n if(parent.ajaxplorer.actionBar.multi_selector)parent.ajaxplorer.actionBar.multi_selector.submitNext();"; } print "</script></html>"; } exit; break; //------------------------------------ // Public URL //------------------------------------ //------------------------------------ // Public URL //------------------------------------ case "public_url": $file = SystemTextEncoding::fromUTF8($file); $url = $this->makePubliclet($file, $password, $expiration); header("Content-type:text/plain"); echo $url; exit(1); break; //------------------------------------ // XML LISTING //------------------------------------ //------------------------------------ // XML LISTING //------------------------------------ case "ls": if (!isset($dir) || $dir == "/") { $dir = ""; } $searchMode = $fileListMode = $completeMode = false; if (isset($mode)) { if ($mode == "search") { $searchMode = true; } else { if ($mode == "file_list") { $fileListMode = true; } else { if ($mode == "complete") { $completeMode = true; } } } } if (isset($skipZip) && $skipZip == "true") { $skipZip = true; } else { $skipZip = false; } if ($test = UserSelection::detectZip($dir)) { $liste = array(); $zip = $this->zipListing($test[0], $test[1], $liste); AJXP_XMLWriter::header(); $tmpDir = $this->getPath() . dirname($test[0]) . ".tmpZipExtract"; foreach ($liste as $zipEntry) { $atts = array(); if (!$fileListMode && !$zipEntry["folder"]) { continue; } $atts[] = "is_file=\"" . ($zipEntry["folder"] ? "false" : "true") . "\""; $atts[] = "text=\"" . Utils::xmlEntities(basename(SystemTextEncoding::toUTF8($zipEntry["stored_filename"]))) . "\""; $atts[] = "filename=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\""; if ($fileListMode) { $atts[] = "filesize=\"" . Utils::roundSize($zipEntry["size"]) . "\""; $atts[] = "bytesize=\"" . $zipEntry["size"] . "\""; $atts[] = "ajxp_modiftime=\"" . $zipEntry["mtime"] . "\""; $atts[] = "mimestring=\"" . Utils::mimetype($zipEntry["stored_filename"], "mime", $zipEntry["folder"]) . "\""; $atts[] = "icon=\"" . Utils::mimetype($zipEntry["stored_filename"], "image", $zipEntry["folder"]) . "\""; $is_image = Utils::is_image(basename($zipEntry["stored_filename"])); $atts[] = "is_image=\"" . $is_image . "\""; if ($is_image) { if (!is_dir($tmpDir)) { mkdir($tmpDir); } $currentFile = $tmpDir . "/" . basename($zipEntry["stored_filename"]); $data = $zip->extract(PCLZIP_OPT_BY_NAME, $zipEntry["stored_filename"], PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_PATH, $tmpDir); list($width, $height, $type, $attr) = @getimagesize($currentFile); $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\""; $atts[] = "image_width=\"{$width}\""; $atts[] = "image_height=\"{$height}\""; unlink($currentFile); } } else { $atts[] = "icon=\"client/images/foldericon.png\""; $atts[] = "openicon=\"client/images/foldericon.png\""; $atts[] = "src=\"content.php?dir=" . urlencode(SystemTextEncoding::toUTF8($zipEntry["filename"])) . "\""; } print "<tree " . join(" ", $atts) . "/>"; } if (is_dir($tmpDir)) { rmdir($tmpDir); } AJXP_XMLWriter::close(); exit(0); } $nom_rep = $this->initName($dir); AJXP_Exception::errorToXml($nom_rep); $threshold = $this->repository->getOption("PAGINATION_THRESHOLD"); if (!isset($threshold) || intval($threshold) == 0) { $threshold = 500; } $limitPerPage = $this->repository->getOption("PAGINATION_NUMBER"); if (!isset($limitPerPage) || intval($limitPerPage) == 0) { $limitPerPage = 200; } if ($fileListMode) { $countFiles = $this->countFiles($nom_rep); if ($countFiles > $threshold) { $offset = 0; $crtPage = 1; if (isset($page)) { $offset = (intval($page) - 1) * $limitPerPage; $crtPage = $page; } $totalPages = floor($countFiles / $limitPerPage) + 1; $reps = $this->listing($nom_rep, false, $offset, $limitPerPage); } else { $reps = $this->listing($nom_rep, $searchMode); } } else { $countFolders = $this->countFiles($nom_rep, true); if ($countFolders > $threshold) { AJXP_XMLWriter::header(); $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png"; $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png"; $attributes = "icon=\"{$icon}\" openicon=\"{$openicon}\""; print "<tree text=\"{$mess['306']} ({$countFolders})...\" {$attributes}></tree>"; AJXP_XMLWriter::close(); exit(1); } $reps = $this->listing($nom_rep, !$searchMode); } //$reps = $result[0]; AJXP_XMLWriter::header(); if (isset($totalPages) && isset($crtPage)) { //print '<columns switchDisplayMode="list" switchGridMode="filelist"/>'; print '<pagination count="' . $countFiles . '" total="' . $totalPages . '" current="' . $crtPage . '"/>'; } foreach ($reps as $repIndex => $repName) { if (preg_match("/\\.zip\$/", $repName) && $skipZip) { continue; } $attributes = ""; if ($searchMode) { if (is_file($nom_rep . "/" . $repIndex)) { $attributes = "is_file=\"true\" icon=\"{$repName}\""; $repName = $repIndex; } } else { if ($fileListMode) { $currentFile = $nom_rep . "/" . $repIndex; $atts = array(); $atts[] = "is_file=\"" . (is_file($currentFile) ? "1" : "0") . "\""; $atts[] = "is_image=\"" . Utils::is_image($currentFile) . "\""; $fGroup = @filegroup($currentFile) || "unknown"; $atts[] = "file_group=\"" . $fGroup . "\""; $fOwner = @fileowner($currentFile) || "unknown"; $atts[] = "file_owner=\"" . $fOwner . "\""; $fPerms = @fileperms($currentFile); if ($fPerms !== false) { $fPerms = substr(decoct($fPerms), is_file($currentFile) ? 2 : 1); } else { $fPerms = '0000'; } $atts[] = "file_perms=\"" . $fPerms . "\""; if (Utils::is_image($currentFile)) { list($width, $height, $type, $attr) = @getimagesize($currentFile); $atts[] = "image_type=\"" . image_type_to_mime_type($type) . "\""; $atts[] = "image_width=\"{$width}\""; $atts[] = "image_height=\"{$height}\""; } $atts[] = "mimestring=\"" . Utils::mimetype($currentFile, "type", is_dir($currentFile)) . "\""; $datemodif = $this->date_modif($currentFile); $atts[] = "ajxp_modiftime=\"" . ($datemodif ? $datemodif : "0") . "\""; $bytesize = @filesize($currentFile) or 0; if ($bytesize < 0) { $bytesize = sprintf("%u", $bytesize); } $atts[] = "filesize=\"" . Utils::roundSize($bytesize) . "\""; $atts[] = "bytesize=\"" . $bytesize . "\""; $atts[] = "filename=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($dir . "/" . $repIndex)) . "\""; $atts[] = "icon=\"" . (is_file($currentFile) ? SystemTextEncoding::toUTF8($repName) : (is_dir($currentFile) ? "folder.png" : "mime-empty.png")) . "\""; $attributes = join(" ", $atts); $repName = $repIndex; } else { $folderBaseName = Utils::xmlEntities($repName); $link = SystemTextEncoding::toUTF8(SERVER_ACCESS . "?dir=" . $dir . "/" . $folderBaseName); $link = urlencode($link); $folderFullName = Utils::xmlEntities($dir) . "/" . $folderBaseName; $parentFolderName = $dir; if (!$completeMode) { $icon = CLIENT_RESOURCES_FOLDER . "/images/foldericon.png"; $openicon = CLIENT_RESOURCES_FOLDER . "/images/openfoldericon.png"; if (preg_match("/\\.zip\$/", $repName)) { $icon = $openicon = CLIENT_RESOURCES_FOLDER . "/images/crystal/actions/16/accessories-archiver.png"; } $attributes = "icon=\"{$icon}\" openicon=\"{$openicon}\" filename=\"" . SystemTextEncoding::toUTF8($folderFullName) . "\" src=\"{$link}\""; } } } print "<tree text=\"" . Utils::xmlEntities(SystemTextEncoding::toUTF8($repName)) . "\" {$attributes}>"; print "</tree>"; } // ADD RECYCLE BIN TO THE LIST if ($nom_rep == $this->repository->getOption("PATH") && RecycleBinManager::recycleEnabled() && !$completeMode && !$skipZip) { $recycleBinOption = $this->repository->getOption("RECYCLE_BIN"); if (is_dir($this->repository->getOption("PATH") . "/" . $recycleBinOption)) { $recycleIcon = $this->countFiles($this->repository->getOption("PATH") . "/" . $recycleBinOption, false, true) > 0 ? "trashcan_full.png" : "trashcan.png"; if ($fileListMode) { print "<tree text=\"" . Utils::xmlEntities($mess[122]) . "\" filesize=\"-\" is_file=\"0\" is_recycle=\"1\" mimestring=\"Trashcan\" ajxp_modiftime=\"" . $this->date_modif($this->repository->getOption("PATH") . "/" . $recycleBinOption) . "\" filename=\"/" . $recycleBinOption . "\" icon=\"{$recycleIcon}\"></tree>"; } else { print "<tree text=\"{$mess['122']}\" is_recycle=\"true\" icon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/{$recycleIcon}\" openIcon=\"" . CLIENT_RESOURCES_FOLDER . "/images/crystal/mimes/16/{$recycleIcon}\" filename=\"/" . $recycleBinOption . "\"/>"; } } } AJXP_XMLWriter::close(); exit(1); break; } if (isset($logMessage) || isset($errorMessage)) { $xmlBuffer .= AJXP_XMLWriter::sendMessage(isset($logMessage) ? $logMessage : null, isset($errorMessage) ? $errorMessage : null, false); } if (isset($requireAuth)) { $xmlBuffer .= AJXP_XMLWriter::requireAuth(false); } if (isset($reload_current_node) && $reload_current_node == "true") { $xmlBuffer .= AJXP_XMLWriter::reloadCurrentNode(false); } if (isset($reload_dest_node) && $reload_dest_node != "") { $xmlBuffer .= AJXP_XMLWriter::reloadNode($reload_dest_node, false); } if (isset($reload_file_list)) { $xmlBuffer .= AJXP_XMLWriter::reloadFileList($reload_file_list, false); } return $xmlBuffer; }
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); }
// 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();
/** * See static method * @param Repository $repository * @throws AJXP_Exception|Exception * @return AbstractAccessDriver */ public function loadRepositoryDriverREST(&$repository) { if (isset($repository->driverInstance)) { return $repository->driverInstance; } $accessType = $repository->getAccessType(); $pServ = AJXP_PluginsService::getInstance(); $plugInstance = $pServ->getPluginByTypeName("access", $accessType); // TRIGGER BEFORE INIT META $metaSources = $repository->getOption("META_SOURCES"); if (isset($metaSources) && is_array($metaSources) && count($metaSources)) { $keys = array_keys($metaSources); foreach ($keys as $plugId) { if ($plugId == "") { continue; } $instance = $pServ->getPluginById($plugId); if (!is_object($instance)) { continue; } if (!method_exists($instance, "beforeInitMeta")) { continue; } try { $instance->init(AuthService::filterPluginParameters($plugId, $metaSources[$plugId], $repository->getId())); $instance->beforeInitMeta($plugInstance, $repository); } catch (Exception $e) { AJXP_Logger::error(__CLASS__, 'Meta plugin', 'Cannot instanciate Meta plugin, reason : ' . $e->getMessage()); $this->errors[] = $e->getMessage(); } } } // INIT MAIN DRIVER $plugInstance->init($repository); try { $plugInstance->initRepository(); } catch (Exception $e) { throw $e; } AJXP_PluginsService::deferBuildingRegistry(); $pServ->setPluginUniqueActiveForType("access", $accessType); // TRIGGER INIT META $metaSources = $repository->getOption("META_SOURCES"); if (isset($metaSources) && is_array($metaSources) && count($metaSources)) { $keys = array_keys($metaSources); foreach ($keys as $plugId) { if ($plugId == "") { continue; } $split = explode(".", $plugId); $instance = $pServ->getPluginById($plugId); if (!is_object($instance)) { continue; } try { $instance->init(AuthService::filterPluginParameters($plugId, $metaSources[$plugId], $repository->getId())); if (!method_exists($instance, "initMeta")) { throw new Exception("Meta Source {$plugId} does not implement the initMeta method."); } $instance->initMeta($plugInstance); } catch (Exception $e) { AJXP_Logger::error(__CLASS__, 'Meta plugin', 'Cannot instanciate Meta plugin, reason : ' . $e->getMessage()); $this->errors[] = $e->getMessage(); } $pServ->setPluginActive($split[0], $split[1]); } } AJXP_PluginsService::flushDeferredRegistryBuilding(); if (count($this->errors) > 0) { $e = new AJXP_Exception("Error while loading repository feature : " . implode(",", $this->errors)); throw $e; } $repository->driverInstance = $plugInstance; if (isset($_SESSION["REPO_ID"]) && $_SESSION["REPO_ID"] == $repository->getId()) { $this->configs["REPOSITORY"] = $repository; if (is_array($this->configs["REPOSITORIES"])) { $this->configs["REPOSITORIES"][$_SESSION['REPO_ID']] = $repository; } } return $plugInstance; }
/** * * @param AJXP_Node $ajxpNode */ public function extractMeta(&$ajxpNode) { //if(isSet($_SESSION["SVN_COMMAND_RUNNING"]) && $_SESSION["SVN_COMMAND_RUNNING"] === true) return ; $realDir = dirname($ajxpNode->getRealFile()); if (SvnManager::$svnListDir == $realDir) { $entries = SvnManager::$svnListCache; } else { try { SvnManager::$svnListDir = $realDir; $entries = $this->svnListNode($realDir); SvnManager::$svnListCache = $entries; } catch (Exception $e) { AJXP_Logger::logAction("Error", array($e->getMessage())); } } $fileId = SystemTextEncoding::toUTF8(basename($ajxpNode->getUrl())); if (isset($entries[$fileId])) { $ajxpNode->mergeMetadata($entries[$fileId]); } }
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; }
$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); } $authPlugin = new Sabre\DAV\Auth\Plugin($authBackend, ConfService::getCoreConf("WEBDAV_DIGESTREALM")); $server->addPlugin($authPlugin); if (!is_dir(AJXP_DATA_PATH . "/plugins/server.sabredav")) { mkdir(AJXP_DATA_PATH . "/plugins/server.sabredav", 0755); $fp = fopen(AJXP_DATA_PATH . "/plugins/server.sabredav/locks", "w"); fwrite($fp, ""); fclose($fp); } $lockBackend = new Sabre\DAV\Locks\Backend\File(AJXP_DATA_PATH . "/plugins/server.sabredav/locks"); $lockPlugin = new Sabre\DAV\Locks\Plugin($lockBackend); $server->addPlugin($lockPlugin); if (ConfService::getCoreConf("WEBDAV_BROWSER_LISTING")) { $browerPlugin = new AJXP_Sabre_BrowserPlugin(isset($repository) ? $repository->getDisplay() : null); $extPlugin = new Sabre\DAV\Browser\GuessContentType(); $server->addPlugin($browerPlugin); $server->addPlugin($extPlugin); } try { $server->exec(); } catch (Exception $e) { AJXP_Logger::error(__CLASS__, "Exception", $e->getMessage()); }