Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
lib/base.php 1 patch
Indentation   +1017 added lines, -1017 removed lines patch added patch discarded remove patch
@@ -73,1023 +73,1023 @@
 block discarded – undo
73 73
  * OC_autoload!
74 74
  */
75 75
 class OC {
76
-	/**
77
-	 * Associative array for autoloading. classname => filename
78
-	 */
79
-	public static $CLASSPATH = [];
80
-	/**
81
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
82
-	 */
83
-	public static $SERVERROOT = '';
84
-	/**
85
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
86
-	 */
87
-	private static $SUBURI = '';
88
-	/**
89
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
90
-	 */
91
-	public static $WEBROOT = '';
92
-	/**
93
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
94
-	 * web path in 'url'
95
-	 */
96
-	public static $APPSROOTS = [];
97
-
98
-	/**
99
-	 * @var string
100
-	 */
101
-	public static $configDir;
102
-
103
-	/**
104
-	 * requested app
105
-	 */
106
-	public static $REQUESTEDAPP = '';
107
-
108
-	/**
109
-	 * check if Nextcloud runs in cli mode
110
-	 */
111
-	public static $CLI = false;
112
-
113
-	/**
114
-	 * @var \OC\Autoloader $loader
115
-	 */
116
-	public static $loader = null;
117
-
118
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
119
-	public static $composerAutoloader = null;
120
-
121
-	/**
122
-	 * @var \OC\Server
123
-	 */
124
-	public static $server = null;
125
-
126
-	/**
127
-	 * @var \OC\Config
128
-	 */
129
-	private static $config = null;
130
-
131
-	/**
132
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
133
-	 * the app path list is empty or contains an invalid path
134
-	 */
135
-	public static function initPaths() {
136
-		if(defined('PHPUNIT_CONFIG_DIR')) {
137
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
138
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
139
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
140
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
141
-			self::$configDir = rtrim($dir, '/') . '/';
142
-		} else {
143
-			self::$configDir = OC::$SERVERROOT . '/config/';
144
-		}
145
-		self::$config = new \OC\Config(self::$configDir);
146
-
147
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
148
-		/**
149
-		 * FIXME: The following lines are required because we can't yet instantiate
150
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
151
-		 */
152
-		$params = [
153
-			'server' => [
154
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
155
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
156
-			],
157
-		];
158
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
159
-		$scriptName = $fakeRequest->getScriptName();
160
-		if (substr($scriptName, -1) == '/') {
161
-			$scriptName .= 'index.php';
162
-			//make sure suburi follows the same rules as scriptName
163
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
164
-				if (substr(OC::$SUBURI, -1) != '/') {
165
-					OC::$SUBURI = OC::$SUBURI . '/';
166
-				}
167
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
168
-			}
169
-		}
170
-
171
-
172
-		if (OC::$CLI) {
173
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
174
-		} else {
175
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
176
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
177
-
178
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
179
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
180
-				}
181
-			} else {
182
-				// The scriptName is not ending with OC::$SUBURI
183
-				// This most likely means that we are calling from CLI.
184
-				// However some cron jobs still need to generate
185
-				// a web URL, so we use overwritewebroot as a fallback.
186
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
187
-			}
188
-
189
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
190
-			// slash which is required by URL generation.
191
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
192
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
193
-				header('Location: '.\OC::$WEBROOT.'/');
194
-				exit();
195
-			}
196
-		}
197
-
198
-		// search the apps folder
199
-		$config_paths = self::$config->getValue('apps_paths', []);
200
-		if (!empty($config_paths)) {
201
-			foreach ($config_paths as $paths) {
202
-				if (isset($paths['url']) && isset($paths['path'])) {
203
-					$paths['url'] = rtrim($paths['url'], '/');
204
-					$paths['path'] = rtrim($paths['path'], '/');
205
-					OC::$APPSROOTS[] = $paths;
206
-				}
207
-			}
208
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
209
-			OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
210
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
211
-			OC::$APPSROOTS[] = [
212
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
213
-				'url' => '/apps',
214
-				'writable' => true
215
-			];
216
-		}
217
-
218
-		if (empty(OC::$APPSROOTS)) {
219
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
220
-				. ' or the folder above. You can also configure the location in the config.php file.');
221
-		}
222
-		$paths = [];
223
-		foreach (OC::$APPSROOTS as $path) {
224
-			$paths[] = $path['path'];
225
-			if (!is_dir($path['path'])) {
226
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
227
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
228
-					. ' config.php file.', $path['path']));
229
-			}
230
-		}
231
-
232
-		// set the right include path
233
-		set_include_path(
234
-			implode(PATH_SEPARATOR, $paths)
235
-		);
236
-	}
237
-
238
-	public static function checkConfig() {
239
-		$l = \OC::$server->getL10N('lib');
240
-
241
-		// Create config if it does not already exist
242
-		$configFilePath = self::$configDir .'/config.php';
243
-		if(!file_exists($configFilePath)) {
244
-			@touch($configFilePath);
245
-		}
246
-
247
-		// Check if config is writable
248
-		$configFileWritable = is_writable($configFilePath);
249
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
250
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
251
-
252
-			$urlGenerator = \OC::$server->getURLGenerator();
253
-
254
-			if (self::$CLI) {
255
-				echo $l->t('Cannot write into "config" directory!')."\n";
256
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
257
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
258
-				echo "\n";
259
-				echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
260
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
261
-				exit;
262
-			} else {
263
-				OC_Template::printErrorPage(
264
-					$l->t('Cannot write into "config" directory!'),
265
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
266
-					[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
267
-					. $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
268
-					[ $urlGenerator->linkToDocs('admin-config') ] ),
269
-					503
270
-				);
271
-			}
272
-		}
273
-	}
274
-
275
-	public static function checkInstalled() {
276
-		if (defined('OC_CONSOLE')) {
277
-			return;
278
-		}
279
-		// Redirect to installer if not installed
280
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
281
-			if (OC::$CLI) {
282
-				throw new Exception('Not installed');
283
-			} else {
284
-				$url = OC::$WEBROOT . '/index.php';
285
-				header('Location: ' . $url);
286
-			}
287
-			exit();
288
-		}
289
-	}
290
-
291
-	public static function checkMaintenanceMode() {
292
-		// Allow ajax update script to execute without being stopped
293
-		if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
294
-			// send http status 503
295
-			http_response_code(503);
296
-			header('Retry-After: 120');
297
-
298
-			// render error page
299
-			$template = new OC_Template('', 'update.user', 'guest');
300
-			OC_Util::addScript('dist/maintenance');
301
-			OC_Util::addStyle('core', 'guest');
302
-			$template->printPage();
303
-			die();
304
-		}
305
-	}
306
-
307
-	/**
308
-	 * Prints the upgrade page
309
-	 *
310
-	 * @param \OC\SystemConfig $systemConfig
311
-	 */
312
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
313
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
-		$tooBig = false;
315
-		if (!$disableWebUpdater) {
316
-			$apps = \OC::$server->getAppManager();
317
-			if ($apps->isInstalled('user_ldap')) {
318
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
-
320
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
321
-					->from('ldap_user_mapping')
322
-					->execute();
323
-				$row = $result->fetch();
324
-				$result->closeCursor();
325
-
326
-				$tooBig = ($row['user_count'] > 50);
327
-			}
328
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
329
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
-
331
-				$result = $qb->select($qb->func()->count('*', 'user_count'))
332
-					->from('user_saml_users')
333
-					->execute();
334
-				$row = $result->fetch();
335
-				$result->closeCursor();
336
-
337
-				$tooBig = ($row['user_count'] > 50);
338
-			}
339
-			if (!$tooBig) {
340
-				// count users
341
-				$stats = \OC::$server->getUserManager()->countUsers();
342
-				$totalUsers = array_sum($stats);
343
-				$tooBig = ($totalUsers > 50);
344
-			}
345
-		}
346
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
-
349
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
-			// send http status 503
351
-			http_response_code(503);
352
-			header('Retry-After: 120');
353
-
354
-			// render error page
355
-			$template = new OC_Template('', 'update.use-cli', 'guest');
356
-			$template->assign('productName', 'nextcloud'); // for now
357
-			$template->assign('version', OC_Util::getVersionString());
358
-			$template->assign('tooBig', $tooBig);
359
-
360
-			$template->printPage();
361
-			die();
362
-		}
363
-
364
-		// check whether this is a core update or apps update
365
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
366
-		$currentVersion = implode('.', \OCP\Util::getVersion());
367
-
368
-		// if not a core upgrade, then it's apps upgrade
369
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
370
-
371
-		$oldTheme = $systemConfig->getValue('theme');
372
-		$systemConfig->setValue('theme', '');
373
-		OC_Util::addScript('config'); // needed for web root
374
-		OC_Util::addScript('update');
375
-
376
-		/** @var \OC\App\AppManager $appManager */
377
-		$appManager = \OC::$server->getAppManager();
378
-
379
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
380
-		$tmpl->assign('version', OC_Util::getVersionString());
381
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
-
383
-		// get third party apps
384
-		$ocVersion = \OCP\Util::getVersion();
385
-		$ocVersion = implode('.', $ocVersion);
386
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
-		$incompatibleShippedApps = [];
388
-		foreach ($incompatibleApps as $appInfo) {
389
-			if ($appManager->isShipped($appInfo['id'])) {
390
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
-			}
392
-		}
393
-
394
-		if (!empty($incompatibleShippedApps)) {
395
-			$l = \OC::$server->getL10N('core');
396
-			$hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
-		}
399
-
400
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
-		$tmpl->assign('productName', 'Nextcloud'); // for now
403
-		$tmpl->assign('oldTheme', $oldTheme);
404
-		$tmpl->printPage();
405
-	}
406
-
407
-	public static function initSession() {
408
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
409
-			ini_set('session.cookie_secure', true);
410
-		}
411
-
412
-		// prevents javascript from accessing php session cookies
413
-		ini_set('session.cookie_httponly', 'true');
414
-
415
-		// set the cookie path to the Nextcloud directory
416
-		$cookie_path = OC::$WEBROOT ? : '/';
417
-		ini_set('session.cookie_path', $cookie_path);
418
-
419
-		// Let the session name be changed in the initSession Hook
420
-		$sessionName = OC_Util::getInstanceId();
421
-
422
-		try {
423
-			// Allow session apps to create a custom session object
424
-			$useCustomSession = false;
425
-			$session = self::$server->getSession();
426
-			OC_Hook::emit('OC', 'initSession', ['session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession]);
427
-			if (!$useCustomSession) {
428
-				// set the session name to the instance id - which is unique
429
-				$session = new \OC\Session\Internal($sessionName);
430
-			}
431
-
432
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
433
-			$session = $cryptoWrapper->wrapSession($session);
434
-			self::$server->setSession($session);
435
-
436
-			// if session can't be started break with http 500 error
437
-		} catch (Exception $e) {
438
-			\OC::$server->getLogger()->logException($e, ['app' => 'base']);
439
-			//show the user a detailed error page
440
-			OC_Template::printExceptionErrorPage($e, 500);
441
-			die();
442
-		}
443
-
444
-		$sessionLifeTime = self::getSessionLifeTime();
445
-
446
-		// session timeout
447
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
448
-			if (isset($_COOKIE[session_name()])) {
449
-				setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
450
-			}
451
-			\OC::$server->getUserSession()->logout();
452
-		}
453
-
454
-		$session->set('LAST_ACTIVITY', time());
455
-	}
456
-
457
-	/**
458
-	 * @return string
459
-	 */
460
-	private static function getSessionLifeTime() {
461
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
462
-	}
463
-
464
-	/**
465
-	 * Try to set some values to the required Nextcloud default
466
-	 */
467
-	public static function setRequiredIniValues() {
468
-		@ini_set('default_charset', 'UTF-8');
469
-		@ini_set('gd.jpeg_ignore_warning', '1');
470
-	}
471
-
472
-	/**
473
-	 * Send the same site cookies
474
-	 */
475
-	private static function sendSameSiteCookies() {
476
-		$cookieParams = session_get_cookie_params();
477
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
478
-		$policies = [
479
-			'lax',
480
-			'strict',
481
-		];
482
-
483
-		// Append __Host to the cookie if it meets the requirements
484
-		$cookiePrefix = '';
485
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486
-			$cookiePrefix = '__Host-';
487
-		}
488
-
489
-		foreach($policies as $policy) {
490
-			header(
491
-				sprintf(
492
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493
-					$cookiePrefix,
494
-					$policy,
495
-					$cookieParams['path'],
496
-					$policy
497
-				),
498
-				false
499
-			);
500
-		}
501
-	}
502
-
503
-	/**
504
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
505
-	 * be set in every request if cookies are sent to add a second level of
506
-	 * defense against CSRF.
507
-	 *
508
-	 * If the cookie is not sent this will set the cookie and reload the page.
509
-	 * We use an additional cookie since we want to protect logout CSRF and
510
-	 * also we can't directly interfere with PHP's session mechanism.
511
-	 */
512
-	private static function performSameSiteCookieProtection() {
513
-		$request = \OC::$server->getRequest();
514
-
515
-		// Some user agents are notorious and don't really properly follow HTTP
516
-		// specifications. For those, have an automated opt-out. Since the protection
517
-		// for remote.php is applied in base.php as starting point we need to opt out
518
-		// here.
519
-		$incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
520
-
521
-		// Fallback, if csrf.optout is unset
522
-		if (!is_array($incompatibleUserAgents)) {
523
-			$incompatibleUserAgents = [
524
-				// OS X Finder
525
-				'/^WebDAVFS/',
526
-				// Windows webdav drive
527
-				'/^Microsoft-WebDAV-MiniRedir/',
528
-			];
529
-		}
530
-
531
-		if($request->isUserAgent($incompatibleUserAgents)) {
532
-			return;
533
-		}
534
-
535
-		if(count($_COOKIE) > 0) {
536
-			$requestUri = $request->getScriptName();
537
-			$processingScript = explode('/', $requestUri);
538
-			$processingScript = $processingScript[count($processingScript)-1];
539
-
540
-			// index.php routes are handled in the middleware
541
-			if($processingScript === 'index.php') {
542
-				return;
543
-			}
544
-
545
-			// All other endpoints require the lax and the strict cookie
546
-			if(!$request->passesStrictCookieCheck()) {
547
-				self::sendSameSiteCookies();
548
-				// Debug mode gets access to the resources without strict cookie
549
-				// due to the fact that the SabreDAV browser also lives there.
550
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
551
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
552
-					exit();
553
-				}
554
-			}
555
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
556
-			self::sendSameSiteCookies();
557
-		}
558
-	}
559
-
560
-	public static function init() {
561
-		// calculate the root directories
562
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
563
-
564
-		// register autoloader
565
-		$loaderStart = microtime(true);
566
-		require_once __DIR__ . '/autoloader.php';
567
-		self::$loader = new \OC\Autoloader([
568
-			OC::$SERVERROOT . '/lib/private/legacy',
569
-		]);
570
-		if (defined('PHPUNIT_RUN')) {
571
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
572
-		}
573
-		spl_autoload_register([self::$loader, 'load']);
574
-		$loaderEnd = microtime(true);
575
-
576
-		self::$CLI = (php_sapi_name() == 'cli');
577
-
578
-		// Add default composer PSR-4 autoloader
579
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
580
-
581
-		try {
582
-			self::initPaths();
583
-			// setup 3rdparty autoloader
584
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
585
-			if (!file_exists($vendorAutoLoad)) {
586
-				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".');
587
-			}
588
-			require_once $vendorAutoLoad;
589
-
590
-		} catch (\RuntimeException $e) {
591
-			if (!self::$CLI) {
592
-				http_response_code(503);
593
-			}
594
-			// we can't use the template error page here, because this needs the
595
-			// DI container which isn't available yet
596
-			print($e->getMessage());
597
-			exit();
598
-		}
599
-
600
-		// setup the basic server
601
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
602
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
603
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
604
-
605
-		// Override php.ini and log everything if we're troubleshooting
606
-		if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
607
-			error_reporting(E_ALL);
608
-		}
609
-
610
-		// Don't display errors and log them
611
-		@ini_set('display_errors', '0');
612
-		@ini_set('log_errors', '1');
613
-
614
-		if(!date_default_timezone_set('UTC')) {
615
-			throw new \RuntimeException('Could not set timezone to UTC');
616
-		}
617
-
618
-		//try to configure php to enable big file uploads.
619
-		//this doesn´t work always depending on the webserver and php configuration.
620
-		//Let´s try to overwrite some defaults anyway
621
-
622
-		//try to set the maximum execution time to 60min
623
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
624
-			@set_time_limit(3600);
625
-		}
626
-		@ini_set('max_execution_time', '3600');
627
-		@ini_set('max_input_time', '3600');
628
-
629
-		//try to set the maximum filesize to 10G
630
-		@ini_set('upload_max_filesize', '10G');
631
-		@ini_set('post_max_size', '10G');
632
-		@ini_set('file_uploads', '50');
633
-
634
-		self::setRequiredIniValues();
635
-		self::handleAuthHeaders();
636
-		self::registerAutoloaderCache();
637
-
638
-		// initialize intl fallback is necessary
639
-		\Patchwork\Utf8\Bootup::initIntl();
640
-		OC_Util::isSetLocaleWorking();
641
-
642
-		if (!defined('PHPUNIT_RUN')) {
643
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
644
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
645
-			OC\Log\ErrorHandler::register($debug);
646
-		}
647
-
648
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
649
-		OC_App::loadApps(['session']);
650
-		if (!self::$CLI) {
651
-			self::initSession();
652
-		}
653
-		\OC::$server->getEventLogger()->end('init_session');
654
-		self::checkConfig();
655
-		self::checkInstalled();
656
-
657
-		OC_Response::addSecurityHeaders();
658
-
659
-		self::performSameSiteCookieProtection();
660
-
661
-		if (!defined('OC_CONSOLE')) {
662
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
663
-			if (count($errors) > 0) {
664
-				if (!self::$CLI) {
665
-					http_response_code(503);
666
-					OC_Util::addStyle('guest');
667
-					try {
668
-						OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
669
-						exit;
670
-					} catch (\Exception $e) {
671
-						// In case any error happens when showing the error page, we simply fall back to posting the text.
672
-						// This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
673
-					}
674
-				}
675
-
676
-				// Convert l10n string into regular string for usage in database
677
-				$staticErrors = [];
678
-				foreach ($errors as $error) {
679
-					echo $error['error'] . "\n";
680
-					echo $error['hint'] . "\n\n";
681
-					$staticErrors[] = [
682
-						'error' => (string)$error['error'],
683
-						'hint' => (string)$error['hint'],
684
-					];
685
-				}
686
-
687
-				try {
688
-					\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
-				} catch (\Exception $e) {
690
-					echo('Writing to database failed');
691
-				}
692
-				exit(1);
693
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
-			}
696
-		}
697
-		//try to set the session lifetime
698
-		$sessionLifeTime = self::getSessionLifeTime();
699
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
-
701
-		$systemConfig = \OC::$server->getSystemConfig();
702
-
703
-		// User and Groups
704
-		if (!$systemConfig->getValue("installed", false)) {
705
-			self::$server->getSession()->set('user_id', '');
706
-		}
707
-
708
-		OC_User::useBackend(new \OC\User\Database());
709
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
-
711
-		// Subscribe to the hook
712
-		\OCP\Util::connectHook(
713
-			'\OCA\Files_Sharing\API\Server2Server',
714
-			'preLoginNameUsedAsUserName',
715
-			'\OC\User\Database',
716
-			'preLoginNameUsedAsUserName'
717
-		);
718
-
719
-		//setup extra user backends
720
-		if (!\OCP\Util::needUpgrade()) {
721
-			OC_User::setupBackends();
722
-		} else {
723
-			// Run upgrades in incognito mode
724
-			OC_User::setIncognitoMode(true);
725
-		}
726
-
727
-		self::registerCleanupHooks();
728
-		self::registerFilesystemHooks();
729
-		self::registerShareHooks();
730
-		self::registerEncryptionWrapper();
731
-		self::registerEncryptionHooks();
732
-		self::registerAccountHooks();
733
-		self::registerResourceCollectionHooks();
734
-		self::registerAppRestrictionsHooks();
735
-
736
-		// Make sure that the application class is not loaded before the database is setup
737
-		if ($systemConfig->getValue("installed", false)) {
738
-			OC_App::loadApp('settings');
739
-			$settings = \OC::$server->query(\OCA\Settings\AppInfo\Application::class);
740
-			$settings->register();
741
-		}
742
-
743
-		//make sure temporary files are cleaned up
744
-		$tmpManager = \OC::$server->getTempManager();
745
-		register_shutdown_function([$tmpManager, 'clean']);
746
-		$lockProvider = \OC::$server->getLockingProvider();
747
-		register_shutdown_function([$lockProvider, 'releaseAll']);
748
-
749
-		// Check whether the sample configuration has been copied
750
-		if($systemConfig->getValue('copied_sample_config', false)) {
751
-			$l = \OC::$server->getL10N('lib');
752
-			OC_Template::printErrorPage(
753
-				$l->t('Sample configuration detected'),
754
-				$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'),
755
-				503
756
-			);
757
-			return;
758
-		}
759
-
760
-		$request = \OC::$server->getRequest();
761
-		$host = $request->getInsecureServerHost();
762
-		/**
763
-		 * if the host passed in headers isn't trusted
764
-		 * FIXME: Should not be in here at all :see_no_evil:
765
-		 */
766
-		if (!OC::$CLI
767
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
768
-			&& self::$server->getConfig()->getSystemValue('installed', false)
769
-		) {
770
-			// Allow access to CSS resources
771
-			$isScssRequest = false;
772
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
773
-				$isScssRequest = true;
774
-			}
775
-
776
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
777
-				http_response_code(400);
778
-				header('Content-Type: application/json');
779
-				echo '{"error": "Trusted domain error.", "code": 15}';
780
-				exit();
781
-			}
782
-
783
-			if (!$isScssRequest) {
784
-				http_response_code(400);
785
-
786
-				\OC::$server->getLogger()->info(
787
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
788
-					[
789
-						'app' => 'core',
790
-						'remoteAddress' => $request->getRemoteAddress(),
791
-						'host' => $host,
792
-					]
793
-				);
794
-
795
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
796
-				$tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
797
-				$tmpl->printPage();
798
-
799
-				exit();
800
-			}
801
-		}
802
-		\OC::$server->getEventLogger()->end('boot');
803
-	}
804
-
805
-	/**
806
-	 * register hooks for the cleanup of cache and bruteforce protection
807
-	 */
808
-	public static function registerCleanupHooks() {
809
-		//don't try to do this before we are properly setup
810
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
811
-
812
-			// NOTE: This will be replaced to use OCP
813
-			$userSession = self::$server->getUserSession();
814
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
815
-				if (!defined('PHPUNIT_RUN')) {
816
-					// reset brute force delay for this IP address and username
817
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
818
-					$request = \OC::$server->getRequest();
819
-					$throttler = \OC::$server->getBruteForceThrottler();
820
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
821
-				}
822
-
823
-				try {
824
-					$cache = new \OC\Cache\File();
825
-					$cache->gc();
826
-				} catch (\OC\ServerNotAvailableException $e) {
827
-					// not a GC exception, pass it on
828
-					throw $e;
829
-				} catch (\OC\ForbiddenException $e) {
830
-					// filesystem blocked for this request, ignore
831
-				} catch (\Exception $e) {
832
-					// a GC exception should not prevent users from using OC,
833
-					// so log the exception
834
-					\OC::$server->getLogger()->logException($e, [
835
-						'message' => 'Exception when running cache gc.',
836
-						'level' => ILogger::WARN,
837
-						'app' => 'core',
838
-					]);
839
-				}
840
-			});
841
-		}
842
-	}
843
-
844
-	private static function registerEncryptionWrapper() {
845
-		$manager = self::$server->getEncryptionManager();
846
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
847
-	}
848
-
849
-	private static function registerEncryptionHooks() {
850
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
851
-		if ($enabled) {
852
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
853
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
854
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
855
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
856
-		}
857
-	}
858
-
859
-	private static function registerAccountHooks() {
860
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
861
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
862
-	}
863
-
864
-	private static function registerAppRestrictionsHooks() {
865
-		$groupManager = self::$server->query(\OCP\IGroupManager::class);
866
-		$groupManager->listen ('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
867
-			$appManager = self::$server->getAppManager();
868
-			$apps = $appManager->getEnabledAppsForGroup($group);
869
-			foreach ($apps as $appId) {
870
-				$restrictions = $appManager->getAppRestriction($appId);
871
-				if (empty($restrictions)) {
872
-					continue;
873
-				}
874
-				$key = array_search($group->getGID(), $restrictions);
875
-				unset($restrictions[$key]);
876
-				$restrictions = array_values($restrictions);
877
-				if (empty($restrictions)) {
878
-					$appManager->disableApp($appId);
879
-				}
880
-				else{
881
-					$appManager->enableAppForGroups($appId, $restrictions);
882
-				}
883
-
884
-			}
885
-		});
886
-	}
887
-
888
-	private static function registerResourceCollectionHooks() {
889
-		\OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
890
-	}
891
-
892
-	/**
893
-	 * register hooks for the filesystem
894
-	 */
895
-	public static function registerFilesystemHooks() {
896
-		// Check for blacklisted files
897
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
898
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
899
-	}
900
-
901
-	/**
902
-	 * register hooks for sharing
903
-	 */
904
-	public static function registerShareHooks() {
905
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
907
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
908
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
909
-		}
910
-	}
911
-
912
-	protected static function registerAutoloaderCache() {
913
-		// The class loader takes an optional low-latency cache, which MUST be
914
-		// namespaced. The instanceid is used for namespacing, but might be
915
-		// unavailable at this point. Furthermore, it might not be possible to
916
-		// generate an instanceid via \OC_Util::getInstanceId() because the
917
-		// config file may not be writable. As such, we only register a class
918
-		// loader cache if instanceid is available without trying to create one.
919
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
-		if ($instanceId) {
921
-			try {
922
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
923
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
-			} catch (\Exception $ex) {
925
-			}
926
-		}
927
-	}
928
-
929
-	/**
930
-	 * Handle the request
931
-	 */
932
-	public static function handleRequest() {
933
-
934
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
-		$systemConfig = \OC::$server->getSystemConfig();
936
-
937
-		// Check if Nextcloud is installed or in maintenance (update) mode
938
-		if (!$systemConfig->getValue('installed', false)) {
939
-			\OC::$server->getSession()->clear();
940
-			$setupHelper = new OC\Setup(
941
-				$systemConfig,
942
-				\OC::$server->getIniWrapper(),
943
-				\OC::$server->getL10N('lib'),
944
-				\OC::$server->query(\OCP\Defaults::class),
945
-				\OC::$server->getLogger(),
946
-				\OC::$server->getSecureRandom(),
947
-				\OC::$server->query(\OC\Installer::class)
948
-			);
949
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
950
-			$controller->run($_POST);
951
-			exit();
952
-		}
953
-
954
-		$request = \OC::$server->getRequest();
955
-		$requestPath = $request->getRawPathInfo();
956
-		if ($requestPath === '/heartbeat') {
957
-			return;
958
-		}
959
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
960
-			self::checkMaintenanceMode();
961
-
962
-			if (\OCP\Util::needUpgrade()) {
963
-				if (function_exists('opcache_reset')) {
964
-					opcache_reset();
965
-				}
966
-				if (!((bool) $systemConfig->getValue('maintenance', false))) {
967
-					self::printUpgradePage($systemConfig);
968
-					exit();
969
-				}
970
-			}
971
-		}
972
-
973
-		// emergency app disabling
974
-		if ($requestPath === '/disableapp'
975
-			&& $request->getMethod() === 'POST'
976
-			&& ((array)$request->getParam('appid')) !== ''
977
-		) {
978
-			\OC_JSON::callCheck();
979
-			\OC_JSON::checkAdminUser();
980
-			$appIds = (array)$request->getParam('appid');
981
-			foreach($appIds as $appId) {
982
-				$appId = \OC_App::cleanAppId($appId);
983
-				\OC::$server->getAppManager()->disableApp($appId);
984
-			}
985
-			\OC_JSON::success();
986
-			exit();
987
-		}
988
-
989
-		// Always load authentication apps
990
-		OC_App::loadApps(['authentication']);
991
-
992
-		// Load minimum set of apps
993
-		if (!\OCP\Util::needUpgrade()
994
-			&& !((bool) $systemConfig->getValue('maintenance', false))) {
995
-			// For logged-in users: Load everything
996
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
997
-				OC_App::loadApps();
998
-			} else {
999
-				// For guests: Load only filesystem and logging
1000
-				OC_App::loadApps(['filesystem', 'logging']);
1001
-				self::handleLogin($request);
1002
-			}
1003
-		}
1004
-
1005
-		if (!self::$CLI) {
1006
-			try {
1007
-				if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1008
-					OC_App::loadApps(['filesystem', 'logging']);
1009
-					OC_App::loadApps();
1010
-				}
1011
-				OC_Util::setupFS();
1012
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1013
-				return;
1014
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1015
-				//header('HTTP/1.0 404 Not Found');
1016
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1017
-				http_response_code(405);
1018
-				return;
1019
-			}
1020
-		}
1021
-
1022
-		// Handle WebDAV
1023
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1024
-			// not allowed any more to prevent people
1025
-			// mounting this root directly.
1026
-			// Users need to mount remote.php/webdav instead.
1027
-			http_response_code(405);
1028
-			return;
1029
-		}
1030
-
1031
-		// Someone is logged in
1032
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
1033
-			OC_App::loadApps();
1034
-			OC_User::setupBackends();
1035
-			OC_Util::setupFS();
1036
-			// FIXME
1037
-			// Redirect to default application
1038
-			OC_Util::redirectToDefaultPage();
1039
-		} else {
1040
-			// Not handled and not logged in
1041
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1042
-		}
1043
-	}
1044
-
1045
-	/**
1046
-	 * Check login: apache auth, auth token, basic auth
1047
-	 *
1048
-	 * @param OCP\IRequest $request
1049
-	 * @return boolean
1050
-	 */
1051
-	static function handleLogin(OCP\IRequest $request) {
1052
-		$userSession = self::$server->getUserSession();
1053
-		if (OC_User::handleApacheAuth()) {
1054
-			return true;
1055
-		}
1056
-		if ($userSession->tryTokenLogin($request)) {
1057
-			return true;
1058
-		}
1059
-		if (isset($_COOKIE['nc_username'])
1060
-			&& isset($_COOKIE['nc_token'])
1061
-			&& isset($_COOKIE['nc_session_id'])
1062
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1063
-			return true;
1064
-		}
1065
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1066
-			return true;
1067
-		}
1068
-		return false;
1069
-	}
1070
-
1071
-	protected static function handleAuthHeaders() {
1072
-		//copy http auth headers for apache+php-fcgid work around
1073
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1074
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1075
-		}
1076
-
1077
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1078
-		$vars = [
1079
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1080
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1081
-		];
1082
-		foreach ($vars as $var) {
1083
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1084
-				$credentials = explode(':', base64_decode($matches[1]), 2);
1085
-				if (count($credentials) === 2) {
1086
-					$_SERVER['PHP_AUTH_USER'] = $credentials[0];
1087
-					$_SERVER['PHP_AUTH_PW'] = $credentials[1];
1088
-					break;
1089
-				}
1090
-			}
1091
-		}
1092
-	}
76
+    /**
77
+     * Associative array for autoloading. classname => filename
78
+     */
79
+    public static $CLASSPATH = [];
80
+    /**
81
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
82
+     */
83
+    public static $SERVERROOT = '';
84
+    /**
85
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
86
+     */
87
+    private static $SUBURI = '';
88
+    /**
89
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
90
+     */
91
+    public static $WEBROOT = '';
92
+    /**
93
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
94
+     * web path in 'url'
95
+     */
96
+    public static $APPSROOTS = [];
97
+
98
+    /**
99
+     * @var string
100
+     */
101
+    public static $configDir;
102
+
103
+    /**
104
+     * requested app
105
+     */
106
+    public static $REQUESTEDAPP = '';
107
+
108
+    /**
109
+     * check if Nextcloud runs in cli mode
110
+     */
111
+    public static $CLI = false;
112
+
113
+    /**
114
+     * @var \OC\Autoloader $loader
115
+     */
116
+    public static $loader = null;
117
+
118
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
119
+    public static $composerAutoloader = null;
120
+
121
+    /**
122
+     * @var \OC\Server
123
+     */
124
+    public static $server = null;
125
+
126
+    /**
127
+     * @var \OC\Config
128
+     */
129
+    private static $config = null;
130
+
131
+    /**
132
+     * @throws \RuntimeException when the 3rdparty directory is missing or
133
+     * the app path list is empty or contains an invalid path
134
+     */
135
+    public static function initPaths() {
136
+        if(defined('PHPUNIT_CONFIG_DIR')) {
137
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
138
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
139
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
140
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
141
+            self::$configDir = rtrim($dir, '/') . '/';
142
+        } else {
143
+            self::$configDir = OC::$SERVERROOT . '/config/';
144
+        }
145
+        self::$config = new \OC\Config(self::$configDir);
146
+
147
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
148
+        /**
149
+         * FIXME: The following lines are required because we can't yet instantiate
150
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
151
+         */
152
+        $params = [
153
+            'server' => [
154
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
155
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
156
+            ],
157
+        ];
158
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
159
+        $scriptName = $fakeRequest->getScriptName();
160
+        if (substr($scriptName, -1) == '/') {
161
+            $scriptName .= 'index.php';
162
+            //make sure suburi follows the same rules as scriptName
163
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
164
+                if (substr(OC::$SUBURI, -1) != '/') {
165
+                    OC::$SUBURI = OC::$SUBURI . '/';
166
+                }
167
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
168
+            }
169
+        }
170
+
171
+
172
+        if (OC::$CLI) {
173
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
174
+        } else {
175
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
176
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
177
+
178
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
179
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
180
+                }
181
+            } else {
182
+                // The scriptName is not ending with OC::$SUBURI
183
+                // This most likely means that we are calling from CLI.
184
+                // However some cron jobs still need to generate
185
+                // a web URL, so we use overwritewebroot as a fallback.
186
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
187
+            }
188
+
189
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
190
+            // slash which is required by URL generation.
191
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
192
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
193
+                header('Location: '.\OC::$WEBROOT.'/');
194
+                exit();
195
+            }
196
+        }
197
+
198
+        // search the apps folder
199
+        $config_paths = self::$config->getValue('apps_paths', []);
200
+        if (!empty($config_paths)) {
201
+            foreach ($config_paths as $paths) {
202
+                if (isset($paths['url']) && isset($paths['path'])) {
203
+                    $paths['url'] = rtrim($paths['url'], '/');
204
+                    $paths['path'] = rtrim($paths['path'], '/');
205
+                    OC::$APPSROOTS[] = $paths;
206
+                }
207
+            }
208
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
209
+            OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
210
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
211
+            OC::$APPSROOTS[] = [
212
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
213
+                'url' => '/apps',
214
+                'writable' => true
215
+            ];
216
+        }
217
+
218
+        if (empty(OC::$APPSROOTS)) {
219
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
220
+                . ' or the folder above. You can also configure the location in the config.php file.');
221
+        }
222
+        $paths = [];
223
+        foreach (OC::$APPSROOTS as $path) {
224
+            $paths[] = $path['path'];
225
+            if (!is_dir($path['path'])) {
226
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
227
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
228
+                    . ' config.php file.', $path['path']));
229
+            }
230
+        }
231
+
232
+        // set the right include path
233
+        set_include_path(
234
+            implode(PATH_SEPARATOR, $paths)
235
+        );
236
+    }
237
+
238
+    public static function checkConfig() {
239
+        $l = \OC::$server->getL10N('lib');
240
+
241
+        // Create config if it does not already exist
242
+        $configFilePath = self::$configDir .'/config.php';
243
+        if(!file_exists($configFilePath)) {
244
+            @touch($configFilePath);
245
+        }
246
+
247
+        // Check if config is writable
248
+        $configFileWritable = is_writable($configFilePath);
249
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
250
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
251
+
252
+            $urlGenerator = \OC::$server->getURLGenerator();
253
+
254
+            if (self::$CLI) {
255
+                echo $l->t('Cannot write into "config" directory!')."\n";
256
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
257
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
258
+                echo "\n";
259
+                echo $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
260
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
261
+                exit;
262
+            } else {
263
+                OC_Template::printErrorPage(
264
+                    $l->t('Cannot write into "config" directory!'),
265
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
266
+                    [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
267
+                    . $l->t('Or, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it. See %s',
268
+                    [ $urlGenerator->linkToDocs('admin-config') ] ),
269
+                    503
270
+                );
271
+            }
272
+        }
273
+    }
274
+
275
+    public static function checkInstalled() {
276
+        if (defined('OC_CONSOLE')) {
277
+            return;
278
+        }
279
+        // Redirect to installer if not installed
280
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
281
+            if (OC::$CLI) {
282
+                throw new Exception('Not installed');
283
+            } else {
284
+                $url = OC::$WEBROOT . '/index.php';
285
+                header('Location: ' . $url);
286
+            }
287
+            exit();
288
+        }
289
+    }
290
+
291
+    public static function checkMaintenanceMode() {
292
+        // Allow ajax update script to execute without being stopped
293
+        if (((bool) \OC::$server->getSystemConfig()->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
294
+            // send http status 503
295
+            http_response_code(503);
296
+            header('Retry-After: 120');
297
+
298
+            // render error page
299
+            $template = new OC_Template('', 'update.user', 'guest');
300
+            OC_Util::addScript('dist/maintenance');
301
+            OC_Util::addStyle('core', 'guest');
302
+            $template->printPage();
303
+            die();
304
+        }
305
+    }
306
+
307
+    /**
308
+     * Prints the upgrade page
309
+     *
310
+     * @param \OC\SystemConfig $systemConfig
311
+     */
312
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
313
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
314
+        $tooBig = false;
315
+        if (!$disableWebUpdater) {
316
+            $apps = \OC::$server->getAppManager();
317
+            if ($apps->isInstalled('user_ldap')) {
318
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
319
+
320
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
321
+                    ->from('ldap_user_mapping')
322
+                    ->execute();
323
+                $row = $result->fetch();
324
+                $result->closeCursor();
325
+
326
+                $tooBig = ($row['user_count'] > 50);
327
+            }
328
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
329
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
330
+
331
+                $result = $qb->select($qb->func()->count('*', 'user_count'))
332
+                    ->from('user_saml_users')
333
+                    ->execute();
334
+                $row = $result->fetch();
335
+                $result->closeCursor();
336
+
337
+                $tooBig = ($row['user_count'] > 50);
338
+            }
339
+            if (!$tooBig) {
340
+                // count users
341
+                $stats = \OC::$server->getUserManager()->countUsers();
342
+                $totalUsers = array_sum($stats);
343
+                $tooBig = ($totalUsers > 50);
344
+            }
345
+        }
346
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
347
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
348
+
349
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
350
+            // send http status 503
351
+            http_response_code(503);
352
+            header('Retry-After: 120');
353
+
354
+            // render error page
355
+            $template = new OC_Template('', 'update.use-cli', 'guest');
356
+            $template->assign('productName', 'nextcloud'); // for now
357
+            $template->assign('version', OC_Util::getVersionString());
358
+            $template->assign('tooBig', $tooBig);
359
+
360
+            $template->printPage();
361
+            die();
362
+        }
363
+
364
+        // check whether this is a core update or apps update
365
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
366
+        $currentVersion = implode('.', \OCP\Util::getVersion());
367
+
368
+        // if not a core upgrade, then it's apps upgrade
369
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
370
+
371
+        $oldTheme = $systemConfig->getValue('theme');
372
+        $systemConfig->setValue('theme', '');
373
+        OC_Util::addScript('config'); // needed for web root
374
+        OC_Util::addScript('update');
375
+
376
+        /** @var \OC\App\AppManager $appManager */
377
+        $appManager = \OC::$server->getAppManager();
378
+
379
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
380
+        $tmpl->assign('version', OC_Util::getVersionString());
381
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
382
+
383
+        // get third party apps
384
+        $ocVersion = \OCP\Util::getVersion();
385
+        $ocVersion = implode('.', $ocVersion);
386
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
387
+        $incompatibleShippedApps = [];
388
+        foreach ($incompatibleApps as $appInfo) {
389
+            if ($appManager->isShipped($appInfo['id'])) {
390
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
391
+            }
392
+        }
393
+
394
+        if (!empty($incompatibleShippedApps)) {
395
+            $l = \OC::$server->getL10N('core');
396
+            $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
397
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
398
+        }
399
+
400
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
401
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
402
+        $tmpl->assign('productName', 'Nextcloud'); // for now
403
+        $tmpl->assign('oldTheme', $oldTheme);
404
+        $tmpl->printPage();
405
+    }
406
+
407
+    public static function initSession() {
408
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
409
+            ini_set('session.cookie_secure', true);
410
+        }
411
+
412
+        // prevents javascript from accessing php session cookies
413
+        ini_set('session.cookie_httponly', 'true');
414
+
415
+        // set the cookie path to the Nextcloud directory
416
+        $cookie_path = OC::$WEBROOT ? : '/';
417
+        ini_set('session.cookie_path', $cookie_path);
418
+
419
+        // Let the session name be changed in the initSession Hook
420
+        $sessionName = OC_Util::getInstanceId();
421
+
422
+        try {
423
+            // Allow session apps to create a custom session object
424
+            $useCustomSession = false;
425
+            $session = self::$server->getSession();
426
+            OC_Hook::emit('OC', 'initSession', ['session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession]);
427
+            if (!$useCustomSession) {
428
+                // set the session name to the instance id - which is unique
429
+                $session = new \OC\Session\Internal($sessionName);
430
+            }
431
+
432
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
433
+            $session = $cryptoWrapper->wrapSession($session);
434
+            self::$server->setSession($session);
435
+
436
+            // if session can't be started break with http 500 error
437
+        } catch (Exception $e) {
438
+            \OC::$server->getLogger()->logException($e, ['app' => 'base']);
439
+            //show the user a detailed error page
440
+            OC_Template::printExceptionErrorPage($e, 500);
441
+            die();
442
+        }
443
+
444
+        $sessionLifeTime = self::getSessionLifeTime();
445
+
446
+        // session timeout
447
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
448
+            if (isset($_COOKIE[session_name()])) {
449
+                setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
450
+            }
451
+            \OC::$server->getUserSession()->logout();
452
+        }
453
+
454
+        $session->set('LAST_ACTIVITY', time());
455
+    }
456
+
457
+    /**
458
+     * @return string
459
+     */
460
+    private static function getSessionLifeTime() {
461
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
462
+    }
463
+
464
+    /**
465
+     * Try to set some values to the required Nextcloud default
466
+     */
467
+    public static function setRequiredIniValues() {
468
+        @ini_set('default_charset', 'UTF-8');
469
+        @ini_set('gd.jpeg_ignore_warning', '1');
470
+    }
471
+
472
+    /**
473
+     * Send the same site cookies
474
+     */
475
+    private static function sendSameSiteCookies() {
476
+        $cookieParams = session_get_cookie_params();
477
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
478
+        $policies = [
479
+            'lax',
480
+            'strict',
481
+        ];
482
+
483
+        // Append __Host to the cookie if it meets the requirements
484
+        $cookiePrefix = '';
485
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486
+            $cookiePrefix = '__Host-';
487
+        }
488
+
489
+        foreach($policies as $policy) {
490
+            header(
491
+                sprintf(
492
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493
+                    $cookiePrefix,
494
+                    $policy,
495
+                    $cookieParams['path'],
496
+                    $policy
497
+                ),
498
+                false
499
+            );
500
+        }
501
+    }
502
+
503
+    /**
504
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
505
+     * be set in every request if cookies are sent to add a second level of
506
+     * defense against CSRF.
507
+     *
508
+     * If the cookie is not sent this will set the cookie and reload the page.
509
+     * We use an additional cookie since we want to protect logout CSRF and
510
+     * also we can't directly interfere with PHP's session mechanism.
511
+     */
512
+    private static function performSameSiteCookieProtection() {
513
+        $request = \OC::$server->getRequest();
514
+
515
+        // Some user agents are notorious and don't really properly follow HTTP
516
+        // specifications. For those, have an automated opt-out. Since the protection
517
+        // for remote.php is applied in base.php as starting point we need to opt out
518
+        // here.
519
+        $incompatibleUserAgents = \OC::$server->getConfig()->getSystemValue('csrf.optout');
520
+
521
+        // Fallback, if csrf.optout is unset
522
+        if (!is_array($incompatibleUserAgents)) {
523
+            $incompatibleUserAgents = [
524
+                // OS X Finder
525
+                '/^WebDAVFS/',
526
+                // Windows webdav drive
527
+                '/^Microsoft-WebDAV-MiniRedir/',
528
+            ];
529
+        }
530
+
531
+        if($request->isUserAgent($incompatibleUserAgents)) {
532
+            return;
533
+        }
534
+
535
+        if(count($_COOKIE) > 0) {
536
+            $requestUri = $request->getScriptName();
537
+            $processingScript = explode('/', $requestUri);
538
+            $processingScript = $processingScript[count($processingScript)-1];
539
+
540
+            // index.php routes are handled in the middleware
541
+            if($processingScript === 'index.php') {
542
+                return;
543
+            }
544
+
545
+            // All other endpoints require the lax and the strict cookie
546
+            if(!$request->passesStrictCookieCheck()) {
547
+                self::sendSameSiteCookies();
548
+                // Debug mode gets access to the resources without strict cookie
549
+                // due to the fact that the SabreDAV browser also lives there.
550
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
551
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
552
+                    exit();
553
+                }
554
+            }
555
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
556
+            self::sendSameSiteCookies();
557
+        }
558
+    }
559
+
560
+    public static function init() {
561
+        // calculate the root directories
562
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
563
+
564
+        // register autoloader
565
+        $loaderStart = microtime(true);
566
+        require_once __DIR__ . '/autoloader.php';
567
+        self::$loader = new \OC\Autoloader([
568
+            OC::$SERVERROOT . '/lib/private/legacy',
569
+        ]);
570
+        if (defined('PHPUNIT_RUN')) {
571
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
572
+        }
573
+        spl_autoload_register([self::$loader, 'load']);
574
+        $loaderEnd = microtime(true);
575
+
576
+        self::$CLI = (php_sapi_name() == 'cli');
577
+
578
+        // Add default composer PSR-4 autoloader
579
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
580
+
581
+        try {
582
+            self::initPaths();
583
+            // setup 3rdparty autoloader
584
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
585
+            if (!file_exists($vendorAutoLoad)) {
586
+                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".');
587
+            }
588
+            require_once $vendorAutoLoad;
589
+
590
+        } catch (\RuntimeException $e) {
591
+            if (!self::$CLI) {
592
+                http_response_code(503);
593
+            }
594
+            // we can't use the template error page here, because this needs the
595
+            // DI container which isn't available yet
596
+            print($e->getMessage());
597
+            exit();
598
+        }
599
+
600
+        // setup the basic server
601
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
602
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
603
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
604
+
605
+        // Override php.ini and log everything if we're troubleshooting
606
+        if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
607
+            error_reporting(E_ALL);
608
+        }
609
+
610
+        // Don't display errors and log them
611
+        @ini_set('display_errors', '0');
612
+        @ini_set('log_errors', '1');
613
+
614
+        if(!date_default_timezone_set('UTC')) {
615
+            throw new \RuntimeException('Could not set timezone to UTC');
616
+        }
617
+
618
+        //try to configure php to enable big file uploads.
619
+        //this doesn´t work always depending on the webserver and php configuration.
620
+        //Let´s try to overwrite some defaults anyway
621
+
622
+        //try to set the maximum execution time to 60min
623
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
624
+            @set_time_limit(3600);
625
+        }
626
+        @ini_set('max_execution_time', '3600');
627
+        @ini_set('max_input_time', '3600');
628
+
629
+        //try to set the maximum filesize to 10G
630
+        @ini_set('upload_max_filesize', '10G');
631
+        @ini_set('post_max_size', '10G');
632
+        @ini_set('file_uploads', '50');
633
+
634
+        self::setRequiredIniValues();
635
+        self::handleAuthHeaders();
636
+        self::registerAutoloaderCache();
637
+
638
+        // initialize intl fallback is necessary
639
+        \Patchwork\Utf8\Bootup::initIntl();
640
+        OC_Util::isSetLocaleWorking();
641
+
642
+        if (!defined('PHPUNIT_RUN')) {
643
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
644
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
645
+            OC\Log\ErrorHandler::register($debug);
646
+        }
647
+
648
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
649
+        OC_App::loadApps(['session']);
650
+        if (!self::$CLI) {
651
+            self::initSession();
652
+        }
653
+        \OC::$server->getEventLogger()->end('init_session');
654
+        self::checkConfig();
655
+        self::checkInstalled();
656
+
657
+        OC_Response::addSecurityHeaders();
658
+
659
+        self::performSameSiteCookieProtection();
660
+
661
+        if (!defined('OC_CONSOLE')) {
662
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
663
+            if (count($errors) > 0) {
664
+                if (!self::$CLI) {
665
+                    http_response_code(503);
666
+                    OC_Util::addStyle('guest');
667
+                    try {
668
+                        OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
669
+                        exit;
670
+                    } catch (\Exception $e) {
671
+                        // In case any error happens when showing the error page, we simply fall back to posting the text.
672
+                        // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
673
+                    }
674
+                }
675
+
676
+                // Convert l10n string into regular string for usage in database
677
+                $staticErrors = [];
678
+                foreach ($errors as $error) {
679
+                    echo $error['error'] . "\n";
680
+                    echo $error['hint'] . "\n\n";
681
+                    $staticErrors[] = [
682
+                        'error' => (string)$error['error'],
683
+                        'hint' => (string)$error['hint'],
684
+                    ];
685
+                }
686
+
687
+                try {
688
+                    \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
689
+                } catch (\Exception $e) {
690
+                    echo('Writing to database failed');
691
+                }
692
+                exit(1);
693
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
694
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
695
+            }
696
+        }
697
+        //try to set the session lifetime
698
+        $sessionLifeTime = self::getSessionLifeTime();
699
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
700
+
701
+        $systemConfig = \OC::$server->getSystemConfig();
702
+
703
+        // User and Groups
704
+        if (!$systemConfig->getValue("installed", false)) {
705
+            self::$server->getSession()->set('user_id', '');
706
+        }
707
+
708
+        OC_User::useBackend(new \OC\User\Database());
709
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
710
+
711
+        // Subscribe to the hook
712
+        \OCP\Util::connectHook(
713
+            '\OCA\Files_Sharing\API\Server2Server',
714
+            'preLoginNameUsedAsUserName',
715
+            '\OC\User\Database',
716
+            'preLoginNameUsedAsUserName'
717
+        );
718
+
719
+        //setup extra user backends
720
+        if (!\OCP\Util::needUpgrade()) {
721
+            OC_User::setupBackends();
722
+        } else {
723
+            // Run upgrades in incognito mode
724
+            OC_User::setIncognitoMode(true);
725
+        }
726
+
727
+        self::registerCleanupHooks();
728
+        self::registerFilesystemHooks();
729
+        self::registerShareHooks();
730
+        self::registerEncryptionWrapper();
731
+        self::registerEncryptionHooks();
732
+        self::registerAccountHooks();
733
+        self::registerResourceCollectionHooks();
734
+        self::registerAppRestrictionsHooks();
735
+
736
+        // Make sure that the application class is not loaded before the database is setup
737
+        if ($systemConfig->getValue("installed", false)) {
738
+            OC_App::loadApp('settings');
739
+            $settings = \OC::$server->query(\OCA\Settings\AppInfo\Application::class);
740
+            $settings->register();
741
+        }
742
+
743
+        //make sure temporary files are cleaned up
744
+        $tmpManager = \OC::$server->getTempManager();
745
+        register_shutdown_function([$tmpManager, 'clean']);
746
+        $lockProvider = \OC::$server->getLockingProvider();
747
+        register_shutdown_function([$lockProvider, 'releaseAll']);
748
+
749
+        // Check whether the sample configuration has been copied
750
+        if($systemConfig->getValue('copied_sample_config', false)) {
751
+            $l = \OC::$server->getL10N('lib');
752
+            OC_Template::printErrorPage(
753
+                $l->t('Sample configuration detected'),
754
+                $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'),
755
+                503
756
+            );
757
+            return;
758
+        }
759
+
760
+        $request = \OC::$server->getRequest();
761
+        $host = $request->getInsecureServerHost();
762
+        /**
763
+         * if the host passed in headers isn't trusted
764
+         * FIXME: Should not be in here at all :see_no_evil:
765
+         */
766
+        if (!OC::$CLI
767
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
768
+            && self::$server->getConfig()->getSystemValue('installed', false)
769
+        ) {
770
+            // Allow access to CSS resources
771
+            $isScssRequest = false;
772
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
773
+                $isScssRequest = true;
774
+            }
775
+
776
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
777
+                http_response_code(400);
778
+                header('Content-Type: application/json');
779
+                echo '{"error": "Trusted domain error.", "code": 15}';
780
+                exit();
781
+            }
782
+
783
+            if (!$isScssRequest) {
784
+                http_response_code(400);
785
+
786
+                \OC::$server->getLogger()->info(
787
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
788
+                    [
789
+                        'app' => 'core',
790
+                        'remoteAddress' => $request->getRemoteAddress(),
791
+                        'host' => $host,
792
+                    ]
793
+                );
794
+
795
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
796
+                $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
797
+                $tmpl->printPage();
798
+
799
+                exit();
800
+            }
801
+        }
802
+        \OC::$server->getEventLogger()->end('boot');
803
+    }
804
+
805
+    /**
806
+     * register hooks for the cleanup of cache and bruteforce protection
807
+     */
808
+    public static function registerCleanupHooks() {
809
+        //don't try to do this before we are properly setup
810
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
811
+
812
+            // NOTE: This will be replaced to use OCP
813
+            $userSession = self::$server->getUserSession();
814
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
815
+                if (!defined('PHPUNIT_RUN')) {
816
+                    // reset brute force delay for this IP address and username
817
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
818
+                    $request = \OC::$server->getRequest();
819
+                    $throttler = \OC::$server->getBruteForceThrottler();
820
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
821
+                }
822
+
823
+                try {
824
+                    $cache = new \OC\Cache\File();
825
+                    $cache->gc();
826
+                } catch (\OC\ServerNotAvailableException $e) {
827
+                    // not a GC exception, pass it on
828
+                    throw $e;
829
+                } catch (\OC\ForbiddenException $e) {
830
+                    // filesystem blocked for this request, ignore
831
+                } catch (\Exception $e) {
832
+                    // a GC exception should not prevent users from using OC,
833
+                    // so log the exception
834
+                    \OC::$server->getLogger()->logException($e, [
835
+                        'message' => 'Exception when running cache gc.',
836
+                        'level' => ILogger::WARN,
837
+                        'app' => 'core',
838
+                    ]);
839
+                }
840
+            });
841
+        }
842
+    }
843
+
844
+    private static function registerEncryptionWrapper() {
845
+        $manager = self::$server->getEncryptionManager();
846
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
847
+    }
848
+
849
+    private static function registerEncryptionHooks() {
850
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
851
+        if ($enabled) {
852
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
853
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
854
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
855
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
856
+        }
857
+    }
858
+
859
+    private static function registerAccountHooks() {
860
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
861
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
862
+    }
863
+
864
+    private static function registerAppRestrictionsHooks() {
865
+        $groupManager = self::$server->query(\OCP\IGroupManager::class);
866
+        $groupManager->listen ('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
867
+            $appManager = self::$server->getAppManager();
868
+            $apps = $appManager->getEnabledAppsForGroup($group);
869
+            foreach ($apps as $appId) {
870
+                $restrictions = $appManager->getAppRestriction($appId);
871
+                if (empty($restrictions)) {
872
+                    continue;
873
+                }
874
+                $key = array_search($group->getGID(), $restrictions);
875
+                unset($restrictions[$key]);
876
+                $restrictions = array_values($restrictions);
877
+                if (empty($restrictions)) {
878
+                    $appManager->disableApp($appId);
879
+                }
880
+                else{
881
+                    $appManager->enableAppForGroups($appId, $restrictions);
882
+                }
883
+
884
+            }
885
+        });
886
+    }
887
+
888
+    private static function registerResourceCollectionHooks() {
889
+        \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
890
+    }
891
+
892
+    /**
893
+     * register hooks for the filesystem
894
+     */
895
+    public static function registerFilesystemHooks() {
896
+        // Check for blacklisted files
897
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
898
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
899
+    }
900
+
901
+    /**
902
+     * register hooks for sharing
903
+     */
904
+    public static function registerShareHooks() {
905
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
906
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
907
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
908
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
909
+        }
910
+    }
911
+
912
+    protected static function registerAutoloaderCache() {
913
+        // The class loader takes an optional low-latency cache, which MUST be
914
+        // namespaced. The instanceid is used for namespacing, but might be
915
+        // unavailable at this point. Furthermore, it might not be possible to
916
+        // generate an instanceid via \OC_Util::getInstanceId() because the
917
+        // config file may not be writable. As such, we only register a class
918
+        // loader cache if instanceid is available without trying to create one.
919
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
920
+        if ($instanceId) {
921
+            try {
922
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
923
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
924
+            } catch (\Exception $ex) {
925
+            }
926
+        }
927
+    }
928
+
929
+    /**
930
+     * Handle the request
931
+     */
932
+    public static function handleRequest() {
933
+
934
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
935
+        $systemConfig = \OC::$server->getSystemConfig();
936
+
937
+        // Check if Nextcloud is installed or in maintenance (update) mode
938
+        if (!$systemConfig->getValue('installed', false)) {
939
+            \OC::$server->getSession()->clear();
940
+            $setupHelper = new OC\Setup(
941
+                $systemConfig,
942
+                \OC::$server->getIniWrapper(),
943
+                \OC::$server->getL10N('lib'),
944
+                \OC::$server->query(\OCP\Defaults::class),
945
+                \OC::$server->getLogger(),
946
+                \OC::$server->getSecureRandom(),
947
+                \OC::$server->query(\OC\Installer::class)
948
+            );
949
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
950
+            $controller->run($_POST);
951
+            exit();
952
+        }
953
+
954
+        $request = \OC::$server->getRequest();
955
+        $requestPath = $request->getRawPathInfo();
956
+        if ($requestPath === '/heartbeat') {
957
+            return;
958
+        }
959
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
960
+            self::checkMaintenanceMode();
961
+
962
+            if (\OCP\Util::needUpgrade()) {
963
+                if (function_exists('opcache_reset')) {
964
+                    opcache_reset();
965
+                }
966
+                if (!((bool) $systemConfig->getValue('maintenance', false))) {
967
+                    self::printUpgradePage($systemConfig);
968
+                    exit();
969
+                }
970
+            }
971
+        }
972
+
973
+        // emergency app disabling
974
+        if ($requestPath === '/disableapp'
975
+            && $request->getMethod() === 'POST'
976
+            && ((array)$request->getParam('appid')) !== ''
977
+        ) {
978
+            \OC_JSON::callCheck();
979
+            \OC_JSON::checkAdminUser();
980
+            $appIds = (array)$request->getParam('appid');
981
+            foreach($appIds as $appId) {
982
+                $appId = \OC_App::cleanAppId($appId);
983
+                \OC::$server->getAppManager()->disableApp($appId);
984
+            }
985
+            \OC_JSON::success();
986
+            exit();
987
+        }
988
+
989
+        // Always load authentication apps
990
+        OC_App::loadApps(['authentication']);
991
+
992
+        // Load minimum set of apps
993
+        if (!\OCP\Util::needUpgrade()
994
+            && !((bool) $systemConfig->getValue('maintenance', false))) {
995
+            // For logged-in users: Load everything
996
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
997
+                OC_App::loadApps();
998
+            } else {
999
+                // For guests: Load only filesystem and logging
1000
+                OC_App::loadApps(['filesystem', 'logging']);
1001
+                self::handleLogin($request);
1002
+            }
1003
+        }
1004
+
1005
+        if (!self::$CLI) {
1006
+            try {
1007
+                if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
1008
+                    OC_App::loadApps(['filesystem', 'logging']);
1009
+                    OC_App::loadApps();
1010
+                }
1011
+                OC_Util::setupFS();
1012
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
1013
+                return;
1014
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
1015
+                //header('HTTP/1.0 404 Not Found');
1016
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
1017
+                http_response_code(405);
1018
+                return;
1019
+            }
1020
+        }
1021
+
1022
+        // Handle WebDAV
1023
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
1024
+            // not allowed any more to prevent people
1025
+            // mounting this root directly.
1026
+            // Users need to mount remote.php/webdav instead.
1027
+            http_response_code(405);
1028
+            return;
1029
+        }
1030
+
1031
+        // Someone is logged in
1032
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
1033
+            OC_App::loadApps();
1034
+            OC_User::setupBackends();
1035
+            OC_Util::setupFS();
1036
+            // FIXME
1037
+            // Redirect to default application
1038
+            OC_Util::redirectToDefaultPage();
1039
+        } else {
1040
+            // Not handled and not logged in
1041
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1042
+        }
1043
+    }
1044
+
1045
+    /**
1046
+     * Check login: apache auth, auth token, basic auth
1047
+     *
1048
+     * @param OCP\IRequest $request
1049
+     * @return boolean
1050
+     */
1051
+    static function handleLogin(OCP\IRequest $request) {
1052
+        $userSession = self::$server->getUserSession();
1053
+        if (OC_User::handleApacheAuth()) {
1054
+            return true;
1055
+        }
1056
+        if ($userSession->tryTokenLogin($request)) {
1057
+            return true;
1058
+        }
1059
+        if (isset($_COOKIE['nc_username'])
1060
+            && isset($_COOKIE['nc_token'])
1061
+            && isset($_COOKIE['nc_session_id'])
1062
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1063
+            return true;
1064
+        }
1065
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1066
+            return true;
1067
+        }
1068
+        return false;
1069
+    }
1070
+
1071
+    protected static function handleAuthHeaders() {
1072
+        //copy http auth headers for apache+php-fcgid work around
1073
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1074
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1075
+        }
1076
+
1077
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1078
+        $vars = [
1079
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1080
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1081
+        ];
1082
+        foreach ($vars as $var) {
1083
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1084
+                $credentials = explode(':', base64_decode($matches[1]), 2);
1085
+                if (count($credentials) === 2) {
1086
+                    $_SERVER['PHP_AUTH_USER'] = $credentials[0];
1087
+                    $_SERVER['PHP_AUTH_PW'] = $credentials[1];
1088
+                    break;
1089
+                }
1090
+            }
1091
+        }
1092
+    }
1093 1093
 }
