/** * @NoAdminRequired * @NoCSRFRequired * @PublicPage */ public function validateEmail() { $email = $this->request->getParam('email'); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { return new TemplateResponse('', 'error', array(array('error' => $this->l10n->t('Email address you entered is not valid'))), 'error'); return new TemplateResponse('', 'error', array('errors' => array(array('error' => $this->l10n->t('Email address you entered is not valid'), 'hint' => ''))), 'error'); } if ($this->pendingreg->find($email)) { return new TemplateResponse('', 'error', array('errors' => array(array('error' => $this->l10n->t('There is already a pending registration with this email'), 'hint' => ''))), 'error'); } if ($this->config->getUsersForUserValue('settings', 'email', $email)) { return new TemplateResponse('', 'error', array('errors' => array(array('error' => $this->l10n->t('There is an existing user with this email'), 'hint' => ''))), 'error'); } // FEATURE: allow only from specific email domain $token = $this->pendingreg->save($email); //TODO: check for error $link = $this->urlgenerator->linkToRoute('registration.register.verifyToken', array('token' => $token)); $link = $this->urlgenerator->getAbsoluteURL($link); $from = Util::getDefaultEmailAddress('register'); $res = new TemplateResponse('registration', 'email', array('link' => $link), 'blank'); $msg = $res->render(); try { $this->mail->sendMail($email, 'ownCloud User', $this->l10n->t('Verify your ownCloud registration request'), $msg, $from, 'ownCloud'); } catch (\Exception $e) { \OC_Template::printErrorPage('A problem occurs during sending the e-mail please contact your administrator.'); return; } return new TemplateResponse('registration', 'message', array('msg' => $this->l10n->t('Verification email successfully sent.')), 'guest'); }
/** * insert the @input values when they do not exist yet * @param string $table name * @param array $input key->value pairs * @return int count of inserted rows */ public function insertIfNotExist($table, $input) { $query = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($input)) . '`) SELECT ' . str_repeat('?,', count($input) - 1) . '? ' . 'FROM `' . $table . '` WHERE '; $inserts = array_values($input); foreach ($input as $key => $value) { $query .= '`' . $key . '`'; if (is_null($value)) { $query .= ' IS NULL AND '; } else { $inserts[] = $value; $query .= ' = ? AND '; } } $query = substr($query, 0, strlen($query) - 5); $query .= ' HAVING COUNT(*) = 0'; try { return $this->conn->executeUpdate($query, $inserts); } catch (\Doctrine\DBAL\DBALException $e) { $entry = 'DB Error: "' . $e->getMessage() . '"<br />'; $entry .= 'Offending command was: ' . $query . '<br />'; \OC_Log::write('core', $entry, \OC_Log::FATAL); error_log('DB error: ' . $entry); \OC_Template::printErrorPage($entry); } }
public static function sendEmail($args) { $isEncrypted = OC_App::isEnabled('files_encryption'); if (!$isEncrypted || isset($_POST['continue'])) { $continue = true; } else { $continue = false; } if (OC_User::userExists($_POST['user']) && $continue) { $token = hash('sha256', OC_Util::generate_random_bytes(30) . OC_Config::getValue('passwordsalt', '')); OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', hash('sha256', $token)); // Hash the token again to prevent timing attacks $email = OC_Preferences::getValue($_POST['user'], 'settings', 'email', ''); if (!empty($email)) { $link = OC_Helper::linkToRoute('core_lostpassword_reset', array('user' => $_POST['user'], 'token' => $token)); $link = OC_Helper::makeURLAbsolute($link); $tmpl = new OC_Template('core/lostpassword', 'email'); $tmpl->assign('link', $link, false); $msg = $tmpl->fetchPage(); $l = OC_L10N::get('core'); $from = OCP\Util::getDefaultEmailAddress('lostpassword-noreply'); try { OC_Mail::send($email, $_POST['user'], $l->t('ownCloud password reset'), $msg, $from, 'ownCloud'); } catch (Exception $e) { OC_Template::printErrorPage('A problem occurs during sending the e-mail please contact your administrator.'); } self::displayLostPasswordPage(false, true); } else { self::displayLostPasswordPage(true, false); } } else { self::displayLostPasswordPage(true, false); } }
public function insertIfNotExist($table, $input) { // NOTE: For SQLite we have to use this clumsy approach // otherwise all fieldnames used must have a unique key. $query = 'SELECT COUNT(*) FROM `' . $table . '` WHERE '; $inserts = array(); foreach ($input as $key => $value) { $query .= '`' . $key . '`'; if (is_null($value)) { $query .= ' IS NULL AND '; } else { $inserts[] = $value; $query .= ' = ? AND '; } } $query = substr($query, 0, strlen($query) - 5); try { $stmt = $this->conn->prepare($query); $result = $stmt->execute($inserts); } catch (\Doctrine\DBAL\DBALException $e) { $entry = 'DB Error: "' . $e->getMessage() . '"<br />'; $entry .= 'Offending command was: ' . $query . '<br />'; \OC_Log::write('core', $entry, \OC_Log::FATAL); error_log('DB error: ' . $entry); \OC_Template::printErrorPage($entry); } if ($stmt->fetchColumn() === '0') { $query = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($input)) . '`) VALUES(' . str_repeat('?,', count($input) - 1) . '? ' . ')'; } else { return 0; //no rows updated } try { $statement = $this->conn->prepare($query); $result = $statement->execute(array_values($input)); } catch (\Doctrine\DBAL\DBALException $e) { $entry = 'DB Error: "' . $e->getMessage() . '"<br />'; $entry .= 'Offending command was: ' . $query . '<br />'; \OC_Log::write('core', $entry, \OC_Log::FATAL); error_log('DB error: ' . $entry); \OC_Template::printErrorPage($entry); } return $result; }
/** * @param Exception $e */ function handleException(Exception $e) { $request = \OC::$server->getRequest(); // in case the request content type is text/xml - we assume it's a WebDAV request $isXmlContentType = strpos($request->getHeader('Content-Type'), 'text/xml'); if ($isXmlContentType === 0) { // fire up a simple server to properly process the exception $server = new Server(); if (!$e instanceof RemoteException) { // we shall not log on RemoteException $server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->getLogger())); } $server->on('beforeMethod', function () use($e) { if ($e instanceof RemoteException) { switch ($e->getCode()) { case OC_Response::STATUS_SERVICE_UNAVAILABLE: throw new ServiceUnavailable($e->getMessage()); case OC_Response::STATUS_NOT_FOUND: throw new \Sabre\DAV\Exception\NotFound($e->getMessage()); } } $class = get_class($e); $msg = $e->getMessage(); throw new ServiceUnavailable("{$class}: {$msg}"); }); $server->exec(); } else { $statusCode = OC_Response::STATUS_INTERNAL_SERVER_ERROR; if ($e instanceof \OC\ServiceUnavailableException) { $statusCode = OC_Response::STATUS_SERVICE_UNAVAILABLE; } if ($e instanceof RemoteException) { // we shall not log on RemoteException OC_Response::setStatus($e->getCode()); OC_Template::printErrorPage($e->getMessage()); } else { \OCP\Util::writeLog('remote', $e->getMessage(), \OCP\Util::FATAL); OC_Response::setStatus($statusCode); OC_Template::printExceptionErrorPage($e); } } }
/** * connects to the database * @return boolean|null true if connection can be established or false on error * * Connects to the database as specified in config.php */ public static function connect() { if (self::$connection) { return true; } $type = OC_Config::getValue('dbtype', 'sqlite'); $factory = new \OC\DB\ConnectionFactory(); if (!$factory->isValidType($type)) { return false; } $connectionParams = array('user' => OC_Config::getValue('dbuser', ''), 'password' => OC_Config::getValue('dbpassword', '')); $name = OC_Config::getValue('dbname', 'owncloud'); if ($factory->normalizeType($type) === 'sqlite3') { $datadir = OC_Config::getValue("datadirectory", OC::$SERVERROOT . '/data'); $connectionParams['path'] = $datadir . '/' . $name . '.db'; } else { $host = OC_Config::getValue('dbhost', ''); if (strpos($host, ':')) { // Host variable may carry a port or socket. list($host, $portOrSocket) = explode(':', $host, 2); if (ctype_digit($portOrSocket)) { $connectionParams['port'] = $portOrSocket; } else { $connectionParams['unix_socket'] = $portOrSocket; } } $connectionParams['host'] = $host; $connectionParams['dbname'] = $name; } $connectionParams['tablePrefix'] = OC_Config::getValue('dbtableprefix', 'oc_'); try { self::$connection = $factory->getConnection($type, $connectionParams); } catch (\Doctrine\DBAL\DBALException $e) { OC_Log::write('core', $e->getMessage(), OC_Log::FATAL); OC_User::setUserId(null); // send http status 503 header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); OC_Template::printErrorPage('Failed to connect to database'); die; } return true; }
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', OC::$SERVERROOT . '/core', OC::$SERVERROOT . '/settings', OC::$SERVERROOT . '/ocs', OC::$SERVERROOT . '/ocs-provider', OC::$SERVERROOT . '/3rdparty']); spl_autoload_register(array(self::$loader, 'load')); $loaderEnd = microtime(true); self::$CLI = php_sapi_name() == 'cli'; try { self::initPaths(); // setup 3rdparty autoloader $vendorAutoLoad = OC::$THIRDPARTYROOT . '/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) { OC_Response::setStatus(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; } foreach (OC::$APPSROOTS as $appRoot) { self::$loader->addValidRoot($appRoot['path']); } // setup the basic server self::$server = new \OC\Server(\OC::$WEBROOT); \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 anyways //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')) { $logger = \OC::$server->getLogger(); OC\Log\ErrorHandler::setLogger($logger); if (\OC::$server->getConfig()->getSystemValue('debug', false)) { OC\Log\ErrorHandler::register(true); set_exception_handler(array('OC_Template', 'printExceptionErrorPage')); } else { OC\Log\ErrorHandler::register(); } } // 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::initTemplateEngine(); self::checkConfig(); self::checkInstalled(); OC_Response::addSecurityHeaders(); if (self::$server->getRequest()->getServerProtocol() === 'https') { ini_set('session.cookie_secure', true); } 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()); //setup extra user backends if (!self::checkUpgrade(false)) { OC_User::setupBackends(); } self::registerCacheHooks(); self::registerFilesystemHooks(); if (\OC::$server->getSystemConfig()->getValue('enable_previews', true)) { self::registerPreviewHooks(); } self::registerShareHooks(); self::registerLogRotate(); self::registerLocalAddressBook(); self::registerEncryptionWrapper(); self::registerEncryptionHooks(); //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')); if ($systemConfig->getValue('installed', false) && !self::checkUpgrade(false)) { if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { OC_Util::addScript('backgroundjobs'); } } // 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 && 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'); $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); $tmpl->assign('domain', $request->server['SERVER_NAME']); $tmpl->printPage(); exit; } \OC::$server->getEventLogger()->end('boot'); }
private function tryFixSubstringLastArgumentDataForMSSQL($input) { $query = $this->statement->getWrappedStatement()->queryString; $pos = stripos($query, 'SUBSTRING'); if ($pos === false) { return $input; } try { $newQuery = ''; $cArg = 0; $inSubstring = false; $queryLength = strlen($query); // Create new query for ($i = 0; $i < $queryLength; $i++) { if ($inSubstring == false) { // Defines when we should start inserting values if (substr($query, $i, 9) == 'SUBSTRING') { $inSubstring = true; } } else { // Defines when we should stop inserting values if (substr($query, $i, 1) == ')') { $inSubstring = false; } } if (substr($query, $i, 1) == '?') { // We found a question mark if ($inSubstring) { $newQuery .= $input[$cArg]; // // Remove from input array // array_splice($input, $cArg, 1); } else { $newQuery .= substr($query, $i, 1); $cArg++; } } else { $newQuery .= substr($query, $i, 1); } } // The global data we need $name = OC_Config::getValue("dbname", "owncloud"); $host = OC_Config::getValue("dbhost", ""); $user = OC_Config::getValue("dbuser", ""); $pass = OC_Config::getValue("dbpassword", ""); if (strpos($host, ':')) { list($host, $port) = explode(':', $host, 2); } else { $port = false; } $opts = array(); if ($port) { $dsn = 'sqlsrv:Server=' . $host . ',' . $port . ';Database=' . $name; } else { $dsn = 'sqlsrv:Server=' . $host . ';Database=' . $name; } $PDO = new PDO($dsn, $user, $pass, $opts); $PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->statement = $PDO->prepare($newQuery); $this->lastArguments = $input; return $input; } catch (PDOException $e) { $entry = 'PDO DB Error: "' . $e->getMessage() . '"<br />'; $entry .= 'Offending command was: ' . $this->statement->queryString . '<br />'; $entry .= 'Input parameters: ' . print_r($input, true) . '<br />'; $entry .= 'Stack trace: ' . $e->getTraceAsString() . '<br />'; OC_Log::write('core', $entry, OC_Log::FATAL); OC_User::setUserId(null); // send http status 503 header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); OC_Template::printErrorPage('Failed to connect to database'); die($entry); } }
public static function init() { // register autoloader $loaderStart = microtime(true); require_once __DIR__ . '/autoloader.php'; self::$loader = new \OC\Autoloader(); spl_autoload_register(array(self::$loader, 'load')); $loaderEnd = microtime(true); self::initPaths(); // setup 3rdparty autoloader $vendorAutoLoad = OC::$THIRDPARTYROOT . '/3rdparty/autoload.php'; if (file_exists($vendorAutoLoad)) { require_once $vendorAutoLoad; } else { OC_Response::setStatus(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('Composer autoloader not found, unable to continue. Check the folder "3rdparty".'); exit(); } // setup the basic server self::$server = new \OC\Server(\OC::$WEBROOT); \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); \OC::$server->getEventLogger()->start('boot', 'Initialize'); // set some stuff //ob_start(); error_reporting(E_ALL | E_STRICT); if (defined('DEBUG') && DEBUG) { ini_set('display_errors', 1); } self::$CLI = (php_sapi_name() == 'cli'); date_default_timezone_set('UTC'); ini_set('arg_separator.output', '&'); //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 anyways //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::handleAuthHeaders(); self::registerAutoloaderCache(); // initialize intl fallback is necessary \Patchwork\Utf8\Bootup::initIntl(); OC_Util::isSetLocaleWorking(); if (!defined('PHPUNIT_RUN')) { OC\Log\ErrorHandler::setLogger(OC_Log::$object); if (defined('DEBUG') and DEBUG) { OC\Log\ErrorHandler::register(true); set_exception_handler(array('OC_Template', 'printExceptionErrorPage')); } else { OC\Log\ErrorHandler::register(); } } // 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::initTemplateEngine(); self::checkConfig(); self::checkInstalled(); self::checkSSL(); OC_Response::addSecurityHeaders(); $errors = OC_Util::checkServer(\OC::$server->getConfig()); if (count($errors) > 0) { if (self::$CLI) { foreach ($errors as $error) { echo $error['error'] . "\n"; echo $error['hint'] . "\n\n"; } } else { OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printGuestPage('', 'error', array('errors' => $errors)); } exit; } //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()); //setup extra user backends if (!self::checkUpgrade(false)) { OC_User::setupBackends(); } self::registerCacheHooks(); self::registerFilesystemHooks(); self::registerPreviewHooks(); self::registerShareHooks(); self::registerLogRotate(); self::registerLocalAddressBook(); //make sure temporary files are cleaned up $tmpManager = \OC::$server->getTempManager(); register_shutdown_function(array($tmpManager, 'clean')); if ($systemConfig->getValue('installed', false) && !self::checkUpgrade(false)) { if (\OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { OC_Util::addScript('backgroundjobs'); } } // 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; } $host = OC_Request::insecureServerHost(); // if the host passed in headers isn't trusted if (!OC::$CLI // overwritehost is always trusted && OC_Request::getOverwriteHost() === null && !OC_Request::isTrustedDomain($host) ) { header('HTTP/1.1 400 Bad Request'); header('Status: 400 Bad Request'); $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); $tmpl->assign('domain', $_SERVER['SERVER_NAME']); $tmpl->printPage(); exit(); } \OC::$server->getEventLogger()->end('boot'); }
public static function checkConfig() { $l = OC_L10N::get('lib'); // Create config in case it does not already exists $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 && \OCP\Util::needUpgrade()) { 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', array(\OC_Helper::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('<a href="'.\OC_Helper::linkToDocs('admin-dir_permissions').'" target="_blank">', '</a>')) ); } } }
* 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 <http://www.gnu.org/licenses/> * */ // Show warning if a PHP version below 5.4.0 is used, this has to happen here // because base.php will already use 5.4 syntax. if (version_compare(PHP_VERSION, '5.4.0') === -1) { echo 'This version of ownCloud requires at least PHP 5.4.0<br/>'; echo 'You are currently running ' . PHP_VERSION . '. Please update your PHP version.'; return; } try { require_once 'lib/base.php'; OC::handleRequest(); } catch (\OC\ServiceUnavailableException $ex) { \OCP\Util::logException('index', $ex); //show the user a detailed error page OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printExceptionErrorPage($ex); } catch (\OC\HintException $ex) { OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printErrorPage($ex->getMessage(), $ex->getHint()); } catch (Exception $ex) { \OCP\Util::logException('index', $ex); //show the user a detailed error page OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR); OC_Template::printExceptionErrorPage($ex); }
public static function checkConfig() { if (file_exists(OC::$SERVERROOT . "/config/config.php") and !is_writable(OC::$SERVERROOT . "/config/config.php")) { $defaults = new OC_Defaults(); if (self::$CLI) { echo "Can't write into config directory!\n"; echo "This can usually be fixed by giving the webserver write access to the config directory\n"; echo "\n"; echo "See " . \OC_Helper::linkToDocs('admin-dir_permissions') . "\n"; exit; } else { OC_Template::printErrorPage("Can't write into config directory!", 'This can usually be fixed by ' . '<a href="' . \OC_Helper::linkToDocs('admin-dir_permissions') . '" target="_blank">giving the webserver write access to the config directory</a>.'); } } }
/** * @brief Post installation checks */ public static function postSetupCheck($params) { // setup was successful -> webdav testing now $l = self::getTrans(); if (OC_Util::isWebDAVWorking()) { header("Location: " . OC::$WEBROOT . '/'); } else { $error = $l->t('Your web server is not yet properly setup to allow files synchronization because the WebDAV interface seems to be broken.'); $hint = $l->t('Please double check the <a href=\'%s\'>installation guides</a>.', \OC_Helper::linkToDocs('admin-install')); OC_Template::printErrorPage($error, $hint); exit; } }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $files ; separated list of files to download * @param boolean $onlyHeader ; boolean to only send header of the request */ public static function get($dir, $files, $onlyHeader = false) { $view = \OC\Files\Filesystem::getView(); $getType = self::FILE; $filename = $dir; try { if (is_array($files) && count($files) === 1) { $files = $files[0]; } if (!is_array($files)) { $filename = $dir . '/' . $files; if (!$view->is_dir($filename)) { self::getSingleFile($view, $dir, $files, $onlyHeader); return; } } $name = 'download'; if (is_array($files)) { $getType = self::ZIP_FILES; $basename = basename($dir); if ($basename) { $name = $basename; } $filename = $dir . '/' . $name; } else { $filename = $dir . '/' . $files; $getType = self::ZIP_DIR; // downloading root ? if ($files !== '') { $name = $files; } } $streamer = new Streamer(); OC_Util::obEnd(); self::lockFiles($view, $dir, $files); $streamer->sendHeaders($name); $executionTime = intval(OC::$server->getIniWrapper()->getNumeric('max_execution_time')); set_time_limit(0); if ($getType === self::ZIP_FILES) { foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $fileSize = \OC\Files\Filesystem::filesize($file); $fh = \OC\Files\Filesystem::fopen($file, 'r'); $streamer->addFileFromStream($fh, basename($file), $fileSize); fclose($fh); } elseif (\OC\Files\Filesystem::is_dir($file)) { $streamer->addDirRecursive($file); } } } elseif ($getType === self::ZIP_DIR) { $file = $dir . '/' . $files; $streamer->addDirRecursive($file); } $streamer->finalize(); set_time_limit($executionTime); self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); } catch (\OCP\Lock\LockedException $ex) { self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); OC::$server->getLogger()->logException($ex); $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint); } catch (\OCP\Files\ForbiddenException $ex) { self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); OC::$server->getLogger()->logException($ex); $l = \OC::$server->getL10N('core'); \OC_Template::printErrorPage($l->t('Can\'t read file'), $ex->getMessage()); } catch (\Exception $ex) { self::unlockAllTheFiles($dir, $files, $getType, $view, $filename); OC::$server->getLogger()->logException($ex); $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint); } }
* 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 <http://www.gnu.org/licenses/> * */ try { require_once 'lib/base.php'; if (\OCP\Util::needUpgrade()) { // since the behavior of apps or remotes are unpredictable during // an upgrade, return a 503 directly OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE); OC_Template::printErrorPage('Service unavailable'); exit; } OC::checkMaintenanceMode(); OC::checkSingleUserMode(true); $request = \OC::$server->getRequest(); $pathInfo = $request->getPathInfo(); if (!$pathInfo && $request->getParam('service', '') === '') { header('HTTP/1.0 404 Not Found'); exit; } elseif ($request->getParam('service', '')) { $service = $request->getParam('service', ''); } else { $pathInfo = trim($pathInfo, '/'); list($service) = explode('/', $pathInfo); }
/** * checks if the selected files are within the size constraint. If not, outputs an error page. * * @param dir $dir * @param files $files */ static function validateZipDownload($dir, $files) { if (!OC_Config::getValue('allowZipDownload', true)) { $l = OC_L10N::get('lib'); header("HTTP/1.0 409 Conflict"); OC_Template::printErrorPage($l->t('ZIP download is turned off.'), $l->t('Files need to be downloaded one by one.') . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>'); exit; } $zipLimit = OC_Config::getValue('maxZipInputSize', OC_Helper::computerFileSize('800 MB')); if ($zipLimit > 0) { $totalsize = 0; if (!is_array($files)) { $files = array($files); } foreach ($files as $file) { $path = $dir . '/' . $file; if (\OC\Files\Filesystem::is_dir($path)) { foreach (\OC\Files\Filesystem::getDirectoryContent($path) as $i) { $totalsize += $i['size']; } } else { $totalsize += \OC\Files\Filesystem::filesize($path); } } if ($totalsize > $zipLimit) { $l = OC_L10N::get('lib'); header("HTTP/1.0 409 Conflict"); OC_Template::printErrorPage($l->t('Selected files too large to generate zip file.'), $l->t('Please download the files separately in smaller chunks or kindly ask your administrator.') . '<br/><a href="javascript:history.back()">' . $l->t('Back to Files') . '</a>'); exit; } } }
/** * @brief Handle the request */ public static function handleRequest() { // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if ownCloud is installed or in maintenance (update) mode if (!OC_Config::getValue('installed', false)) { require_once 'core/setup.php'; exit; } $host = OC_Request::insecureServerHost(); // if the host passed in headers isn't trusted if (!OC::$CLI && OC_Request::getOverwriteHost() === null && !OC_Request::isTrustedDomain($host)) { header('HTTP/1.1 400 Bad Request'); header('Status: 400 Bad Request'); OC_Template::printErrorPage('You are accessing the server from an untrusted domain.', 'Please contact your administrator. If you are an administrator of this instance, configure the "trusted_domain" setting in config/config.php. An example configuration is provided in config/config.sample.php.'); return; } $request = OC_Request::getPathInfo(); if (substr($request, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode(); self::checkUpgrade(); } // Test it the user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP OC::tryBasicAuthLogin(); if (!self::$CLI and (!isset($_GET["logout"]) or $_GET["logout"] !== 'true')) { try { if (!OC_Config::getValue('maintenance', false)) { OC_App::loadApps(); } self::checkSingleUserMode(); OC::getRouter()->match(OC_Request::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; } } $app = OC::$REQUESTEDAPP; $file = OC::$REQUESTEDFILE; $param = array('app' => $app, 'file' => $file); // Handle app css files if (substr($file, -3) == 'css') { self::loadCSSFile($param); return; } // Handle redirect URL for logged in users if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) { $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url'])); // Deny the redirect if the URL contains a @ // This prevents unvalidated redirects like ?redirect_url=:user@domain.com if (strpos($location, '@') === false) { header('Location: ' . $location); 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(); if (isset($_GET["logout"]) and $_GET["logout"]) { if (isset($_COOKIE['oc_token'])) { OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']); } OC_User::logout(); header("Location: " . OC::$WEBROOT . '/'); } else { if (is_null($file)) { $param['file'] = 'index.php'; } $file_ext = substr($param['file'], -3); if ($file_ext != 'php' || !self::loadAppScriptFile($param)) { header('HTTP/1.0 404 Not Found'); } } return; } // Not handled and not logged in self::handleLogin(); }
public static function checkConfig() { $l = OC_L10N::get('lib'); if (file_exists(self::$configDir . "/config.php") and !is_writable(self::$configDir . "/config.php") ) { 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', array(\OC_Helper::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('<a href="'.\OC_Helper::linkToDocs('admin-dir_permissions').'" target="_blank">', '</a>')) ); } } }
/** * Handle the request */ public static function handleRequest() { $l = \OC_L10N::get('lib'); // load all the classpaths from the enabled apps so they are available // in the routing files of each app OC::loadAppClassPaths(); // Check if ownCloud is installed or in maintenance (update) mode if (!OC_Config::getValue('installed', false)) { $controller = new OC\Core\Setup\Controller(); $controller->run($_POST); exit; } $host = OC_Request::insecureServerHost(); // if the host passed in headers isn't trusted if (!OC::$CLI && OC_Request::getOverwriteHost() === null && !OC_Request::isTrustedDomain($host)) { header('HTTP/1.1 400 Bad Request'); header('Status: 400 Bad Request'); OC_Template::printErrorPage($l->t('You are accessing the server from an untrusted domain.'), $l->t('Please contact your administrator. If you are an administrator of this instance, configure the "trusted_domain" setting in config/config.php. An example configuration is provided in config/config.sample.php.')); return; } $request = OC_Request::getPathInfo(); if (substr($request, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode(); self::checkUpgrade(); } if (!OC_User::isLoggedIn()) { // Test it the user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP OC::tryBasicAuthLogin(); } if (!self::$CLI and (!isset($_GET["logout"]) or $_GET["logout"] !== 'true')) { try { if (!OC_Config::getValue('maintenance', false) && !\OCP\Util::needUpgrade()) { OC_App::loadApps(array('authentication')); OC_App::loadApps(array('filesystem', 'logging')); OC_App::loadApps(); } self::checkSingleUserMode(); OC::$server->getRouter()->match(OC_Request::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; } } // Load minimum set of apps if (!self::checkUpgrade(false)) { // For logged-in users: Load everything if (OC_User::isLoggedIn()) { OC_App::loadApps(); } else { // For guests: Load only authentication, filesystem and logging OC_App::loadApps(array('authentication')); OC_App::loadApps(array('filesystem', 'logging')); } } // Handle redirect URL for logged in users if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) { $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url'])); // Deny the redirect if the URL contains a @ // This prevents unvalidated redirects like ?redirect_url=:user@domain.com if (strpos($location, '@') === false) { header('Location: ' . $location); 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; } // Redirect to index if the logout link is accessed without valid session // this is needed to prevent "Token expired" messages while login if a session is expired // @see https://github.com/owncloud/core/pull/8443#issuecomment-42425583 if (isset($_GET['logout']) && !OC_User::isLoggedIn()) { header("Location: " . OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); return; } // Someone is logged in if (OC_User::isLoggedIn()) { OC_App::loadApps(); OC_User::setupBackends(); if (isset($_GET["logout"]) and $_GET["logout"]) { OC_JSON::callCheck(); if (isset($_COOKIE['oc_token'])) { OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']); } if (isset($_SERVER['PHP_AUTH_USER'])) { if (isset($_COOKIE['oc_ignore_php_auth_user'])) { // Ignore HTTP Authentication for 5 more mintues. setcookie('oc_ignore_php_auth_user', $_SERVER['PHP_AUTH_USER'], time() + 300, OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); } elseif ($_SERVER['PHP_AUTH_USER'] === self::$session->get('loginname')) { // Ignore HTTP Authentication to allow a different user to log in. setcookie('oc_ignore_php_auth_user', $_SERVER['PHP_AUTH_USER'], 0, OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); } } OC_User::logout(); // redirect to webroot and add slash if webroot is empty header("Location: " . OC::$WEBROOT . (empty(OC::$WEBROOT) ? '/' : '')); } else { // Redirect to default application OC_Util::redirectToDefaultPage(); } } else { // Not handled and not logged in self::handleLogin(); } }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $files ; separated list of files to download * @param boolean $onlyHeader ; boolean to only send header of the request */ public static function get($dir, $files, $onlyHeader = false) { $view = \OC\Files\Filesystem::getView(); if (is_array($files) && count($files) === 1) { $files = $files[0]; } if (is_array($files)) { $getType = self::ZIP_FILES; $basename = basename($dir); if ($basename) { $name = $basename; } else { $name = 'download'; } $filename = $dir . '/' . $name; } else { $filename = $dir . '/' . $files; if (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) { $getType = self::ZIP_DIR; // downloading root ? if ($files === '') { $name = 'download'; } else { $name = $files; } } else { $getType = self::FILE; $name = $files; } } if ($getType === self::FILE) { $streamer = false; } else { $streamer = new Streamer(); } OC_Util::obEnd(); try { if ($getType === self::FILE) { $view->lockFile($filename, ILockingProvider::LOCK_SHARED); } if ($streamer) { $streamer->sendHeaders($name); } elseif (\OC\Files\Filesystem::isReadable($filename)) { self::sendHeaders($filename, $name); } elseif (!\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->printPage(); exit; } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($onlyHeader) { return; } if ($streamer) { $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); if ($getType === self::ZIP_FILES) { foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $fileSize = \OC\Files\Filesystem::filesize($file); $fh = \OC\Files\Filesystem::fopen($file, 'r'); $streamer->addFileFromStream($fh, basename($file), $fileSize); fclose($fh); } elseif (\OC\Files\Filesystem::is_dir($file)) { $streamer->addDirRecursive($file); } } } elseif ($getType === self::ZIP_DIR) { $file = $dir . '/' . $files; $streamer->addDirRecursive($file); } $streamer->finalize(); set_time_limit($executionTime); } else { \OC\Files\Filesystem::readfile($filename); } if ($getType === self::FILE) { $view->unlockFile($filename, ILockingProvider::LOCK_SHARED); } } catch (\OCP\Lock\LockedException $ex) { $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint); } catch (\Exception $ex) { $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint); } }
/** * Ends dialog when session is in full web */ function denyOnWeb($respons) { \OC_Template::printErrorPage($this->getNiceMessage($respons)); $this->doesExit(); }
/** * @brief Insert a row if a matching row doesn't exists. * @param string $table. The table to insert into in the form '*PREFIX*tableName' * @param array $input. An array of fieldname/value pairs * @returns The return value from PDOStatementWrapper->execute() */ public static function insertIfNotExist($table, $input) { self::connect(); $prefix = OC_Config::getValue("dbtableprefix", "oc_"); $table = str_replace('*PREFIX*', $prefix, $table); if (is_null(self::$type)) { self::$type = OC_Config::getValue("dbtype", "sqlite"); } $type = self::$type; $query = ''; // differences in escaping of table names ('`' for mysql) and getting the current timestamp if ($type == 'sqlite' || $type == 'sqlite3') { // NOTE: For SQLite we have to use this clumsy approach // otherwise all fieldnames used must have a unique key. $query = 'SELECT * FROM "' . $table . '" WHERE '; foreach ($input as $key => $value) { $query .= $key . " = '" . $value . '\' AND '; } $query = substr($query, 0, strlen($query) - 5); try { $stmt = self::prepare($query); $result = $stmt->execute(); } catch (PDOException $e) { $entry = 'DB Error: "' . $e->getMessage() . '"<br />'; $entry .= 'Offending command was: ' . $query . '<br />'; OC_Log::write('core', $entry, OC_Log::FATAL); error_log('DB error: ' . $entry); OC_Template::printErrorPage($entry); } if ($result->numRows() == 0) { $query = 'INSERT INTO "' . $table . '" ("' . implode('","', array_keys($input)) . '") VALUES("' . implode('","', array_values($input)) . '")'; } else { return true; } } elseif ($type == 'pgsql' || $type == 'oci' || $type == 'mysql') { $query = 'INSERT INTO `' . $table . '` (' . implode(',', array_keys($input)) . ') SELECT \'' . implode('\',\'', array_values($input)) . '\' FROM ' . $table . ' WHERE '; foreach ($input as $key => $value) { $query .= $key . " = '" . $value . '\' AND '; } $query = substr($query, 0, strlen($query) - 5); $query .= ' HAVING COUNT(*) = 0'; } // TODO: oci should be use " (quote) instead of ` (backtick). //OC_Log::write('core', __METHOD__ . ', type: ' . $type . ', query: ' . $query, OC_Log::DEBUG); try { $result = self::prepare($query); } catch (PDOException $e) { $entry = 'DB Error: "' . $e->getMessage() . '"<br />'; $entry .= 'Offending command was: ' . $query . '<br />'; OC_Log::write('core', $entry, OC_Log::FATAL); error_log('DB error: ' . $entry); OC_Template::printErrorPage($entry); } return $result->execute(); }
/** * return the content of a file or return a zip file containing multiple files * * @param string $dir * @param string $files ; separated list of files to download * @param boolean $only_header ; boolean to only send header of the request */ public static function get($dir, $files, $only_header = false) { $view = \OC\Files\Filesystem::getView(); $xsendfile = false; if (\OC::$server->getLockingProvider() instanceof NoopLockingProvider) { if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) || isset($_SERVER['MOD_X_SENDFILE2_ENABLED']) || isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) { $xsendfile = true; } } if (is_array($files) && count($files) === 1) { $files = $files[0]; } if (is_array($files)) { $get_type = self::ZIP_FILES; $basename = basename($dir); if ($basename) { $name = $basename . '.zip'; } else { $name = 'download.zip'; } $filename = $dir . '/' . $name; } else { $filename = $dir . '/' . $files; if (\OC\Files\Filesystem::is_dir($dir . '/' . $files)) { $get_type = self::ZIP_DIR; // downloading root ? if ($files === '') { $name = 'download.zip'; } else { $name = $files . '.zip'; } } else { $get_type = self::FILE; $name = $files; } } if ($get_type === self::FILE) { $zip = false; if ($xsendfile && \OC::$server->getEncryptionManager()->isEnabled()) { $xsendfile = false; } } else { $zip = new ZipStreamer(false); } OC_Util::obEnd(); try { if ($get_type === self::FILE) { $view->lockFile($filename, ILockingProvider::LOCK_SHARED); } if ($zip or \OC\Files\Filesystem::isReadable($filename)) { self::sendHeaders($filename, $name, $zip); } elseif (!\OC\Files\Filesystem::file_exists($filename)) { header("HTTP/1.0 404 Not Found"); $tmpl = new OC_Template('', '404', 'guest'); $tmpl->printPage(); exit; } else { header("HTTP/1.0 403 Forbidden"); die('403 Forbidden'); } if ($only_header) { return; } if ($zip) { $executionTime = intval(ini_get('max_execution_time')); set_time_limit(0); if ($get_type === self::ZIP_FILES) { foreach ($files as $file) { $file = $dir . '/' . $file; if (\OC\Files\Filesystem::is_file($file)) { $fh = \OC\Files\Filesystem::fopen($file, 'r'); $zip->addFileFromStream($fh, basename($file)); fclose($fh); } elseif (\OC\Files\Filesystem::is_dir($file)) { self::zipAddDir($file, $zip); } } } elseif ($get_type === self::ZIP_DIR) { $file = $dir . '/' . $files; self::zipAddDir($file, $zip); } $zip->finalize(); set_time_limit($executionTime); } else { if ($xsendfile) { /** @var $storage \OC\Files\Storage\Storage */ list($storage) = $view->resolvePath($filename); if ($storage->isLocal()) { self::addSendfileHeader($filename); } else { \OC\Files\Filesystem::readfile($filename); } } else { \OC\Files\Filesystem::readfile($filename); } } if ($get_type === self::FILE) { $view->unlockFile($filename, ILockingProvider::LOCK_SHARED); } } catch (\OCP\Lock\LockedException $ex) { $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('File is currently busy, please try again later'), $hint); } catch (\Exception $ex) { $l = \OC::$server->getL10N('core'); $hint = method_exists($ex, 'getHint') ? $ex->getHint() : ''; \OC_Template::printErrorPage($l->t('Can\'t read file'), $hint); } }
/** * @brief connects to the database * @return bool true if connection can be established or false on error * * Connects to the database as specified in config.php */ public static function connect() { if (self::$connection) { return true; } // The global data we need $name = OC_Config::getValue("dbname", "owncloud"); $host = OC_Config::getValue("dbhost", ""); $user = OC_Config::getValue("dbuser", ""); $pass = OC_Config::getValue("dbpassword", ""); $type = OC_Config::getValue("dbtype", "sqlite"); if (strpos($host, ':')) { list($host, $port) = explode(':', $host, 2); } else { $port = false; } // do nothing if the connection already has been established if (!self::$connection) { $config = new \Doctrine\DBAL\Configuration(); $eventManager = new \Doctrine\Common\EventManager(); switch ($type) { case 'sqlite': case 'sqlite3': $datadir = OC_Config::getValue("datadirectory", OC::$SERVERROOT . '/data'); $connectionParams = array('user' => $user, 'password' => $pass, 'path' => $datadir . '/' . $name . '.db', 'driver' => 'pdo_sqlite'); $connectionParams['adapter'] = '\\OC\\DB\\AdapterSqlite'; $connectionParams['wrapperClass'] = 'OC\\DB\\Connection'; break; case 'mysql': $connectionParams = array('user' => $user, 'password' => $pass, 'host' => $host, 'port' => $port, 'dbname' => $name, 'charset' => 'UTF8', 'driver' => 'pdo_mysql'); $connectionParams['adapter'] = '\\OC\\DB\\Adapter'; $connectionParams['wrapperClass'] = 'OC\\DB\\Connection'; // Send "SET NAMES utf8". Only required on PHP 5.3 below 5.3.6. // See http://stackoverflow.com/questions/4361459/php-pdo-charset-set-names#4361485 $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit()); break; case 'pgsql': $connectionParams = array('user' => $user, 'password' => $pass, 'host' => $host, 'port' => $port, 'dbname' => $name, 'driver' => 'pdo_pgsql'); $connectionParams['adapter'] = '\\OC\\DB\\AdapterPgSql'; $connectionParams['wrapperClass'] = 'OC\\DB\\Connection'; break; case 'oci': $connectionParams = array('user' => $user, 'password' => $pass, 'host' => $host, 'dbname' => $name, 'charset' => 'AL32UTF8', 'driver' => 'oci8'); if (!empty($port)) { $connectionParams['port'] = $port; } $connectionParams['adapter'] = '\\OC\\DB\\AdapterOCI8'; $connectionParams['wrapperClass'] = 'OC\\DB\\OracleConnection'; $eventManager->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\OracleSessionInit()); break; case 'mssql': $connectionParams = array('user' => $user, 'password' => $pass, 'host' => $host, 'port' => $port, 'dbname' => $name, 'charset' => 'UTF8', 'driver' => 'pdo_sqlsrv'); $connectionParams['adapter'] = '\\OC\\DB\\AdapterSQLSrv'; $connectionParams['wrapperClass'] = 'OC\\DB\\Connection'; break; default: return false; } $connectionParams['tablePrefix'] = OC_Config::getValue('dbtableprefix', 'oc_'); try { self::$connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config, $eventManager); if ($type === 'sqlite' || $type === 'sqlite3') { // Sqlite doesn't handle query caching and schema changes // TODO: find a better way to handle this self::$connection->disableQueryStatementCaching(); } } catch (\Doctrine\DBAL\DBALException $e) { OC_Log::write('core', $e->getMessage(), OC_Log::FATAL); OC_User::setUserId(null); // send http status 503 header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); OC_Template::printErrorPage('Failed to connect to database'); die; } } return true; }