* @author Andreas Fischer * @author Arthur Schiwon * @author Bart Visscher * @author Bernhard Posselt * @author Björn Schießle * @author Christoph Wurst * @author davidgumberg * @author Florin Peter * @author Georg Ehrke * @author Hugo Gonzalez Labrador * @author Individual IT Services * @author Jakob Sack * @author Joachim Bauch * @author Joachim Sokolowski * @author Joas Schilling * @author Jörn Friedrich Dreyer * @author Lukas Reschke * @author Michael Gapczynski * @author Morris Jobke * @author Owen Winkler * @author Phil Davis * @author Ramiro Aparicio * @author Robin Appelman * @author Robin McCorkell * @author Roeland Jago Douma * @author Stefan Weil * @author Thomas Müller * @author Thomas Pulzer * @author Thomas Tanghus * @author Vincent Petry * @author Volkan Gezer * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see * */ require_once 'public/Constants.php'; /** * Class that is a namespace for all global OC variables * No, we can not put this class in its own file because it is used by * OC_autoload! */ class OC { /** * Associative array for autoloading. classname => filename */ public static $CLASSPATH = array(); /** * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) */ public static $SERVERROOT = ''; /** * the current request path relative to the Nextcloud root (e.g. files/index.php) */ private static $SUBURI = ''; /** * the Nextcloud root path for http requests (e.g. nextcloud/) */ public static $WEBROOT = ''; /** * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and * web path in 'url' */ public static $APPSROOTS = array(); /** * @var string */ public static $configDir; /** * requested app */ public static $REQUESTEDAPP = ''; /** * check if Nextcloud runs in cli mode */ public static $CLI = false; /** * @var \OC\Autoloader $loader */ public static $loader = null; /** @var \Composer\Autoload\ClassLoader $composerAutoloader */ public static $composerAutoloader = null; /** * @var \OC\Server */ public static $server = null; /** * @var \OC\Config */ private static $config = null; /** * @throws \RuntimeException when the 3rdparty directory is missing or * the app path list is empty or contains an invalid path */ public static function initPaths() { if(defined('PHPUNIT_CONFIG_DIR')) { self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { self::$configDir = OC::$SERVERROOT . '/tests/config/'; } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { self::$configDir = rtrim($dir, '/') . '/'; } else { self::$configDir = OC::$SERVERROOT . '/config/'; } self::$config = new \OC\Config(self::$configDir); OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT))); /** * FIXME: The following lines are required because we can't yet instantiiate * \OC::$server->getRequest() since \OC::$server does not yet exist. */ $params = [ 'server' => [ 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'], 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'], ], ]; $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config))); $scriptName = $fakeRequest->getScriptName(); if (substr($scriptName, -1) == '/') { $scriptName .= 'index.php'; //make sure suburi follows the same rules as scriptName if (substr(OC::$SUBURI, -9) != 'index.php') { if (substr(OC::$SUBURI, -1) != '/') { OC::$SUBURI = OC::$SUBURI . '/'; } OC::$SUBURI = OC::$SUBURI . 'index.php'; } } if (OC::$CLI) { OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); } else { if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { OC::$WEBROOT = '/' . OC::$WEBROOT; } } else { // The scriptName is not ending with OC::$SUBURI // This most likely means that we are calling from CLI. // However some cron jobs still need to generate // a web URL, so we use overwritewebroot as a fallback. OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); } // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing // slash which is required by URL generation. if($_SERVER['REQUEST_URI'] === \OC::$WEBROOT && substr($_SERVER['REQUEST_URI'], -1) !== '/') { header('Location: '.\OC::$WEBROOT.'/'); exit(); } } // search the apps folder $config_paths = self::$config->getValue('apps_paths', array()); if (!empty($config_paths)) { foreach ($config_paths as $paths) { if (isset($paths['url']) && isset($paths['path'])) { $paths['url'] = rtrim($paths['url'], '/'); $paths['path'] = rtrim($paths['path'], '/'); OC::$APPSROOTS[] = $paths; } } } elseif (file_exists(OC::$SERVERROOT . '/apps')) { OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true); } elseif (file_exists(OC::$SERVERROOT . '/../apps')) { OC::$APPSROOTS[] = array( 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps', 'url' => '/apps', 'writable' => true ); } if (empty(OC::$APPSROOTS)) { throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' . ' or the folder above. You can also configure the location in the config.php file.'); } $paths = array(); foreach (OC::$APPSROOTS as $path) { $paths[] = $path['path']; if (!is_dir($path['path'])) { throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' . ' Nextcloud folder or the folder above. You can also configure the location in the' . ' config.php file.', $path['path'])); } } // set the right include path set_include_path( OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR . self::$configDir . PATH_SEPARATOR . OC::$SERVERROOT . '/3rdparty' . PATH_SEPARATOR . implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR . get_include_path() . PATH_SEPARATOR . OC::$SERVERROOT ); } public static function checkConfig() { $l = \OC::$server->getL10N('lib'); // Create config if it does not already exist $configFilePath = self::$configDir .'/config.php'; if(!file_exists($configFilePath)) { @touch($configFilePath); } // Check if config is writable $configFileWritable = is_writable($configFilePath); if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() || !$configFileWritable && self::checkUpgrade(false)) { $urlGenerator = \OC::$server->getURLGenerator(); if (self::$CLI) { echo $l->t('Cannot write into "config" directory!')."\n"; echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n"; echo "\n"; echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n"; exit; } else { OC_Template::printErrorPage( $l->t('Cannot write into "config" directory!'), $l->t('This can usually be fixed by ' . '%sgiving the webserver write access to the config directory%s.', array('', '')) ); } } } public static function checkInstalled() { if (defined('OC_CONSOLE')) { return; } // Redirect to installer if not installed if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { if (OC::$CLI) { throw new Exception('Not installed'); } else { $url = OC::$WEBROOT . '/index.php'; header('Location: ' . $url); } exit(); } } public static function checkMaintenanceMode() { // Allow ajax update script to execute without being stopped if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') { // send http status 503 header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 120'); // render error page $template = new OC_Template('', 'update.user', 'guest'); OC_Util::addScript('maintenance-check'); $template->printPage(); die(); } } public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) { if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) { return; } $user = OC_User::getUserSession()->getUser(); if ($user) { $group = \OC::$server->getGroupManager()->get('admin'); if ($group->inGroup($user)) { return; } } else { if(!$lockIfNoUserLoggedIn) { return; } } // send http status 503 header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 120'); // render error page $template = new OC_Template('', 'singleuser.user', 'guest'); $template->printPage(); die(); } /** * Checks if the version requires an update and shows * @param bool $showTemplate Whether an update screen should get shown * @return bool|void */ public static function checkUpgrade($showTemplate = true) { if (\OCP\Util::needUpgrade()) { $systemConfig = \OC::$server->getSystemConfig(); if ($showTemplate && !$systemConfig->getValue('maintenance', false)) { self::printUpgradePage(); exit(); } else { return true; } } return false; } /** * Prints the upgrade page */ private static function printUpgradePage() { $systemConfig = \OC::$server->getSystemConfig(); $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); $tooBig = false; if (!$disableWebUpdater) { $apps = \OC::$server->getAppManager(); $tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth'); if (!$tooBig) { // count users $stats = \OC::$server->getUserManager()->countUsers(); $totalUsers = array_sum($stats); $tooBig = ($totalUsers > 50); } } if ($disableWebUpdater || $tooBig) { // send http status 503 header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 120'); // render error page $template = new OC_Template('', 'update.use-cli', 'guest'); $template->assign('productName', 'nextcloud'); // for now $template->assign('version', OC_Util::getVersionString()); $template->assign('tooBig', $tooBig); $template->printPage(); die(); } // check whether this is a core update or apps update $installedVersion = $systemConfig->getValue('version', '0.0.0'); $currentVersion = implode('.', \OCP\Util::getVersion()); // if not a core upgrade, then it's apps upgrade $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '=')); $oldTheme = $systemConfig->getValue('theme'); $systemConfig->setValue('theme', ''); \OCP\Util::addScript('config'); // needed for web root \OCP\Util::addScript('update'); \OCP\Util::addStyle('update'); $appManager = \OC::$server->getAppManager(); $tmpl = new OC_Template('', 'update.admin', 'guest'); $tmpl->assign('version', OC_Util::getVersionString()); $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); // get third party apps $ocVersion = \OCP\Util::getVersion(); $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); $tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion)); $tmpl->assign('productName', 'Nextcloud'); // for now $tmpl->assign('oldTheme', $oldTheme); $tmpl->printPage(); } public static function initSession() { // prevents javascript from accessing php session cookies ini_set('session.cookie_httponly', true); // set the cookie path to the Nextcloud directory $cookie_path = OC::$WEBROOT ? : '/'; ini_set('session.cookie_path', $cookie_path); // Let the session name be changed in the initSession Hook $sessionName = OC_Util::getInstanceId(); try { // Allow session apps to create a custom session object $useCustomSession = false; $session = self::$server->getSession(); OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession)); if (!$useCustomSession) { // set the session name to the instance id - which is unique $session = new \OC\Session\Internal($sessionName); } $cryptoWrapper = \OC::$server->getSessionCryptoWrapper(); $session = $cryptoWrapper->wrapSession($session); self::$server->setSession($session); // if session can't be started break with http 500 error } catch (Exception $e) { \OCP\Util::logException('base', $e); //show the user a detailed error page OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR); OC_Template::printExceptionErrorPage($e); die(); } $sessionLifeTime = self::getSessionLifeTime(); // session timeout if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { if (isset($_COOKIE[session_name()])) { setcookie(session_name(), null, -1, self::$WEBROOT ? : '/'); } \OC::$server->getUserSession()->logout(); } $session->set('LAST_ACTIVITY', time()); } /** * @return string */ private static function getSessionLifeTime() { return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24); } public static function loadAppClassPaths() { foreach (OC_App::getEnabledApps() as $app) { $appPath = OC_App::getAppPath($app); if ($appPath === false) { continue; } $file = $appPath . '/appinfo/classpath.php'; if (file_exists($file)) { require_once $file; } } } /** * Try to set some values to the required Nextcloud default */ public static function setRequiredIniValues() { @ini_set('default_charset', 'UTF-8'); @ini_set('gd.jpeg_ignore_warning', 1); } /** * Send the same site cookies */ private static function sendSameSiteCookies() { $cookieParams = session_get_cookie_params(); $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; $policies = [ 'lax', 'strict', ]; foreach($policies as $policy) { header( sprintf( 'Set-Cookie: nc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', $policy, $cookieParams['path'], $policy ), false ); } } /** * Same Site cookie to further mitigate CSRF attacks. This cookie has to * be set in every request if cookies are sent to add a second level of * defense against CSRF. * * If the cookie is not sent this will set the cookie and reload the page. * We use an additional cookie since we want to protect logout CSRF and * also we can't directly interfere with PHP's session mechanism. */ private static function performSameSiteCookieProtection() { $request = \OC::$server->getRequest(); // Some user agents are notorious and don't really properly follow HTTP // specifications. For those, have an automated opt-out. Since the protection // for remote.php is applied in base.php as starting point we need to opt out // here. $incompatibleUserAgents = [ // OS X Finder '/^WebDAVFS/', ]; if($request->isUserAgent($incompatibleUserAgents)) { return; } // Chrome on Android has a bug that it doesn't sent cookies with the // same-site attribute for the download manager. To work around that // all same-site cookies get deleted and recreated directly. Awesome! // FIXME: Remove once Chrome 54 is deployed to end-users // @see https://github.com/nextcloud/server/pull/1454 if($request->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME])) { return; } if(count($_COOKIE) > 0) { $requestUri = $request->getScriptName(); $processingScript = explode('/', $requestUri); $processingScript = $processingScript[count($processingScript)-1]; // FIXME: In a SAML scenario we don't get any strict or lax cookie // send for the ACS endpoint. Since we have some legacy code in Nextcloud // (direct PHP files) the enforcement of lax cookies is performed here // instead of the middleware. // // This means we cannot exclude some routes from the cookie validation, // which normally is not a problem but is a little bit cumbersome for // this use-case. // Once the old legacy PHP endpoints have been removed we can move // the verification into a middleware and also adds some exemptions. // // Questions about this code? Ask Lukas ;-) $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT)); if($currentUrl === '/index.php/apps/user_saml/saml/acs') { return; } // For the "index.php" endpoint only a lax cookie is required. if($processingScript === 'index.php') { if(!$request->passesLaxCookieCheck()) { self::sendSameSiteCookies(); header('Location: '.$_SERVER['REQUEST_URI']); exit(); } } else { // All other endpoints require the lax and the strict cookie if(!$request->passesStrictCookieCheck()) { self::sendSameSiteCookies(); // Debug mode gets access to the resources without strict cookie // due to the fact that the SabreDAV browser also lives there. if(!\OC::$server->getConfig()->getSystemValue('debug', false)) { http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); exit(); } } } } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { self::sendSameSiteCookies(); } } public static function init() { // calculate the root directories OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4)); // register autoloader $loaderStart = microtime(true); require_once __DIR__ . '/autoloader.php'; self::$loader = new \OC\Autoloader([ OC::$SERVERROOT . '/lib/private/legacy', ]); if (defined('PHPUNIT_RUN')) { self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); } spl_autoload_register(array(self::$loader, 'load')); $loaderEnd = microtime(true); self::$CLI = (php_sapi_name() == 'cli'); // Add default composer PSR-4 autoloader self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; try { self::initPaths(); // setup 3rdparty autoloader $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php'; if (!file_exists($vendorAutoLoad)) { throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); } require_once $vendorAutoLoad; } catch (\RuntimeException $e) { if (!self::$CLI) { $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']); $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1'; header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE); } // we can't use the template error page here, because this needs the // DI container which isn't available yet print($e->getMessage()); exit(); } // setup the basic server self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); \OC::$server->getEventLogger()->start('boot', 'Initialize'); // Don't display errors and log them error_reporting(E_ALL | E_STRICT); @ini_set('display_errors', 0); @ini_set('log_errors', 1); date_default_timezone_set('UTC'); //try to configure php to enable big file uploads. //this doesn´t work always depending on the webserver and php configuration. //Let´s try to overwrite some defaults anyway //try to set the maximum execution time to 60min @set_time_limit(3600); @ini_set('max_execution_time', 3600); @ini_set('max_input_time', 3600); //try to set the maximum filesize to 10G @ini_set('upload_max_filesize', '10G'); @ini_set('post_max_size', '10G'); @ini_set('file_uploads', '50'); self::setRequiredIniValues(); self::handleAuthHeaders(); self::registerAutoloaderCache(); // initialize intl fallback is necessary \Patchwork\Utf8\Bootup::initIntl(); OC_Util::isSetLocaleWorking(); if (!defined('PHPUNIT_RUN')) { OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger()); $debug = \OC::$server->getConfig()->getSystemValue('debug', false); OC\Log\ErrorHandler::register($debug); } // register the stream wrappers stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir'); stream_wrapper_register('static', 'OC\Files\Stream\StaticStream'); stream_wrapper_register('close', 'OC\Files\Stream\Close'); stream_wrapper_register('quota', 'OC\Files\Stream\Quota'); stream_wrapper_register('oc', 'OC\Files\Stream\OC'); \OC::$server->getEventLogger()->start('init_session', 'Initialize session'); OC_App::loadApps(array('session')); if (!self::$CLI) { self::initSession(); } \OC::$server->getEventLogger()->end('init_session'); self::checkConfig(); self::checkInstalled(); OC_Response::addSecurityHeaders(); if(self::$server->getRequest()->getServerProtocol() === 'https') { ini_set('session.cookie_secure', true); } self::performSameSiteCookieProtection(); if (!defined('OC_CONSOLE')) { $errors = OC_Util::checkServer(\OC::$server->getConfig()); if (count($errors) > 0) { if (self::$CLI) { // Convert l10n string into regular string for usage in database $staticErrors = []; foreach ($errors as $error) { echo $error['error'] . "\n"; echo $error['hint'] . "\n\n"; $staticErrors[] = [ 'error' => (string)$error['error'], 'hint' => (string)$error['hint'], ]; } try { \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors)); } catch (\Exception $e) { echo('Writing to database failed'); } exit(1); } else { OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printGuestPage('', 'error', array('errors' => $errors)); exit; } } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) { \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors'); } } //try to set the session lifetime $sessionLifeTime = self::getSessionLifeTime(); @ini_set('gc_maxlifetime', (string)$sessionLifeTime); $systemConfig = \OC::$server->getSystemConfig(); // User and Groups if (!$systemConfig->getValue("installed", false)) { self::$server->getSession()->set('user_id', ''); } OC_User::useBackend(new \OC\User\Database()); OC_Group::useBackend(new \OC\Group\Database()); // Subscribe to the hook \OCP\Util::connectHook( '\OCA\Files_Sharing\API\Server2Server', 'preLoginNameUsedAsUserName', '\OC\User\Database', 'preLoginNameUsedAsUserName' ); //setup extra user backends if (!self::checkUpgrade(false)) { OC_User::setupBackends(); } else { // Run upgrades in incognito mode OC_User::setIncognitoMode(true); } self::registerCacheHooks(); self::registerFilesystemHooks(); if ($systemConfig->getValue('enable_previews', true)) { self::registerPreviewHooks(); } self::registerShareHooks(); self::registerLogRotate(); self::registerEncryptionWrapper(); self::registerEncryptionHooks(); self::registerSettingsHooks(); //make sure temporary files are cleaned up $tmpManager = \OC::$server->getTempManager(); register_shutdown_function(array($tmpManager, 'clean')); $lockProvider = \OC::$server->getLockingProvider(); register_shutdown_function(array($lockProvider, 'releaseAll')); // Check whether the sample configuration has been copied if($systemConfig->getValue('copied_sample_config', false)) { $l = \OC::$server->getL10N('lib'); header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); OC_Template::printErrorPage( $l->t('Sample configuration detected'), $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php') ); return; } $request = \OC::$server->getRequest(); $host = $request->getInsecureServerHost(); /** * if the host passed in headers isn't trusted * FIXME: Should not be in here at all :see_no_evil: */ if (!OC::$CLI // overwritehost is always trusted, workaround to not have to make // \OC\AppFramework\Http\Request::getOverwriteHost public && self::$server->getConfig()->getSystemValue('overwritehost') === '' && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host) && self::$server->getConfig()->getSystemValue('installed', false) ) { header('HTTP/1.1 400 Bad Request'); header('Status: 400 Bad Request'); \OC::$server->getLogger()->warning( 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', [ 'app' => 'core', 'remoteAddress' => $request->getRemoteAddress(), 'host' => $host, ] ); $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); $tmpl->assign('domain', $host); $tmpl->printPage(); exit(); } \OC::$server->getEventLogger()->end('boot'); } /** * register hooks for the cache */ public static function registerCacheHooks() { //don't try to do this before we are properly setup if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) { // NOTE: This will be replaced to use OCP $userSession = self::$server->getUserSession(); $userSession->listen('\OC\User', 'postLogin', function () { try { $cache = new \OC\Cache\File(); $cache->gc(); } catch (\OC\ServerNotAvailableException $e) { // not a GC exception, pass it on throw $e; } catch (\Exception $e) { // a GC exception should not prevent users from using OC, // so log the exception \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core')); } }); } } public static function registerSettingsHooks() { $dispatcher = \OC::$server->getEventDispatcher(); $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) { /** @var \OCP\App\ManagerEvent $event */ \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID()); }); $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) { /** @var \OCP\App\ManagerEvent $event */ $jobList = \OC::$server->getJobList(); $job = 'OC\\Settings\\RemoveOrphaned'; if(!($jobList->has($job, null))) { $jobList->add($job); } }); } private static function registerEncryptionWrapper() { $manager = self::$server->getEncryptionManager(); \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage'); } private static function registerEncryptionHooks() { $enabled = self::$server->getEncryptionManager()->isEnabled(); if ($enabled) { \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared'); \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared'); \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename'); \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore'); } } /** * register hooks for the cache */ public static function registerLogRotate() { $systemConfig = \OC::$server->getSystemConfig(); if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) { //don't try to do this before we are properly setup //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/nextcloud.log')); } } /** * register hooks for the filesystem */ public static function registerFilesystemHooks() { // Check for blacklisted files OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted'); OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted'); } /** * register hooks for previews */ public static function registerPreviewHooks() { OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write'); OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files'); OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete'); OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete'); OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files'); OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions'); OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete'); OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions'); } /** * register hooks for sharing */ public static function registerShareHooks() { if (\OC::$server->getSystemConfig()->getValue('installed')) { OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser'); OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup'); OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup'); } } protected static function registerAutoloaderCache() { // The class loader takes an optional low-latency cache, which MUST be // namespaced. The instanceid is used for namespacing, but might be // unavailable at this point. Furthermore, it might not be possible to // generate an instanceid via \OC_Util::getInstanceId() because the // config file may not be writable. As such, we only register a class // loader cache if instanceid is available without trying to create one. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null); if ($instanceId) { try { $memcacheFactory = \OC::$server->getMemCacheFactory(); self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader')); } catch (\Exception $ex) { } } } /** * Handle the request */ public static function handleRequest() { \OC::$server->getEventLogger()->start('handle_request', 'Handle request'); $systemConfig = \OC::$server->getSystemConfig(); // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if Nextcloud is installed or in maintenance (update) mode if (!$systemConfig->getValue('installed', false)) { \OC::$server->getSession()->clear(); $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(), \OC::$server->getL10N('lib'), \OC::$server->getThemingDefaults(), \OC::$server->getLogger(), \OC::$server->getSecureRandom()); $controller = new OC\Core\Controller\SetupController($setupHelper); $controller->run($_POST); exit(); } $request = \OC::$server->getRequest(); $requestPath = $request->getRawPathInfo(); if ($requestPath === '/heartbeat') { return; } if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode(); self::checkUpgrade(); } // emergency app disabling if ($requestPath === '/disableapp' && $request->getMethod() === 'POST' && ((string)$request->getParam('appid')) !== '' ) { \OCP\JSON::callCheck(); \OCP\JSON::checkAdminUser(); $appId = (string)$request->getParam('appid'); $appId = \OC_App::cleanAppId($appId); \OC_App::disable($appId); \OC_JSON::success(); exit(); } // Always load authentication apps OC_App::loadApps(['authentication']); // Load minimum set of apps if (!self::checkUpgrade(false) && !$systemConfig->getValue('maintenance', false)) { // For logged-in users: Load everything if(OC_User::isLoggedIn()) { OC_App::loadApps(); } else { // For guests: Load only filesystem and logging OC_App::loadApps(array('filesystem', 'logging')); self::handleLogin($request); } } if (!self::$CLI) { try { if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) { OC_App::loadApps(array('filesystem', 'logging')); OC_App::loadApps(); } self::checkSingleUserMode(); OC_Util::setupFS(); OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo()); return; } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { //header('HTTP/1.0 404 Not Found'); } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { OC_Response::setStatus(405); return; } } // Handle WebDAV if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') { // not allowed any more to prevent people // mounting this root directly. // Users need to mount remote.php/webdav instead. header('HTTP/1.1 405 Method Not Allowed'); header('Status: 405 Method Not Allowed'); return; } // Someone is logged in if (OC_User::isLoggedIn()) { OC_App::loadApps(); OC_User::setupBackends(); OC_Util::setupFS(); // FIXME // Redirect to default application OC_Util::redirectToDefaultPage(); } else { // Not handled and not logged in header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm')); } } /** * Check login: apache auth, auth token, basic auth * * @param OCP\IRequest $request * @return boolean */ static function handleLogin(OCP\IRequest $request) { $userSession = self::$server->getUserSession(); if (OC_User::handleApacheAuth()) { return true; } if ($userSession->tryTokenLogin($request)) { return true; } if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) { return true; } return false; } protected static function handleAuthHeaders() { //copy http auth headers for apache+php-fcgid work around if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; } // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. $vars = array( 'HTTP_AUTHORIZATION', // apache+php-cgi work around 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative ); foreach ($vars as $var) { if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { list($name, $password) = explode(':', base64_decode($matches[1]), 2); $_SERVER['PHP_AUTH_USER'] = $name; $_SERVER['PHP_AUTH_PW'] = $password; break; } } } } OC::init(); 7' href='#n847'>847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
/*
 * Copyright 2000-2016 Vaadin Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.vaadin.ui;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.vaadin.data.Binder;
import com.vaadin.data.HasHierarchicalDataProvider;
import com.vaadin.data.SelectionModel;
import com.vaadin.data.TreeData;
import com.vaadin.data.provider.DataGenerator;
import com.vaadin.data.provider.DataProvider;
import com.vaadin.data.provider.HierarchicalDataProvider;
import com.vaadin.data.provider.HierarchicalQuery;
import com.vaadin.data.provider.TreeDataProvider;
import com.vaadin.event.CollapseEvent;
import com.vaadin.event.CollapseEvent.CollapseListener;
import com.vaadin.event.ConnectorEvent;
import com.vaadin.event.ContextClickEvent;
import com.vaadin.event.ExpandEvent;
import com.vaadin.event.ExpandEvent.ExpandListener;
import com.vaadin.event.SerializableEventListener;
import com.vaadin.event.selection.SelectionListener;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.Resource;
import com.vaadin.shared.EventId;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.Registration;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.shared.ui.grid.HeightMode;
import com.vaadin.shared.ui.grid.ScrollDestination;
import com.vaadin.shared.ui.tree.TreeMultiSelectionModelState;
import com.vaadin.shared.ui.tree.TreeRendererState;
import com.vaadin.ui.Grid.SelectionMode;
import com.vaadin.ui.components.grid.DescriptionGenerator;
import com.vaadin.ui.components.grid.MultiSelectionModelImpl;
import com.vaadin.ui.components.grid.NoSelectionModel;
import com.vaadin.ui.components.grid.SingleSelectionModelImpl;
import com.vaadin.ui.declarative.DesignAttributeHandler;
import com.vaadin.ui.declarative.DesignContext;
import com.vaadin.ui.renderers.AbstractRenderer;
import com.vaadin.util.ReflectTools;

import elemental.json.JsonObject;

/**
 * Tree component. A Tree can be used to select an item from a hierarchical set
 * of items.
 *
 * @author Vaadin Ltd
 * @since 8.1
 *
 * @param <T>
 *            the data type
 */
public class Tree<T> extends Composite
        implements HasHierarchicalDataProvider<T> {

    @Deprecated
    private static final Method ITEM_CLICK_METHOD = ReflectTools
            .findMethod(ItemClickListener.class, "itemClick", ItemClick.class);
    private Registration contextClickRegistration = null;

    /**
     * A listener for item click events.
     *
     * @param <T>
     *            the tree item type
     *
     * @see ItemClick
     * @see Registration
     * @since 8.1
     */
    @FunctionalInterface
    public interface ItemClickListener<T> extends SerializableEventListener {
        /**
         * Invoked when this listener receives a item click event from a Tree to
         * which it has been added.
         *
         * @param event
         *            the received event, not {@code null}
         */
        public void itemClick(Tree.ItemClick<T> event);
    }

    /**
     * Tree item click event.
     *
     * @param <T>
     *            the data type of tree
     * @since 8.1
     */
    public static class ItemClick<T> extends ConnectorEvent {

        private final T item;
        private final MouseEventDetails mouseEventDetails;

        /**
         * Constructs a new item click.
         *
         * @param source
         *            the tree component
         * @param item
         *            the clicked item
         * @param mouseEventDetails
         *            information about the original mouse event (mouse button
         *            clicked, coordinates if available etc.)
         */
        protected ItemClick(Tree<T> source, T item,
                MouseEventDetails mouseEventDetails) {
            super(source);
            this.item = item;
            this.mouseEventDetails = mouseEventDetails;
        }

        /**
         * Returns the clicked item.
         *
         * @return the clicked item
         */
        public T getItem() {
            return item;
        }

        @SuppressWarnings("unchecked")
        @Override
        public Tree<T> getSource() {
            return (Tree<T>) super.getSource();
        }

        /**
         * Returns the mouse event details.
         *
         * @return the mouse event details
         */
        public MouseEventDetails getMouseEventDetails() {
            return mouseEventDetails;
        }
    }

    /**
     * String renderer that handles icon resources and stores their identifiers
     * into data objects.
     *
     * @since 8.1
     */
    public final class TreeRenderer extends AbstractRenderer<T, String>
            implements DataGenerator<T> {

        /**
         * Constructs a new TreeRenderer.
         */
        protected TreeRenderer() {
            super(String.class);
        }

        private Map<T, String> resourceKeyMap = new HashMap<>();
        private int counter = 0;

        @Override
        public void generateData(T item, JsonObject jsonObject) {
            Resource resource = iconProvider.apply(item);
            if (resource == null) {
                destroyData(item);
                return;
            }

            if (!resourceKeyMap.containsKey(item)) {
                resourceKeyMap.put(item, "icon" + (counter++));
            }
            setResource(resourceKeyMap.get(item), resource);
            jsonObject.put("itemIcon", resourceKeyMap.get(item));
        }

        @Override
        public void destroyData(T item) {
            if (resourceKeyMap.containsKey(item)) {
                setResource(resourceKeyMap.get(item), null);
                resourceKeyMap.remove(item);
            }
        }

        @Override
        public void destroyAllData() {
            Set<T> keys = new HashSet<>(resourceKeyMap.keySet());
            for (T key : keys) {
                destroyData(key);
            }
        }

        @Override
        protected TreeRendererState getState() {
            return (TreeRendererState) super.getState();
        }

        @Override
        protected TreeRendererState getState(boolean markAsDirty) {
            return (TreeRendererState) super.getState(markAsDirty);
        }
    }

    /**
     * Custom MultiSelectionModel for Tree. TreeMultiSelectionModel does not
     * show selection column.
     *
     * @param <T>
     *            the tree item type
     *
     * @since 8.1
     */
    public static final class TreeMultiSelectionModel<T>
            extends MultiSelectionModelImpl<T> {

        @Override
        protected TreeMultiSelectionModelState getState() {
            return (TreeMultiSelectionModelState) super.getState();
        }

        @Override
        protected TreeMultiSelectionModelState getState(boolean markAsDirty) {
            return (TreeMultiSelectionModelState) super.getState(markAsDirty);
        }
    }

    private TreeGrid<T> treeGrid = new TreeGrid<>();
    private ItemCaptionGenerator<T> captionGenerator = String::valueOf;
    private IconGenerator<T> iconProvider = t -> null;
    private final TreeRenderer renderer;
    private boolean autoRecalculateWidth = true;

    /**
     * Constructs a new Tree Component.
     */
    public Tree() {
        setCompositionRoot(treeGrid);
        renderer = new TreeRenderer();
        treeGrid.getDataCommunicator().addDataGenerator(renderer);
        treeGrid.addColumn(i -> captionGenerator.apply(i), renderer)
                .setId("column");
        treeGrid.setHierarchyColumn("column");
        while (treeGrid.getHeaderRowCount() > 0) {
            treeGrid.removeHeaderRow(0);
        }
        treeGrid.setPrimaryStyleName("v-tree8");
        treeGrid.setRowHeight(28);

        setWidth("100%");
        treeGrid.setHeightUndefined();
        treeGrid.setHeightMode(HeightMode.UNDEFINED);

        treeGrid.addExpandListener(e -> {
            fireExpandEvent(e.getExpandedItem(), e.isUserOriginated());
            if (autoRecalculateWidth) {
                treeGrid.recalculateColumnWidths();
            }
        });
        treeGrid.addCollapseListener(e -> {
            fireCollapseEvent(e.getCollapsedItem(), e.isUserOriginated());
            if (autoRecalculateWidth) {
                treeGrid.recalculateColumnWidths();
            }
        });
        treeGrid.addItemClickListener(e -> fireEvent(
                new ItemClick<>(this, e.getItem(), e.getMouseEventDetails())));
    }

    /**
     * Constructs a new Tree Component with given caption.
     *
     * @param caption
     *            the caption for component
     */
    public Tree(String caption) {
        this();

        setCaption(caption);
    }

    /**
     * Constructs a new Tree Component with given caption and {@code TreeData}.
     *
     * @param caption
     *            the caption for component
     * @param treeData
     *            the tree data for component
     */
    public Tree(String caption, TreeData<T> treeData) {
        this(caption, new TreeDataProvider<>(treeData));
    }

    /**
     * Constructs a new Tree Component with given caption and
     * {@code HierarchicalDataProvider}.
     *
     * @param caption
     *            the caption for component
     * @param dataProvider
     *            the hierarchical data provider for component
     */
    public Tree(String caption, HierarchicalDataProvider<T, ?> dataProvider) {
        this(caption);

        treeGrid.setDataProvider(dataProvider);
    }

    /**
     * Constructs a new Tree Component with given
     * {@code HierarchicalDataProvider}.
     *
     * @param dataProvider
     *            the hierarchical data provider for component
     */
    public Tree(HierarchicalDataProvider<T, ?> dataProvider) {
        this(null, dataProvider);
    }

    @Override
    public HierarchicalDataProvider<T, ?> getDataProvider() {
        return treeGrid.getDataProvider();
    }

    @Override
    public void setDataProvider(DataProvider<T, ?> dataProvider) {
        treeGrid.setDataProvider(dataProvider);
    }

    /**
     * Adds an ExpandListener to this Tree.
     *
     * @see ExpandEvent
     *
     * @param listener
     *            the listener to add
     * @return a registration for the listener
     */
    public Registration addExpandListener(ExpandListener<T> listener) {
        return addListener(ExpandEvent.class, listener,
                ExpandListener.EXPAND_METHOD);
    }

    /**
     * Adds a CollapseListener to this Tree.
     *
     * @see CollapseEvent
     *
     * @param listener
     *            the listener to add
     * @return a registration for the listener
     */
    public Registration addCollapseListener(CollapseListener<T> listener) {
        return addListener(CollapseEvent.class, listener,
                CollapseListener.COLLAPSE_METHOD);
    }

    /**
     * Fires an expand event with given item.
     *
     * @param item
     *            the expanded item
     * @param userOriginated
     *            whether the expand was triggered by a user interaction or the
     *            server
     */
    protected void fireExpandEvent(T item, boolean userOriginated) {
        fireEvent(new ExpandEvent<>(this, item, userOriginated));
    }

    /**
     * Fires a collapse event with given item.
     *
     * @param item
     *            the collapsed item
     * @param userOriginated
     *            whether the collapse was triggered by a user interaction or
     *            the server
     */
    protected void fireCollapseEvent(T item, boolean userOriginated) {
        fireEvent(new CollapseEvent<>(this, item, userOriginated));
    }

    /**
     * Expands the given items.
     * <p>
     * If an item is currently expanded, does nothing. If an item does not have
     * any children, does nothing.
     *
     * @param items
     *            the items to expand
     */
    public void expand(T... items) {
        treeGrid.expand(items);
    }

    /**
     * Expands the given items.
     * <p>
     * If an item is currently expanded, does nothing. If an item does not have
     * any children, does nothing.
     *
     * @param items
     *            the items to expand
     */
    public void expand(Collection<T> items) {
        treeGrid.expand(items);
    }

    /**
     * Collapse the given items.
     * <p>
     * For items that are already collapsed, does nothing.
     *
     * @param items
     *            the collection of items to collapse
     */
    public void collapse(T... items) {
        treeGrid.collapse(items);
    }

    /**
     * Collapse the given items.
     * <p>
     * For items that are already collapsed, does nothing.
     *
     * @param items
     *            the collection of items to collapse
     */
    public void collapse(Collection<T> items) {
        treeGrid.collapse(items);
    }

    /**
     * Returns whether a given item is expanded or collapsed.
     *
     * @param item
     *            the item to check
     * @return true if the item is expanded, false if collapsed
     */
    public boolean isExpanded(T item) {
        return treeGrid.isExpanded(item);
    }

    /**
     * This method is a shorthand that delegates to the currently set selection
     * model.
     *
     * @see #getSelectionModel()
     *
     * @return set of selected items
     */
    public Set<T> getSelectedItems() {
        return treeGrid.getSelectedItems();
    }

    /**
     * This method is a shorthand that delegates to the currently set selection
     * model.
     *
     * @param item
     *            item to select
     *
     * @see SelectionModel#select(Object)
     * @see #getSelectionModel()
     */
    public void select(T item) {
        treeGrid.select(item);
    }

    /**
     * This method is a shorthand that delegates to the currently set selection
     * model.
     *
     * @param item
     *            item to deselect
     *
     * @see SelectionModel#deselect(Object)
     * @see #getSelectionModel()
     */
    public void deselect(T item) {
        treeGrid.deselect(item);
    }

    /**
     * Adds a selection listener to the current selection model.
     * <p>
     * <strong>NOTE:</strong> If selection mode is switched with
     * {@link #setSelectionMode(SelectionMode)}, then this listener is not
     * triggered anymore when selection changes!
     *
     * @param listener
     *            the listener to add
     * @return a registration handle to remove the listener
     *
     * @throws UnsupportedOperationException
     *             if selection has been disabled with
     *             {@link SelectionMode#NONE}
     */
    public Registration addSelectionListener(SelectionListener<T> listener) {
        return treeGrid.addSelectionListener(listener);
    }

    /**
     * Use this tree as a single select in {@link Binder}. Throws
     * {@link IllegalStateException} if the tree is not using
     * {@link SelectionMode#SINGLE}.
     *
     * @return the single select wrapper that can be used in binder
     */
    public SingleSelect<T> asSingleSelect() {
        return treeGrid.asSingleSelect();
    }

    /**
     * Returns the selection model for this Tree.
     *
     * @return the selection model, not <code>null</code>
     */
    public SelectionModel<T> getSelectionModel() {
        return treeGrid.getSelectionModel();
    }

    /**
     * Sets the item caption generator that is used to produce the strings shown
     * as the text for each item. By default, {@link String#valueOf(Object)} is
     * used.
     *
     * @param captionGenerator
     *            the item caption provider to use, not <code>null</code>
     */
    public void setItemCaptionGenerator(
            ItemCaptionGenerator<T> captionGenerator) {
        Objects.requireNonNull(captionGenerator,
                "Caption generator must not be null");
        this.captionGenerator = captionGenerator;
        treeGrid.getDataCommunicator().reset();
    }

    /**
     * Sets the item icon generator that is used to produce custom icons for
     * items. The generator can return <code>null</code> for items with no icon.
     *
     * @see IconGenerator
     *
     * @param iconGenerator
     *            the item icon generator to set, not <code>null</code>
     * @throws NullPointerException
     *             if {@code itemIconGenerator} is {@code null}
     */
    public void setItemIconGenerator(IconGenerator<T> iconGenerator) {
        Objects.requireNonNull(iconGenerator,
                "Item icon generator must not be null");
        this.iconProvider = iconGenerator;
        treeGrid.getDataCommunicator().reset();
    }

    /**
     * Sets the item collapse allowed provider for this Tree. The provider
     * should return {@code true} for any item that the user can collapse.
     * <p>
     * <strong>Note:</strong> This callback will be accessed often when sending
     * data to the client. The callback should not do any costly operations.
     *
     * @param provider
     *            the item collapse allowed provider, not {@code null}
     */
    public void setItemCollapseAllowedProvider(
            ItemCollapseAllowedProvider<T> provider) {
        treeGrid.setItemCollapseAllowedProvider(provider);
    }

    /**
     * Sets the style generator that is used for generating class names for
     * items in this tree. Returning null from the generator results in no
     * custom style name being set.
     *
     * @see StyleGenerator
     *
     * @param styleGenerator
     *            the item style generator to set, not {@code null}
     * @throws NullPointerException
     *             if {@code styleGenerator} is {@code null}
     */
    public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
        treeGrid.setStyleGenerator(styleGenerator);
    }

    /**
     * Sets the description generator that is used for generating tooltip
     * descriptions for items.
     *
     * @since 8.2
     * @param descriptionGenerator
     *            the item description generator to set, or <code>null</code> to
     *            remove a previously set generator
     */
    public void setItemDescriptionGenerator(
            DescriptionGenerator<T> descriptionGenerator) {
        treeGrid.setDescriptionGenerator(descriptionGenerator);
    }

    /**
     * Gets the item caption generator.
     *
     * @return the item caption generator
     */
    public ItemCaptionGenerator<T> getItemCaptionGenerator() {
        return captionGenerator;
    }

    /**
     * Gets the item icon generator.
     *
     * @see IconGenerator
     *
     * @return the item icon generator
     */
    public IconGenerator<T> getItemIconGenerator() {
        return iconProvider;
    }

    /**
     * Gets the item collapse allowed provider.
     *
     * @return the item collapse allowed provider
     */
    public ItemCollapseAllowedProvider<T> getItemCollapseAllowedProvider() {
        return treeGrid.getItemCollapseAllowedProvider();
    }

    /**
     * Gets the style generator.
     *
     * @see StyleGenerator
     *
     * @return the item style generator
     */
    public StyleGenerator<T> getStyleGenerator() {
        return treeGrid.getStyleGenerator();
    }

    /**
     * Gets the item description generator.
     *
     * @since 8.2
     * @return the item description generator
     */
    public DescriptionGenerator<T> getItemDescriptionGenerator() {
        return treeGrid.getDescriptionGenerator();
    }

    /**
     * Adds an item click listener. The listener is called when an item of this
     * {@code Tree} is clicked.
     *
     * @param listener
     *            the item click listener, not null
     * @return a registration for the listener
     * @see #addContextClickListener
     */
    public Registration addItemClickListener(ItemClickListener<T> listener) {
        return addListener(ItemClick.class, listener, ITEM_CLICK_METHOD);
    }

    /**
     * Sets the tree's selection mode.
     * <p>
     * The built-in selection modes are:
     * <ul>
     * <li>{@link SelectionMode#SINGLE} <b>the default model</b></li>
     * <li>{@link SelectionMode#MULTI}</li>
     * <li>{@link SelectionMode#NONE} preventing selection</li>
     * </ul>
     *
     * @param selectionMode
     *            the selection mode to switch to, not {@code null}
     * @return the used selection model
     *
     * @see SelectionMode
     */
    public SelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
        Objects.requireNonNull(selectionMode,
                "Can not set selection mode to null");
        switch (selectionMode) {
        case MULTI:
            TreeMultiSelectionModel<T> model = new TreeMultiSelectionModel<>();
            treeGrid.setSelectionModel(model);
            return model;
        default:
            return treeGrid.setSelectionMode(selectionMode);
        }
    }

    private SelectionMode getSelectionMode() {
        SelectionModel<T> selectionModel = getSelectionModel();
        SelectionMode mode = null;
        if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
            mode = SelectionMode.SINGLE;
        } else if (selectionModel.getClass()
                .equals(TreeMultiSelectionModel.class)) {
            mode = SelectionMode.MULTI;
        } else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
            mode = SelectionMode.NONE;
        }
        return mode;
    }

    @Override
    public void setCaption(String caption) {
        treeGrid.setCaption(caption);
    }

    @Override
    public String getCaption() {
        return treeGrid.getCaption();
    }

    @Override
    public void setIcon(Resource icon) {
        treeGrid.setIcon(icon);
    }

    @Override
    public Resource getIcon() {
        return treeGrid.getIcon();
    }

    @Override
    public String getStyleName() {
        return treeGrid.getStyleName();
    }

    @Override
    public void setStyleName(String style) {
        treeGrid.setStyleName(style);
    }

    @Override
    public void setStyleName(String style, boolean add) {
        treeGrid.setStyleName(style, add);
    }

    @Override
    public void addStyleName(String style) {
        treeGrid.addStyleName(style);
    }

    @Override
    public void removeStyleName(String style) {
        treeGrid.removeStyleName(style);
    }

    @Override
    public String getPrimaryStyleName() {
        return treeGrid.getPrimaryStyleName();
    }

    @Override
    public void setPrimaryStyleName(String style) {
        treeGrid.setPrimaryStyleName(style);
    }

    @Override
    public void setId(String id) {
        treeGrid.setId(id);
    }

    @Override
    public String getId() {
        return treeGrid.getId();
    }

    @Override
    public void setCaptionAsHtml(boolean captionAsHtml) {
        treeGrid.setCaptionAsHtml(captionAsHtml);
    }

    @Override
    public boolean isCaptionAsHtml() {
        return treeGrid.isCaptionAsHtml();
    }

    @Override
    public void setDescription(String description) {
        treeGrid.setDescription(description);
    }

    @Override
    public void setDescription(String description, ContentMode mode) {
        treeGrid.setDescription(description, mode);
    }

    @Override
    public ErrorMessage getErrorMessage() {
        return treeGrid.getErrorMessage();
    }

    @Override
    public ErrorMessage getComponentError() {
        return treeGrid.getComponentError();
    }

    @Override
    public void setComponentError(ErrorMessage componentError) {
        treeGrid.setComponentError(componentError);
    }

    /**
     * Sets the height of a row. If -1 (default), the row height is calculated
     * based on the theme for an empty row before the Tree is displayed.
     *
     * @param rowHeight
     *            The height of a row in pixels or -1 for automatic calculation
     */
    public void setRowHeight(double rowHeight) {
        treeGrid.setRowHeight(rowHeight);
    }

    /**
     * Gets the currently set content mode of the item captions of this Tree.
     *
     * @since 8.1.3
     * @see ContentMode
     * @return the content mode of the item captions of this Tree
     */
    public ContentMode getContentMode() {
        return renderer.getState(false).mode;
    }

    /**
     * Sets the content mode of the item caption.
     *
     * @see ContentMode
     * @param contentMode
     *            the content mode
     */
    public void setContentMode(ContentMode contentMode) {
        renderer.getState().mode = contentMode;
    }

    /**
     * Returns the current state of automatic width recalculation.
     *
     * @return {@code true} if enabled; {@code false} if disabled
     *
     * @since 8.1.1
     */
    public boolean isAutoRecalculateWidth() {
        return autoRecalculateWidth;
    }

    /**
     * Sets the automatic width recalculation on or off. This feature is on by
     * default.
     *
     * @param autoRecalculateWidth
     *            {@code true} to enable recalculation; {@code false} to turn it
     *            off
     *
     * @since 8.1.1
     */
    public void setAutoRecalculateWidth(boolean autoRecalculateWidth) {
        this.autoRecalculateWidth = autoRecalculateWidth;

        treeGrid.getColumns().get(0)
                .setMinimumWidthFromContent(autoRecalculateWidth);
        treeGrid.recalculateColumnWidths();
    }

    /**
     * Adds a context click listener that gets notified when a context click
     * happens.
     *
     * @param listener
     *            the context click listener to add, not null actual event
     *            provided to the listener is {@link TreeContextClickEvent}
     * @return a registration object for removing the listener
     *
     * @since 8.1
     * @see #addItemClickListener
     * @see Registration
     */
    @Override
    public Registration addContextClickListener(
            ContextClickEvent.ContextClickListener listener) {
        Registration registration = addListener(EventId.CONTEXT_CLICK,
                ContextClickEvent.class, listener,
                ContextClickEvent.CONTEXT_CLICK_METHOD);
        setupContextClickListener();
        return () -> {
            registration.remove();
            setupContextClickListener();
        };
    }

    @Override
    @Deprecated
    public void removeContextClickListener(
            ContextClickEvent.ContextClickListener listener) {
        super.removeContextClickListener(listener);
        setupContextClickListener();
    }

    @Override
    public void writeDesign(Element design, DesignContext designContext) {
        super.writeDesign(design, designContext);
        Attributes attrs = design.attributes();

        SelectionMode mode = getSelectionMode();
        if (mode != null) {
            DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
                    SelectionMode.SINGLE, SelectionMode.class, designContext);
        }
        DesignAttributeHandler.writeAttribute("content-mode", attrs,
                getContentMode(), ContentMode.TEXT, ContentMode.class,
                designContext);

        if (designContext.shouldWriteData(this)) {
            writeItems(design, designContext);
        }
    }

    private void writeItems(Element design, DesignContext designContext) {
        getDataProvider().fetch(new HierarchicalQuery<>(null, null))
                .forEach(item -> writeItem(design, designContext, item, null));
    }

    private void writeItem(Element design, DesignContext designContext, T item,
            T parent) {

        Element itemElement = design.appendElement("node");
        itemElement.attr("item", serializeDeclarativeRepresentation(item));

        if (parent != null) {
            itemElement.attr("parent",
                    serializeDeclarativeRepresentation(parent));
        }

        if (getSelectionModel().isSelected(item)) {
            itemElement.attr("selected", "");
        }

        Resource icon = getItemIconGenerator().apply(item);
        DesignAttributeHandler.writeAttribute("icon", itemElement.attributes(),
                icon, null, Resource.class, designContext);

        String text = getItemCaptionGenerator().apply(item);
        itemElement.html(
                Optional.ofNullable(text).map(Object::toString).orElse(""));

        getDataProvider().fetch(new HierarchicalQuery<>(null, item)).forEach(
                childItem -> writeItem(design, designContext, childItem, item));
    }

    @Override
    public void readDesign(Element design, DesignContext designContext) {
        super.readDesign(design, designContext);
        Attributes attrs = design.attributes();
        if (attrs.hasKey("selection-mode")) {
            setSelectionMode(DesignAttributeHandler.readAttribute(
                    "selection-mode", attrs, SelectionMode.class));
        }
        if (attrs.hasKey("content-mode")) {
            setContentMode(DesignAttributeHandler.readAttribute("content-mode",
                    attrs, ContentMode.class));
        }
        readItems(design.children());
    }

    private void readItems(Elements bodyItems) {
        if (bodyItems.isEmpty()) {
            return;
        }

        DeclarativeValueProvider<T> valueProvider = new DeclarativeValueProvider<>();
        setItemCaptionGenerator(item -> valueProvider.apply(item));

        DeclarativeIconGenerator<T> iconGenerator = new DeclarativeIconGenerator<>(
                item -> null);
        setItemIconGenerator(iconGenerator);

        getSelectionModel().deselectAll();
        List<T> selectedItems = new ArrayList<>();
        TreeData<T> data = new TreeData<T>();

        for (Element row : bodyItems) {
            T item = deserializeDeclarativeRepresentation(row.attr("item"));
            T parent = null;
            if (row.hasAttr("parent")) {
                parent = deserializeDeclarativeRepresentation(
                        row.attr("parent"));
            }
            data.addItem(parent, item);
            if (row.hasAttr("selected")) {
                selectedItems.add(item);
            }

            valueProvider.addValue(item, row.html());
            iconGenerator.setIcon(item, DesignAttributeHandler
                    .readAttribute("icon", row.attributes(), Resource.class));
        }

        setDataProvider(new TreeDataProvider<>(data));
        selectedItems.forEach(getSelectionModel()::select);
    }

    /**
     * Deserializes a string to a data item. Used when reading from the
     * declarative format of this Tree.
     * <p>
     * Default implementation is able to handle only {@link String} as an item
     * type. There will be a {@link ClassCastException} if {@code T } is not a
     * {@link String}.
     *
     * @since 8.1.3
     *
     * @see #serializeDeclarativeRepresentation(Object)
     *
     * @param item
     *            string to deserialize
     * @throws ClassCastException
     *             if type {@code T} is not a {@link String}
     * @return deserialized item
     */
    @SuppressWarnings("unchecked")
    protected T deserializeDeclarativeRepresentation(String item) {
        if (item == null) {
            return (T) new String(UUID.randomUUID().toString());
        }
        return (T) new String(item);
    }

    /**
     * Serializes an {@code item} to a string. Used when saving this Tree to its
     * declarative format.
     * <p>
     * Default implementation delegates a call to {@code item.toString()}.
     *
     * @since 8.1.3
     *
     * @see #deserializeDeclarativeRepresentation(String)
     *
     * @param item
     *            a data item
     * @return string representation of the {@code item}.
     */
    protected String serializeDeclarativeRepresentation(T item) {
        return item.toString();
    }

    private void setupContextClickListener() {
        if (hasListeners(ContextClickEvent.class)) {
            if (contextClickRegistration == null) {
                contextClickRegistration = treeGrid
                        .addContextClickListener(event -> {
                            T item = null;
                            if (event instanceof Grid.GridContextClickEvent) {
                                item = ((Grid.GridContextClickEvent<T>) event)
                                        .getItem();
                            }
                            fireEvent(new TreeContextClickEvent<>(this,
                                    event.getMouseEventDetails(), item));
                        });
            }
        } else if (contextClickRegistration != null) {
            contextClickRegistration.remove();
            contextClickRegistration = null;
        }
    }

    /**
     * ContextClickEvent for the Tree Component.
     * <p>
     * Usage:
     *
     * <pre>
     * tree.addContextClickListener(event -&gt; Notification.show(
     *         ((TreeContextClickEvent&lt;Person&gt;) event).getItem() + " Clicked"));
     * </pre>
     *
     * @param <T>
     *            the tree bean type
     * @since 8.1
     */
    public static class TreeContextClickEvent<T> extends ContextClickEvent {

        private final T item;

        /**
         * Creates a new context click event.
         *
         * @param source
         *            the tree where the context click occurred
         * @param mouseEventDetails
         *            details about mouse position
         * @param item
         *            the item which was clicked or {@code null} if the click
         *            happened outside any item
         */
        public TreeContextClickEvent(Tree<T> source,
                MouseEventDetails mouseEventDetails, T item) {
            super(source, mouseEventDetails);
            this.item = item;
        }

        /**
         * Returns the item of context clicked row.
         *
         * @return clicked item; {@code null} the click happened outside any
         *         item
         */
        public T getItem() {
            return item;
        }

        @Override
        public Tree<T> getComponent() {
            return (Tree<T>) super.getComponent();
        }
    }

    /**
     * Scrolls to a certain item, using {@link ScrollDestination#ANY}.
     * <p>
     * If the item has an open details row, its size will also be taken into
     * account.
     *
     * @param row
     *            zero based index of the item to scroll to in the current view.
     * @throws IllegalArgumentException
     *             if the provided row is outside the item range
     * @since 8.2
     */
    public void scrollTo(int row) throws IllegalArgumentException {
        treeGrid.scrollTo(row, ScrollDestination.ANY);
    }

    /**
     * Scrolls to a certain item, using user-specified scroll destination.
     * <p>
     * If the item has an open details row, its size will also be taken into
     * account.
     *
     * @param row
     *            zero based index of the item to scroll to in the current view.
     * @param destination
     *            value specifying desired position of scrolled-to row, not
     *            {@code null}
     * @throws IllegalArgumentException
     *             if the provided row is outside the item range
     * @since 8.2
     */
    public void scrollTo(int row, ScrollDestination destination) {
        treeGrid.scrollTo(row, destination);
    }

    /**
     * Scrolls to the beginning of the first data row.
     *
     * @since 8.2
     */
    public void scrollToStart() {
        treeGrid.scrollToStart();
    }

    /**
     * Scrolls to the end of the last data row.
     *
     * @since 8.2
     */
    public void scrollToEnd() {
        treeGrid.scrollToEnd();
    }

}