1094 1094
 
1095 1095
 OC::init();
Please login to merge, or discard this patch.
lib/public/DB/QueryBuilder/IQueryBuilder.php 1 patch
Indentation   +867 added lines, -867 removed lines patch added patch discarded remove patch
@@ -34,871 +34,871 @@
 block discarded – undo
34 34
  */
35 35
 interface IQueryBuilder {
36 36
 
37
-	/**
38
-	 * @since 9.0.0
39
-	 */
40
-	const PARAM_NULL = \PDO::PARAM_NULL;
41
-	/**
42
-	 * @since 9.0.0
43
-	 */
44
-	const PARAM_BOOL = \PDO::PARAM_BOOL;
45
-	/**
46
-	 * @since 9.0.0
47
-	 */
48
-	const PARAM_INT = \PDO::PARAM_INT;
49
-	/**
50
-	 * @since 9.0.0
51
-	 */
52
-	const PARAM_STR = \PDO::PARAM_STR;
53
-	/**
54
-	 * @since 9.0.0
55
-	 */
56
-	const PARAM_LOB = \PDO::PARAM_LOB;
57
-	/**
58
-	 * @since 9.0.0
59
-	 */
60
-	const PARAM_DATE = 'datetime';
61
-
62
-	/**
63
-	 * @since 9.0.0
64
-	 */
65
-	const PARAM_INT_ARRAY = Connection::PARAM_INT_ARRAY;
66
-	/**
67
-	 * @since 9.0.0
68
-	 */
69
-	const PARAM_STR_ARRAY = Connection::PARAM_STR_ARRAY;
70
-
71
-
72
-	/**
73
-	 * Enable/disable automatic prefixing of table names with the oc_ prefix
74
-	 *
75
-	 * @param bool $enabled If set to true table names will be prefixed with the
76
-	 * owncloud database prefix automatically.
77
-	 * @since 8.2.0
78
-	 */
79
-	public function automaticTablePrefix($enabled);
80
-
81
-	/**
82
-	 * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
83
-	 * This producer method is intended for convenient inline usage. Example:
84
-	 *
85
-	 * <code>
86
-	 *     $qb = $conn->getQueryBuilder()
87
-	 *         ->select('u')
88
-	 *         ->from('users', 'u')
89
-	 *         ->where($qb->expr()->eq('u.id', 1));
90
-	 * </code>
91
-	 *
92
-	 * For more complex expression construction, consider storing the expression
93
-	 * builder object in a local variable.
94
-	 *
95
-	 * @return \OCP\DB\QueryBuilder\IExpressionBuilder
96
-	 * @since 8.2.0
97
-	 */
98
-	public function expr();
99
-
100
-	/**
101
-	 * Gets an FunctionBuilder used for object-oriented construction of query functions.
102
-	 * This producer method is intended for convenient inline usage. Example:
103
-	 *
104
-	 * <code>
105
-	 *     $qb = $conn->getQueryBuilder()
106
-	 *         ->select('u')
107
-	 *         ->from('users', 'u')
108
-	 *         ->where($qb->fun()->md5('u.id'));
109
-	 * </code>
110
-	 *
111
-	 * For more complex function construction, consider storing the function
112
-	 * builder object in a local variable.
113
-	 *
114
-	 * @return \OCP\DB\QueryBuilder\IFunctionBuilder
115
-	 * @since 12.0.0
116
-	 */
117
-	public function func();
118
-
119
-	/**
120
-	 * Gets the type of the currently built query.
121
-	 *
122
-	 * @return integer
123
-	 * @since 8.2.0
124
-	 */
125
-	public function getType();
126
-
127
-	/**
128
-	 * Gets the associated DBAL Connection for this query builder.
129
-	 *
130
-	 * @return \OCP\IDBConnection
131
-	 * @since 8.2.0
132
-	 */
133
-	public function getConnection();
134
-
135
-	/**
136
-	 * Gets the state of this query builder instance.
137
-	 *
138
-	 * @return integer Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
139
-	 * @since 8.2.0
140
-	 */
141
-	public function getState();
142
-
143
-	/**
144
-	 * Executes this query using the bound parameters and their types.
145
-	 *
146
-	 * Uses {@see Connection::executeQuery} for select statements and {@see Connection::executeUpdate}
147
-	 * for insert, update and delete statements.
148
-	 *
149
-	 * @return \Doctrine\DBAL\Driver\Statement|int
150
-	 * @since 8.2.0
151
-	 */
152
-	public function execute();
153
-
154
-	/**
155
-	 * Gets the complete SQL string formed by the current specifications of this QueryBuilder.
156
-	 *
157
-	 * <code>
158
-	 *     $qb = $conn->getQueryBuilder()
159
-	 *         ->select('u')
160
-	 *         ->from('User', 'u')
161
-	 *     echo $qb->getSQL(); // SELECT u FROM User u
162
-	 * </code>
163
-	 *
164
-	 * @return string The SQL query string.
165
-	 * @since 8.2.0
166
-	 */
167
-	public function getSQL();
168
-
169
-	/**
170
-	 * Sets a query parameter for the query being constructed.
171
-	 *
172
-	 * <code>
173
-	 *     $qb = $conn->getQueryBuilder()
174
-	 *         ->select('u')
175
-	 *         ->from('users', 'u')
176
-	 *         ->where('u.id = :user_id')
177
-	 *         ->setParameter(':user_id', 1);
178
-	 * </code>
179
-	 *
180
-	 * @param string|integer $key The parameter position or name.
181
-	 * @param mixed $value The parameter value.
182
-	 * @param string|null|int $type One of the IQueryBuilder::PARAM_* constants.
183
-	 *
184
-	 * @return $this This QueryBuilder instance.
185
-	 * @since 8.2.0
186
-	 */
187
-	public function setParameter($key, $value, $type = null);
188
-
189
-	/**
190
-	 * Sets a collection of query parameters for the query being constructed.
191
-	 *
192
-	 * <code>
193
-	 *     $qb = $conn->getQueryBuilder()
194
-	 *         ->select('u')
195
-	 *         ->from('users', 'u')
196
-	 *         ->where('u.id = :user_id1 OR u.id = :user_id2')
197
-	 *         ->setParameters(array(
198
-	 *             ':user_id1' => 1,
199
-	 *             ':user_id2' => 2
200
-	 *         ));
201
-	 * </code>
202
-	 *
203
-	 * @param array $params The query parameters to set.
204
-	 * @param array $types The query parameters types to set.
205
-	 *
206
-	 * @return $this This QueryBuilder instance.
207
-	 * @since 8.2.0
208
-	 */
209
-	public function setParameters(array $params, array $types = []);
210
-
211
-	/**
212
-	 * Gets all defined query parameters for the query being constructed indexed by parameter index or name.
213
-	 *
214
-	 * @return array The currently defined query parameters indexed by parameter index or name.
215
-	 * @since 8.2.0
216
-	 */
217
-	public function getParameters();
218
-
219
-	/**
220
-	 * Gets a (previously set) query parameter of the query being constructed.
221
-	 *
222
-	 * @param mixed $key The key (index or name) of the bound parameter.
223
-	 *
224
-	 * @return mixed The value of the bound parameter.
225
-	 * @since 8.2.0
226
-	 */
227
-	public function getParameter($key);
228
-
229
-	/**
230
-	 * Gets all defined query parameter types for the query being constructed indexed by parameter index or name.
231
-	 *
232
-	 * @return array The currently defined query parameter types indexed by parameter index or name.
233
-	 * @since 8.2.0
234
-	 */
235
-	public function getParameterTypes();
236
-
237
-	/**
238
-	 * Gets a (previously set) query parameter type of the query being constructed.
239
-	 *
240
-	 * @param mixed $key The key (index or name) of the bound parameter type.
241
-	 *
242
-	 * @return mixed The value of the bound parameter type.
243
-	 * @since 8.2.0
244
-	 */
245
-	public function getParameterType($key);
246
-
247
-	/**
248
-	 * Sets the position of the first result to retrieve (the "offset").
249
-	 *
250
-	 * @param integer $firstResult The first result to return.
251
-	 *
252
-	 * @return $this This QueryBuilder instance.
253
-	 * @since 8.2.0
254
-	 */
255
-	public function setFirstResult($firstResult);
256
-
257
-	/**
258
-	 * Gets the position of the first result the query object was set to retrieve (the "offset").
259
-	 * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder.
260
-	 *
261
-	 * @return integer The position of the first result.
262
-	 * @since 8.2.0
263
-	 */
264
-	public function getFirstResult();
265
-
266
-	/**
267
-	 * Sets the maximum number of results to retrieve (the "limit").
268
-	 *
269
-	 * @param integer $maxResults The maximum number of results to retrieve.
270
-	 *
271
-	 * @return $this This QueryBuilder instance.
272
-	 * @since 8.2.0
273
-	 */
274
-	public function setMaxResults($maxResults);
275
-
276
-	/**
277
-	 * Gets the maximum number of results the query object was set to retrieve (the "limit").
278
-	 * Returns NULL if {@link setMaxResults} was not applied to this query builder.
279
-	 *
280
-	 * @return integer The maximum number of results.
281
-	 * @since 8.2.0
282
-	 */
283
-	public function getMaxResults();
284
-
285
-	/**
286
-	 * Specifies an item that is to be returned in the query result.
287
-	 * Replaces any previously specified selections, if any.
288
-	 *
289
-	 * <code>
290
-	 *     $qb = $conn->getQueryBuilder()
291
-	 *         ->select('u.id', 'p.id')
292
-	 *         ->from('users', 'u')
293
-	 *         ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
294
-	 * </code>
295
-	 *
296
-	 * @param mixed ...$selects The selection expressions.
297
-	 *
298
-	 * @return $this This QueryBuilder instance.
299
-	 * @since 8.2.0
300
-	 */
301
-	public function select(...$selects);
302
-
303
-	/**
304
-	 * Specifies an item that is to be returned with a different name in the query result.
305
-	 *
306
-	 * <code>
307
-	 *     $qb = $conn->getQueryBuilder()
308
-	 *         ->selectAlias('u.id', 'user_id')
309
-	 *         ->from('users', 'u')
310
-	 *         ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
311
-	 * </code>
312
-	 *
313
-	 * @param mixed $select The selection expressions.
314
-	 * @param string $alias The column alias used in the constructed query.
315
-	 *
316
-	 * @return $this This QueryBuilder instance.
317
-	 * @since 8.2.1
318
-	 */
319
-	public function selectAlias($select, $alias);
320
-
321
-	/**
322
-	 * Specifies an item that is to be returned uniquely in the query result.
323
-	 *
324
-	 * <code>
325
-	 *     $qb = $conn->getQueryBuilder()
326
-	 *         ->selectDistinct('type')
327
-	 *         ->from('users');
328
-	 * </code>
329
-	 *
330
-	 * @param mixed $select The selection expressions.
331
-	 *
332
-	 * @return $this This QueryBuilder instance.
333
-	 * @since 9.0.0
334
-	 */
335
-	public function selectDistinct($select);
336
-
337
-	/**
338
-	 * Adds an item that is to be returned in the query result.
339
-	 *
340
-	 * <code>
341
-	 *     $qb = $conn->getQueryBuilder()
342
-	 *         ->select('u.id')
343
-	 *         ->addSelect('p.id')
344
-	 *         ->from('users', 'u')
345
-	 *         ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
346
-	 * </code>
347
-	 *
348
-	 * @param mixed ...$select The selection expression.
349
-	 *
350
-	 * @return $this This QueryBuilder instance.
351
-	 * @since 8.2.0
352
-	 */
353
-	public function addSelect(...$select);
354
-
355
-	/**
356
-	 * Turns the query being built into a bulk delete query that ranges over
357
-	 * a certain table.
358
-	 *
359
-	 * <code>
360
-	 *     $qb = $conn->getQueryBuilder()
361
-	 *         ->delete('users', 'u')
362
-	 *         ->where('u.id = :user_id');
363
-	 *         ->setParameter(':user_id', 1);
364
-	 * </code>
365
-	 *
366
-	 * @param string $delete The table whose rows are subject to the deletion.
367
-	 * @param string $alias The table alias used in the constructed query.
368
-	 *
369
-	 * @return $this This QueryBuilder instance.
370
-	 * @since 8.2.0
371
-	 */
372
-	public function delete($delete = null, $alias = null);
373
-
374
-	/**
375
-	 * Turns the query being built into a bulk update query that ranges over
376
-	 * a certain table
377
-	 *
378
-	 * <code>
379
-	 *     $qb = $conn->getQueryBuilder()
380
-	 *         ->update('users', 'u')
381
-	 *         ->set('u.password', md5('password'))
382
-	 *         ->where('u.id = ?');
383
-	 * </code>
384
-	 *
385
-	 * @param string $update The table whose rows are subject to the update.
386
-	 * @param string $alias The table alias used in the constructed query.
387
-	 *
388
-	 * @return $this This QueryBuilder instance.
389
-	 * @since 8.2.0
390
-	 */
391
-	public function update($update = null, $alias = null);
392
-
393
-	/**
394
-	 * Turns the query being built into an insert query that inserts into
395
-	 * a certain table
396
-	 *
397
-	 * <code>
398
-	 *     $qb = $conn->getQueryBuilder()
399
-	 *         ->insert('users')
400
-	 *         ->values(
401
-	 *             array(
402
-	 *                 'name' => '?',
403
-	 *                 'password' => '?'
404
-	 *             )
405
-	 *         );
406
-	 * </code>
407
-	 *
408
-	 * @param string $insert The table into which the rows should be inserted.
409
-	 *
410
-	 * @return $this This QueryBuilder instance.
411
-	 * @since 8.2.0
412
-	 */
413
-	public function insert($insert = null);
414
-
415
-	/**
416
-	 * Creates and adds a query root corresponding to the table identified by the
417
-	 * given alias, forming a cartesian product with any existing query roots.
418
-	 *
419
-	 * <code>
420
-	 *     $qb = $conn->getQueryBuilder()
421
-	 *         ->select('u.id')
422
-	 *         ->from('users', 'u')
423
-	 * </code>
424
-	 *
425
-	 * @param string $from The table.
426
-	 * @param string|null $alias The alias of the table.
427
-	 *
428
-	 * @return $this This QueryBuilder instance.
429
-	 * @since 8.2.0
430
-	 */
431
-	public function from($from, $alias = null);
432
-
433
-	/**
434
-	 * Creates and adds a join to the query.
435
-	 *
436
-	 * <code>
437
-	 *     $qb = $conn->getQueryBuilder()
438
-	 *         ->select('u.name')
439
-	 *         ->from('users', 'u')
440
-	 *         ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
441
-	 * </code>
442
-	 *
443
-	 * @param string $fromAlias The alias that points to a from clause.
444
-	 * @param string $join The table name to join.
445
-	 * @param string $alias The alias of the join table.
446
-	 * @param string $condition The condition for the join.
447
-	 *
448
-	 * @return $this This QueryBuilder instance.
449
-	 * @since 8.2.0
450
-	 */
451
-	public function join($fromAlias, $join, $alias, $condition = null);
452
-
453
-	/**
454
-	 * Creates and adds a join to the query.
455
-	 *
456
-	 * <code>
457
-	 *     $qb = $conn->getQueryBuilder()
458
-	 *         ->select('u.name')
459
-	 *         ->from('users', 'u')
460
-	 *         ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
461
-	 * </code>
462
-	 *
463
-	 * @param string $fromAlias The alias that points to a from clause.
464
-	 * @param string $join The table name to join.
465
-	 * @param string $alias The alias of the join table.
466
-	 * @param string $condition The condition for the join.
467
-	 *
468
-	 * @return $this This QueryBuilder instance.
469
-	 * @since 8.2.0
470
-	 */
471
-	public function innerJoin($fromAlias, $join, $alias, $condition = null);
472
-
473
-	/**
474
-	 * Creates and adds a left join to the query.
475
-	 *
476
-	 * <code>
477
-	 *     $qb = $conn->getQueryBuilder()
478
-	 *         ->select('u.name')
479
-	 *         ->from('users', 'u')
480
-	 *         ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
481
-	 * </code>
482
-	 *
483
-	 * @param string $fromAlias The alias that points to a from clause.
484
-	 * @param string $join The table name to join.
485
-	 * @param string $alias The alias of the join table.
486
-	 * @param string $condition The condition for the join.
487
-	 *
488
-	 * @return $this This QueryBuilder instance.
489
-	 * @since 8.2.0
490
-	 */
491
-	public function leftJoin($fromAlias, $join, $alias, $condition = null);
492
-
493
-	/**
494
-	 * Creates and adds a right join to the query.
495
-	 *
496
-	 * <code>
497
-	 *     $qb = $conn->getQueryBuilder()
498
-	 *         ->select('u.name')
499
-	 *         ->from('users', 'u')
500
-	 *         ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
501
-	 * </code>
502
-	 *
503
-	 * @param string $fromAlias The alias that points to a from clause.
504
-	 * @param string $join The table name to join.
505
-	 * @param string $alias The alias of the join table.
506
-	 * @param string $condition The condition for the join.
507
-	 *
508
-	 * @return $this This QueryBuilder instance.
509
-	 * @since 8.2.0
510
-	 */
511
-	public function rightJoin($fromAlias, $join, $alias, $condition = null);
512
-
513
-	/**
514
-	 * Sets a new value for a column in a bulk update query.
515
-	 *
516
-	 * <code>
517
-	 *     $qb = $conn->getQueryBuilder()
518
-	 *         ->update('users', 'u')
519
-	 *         ->set('u.password', md5('password'))
520
-	 *         ->where('u.id = ?');
521
-	 * </code>
522
-	 *
523
-	 * @param string $key The column to set.
524
-	 * @param string $value The value, expression, placeholder, etc.
525
-	 *
526
-	 * @return $this This QueryBuilder instance.
527
-	 * @since 8.2.0
528
-	 */
529
-	public function set($key, $value);
530
-
531
-	/**
532
-	 * Specifies one or more restrictions to the query result.
533
-	 * Replaces any previously specified restrictions, if any.
534
-	 *
535
-	 * <code>
536
-	 *     $qb = $conn->getQueryBuilder()
537
-	 *         ->select('u.name')
538
-	 *         ->from('users', 'u')
539
-	 *         ->where('u.id = ?');
540
-	 *
541
-	 *     // You can optionally programatically build and/or expressions
542
-	 *     $qb = $conn->getQueryBuilder();
543
-	 *
544
-	 *     $or = $qb->expr()->orx();
545
-	 *     $or->add($qb->expr()->eq('u.id', 1));
546
-	 *     $or->add($qb->expr()->eq('u.id', 2));
547
-	 *
548
-	 *     $qb->update('users', 'u')
549
-	 *         ->set('u.password', md5('password'))
550
-	 *         ->where($or);
551
-	 * </code>
552
-	 *
553
-	 * @param mixed $predicates The restriction predicates.
554
-	 *
555
-	 * @return $this This QueryBuilder instance.
556
-	 * @since 8.2.0
557
-	 */
558
-	public function where(...$predicates);
559
-
560
-	/**
561
-	 * Adds one or more restrictions to the query results, forming a logical
562
-	 * conjunction with any previously specified restrictions.
563
-	 *
564
-	 * <code>
565
-	 *     $qb = $conn->getQueryBuilder()
566
-	 *         ->select('u')
567
-	 *         ->from('users', 'u')
568
-	 *         ->where('u.username LIKE ?')
569
-	 *         ->andWhere('u.is_active = 1');
570
-	 * </code>
571
-	 *
572
-	 * @param mixed ...$where The query restrictions.
573
-	 *
574
-	 * @return $this This QueryBuilder instance.
575
-	 *
576
-	 * @see where()
577
-	 * @since 8.2.0
578
-	 */
579
-	public function andWhere(...$where);
580
-
581
-	/**
582
-	 * Adds one or more restrictions to the query results, forming a logical
583
-	 * disjunction with any previously specified restrictions.
584
-	 *
585
-	 * <code>
586
-	 *     $qb = $conn->getQueryBuilder()
587
-	 *         ->select('u.name')
588
-	 *         ->from('users', 'u')
589
-	 *         ->where('u.id = 1')
590
-	 *         ->orWhere('u.id = 2');
591
-	 * </code>
592
-	 *
593
-	 * @param mixed ...$where The WHERE statement.
594
-	 *
595
-	 * @return $this This QueryBuilder instance.
596
-	 *
597
-	 * @see where()
598
-	 * @since 8.2.0
599
-	 */
600
-	public function orWhere(...$where);
601
-
602
-	/**
603
-	 * Specifies a grouping over the results of the query.
604
-	 * Replaces any previously specified groupings, if any.
605
-	 *
606
-	 * <code>
607
-	 *     $qb = $conn->getQueryBuilder()
608
-	 *         ->select('u.name')
609
-	 *         ->from('users', 'u')
610
-	 *         ->groupBy('u.id');
611
-	 * </code>
612
-	 *
613
-	 * @param mixed ...$groupBys The grouping expression.
614
-	 *
615
-	 * @return $this This QueryBuilder instance.
616
-	 * @since 8.2.0
617
-	 */
618
-	public function groupBy(...$groupBys);
619
-
620
-	/**
621
-	 * Adds a grouping expression to the query.
622
-	 *
623
-	 * <code>
624
-	 *     $qb = $conn->getQueryBuilder()
625
-	 *         ->select('u.name')
626
-	 *         ->from('users', 'u')
627
-	 *         ->groupBy('u.lastLogin');
628
-	 *         ->addGroupBy('u.createdAt')
629
-	 * </code>
630
-	 *
631
-	 * @param mixed ...$groupBy The grouping expression.
632
-	 *
633
-	 * @return $this This QueryBuilder instance.
634
-	 * @since 8.2.0
635
-	 */
636
-	public function addGroupBy(...$groupBy);
637
-
638
-	/**
639
-	 * Sets a value for a column in an insert query.
640
-	 *
641
-	 * <code>
642
-	 *     $qb = $conn->getQueryBuilder()
643
-	 *         ->insert('users')
644
-	 *         ->values(
645
-	 *             array(
646
-	 *                 'name' => '?'
647
-	 *             )
648
-	 *         )
649
-	 *         ->setValue('password', '?');
650
-	 * </code>
651
-	 *
652
-	 * @param string $column The column into which the value should be inserted.
653
-	 * @param string $value The value that should be inserted into the column.
654
-	 *
655
-	 * @return $this This QueryBuilder instance.
656
-	 * @since 8.2.0
657
-	 */
658
-	public function setValue($column, $value);
659
-
660
-	/**
661
-	 * Specifies values for an insert query indexed by column names.
662
-	 * Replaces any previous values, if any.
663
-	 *
664
-	 * <code>
665
-	 *     $qb = $conn->getQueryBuilder()
666
-	 *         ->insert('users')
667
-	 *         ->values(
668
-	 *             array(
669
-	 *                 'name' => '?',
670
-	 *                 'password' => '?'
671
-	 *             )
672
-	 *         );
673
-	 * </code>
674
-	 *
675
-	 * @param array $values The values to specify for the insert query indexed by column names.
676
-	 *
677
-	 * @return $this This QueryBuilder instance.
678
-	 * @since 8.2.0
679
-	 */
680
-	public function values(array $values);
681
-
682
-	/**
683
-	 * Specifies a restriction over the groups of the query.
684
-	 * Replaces any previous having restrictions, if any.
685
-	 *
686
-	 * @param mixed ...$having The restriction over the groups.
687
-	 *
688
-	 * @return $this This QueryBuilder instance.
689
-	 * @since 8.2.0
690
-	 */
691
-	public function having(...$having);
692
-
693
-	/**
694
-	 * Adds a restriction over the groups of the query, forming a logical
695
-	 * conjunction with any existing having restrictions.
696
-	 *
697
-	 * @param mixed ...$having The restriction to append.
698
-	 *
699
-	 * @return $this This QueryBuilder instance.
700
-	 * @since 8.2.0
701
-	 */
702
-	public function andHaving(...$having);
703
-
704
-	/**
705
-	 * Adds a restriction over the groups of the query, forming a logical
706
-	 * disjunction with any existing having restrictions.
707
-	 *
708
-	 * @param mixed ...$having The restriction to add.
709
-	 *
710
-	 * @return $this This QueryBuilder instance.
711
-	 * @since 8.2.0
712
-	 */
713
-	public function orHaving(...$having);
714
-
715
-	/**
716
-	 * Specifies an ordering for the query results.
717
-	 * Replaces any previously specified orderings, if any.
718
-	 *
719
-	 * @param string $sort The ordering expression.
720
-	 * @param string $order The ordering direction.
721
-	 *
722
-	 * @return $this This QueryBuilder instance.
723
-	 * @since 8.2.0
724
-	 */
725
-	public function orderBy($sort, $order = null);
726
-
727
-	/**
728
-	 * Adds an ordering to the query results.
729
-	 *
730
-	 * @param string $sort The ordering expression.
731
-	 * @param string $order The ordering direction.
732
-	 *
733
-	 * @return $this This QueryBuilder instance.
734
-	 * @since 8.2.0
735
-	 */
736
-	public function addOrderBy($sort, $order = null);
737
-
738
-	/**
739
-	 * Gets a query part by its name.
740
-	 *
741
-	 * @param string $queryPartName
742
-	 *
743
-	 * @return mixed
744
-	 * @since 8.2.0
745
-	 */
746
-	public function getQueryPart($queryPartName);
747
-
748
-	/**
749
-	 * Gets all query parts.
750
-	 *
751
-	 * @return array
752
-	 * @since 8.2.0
753
-	 */
754
-	public function getQueryParts();
755
-
756
-	/**
757
-	 * Resets SQL parts.
758
-	 *
759
-	 * @param array|null $queryPartNames
760
-	 *
761
-	 * @return $this This QueryBuilder instance.
762
-	 * @since 8.2.0
763
-	 */
764
-	public function resetQueryParts($queryPartNames = null);
765
-
766
-	/**
767
-	 * Resets a single SQL part.
768
-	 *
769
-	 * @param string $queryPartName
770
-	 *
771
-	 * @return $this This QueryBuilder instance.
772
-	 * @since 8.2.0
773
-	 */
774
-	public function resetQueryPart($queryPartName);
775
-
776
-	/**
777
-	 * Creates a new named parameter and bind the value $value to it.
778
-	 *
779
-	 * This method provides a shortcut for PDOStatement::bindValue
780
-	 * when using prepared statements.
781
-	 *
782
-	 * The parameter $value specifies the value that you want to bind. If
783
-	 * $placeholder is not provided bindValue() will automatically create a
784
-	 * placeholder for you. An automatic placeholder will be of the name
785
-	 * ':dcValue1', ':dcValue2' etc.
786
-	 *
787
-	 * For more information see {@link http://php.net/pdostatement-bindparam}
788
-	 *
789
-	 * Example:
790
-	 * <code>
791
-	 * $value = 2;
792
-	 * $q->eq( 'id', $q->bindValue( $value ) );
793
-	 * $stmt = $q->executeQuery(); // executed with 'id = 2'
794
-	 * </code>
795
-	 *
796
-	 * @license New BSD License
797
-	 * @link http://www.zetacomponents.org
798
-	 *
799
-	 * @param mixed $value
800
-	 * @param mixed $type
801
-	 * @param string $placeHolder The name to bind with. The string must start with a colon ':'.
802
-	 *
803
-	 * @return IParameter
804
-	 * @since 8.2.0
805
-	 */
806
-	public function createNamedParameter($value, $type = self::PARAM_STR, $placeHolder = null);
807
-
808
-	/**
809
-	 * Creates a new positional parameter and bind the given value to it.
810
-	 *
811
-	 * Attention: If you are using positional parameters with the query builder you have
812
-	 * to be very careful to bind all parameters in the order they appear in the SQL
813
-	 * statement , otherwise they get bound in the wrong order which can lead to serious
814
-	 * bugs in your code.
815
-	 *
816
-	 * Example:
817
-	 * <code>
818
-	 *  $qb = $conn->getQueryBuilder();
819
-	 *  $qb->select('u.*')
820
-	 *     ->from('users', 'u')
821
-	 *     ->where('u.username = ' . $qb->createPositionalParameter('Foo', IQueryBuilder::PARAM_STR))
822
-	 *     ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', IQueryBuilder::PARAM_STR))
823
-	 * </code>
824
-	 *
825
-	 * @param mixed $value
826
-	 * @param integer $type
827
-	 *
828
-	 * @return IParameter
829
-	 * @since 8.2.0
830
-	 */
831
-	public function createPositionalParameter($value, $type = self::PARAM_STR);
832
-
833
-	/**
834
-	 * Creates a new parameter
835
-	 *
836
-	 * Example:
837
-	 * <code>
838
-	 *  $qb = $conn->getQueryBuilder();
839
-	 *  $qb->select('u.*')
840
-	 *     ->from('users', 'u')
841
-	 *     ->where('u.username = ' . $qb->createParameter('name'))
842
-	 *     ->setParameter('name', 'Bar', IQueryBuilder::PARAM_STR))
843
-	 * </code>
844
-	 *
845
-	 * @param string $name
846
-	 *
847
-	 * @return IParameter
848
-	 * @since 8.2.0
849
-	 */
850
-	public function createParameter($name);
851
-
852
-	/**
853
-	 * Creates a new function
854
-	 *
855
-	 * Attention: Column names inside the call have to be quoted before hand
856
-	 *
857
-	 * Example:
858
-	 * <code>
859
-	 *  $qb = $conn->getQueryBuilder();
860
-	 *  $qb->select($qb->createFunction('COUNT(*)'))
861
-	 *     ->from('users', 'u')
862
-	 *  echo $qb->getSQL(); // SELECT COUNT(*) FROM `users` u
863
-	 * </code>
864
-	 * <code>
865
-	 *  $qb = $conn->getQueryBuilder();
866
-	 *  $qb->select($qb->createFunction('COUNT(`column`)'))
867
-	 *     ->from('users', 'u')
868
-	 *  echo $qb->getSQL(); // SELECT COUNT(`column`) FROM `users` u
869
-	 * </code>
870
-	 *
871
-	 * @param string $call
872
-	 *
873
-	 * @return IQueryFunction
874
-	 * @since 8.2.0
875
-	 */
876
-	public function createFunction($call);
877
-
878
-	/**
879
-	 * Used to get the id of the last inserted element
880
-	 * @return int
881
-	 * @throws \BadMethodCallException When being called before an insert query has been run.
882
-	 * @since 9.0.0
883
-	 */
884
-	public function getLastInsertId();
885
-
886
-	/**
887
-	 * Returns the table name quoted and with database prefix as needed by the implementation
888
-	 *
889
-	 * @param string $table
890
-	 * @return string
891
-	 * @since 9.0.0
892
-	 */
893
-	public function getTableName($table);
894
-
895
-	/**
896
-	 * Returns the column name quoted and with table alias prefix as needed by the implementation
897
-	 *
898
-	 * @param string $column
899
-	 * @param string $tableAlias
900
-	 * @return string
901
-	 * @since 9.0.0
902
-	 */
903
-	public function getColumnName($column, $tableAlias = '');
37
+    /**
38
+     * @since 9.0.0
39
+     */
40
+    const PARAM_NULL = \PDO::PARAM_NULL;
41
+    /**
42
+     * @since 9.0.0
43
+     */
44
+    const PARAM_BOOL = \PDO::PARAM_BOOL;
45
+    /**
46
+     * @since 9.0.0
47
+     */
48
+    const PARAM_INT = \PDO::PARAM_INT;
49
+    /**
50
+     * @since 9.0.0
51
+     */
52
+    const PARAM_STR = \PDO::PARAM_STR;
53
+    /**
54
+     * @since 9.0.0
55
+     */
56
+    const PARAM_LOB = \PDO::PARAM_LOB;
57
+    /**
58
+     * @since 9.0.0
59
+     */
60
+    const PARAM_DATE = 'datetime';
61
+
62
+    /**
63
+     * @since 9.0.0
64
+     */
65
+    const PARAM_INT_ARRAY = Connection::PARAM_INT_ARRAY;
66
+    /**
67
+     * @since 9.0.0
68
+     */
69
+    const PARAM_STR_ARRAY = Connection::PARAM_STR_ARRAY;
70
+
71
+
72
+    /**
73
+     * Enable/disable automatic prefixing of table names with the oc_ prefix
74
+     *
75
+     * @param bool $enabled If set to true table names will be prefixed with the
76
+     * owncloud database prefix automatically.
77
+     * @since 8.2.0
78
+     */
79
+    public function automaticTablePrefix($enabled);
80
+
81
+    /**
82
+     * Gets an ExpressionBuilder used for object-oriented construction of query expressions.
83
+     * This producer method is intended for convenient inline usage. Example:
84
+     *
85
+     * <code>
86
+     *     $qb = $conn->getQueryBuilder()
87
+     *         ->select('u')
88
+     *         ->from('users', 'u')
89
+     *         ->where($qb->expr()->eq('u.id', 1));
90
+     * </code>
91
+     *
92
+     * For more complex expression construction, consider storing the expression
93
+     * builder object in a local variable.
94
+     *
95
+     * @return \OCP\DB\QueryBuilder\IExpressionBuilder
96
+     * @since 8.2.0
97
+     */
98
+    public function expr();
99
+
100
+    /**
101
+     * Gets an FunctionBuilder used for object-oriented construction of query functions.
102
+     * This producer method is intended for convenient inline usage. Example:
103
+     *
104
+     * <code>
105
+     *     $qb = $conn->getQueryBuilder()
106
+     *         ->select('u')
107
+     *         ->from('users', 'u')
108
+     *         ->where($qb->fun()->md5('u.id'));
109
+     * </code>
110
+     *
111
+     * For more complex function construction, consider storing the function
112
+     * builder object in a local variable.
113
+     *
114
+     * @return \OCP\DB\QueryBuilder\IFunctionBuilder
115
+     * @since 12.0.0
116
+     */
117
+    public function func();
118
+
119
+    /**
120
+     * Gets the type of the currently built query.
121
+     *
122
+     * @return integer
123
+     * @since 8.2.0
124
+     */
125
+    public function getType();
126
+
127
+    /**
128
+     * Gets the associated DBAL Connection for this query builder.
129
+     *
130
+     * @return \OCP\IDBConnection
131
+     * @since 8.2.0
132
+     */
133
+    public function getConnection();
134
+
135
+    /**
136
+     * Gets the state of this query builder instance.
137
+     *
138
+     * @return integer Either QueryBuilder::STATE_DIRTY or QueryBuilder::STATE_CLEAN.
139
+     * @since 8.2.0
140
+     */
141
+    public function getState();
142
+
143
+    /**
144
+     * Executes this query using the bound parameters and their types.
145
+     *
146
+     * Uses {@see Connection::executeQuery} for select statements and {@see Connection::executeUpdate}
147
+     * for insert, update and delete statements.
148
+     *
149
+     * @return \Doctrine\DBAL\Driver\Statement|int
150
+     * @since 8.2.0
151
+     */
152
+    public function execute();
153
+
154
+    /**
155
+     * Gets the complete SQL string formed by the current specifications of this QueryBuilder.
156
+     *
157
+     * <code>
158
+     *     $qb = $conn->getQueryBuilder()
159
+     *         ->select('u')
160
+     *         ->from('User', 'u')
161
+     *     echo $qb->getSQL(); // SELECT u FROM User u
162
+     * </code>
163
+     *
164
+     * @return string The SQL query string.
165
+     * @since 8.2.0
166
+     */
167
+    public function getSQL();
168
+
169
+    /**
170
+     * Sets a query parameter for the query being constructed.
171
+     *
172
+     * <code>
173
+     *     $qb = $conn->getQueryBuilder()
174
+     *         ->select('u')
175
+     *         ->from('users', 'u')
176
+     *         ->where('u.id = :user_id')
177
+     *         ->setParameter(':user_id', 1);
178
+     * </code>
179
+     *
180
+     * @param string|integer $key The parameter position or name.
181
+     * @param mixed $value The parameter value.
182
+     * @param string|null|int $type One of the IQueryBuilder::PARAM_* constants.
183
+     *
184
+     * @return $this This QueryBuilder instance.
185
+     * @since 8.2.0
186
+     */
187
+    public function setParameter($key, $value, $type = null);
188
+
189
+    /**
190
+     * Sets a collection of query parameters for the query being constructed.
191
+     *
192
+     * <code>
193
+     *     $qb = $conn->getQueryBuilder()
194
+     *         ->select('u')
195
+     *         ->from('users', 'u')
196
+     *         ->where('u.id = :user_id1 OR u.id = :user_id2')
197
+     *         ->setParameters(array(
198
+     *             ':user_id1' => 1,
199
+     *             ':user_id2' => 2
200
+     *         ));
201
+     * </code>
202
+     *
203
+     * @param array $params The query parameters to set.
204
+     * @param array $types The query parameters types to set.
205
+     *
206
+     * @return $this This QueryBuilder instance.
207
+     * @since 8.2.0
208
+     */
209
+    public function setParameters(array $params, array $types = []);
210
+
211
+    /**
212
+     * Gets all defined query parameters for the query being constructed indexed by parameter index or name.
213
+     *
214
+     * @return array The currently defined query parameters indexed by parameter index or name.
215
+     * @since 8.2.0
216
+     */
217
+    public function getParameters();
218
+
219
+    /**
220
+     * Gets a (previously set) query parameter of the query being constructed.
221
+     *
222
+     * @param mixed $key The key (index or name) of the bound parameter.
223
+     *
224
+     * @return mixed The value of the bound parameter.
225
+     * @since 8.2.0
226
+     */
227
+    public function getParameter($key);
228
+
229
+    /**
230
+     * Gets all defined query parameter types for the query being constructed indexed by parameter index or name.
231
+     *
232
+     * @return array The currently defined query parameter types indexed by parameter index or name.
233
+     * @since 8.2.0
234
+     */
235
+    public function getParameterTypes();
236
+
237
+    /**
238
+     * Gets a (previously set) query parameter type of the query being constructed.
239
+     *
240
+     * @param mixed $key The key (index or name) of the bound parameter type.
241
+     *
242
+     * @return mixed The value of the bound parameter type.
243
+     * @since 8.2.0
244
+     */
245
+    public function getParameterType($key);
246
+
247
+    /**
248
+     * Sets the position of the first result to retrieve (the "offset").
249
+     *
250
+     * @param integer $firstResult The first result to return.
251
+     *
252
+     * @return $this This QueryBuilder instance.
253
+     * @since 8.2.0
254
+     */
255
+    public function setFirstResult($firstResult);
256
+
257
+    /**
258
+     * Gets the position of the first result the query object was set to retrieve (the "offset").
259
+     * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder.
260
+     *
261
+     * @return integer The position of the first result.
262
+     * @since 8.2.0
263
+     */
264
+    public function getFirstResult();
265
+
266
+    /**
267
+     * Sets the maximum number of results to retrieve (the "limit").
268
+     *
269
+     * @param integer $maxResults The maximum number of results to retrieve.
270
+     *
271
+     * @return $this This QueryBuilder instance.
272
+     * @since 8.2.0
273
+     */
274
+    public function setMaxResults($maxResults);
275
+
276
+    /**
277
+     * Gets the maximum number of results the query object was set to retrieve (the "limit").
278
+     * Returns NULL if {@link setMaxResults} was not applied to this query builder.
279
+     *
280
+     * @return integer The maximum number of results.
281
+     * @since 8.2.0
282
+     */
283
+    public function getMaxResults();
284
+
285
+    /**
286
+     * Specifies an item that is to be returned in the query result.
287
+     * Replaces any previously specified selections, if any.
288
+     *
289
+     * <code>
290
+     *     $qb = $conn->getQueryBuilder()
291
+     *         ->select('u.id', 'p.id')
292
+     *         ->from('users', 'u')
293
+     *         ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
294
+     * </code>
295
+     *
296
+     * @param mixed ...$selects The selection expressions.
297
+     *
298
+     * @return $this This QueryBuilder instance.
299
+     * @since 8.2.0
300
+     */
301
+    public function select(...$selects);
302
+
303
+    /**
304
+     * Specifies an item that is to be returned with a different name in the query result.
305
+     *
306
+     * <code>
307
+     *     $qb = $conn->getQueryBuilder()
308
+     *         ->selectAlias('u.id', 'user_id')
309
+     *         ->from('users', 'u')
310
+     *         ->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id');
311
+     * </code>
312
+     *
313
+     * @param mixed $select The selection expressions.
314
+     * @param string $alias The column alias used in the constructed query.
315
+     *
316
+     * @return $this This QueryBuilder instance.
317
+     * @since 8.2.1
318
+     */
319
+    public function selectAlias($select, $alias);
320
+
321
+    /**
322
+     * Specifies an item that is to be returned uniquely in the query result.
323
+     *
324
+     * <code>
325
+     *     $qb = $conn->getQueryBuilder()
326
+     *         ->selectDistinct('type')
327
+     *         ->from('users');
328
+     * </code>
329
+     *
330
+     * @param mixed $select The selection expressions.
331
+     *
332
+     * @return $this This QueryBuilder instance.
333
+     * @since 9.0.0
334
+     */
335
+    public function selectDistinct($select);
336
+
337
+    /**
338
+     * Adds an item that is to be returned in the query result.
339
+     *
340
+     * <code>
341
+     *     $qb = $conn->getQueryBuilder()
342
+     *         ->select('u.id')
343
+     *         ->addSelect('p.id')
344
+     *         ->from('users', 'u')
345
+     *         ->leftJoin('u', 'phonenumbers', 'u.id = p.user_id');
346
+     * </code>
347
+     *
348
+     * @param mixed ...$select The selection expression.
349
+     *
350
+     * @return $this This QueryBuilder instance.
351
+     * @since 8.2.0
352
+     */
353
+    public function addSelect(...$select);
354
+
355
+    /**
356
+     * Turns the query being built into a bulk delete query that ranges over
357
+     * a certain table.
358
+     *
359
+     * <code>
360
+     *     $qb = $conn->getQueryBuilder()
361
+     *         ->delete('users', 'u')
362
+     *         ->where('u.id = :user_id');
363
+     *         ->setParameter(':user_id', 1);
364
+     * </code>
365
+     *
366
+     * @param string $delete The table whose rows are subject to the deletion.
367
+     * @param string $alias The table alias used in the constructed query.
368
+     *
369
+     * @return $this This QueryBuilder instance.
370
+     * @since 8.2.0
371
+     */
372
+    public function delete($delete = null, $alias = null);
373
+
374
+    /**
375
+     * Turns the query being built into a bulk update query that ranges over
376
+     * a certain table
377
+     *
378
+     * <code>
379
+     *     $qb = $conn->getQueryBuilder()
380
+     *         ->update('users', 'u')
381
+     *         ->set('u.password', md5('password'))
382
+     *         ->where('u.id = ?');
383
+     * </code>
384
+     *
385
+     * @param string $update The table whose rows are subject to the update.
386
+     * @param string $alias The table alias used in the constructed query.
387
+     *
388
+     * @return $this This QueryBuilder instance.
389
+     * @since 8.2.0
390
+     */
391
+    public function update($update = null, $alias = null);
392
+
393
+    /**
394
+     * Turns the query being built into an insert query that inserts into
395
+     * a certain table
396
+     *
397
+     * <code>
398
+     *     $qb = $conn->getQueryBuilder()
399
+     *         ->insert('users')
400
+     *         ->values(
401
+     *             array(
402
+     *                 'name' => '?',
403
+     *                 'password' => '?'
404
+     *             )
405
+     *         );
406
+     * </code>
407
+     *
408
+     * @param string $insert The table into which the rows should be inserted.
409
+     *
410
+     * @return $this This QueryBuilder instance.
411
+     * @since 8.2.0
412
+     */
413
+    public function insert($insert = null);
414
+
415
+    /**
416
+     * Creates and adds a query root corresponding to the table identified by the
417
+     * given alias, forming a cartesian product with any existing query roots.
418
+     *
419
+     * <code>
420
+     *     $qb = $conn->getQueryBuilder()
421
+     *         ->select('u.id')
422
+     *         ->from('users', 'u')
423
+     * </code>
424
+     *
425
+     * @param string $from The table.
426
+     * @param string|null $alias The alias of the table.
427
+     *
428
+     * @return $this This QueryBuilder instance.
429
+     * @since 8.2.0
430
+     */
431
+    public function from($from, $alias = null);
432
+
433
+    /**
434
+     * Creates and adds a join to the query.
435
+     *
436
+     * <code>
437
+     *     $qb = $conn->getQueryBuilder()
438
+     *         ->select('u.name')
439
+     *         ->from('users', 'u')
440
+     *         ->join('u', 'phonenumbers', 'p', 'p.is_primary = 1');
441
+     * </code>
442
+     *
443
+     * @param string $fromAlias The alias that points to a from clause.
444
+     * @param string $join The table name to join.
445
+     * @param string $alias The alias of the join table.
446
+     * @param string $condition The condition for the join.
447
+     *
448
+     * @return $this This QueryBuilder instance.
449
+     * @since 8.2.0
450
+     */
451
+    public function join($fromAlias, $join, $alias, $condition = null);
452
+
453
+    /**
454
+     * Creates and adds a join to the query.
455
+     *
456
+     * <code>
457
+     *     $qb = $conn->getQueryBuilder()
458
+     *         ->select('u.name')
459
+     *         ->from('users', 'u')
460
+     *         ->innerJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
461
+     * </code>
462
+     *
463
+     * @param string $fromAlias The alias that points to a from clause.
464
+     * @param string $join The table name to join.
465
+     * @param string $alias The alias of the join table.
466
+     * @param string $condition The condition for the join.
467
+     *
468
+     * @return $this This QueryBuilder instance.
469
+     * @since 8.2.0
470
+     */
471
+    public function innerJoin($fromAlias, $join, $alias, $condition = null);
472
+
473
+    /**
474
+     * Creates and adds a left join to the query.
475
+     *
476
+     * <code>
477
+     *     $qb = $conn->getQueryBuilder()
478
+     *         ->select('u.name')
479
+     *         ->from('users', 'u')
480
+     *         ->leftJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
481
+     * </code>
482
+     *
483
+     * @param string $fromAlias The alias that points to a from clause.
484
+     * @param string $join The table name to join.
485
+     * @param string $alias The alias of the join table.
486
+     * @param string $condition The condition for the join.
487
+     *
488
+     * @return $this This QueryBuilder instance.
489
+     * @since 8.2.0
490
+     */
491
+    public function leftJoin($fromAlias, $join, $alias, $condition = null);
492
+
493
+    /**
494
+     * Creates and adds a right join to the query.
495
+     *
496
+     * <code>
497
+     *     $qb = $conn->getQueryBuilder()
498
+     *         ->select('u.name')
499
+     *         ->from('users', 'u')
500
+     *         ->rightJoin('u', 'phonenumbers', 'p', 'p.is_primary = 1');
501
+     * </code>
502
+     *
503
+     * @param string $fromAlias The alias that points to a from clause.
504
+     * @param string $join The table name to join.
505
+     * @param string $alias The alias of the join table.
506
+     * @param string $condition The condition for the join.
507
+     *
508
+     * @return $this This QueryBuilder instance.
509
+     * @since 8.2.0
510
+     */
511
+    public function rightJoin($fromAlias, $join, $alias, $condition = null);
512
+
513
+    /**
514
+     * Sets a new value for a column in a bulk update query.
515
+     *
516
+     * <code>
517
+     *     $qb = $conn->getQueryBuilder()
518
+     *         ->update('users', 'u')
519
+     *         ->set('u.password', md5('password'))
520
+     *         ->where('u.id = ?');
521
+     * </code>
522
+     *
523
+     * @param string $key The column to set.
524
+     * @param string $value The value, expression, placeholder, etc.
525
+     *
526
+     * @return $this This QueryBuilder instance.
527
+     * @since 8.2.0
528
+     */
529
+    public function set($key, $value);
530
+
531
+    /**
532
+     * Specifies one or more restrictions to the query result.
533
+     * Replaces any previously specified restrictions, if any.
534
+     *
535
+     * <code>
536
+     *     $qb = $conn->getQueryBuilder()
537
+     *         ->select('u.name')
538
+     *         ->from('users', 'u')
539
+     *         ->where('u.id = ?');
540
+     *
541
+     *     // You can optionally programatically build and/or expressions
542
+     *     $qb = $conn->getQueryBuilder();
543
+     *
544
+     *     $or = $qb->expr()->orx();
545
+     *     $or->add($qb->expr()->eq('u.id', 1));
546
+     *     $or->add($qb->expr()->eq('u.id', 2));
547
+     *
548
+     *     $qb->update('users', 'u')
549
+     *         ->set('u.password', md5('password'))
550
+     *         ->where($or);
551
+     * </code>
552
+     *
553
+     * @param mixed $predicates The restriction predicates.
554
+     *
555
+     * @return $this This QueryBuilder instance.
556
+     * @since 8.2.0
557
+     */
558
+    public function where(...$predicates);
559
+
560
+    /**
561
+     * Adds one or more restrictions to the query results, forming a logical
562
+     * conjunction with any previously specified restrictions.
563
+     *
564
+     * <code>
565
+     *     $qb = $conn->getQueryBuilder()
566
+     *         ->select('u')
567
+     *         ->from('users', 'u')
568
+     *         ->where('u.username LIKE ?')
569
+     *         ->andWhere('u.is_active = 1');
570
+     * </code>
571
+     *
572
+     * @param mixed ...$where The query restrictions.
573
+     *
574
+     * @return $this This QueryBuilder instance.
575
+     *
576
+     * @see where()
577
+     * @since 8.2.0
578
+     */
579
+    public function andWhere(...$where);
580
+
581
+    /**
582
+     * Adds one or more restrictions to the query results, forming a logical
583
+     * disjunction with any previously specified restrictions.
584
+     *
585
+     * <code>
586
+     *     $qb = $conn->getQueryBuilder()
587
+     *         ->select('u.name')
588
+     *         ->from('users', 'u')
589
+     *         ->where('u.id = 1')
590
+     *         ->orWhere('u.id = 2');
591
+     * </code>
592
+     *
593
+     * @param mixed ...$where The WHERE statement.
594
+     *
595
+     * @return $this This QueryBuilder instance.
596
+     *
597
+     * @see where()
598
+     * @since 8.2.0
599
+     */
600
+    public function orWhere(...$where);
601
+
602
+    /**
603
+     * Specifies a grouping over the results of the query.
604
+     * Replaces any previously specified groupings, if any.
605
+     *
606
+     * <code>
607
+     *     $qb = $conn->getQueryBuilder()
608
+     *         ->select('u.name')
609
+     *         ->from('users', 'u')
610
+     *         ->groupBy('u.id');
611
+     * </code>
612
+     *
613
+     * @param mixed ...$groupBys The grouping expression.
614
+     *
615
+     * @return $this This QueryBuilder instance.
616
+     * @since 8.2.0
617
+     */
618
+    public function groupBy(...$groupBys);
619
+
620
+    /**
621
+     * Adds a grouping expression to the query.
622
+     *
623
+     * <code>
624
+     *     $qb = $conn->getQueryBuilder()
625
+     *         ->select('u.name')
626
+     *         ->from('users', 'u')
627
+     *         ->groupBy('u.lastLogin');
628
+     *         ->addGroupBy('u.createdAt')
629
+     * </code>
630
+     *
631
+     * @param mixed ...$groupBy The grouping expression.
632
+     *
633
+     * @return $this This QueryBuilder instance.
634
+     * @since 8.2.0
635
+     */
636
+    public function addGroupBy(...$groupBy);
637
+
638
+    /**
639
+     * Sets a value for a column in an insert query.
640
+     *
641
+     * <code>
642
+     *     $qb = $conn->getQueryBuilder()
643
+     *         ->insert('users')
644
+     *         ->values(
645
+     *             array(
646
+     *                 'name' => '?'
647
+     *             )
648
+     *         )
649
+     *         ->setValue('password', '?');
650
+     * </code>
651
+     *
652
+     * @param string $column The column into which the value should be inserted.
653
+     * @param string $value The value that should be inserted into the column.
654
+     *
655
+     * @return $this This QueryBuilder instance.
656
+     * @since 8.2.0
657
+     */
658
+    public function setValue($column, $value);
659
+
660
+    /**
661
+     * Specifies values for an insert query indexed by column names.
662
+     * Replaces any previous values, if any.
663
+     *
664
+     * <code>
665
+     *     $qb = $conn->getQueryBuilder()
666
+     *         ->insert('users')
667
+     *         ->values(
668
+     *             array(
669
+     *                 'name' => '?',
670
+     *                 'password' => '?'
671
+     *             )
672
+     *         );
673
+     * </code>
674
+     *
675
+     * @param array $values The values to specify for the insert query indexed by column names.
676
+     *
677
+     * @return $this This QueryBuilder instance.
678
+     * @since 8.2.0
679
+     */
680
+    public function values(array $values);
681
+
682
+    /**
683
+     * Specifies a restriction over the groups of the query.
684
+     * Replaces any previous having restrictions, if any.
685
+     *
686
+     * @param mixed ...$having The restriction over the groups.
687
+     *
688
+     * @return $this This QueryBuilder instance.
689
+     * @since 8.2.0
690
+     */
691
+    public function having(...$having);
692
+
693
+    /**
694
+     * Adds a restriction over the groups of the query, forming a logical
695
+     * conjunction with any existing having restrictions.
696
+     *
697
+     * @param mixed ...$having The restriction to append.
698
+     *
699
+     * @return $this This QueryBuilder instance.
700
+     * @since 8.2.0
701
+     */
702
+    public function andHaving(...$having);
703
+
704
+    /**
705
+     * Adds a restriction over the groups of the query, forming a logical
706
+     * disjunction with any existing having restrictions.
707
+     *
708
+     * @param mixed ...$having The restriction to add.
709
+     *
710
+     * @return $this This QueryBuilder instance.
711
+     * @since 8.2.0
712
+     */
713
+    public function orHaving(...$having);
714
+
715
+    /**
716
+     * Specifies an ordering for the query results.
717
+     * Replaces any previously specified orderings, if any.
718
+     *
719
+     * @param string $sort The ordering expression.
720
+     * @param string $order The ordering direction.
721
+     *
722
+     * @return $this This QueryBuilder instance.
723
+     * @since 8.2.0
724
+     */
725
+    public function orderBy($sort, $order = null);
726
+
727
+    /**
728
+     * Adds an ordering to the query results.
729
+     *
730
+     * @param string $sort The ordering expression.
731
+     * @param string $order The ordering direction.
732
+     *
733
+     * @return $this This QueryBuilder instance.
734
+     * @since 8.2.0
735
+     */
736
+    public function addOrderBy($sort, $order = null);
737
+
738
+    /**
739
+     * Gets a query part by its name.
740
+     *
741
+     * @param string $queryPartName
742
+     *
743
+     * @return mixed
744
+     * @since 8.2.0
745
+     */
746
+    public function getQueryPart($queryPartName);
747
+
748
+    /**
749
+     * Gets all query parts.
750
+     *
751
+     * @return array
752
+     * @since 8.2.0
753
+     */
754
+    public function getQueryParts();
755
+
756
+    /**
757
+     * Resets SQL parts.
758
+     *
759
+     * @param array|null $queryPartNames
760
+     *
761
+     * @return $this This QueryBuilder instance.
762
+     * @since 8.2.0
763
+     */
764
+    public function resetQueryParts($queryPartNames = null);
765
+
766
+    /**
767
+     * Resets a single SQL part.
768
+     *
769
+     * @param string $queryPartName
770
+     *
771
+     * @return $this This QueryBuilder instance.
772
+     * @since 8.2.0
773
+     */
774
+    public function resetQueryPart($queryPartName);
775
+
776
+    /**
777
+     * Creates a new named parameter and bind the value $value to it.
778
+     *
779
+     * This method provides a shortcut for PDOStatement::bindValue
780
+     * when using prepared statements.
781
+     *
782
+     * The parameter $value specifies the value that you want to bind. If
783
+     * $placeholder is not provided bindValue() will automatically create a
784
+     * placeholder for you. An automatic placeholder will be of the name
785
+     * ':dcValue1', ':dcValue2' etc.
786
+     *
787
+     * For more information see {@link http://php.net/pdostatement-bindparam}
788
+     *
789
+     * Example:
790
+     * <code>
791
+     * $value = 2;
792
+     * $q->eq( 'id', $q->bindValue( $value ) );
793
+     * $stmt = $q->executeQuery(); // executed with 'id = 2'
794
+     * </code>
795
+     *
796
+     * @license New BSD License
797
+     * @link http://www.zetacomponents.org
798
+     *
799
+     * @param mixed $value
800
+     * @param mixed $type
801
+     * @param string $placeHolder The name to bind with. The string must start with a colon ':'.
802
+     *
803
+     * @return IParameter
804
+     * @since 8.2.0
805
+     */
806
+    public function createNamedParameter($value, $type = self::PARAM_STR, $placeHolder = null);
807
+
808
+    /**
809
+     * Creates a new positional parameter and bind the given value to it.
810
+     *
811
+     * Attention: If you are using positional parameters with the query builder you have
812
+     * to be very careful to bind all parameters in the order they appear in the SQL
813
+     * statement , otherwise they get bound in the wrong order which can lead to serious
814
+     * bugs in your code.
815
+     *
816
+     * Example:
817
+     * <code>
818
+     *  $qb = $conn->getQueryBuilder();
819
+     *  $qb->select('u.*')
820
+     *     ->from('users', 'u')
821
+     *     ->where('u.username = ' . $qb->createPositionalParameter('Foo', IQueryBuilder::PARAM_STR))
822
+     *     ->orWhere('u.username = ' . $qb->createPositionalParameter('Bar', IQueryBuilder::PARAM_STR))
823
+     * </code>
824
+     *
825
+     * @param mixed $value
826
+     * @param integer $type
827
+     *
828
+     * @return IParameter
829
+     * @since 8.2.0
830
+     */
831
+    public function createPositionalParameter($value, $type = self::PARAM_STR);
832
+
833
+    /**
834
+     * Creates a new parameter
835
+     *
836
+     * Example:
837
+     * <code>
838
+     *  $qb = $conn->getQueryBuilder();
839
+     *  $qb->select('u.*')
840
+     *     ->from('users', 'u')
841
+     *     ->where('u.username = ' . $qb->createParameter('name'))
842
+     *     ->setParameter('name', 'Bar', IQueryBuilder::PARAM_STR))
843
+     * </code>
844
+     *
845
+     * @param string $name
846
+     *
847
+     * @return IParameter
848
+     * @since 8.2.0
849
+     */
850
+    public function createParameter($name);
851
+
852
+    /**
853
+     * Creates a new function
854
+     *
855
+     * Attention: Column names inside the call have to be quoted before hand
856
+     *
857
+     * Example:
858
+     * <code>
859
+     *  $qb = $conn->getQueryBuilder();
860
+     *  $qb->select($qb->createFunction('COUNT(*)'))
861
+     *     ->from('users', 'u')
862
+     *  echo $qb->getSQL(); // SELECT COUNT(*) FROM `users` u
863
+     * </code>
864
+     * <code>
865
+     *  $qb = $conn->getQueryBuilder();
866
+     *  $qb->select($qb->createFunction('COUNT(`column`)'))
867
+     *     ->from('users', 'u')
868
+     *  echo $qb->getSQL(); // SELECT COUNT(`column`) FROM `users` u
869
+     * </code>
870
+     *
871
+     * @param string $call
872
+     *
873
+     * @return IQueryFunction
874
+     * @since 8.2.0
875
+     */
876
+    public function createFunction($call);
877
+
878
+    /**
879
+     * Used to get the id of the last inserted element
880
+     * @return int
881
+     * @throws \BadMethodCallException When being called before an insert query has been run.
882
+     * @since 9.0.0
883
+     */
884
+    public function getLastInsertId();
885
+
886
+    /**
887
+     * Returns the table name quoted and with database prefix as needed by the implementation
888
+     *
889
+     * @param string $table
890
+     * @return string
891
+     * @since 9.0.0
892
+     */
893
+    public function getTableName($table);
894
+
895
+    /**
896
+     * Returns the column name quoted and with table alias prefix as needed by the implementation
897
+     *
898
+     * @param string $column
899
+     * @param string $tableAlias
900
+     * @return string
901
+     * @since 9.0.0
902
+     */
903
+    public function getColumnName($column, $tableAlias = '');
904 904
 }
Please login to merge, or discard this patch.
lib/public/ISearch.php 1 patch
Indentation   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -33,36 +33,36 @@
 block discarded – undo
33 33
  */
34 34
 interface ISearch {
35 35
 
36
-	/**
37
-	 * Search all providers for $query
38
-	 * @param string $query
39
-	 * @param string[] $inApps optionally limit results to the given apps
40
-	 * @param int $page pages start at page 1
41
-	 * @param int $size
42
-	 * @return array An array of OCP\Search\Result's
43
-	 * @since 8.0.0
44
-	 */
45
-	public function searchPaged($query, array $inApps = [], $page = 1, $size = 30);
36
+    /**
37
+     * Search all providers for $query
38
+     * @param string $query
39
+     * @param string[] $inApps optionally limit results to the given apps
40
+     * @param int $page pages start at page 1
41
+     * @param int $size
42
+     * @return array An array of OCP\Search\Result's
43
+     * @since 8.0.0
44
+     */
45
+    public function searchPaged($query, array $inApps = [], $page = 1, $size = 30);
46 46
 
47
-	/**
48
-	 * Register a new search provider to search with
49
-	 * @param string $class class name of a OCP\Search\Provider
50
-	 * @param array $options optional
51
-	 * @since 7.0.0
52
-	 */
53
-	public function registerProvider($class, array $options = []);
47
+    /**
48
+     * Register a new search provider to search with
49
+     * @param string $class class name of a OCP\Search\Provider
50
+     * @param array $options optional
51
+     * @since 7.0.0
52
+     */
53
+    public function registerProvider($class, array $options = []);
54 54
 
55
-	/**
56
-	 * Remove one existing search provider
57
-	 * @param string $provider class name of a OCP\Search\Provider
58
-	 * @since 7.0.0
59
-	 */
60
-	public function removeProvider($provider);
55
+    /**
56
+     * Remove one existing search provider
57
+     * @param string $provider class name of a OCP\Search\Provider
58
+     * @since 7.0.0
59
+     */
60
+    public function removeProvider($provider);
61 61
 
62
-	/**
63
-	 * Remove all registered search providers
64
-	 * @since 7.0.0
65
-	 */
66
-	public function clearProviders();
62
+    /**
63
+     * Remove all registered search providers
64
+     * @since 7.0.0
65
+     */
66
+    public function clearProviders();
67 67
 
68 68
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/Template/PublicTemplateResponse.php 1 patch
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -35,125 +35,125 @@
 block discarded – undo
35 35
  */
36 36
 class PublicTemplateResponse extends TemplateResponse {
37 37
 
38
-	private $headerTitle = '';
39
-	private $headerDetails = '';
40
-	private $headerActions = [];
41
-	private $footerVisible = true;
42
-
43
-	/**
44
-	 * PublicTemplateResponse constructor.
45
-	 *
46
-	 * @param string $appName
47
-	 * @param string $templateName
48
-	 * @param array $params
49
-	 * @since 14.0.0
50
-	 */
51
-	public function __construct(string $appName, string $templateName, array $params = []) {
52
-		parent::__construct($appName, $templateName, $params, 'public');
53
-		\OC_Util::addScript('core', 'public/publicpage');
54
-	}
55
-
56
-	/**
57
-	 * @param string $title
58
-	 * @since 14.0.0
59
-	 */
60
-	public function setHeaderTitle(string $title) {
61
-		$this->headerTitle = $title;
62
-	}
63
-
64
-	/**
65
-	 * @return string
66
-	 * @since 14.0.0
67
-	 */
68
-	public function getHeaderTitle(): string {
69
-		return $this->headerTitle;
70
-	}
71
-
72
-	/**
73
-	 * @param string $details
74
-	 * @since 14.0.0
75
-	 */
76
-	public function setHeaderDetails(string $details) {
77
-		$this->headerDetails = $details;
78
-	}
79
-
80
-	/**
81
-	 * @return string
82
-	 * @since 14.0.0
83
-	 */
84
-	public function getHeaderDetails(): string {
85
-		return $this->headerDetails;
86
-	}
87
-
88
-	/**
89
-	 * @param array $actions
90
-	 * @since 14.0.0
91
-	 * @throws InvalidArgumentException
92
-	 */
93
-	public function setHeaderActions(array $actions) {
94
-		foreach ($actions as $action) {
95
-			if ($actions instanceof IMenuAction) {
96
-				throw new InvalidArgumentException('Actions must be of type IMenuAction');
97
-			}
98
-			$this->headerActions[] = $action;
99
-		}
100
-		usort($this->headerActions, function(IMenuAction $a, IMenuAction $b) {
101
-			return $a->getPriority() > $b->getPriority();
102
-		});
103
-	}
104
-
105
-	/**
106
-	 * @return IMenuAction
107
-	 * @since 14.0.0
108
-	 * @throws \Exception
109
-	 */
110
-	public function getPrimaryAction(): IMenuAction {
111
-		if ($this->getActionCount() > 0) {
112
-			return $this->headerActions[0];
113
-		}
114
-		throw new \Exception('No header actions have been set');
115
-	}
116
-
117
-	/**
118
-	 * @return int
119
-	 * @since 14.0.0
120
-	 */
121
-	public function getActionCount(): int {
122
-		return count($this->headerActions);
123
-	}
124
-
125
-	/**
126
-	 * @return IMenuAction[]
127
-	 * @since 14.0.0
128
-	 */
129
-	public function getOtherActions(): array {
130
-		return array_slice($this->headerActions, 1);
131
-	}
132
-
133
-	/**
134
-	 * @since 14.0.0
135
-	 */
136
-	public function setFooterVisible(bool $visible = false) {
137
-		$this->footerVisible = $visible;
138
-	}
139
-
140
-	/**
141
-	 * @since 14.0.0
142
-	 */
143
-	public function getFooterVisible(): bool {
144
-		return $this->footerVisible;
145
-	}
146
-
147
-	/**
148
-	 * @return string
149
-	 * @since 14.0.0
150
-	 */
151
-	public function render(): string {
152
-		$params = array_merge($this->getParams(), [
153
-			'template' => $this,
154
-		]);
155
-		$this->setParams($params);
156
-		return  parent::render();
157
-	}
38
+    private $headerTitle = '';
39
+    private $headerDetails = '';
40
+    private $headerActions = [];
41
+    private $footerVisible = true;
42
+
43
+    /**
44
+     * PublicTemplateResponse constructor.
45
+     *
46
+     * @param string $appName
47
+     * @param string $templateName
48
+     * @param array $params
49
+     * @since 14.0.0
50
+     */
51
+    public function __construct(string $appName, string $templateName, array $params = []) {
52
+        parent::__construct($appName, $templateName, $params, 'public');
53
+        \OC_Util::addScript('core', 'public/publicpage');
54
+    }
55
+
56
+    /**
57
+     * @param string $title
58
+     * @since 14.0.0
59
+     */
60
+    public function setHeaderTitle(string $title) {
61
+        $this->headerTitle = $title;
62
+    }
63
+
64
+    /**
65
+     * @return string
66
+     * @since 14.0.0
67
+     */
68
+    public function getHeaderTitle(): string {
69
+        return $this->headerTitle;
70
+    }
71
+
72
+    /**
73
+     * @param string $details
74
+     * @since 14.0.0
75
+     */
76
+    public function setHeaderDetails(string $details) {
77
+        $this->headerDetails = $details;
78
+    }
79
+
80
+    /**
81
+     * @return string
82
+     * @since 14.0.0
83
+     */
84
+    public function getHeaderDetails(): string {
85
+        return $this->headerDetails;
86
+    }
87
+
88
+    /**
89
+     * @param array $actions
90
+     * @since 14.0.0
91
+     * @throws InvalidArgumentException
92
+     */
93
+    public function setHeaderActions(array $actions) {
94
+        foreach ($actions as $action) {
95
+            if ($actions instanceof IMenuAction) {
96
+                throw new InvalidArgumentException('Actions must be of type IMenuAction');
97
+            }
98
+            $this->headerActions[] = $action;
99
+        }
100
+        usort($this->headerActions, function(IMenuAction $a, IMenuAction $b) {
101
+            return $a->getPriority() > $b->getPriority();
102
+        });
103
+    }
104
+
105
+    /**
106
+     * @return IMenuAction
107
+     * @since 14.0.0
108
+     * @throws \Exception
109
+     */
110
+    public function getPrimaryAction(): IMenuAction {
111
+        if ($this->getActionCount() > 0) {
112
+            return $this->headerActions[0];
113
+        }
114
+        throw new \Exception('No header actions have been set');
115
+    }
116
+
117
+    /**
118
+     * @return int
119
+     * @since 14.0.0
120
+     */
121
+    public function getActionCount(): int {
122
+        return count($this->headerActions);
123
+    }
124
+
125
+    /**
126
+     * @return IMenuAction[]
127
+     * @since 14.0.0
128
+     */
129
+    public function getOtherActions(): array {
130
+        return array_slice($this->headerActions, 1);
131
+    }
132
+
133
+    /**
134
+     * @since 14.0.0
135
+     */
136
+    public function setFooterVisible(bool $visible = false) {
137
+        $this->footerVisible = $visible;
138
+    }
139
+
140
+    /**
141
+     * @since 14.0.0
142
+     */
143
+    public function getFooterVisible(): bool {
144
+        return $this->footerVisible;
145
+    }
146
+
147
+    /**
148
+     * @return string
149
+     * @since 14.0.0
150
+     */
151
+    public function render(): string {
152
+        $params = array_merge($this->getParams(), [
153
+            'template' => $this,
154
+        ]);
155
+        $this->setParams($params);
156
+        return  parent::render();
157
+    }
158 158
 
159 159
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/TemplateResponse.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -39,132 +39,132 @@
 block discarded – undo
39 39
  */
40 40
 class TemplateResponse extends Response {
41 41
 
42
-	const EVENT_LOAD_ADDITIONAL_SCRIPTS = self::class . '::loadAdditionalScripts';
43
-	const EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN = self::class . '::loadAdditionalScriptsLoggedIn';
44
-
45
-	/**
46
-	 * name of the template
47
-	 * @var string
48
-	 */
49
-	protected $templateName;
50
-
51
-	/**
52
-	 * parameters
53
-	 * @var array
54
-	 */
55
-	protected $params;
56
-
57
-	/**
58
-	 * rendering type (admin, user, blank)
59
-	 * @var string
60
-	 */
61
-	protected $renderAs;
62
-
63
-	/**
64
-	 * app name
65
-	 * @var string
66
-	 */
67
-	protected $appName;
68
-
69
-	/**
70
-	 * constructor of TemplateResponse
71
-	 * @param string $appName the name of the app to load the template from
72
-	 * @param string $templateName the name of the template
73
-	 * @param array $params an array of parameters which should be passed to the
74
-	 * template
75
-	 * @param string $renderAs how the page should be rendered, defaults to user
76
-	 * @since 6.0.0 - parameters $params and $renderAs were added in 7.0.0
77
-	 */
78
-	public function __construct($appName, $templateName, array $params=[],
79
-	                            $renderAs='user') {
80
-		parent::__construct();
81
-
82
-		$this->templateName = $templateName;
83
-		$this->appName = $appName;
84
-		$this->params = $params;
85
-		$this->renderAs = $renderAs;
86
-
87
-		$this->setContentSecurityPolicy(new ContentSecurityPolicy());
88
-		$this->setFeaturePolicy(new FeaturePolicy());
89
-	}
90
-
91
-
92
-	/**
93
-	 * Sets template parameters
94
-	 * @param array $params an array with key => value structure which sets template
95
-	 *                      variables
96
-	 * @return TemplateResponse Reference to this object
97
-	 * @since 6.0.0 - return value was added in 7.0.0
98
-	 */
99
-	public function setParams(array $params){
100
-		$this->params = $params;
101
-
102
-		return $this;
103
-	}
104
-
105
-
106
-	/**
107
-	 * Used for accessing the set parameters
108
-	 * @return array the params
109
-	 * @since 6.0.0
110
-	 */
111
-	public function getParams(){
112
-		return $this->params;
113
-	}
114
-
115
-
116
-	/**
117
-	 * Used for accessing the name of the set template
118
-	 * @return string the name of the used template
119
-	 * @since 6.0.0
120
-	 */
121
-	public function getTemplateName(){
122
-		return $this->templateName;
123
-	}
124
-
125
-
126
-	/**
127
-	 * Sets the template page
128
-	 * @param string $renderAs admin, user or blank. Admin also prints the admin
129
-	 *                         settings header and footer, user renders the normal
130
-	 *                         normal page including footer and header and blank
131
-	 *                         just renders the plain template
132
-	 * @return TemplateResponse Reference to this object
133
-	 * @since 6.0.0 - return value was added in 7.0.0
134
-	 */
135
-	public function renderAs($renderAs){
136
-		$this->renderAs = $renderAs;
137
-
138
-		return $this;
139
-	}
140
-
141
-
142
-	/**
143
-	 * Returns the set renderAs
144
-	 * @return string the renderAs value
145
-	 * @since 6.0.0
146
-	 */
147
-	public function getRenderAs(){
148
-		return $this->renderAs;
149
-	}
150
-
151
-
152
-	/**
153
-	 * Returns the rendered html
154
-	 * @return string the rendered html
155
-	 * @since 6.0.0
156
-	 */
157
-	public function render(){
158
-		// \OCP\Template needs an empty string instead of 'blank' for an unwrapped response
159
-		$renderAs = $this->renderAs === 'blank' ? '' : $this->renderAs;
160
-
161
-		$template = new \OCP\Template($this->appName, $this->templateName, $renderAs);
162
-
163
-		foreach($this->params as $key => $value){
164
-			$template->assign($key, $value);
165
-		}
166
-
167
-		return $template->fetchPage($this->params);
168
-	}
42
+    const EVENT_LOAD_ADDITIONAL_SCRIPTS = self::class . '::loadAdditionalScripts';
43
+    const EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN = self::class . '::loadAdditionalScriptsLoggedIn';
44
+
45
+    /**
46
+     * name of the template
47
+     * @var string
48
+     */
49
+    protected $templateName;
50
+
51
+    /**
52
+     * parameters
53
+     * @var array
54
+     */
55
+    protected $params;
56
+
57
+    /**
58
+     * rendering type (admin, user, blank)
59
+     * @var string
60
+     */
61
+    protected $renderAs;
62
+
63
+    /**
64
+     * app name
65
+     * @var string
66
+     */
67
+    protected $appName;
68
+
69
+    /**
70
+     * constructor of TemplateResponse
71
+     * @param string $appName the name of the app to load the template from
72
+     * @param string $templateName the name of the template
73
+     * @param array $params an array of parameters which should be passed to the
74
+     * template
75
+     * @param string $renderAs how the page should be rendered, defaults to user
76
+     * @since 6.0.0 - parameters $params and $renderAs were added in 7.0.0
77
+     */
78
+    public function __construct($appName, $templateName, array $params=[],
79
+                                $renderAs='user') {
80
+        parent::__construct();
81
+
82
+        $this->templateName = $templateName;
83
+        $this->appName = $appName;
84
+        $this->params = $params;
85
+        $this->renderAs = $renderAs;
86
+
87
+        $this->setContentSecurityPolicy(new ContentSecurityPolicy());
88
+        $this->setFeaturePolicy(new FeaturePolicy());
89
+    }
90
+
91
+
92
+    /**
93
+     * Sets template parameters
94
+     * @param array $params an array with key => value structure which sets template
95
+     *                      variables
96
+     * @return TemplateResponse Reference to this object
97
+     * @since 6.0.0 - return value was added in 7.0.0
98
+     */
99
+    public function setParams(array $params){
100
+        $this->params = $params;
101
+
102
+        return $this;
103
+    }
104
+
105
+
106
+    /**
107
+     * Used for accessing the set parameters
108
+     * @return array the params
109
+     * @since 6.0.0
110
+     */
111
+    public function getParams(){
112
+        return $this->params;
113
+    }
114
+
115
+
116
+    /**
117
+     * Used for accessing the name of the set template
118
+     * @return string the name of the used template
119
+     * @since 6.0.0
120
+     */
121
+    public function getTemplateName(){
122
+        return $this->templateName;
123
+    }
124
+
125
+
126
+    /**
127
+     * Sets the template page
128
+     * @param string $renderAs admin, user or blank. Admin also prints the admin
129
+     *                         settings header and footer, user renders the normal
130
+     *                         normal page including footer and header and blank
131
+     *                         just renders the plain template
132
+     * @return TemplateResponse Reference to this object
133
+     * @since 6.0.0 - return value was added in 7.0.0
134
+     */
135
+    public function renderAs($renderAs){
136
+        $this->renderAs = $renderAs;
137
+
138
+        return $this;
139
+    }
140
+
141
+
142
+    /**
143
+     * Returns the set renderAs
144
+     * @return string the renderAs value
145
+     * @since 6.0.0
146
+     */
147
+    public function getRenderAs(){
148
+        return $this->renderAs;
149
+    }
150
+
151
+
152
+    /**
153
+     * Returns the rendered html
154
+     * @return string the rendered html
155
+     * @since 6.0.0
156
+     */
157
+    public function render(){
158
+        // \OCP\Template needs an empty string instead of 'blank' for an unwrapped response
159
+        $renderAs = $this->renderAs === 'blank' ? '' : $this->renderAs;
160
+
161
+        $template = new \OCP\Template($this->appName, $this->templateName, $renderAs);
162
+
163
+        foreach($this->params as $key => $value){
164
+            $template->assign($key, $value);
165
+        }
166
+
167
+        return $template->fetchPage($this->params);
168
+    }
169 169
 
170 170
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/JSONResponse.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -40,65 +40,65 @@
 block discarded – undo
40 40
  */
41 41
 class JSONResponse extends Response {
42 42
 
43
-	/**
44
-	 * response data
45
-	 * @var array|object
46
-	 */
47
-	protected $data;
48
-
49
-
50
-	/**
51
-	 * constructor of JSONResponse
52
-	 * @param array|object $data the object or array that should be transformed
53
-	 * @param int $statusCode the Http status code, defaults to 200
54
-	 * @since 6.0.0
55
-	 */
56
-	public function __construct($data=[], $statusCode=Http::STATUS_OK) {
57
-		parent::__construct();
58
-
59
-		$this->data = $data;
60
-		$this->setStatus($statusCode);
61
-		$this->addHeader('Content-Type', 'application/json; charset=utf-8');
62
-	}
63
-
64
-
65
-	/**
66
-	 * Returns the rendered json
67
-	 * @return string the rendered json
68
-	 * @since 6.0.0
69
-	 * @throws \Exception If data could not get encoded
70
-	 */
71
-	public function render() {
72
-		$response = json_encode($this->data, JSON_HEX_TAG);
73
-		if($response === false) {
74
-			throw new \Exception(sprintf('Could not json_encode due to invalid ' .
75
-				'non UTF-8 characters in the array: %s', var_export($this->data, true)));
76
-		}
77
-
78
-		return $response;
79
-	}
80
-
81
-	/**
82
-	 * Sets values in the data json array
83
-	 * @param array|object $data an array or object which will be transformed
84
-	 *                             to JSON
85
-	 * @return JSONResponse Reference to this object
86
-	 * @since 6.0.0 - return value was added in 7.0.0
87
-	 */
88
-	public function setData($data){
89
-		$this->data = $data;
90
-
91
-		return $this;
92
-	}
93
-
94
-
95
-	/**
96
-	 * Used to get the set parameters
97
-	 * @return array the data
98
-	 * @since 6.0.0
99
-	 */
100
-	public function getData(){
101
-		return $this->data;
102
-	}
43
+    /**
44
+     * response data
45
+     * @var array|object
46
+     */
47
+    protected $data;
48
+
49
+
50
+    /**
51
+     * constructor of JSONResponse
52
+     * @param array|object $data the object or array that should be transformed
53
+     * @param int $statusCode the Http status code, defaults to 200
54
+     * @since 6.0.0
55
+     */
56
+    public function __construct($data=[], $statusCode=Http::STATUS_OK) {
57
+        parent::__construct();
58
+
59
+        $this->data = $data;
60
+        $this->setStatus($statusCode);
61
+        $this->addHeader('Content-Type', 'application/json; charset=utf-8');
62
+    }
63
+
64
+
65
+    /**
66
+     * Returns the rendered json
67
+     * @return string the rendered json
68
+     * @since 6.0.0
69
+     * @throws \Exception If data could not get encoded
70
+     */
71
+    public function render() {
72
+        $response = json_encode($this->data, JSON_HEX_TAG);
73
+        if($response === false) {
74
+            throw new \Exception(sprintf('Could not json_encode due to invalid ' .
75
+                'non UTF-8 characters in the array: %s', var_export($this->data, true)));
76
+        }
77
+
78
+        return $response;
79
+    }
80
+
81
+    /**
82
+     * Sets values in the data json array
83
+     * @param array|object $data an array or object which will be transformed
84
+     *                             to JSON
85
+     * @return JSONResponse Reference to this object
86
+     * @since 6.0.0 - return value was added in 7.0.0
87
+     */
88
+    public function setData($data){
89
+        $this->data = $data;
90
+
91
+        return $this;
92
+    }
93
+
94
+
95
+    /**
96
+     * Used to get the set parameters
97
+     * @return array the data
98
+     * @since 6.0.0
99
+     */
100
+    public function getData(){
101
+        return $this->data;
102
+    }
103 103
 
104 104
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/DataResponse.php 1 patch
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -38,50 +38,50 @@
 block discarded – undo
38 38
  */
39 39
 class DataResponse extends Response {
40 40
 
41
-	/**
42
-	 * response data
43
-	 * @var array|object
44
-	 */
45
-	protected $data;
41
+    /**
42
+     * response data
43
+     * @var array|object
44
+     */
45
+    protected $data;
46 46
 
47 47
 
48
-	/**
49
-	 * @param array|object $data the object or array that should be transformed
50
-	 * @param int $statusCode the Http status code, defaults to 200
51
-	 * @param array $headers additional key value based headers
52
-	 * @since 8.0.0
53
-	 */
54
-	public function __construct($data=[], $statusCode=Http::STATUS_OK,
55
-	                            array $headers=[]) {
56
-		parent::__construct();
48
+    /**
49
+     * @param array|object $data the object or array that should be transformed
50
+     * @param int $statusCode the Http status code, defaults to 200
51
+     * @param array $headers additional key value based headers
52
+     * @since 8.0.0
53
+     */
54
+    public function __construct($data=[], $statusCode=Http::STATUS_OK,
55
+                                array $headers=[]) {
56
+        parent::__construct();
57 57
 
58
-		$this->data = $data;
59
-		$this->setStatus($statusCode);
60
-		$this->setHeaders(array_merge($this->getHeaders(), $headers));
61
-	}
58
+        $this->data = $data;
59
+        $this->setStatus($statusCode);
60
+        $this->setHeaders(array_merge($this->getHeaders(), $headers));
61
+    }
62 62
 
63 63
 
64
-	/**
65
-	 * Sets values in the data json array
66
-	 * @param array|object $data an array or object which will be transformed
67
-	 * @return DataResponse Reference to this object
68
-	 * @since 8.0.0
69
-	 */
70
-	public function setData($data){
71
-		$this->data = $data;
64
+    /**
65
+     * Sets values in the data json array
66
+     * @param array|object $data an array or object which will be transformed
67
+     * @return DataResponse Reference to this object
68
+     * @since 8.0.0
69
+     */
70
+    public function setData($data){
71
+        $this->data = $data;
72 72
 
73
-		return $this;
74
-	}
73
+        return $this;
74
+    }
75 75
 
76 76
 
77
-	/**
78
-	 * Used to get the set parameters
79
-	 * @return array the data
80
-	 * @since 8.0.0
81
-	 */
82
-	public function getData(){
83
-		return $this->data;
84
-	}
77
+    /**
78
+     * Used to get the set parameters
79
+     * @return array the data
80
+     * @since 8.0.0
81
+     */
82
+    public function getData(){
83
+        return $this->data;
84
+    }
85 85
 
86 86
 
87 87
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/Response.php 1 patch
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -45,359 +45,359 @@
 block discarded – undo
45 45
  */
46 46
 class Response {
47 47
 
48
-	/**
49
-	 * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
50
-	 * @var array
51
-	 */
52
-	private $headers = [
53
-		'Cache-Control' => 'no-cache, no-store, must-revalidate'
54
-	];
55
-
56
-
57
-	/**
58
-	 * Cookies that will be need to be constructed as header
59
-	 * @var array
60
-	 */
61
-	private $cookies = [];
62
-
63
-
64
-	/**
65
-	 * HTTP status code - defaults to STATUS OK
66
-	 * @var int
67
-	 */
68
-	private $status = Http::STATUS_OK;
69
-
70
-
71
-	/**
72
-	 * Last modified date
73
-	 * @var \DateTime
74
-	 */
75
-	private $lastModified;
76
-
77
-
78
-	/**
79
-	 * ETag
80
-	 * @var string
81
-	 */
82
-	private $ETag;
83
-
84
-	/** @var ContentSecurityPolicy|null Used Content-Security-Policy */
85
-	private $contentSecurityPolicy = null;
86
-
87
-	/** @var FeaturePolicy */
88
-	private $featurePolicy;
89
-
90
-	/** @var bool */
91
-	private $throttled = false;
92
-	/** @var array */
93
-	private $throttleMetadata = [];
94
-
95
-	/**
96
-	 * @since 17.0.0
97
-	 */
98
-	public function __construct() {
99
-	}
100
-
101
-	/**
102
-	 * Caches the response
103
-	 * @param int $cacheSeconds the amount of seconds that should be cached
104
-	 * if 0 then caching will be disabled
105
-	 * @return $this
106
-	 * @since 6.0.0 - return value was added in 7.0.0
107
-	 */
108
-	public function cacheFor(int $cacheSeconds) {
109
-		if($cacheSeconds > 0) {
110
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
111
-
112
-			// Old scool prama caching
113
-			$this->addHeader('Pragma', 'public');
114
-
115
-			// Set expires header
116
-			$expires = new \DateTime();
117
-			/** @var ITimeFactory $time */
118
-			$time = \OC::$server->query(ITimeFactory::class);
119
-			$expires->setTimestamp($time->getTime());
120
-			$expires->add(new \DateInterval('PT'.$cacheSeconds.'S'));
121
-			$this->addHeader('Expires', $expires->format(\DateTime::RFC2822));
122
-		} else {
123
-			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
124
-			unset($this->headers['Expires'], $this->headers['Pragma']);
125
-		}
126
-
127
-		return $this;
128
-	}
129
-
130
-	/**
131
-	 * Adds a new cookie to the response
132
-	 * @param string $name The name of the cookie
133
-	 * @param string $value The value of the cookie
134
-	 * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
135
-	 * 									to null cookie will be considered as session
136
-	 * 									cookie.
137
-	 * @return $this
138
-	 * @since 8.0.0
139
-	 */
140
-	public function addCookie($name, $value, \DateTime $expireDate = null) {
141
-		$this->cookies[$name] = ['value' => $value, 'expireDate' => $expireDate];
142
-		return $this;
143
-	}
144
-
145
-
146
-	/**
147
-	 * Set the specified cookies
148
-	 * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
149
-	 * @return $this
150
-	 * @since 8.0.0
151
-	 */
152
-	public function setCookies(array $cookies) {
153
-		$this->cookies = $cookies;
154
-		return $this;
155
-	}
156
-
157
-
158
-	/**
159
-	 * Invalidates the specified cookie
160
-	 * @param string $name
161
-	 * @return $this
162
-	 * @since 8.0.0
163
-	 */
164
-	public function invalidateCookie($name) {
165
-		$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
166
-		return $this;
167
-	}
168
-
169
-	/**
170
-	 * Invalidates the specified cookies
171
-	 * @param array $cookieNames array('foo', 'bar')
172
-	 * @return $this
173
-	 * @since 8.0.0
174
-	 */
175
-	public function invalidateCookies(array $cookieNames) {
176
-		foreach($cookieNames as $cookieName) {
177
-			$this->invalidateCookie($cookieName);
178
-		}
179
-		return $this;
180
-	}
181
-
182
-	/**
183
-	 * Returns the cookies
184
-	 * @return array
185
-	 * @since 8.0.0
186
-	 */
187
-	public function getCookies() {
188
-		return $this->cookies;
189
-	}
190
-
191
-	/**
192
-	 * Adds a new header to the response that will be called before the render
193
-	 * function
194
-	 * @param string $name The name of the HTTP header
195
-	 * @param string $value The value, null will delete it
196
-	 * @return $this
197
-	 * @since 6.0.0 - return value was added in 7.0.0
198
-	 */
199
-	public function addHeader($name, $value) {
200
-		$name = trim($name);  // always remove leading and trailing whitespace
201
-		                      // to be able to reliably check for security
202
-		                      // headers
203
-
204
-		if(is_null($value)) {
205
-			unset($this->headers[$name]);
206
-		} else {
207
-			$this->headers[$name] = $value;
208
-		}
209
-
210
-		return $this;
211
-	}
212
-
213
-
214
-	/**
215
-	 * Set the headers
216
-	 * @param array $headers value header pairs
217
-	 * @return $this
218
-	 * @since 8.0.0
219
-	 */
220
-	public function setHeaders(array $headers) {
221
-		$this->headers = $headers;
222
-
223
-		return $this;
224
-	}
225
-
226
-
227
-	/**
228
-	 * Returns the set headers
229
-	 * @return array the headers
230
-	 * @since 6.0.0
231
-	 */
232
-	public function getHeaders() {
233
-		$mergeWith = [];
234
-
235
-		if($this->lastModified) {
236
-			$mergeWith['Last-Modified'] =
237
-				$this->lastModified->format(\DateTime::RFC2822);
238
-		}
239
-
240
-		$this->headers['Content-Security-Policy'] = $this->getContentSecurityPolicy()->buildPolicy();
241
-		$this->headers['Feature-Policy'] = $this->getFeaturePolicy()->buildPolicy();
242
-
243
-		if($this->ETag) {
244
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
245
-		}
246
-
247
-		return array_merge($mergeWith, $this->headers);
248
-	}
249
-
250
-
251
-	/**
252
-	 * By default renders no output
253
-	 * @return string
254
-	 * @since 6.0.0
255
-	 */
256
-	public function render() {
257
-		return '';
258
-	}
259
-
260
-
261
-	/**
262
-	 * Set response status
263
-	 * @param int $status a HTTP status code, see also the STATUS constants
264
-	 * @return Response Reference to this object
265
-	 * @since 6.0.0 - return value was added in 7.0.0
266
-	 */
267
-	public function setStatus($status) {
268
-		$this->status = $status;
269
-
270
-		return $this;
271
-	}
272
-
273
-	/**
274
-	 * Set a Content-Security-Policy
275
-	 * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
276
-	 * @return $this
277
-	 * @since 8.1.0
278
-	 */
279
-	public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
280
-		$this->contentSecurityPolicy = $csp;
281
-		return $this;
282
-	}
283
-
284
-	/**
285
-	 * Get the currently used Content-Security-Policy
286
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
287
-	 *                                    none specified.
288
-	 * @since 8.1.0
289
-	 */
290
-	public function getContentSecurityPolicy() {
291
-		if ($this->contentSecurityPolicy === null) {
292
-			$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
293
-		}
294
-		return $this->contentSecurityPolicy;
295
-	}
296
-
297
-
298
-	/**
299
-	 * @since 17.0.0
300
-	 */
301
-	public function getFeaturePolicy(): EmptyFeaturePolicy {
302
-		if ($this->featurePolicy === null) {
303
-			$this->setFeaturePolicy(new EmptyFeaturePolicy());
304
-		}
305
-		return $this->featurePolicy;
306
-	}
307
-
308
-	/**
309
-	 * @since 17.0.0
310
-	 */
311
-	public function setFeaturePolicy(EmptyFeaturePolicy $featurePolicy): self {
312
-		$this->featurePolicy = $featurePolicy;
313
-
314
-		return $this;
315
-	}
316
-
317
-
318
-
319
-	/**
320
-	 * Get response status
321
-	 * @since 6.0.0
322
-	 */
323
-	public function getStatus() {
324
-		return $this->status;
325
-	}
326
-
327
-
328
-	/**
329
-	 * Get the ETag
330
-	 * @return string the etag
331
-	 * @since 6.0.0
332
-	 */
333
-	public function getETag() {
334
-		return $this->ETag;
335
-	}
336
-
337
-
338
-	/**
339
-	 * Get "last modified" date
340
-	 * @return \DateTime RFC2822 formatted last modified date
341
-	 * @since 6.0.0
342
-	 */
343
-	public function getLastModified() {
344
-		return $this->lastModified;
345
-	}
346
-
347
-
348
-	/**
349
-	 * Set the ETag
350
-	 * @param string $ETag
351
-	 * @return Response Reference to this object
352
-	 * @since 6.0.0 - return value was added in 7.0.0
353
-	 */
354
-	public function setETag($ETag) {
355
-		$this->ETag = $ETag;
356
-
357
-		return $this;
358
-	}
359
-
360
-
361
-	/**
362
-	 * Set "last modified" date
363
-	 * @param \DateTime $lastModified
364
-	 * @return Response Reference to this object
365
-	 * @since 6.0.0 - return value was added in 7.0.0
366
-	 */
367
-	public function setLastModified($lastModified) {
368
-		$this->lastModified = $lastModified;
369
-
370
-		return $this;
371
-	}
372
-
373
-	/**
374
-	 * Marks the response as to throttle. Will be throttled when the
375
-	 * @BruteForceProtection annotation is added.
376
-	 *
377
-	 * @param array $metadata
378
-	 * @since 12.0.0
379
-	 */
380
-	public function throttle(array $metadata = []) {
381
-		$this->throttled = true;
382
-		$this->throttleMetadata = $metadata;
383
-	}
384
-
385
-	/**
386
-	 * Returns the throttle metadata, defaults to empty array
387
-	 *
388
-	 * @return array
389
-	 * @since 13.0.0
390
-	 */
391
-	public function getThrottleMetadata() {
392
-		return $this->throttleMetadata;
393
-	}
394
-
395
-	/**
396
-	 * Whether the current response is throttled.
397
-	 *
398
-	 * @since 12.0.0
399
-	 */
400
-	public function isThrottled() {
401
-		return $this->throttled;
402
-	}
48
+    /**
49
+     * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
50
+     * @var array
51
+     */
52
+    private $headers = [
53
+        'Cache-Control' => 'no-cache, no-store, must-revalidate'
54
+    ];
55
+
56
+
57
+    /**
58
+     * Cookies that will be need to be constructed as header
59
+     * @var array
60
+     */
61
+    private $cookies = [];
62
+
63
+
64
+    /**
65
+     * HTTP status code - defaults to STATUS OK
66
+     * @var int
67
+     */
68
+    private $status = Http::STATUS_OK;
69
+
70
+
71
+    /**
72
+     * Last modified date
73
+     * @var \DateTime
74
+     */
75
+    private $lastModified;
76
+
77
+
78
+    /**
79
+     * ETag
80
+     * @var string
81
+     */
82
+    private $ETag;
83
+
84
+    /** @var ContentSecurityPolicy|null Used Content-Security-Policy */
85
+    private $contentSecurityPolicy = null;
86
+
87
+    /** @var FeaturePolicy */
88
+    private $featurePolicy;
89
+
90
+    /** @var bool */
91
+    private $throttled = false;
92
+    /** @var array */
93
+    private $throttleMetadata = [];
94
+
95
+    /**
96
+     * @since 17.0.0
97
+     */
98
+    public function __construct() {
99
+    }
100
+
101
+    /**
102
+     * Caches the response
103
+     * @param int $cacheSeconds the amount of seconds that should be cached
104
+     * if 0 then caching will be disabled
105
+     * @return $this
106
+     * @since 6.0.0 - return value was added in 7.0.0
107
+     */
108
+    public function cacheFor(int $cacheSeconds) {
109
+        if($cacheSeconds > 0) {
110
+            $this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
111
+
112
+            // Old scool prama caching
113
+            $this->addHeader('Pragma', 'public');
114
+
115
+            // Set expires header
116
+            $expires = new \DateTime();
117
+            /** @var ITimeFactory $time */
118
+            $time = \OC::$server->query(ITimeFactory::class);
119
+            $expires->setTimestamp($time->getTime());
120
+            $expires->add(new \DateInterval('PT'.$cacheSeconds.'S'));
121
+            $this->addHeader('Expires', $expires->format(\DateTime::RFC2822));
122
+        } else {
123
+            $this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
124
+            unset($this->headers['Expires'], $this->headers['Pragma']);
125
+        }
126
+
127
+        return $this;
128
+    }
129
+
130
+    /**
131
+     * Adds a new cookie to the response
132
+     * @param string $name The name of the cookie
133
+     * @param string $value The value of the cookie
134
+     * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
135
+     * 									to null cookie will be considered as session
136
+     * 									cookie.
137
+     * @return $this
138
+     * @since 8.0.0
139
+     */
140
+    public function addCookie($name, $value, \DateTime $expireDate = null) {
141
+        $this->cookies[$name] = ['value' => $value, 'expireDate' => $expireDate];
142
+        return $this;
143
+    }
144
+
145
+
146
+    /**
147
+     * Set the specified cookies
148
+     * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
149
+     * @return $this
150
+     * @since 8.0.0
151
+     */
152
+    public function setCookies(array $cookies) {
153
+        $this->cookies = $cookies;
154
+        return $this;
155
+    }
156
+
157
+
158
+    /**
159
+     * Invalidates the specified cookie
160
+     * @param string $name
161
+     * @return $this
162
+     * @since 8.0.0
163
+     */
164
+    public function invalidateCookie($name) {
165
+        $this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
166
+        return $this;
167
+    }
168
+
169
+    /**
170
+     * Invalidates the specified cookies
171
+     * @param array $cookieNames array('foo', 'bar')
172
+     * @return $this
173
+     * @since 8.0.0
174
+     */
175
+    public function invalidateCookies(array $cookieNames) {
176
+        foreach($cookieNames as $cookieName) {
177
+            $this->invalidateCookie($cookieName);
178
+        }
179
+        return $this;
180
+    }
181
+
182
+    /**
183
+     * Returns the cookies
184
+     * @return array
185
+     * @since 8.0.0
186
+     */
187
+    public function getCookies() {
188
+        return $this->cookies;
189
+    }
190
+
191
+    /**
192
+     * Adds a new header to the response that will be called before the render
193
+     * function
194
+     * @param string $name The name of the HTTP header
195
+     * @param string $value The value, null will delete it
196
+     * @return $this
197
+     * @since 6.0.0 - return value was added in 7.0.0
198
+     */
199
+    public function addHeader($name, $value) {
200
+        $name = trim($name);  // always remove leading and trailing whitespace
201
+                                // to be able to reliably check for security
202
+                                // headers
203
+
204
+        if(is_null($value)) {
205
+            unset($this->headers[$name]);
206
+        } else {
207
+            $this->headers[$name] = $value;
208
+        }
209
+
210
+        return $this;
211
+    }
212
+
213
+
214
+    /**
215
+     * Set the headers
216
+     * @param array $headers value header pairs
217
+     * @return $this
218
+     * @since 8.0.0
219
+     */
220
+    public function setHeaders(array $headers) {
221
+        $this->headers = $headers;
222
+
223
+        return $this;
224
+    }
225
+
226
+
227
+    /**
228
+     * Returns the set headers
229
+     * @return array the headers
230
+     * @since 6.0.0
231
+     */
232
+    public function getHeaders() {
233
+        $mergeWith = [];
234
+
235
+        if($this->lastModified) {
236
+            $mergeWith['Last-Modified'] =
237
+                $this->lastModified->format(\DateTime::RFC2822);
238
+        }
239
+
240
+        $this->headers['Content-Security-Policy'] = $this->getContentSecurityPolicy()->buildPolicy();
241
+        $this->headers['Feature-Policy'] = $this->getFeaturePolicy()->buildPolicy();
242
+
243
+        if($this->ETag) {
244
+            $mergeWith['ETag'] = '"' . $this->ETag . '"';
245
+        }
246
+
247
+        return array_merge($mergeWith, $this->headers);
248
+    }
249
+
250
+
251
+    /**
252
+     * By default renders no output
253
+     * @return string
254
+     * @since 6.0.0
255
+     */
256
+    public function render() {
257
+        return '';
258
+    }
259
+
260
+
261
+    /**
262
+     * Set response status
263
+     * @param int $status a HTTP status code, see also the STATUS constants
264
+     * @return Response Reference to this object
265
+     * @since 6.0.0 - return value was added in 7.0.0
266
+     */
267
+    public function setStatus($status) {
268
+        $this->status = $status;
269
+
270
+        return $this;
271
+    }
272
+
273
+    /**
274
+     * Set a Content-Security-Policy
275
+     * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
276
+     * @return $this
277
+     * @since 8.1.0
278
+     */
279
+    public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
280
+        $this->contentSecurityPolicy = $csp;
281
+        return $this;
282
+    }
283
+
284
+    /**
285
+     * Get the currently used Content-Security-Policy
286
+     * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
287
+     *                                    none specified.
288
+     * @since 8.1.0
289
+     */
290
+    public function getContentSecurityPolicy() {
291
+        if ($this->contentSecurityPolicy === null) {
292
+            $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
293
+        }
294
+        return $this->contentSecurityPolicy;
295
+    }
296
+
297
+
298
+    /**
299
+     * @since 17.0.0
300
+     */
301
+    public function getFeaturePolicy(): EmptyFeaturePolicy {
302
+        if ($this->featurePolicy === null) {
303
+            $this->setFeaturePolicy(new EmptyFeaturePolicy());
304
+        }
305
+        return $this->featurePolicy;
306
+    }
307
+
308
+    /**
309
+     * @since 17.0.0
310
+     */
311
+    public function setFeaturePolicy(EmptyFeaturePolicy $featurePolicy): self {
312
+        $this->featurePolicy = $featurePolicy;
313
+
314
+        return $this;
315
+    }
316
+
317
+
318
+
319
+    /**
320
+     * Get response status
321
+     * @since 6.0.0
322
+     */
323
+    public function getStatus() {
324
+        return $this->status;
325
+    }
326
+
327
+
328
+    /**
329
+     * Get the ETag
330
+     * @return string the etag
331
+     * @since 6.0.0
332
+     */
333
+    public function getETag() {
334
+        return $this->ETag;
335
+    }
336
+
337
+
338
+    /**
339
+     * Get "last modified" date
340
+     * @return \DateTime RFC2822 formatted last modified date
341
+     * @since 6.0.0
342
+     */
343
+    public function getLastModified() {
344
+        return $this->lastModified;
345
+    }
346
+
347
+
348
+    /**
349
+     * Set the ETag
350
+     * @param string $ETag
351
+     * @return Response Reference to this object
352
+     * @since 6.0.0 - return value was added in 7.0.0
353
+     */
354
+    public function setETag($ETag) {
355
+        $this->ETag = $ETag;
356
+
357
+        return $this;
358
+    }
359
+
360
+
361
+    /**
362
+     * Set "last modified" date
363
+     * @param \DateTime $lastModified
364
+     * @return Response Reference to this object
365
+     * @since 6.0.0 - return value was added in 7.0.0
366
+     */
367
+    public function setLastModified($lastModified) {
368
+        $this->lastModified = $lastModified;
369
+
370
+        return $this;
371
+    }
372
+
373
+    /**
374
+     * Marks the response as to throttle. Will be throttled when the
375
+     * @BruteForceProtection annotation is added.
376
+     *
377
+     * @param array $metadata
378
+     * @since 12.0.0
379
+     */
380
+    public function throttle(array $metadata = []) {
381
+        $this->throttled = true;
382
+        $this->throttleMetadata = $metadata;
383
+    }
384
+
385
+    /**
386
+     * Returns the throttle metadata, defaults to empty array
387
+     *
388
+     * @return array
389
+     * @since 13.0.0
390
+     */
391
+    public function getThrottleMetadata() {
392
+        return $this->throttleMetadata;
393
+    }
394
+
395
+    /**
396
+     * Whether the current response is throttled.
397
+     *
398
+     * @since 12.0.0
399
+     */
400
+    public function isThrottled() {
401
+        return $this->throttled;
402
+    }
403 403
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/Entity.php 1 patch
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -36,236 +36,236 @@
 block discarded – undo
36 36
  */
37 37
 abstract class Entity {
38 38
 
39
-	public $id;
40
-
41
-	private $_updatedFields = [];
42
-	private $_fieldTypes = ['id' => 'integer'];
43
-
44
-
45
-	/**
46
-	 * Simple alternative constructor for building entities from a request
47
-	 * @param array $params the array which was obtained via $this->params('key')
48
-	 * in the controller
49
-	 * @return Entity
50
-	 * @since 7.0.0
51
-	 */
52
-	public static function fromParams(array $params) {
53
-		$instance = new static();
54
-
55
-		foreach($params as $key => $value) {
56
-			$method = 'set' . ucfirst($key);
57
-			$instance->$method($value);
58
-		}
59
-
60
-		return $instance;
61
-	}
62
-
63
-
64
-	/**
65
-	 * Maps the keys of the row array to the attributes
66
-	 * @param array $row the row to map onto the entity
67
-	 * @since 7.0.0
68
-	 */
69
-	public static function fromRow(array $row){
70
-		$instance = new static();
71
-
72
-		foreach($row as $key => $value){
73
-			$prop = ucfirst($instance->columnToProperty($key));
74
-			$setter = 'set' . $prop;
75
-			$instance->$setter($value);
76
-		}
77
-
78
-		$instance->resetUpdatedFields();
79
-
80
-		return $instance;
81
-	}
82
-
83
-
84
-	/**
85
-	 * @return array with attribute and type
86
-	 * @since 7.0.0
87
-	 */
88
-	public function getFieldTypes() {
89
-		return $this->_fieldTypes;
90
-	}
91
-
92
-
93
-	/**
94
-	 * Marks the entity as clean needed for setting the id after the insertion
95
-	 * @since 7.0.0
96
-	 */
97
-	public function resetUpdatedFields(){
98
-		$this->_updatedFields = [];
99
-	}
100
-
101
-	/**
102
-	 * Generic setter for properties
103
-	 * @since 7.0.0
104
-	 */
105
-	protected function setter($name, $args) {
106
-		// setters should only work for existing attributes
107
-		if(property_exists($this, $name)){
108
-			if($this->$name === $args[0]) {
109
-				return;
110
-			}
111
-			$this->markFieldUpdated($name);
112
-
113
-			// if type definition exists, cast to correct type
114
-			if($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
115
-				settype($args[0], $this->_fieldTypes[$name]);
116
-			}
117
-			$this->$name = $args[0];
118
-
119
-		} else {
120
-			throw new \BadFunctionCallException($name .
121
-				' is not a valid attribute');
122
-		}
123
-	}
124
-
125
-	/**
126
-	 * Generic getter for properties
127
-	 * @since 7.0.0
128
-	 */
129
-	protected function getter($name) {
130
-		// getters should only work for existing attributes
131
-		if(property_exists($this, $name)){
132
-			return $this->$name;
133
-		} else {
134
-			throw new \BadFunctionCallException($name .
135
-				' is not a valid attribute');
136
-		}
137
-	}
138
-
139
-
140
-	/**
141
-	 * Each time a setter is called, push the part after set
142
-	 * into an array: for instance setId will save Id in the
143
-	 * updated fields array so it can be easily used to create the
144
-	 * getter method
145
-	 * @since 7.0.0
146
-	 */
147
-	public function __call($methodName, $args) {
148
-		if (strpos($methodName, 'set') === 0) {
149
-			$this->setter(lcfirst(substr($methodName, 3)), $args);
150
-		} elseif (strpos($methodName, 'get') === 0) {
151
-			return $this->getter(lcfirst(substr($methodName, 3)));
152
-		} elseif ($this->isGetterForBoolProperty($methodName)) {
153
-			return $this->getter(lcfirst(substr($methodName, 2)));
154
-		} else {
155
-			throw new \BadFunctionCallException($methodName .
156
-				' does not exist');
157
-		}
158
-
159
-	}
160
-
161
-	/**
162
-	 * @param string $methodName
163
-	 * @return bool
164
-	 * @since 18.0.0
165
-	 */
166
-	protected function isGetterForBoolProperty(string $methodName): bool {
167
-		if (strpos($methodName, 'is') === 0) {
168
-			$fieldName = lcfirst(substr($methodName, 2));
169
-			return isset($this->_fieldTypes[$fieldName]) && strpos($this->_fieldTypes[$fieldName], 'bool') === 0;
170
-		}
171
-		return false;
172
-	}
173
-
174
-	/**
175
-	 * Mark am attribute as updated
176
-	 * @param string $attribute the name of the attribute
177
-	 * @since 7.0.0
178
-	 */
179
-	protected function markFieldUpdated($attribute){
180
-		$this->_updatedFields[$attribute] = true;
181
-	}
182
-
183
-
184
-	/**
185
-	 * Transform a database columnname to a property
186
-	 * @param string $columnName the name of the column
187
-	 * @return string the property name
188
-	 * @since 7.0.0
189
-	 */
190
-	public function columnToProperty($columnName){
191
-		$parts = explode('_', $columnName);
192
-		$property = null;
193
-
194
-		foreach($parts as $part){
195
-			if($property === null){
196
-				$property = $part;
197
-			} else {
198
-				$property .= ucfirst($part);
199
-			}
200
-		}
201
-
202
-		return $property;
203
-	}
204
-
205
-
206
-	/**
207
-	 * Transform a property to a database column name
208
-	 * @param string $property the name of the property
209
-	 * @return string the column name
210
-	 * @since 7.0.0
211
-	 */
212
-	public function propertyToColumn($property){
213
-		$parts = preg_split('/(?=[A-Z])/', $property);
214
-		$column = null;
215
-
216
-		foreach($parts as $part){
217
-			if($column === null){
218
-				$column = $part;
219
-			} else {
220
-				$column .= '_' . lcfirst($part);
221
-			}
222
-		}
223
-
224
-		return $column;
225
-	}
226
-
227
-
228
-	/**
229
-	 * @return array array of updated fields for update query
230
-	 * @since 7.0.0
231
-	 */
232
-	public function getUpdatedFields(){
233
-		return $this->_updatedFields;
234
-	}
235
-
236
-
237
-	/**
238
-	 * Adds type information for a field so that its automatically casted to
239
-	 * that value once its being returned from the database
240
-	 * @param string $fieldName the name of the attribute
241
-	 * @param string $type the type which will be used to call settype()
242
-	 * @since 7.0.0
243
-	 */
244
-	protected function addType($fieldName, $type){
245
-		$this->_fieldTypes[$fieldName] = $type;
246
-	}
247
-
248
-
249
-	/**
250
-	 * Slugify the value of a given attribute
251
-	 * Warning: This doesn't result in a unique value
252
-	 * @param string $attributeName the name of the attribute, which value should be slugified
253
-	 * @return string slugified value
254
-	 * @since 7.0.0
255
-	 */
256
-	public function slugify($attributeName){
257
-		// toSlug should only work for existing attributes
258
-		if(property_exists($this, $attributeName)){
259
-			$value = $this->$attributeName;
260
-			// replace everything except alphanumeric with a single '-'
261
-			$value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
262
-			$value = strtolower($value);
263
-			// trim '-'
264
-			return trim($value, '-');
265
-		} else {
266
-			throw new \BadFunctionCallException($attributeName .
267
-				' is not a valid attribute');
268
-		}
269
-	}
39
+    public $id;
40
+
41
+    private $_updatedFields = [];
42
+    private $_fieldTypes = ['id' => 'integer'];
43
+
44
+
45
+    /**
46
+     * Simple alternative constructor for building entities from a request
47
+     * @param array $params the array which was obtained via $this->params('key')
48
+     * in the controller
49
+     * @return Entity
50
+     * @since 7.0.0
51
+     */
52
+    public static function fromParams(array $params) {
53
+        $instance = new static();
54
+
55
+        foreach($params as $key => $value) {
56
+            $method = 'set' . ucfirst($key);
57
+            $instance->$method($value);
58
+        }
59
+
60
+        return $instance;
61
+    }
62
+
63
+
64
+    /**
65
+     * Maps the keys of the row array to the attributes
66
+     * @param array $row the row to map onto the entity
67
+     * @since 7.0.0
68
+     */
69
+    public static function fromRow(array $row){
70
+        $instance = new static();
71
+
72
+        foreach($row as $key => $value){
73
+            $prop = ucfirst($instance->columnToProperty($key));
74
+            $setter = 'set' . $prop;
75
+            $instance->$setter($value);
76
+        }
77
+
78
+        $instance->resetUpdatedFields();
79
+
80
+        return $instance;
81
+    }
82
+
83
+
84
+    /**
85
+     * @return array with attribute and type
86
+     * @since 7.0.0
87
+     */
88
+    public function getFieldTypes() {
89
+        return $this->_fieldTypes;
90
+    }
91
+
92
+
93
+    /**
94
+     * Marks the entity as clean needed for setting the id after the insertion
95
+     * @since 7.0.0
96
+     */
97
+    public function resetUpdatedFields(){
98
+        $this->_updatedFields = [];
99
+    }
100
+
101
+    /**
102
+     * Generic setter for properties
103
+     * @since 7.0.0
104
+     */
105
+    protected function setter($name, $args) {
106
+        // setters should only work for existing attributes
107
+        if(property_exists($this, $name)){
108
+            if($this->$name === $args[0]) {
109
+                return;
110
+            }
111
+            $this->markFieldUpdated($name);
112
+
113
+            // if type definition exists, cast to correct type
114
+            if($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
115
+                settype($args[0], $this->_fieldTypes[$name]);
116
+            }
117
+            $this->$name = $args[0];
118
+
119
+        } else {
120
+            throw new \BadFunctionCallException($name .
121
+                ' is not a valid attribute');
122
+        }
123
+    }
124
+
125
+    /**
126
+     * Generic getter for properties
127
+     * @since 7.0.0
128
+     */
129
+    protected function getter($name) {
130
+        // getters should only work for existing attributes
131
+        if(property_exists($this, $name)){
132
+            return $this->$name;
133
+        } else {
134
+            throw new \BadFunctionCallException($name .
135
+                ' is not a valid attribute');
136
+        }
137
+    }
138
+
139
+
140
+    /**
141
+     * Each time a setter is called, push the part after set
142
+     * into an array: for instance setId will save Id in the
143
+     * updated fields array so it can be easily used to create the
144
+     * getter method
145
+     * @since 7.0.0
146
+     */
147
+    public function __call($methodName, $args) {
148
+        if (strpos($methodName, 'set') === 0) {
149
+            $this->setter(lcfirst(substr($methodName, 3)), $args);
150
+        } elseif (strpos($methodName, 'get') === 0) {
151
+            return $this->getter(lcfirst(substr($methodName, 3)));
152
+        } elseif ($this->isGetterForBoolProperty($methodName)) {
153
+            return $this->getter(lcfirst(substr($methodName, 2)));
154
+        } else {
155
+            throw new \BadFunctionCallException($methodName .
156
+                ' does not exist');
157
+        }
158
+
159
+    }
160
+
161
+    /**
162
+     * @param string $methodName
163
+     * @return bool
164
+     * @since 18.0.0
165
+     */
166
+    protected function isGetterForBoolProperty(string $methodName): bool {
167
+        if (strpos($methodName, 'is') === 0) {
168
+            $fieldName = lcfirst(substr($methodName, 2));
169
+            return isset($this->_fieldTypes[$fieldName]) && strpos($this->_fieldTypes[$fieldName], 'bool') === 0;
170
+        }
171
+        return false;
172
+    }
173
+
174
+    /**
175
+     * Mark am attribute as updated
176
+     * @param string $attribute the name of the attribute
177
+     * @since 7.0.0
178
+     */
179
+    protected function markFieldUpdated($attribute){
180
+        $this->_updatedFields[$attribute] = true;
181
+    }
182
+
183
+
184
+    /**
185
+     * Transform a database columnname to a property
186
+     * @param string $columnName the name of the column
187
+     * @return string the property name
188
+     * @since 7.0.0
189
+     */
190
+    public function columnToProperty($columnName){
191
+        $parts = explode('_', $columnName);
192
+        $property = null;
193
+
194
+        foreach($parts as $part){
195
+            if($property === null){
196
+                $property = $part;
197
+            } else {
198
+                $property .= ucfirst($part);
199
+            }
200
+        }
201
+
202
+        return $property;
203
+    }
204
+
205
+
206
+    /**
207
+     * Transform a property to a database column name
208
+     * @param string $property the name of the property
209
+     * @return string the column name
210
+     * @since 7.0.0
211
+     */
212
+    public function propertyToColumn($property){
213
+        $parts = preg_split('/(?=[A-Z])/', $property);
214
+        $column = null;
215
+
216
+        foreach($parts as $part){
217
+            if($column === null){
218
+                $column = $part;
219
+            } else {
220
+                $column .= '_' . lcfirst($part);
221
+            }
222
+        }
223
+
224
+        return $column;
225
+    }
226
+
227
+
228
+    /**
229
+     * @return array array of updated fields for update query
230
+     * @since 7.0.0
231
+     */
232
+    public function getUpdatedFields(){
233
+        return $this->_updatedFields;
234
+    }
235
+
236
+
237
+    /**
238
+     * Adds type information for a field so that its automatically casted to
239
+     * that value once its being returned from the database
240
+     * @param string $fieldName the name of the attribute
241
+     * @param string $type the type which will be used to call settype()
242
+     * @since 7.0.0
243
+     */
244
+    protected function addType($fieldName, $type){
245
+        $this->_fieldTypes[$fieldName] = $type;
246
+    }
247
+
248
+
249
+    /**
250
+     * Slugify the value of a given attribute
251
+     * Warning: This doesn't result in a unique value
252
+     * @param string $attributeName the name of the attribute, which value should be slugified
253
+     * @return string slugified value
254
+     * @since 7.0.0
255
+     */
256
+    public function slugify($attributeName){
257
+        // toSlug should only work for existing attributes
258
+        if(property_exists($this, $attributeName)){
259
+            $value = $this->$attributeName;
260
+            // replace everything except alphanumeric with a single '-'
261
+            $value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
262
+            $value = strtolower($value);
263
+            // trim '-'
264
+            return trim($value, '-');
265
+        } else {
266
+            throw new \BadFunctionCallException($attributeName .
267
+                ' is not a valid attribute');
268
+        }
269
+    }
270 270
 
271 271
 }
Please login to merge, or discard this patch.