Passed
Push — master ( cb1d9c...5b6246 )
by John
13:49 queued 12s
created
lib/public/Dashboard/IManager.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -34,16 +34,16 @@
 block discarded – undo
34 34
  */
35 35
 interface IManager {
36 36
 
37
-	/**
38
-	 * @param string $widgetClass
39
-	 * @since 20.0.0
40
-	 */
41
-	public function lazyRegisterWidget(string $widgetClass): void;
37
+    /**
38
+     * @param string $widgetClass
39
+     * @since 20.0.0
40
+     */
41
+    public function lazyRegisterWidget(string $widgetClass): void;
42 42
 
43
-	/**
44
-	 * @since 20.0.0
45
-	 *
46
-	 * @return IWidget[]
47
-	 */
48
-	public function getWidgets(): array;
43
+    /**
44
+     * @since 20.0.0
45
+     *
46
+     * @return IWidget[]
47
+     */
48
+    public function getWidgets(): array;
49 49
 }
Please login to merge, or discard this patch.
lib/public/Dashboard/RegisterWidgetEvent.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -41,19 +41,19 @@
 block discarded – undo
41 41
  * @deprecated 20.0.0
42 42
  */
43 43
 class RegisterWidgetEvent extends Event {
44
-	private $manager;
44
+    private $manager;
45 45
 
46
-	public function __construct(IManager $manager) {
47
-		parent::__construct();
46
+    public function __construct(IManager $manager) {
47
+        parent::__construct();
48 48
 
49
-		$this->manager = $manager;
50
-	}
49
+        $this->manager = $manager;
50
+    }
51 51
 
52
-	/**
53
-	 * @param string $panelClass
54
-	 * @since 20.0.0
55
-	 */
56
-	public function registerWidget(string $panelClass) {
57
-		$this->manager->lazyRegisterWidget($panelClass);
58
-	}
52
+    /**
53
+     * @param string $panelClass
54
+     * @since 20.0.0
55
+     */
56
+    public function registerWidget(string $panelClass) {
57
+        $this->manager->lazyRegisterWidget($panelClass);
58
+    }
59 59
 }
Please login to merge, or discard this patch.
lib/public/Dashboard/IWidget.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -34,39 +34,39 @@
 block discarded – undo
34 34
  */
35 35
 interface IWidget {
36 36
 
37
-	/**
38
-	 * @return string Unique id that identifies the widget, e.g. the app id
39
-	 * @since 20.0.0
40
-	 */
41
-	public function getId(): string;
37
+    /**
38
+     * @return string Unique id that identifies the widget, e.g. the app id
39
+     * @since 20.0.0
40
+     */
41
+    public function getId(): string;
42 42
 
43
-	/**
44
-	 * @return string User facing title of the widget
45
-	 * @since 20.0.0
46
-	 */
47
-	public function getTitle(): string;
43
+    /**
44
+     * @return string User facing title of the widget
45
+     * @since 20.0.0
46
+     */
47
+    public function getTitle(): string;
48 48
 
49
-	/**
50
-	 * @return int Initial order for widget sorting
51
-	 * @since 20.0.0
52
-	 */
53
-	public function getOrder(): int;
49
+    /**
50
+     * @return int Initial order for widget sorting
51
+     * @since 20.0.0
52
+     */
53
+    public function getOrder(): int;
54 54
 
55
-	/**
56
-	 * @return string css class that displays an icon next to the widget title
57
-	 * @since 20.0.0
58
-	 */
59
-	public function getIconClass(): string;
55
+    /**
56
+     * @return string css class that displays an icon next to the widget title
57
+     * @since 20.0.0
58
+     */
59
+    public function getIconClass(): string;
60 60
 
61
-	/**
62
-	 * @return string|null The absolute url to the apps own view
63
-	 * @since 20.0.0
64
-	 */
65
-	public function getUrl(): ?string;
61
+    /**
62
+     * @return string|null The absolute url to the apps own view
63
+     * @since 20.0.0
64
+     */
65
+    public function getUrl(): ?string;
66 66
 
67
-	/**
68
-	 * Execute widget bootstrap code like loading scripts and providing initial state
69
-	 * @since 20.0.0
70
-	 */
71
-	public function load(): void;
67
+    /**
68
+     * Execute widget bootstrap code like loading scripts and providing initial state
69
+     * @since 20.0.0
70
+     */
71
+    public function load(): void;
72 72
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Bootstrap/IRegistrationContext.php 1 patch
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -37,119 +37,119 @@
 block discarded – undo
37 37
  */
38 38
 interface IRegistrationContext {
39 39
 
40
-	/**
41
-	 * @param string $capability
42
-	 * @see IAppContainer::registerCapability
43
-	 *
44
-	 * @since 20.0.0
45
-	 */
46
-	public function registerCapability(string $capability): void;
40
+    /**
41
+     * @param string $capability
42
+     * @see IAppContainer::registerCapability
43
+     *
44
+     * @since 20.0.0
45
+     */
46
+    public function registerCapability(string $capability): void;
47 47
 
48
-	/**
49
-	 * Register an implementation of \OCP\Support\CrashReport\IReporter that
50
-	 * will receive unhandled exceptions and throwables
51
-	 *
52
-	 * @param string $reporterClass
53
-	 * @return void
54
-	 * @since 20.0.0
55
-	 */
56
-	public function registerCrashReporter(string $reporterClass): void;
48
+    /**
49
+     * Register an implementation of \OCP\Support\CrashReport\IReporter that
50
+     * will receive unhandled exceptions and throwables
51
+     *
52
+     * @param string $reporterClass
53
+     * @return void
54
+     * @since 20.0.0
55
+     */
56
+    public function registerCrashReporter(string $reporterClass): void;
57 57
 
58
-	/**
59
-	 * Register an implementation of \OCP\Dashboard\IPanel that
60
-	 * will handle the implementation of a dashboard panel
61
-	 *
62
-	 * @param string $widgetClass
63
-	 * @return void
64
-	 * @since 20.0.0
65
-	 */
66
-	public function registerDashboardWidget(string $widgetClass): void;
67
-	/**
68
-	 * Register a service
69
-	 *
70
-	 * @param string $name
71
-	 * @param callable $factory
72
-	 * @param bool $shared
73
-	 *
74
-	 * @return void
75
-	 * @see IContainer::registerService()
76
-	 *
77
-	 * @since 20.0.0
78
-	 */
79
-	public function registerService(string $name, callable $factory, bool $shared = true): void;
58
+    /**
59
+     * Register an implementation of \OCP\Dashboard\IPanel that
60
+     * will handle the implementation of a dashboard panel
61
+     *
62
+     * @param string $widgetClass
63
+     * @return void
64
+     * @since 20.0.0
65
+     */
66
+    public function registerDashboardWidget(string $widgetClass): void;
67
+    /**
68
+     * Register a service
69
+     *
70
+     * @param string $name
71
+     * @param callable $factory
72
+     * @param bool $shared
73
+     *
74
+     * @return void
75
+     * @see IContainer::registerService()
76
+     *
77
+     * @since 20.0.0
78
+     */
79
+    public function registerService(string $name, callable $factory, bool $shared = true): void;
80 80
 
81
-	/**
82
-	 * @param string $alias
83
-	 * @param string $target
84
-	 *
85
-	 * @return void
86
-	 * @see IContainer::registerAlias()
87
-	 *
88
-	 * @since 20.0.0
89
-	 */
90
-	public function registerServiceAlias(string $alias, string $target): void;
81
+    /**
82
+     * @param string $alias
83
+     * @param string $target
84
+     *
85
+     * @return void
86
+     * @see IContainer::registerAlias()
87
+     *
88
+     * @since 20.0.0
89
+     */
90
+    public function registerServiceAlias(string $alias, string $target): void;
91 91
 
92
-	/**
93
-	 * @param string $name
94
-	 * @param mixed $value
95
-	 *
96
-	 * @return void
97
-	 * @see IContainer::registerParameter()
98
-	 *
99
-	 * @since 20.0.0
100
-	 */
101
-	public function registerParameter(string $name, $value): void;
92
+    /**
93
+     * @param string $name
94
+     * @param mixed $value
95
+     *
96
+     * @return void
97
+     * @see IContainer::registerParameter()
98
+     *
99
+     * @since 20.0.0
100
+     */
101
+    public function registerParameter(string $name, $value): void;
102 102
 
103
-	/**
104
-	 * Register a service listener
105
-	 *
106
-	 * This is equivalent to calling IEventDispatcher::addServiceListener
107
-	 *
108
-	 * @param string $event preferably the fully-qualified class name of the Event sub class to listen for
109
-	 * @param string $listener fully qualified class name (or ::class notation) of a \OCP\EventDispatcher\IEventListener that can be built by the DI container
110
-	 * @param int $priority
111
-	 *
112
-	 * @see IEventDispatcher::addServiceListener()
113
-	 *
114
-	 * @since 20.0.0
115
-	 */
116
-	public function registerEventListener(string $event, string $listener, int $priority = 0): void;
103
+    /**
104
+     * Register a service listener
105
+     *
106
+     * This is equivalent to calling IEventDispatcher::addServiceListener
107
+     *
108
+     * @param string $event preferably the fully-qualified class name of the Event sub class to listen for
109
+     * @param string $listener fully qualified class name (or ::class notation) of a \OCP\EventDispatcher\IEventListener that can be built by the DI container
110
+     * @param int $priority
111
+     *
112
+     * @see IEventDispatcher::addServiceListener()
113
+     *
114
+     * @since 20.0.0
115
+     */
116
+    public function registerEventListener(string $event, string $listener, int $priority = 0): void;
117 117
 
118
-	/**
119
-	 * @param string $class
120
-	 *
121
-	 * @return void
122
-	 * @see IAppContainer::registerMiddleWare()
123
-	 *
124
-	 * @since 20.0.0
125
-	 */
126
-	public function registerMiddleware(string $class): void;
118
+    /**
119
+     * @param string $class
120
+     *
121
+     * @return void
122
+     * @see IAppContainer::registerMiddleWare()
123
+     *
124
+     * @since 20.0.0
125
+     */
126
+    public function registerMiddleware(string $class): void;
127 127
 
128
-	/**
129
-	 * Register a search provider for the unified search
130
-	 *
131
-	 * It is allowed to register more than one provider per app as the search
132
-	 * results can go into distinct sections, e.g. "Files" and "Files shared
133
-	 * with you" in the Files app.
134
-	 *
135
-	 * @param string $class
136
-	 *
137
-	 * @return void
138
-	 *
139
-	 * @since 20.0.0
140
-	 */
141
-	public function registerSearchProvider(string $class): void;
128
+    /**
129
+     * Register a search provider for the unified search
130
+     *
131
+     * It is allowed to register more than one provider per app as the search
132
+     * results can go into distinct sections, e.g. "Files" and "Files shared
133
+     * with you" in the Files app.
134
+     *
135
+     * @param string $class
136
+     *
137
+     * @return void
138
+     *
139
+     * @since 20.0.0
140
+     */
141
+    public function registerSearchProvider(string $class): void;
142 142
 
143
-	/**
144
-	 * Register an alternative login option
145
-	 *
146
-	 * It is allowed to register more than one option per app.
147
-	 *
148
-	 * @param string $class
149
-	 *
150
-	 * @return void
151
-	 *
152
-	 * @since 20.0.0
153
-	 */
154
-	public function registerAlternativeLogin(string $class): void;
143
+    /**
144
+     * Register an alternative login option
145
+     *
146
+     * It is allowed to register more than one option per app.
147
+     *
148
+     * @param string $class
149
+     *
150
+     * @return void
151
+     *
152
+     * @since 20.0.0
153
+     */
154
+    public function registerAlternativeLogin(string $class): void;
155 155
 }
Please login to merge, or discard this patch.
lib/private/Dashboard/Manager.php 2 patches
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -36,78 +36,78 @@
 block discarded – undo
36 36
 
37 37
 class Manager implements IManager {
38 38
 
39
-	/** @var array */
40
-	private $lazyWidgets = [];
39
+    /** @var array */
40
+    private $lazyWidgets = [];
41 41
 
42
-	/** @var IWidget[] */
43
-	private $widgets = [];
42
+    /** @var IWidget[] */
43
+    private $widgets = [];
44 44
 
45
-	/** @var IServerContainer */
46
-	private $serverContainer;
45
+    /** @var IServerContainer */
46
+    private $serverContainer;
47 47
 
48
-	public function __construct(IServerContainer $serverContainer) {
49
-		$this->serverContainer = $serverContainer;
50
-	}
48
+    public function __construct(IServerContainer $serverContainer) {
49
+        $this->serverContainer = $serverContainer;
50
+    }
51 51
 
52
-	private function registerWidget(IWidget $widget): void {
53
-		if (array_key_exists($widget->getId(), $this->widgets)) {
54
-			throw new InvalidArgumentException('Dashboard widget with this id has already been registered');
55
-		}
52
+    private function registerWidget(IWidget $widget): void {
53
+        if (array_key_exists($widget->getId(), $this->widgets)) {
54
+            throw new InvalidArgumentException('Dashboard widget with this id has already been registered');
55
+        }
56 56
 
57
-		$this->widgets[$widget->getId()] = $widget;
58
-	}
57
+        $this->widgets[$widget->getId()] = $widget;
58
+    }
59 59
 
60
-	public function lazyRegisterWidget(string $widgetClass): void {
61
-		$this->lazyWidgets[] = $widgetClass;
62
-	}
60
+    public function lazyRegisterWidget(string $widgetClass): void {
61
+        $this->lazyWidgets[] = $widgetClass;
62
+    }
63 63
 
64
-	public function loadLazyPanels(): void {
65
-		$classes = $this->lazyWidgets;
66
-		foreach ($classes as $class) {
67
-			try {
68
-				/** @var IWidget $widget */
69
-				$widget = $this->serverContainer->query($class);
70
-			} catch (QueryException $e) {
71
-				/*
64
+    public function loadLazyPanels(): void {
65
+        $classes = $this->lazyWidgets;
66
+        foreach ($classes as $class) {
67
+            try {
68
+                /** @var IWidget $widget */
69
+                $widget = $this->serverContainer->query($class);
70
+            } catch (QueryException $e) {
71
+                /*
72 72
 				 * There is a circular dependency between the logger and the registry, so
73 73
 				 * we can not inject it. Thus the static call.
74 74
 				 */
75
-				\OC::$server->getLogger()->logException($e, [
76
-					'message' => 'Could not load lazy dashbaord widget: ' . $e->getMessage(),
77
-					'level' => ILogger::FATAL,
78
-				]);
79
-			}
80
-			/**
81
-			 * Try to register the loaded reporter. Theoretically it could be of a wrong
82
-			 * type, so we might get a TypeError here that we should catch.
83
-			 */
84
-			try {
85
-				$this->registerWidget($widget);
86
-			} catch (Throwable $e) {
87
-				/*
75
+                \OC::$server->getLogger()->logException($e, [
76
+                    'message' => 'Could not load lazy dashbaord widget: ' . $e->getMessage(),
77
+                    'level' => ILogger::FATAL,
78
+                ]);
79
+            }
80
+            /**
81
+             * Try to register the loaded reporter. Theoretically it could be of a wrong
82
+             * type, so we might get a TypeError here that we should catch.
83
+             */
84
+            try {
85
+                $this->registerWidget($widget);
86
+            } catch (Throwable $e) {
87
+                /*
88 88
 				 * There is a circular dependency between the logger and the registry, so
89 89
 				 * we can not inject it. Thus the static call.
90 90
 				 */
91
-				\OC::$server->getLogger()->logException($e, [
92
-					'message' => 'Could not register lazy dashboard widget: ' . $e->getMessage(),
93
-					'level' => ILogger::FATAL,
94
-				]);
95
-			}
91
+                \OC::$server->getLogger()->logException($e, [
92
+                    'message' => 'Could not register lazy dashboard widget: ' . $e->getMessage(),
93
+                    'level' => ILogger::FATAL,
94
+                ]);
95
+            }
96 96
 
97
-			try {
98
-				$widget->load();
99
-			} catch (Throwable $e) {
100
-				\OC::$server->getLogger()->logException($e, [
101
-					'message' => 'Error during dashboard widget loading: ' . $e->getMessage(),
102
-					'level' => ILogger::FATAL,
103
-				]);
104
-			}
105
-		}
106
-		$this->lazyWidgets = [];
107
-	}
97
+            try {
98
+                $widget->load();
99
+            } catch (Throwable $e) {
100
+                \OC::$server->getLogger()->logException($e, [
101
+                    'message' => 'Error during dashboard widget loading: ' . $e->getMessage(),
102
+                    'level' => ILogger::FATAL,
103
+                ]);
104
+            }
105
+        }
106
+        $this->lazyWidgets = [];
107
+    }
108 108
 
109
-	public function getWidgets(): array {
110
-		$this->loadLazyPanels();
111
-		return $this->widgets;
112
-	}
109
+    public function getWidgets(): array {
110
+        $this->loadLazyPanels();
111
+        return $this->widgets;
112
+    }
113 113
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 				 * we can not inject it. Thus the static call.
74 74
 				 */
75 75
 				\OC::$server->getLogger()->logException($e, [
76
-					'message' => 'Could not load lazy dashbaord widget: ' . $e->getMessage(),
76
+					'message' => 'Could not load lazy dashbaord widget: '.$e->getMessage(),
77 77
 					'level' => ILogger::FATAL,
78 78
 				]);
79 79
 			}
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 				 * we can not inject it. Thus the static call.
90 90
 				 */
91 91
 				\OC::$server->getLogger()->logException($e, [
92
-					'message' => 'Could not register lazy dashboard widget: ' . $e->getMessage(),
92
+					'message' => 'Could not register lazy dashboard widget: '.$e->getMessage(),
93 93
 					'level' => ILogger::FATAL,
94 94
 				]);
95 95
 			}
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 				$widget->load();
99 99
 			} catch (Throwable $e) {
100 100
 				\OC::$server->getLogger()->logException($e, [
101
-					'message' => 'Error during dashboard widget loading: ' . $e->getMessage(),
101
+					'message' => 'Error during dashboard widget loading: '.$e->getMessage(),
102 102
 					'level' => ILogger::FATAL,
103 103
 				]);
104 104
 			}
Please login to merge, or discard this patch.
lib/private/legacy/OC_Util.php 1 patch
Indentation   +1394 added lines, -1394 removed lines patch added patch discarded remove patch
@@ -71,1403 +71,1403 @@
 block discarded – undo
71 71
 use OCP\IUserSession;
72 72
 
73 73
 class OC_Util {
74
-	public static $scripts = [];
75
-	public static $styles = [];
76
-	public static $headers = [];
77
-	private static $rootMounted = false;
78
-	private static $fsSetup = false;
79
-
80
-	/** @var array Local cache of version.php */
81
-	private static $versionCache = null;
82
-
83
-	protected static function getAppManager() {
84
-		return \OC::$server->getAppManager();
85
-	}
86
-
87
-	private static function initLocalStorageRootFS() {
88
-		// mount local file backend as root
89
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
90
-		//first set up the local "root" storage
91
-		\OC\Files\Filesystem::initMountManager();
92
-		if (!self::$rootMounted) {
93
-			\OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
94
-			self::$rootMounted = true;
95
-		}
96
-	}
97
-
98
-	/**
99
-	 * mounting an object storage as the root fs will in essence remove the
100
-	 * necessity of a data folder being present.
101
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
102
-	 *
103
-	 * @param array $config containing 'class' and optional 'arguments'
104
-	 * @suppress PhanDeprecatedFunction
105
-	 */
106
-	private static function initObjectStoreRootFS($config) {
107
-		// check misconfiguration
108
-		if (empty($config['class'])) {
109
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
110
-		}
111
-		if (!isset($config['arguments'])) {
112
-			$config['arguments'] = [];
113
-		}
114
-
115
-		// instantiate object store implementation
116
-		$name = $config['class'];
117
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
118
-			$segments = explode('\\', $name);
119
-			OC_App::loadApp(strtolower($segments[1]));
120
-		}
121
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
122
-		// mount with plain / root object store implementation
123
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
124
-
125
-		// mount object storage as root
126
-		\OC\Files\Filesystem::initMountManager();
127
-		if (!self::$rootMounted) {
128
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
129
-			self::$rootMounted = true;
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * mounting an object storage as the root fs will in essence remove the
135
-	 * necessity of a data folder being present.
136
-	 *
137
-	 * @param array $config containing 'class' and optional 'arguments'
138
-	 * @suppress PhanDeprecatedFunction
139
-	 */
140
-	private static function initObjectStoreMultibucketRootFS($config) {
141
-		// check misconfiguration
142
-		if (empty($config['class'])) {
143
-			\OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
144
-		}
145
-		if (!isset($config['arguments'])) {
146
-			$config['arguments'] = [];
147
-		}
148
-
149
-		// instantiate object store implementation
150
-		$name = $config['class'];
151
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
152
-			$segments = explode('\\', $name);
153
-			OC_App::loadApp(strtolower($segments[1]));
154
-		}
155
-
156
-		if (!isset($config['arguments']['bucket'])) {
157
-			$config['arguments']['bucket'] = '';
158
-		}
159
-		// put the root FS always in first bucket for multibucket configuration
160
-		$config['arguments']['bucket'] .= '0';
161
-
162
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
163
-		// mount with plain / root object store implementation
164
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
165
-
166
-		// mount object storage as root
167
-		\OC\Files\Filesystem::initMountManager();
168
-		if (!self::$rootMounted) {
169
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
170
-			self::$rootMounted = true;
171
-		}
172
-	}
173
-
174
-	/**
175
-	 * Can be set up
176
-	 *
177
-	 * @param string $user
178
-	 * @return boolean
179
-	 * @description configure the initial filesystem based on the configuration
180
-	 * @suppress PhanDeprecatedFunction
181
-	 * @suppress PhanAccessMethodInternal
182
-	 */
183
-	public static function setupFS($user = '') {
184
-		//setting up the filesystem twice can only lead to trouble
185
-		if (self::$fsSetup) {
186
-			return false;
187
-		}
188
-
189
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
190
-
191
-		// If we are not forced to load a specific user we load the one that is logged in
192
-		if ($user === null) {
193
-			$user = '';
194
-		} elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
195
-			$user = OC_User::getUser();
196
-		}
197
-
198
-		// load all filesystem apps before, so no setup-hook gets lost
199
-		OC_App::loadApps(['filesystem']);
200
-
201
-		// the filesystem will finish when $user is not empty,
202
-		// mark fs setup here to avoid doing the setup from loading
203
-		// OC_Filesystem
204
-		if ($user != '') {
205
-			self::$fsSetup = true;
206
-		}
207
-
208
-		\OC\Files\Filesystem::initMountManager();
209
-
210
-		$prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
211
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
212
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
213
-				/** @var \OC\Files\Storage\Common $storage */
214
-				$storage->setMountOptions($mount->getOptions());
215
-			}
216
-			return $storage;
217
-		});
218
-
219
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
220
-			if (!$mount->getOption('enable_sharing', true)) {
221
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
222
-					'storage' => $storage,
223
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
224
-				]);
225
-			}
226
-			return $storage;
227
-		});
228
-
229
-		// install storage availability wrapper, before most other wrappers
230
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
231
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
232
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
233
-			}
234
-			return $storage;
235
-		});
236
-
237
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
238
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
239
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
240
-			}
241
-			return $storage;
242
-		});
243
-
244
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
245
-			// set up quota for home storages, even for other users
246
-			// which can happen when using sharing
247
-
248
-			/**
249
-			 * @var \OC\Files\Storage\Storage $storage
250
-			 */
251
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
252
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
253
-			) {
254
-				/** @var \OC\Files\Storage\Home $storage */
255
-				if (is_object($storage->getUser())) {
256
-					$quota = OC_Util::getUserQuota($storage->getUser());
257
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
258
-						return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
259
-					}
260
-				}
261
-			}
262
-
263
-			return $storage;
264
-		});
265
-
266
-		\OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
267
-			/*
74
+    public static $scripts = [];
75
+    public static $styles = [];
76
+    public static $headers = [];
77
+    private static $rootMounted = false;
78
+    private static $fsSetup = false;
79
+
80
+    /** @var array Local cache of version.php */
81
+    private static $versionCache = null;
82
+
83
+    protected static function getAppManager() {
84
+        return \OC::$server->getAppManager();
85
+    }
86
+
87
+    private static function initLocalStorageRootFS() {
88
+        // mount local file backend as root
89
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
90
+        //first set up the local "root" storage
91
+        \OC\Files\Filesystem::initMountManager();
92
+        if (!self::$rootMounted) {
93
+            \OC\Files\Filesystem::mount(LocalRootStorage::class, ['datadir' => $configDataDirectory], '/');
94
+            self::$rootMounted = true;
95
+        }
96
+    }
97
+
98
+    /**
99
+     * mounting an object storage as the root fs will in essence remove the
100
+     * necessity of a data folder being present.
101
+     * TODO make home storage aware of this and use the object storage instead of local disk access
102
+     *
103
+     * @param array $config containing 'class' and optional 'arguments'
104
+     * @suppress PhanDeprecatedFunction
105
+     */
106
+    private static function initObjectStoreRootFS($config) {
107
+        // check misconfiguration
108
+        if (empty($config['class'])) {
109
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
110
+        }
111
+        if (!isset($config['arguments'])) {
112
+            $config['arguments'] = [];
113
+        }
114
+
115
+        // instantiate object store implementation
116
+        $name = $config['class'];
117
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
118
+            $segments = explode('\\', $name);
119
+            OC_App::loadApp(strtolower($segments[1]));
120
+        }
121
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
122
+        // mount with plain / root object store implementation
123
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
124
+
125
+        // mount object storage as root
126
+        \OC\Files\Filesystem::initMountManager();
127
+        if (!self::$rootMounted) {
128
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
129
+            self::$rootMounted = true;
130
+        }
131
+    }
132
+
133
+    /**
134
+     * mounting an object storage as the root fs will in essence remove the
135
+     * necessity of a data folder being present.
136
+     *
137
+     * @param array $config containing 'class' and optional 'arguments'
138
+     * @suppress PhanDeprecatedFunction
139
+     */
140
+    private static function initObjectStoreMultibucketRootFS($config) {
141
+        // check misconfiguration
142
+        if (empty($config['class'])) {
143
+            \OCP\Util::writeLog('files', 'No class given for objectstore', ILogger::ERROR);
144
+        }
145
+        if (!isset($config['arguments'])) {
146
+            $config['arguments'] = [];
147
+        }
148
+
149
+        // instantiate object store implementation
150
+        $name = $config['class'];
151
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
152
+            $segments = explode('\\', $name);
153
+            OC_App::loadApp(strtolower($segments[1]));
154
+        }
155
+
156
+        if (!isset($config['arguments']['bucket'])) {
157
+            $config['arguments']['bucket'] = '';
158
+        }
159
+        // put the root FS always in first bucket for multibucket configuration
160
+        $config['arguments']['bucket'] .= '0';
161
+
162
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
163
+        // mount with plain / root object store implementation
164
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
165
+
166
+        // mount object storage as root
167
+        \OC\Files\Filesystem::initMountManager();
168
+        if (!self::$rootMounted) {
169
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
170
+            self::$rootMounted = true;
171
+        }
172
+    }
173
+
174
+    /**
175
+     * Can be set up
176
+     *
177
+     * @param string $user
178
+     * @return boolean
179
+     * @description configure the initial filesystem based on the configuration
180
+     * @suppress PhanDeprecatedFunction
181
+     * @suppress PhanAccessMethodInternal
182
+     */
183
+    public static function setupFS($user = '') {
184
+        //setting up the filesystem twice can only lead to trouble
185
+        if (self::$fsSetup) {
186
+            return false;
187
+        }
188
+
189
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
190
+
191
+        // If we are not forced to load a specific user we load the one that is logged in
192
+        if ($user === null) {
193
+            $user = '';
194
+        } elseif ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
195
+            $user = OC_User::getUser();
196
+        }
197
+
198
+        // load all filesystem apps before, so no setup-hook gets lost
199
+        OC_App::loadApps(['filesystem']);
200
+
201
+        // the filesystem will finish when $user is not empty,
202
+        // mark fs setup here to avoid doing the setup from loading
203
+        // OC_Filesystem
204
+        if ($user != '') {
205
+            self::$fsSetup = true;
206
+        }
207
+
208
+        \OC\Files\Filesystem::initMountManager();
209
+
210
+        $prevLogging = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
211
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
212
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
213
+                /** @var \OC\Files\Storage\Common $storage */
214
+                $storage->setMountOptions($mount->getOptions());
215
+            }
216
+            return $storage;
217
+        });
218
+
219
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
220
+            if (!$mount->getOption('enable_sharing', true)) {
221
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
222
+                    'storage' => $storage,
223
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
224
+                ]);
225
+            }
226
+            return $storage;
227
+        });
228
+
229
+        // install storage availability wrapper, before most other wrappers
230
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
231
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
232
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
233
+            }
234
+            return $storage;
235
+        });
236
+
237
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
238
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
239
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
240
+            }
241
+            return $storage;
242
+        });
243
+
244
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
245
+            // set up quota for home storages, even for other users
246
+            // which can happen when using sharing
247
+
248
+            /**
249
+             * @var \OC\Files\Storage\Storage $storage
250
+             */
251
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
252
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
253
+            ) {
254
+                /** @var \OC\Files\Storage\Home $storage */
255
+                if (is_object($storage->getUser())) {
256
+                    $quota = OC_Util::getUserQuota($storage->getUser());
257
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
258
+                        return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $quota, 'root' => 'files']);
259
+                    }
260
+                }
261
+            }
262
+
263
+            return $storage;
264
+        });
265
+
266
+        \OC\Files\Filesystem::addStorageWrapper('readonly', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
267
+            /*
268 268
 			 * Do not allow any operations that modify the storage
269 269
 			 */
270
-			if ($mount->getOption('readonly', false)) {
271
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
272
-					'storage' => $storage,
273
-					'mask' => \OCP\Constants::PERMISSION_ALL & ~(
274
-						\OCP\Constants::PERMISSION_UPDATE |
275
-						\OCP\Constants::PERMISSION_CREATE |
276
-						\OCP\Constants::PERMISSION_DELETE
277
-					),
278
-				]);
279
-			}
280
-			return $storage;
281
-		});
282
-
283
-		OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
284
-
285
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
286
-
287
-		//check if we are using an object storage
288
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
289
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
290
-
291
-		// use the same order as in ObjectHomeMountProvider
292
-		if (isset($objectStoreMultibucket)) {
293
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
294
-		} elseif (isset($objectStore)) {
295
-			self::initObjectStoreRootFS($objectStore);
296
-		} else {
297
-			self::initLocalStorageRootFS();
298
-		}
299
-
300
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
301
-			\OC::$server->getEventLogger()->end('setup_fs');
302
-			return false;
303
-		}
304
-
305
-		//if we aren't logged in, there is no use to set up the filesystem
306
-		if ($user != "") {
307
-			$userDir = '/' . $user . '/files';
308
-
309
-			//jail the user into his "home" directory
310
-			\OC\Files\Filesystem::init($user, $userDir);
311
-
312
-			OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
313
-		}
314
-		\OC::$server->getEventLogger()->end('setup_fs');
315
-		return true;
316
-	}
317
-
318
-	/**
319
-	 * check if a password is required for each public link
320
-	 *
321
-	 * @return boolean
322
-	 * @suppress PhanDeprecatedFunction
323
-	 */
324
-	public static function isPublicLinkPasswordRequired() {
325
-		$enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
326
-		return $enforcePassword === 'yes';
327
-	}
328
-
329
-	/**
330
-	 * check if sharing is disabled for the current user
331
-	 * @param IConfig $config
332
-	 * @param IGroupManager $groupManager
333
-	 * @param IUser|null $user
334
-	 * @return bool
335
-	 */
336
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
337
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
338
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
339
-			$excludedGroups = json_decode($groupsList);
340
-			if (is_null($excludedGroups)) {
341
-				$excludedGroups = explode(',', $groupsList);
342
-				$newValue = json_encode($excludedGroups);
343
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
344
-			}
345
-			$usersGroups = $groupManager->getUserGroupIds($user);
346
-			if (!empty($usersGroups)) {
347
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
348
-				// if the user is only in groups which are disabled for sharing then
349
-				// sharing is also disabled for the user
350
-				if (empty($remainingGroups)) {
351
-					return true;
352
-				}
353
-			}
354
-		}
355
-		return false;
356
-	}
357
-
358
-	/**
359
-	 * check if share API enforces a default expire date
360
-	 *
361
-	 * @return boolean
362
-	 * @suppress PhanDeprecatedFunction
363
-	 */
364
-	public static function isDefaultExpireDateEnforced() {
365
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
366
-		$enforceDefaultExpireDate = false;
367
-		if ($isDefaultExpireDateEnabled === 'yes') {
368
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
369
-			$enforceDefaultExpireDate = $value === 'yes';
370
-		}
371
-
372
-		return $enforceDefaultExpireDate;
373
-	}
374
-
375
-	/**
376
-	 * Get the quota of a user
377
-	 *
378
-	 * @param IUser|null $user
379
-	 * @return float Quota bytes
380
-	 */
381
-	public static function getUserQuota(?IUser $user) {
382
-		if (is_null($user)) {
383
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
384
-		}
385
-		$userQuota = $user->getQuota();
386
-		if ($userQuota === 'none') {
387
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
388
-		}
389
-		return OC_Helper::computerFileSize($userQuota);
390
-	}
391
-
392
-	/**
393
-	 * copies the skeleton to the users /files
394
-	 *
395
-	 * @param string $userId
396
-	 * @param \OCP\Files\Folder $userDirectory
397
-	 * @throws \OCP\Files\NotFoundException
398
-	 * @throws \OCP\Files\NotPermittedException
399
-	 * @suppress PhanDeprecatedFunction
400
-	 */
401
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
402
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
404
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
-
406
-		if (!file_exists($skeletonDirectory)) {
407
-			$dialectStart = strpos($userLang, '_');
408
-			if ($dialectStart !== false) {
409
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
-			}
411
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
-			}
414
-			if (!file_exists($skeletonDirectory)) {
415
-				$skeletonDirectory = '';
416
-			}
417
-		}
418
-
419
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
-
421
-		if ($instanceId === null) {
422
-			throw new \RuntimeException('no instance id!');
423
-		}
424
-		$appdata = 'appdata_' . $instanceId;
425
-		if ($userId === $appdata) {
426
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
427
-		}
428
-
429
-		if (!empty($skeletonDirectory)) {
430
-			\OCP\Util::writeLog(
431
-				'files_skeleton',
432
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
433
-				ILogger::DEBUG
434
-			);
435
-			self::copyr($skeletonDirectory, $userDirectory);
436
-			// update the file cache
437
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * copies a directory recursively by using streams
443
-	 *
444
-	 * @param string $source
445
-	 * @param \OCP\Files\Folder $target
446
-	 * @return void
447
-	 */
448
-	public static function copyr($source, \OCP\Files\Folder $target) {
449
-		$logger = \OC::$server->getLogger();
450
-
451
-		// Verify if folder exists
452
-		$dir = opendir($source);
453
-		if ($dir === false) {
454
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
-			return;
456
-		}
457
-
458
-		// Copy the files
459
-		while (false !== ($file = readdir($dir))) {
460
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
-				if (is_dir($source . '/' . $file)) {
462
-					$child = $target->newFolder($file);
463
-					self::copyr($source . '/' . $file, $child);
464
-				} else {
465
-					$child = $target->newFile($file);
466
-					$sourceStream = fopen($source . '/' . $file, 'r');
467
-					if ($sourceStream === false) {
468
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
-						closedir($dir);
470
-						return;
471
-					}
472
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
-				}
474
-			}
475
-		}
476
-		closedir($dir);
477
-	}
478
-
479
-	/**
480
-	 * @return void
481
-	 * @suppress PhanUndeclaredMethod
482
-	 */
483
-	public static function tearDownFS() {
484
-		\OC\Files\Filesystem::tearDown();
485
-		\OC::$server->getRootFolder()->clearCache();
486
-		self::$fsSetup = false;
487
-		self::$rootMounted = false;
488
-	}
489
-
490
-	/**
491
-	 * get the current installed version of ownCloud
492
-	 *
493
-	 * @return array
494
-	 */
495
-	public static function getVersion() {
496
-		OC_Util::loadVersion();
497
-		return self::$versionCache['OC_Version'];
498
-	}
499
-
500
-	/**
501
-	 * get the current installed version string of ownCloud
502
-	 *
503
-	 * @return string
504
-	 */
505
-	public static function getVersionString() {
506
-		OC_Util::loadVersion();
507
-		return self::$versionCache['OC_VersionString'];
508
-	}
509
-
510
-	/**
511
-	 * @deprecated the value is of no use anymore
512
-	 * @return string
513
-	 */
514
-	public static function getEditionString() {
515
-		return '';
516
-	}
517
-
518
-	/**
519
-	 * @description get the update channel of the current installed of ownCloud.
520
-	 * @return string
521
-	 */
522
-	public static function getChannel() {
523
-		OC_Util::loadVersion();
524
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
-	}
526
-
527
-	/**
528
-	 * @description get the build number of the current installed of ownCloud.
529
-	 * @return string
530
-	 */
531
-	public static function getBuild() {
532
-		OC_Util::loadVersion();
533
-		return self::$versionCache['OC_Build'];
534
-	}
535
-
536
-	/**
537
-	 * @description load the version.php into the session as cache
538
-	 * @suppress PhanUndeclaredVariable
539
-	 */
540
-	private static function loadVersion() {
541
-		if (self::$versionCache !== null) {
542
-			return;
543
-		}
544
-
545
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
-		require OC::$SERVERROOT . '/version.php';
547
-		/** @var $timestamp int */
548
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
-		/** @var $OC_Version string */
550
-		self::$versionCache['OC_Version'] = $OC_Version;
551
-		/** @var $OC_VersionString string */
552
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
-		/** @var $OC_Build string */
554
-		self::$versionCache['OC_Build'] = $OC_Build;
555
-
556
-		/** @var $OC_Channel string */
557
-		self::$versionCache['OC_Channel'] = $OC_Channel;
558
-	}
559
-
560
-	/**
561
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
-	 *
563
-	 * @param string $application application to get the files from
564
-	 * @param string $directory directory within this application (css, js, vendor, etc)
565
-	 * @param string $file the file inside of the above folder
566
-	 * @return string the path
567
-	 */
568
-	private static function generatePath($application, $directory, $file) {
569
-		if (is_null($file)) {
570
-			$file = $application;
571
-			$application = "";
572
-		}
573
-		if (!empty($application)) {
574
-			return "$application/$directory/$file";
575
-		} else {
576
-			return "$directory/$file";
577
-		}
578
-	}
579
-
580
-	/**
581
-	 * add a javascript file
582
-	 *
583
-	 * @param string $application application id
584
-	 * @param string|null $file filename
585
-	 * @param bool $prepend prepend the Script to the beginning of the list
586
-	 * @return void
587
-	 */
588
-	public static function addScript($application, $file = null, $prepend = false) {
589
-		$path = OC_Util::generatePath($application, 'js', $file);
590
-
591
-		// core js files need separate handling
592
-		if ($application !== 'core' && $file !== null) {
593
-			self::addTranslations($application);
594
-		}
595
-		self::addExternalResource($application, $prepend, $path, "script");
596
-	}
597
-
598
-	/**
599
-	 * add a javascript file from the vendor sub folder
600
-	 *
601
-	 * @param string $application application id
602
-	 * @param string|null $file filename
603
-	 * @param bool $prepend prepend the Script to the beginning of the list
604
-	 * @return void
605
-	 */
606
-	public static function addVendorScript($application, $file = null, $prepend = false) {
607
-		$path = OC_Util::generatePath($application, 'vendor', $file);
608
-		self::addExternalResource($application, $prepend, $path, "script");
609
-	}
610
-
611
-	/**
612
-	 * add a translation JS file
613
-	 *
614
-	 * @param string $application application id
615
-	 * @param string|null $languageCode language code, defaults to the current language
616
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
617
-	 */
618
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
619
-		if (is_null($languageCode)) {
620
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
621
-		}
622
-		if (!empty($application)) {
623
-			$path = "$application/l10n/$languageCode";
624
-		} else {
625
-			$path = "l10n/$languageCode";
626
-		}
627
-		self::addExternalResource($application, $prepend, $path, "script");
628
-	}
629
-
630
-	/**
631
-	 * add a css file
632
-	 *
633
-	 * @param string $application application id
634
-	 * @param string|null $file filename
635
-	 * @param bool $prepend prepend the Style to the beginning of the list
636
-	 * @return void
637
-	 */
638
-	public static function addStyle($application, $file = null, $prepend = false) {
639
-		$path = OC_Util::generatePath($application, 'css', $file);
640
-		self::addExternalResource($application, $prepend, $path, "style");
641
-	}
642
-
643
-	/**
644
-	 * add a css file from the vendor sub folder
645
-	 *
646
-	 * @param string $application application id
647
-	 * @param string|null $file filename
648
-	 * @param bool $prepend prepend the Style to the beginning of the list
649
-	 * @return void
650
-	 */
651
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
652
-		$path = OC_Util::generatePath($application, 'vendor', $file);
653
-		self::addExternalResource($application, $prepend, $path, "style");
654
-	}
655
-
656
-	/**
657
-	 * add an external resource css/js file
658
-	 *
659
-	 * @param string $application application id
660
-	 * @param bool $prepend prepend the file to the beginning of the list
661
-	 * @param string $path
662
-	 * @param string $type (script or style)
663
-	 * @return void
664
-	 */
665
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
666
-		if ($type === "style") {
667
-			if (!in_array($path, self::$styles)) {
668
-				if ($prepend === true) {
669
-					array_unshift(self::$styles, $path);
670
-				} else {
671
-					self::$styles[] = $path;
672
-				}
673
-			}
674
-		} elseif ($type === "script") {
675
-			if (!in_array($path, self::$scripts)) {
676
-				if ($prepend === true) {
677
-					array_unshift(self::$scripts, $path);
678
-				} else {
679
-					self::$scripts [] = $path;
680
-				}
681
-			}
682
-		}
683
-	}
684
-
685
-	/**
686
-	 * Add a custom element to the header
687
-	 * If $text is null then the element will be written as empty element.
688
-	 * So use "" to get a closing tag.
689
-	 * @param string $tag tag name of the element
690
-	 * @param array $attributes array of attributes for the element
691
-	 * @param string $text the text content for the element
692
-	 * @param bool $prepend prepend the header to the beginning of the list
693
-	 */
694
-	public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
695
-		$header = [
696
-			'tag' => $tag,
697
-			'attributes' => $attributes,
698
-			'text' => $text
699
-		];
700
-		if ($prepend === true) {
701
-			array_unshift(self::$headers, $header);
702
-		} else {
703
-			self::$headers[] = $header;
704
-		}
705
-	}
706
-
707
-	/**
708
-	 * check if the current server configuration is suitable for ownCloud
709
-	 *
710
-	 * @param \OC\SystemConfig $config
711
-	 * @return array arrays with error messages and hints
712
-	 */
713
-	public static function checkServer(\OC\SystemConfig $config) {
714
-		$l = \OC::$server->getL10N('lib');
715
-		$errors = [];
716
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
717
-
718
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
719
-			// this check needs to be done every time
720
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
721
-		}
722
-
723
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
724
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
725
-			return $errors;
726
-		}
727
-
728
-		$webServerRestart = false;
729
-		$setup = new \OC\Setup(
730
-			$config,
731
-			\OC::$server->getIniWrapper(),
732
-			\OC::$server->getL10N('lib'),
733
-			\OC::$server->query(\OCP\Defaults::class),
734
-			\OC::$server->getLogger(),
735
-			\OC::$server->getSecureRandom(),
736
-			\OC::$server->query(\OC\Installer::class)
737
-		);
738
-
739
-		$urlGenerator = \OC::$server->getURLGenerator();
740
-
741
-		$availableDatabases = $setup->getSupportedDatabases();
742
-		if (empty($availableDatabases)) {
743
-			$errors[] = [
744
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
745
-				'hint' => '' //TODO: sane hint
746
-			];
747
-			$webServerRestart = true;
748
-		}
749
-
750
-		// Check if config folder is writable.
751
-		if (!OC_Helper::isReadOnlyConfigEnabled()) {
752
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
753
-				$errors[] = [
754
-					'error' => $l->t('Cannot write into "config" directory'),
755
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
756
-						[ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
757
-						. $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',
758
-						[ $urlGenerator->linkToDocs('admin-config') ])
759
-				];
760
-			}
761
-		}
762
-
763
-		// Check if there is a writable install folder.
764
-		if ($config->getValue('appstoreenabled', true)) {
765
-			if (OC_App::getInstallPath() === null
766
-				|| !is_writable(OC_App::getInstallPath())
767
-				|| !is_readable(OC_App::getInstallPath())
768
-			) {
769
-				$errors[] = [
770
-					'error' => $l->t('Cannot write into "apps" directory'),
771
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
772
-						. ' or disabling the appstore in the config file.')
773
-				];
774
-			}
775
-		}
776
-		// Create root dir.
777
-		if ($config->getValue('installed', false)) {
778
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
779
-				$success = @mkdir($CONFIG_DATADIRECTORY);
780
-				if ($success) {
781
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
782
-				} else {
783
-					$errors[] = [
784
-						'error' => $l->t('Cannot create "data" directory'),
785
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
786
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
787
-					];
788
-				}
789
-			} elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
790
-				// is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
791
-				$testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
792
-				$handle = fopen($testFile, 'w');
793
-				if (!$handle || fwrite($handle, 'Test write operation') === false) {
794
-					$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
795
-						[$urlGenerator->linkToDocs('admin-dir_permissions')]);
796
-					$errors[] = [
797
-						'error' => 'Your data directory is not writable',
798
-						'hint' => $permissionsHint
799
-					];
800
-				} else {
801
-					fclose($handle);
802
-					unlink($testFile);
803
-				}
804
-			} else {
805
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
806
-			}
807
-		}
808
-
809
-		if (!OC_Util::isSetLocaleWorking()) {
810
-			$errors[] = [
811
-				'error' => $l->t('Setting locale to %s failed',
812
-					['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
813
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
814
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
815
-			];
816
-		}
817
-
818
-		// Contains the dependencies that should be checked against
819
-		// classes = class_exists
820
-		// functions = function_exists
821
-		// defined = defined
822
-		// ini = ini_get
823
-		// If the dependency is not found the missing module name is shown to the EndUser
824
-		// When adding new checks always verify that they pass on Travis as well
825
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
826
-		$dependencies = [
827
-			'classes' => [
828
-				'ZipArchive' => 'zip',
829
-				'DOMDocument' => 'dom',
830
-				'XMLWriter' => 'XMLWriter',
831
-				'XMLReader' => 'XMLReader',
832
-			],
833
-			'functions' => [
834
-				'xml_parser_create' => 'libxml',
835
-				'mb_strcut' => 'mbstring',
836
-				'ctype_digit' => 'ctype',
837
-				'json_encode' => 'JSON',
838
-				'gd_info' => 'GD',
839
-				'gzencode' => 'zlib',
840
-				'iconv' => 'iconv',
841
-				'simplexml_load_string' => 'SimpleXML',
842
-				'hash' => 'HASH Message Digest Framework',
843
-				'curl_init' => 'cURL',
844
-				'openssl_verify' => 'OpenSSL',
845
-			],
846
-			'defined' => [
847
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
848
-			],
849
-			'ini' => [
850
-				'default_charset' => 'UTF-8',
851
-			],
852
-		];
853
-		$missingDependencies = [];
854
-		$invalidIniSettings = [];
855
-
856
-		$iniWrapper = \OC::$server->getIniWrapper();
857
-		foreach ($dependencies['classes'] as $class => $module) {
858
-			if (!class_exists($class)) {
859
-				$missingDependencies[] = $module;
860
-			}
861
-		}
862
-		foreach ($dependencies['functions'] as $function => $module) {
863
-			if (!function_exists($function)) {
864
-				$missingDependencies[] = $module;
865
-			}
866
-		}
867
-		foreach ($dependencies['defined'] as $defined => $module) {
868
-			if (!defined($defined)) {
869
-				$missingDependencies[] = $module;
870
-			}
871
-		}
872
-		foreach ($dependencies['ini'] as $setting => $expected) {
873
-			if (is_bool($expected)) {
874
-				if ($iniWrapper->getBool($setting) !== $expected) {
875
-					$invalidIniSettings[] = [$setting, $expected];
876
-				}
877
-			}
878
-			if (is_int($expected)) {
879
-				if ($iniWrapper->getNumeric($setting) !== $expected) {
880
-					$invalidIniSettings[] = [$setting, $expected];
881
-				}
882
-			}
883
-			if (is_string($expected)) {
884
-				if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
885
-					$invalidIniSettings[] = [$setting, $expected];
886
-				}
887
-			}
888
-		}
889
-
890
-		foreach ($missingDependencies as $missingDependency) {
891
-			$errors[] = [
892
-				'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
893
-				'hint' => $l->t('Please ask your server administrator to install the module.'),
894
-			];
895
-			$webServerRestart = true;
896
-		}
897
-		foreach ($invalidIniSettings as $setting) {
898
-			if (is_bool($setting[1])) {
899
-				$setting[1] = $setting[1] ? 'on' : 'off';
900
-			}
901
-			$errors[] = [
902
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
903
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
904
-			];
905
-			$webServerRestart = true;
906
-		}
907
-
908
-		/**
909
-		 * The mbstring.func_overload check can only be performed if the mbstring
910
-		 * module is installed as it will return null if the checking setting is
911
-		 * not available and thus a check on the boolean value fails.
912
-		 *
913
-		 * TODO: Should probably be implemented in the above generic dependency
914
-		 *       check somehow in the long-term.
915
-		 */
916
-		if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
917
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
918
-			$errors[] = [
919
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
920
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
921
-			];
922
-		}
923
-
924
-		if (function_exists('xml_parser_create') &&
925
-			LIBXML_LOADED_VERSION < 20700) {
926
-			$version = LIBXML_LOADED_VERSION;
927
-			$major = floor($version/10000);
928
-			$version -= ($major * 10000);
929
-			$minor = floor($version/100);
930
-			$version -= ($minor * 100);
931
-			$patch = $version;
932
-			$errors[] = [
933
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
934
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
935
-			];
936
-		}
937
-
938
-		if (!self::isAnnotationsWorking()) {
939
-			$errors[] = [
940
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
941
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
942
-			];
943
-		}
944
-
945
-		if (!\OC::$CLI && $webServerRestart) {
946
-			$errors[] = [
947
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
948
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
949
-			];
950
-		}
951
-
952
-		$errors = array_merge($errors, self::checkDatabaseVersion());
953
-
954
-		// Cache the result of this function
955
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
956
-
957
-		return $errors;
958
-	}
959
-
960
-	/**
961
-	 * Check the database version
962
-	 *
963
-	 * @return array errors array
964
-	 */
965
-	public static function checkDatabaseVersion() {
966
-		$l = \OC::$server->getL10N('lib');
967
-		$errors = [];
968
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
969
-		if ($dbType === 'pgsql') {
970
-			// check PostgreSQL version
971
-			try {
972
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
973
-				$data = $result->fetchRow();
974
-				if (isset($data['server_version'])) {
975
-					$version = $data['server_version'];
976
-					if (version_compare($version, '9.0.0', '<')) {
977
-						$errors[] = [
978
-							'error' => $l->t('PostgreSQL >= 9 required'),
979
-							'hint' => $l->t('Please upgrade your database version')
980
-						];
981
-					}
982
-				}
983
-			} catch (\Doctrine\DBAL\DBALException $e) {
984
-				$logger = \OC::$server->getLogger();
985
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
986
-				$logger->logException($e);
987
-			}
988
-		}
989
-		return $errors;
990
-	}
991
-
992
-	/**
993
-	 * Check for correct file permissions of data directory
994
-	 *
995
-	 * @param string $dataDirectory
996
-	 * @return array arrays with error messages and hints
997
-	 */
998
-	public static function checkDataDirectoryPermissions($dataDirectory) {
999
-		if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1000
-			return  [];
1001
-		}
1002
-
1003
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1004
-		if (substr($perms, -1) !== '0') {
1005
-			chmod($dataDirectory, 0770);
1006
-			clearstatcache();
1007
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1008
-			if ($perms[2] !== '0') {
1009
-				$l = \OC::$server->getL10N('lib');
1010
-				return [[
1011
-					'error' => $l->t('Your data directory is readable by other users'),
1012
-					'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1013
-				]];
1014
-			}
1015
-		}
1016
-		return [];
1017
-	}
1018
-
1019
-	/**
1020
-	 * Check that the data directory exists and is valid by
1021
-	 * checking the existence of the ".ocdata" file.
1022
-	 *
1023
-	 * @param string $dataDirectory data directory path
1024
-	 * @return array errors found
1025
-	 */
1026
-	public static function checkDataDirectoryValidity($dataDirectory) {
1027
-		$l = \OC::$server->getL10N('lib');
1028
-		$errors = [];
1029
-		if ($dataDirectory[0] !== '/') {
1030
-			$errors[] = [
1031
-				'error' => $l->t('Your data directory must be an absolute path'),
1032
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1033
-			];
1034
-		}
1035
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1036
-			$errors[] = [
1037
-				'error' => $l->t('Your data directory is invalid'),
1038
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1039
-					' in the root of the data directory.')
1040
-			];
1041
-		}
1042
-		return $errors;
1043
-	}
1044
-
1045
-	/**
1046
-	 * Check if the user is logged in, redirects to home if not. With
1047
-	 * redirect URL parameter to the request URI.
1048
-	 *
1049
-	 * @return void
1050
-	 */
1051
-	public static function checkLoggedIn() {
1052
-		// Check if we are a user
1053
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1054
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1055
-						'core.login.showLoginForm',
1056
-						[
1057
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1058
-						]
1059
-					)
1060
-			);
1061
-			exit();
1062
-		}
1063
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1064
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1065
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1066
-			exit();
1067
-		}
1068
-	}
1069
-
1070
-	/**
1071
-	 * Check if the user is a admin, redirects to home if not
1072
-	 *
1073
-	 * @return void
1074
-	 */
1075
-	public static function checkAdminUser() {
1076
-		OC_Util::checkLoggedIn();
1077
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1078
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1079
-			exit();
1080
-		}
1081
-	}
1082
-
1083
-	/**
1084
-	 * Returns the URL of the default page
1085
-	 * based on the system configuration and
1086
-	 * the apps visible for the current user
1087
-	 *
1088
-	 * @return string URL
1089
-	 * @suppress PhanDeprecatedFunction
1090
-	 */
1091
-	public static function getDefaultPageUrl() {
1092
-		/** @var IConfig $config */
1093
-		$config = \OC::$server->get(IConfig::class);
1094
-		$urlGenerator = \OC::$server->getURLGenerator();
1095
-		// Deny the redirect if the URL contains a @
1096
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1097
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1098
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1099
-		} else {
1100
-			$defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1101
-			if ($defaultPage) {
1102
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1103
-			} else {
1104
-				$appId = 'files';
1105
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1106
-
1107
-				/** @var IUserSession $userSession */
1108
-				$userSession = \OC::$server->get(IUserSession::class);
1109
-				$user = $userSession->getUser();
1110
-				if ($user) {
1111
-					$userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1112
-					$defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1113
-				}
1114
-
1115
-				// find the first app that is enabled for the current user
1116
-				foreach ($defaultApps as $defaultApp) {
1117
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1118
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1119
-						$appId = $defaultApp;
1120
-						break;
1121
-					}
1122
-				}
1123
-
1124
-				if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1125
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1126
-				} else {
1127
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1128
-				}
1129
-			}
1130
-		}
1131
-		return $location;
1132
-	}
1133
-
1134
-	/**
1135
-	 * Redirect to the user default page
1136
-	 *
1137
-	 * @return void
1138
-	 */
1139
-	public static function redirectToDefaultPage() {
1140
-		$location = self::getDefaultPageUrl();
1141
-		header('Location: ' . $location);
1142
-		exit();
1143
-	}
1144
-
1145
-	/**
1146
-	 * get an id unique for this instance
1147
-	 *
1148
-	 * @return string
1149
-	 */
1150
-	public static function getInstanceId() {
1151
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1152
-		if (is_null($id)) {
1153
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1154
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1155
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1156
-		}
1157
-		return $id;
1158
-	}
1159
-
1160
-	/**
1161
-	 * Public function to sanitize HTML
1162
-	 *
1163
-	 * This function is used to sanitize HTML and should be applied on any
1164
-	 * string or array of strings before displaying it on a web page.
1165
-	 *
1166
-	 * @param string|array $value
1167
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1168
-	 */
1169
-	public static function sanitizeHTML($value) {
1170
-		if (is_array($value)) {
1171
-			$value = array_map(function ($value) {
1172
-				return self::sanitizeHTML($value);
1173
-			}, $value);
1174
-		} else {
1175
-			// Specify encoding for PHP<5.4
1176
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1177
-		}
1178
-		return $value;
1179
-	}
1180
-
1181
-	/**
1182
-	 * Public function to encode url parameters
1183
-	 *
1184
-	 * This function is used to encode path to file before output.
1185
-	 * Encoding is done according to RFC 3986 with one exception:
1186
-	 * Character '/' is preserved as is.
1187
-	 *
1188
-	 * @param string $component part of URI to encode
1189
-	 * @return string
1190
-	 */
1191
-	public static function encodePath($component) {
1192
-		$encoded = rawurlencode($component);
1193
-		$encoded = str_replace('%2F', '/', $encoded);
1194
-		return $encoded;
1195
-	}
1196
-
1197
-
1198
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1199
-		// php dev server does not support htaccess
1200
-		if (php_sapi_name() === 'cli-server') {
1201
-			return false;
1202
-		}
1203
-
1204
-		// testdata
1205
-		$fileName = '/htaccesstest.txt';
1206
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1207
-
1208
-		// creating a test file
1209
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1210
-
1211
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1212
-			return false;
1213
-		}
1214
-
1215
-		$fp = @fopen($testFile, 'w');
1216
-		if (!$fp) {
1217
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1218
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1219
-		}
1220
-		fwrite($fp, $testContent);
1221
-		fclose($fp);
1222
-
1223
-		return $testContent;
1224
-	}
1225
-
1226
-	/**
1227
-	 * Check if the .htaccess file is working
1228
-	 * @param \OCP\IConfig $config
1229
-	 * @return bool
1230
-	 * @throws Exception
1231
-	 * @throws \OC\HintException If the test file can't get written.
1232
-	 */
1233
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1234
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1235
-			return true;
1236
-		}
1237
-
1238
-		$testContent = $this->createHtaccessTestFile($config);
1239
-		if ($testContent === false) {
1240
-			return false;
1241
-		}
1242
-
1243
-		$fileName = '/htaccesstest.txt';
1244
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1245
-
1246
-		// accessing the file via http
1247
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1248
-		try {
1249
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1250
-		} catch (\Exception $e) {
1251
-			$content = false;
1252
-		}
1253
-
1254
-		if (strpos($url, 'https:') === 0) {
1255
-			$url = 'http:' . substr($url, 6);
1256
-		} else {
1257
-			$url = 'https:' . substr($url, 5);
1258
-		}
1259
-
1260
-		try {
1261
-			$fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1262
-		} catch (\Exception $e) {
1263
-			$fallbackContent = false;
1264
-		}
1265
-
1266
-		// cleanup
1267
-		@unlink($testFile);
1268
-
1269
-		/*
270
+            if ($mount->getOption('readonly', false)) {
271
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
272
+                    'storage' => $storage,
273
+                    'mask' => \OCP\Constants::PERMISSION_ALL & ~(
274
+                        \OCP\Constants::PERMISSION_UPDATE |
275
+                        \OCP\Constants::PERMISSION_CREATE |
276
+                        \OCP\Constants::PERMISSION_DELETE
277
+                    ),
278
+                ]);
279
+            }
280
+            return $storage;
281
+        });
282
+
283
+        OC_Hook::emit('OC_Filesystem', 'preSetup', ['user' => $user]);
284
+
285
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($prevLogging);
286
+
287
+        //check if we are using an object storage
288
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
289
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
290
+
291
+        // use the same order as in ObjectHomeMountProvider
292
+        if (isset($objectStoreMultibucket)) {
293
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
294
+        } elseif (isset($objectStore)) {
295
+            self::initObjectStoreRootFS($objectStore);
296
+        } else {
297
+            self::initLocalStorageRootFS();
298
+        }
299
+
300
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
301
+            \OC::$server->getEventLogger()->end('setup_fs');
302
+            return false;
303
+        }
304
+
305
+        //if we aren't logged in, there is no use to set up the filesystem
306
+        if ($user != "") {
307
+            $userDir = '/' . $user . '/files';
308
+
309
+            //jail the user into his "home" directory
310
+            \OC\Files\Filesystem::init($user, $userDir);
311
+
312
+            OC_Hook::emit('OC_Filesystem', 'setup', ['user' => $user, 'user_dir' => $userDir]);
313
+        }
314
+        \OC::$server->getEventLogger()->end('setup_fs');
315
+        return true;
316
+    }
317
+
318
+    /**
319
+     * check if a password is required for each public link
320
+     *
321
+     * @return boolean
322
+     * @suppress PhanDeprecatedFunction
323
+     */
324
+    public static function isPublicLinkPasswordRequired() {
325
+        $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no');
326
+        return $enforcePassword === 'yes';
327
+    }
328
+
329
+    /**
330
+     * check if sharing is disabled for the current user
331
+     * @param IConfig $config
332
+     * @param IGroupManager $groupManager
333
+     * @param IUser|null $user
334
+     * @return bool
335
+     */
336
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
337
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
338
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
339
+            $excludedGroups = json_decode($groupsList);
340
+            if (is_null($excludedGroups)) {
341
+                $excludedGroups = explode(',', $groupsList);
342
+                $newValue = json_encode($excludedGroups);
343
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
344
+            }
345
+            $usersGroups = $groupManager->getUserGroupIds($user);
346
+            if (!empty($usersGroups)) {
347
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
348
+                // if the user is only in groups which are disabled for sharing then
349
+                // sharing is also disabled for the user
350
+                if (empty($remainingGroups)) {
351
+                    return true;
352
+                }
353
+            }
354
+        }
355
+        return false;
356
+    }
357
+
358
+    /**
359
+     * check if share API enforces a default expire date
360
+     *
361
+     * @return boolean
362
+     * @suppress PhanDeprecatedFunction
363
+     */
364
+    public static function isDefaultExpireDateEnforced() {
365
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
366
+        $enforceDefaultExpireDate = false;
367
+        if ($isDefaultExpireDateEnabled === 'yes') {
368
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
369
+            $enforceDefaultExpireDate = $value === 'yes';
370
+        }
371
+
372
+        return $enforceDefaultExpireDate;
373
+    }
374
+
375
+    /**
376
+     * Get the quota of a user
377
+     *
378
+     * @param IUser|null $user
379
+     * @return float Quota bytes
380
+     */
381
+    public static function getUserQuota(?IUser $user) {
382
+        if (is_null($user)) {
383
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
384
+        }
385
+        $userQuota = $user->getQuota();
386
+        if ($userQuota === 'none') {
387
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
388
+        }
389
+        return OC_Helper::computerFileSize($userQuota);
390
+    }
391
+
392
+    /**
393
+     * copies the skeleton to the users /files
394
+     *
395
+     * @param string $userId
396
+     * @param \OCP\Files\Folder $userDirectory
397
+     * @throws \OCP\Files\NotFoundException
398
+     * @throws \OCP\Files\NotPermittedException
399
+     * @suppress PhanDeprecatedFunction
400
+     */
401
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
402
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
403
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
404
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
405
+
406
+        if (!file_exists($skeletonDirectory)) {
407
+            $dialectStart = strpos($userLang, '_');
408
+            if ($dialectStart !== false) {
409
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
410
+            }
411
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
412
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
413
+            }
414
+            if (!file_exists($skeletonDirectory)) {
415
+                $skeletonDirectory = '';
416
+            }
417
+        }
418
+
419
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
420
+
421
+        if ($instanceId === null) {
422
+            throw new \RuntimeException('no instance id!');
423
+        }
424
+        $appdata = 'appdata_' . $instanceId;
425
+        if ($userId === $appdata) {
426
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
427
+        }
428
+
429
+        if (!empty($skeletonDirectory)) {
430
+            \OCP\Util::writeLog(
431
+                'files_skeleton',
432
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
433
+                ILogger::DEBUG
434
+            );
435
+            self::copyr($skeletonDirectory, $userDirectory);
436
+            // update the file cache
437
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
438
+        }
439
+    }
440
+
441
+    /**
442
+     * copies a directory recursively by using streams
443
+     *
444
+     * @param string $source
445
+     * @param \OCP\Files\Folder $target
446
+     * @return void
447
+     */
448
+    public static function copyr($source, \OCP\Files\Folder $target) {
449
+        $logger = \OC::$server->getLogger();
450
+
451
+        // Verify if folder exists
452
+        $dir = opendir($source);
453
+        if ($dir === false) {
454
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
455
+            return;
456
+        }
457
+
458
+        // Copy the files
459
+        while (false !== ($file = readdir($dir))) {
460
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
461
+                if (is_dir($source . '/' . $file)) {
462
+                    $child = $target->newFolder($file);
463
+                    self::copyr($source . '/' . $file, $child);
464
+                } else {
465
+                    $child = $target->newFile($file);
466
+                    $sourceStream = fopen($source . '/' . $file, 'r');
467
+                    if ($sourceStream === false) {
468
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
469
+                        closedir($dir);
470
+                        return;
471
+                    }
472
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
473
+                }
474
+            }
475
+        }
476
+        closedir($dir);
477
+    }
478
+
479
+    /**
480
+     * @return void
481
+     * @suppress PhanUndeclaredMethod
482
+     */
483
+    public static function tearDownFS() {
484
+        \OC\Files\Filesystem::tearDown();
485
+        \OC::$server->getRootFolder()->clearCache();
486
+        self::$fsSetup = false;
487
+        self::$rootMounted = false;
488
+    }
489
+
490
+    /**
491
+     * get the current installed version of ownCloud
492
+     *
493
+     * @return array
494
+     */
495
+    public static function getVersion() {
496
+        OC_Util::loadVersion();
497
+        return self::$versionCache['OC_Version'];
498
+    }
499
+
500
+    /**
501
+     * get the current installed version string of ownCloud
502
+     *
503
+     * @return string
504
+     */
505
+    public static function getVersionString() {
506
+        OC_Util::loadVersion();
507
+        return self::$versionCache['OC_VersionString'];
508
+    }
509
+
510
+    /**
511
+     * @deprecated the value is of no use anymore
512
+     * @return string
513
+     */
514
+    public static function getEditionString() {
515
+        return '';
516
+    }
517
+
518
+    /**
519
+     * @description get the update channel of the current installed of ownCloud.
520
+     * @return string
521
+     */
522
+    public static function getChannel() {
523
+        OC_Util::loadVersion();
524
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
525
+    }
526
+
527
+    /**
528
+     * @description get the build number of the current installed of ownCloud.
529
+     * @return string
530
+     */
531
+    public static function getBuild() {
532
+        OC_Util::loadVersion();
533
+        return self::$versionCache['OC_Build'];
534
+    }
535
+
536
+    /**
537
+     * @description load the version.php into the session as cache
538
+     * @suppress PhanUndeclaredVariable
539
+     */
540
+    private static function loadVersion() {
541
+        if (self::$versionCache !== null) {
542
+            return;
543
+        }
544
+
545
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
546
+        require OC::$SERVERROOT . '/version.php';
547
+        /** @var $timestamp int */
548
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
549
+        /** @var $OC_Version string */
550
+        self::$versionCache['OC_Version'] = $OC_Version;
551
+        /** @var $OC_VersionString string */
552
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
553
+        /** @var $OC_Build string */
554
+        self::$versionCache['OC_Build'] = $OC_Build;
555
+
556
+        /** @var $OC_Channel string */
557
+        self::$versionCache['OC_Channel'] = $OC_Channel;
558
+    }
559
+
560
+    /**
561
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
562
+     *
563
+     * @param string $application application to get the files from
564
+     * @param string $directory directory within this application (css, js, vendor, etc)
565
+     * @param string $file the file inside of the above folder
566
+     * @return string the path
567
+     */
568
+    private static function generatePath($application, $directory, $file) {
569
+        if (is_null($file)) {
570
+            $file = $application;
571
+            $application = "";
572
+        }
573
+        if (!empty($application)) {
574
+            return "$application/$directory/$file";
575
+        } else {
576
+            return "$directory/$file";
577
+        }
578
+    }
579
+
580
+    /**
581
+     * add a javascript file
582
+     *
583
+     * @param string $application application id
584
+     * @param string|null $file filename
585
+     * @param bool $prepend prepend the Script to the beginning of the list
586
+     * @return void
587
+     */
588
+    public static function addScript($application, $file = null, $prepend = false) {
589
+        $path = OC_Util::generatePath($application, 'js', $file);
590
+
591
+        // core js files need separate handling
592
+        if ($application !== 'core' && $file !== null) {
593
+            self::addTranslations($application);
594
+        }
595
+        self::addExternalResource($application, $prepend, $path, "script");
596
+    }
597
+
598
+    /**
599
+     * add a javascript file from the vendor sub folder
600
+     *
601
+     * @param string $application application id
602
+     * @param string|null $file filename
603
+     * @param bool $prepend prepend the Script to the beginning of the list
604
+     * @return void
605
+     */
606
+    public static function addVendorScript($application, $file = null, $prepend = false) {
607
+        $path = OC_Util::generatePath($application, 'vendor', $file);
608
+        self::addExternalResource($application, $prepend, $path, "script");
609
+    }
610
+
611
+    /**
612
+     * add a translation JS file
613
+     *
614
+     * @param string $application application id
615
+     * @param string|null $languageCode language code, defaults to the current language
616
+     * @param bool|null $prepend prepend the Script to the beginning of the list
617
+     */
618
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
619
+        if (is_null($languageCode)) {
620
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
621
+        }
622
+        if (!empty($application)) {
623
+            $path = "$application/l10n/$languageCode";
624
+        } else {
625
+            $path = "l10n/$languageCode";
626
+        }
627
+        self::addExternalResource($application, $prepend, $path, "script");
628
+    }
629
+
630
+    /**
631
+     * add a css file
632
+     *
633
+     * @param string $application application id
634
+     * @param string|null $file filename
635
+     * @param bool $prepend prepend the Style to the beginning of the list
636
+     * @return void
637
+     */
638
+    public static function addStyle($application, $file = null, $prepend = false) {
639
+        $path = OC_Util::generatePath($application, 'css', $file);
640
+        self::addExternalResource($application, $prepend, $path, "style");
641
+    }
642
+
643
+    /**
644
+     * add a css file from the vendor sub folder
645
+     *
646
+     * @param string $application application id
647
+     * @param string|null $file filename
648
+     * @param bool $prepend prepend the Style to the beginning of the list
649
+     * @return void
650
+     */
651
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
652
+        $path = OC_Util::generatePath($application, 'vendor', $file);
653
+        self::addExternalResource($application, $prepend, $path, "style");
654
+    }
655
+
656
+    /**
657
+     * add an external resource css/js file
658
+     *
659
+     * @param string $application application id
660
+     * @param bool $prepend prepend the file to the beginning of the list
661
+     * @param string $path
662
+     * @param string $type (script or style)
663
+     * @return void
664
+     */
665
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
666
+        if ($type === "style") {
667
+            if (!in_array($path, self::$styles)) {
668
+                if ($prepend === true) {
669
+                    array_unshift(self::$styles, $path);
670
+                } else {
671
+                    self::$styles[] = $path;
672
+                }
673
+            }
674
+        } elseif ($type === "script") {
675
+            if (!in_array($path, self::$scripts)) {
676
+                if ($prepend === true) {
677
+                    array_unshift(self::$scripts, $path);
678
+                } else {
679
+                    self::$scripts [] = $path;
680
+                }
681
+            }
682
+        }
683
+    }
684
+
685
+    /**
686
+     * Add a custom element to the header
687
+     * If $text is null then the element will be written as empty element.
688
+     * So use "" to get a closing tag.
689
+     * @param string $tag tag name of the element
690
+     * @param array $attributes array of attributes for the element
691
+     * @param string $text the text content for the element
692
+     * @param bool $prepend prepend the header to the beginning of the list
693
+     */
694
+    public static function addHeader($tag, $attributes, $text = null, $prepend = false) {
695
+        $header = [
696
+            'tag' => $tag,
697
+            'attributes' => $attributes,
698
+            'text' => $text
699
+        ];
700
+        if ($prepend === true) {
701
+            array_unshift(self::$headers, $header);
702
+        } else {
703
+            self::$headers[] = $header;
704
+        }
705
+    }
706
+
707
+    /**
708
+     * check if the current server configuration is suitable for ownCloud
709
+     *
710
+     * @param \OC\SystemConfig $config
711
+     * @return array arrays with error messages and hints
712
+     */
713
+    public static function checkServer(\OC\SystemConfig $config) {
714
+        $l = \OC::$server->getL10N('lib');
715
+        $errors = [];
716
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
717
+
718
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
719
+            // this check needs to be done every time
720
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
721
+        }
722
+
723
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
724
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
725
+            return $errors;
726
+        }
727
+
728
+        $webServerRestart = false;
729
+        $setup = new \OC\Setup(
730
+            $config,
731
+            \OC::$server->getIniWrapper(),
732
+            \OC::$server->getL10N('lib'),
733
+            \OC::$server->query(\OCP\Defaults::class),
734
+            \OC::$server->getLogger(),
735
+            \OC::$server->getSecureRandom(),
736
+            \OC::$server->query(\OC\Installer::class)
737
+        );
738
+
739
+        $urlGenerator = \OC::$server->getURLGenerator();
740
+
741
+        $availableDatabases = $setup->getSupportedDatabases();
742
+        if (empty($availableDatabases)) {
743
+            $errors[] = [
744
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
745
+                'hint' => '' //TODO: sane hint
746
+            ];
747
+            $webServerRestart = true;
748
+        }
749
+
750
+        // Check if config folder is writable.
751
+        if (!OC_Helper::isReadOnlyConfigEnabled()) {
752
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
753
+                $errors[] = [
754
+                    'error' => $l->t('Cannot write into "config" directory'),
755
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
756
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ]) . '. '
757
+                        . $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',
758
+                        [ $urlGenerator->linkToDocs('admin-config') ])
759
+                ];
760
+            }
761
+        }
762
+
763
+        // Check if there is a writable install folder.
764
+        if ($config->getValue('appstoreenabled', true)) {
765
+            if (OC_App::getInstallPath() === null
766
+                || !is_writable(OC_App::getInstallPath())
767
+                || !is_readable(OC_App::getInstallPath())
768
+            ) {
769
+                $errors[] = [
770
+                    'error' => $l->t('Cannot write into "apps" directory'),
771
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
772
+                        . ' or disabling the appstore in the config file.')
773
+                ];
774
+            }
775
+        }
776
+        // Create root dir.
777
+        if ($config->getValue('installed', false)) {
778
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
779
+                $success = @mkdir($CONFIG_DATADIRECTORY);
780
+                if ($success) {
781
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
782
+                } else {
783
+                    $errors[] = [
784
+                        'error' => $l->t('Cannot create "data" directory'),
785
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
786
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
787
+                    ];
788
+                }
789
+            } elseif (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
790
+                // is_writable doesn't work for NFS mounts, so try to write a file and check if it exists.
791
+                $testFile = sprintf('%s/%s.tmp', $CONFIG_DATADIRECTORY, uniqid('data_dir_writability_test_'));
792
+                $handle = fopen($testFile, 'w');
793
+                if (!$handle || fwrite($handle, 'Test write operation') === false) {
794
+                    $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
795
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')]);
796
+                    $errors[] = [
797
+                        'error' => 'Your data directory is not writable',
798
+                        'hint' => $permissionsHint
799
+                    ];
800
+                } else {
801
+                    fclose($handle);
802
+                    unlink($testFile);
803
+                }
804
+            } else {
805
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
806
+            }
807
+        }
808
+
809
+        if (!OC_Util::isSetLocaleWorking()) {
810
+            $errors[] = [
811
+                'error' => $l->t('Setting locale to %s failed',
812
+                    ['en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
813
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8']),
814
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
815
+            ];
816
+        }
817
+
818
+        // Contains the dependencies that should be checked against
819
+        // classes = class_exists
820
+        // functions = function_exists
821
+        // defined = defined
822
+        // ini = ini_get
823
+        // If the dependency is not found the missing module name is shown to the EndUser
824
+        // When adding new checks always verify that they pass on Travis as well
825
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
826
+        $dependencies = [
827
+            'classes' => [
828
+                'ZipArchive' => 'zip',
829
+                'DOMDocument' => 'dom',
830
+                'XMLWriter' => 'XMLWriter',
831
+                'XMLReader' => 'XMLReader',
832
+            ],
833
+            'functions' => [
834
+                'xml_parser_create' => 'libxml',
835
+                'mb_strcut' => 'mbstring',
836
+                'ctype_digit' => 'ctype',
837
+                'json_encode' => 'JSON',
838
+                'gd_info' => 'GD',
839
+                'gzencode' => 'zlib',
840
+                'iconv' => 'iconv',
841
+                'simplexml_load_string' => 'SimpleXML',
842
+                'hash' => 'HASH Message Digest Framework',
843
+                'curl_init' => 'cURL',
844
+                'openssl_verify' => 'OpenSSL',
845
+            ],
846
+            'defined' => [
847
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
848
+            ],
849
+            'ini' => [
850
+                'default_charset' => 'UTF-8',
851
+            ],
852
+        ];
853
+        $missingDependencies = [];
854
+        $invalidIniSettings = [];
855
+
856
+        $iniWrapper = \OC::$server->getIniWrapper();
857
+        foreach ($dependencies['classes'] as $class => $module) {
858
+            if (!class_exists($class)) {
859
+                $missingDependencies[] = $module;
860
+            }
861
+        }
862
+        foreach ($dependencies['functions'] as $function => $module) {
863
+            if (!function_exists($function)) {
864
+                $missingDependencies[] = $module;
865
+            }
866
+        }
867
+        foreach ($dependencies['defined'] as $defined => $module) {
868
+            if (!defined($defined)) {
869
+                $missingDependencies[] = $module;
870
+            }
871
+        }
872
+        foreach ($dependencies['ini'] as $setting => $expected) {
873
+            if (is_bool($expected)) {
874
+                if ($iniWrapper->getBool($setting) !== $expected) {
875
+                    $invalidIniSettings[] = [$setting, $expected];
876
+                }
877
+            }
878
+            if (is_int($expected)) {
879
+                if ($iniWrapper->getNumeric($setting) !== $expected) {
880
+                    $invalidIniSettings[] = [$setting, $expected];
881
+                }
882
+            }
883
+            if (is_string($expected)) {
884
+                if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
885
+                    $invalidIniSettings[] = [$setting, $expected];
886
+                }
887
+            }
888
+        }
889
+
890
+        foreach ($missingDependencies as $missingDependency) {
891
+            $errors[] = [
892
+                'error' => $l->t('PHP module %s not installed.', [$missingDependency]),
893
+                'hint' => $l->t('Please ask your server administrator to install the module.'),
894
+            ];
895
+            $webServerRestart = true;
896
+        }
897
+        foreach ($invalidIniSettings as $setting) {
898
+            if (is_bool($setting[1])) {
899
+                $setting[1] = $setting[1] ? 'on' : 'off';
900
+            }
901
+            $errors[] = [
902
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
903
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
904
+            ];
905
+            $webServerRestart = true;
906
+        }
907
+
908
+        /**
909
+         * The mbstring.func_overload check can only be performed if the mbstring
910
+         * module is installed as it will return null if the checking setting is
911
+         * not available and thus a check on the boolean value fails.
912
+         *
913
+         * TODO: Should probably be implemented in the above generic dependency
914
+         *       check somehow in the long-term.
915
+         */
916
+        if ($iniWrapper->getBool('mbstring.func_overload') !== null &&
917
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
918
+            $errors[] = [
919
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
920
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
921
+            ];
922
+        }
923
+
924
+        if (function_exists('xml_parser_create') &&
925
+            LIBXML_LOADED_VERSION < 20700) {
926
+            $version = LIBXML_LOADED_VERSION;
927
+            $major = floor($version/10000);
928
+            $version -= ($major * 10000);
929
+            $minor = floor($version/100);
930
+            $version -= ($minor * 100);
931
+            $patch = $version;
932
+            $errors[] = [
933
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
934
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
935
+            ];
936
+        }
937
+
938
+        if (!self::isAnnotationsWorking()) {
939
+            $errors[] = [
940
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
941
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
942
+            ];
943
+        }
944
+
945
+        if (!\OC::$CLI && $webServerRestart) {
946
+            $errors[] = [
947
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
948
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
949
+            ];
950
+        }
951
+
952
+        $errors = array_merge($errors, self::checkDatabaseVersion());
953
+
954
+        // Cache the result of this function
955
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
956
+
957
+        return $errors;
958
+    }
959
+
960
+    /**
961
+     * Check the database version
962
+     *
963
+     * @return array errors array
964
+     */
965
+    public static function checkDatabaseVersion() {
966
+        $l = \OC::$server->getL10N('lib');
967
+        $errors = [];
968
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
969
+        if ($dbType === 'pgsql') {
970
+            // check PostgreSQL version
971
+            try {
972
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
973
+                $data = $result->fetchRow();
974
+                if (isset($data['server_version'])) {
975
+                    $version = $data['server_version'];
976
+                    if (version_compare($version, '9.0.0', '<')) {
977
+                        $errors[] = [
978
+                            'error' => $l->t('PostgreSQL >= 9 required'),
979
+                            'hint' => $l->t('Please upgrade your database version')
980
+                        ];
981
+                    }
982
+                }
983
+            } catch (\Doctrine\DBAL\DBALException $e) {
984
+                $logger = \OC::$server->getLogger();
985
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
986
+                $logger->logException($e);
987
+            }
988
+        }
989
+        return $errors;
990
+    }
991
+
992
+    /**
993
+     * Check for correct file permissions of data directory
994
+     *
995
+     * @param string $dataDirectory
996
+     * @return array arrays with error messages and hints
997
+     */
998
+    public static function checkDataDirectoryPermissions($dataDirectory) {
999
+        if (\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
1000
+            return  [];
1001
+        }
1002
+
1003
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1004
+        if (substr($perms, -1) !== '0') {
1005
+            chmod($dataDirectory, 0770);
1006
+            clearstatcache();
1007
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1008
+            if ($perms[2] !== '0') {
1009
+                $l = \OC::$server->getL10N('lib');
1010
+                return [[
1011
+                    'error' => $l->t('Your data directory is readable by other users'),
1012
+                    'hint' => $l->t('Please change the permissions to 0770 so that the directory cannot be listed by other users.'),
1013
+                ]];
1014
+            }
1015
+        }
1016
+        return [];
1017
+    }
1018
+
1019
+    /**
1020
+     * Check that the data directory exists and is valid by
1021
+     * checking the existence of the ".ocdata" file.
1022
+     *
1023
+     * @param string $dataDirectory data directory path
1024
+     * @return array errors found
1025
+     */
1026
+    public static function checkDataDirectoryValidity($dataDirectory) {
1027
+        $l = \OC::$server->getL10N('lib');
1028
+        $errors = [];
1029
+        if ($dataDirectory[0] !== '/') {
1030
+            $errors[] = [
1031
+                'error' => $l->t('Your data directory must be an absolute path'),
1032
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1033
+            ];
1034
+        }
1035
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1036
+            $errors[] = [
1037
+                'error' => $l->t('Your data directory is invalid'),
1038
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1039
+                    ' in the root of the data directory.')
1040
+            ];
1041
+        }
1042
+        return $errors;
1043
+    }
1044
+
1045
+    /**
1046
+     * Check if the user is logged in, redirects to home if not. With
1047
+     * redirect URL parameter to the request URI.
1048
+     *
1049
+     * @return void
1050
+     */
1051
+    public static function checkLoggedIn() {
1052
+        // Check if we are a user
1053
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1054
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1055
+                        'core.login.showLoginForm',
1056
+                        [
1057
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1058
+                        ]
1059
+                    )
1060
+            );
1061
+            exit();
1062
+        }
1063
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1064
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1065
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1066
+            exit();
1067
+        }
1068
+    }
1069
+
1070
+    /**
1071
+     * Check if the user is a admin, redirects to home if not
1072
+     *
1073
+     * @return void
1074
+     */
1075
+    public static function checkAdminUser() {
1076
+        OC_Util::checkLoggedIn();
1077
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1078
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1079
+            exit();
1080
+        }
1081
+    }
1082
+
1083
+    /**
1084
+     * Returns the URL of the default page
1085
+     * based on the system configuration and
1086
+     * the apps visible for the current user
1087
+     *
1088
+     * @return string URL
1089
+     * @suppress PhanDeprecatedFunction
1090
+     */
1091
+    public static function getDefaultPageUrl() {
1092
+        /** @var IConfig $config */
1093
+        $config = \OC::$server->get(IConfig::class);
1094
+        $urlGenerator = \OC::$server->getURLGenerator();
1095
+        // Deny the redirect if the URL contains a @
1096
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1097
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1098
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1099
+        } else {
1100
+            $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage');
1101
+            if ($defaultPage) {
1102
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1103
+            } else {
1104
+                $appId = 'files';
1105
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'dashboard,files'));
1106
+
1107
+                /** @var IUserSession $userSession */
1108
+                $userSession = \OC::$server->get(IUserSession::class);
1109
+                $user = $userSession->getUser();
1110
+                if ($user) {
1111
+                    $userDefaultApps = explode(',', $config->getUserValue($user->getUID(), 'core', 'defaultapp'));
1112
+                    $defaultApps = array_filter(array_merge($userDefaultApps, $defaultApps));
1113
+                }
1114
+
1115
+                // find the first app that is enabled for the current user
1116
+                foreach ($defaultApps as $defaultApp) {
1117
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1118
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1119
+                        $appId = $defaultApp;
1120
+                        break;
1121
+                    }
1122
+                }
1123
+
1124
+                if ($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1125
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1126
+                } else {
1127
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1128
+                }
1129
+            }
1130
+        }
1131
+        return $location;
1132
+    }
1133
+
1134
+    /**
1135
+     * Redirect to the user default page
1136
+     *
1137
+     * @return void
1138
+     */
1139
+    public static function redirectToDefaultPage() {
1140
+        $location = self::getDefaultPageUrl();
1141
+        header('Location: ' . $location);
1142
+        exit();
1143
+    }
1144
+
1145
+    /**
1146
+     * get an id unique for this instance
1147
+     *
1148
+     * @return string
1149
+     */
1150
+    public static function getInstanceId() {
1151
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1152
+        if (is_null($id)) {
1153
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1154
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1155
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1156
+        }
1157
+        return $id;
1158
+    }
1159
+
1160
+    /**
1161
+     * Public function to sanitize HTML
1162
+     *
1163
+     * This function is used to sanitize HTML and should be applied on any
1164
+     * string or array of strings before displaying it on a web page.
1165
+     *
1166
+     * @param string|array $value
1167
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1168
+     */
1169
+    public static function sanitizeHTML($value) {
1170
+        if (is_array($value)) {
1171
+            $value = array_map(function ($value) {
1172
+                return self::sanitizeHTML($value);
1173
+            }, $value);
1174
+        } else {
1175
+            // Specify encoding for PHP<5.4
1176
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1177
+        }
1178
+        return $value;
1179
+    }
1180
+
1181
+    /**
1182
+     * Public function to encode url parameters
1183
+     *
1184
+     * This function is used to encode path to file before output.
1185
+     * Encoding is done according to RFC 3986 with one exception:
1186
+     * Character '/' is preserved as is.
1187
+     *
1188
+     * @param string $component part of URI to encode
1189
+     * @return string
1190
+     */
1191
+    public static function encodePath($component) {
1192
+        $encoded = rawurlencode($component);
1193
+        $encoded = str_replace('%2F', '/', $encoded);
1194
+        return $encoded;
1195
+    }
1196
+
1197
+
1198
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1199
+        // php dev server does not support htaccess
1200
+        if (php_sapi_name() === 'cli-server') {
1201
+            return false;
1202
+        }
1203
+
1204
+        // testdata
1205
+        $fileName = '/htaccesstest.txt';
1206
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1207
+
1208
+        // creating a test file
1209
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1210
+
1211
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1212
+            return false;
1213
+        }
1214
+
1215
+        $fp = @fopen($testFile, 'w');
1216
+        if (!$fp) {
1217
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1218
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1219
+        }
1220
+        fwrite($fp, $testContent);
1221
+        fclose($fp);
1222
+
1223
+        return $testContent;
1224
+    }
1225
+
1226
+    /**
1227
+     * Check if the .htaccess file is working
1228
+     * @param \OCP\IConfig $config
1229
+     * @return bool
1230
+     * @throws Exception
1231
+     * @throws \OC\HintException If the test file can't get written.
1232
+     */
1233
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1234
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1235
+            return true;
1236
+        }
1237
+
1238
+        $testContent = $this->createHtaccessTestFile($config);
1239
+        if ($testContent === false) {
1240
+            return false;
1241
+        }
1242
+
1243
+        $fileName = '/htaccesstest.txt';
1244
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1245
+
1246
+        // accessing the file via http
1247
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1248
+        try {
1249
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1250
+        } catch (\Exception $e) {
1251
+            $content = false;
1252
+        }
1253
+
1254
+        if (strpos($url, 'https:') === 0) {
1255
+            $url = 'http:' . substr($url, 6);
1256
+        } else {
1257
+            $url = 'https:' . substr($url, 5);
1258
+        }
1259
+
1260
+        try {
1261
+            $fallbackContent = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1262
+        } catch (\Exception $e) {
1263
+            $fallbackContent = false;
1264
+        }
1265
+
1266
+        // cleanup
1267
+        @unlink($testFile);
1268
+
1269
+        /*
1270 1270
 		 * If the content is not equal to test content our .htaccess
1271 1271
 		 * is working as required
1272 1272
 		 */
1273
-		return $content !== $testContent && $fallbackContent !== $testContent;
1274
-	}
1275
-
1276
-	/**
1277
-	 * Check if the setlocal call does not work. This can happen if the right
1278
-	 * local packages are not available on the server.
1279
-	 *
1280
-	 * @return bool
1281
-	 */
1282
-	public static function isSetLocaleWorking() {
1283
-		\Patchwork\Utf8\Bootup::initLocale();
1284
-		if ('' === basename('§')) {
1285
-			return false;
1286
-		}
1287
-		return true;
1288
-	}
1289
-
1290
-	/**
1291
-	 * Check if it's possible to get the inline annotations
1292
-	 *
1293
-	 * @return bool
1294
-	 */
1295
-	public static function isAnnotationsWorking() {
1296
-		$reflection = new \ReflectionMethod(__METHOD__);
1297
-		$docs = $reflection->getDocComment();
1298
-
1299
-		return (is_string($docs) && strlen($docs) > 50);
1300
-	}
1301
-
1302
-	/**
1303
-	 * Check if the PHP module fileinfo is loaded.
1304
-	 *
1305
-	 * @return bool
1306
-	 */
1307
-	public static function fileInfoLoaded() {
1308
-		return function_exists('finfo_open');
1309
-	}
1310
-
1311
-	/**
1312
-	 * clear all levels of output buffering
1313
-	 *
1314
-	 * @return void
1315
-	 */
1316
-	public static function obEnd() {
1317
-		while (ob_get_level()) {
1318
-			ob_end_clean();
1319
-		}
1320
-	}
1321
-
1322
-	/**
1323
-	 * Checks whether the server is running on Mac OS X
1324
-	 *
1325
-	 * @return bool true if running on Mac OS X, false otherwise
1326
-	 */
1327
-	public static function runningOnMac() {
1328
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1329
-	}
1330
-
1331
-	/**
1332
-	 * Handles the case that there may not be a theme, then check if a "default"
1333
-	 * theme exists and take that one
1334
-	 *
1335
-	 * @return string the theme
1336
-	 */
1337
-	public static function getTheme() {
1338
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1339
-
1340
-		if ($theme === '') {
1341
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1342
-				$theme = 'default';
1343
-			}
1344
-		}
1345
-
1346
-		return $theme;
1347
-	}
1348
-
1349
-	/**
1350
-	 * Normalize a unicode string
1351
-	 *
1352
-	 * @param string $value a not normalized string
1353
-	 * @return bool|string
1354
-	 */
1355
-	public static function normalizeUnicode($value) {
1356
-		if (Normalizer::isNormalized($value)) {
1357
-			return $value;
1358
-		}
1359
-
1360
-		$normalizedValue = Normalizer::normalize($value);
1361
-		if ($normalizedValue === null || $normalizedValue === false) {
1362
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1363
-			return $value;
1364
-		}
1365
-
1366
-		return $normalizedValue;
1367
-	}
1368
-
1369
-	/**
1370
-	 * A human readable string is generated based on version and build number
1371
-	 *
1372
-	 * @return string
1373
-	 */
1374
-	public static function getHumanVersion() {
1375
-		$version = OC_Util::getVersionString();
1376
-		$build = OC_Util::getBuild();
1377
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1378
-			$version .= ' Build:' . $build;
1379
-		}
1380
-		return $version;
1381
-	}
1382
-
1383
-	/**
1384
-	 * Returns whether the given file name is valid
1385
-	 *
1386
-	 * @param string $file file name to check
1387
-	 * @return bool true if the file name is valid, false otherwise
1388
-	 * @deprecated use \OC\Files\View::verifyPath()
1389
-	 */
1390
-	public static function isValidFileName($file) {
1391
-		$trimmed = trim($file);
1392
-		if ($trimmed === '') {
1393
-			return false;
1394
-		}
1395
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1396
-			return false;
1397
-		}
1398
-
1399
-		// detect part files
1400
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1401
-			return false;
1402
-		}
1403
-
1404
-		foreach (str_split($trimmed) as $char) {
1405
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1406
-				return false;
1407
-			}
1408
-		}
1409
-		return true;
1410
-	}
1411
-
1412
-	/**
1413
-	 * Check whether the instance needs to perform an upgrade,
1414
-	 * either when the core version is higher or any app requires
1415
-	 * an upgrade.
1416
-	 *
1417
-	 * @param \OC\SystemConfig $config
1418
-	 * @return bool whether the core or any app needs an upgrade
1419
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1420
-	 */
1421
-	public static function needUpgrade(\OC\SystemConfig $config) {
1422
-		if ($config->getValue('installed', false)) {
1423
-			$installedVersion = $config->getValue('version', '0.0.0');
1424
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1425
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1426
-			if ($versionDiff > 0) {
1427
-				return true;
1428
-			} elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1429
-				// downgrade with debug
1430
-				$installedMajor = explode('.', $installedVersion);
1431
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1432
-				$currentMajor = explode('.', $currentVersion);
1433
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1434
-				if ($installedMajor === $currentMajor) {
1435
-					// Same major, allow downgrade for developers
1436
-					return true;
1437
-				} else {
1438
-					// downgrade attempt, throw exception
1439
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1440
-				}
1441
-			} elseif ($versionDiff < 0) {
1442
-				// downgrade attempt, throw exception
1443
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1444
-			}
1445
-
1446
-			// also check for upgrades for apps (independently from the user)
1447
-			$apps = \OC_App::getEnabledApps(false, true);
1448
-			$shouldUpgrade = false;
1449
-			foreach ($apps as $app) {
1450
-				if (\OC_App::shouldUpgrade($app)) {
1451
-					$shouldUpgrade = true;
1452
-					break;
1453
-				}
1454
-			}
1455
-			return $shouldUpgrade;
1456
-		} else {
1457
-			return false;
1458
-		}
1459
-	}
1460
-
1461
-	/**
1462
-	 * is this Internet explorer ?
1463
-	 *
1464
-	 * @return boolean
1465
-	 */
1466
-	public static function isIe() {
1467
-		if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1468
-			return false;
1469
-		}
1470
-
1471
-		return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1472
-	}
1273
+        return $content !== $testContent && $fallbackContent !== $testContent;
1274
+    }
1275
+
1276
+    /**
1277
+     * Check if the setlocal call does not work. This can happen if the right
1278
+     * local packages are not available on the server.
1279
+     *
1280
+     * @return bool
1281
+     */
1282
+    public static function isSetLocaleWorking() {
1283
+        \Patchwork\Utf8\Bootup::initLocale();
1284
+        if ('' === basename('§')) {
1285
+            return false;
1286
+        }
1287
+        return true;
1288
+    }
1289
+
1290
+    /**
1291
+     * Check if it's possible to get the inline annotations
1292
+     *
1293
+     * @return bool
1294
+     */
1295
+    public static function isAnnotationsWorking() {
1296
+        $reflection = new \ReflectionMethod(__METHOD__);
1297
+        $docs = $reflection->getDocComment();
1298
+
1299
+        return (is_string($docs) && strlen($docs) > 50);
1300
+    }
1301
+
1302
+    /**
1303
+     * Check if the PHP module fileinfo is loaded.
1304
+     *
1305
+     * @return bool
1306
+     */
1307
+    public static function fileInfoLoaded() {
1308
+        return function_exists('finfo_open');
1309
+    }
1310
+
1311
+    /**
1312
+     * clear all levels of output buffering
1313
+     *
1314
+     * @return void
1315
+     */
1316
+    public static function obEnd() {
1317
+        while (ob_get_level()) {
1318
+            ob_end_clean();
1319
+        }
1320
+    }
1321
+
1322
+    /**
1323
+     * Checks whether the server is running on Mac OS X
1324
+     *
1325
+     * @return bool true if running on Mac OS X, false otherwise
1326
+     */
1327
+    public static function runningOnMac() {
1328
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1329
+    }
1330
+
1331
+    /**
1332
+     * Handles the case that there may not be a theme, then check if a "default"
1333
+     * theme exists and take that one
1334
+     *
1335
+     * @return string the theme
1336
+     */
1337
+    public static function getTheme() {
1338
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1339
+
1340
+        if ($theme === '') {
1341
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1342
+                $theme = 'default';
1343
+            }
1344
+        }
1345
+
1346
+        return $theme;
1347
+    }
1348
+
1349
+    /**
1350
+     * Normalize a unicode string
1351
+     *
1352
+     * @param string $value a not normalized string
1353
+     * @return bool|string
1354
+     */
1355
+    public static function normalizeUnicode($value) {
1356
+        if (Normalizer::isNormalized($value)) {
1357
+            return $value;
1358
+        }
1359
+
1360
+        $normalizedValue = Normalizer::normalize($value);
1361
+        if ($normalizedValue === null || $normalizedValue === false) {
1362
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1363
+            return $value;
1364
+        }
1365
+
1366
+        return $normalizedValue;
1367
+    }
1368
+
1369
+    /**
1370
+     * A human readable string is generated based on version and build number
1371
+     *
1372
+     * @return string
1373
+     */
1374
+    public static function getHumanVersion() {
1375
+        $version = OC_Util::getVersionString();
1376
+        $build = OC_Util::getBuild();
1377
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1378
+            $version .= ' Build:' . $build;
1379
+        }
1380
+        return $version;
1381
+    }
1382
+
1383
+    /**
1384
+     * Returns whether the given file name is valid
1385
+     *
1386
+     * @param string $file file name to check
1387
+     * @return bool true if the file name is valid, false otherwise
1388
+     * @deprecated use \OC\Files\View::verifyPath()
1389
+     */
1390
+    public static function isValidFileName($file) {
1391
+        $trimmed = trim($file);
1392
+        if ($trimmed === '') {
1393
+            return false;
1394
+        }
1395
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1396
+            return false;
1397
+        }
1398
+
1399
+        // detect part files
1400
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1401
+            return false;
1402
+        }
1403
+
1404
+        foreach (str_split($trimmed) as $char) {
1405
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1406
+                return false;
1407
+            }
1408
+        }
1409
+        return true;
1410
+    }
1411
+
1412
+    /**
1413
+     * Check whether the instance needs to perform an upgrade,
1414
+     * either when the core version is higher or any app requires
1415
+     * an upgrade.
1416
+     *
1417
+     * @param \OC\SystemConfig $config
1418
+     * @return bool whether the core or any app needs an upgrade
1419
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1420
+     */
1421
+    public static function needUpgrade(\OC\SystemConfig $config) {
1422
+        if ($config->getValue('installed', false)) {
1423
+            $installedVersion = $config->getValue('version', '0.0.0');
1424
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1425
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1426
+            if ($versionDiff > 0) {
1427
+                return true;
1428
+            } elseif ($config->getValue('debug', false) && $versionDiff < 0) {
1429
+                // downgrade with debug
1430
+                $installedMajor = explode('.', $installedVersion);
1431
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1432
+                $currentMajor = explode('.', $currentVersion);
1433
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1434
+                if ($installedMajor === $currentMajor) {
1435
+                    // Same major, allow downgrade for developers
1436
+                    return true;
1437
+                } else {
1438
+                    // downgrade attempt, throw exception
1439
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1440
+                }
1441
+            } elseif ($versionDiff < 0) {
1442
+                // downgrade attempt, throw exception
1443
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1444
+            }
1445
+
1446
+            // also check for upgrades for apps (independently from the user)
1447
+            $apps = \OC_App::getEnabledApps(false, true);
1448
+            $shouldUpgrade = false;
1449
+            foreach ($apps as $app) {
1450
+                if (\OC_App::shouldUpgrade($app)) {
1451
+                    $shouldUpgrade = true;
1452
+                    break;
1453
+                }
1454
+            }
1455
+            return $shouldUpgrade;
1456
+        } else {
1457
+            return false;
1458
+        }
1459
+    }
1460
+
1461
+    /**
1462
+     * is this Internet explorer ?
1463
+     *
1464
+     * @return boolean
1465
+     */
1466
+    public static function isIe() {
1467
+        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
1468
+            return false;
1469
+        }
1470
+
1471
+        return preg_match(Request::USER_AGENT_IE, $_SERVER['HTTP_USER_AGENT']) === 1;
1472
+    }
1473 1473
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Bootstrap/RegistrationContext.php 1 patch
Indentation   +374 added lines, -374 removed lines patch added patch discarded remove patch
@@ -36,378 +36,378 @@
 block discarded – undo
36 36
 
37 37
 class RegistrationContext {
38 38
 
39
-	/** @var array[] */
40
-	private $capabilities = [];
41
-
42
-	/** @var array[] */
43
-	private $crashReporters = [];
44
-
45
-	/** @var array[] */
46
-	private $dashboardPanels = [];
47
-
48
-	/** @var array[] */
49
-	private $services = [];
50
-
51
-	/** @var array[] */
52
-	private $aliases = [];
53
-
54
-	/** @var array[] */
55
-	private $parameters = [];
56
-
57
-	/** @var array[] */
58
-	private $eventListeners = [];
59
-
60
-	/** @var array[] */
61
-	private $middlewares = [];
62
-
63
-	/** @var array[] */
64
-	private $searchProviders = [];
65
-
66
-	/** @var array[] */
67
-	private $alternativeLogins = [];
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	public function __construct(ILogger $logger) {
73
-		$this->logger = $logger;
74
-	}
75
-
76
-	public function for(string $appId): IRegistrationContext {
77
-		return new class($appId, $this) implements IRegistrationContext {
78
-			/** @var string */
79
-			private $appId;
80
-
81
-			/** @var RegistrationContext */
82
-			private $context;
83
-
84
-			public function __construct(string $appId, RegistrationContext $context) {
85
-				$this->appId = $appId;
86
-				$this->context = $context;
87
-			}
88
-
89
-			public function registerCapability(string $capability): void {
90
-				$this->context->registerCapability(
91
-					$this->appId,
92
-					$capability
93
-				);
94
-			}
95
-
96
-			public function registerCrashReporter(string $reporterClass): void {
97
-				$this->context->registerCrashReporter(
98
-					$this->appId,
99
-					$reporterClass
100
-				);
101
-			}
102
-
103
-			public function registerDashboardWidget(string $widgetClass): void {
104
-				$this->context->registerDashboardPanel(
105
-					$this->appId,
106
-					$widgetClass
107
-				);
108
-			}
109
-
110
-			public function registerService(string $name, callable $factory, bool $shared = true): void {
111
-				$this->context->registerService(
112
-					$this->appId,
113
-					$name,
114
-					$factory,
115
-					$shared
116
-				);
117
-			}
118
-
119
-			public function registerServiceAlias(string $alias, string $target): void {
120
-				$this->context->registerServiceAlias(
121
-					$this->appId,
122
-					$alias,
123
-					$target
124
-				);
125
-			}
126
-
127
-			public function registerParameter(string $name, $value): void {
128
-				$this->context->registerParameter(
129
-					$this->appId,
130
-					$name,
131
-					$value
132
-				);
133
-			}
134
-
135
-			public function registerEventListener(string $event, string $listener, int $priority = 0): void {
136
-				$this->context->registerEventListener(
137
-					$this->appId,
138
-					$event,
139
-					$listener,
140
-					$priority
141
-				);
142
-			}
143
-
144
-			public function registerMiddleware(string $class): void {
145
-				$this->context->registerMiddleware(
146
-					$this->appId,
147
-					$class
148
-				);
149
-			}
150
-
151
-			public function registerSearchProvider(string $class): void {
152
-				$this->context->registerSearchProvider(
153
-					$this->appId,
154
-					$class
155
-				);
156
-			}
157
-
158
-			public function registerAlternativeLogin(string $class): void {
159
-				$this->context->registerAlternativeLogin(
160
-					$this->appId,
161
-					$class
162
-				);
163
-			}
164
-		};
165
-	}
166
-
167
-	public function registerCapability(string $appId, string $capability): void {
168
-		$this->capabilities[] = [
169
-			'appId' => $appId,
170
-			'capability' => $capability
171
-		];
172
-	}
173
-
174
-	public function registerCrashReporter(string $appId, string $reporterClass): void {
175
-		$this->crashReporters[] = [
176
-			'appId' => $appId,
177
-			'class' => $reporterClass,
178
-		];
179
-	}
180
-
181
-	public function registerDashboardPanel(string $appId, string $panelClass): void {
182
-		$this->dashboardPanels[] = [
183
-			'appId' => $appId,
184
-			'class' => $panelClass
185
-		];
186
-	}
187
-
188
-	public function registerService(string $appId, string $name, callable $factory, bool $shared = true): void {
189
-		$this->services[] = [
190
-			"appId" => $appId,
191
-			"name" => $name,
192
-			"factory" => $factory,
193
-			"sharred" => $shared,
194
-		];
195
-	}
196
-
197
-	public function registerServiceAlias(string $appId, string $alias, string $target): void {
198
-		$this->aliases[] = [
199
-			"appId" => $appId,
200
-			"alias" => $alias,
201
-			"target" => $target,
202
-		];
203
-	}
204
-
205
-	public function registerParameter(string $appId, string $name, $value): void {
206
-		$this->parameters[] = [
207
-			"appId" => $appId,
208
-			"name" => $name,
209
-			"value" => $value,
210
-		];
211
-	}
212
-
213
-	public function registerEventListener(string $appId, string $event, string $listener, int $priority = 0): void {
214
-		$this->eventListeners[] = [
215
-			"appId" => $appId,
216
-			"event" => $event,
217
-			"listener" => $listener,
218
-			"priority" => $priority,
219
-		];
220
-	}
221
-
222
-	public function registerMiddleware(string $appId, string $class): void {
223
-		$this->middlewares[] = [
224
-			"appId" => $appId,
225
-			"class" => $class,
226
-		];
227
-	}
228
-
229
-	public function registerSearchProvider(string $appId, string $class) {
230
-		$this->searchProviders[] = [
231
-			'appId' => $appId,
232
-			'class' => $class,
233
-		];
234
-	}
235
-
236
-	public function registerAlternativeLogin(string $appId, string $class): void {
237
-		$this->alternativeLogins[] = [
238
-			'appId' => $appId,
239
-			'class' => $class,
240
-		];
241
-	}
242
-
243
-	/**
244
-	 * @param App[] $apps
245
-	 */
246
-	public function delegateCapabilityRegistrations(array $apps): void {
247
-		foreach ($this->capabilities as $registration) {
248
-			try {
249
-				$apps[$registration['appId']]
250
-					->getContainer()
251
-					->registerCapability($registration['capability']);
252
-			} catch (Throwable $e) {
253
-				$appId = $registration['appId'];
254
-				$this->logger->logException($e, [
255
-					'message' => "Error during capability registration of $appId: " . $e->getMessage(),
256
-					'level' => ILogger::ERROR,
257
-				]);
258
-			}
259
-		}
260
-	}
261
-
262
-	/**
263
-	 * @param App[] $apps
264
-	 */
265
-	public function delegateCrashReporterRegistrations(array $apps, Registry $registry): void {
266
-		foreach ($this->crashReporters as $registration) {
267
-			try {
268
-				$registry->registerLazy($registration['class']);
269
-			} catch (Throwable $e) {
270
-				$appId = $registration['appId'];
271
-				$this->logger->logException($e, [
272
-					'message' => "Error during crash reporter registration of $appId: " . $e->getMessage(),
273
-					'level' => ILogger::ERROR,
274
-				]);
275
-			}
276
-		}
277
-	}
278
-
279
-	/**
280
-	 * @param App[] $apps
281
-	 */
282
-	public function delegateDashboardPanelRegistrations(array $apps, IManager $dashboardManager): void {
283
-		foreach ($this->dashboardPanels as $panel) {
284
-			try {
285
-				$dashboardManager->lazyRegisterWidget($panel['class']);
286
-			} catch (Throwable $e) {
287
-				$appId = $panel['appId'];
288
-				$this->logger->logException($e, [
289
-					'message' => "Error during dashboard registration of $appId: " . $e->getMessage(),
290
-					'level' => ILogger::ERROR,
291
-				]);
292
-			}
293
-		}
294
-	}
295
-
296
-	public function delegateEventListenerRegistrations(IEventDispatcher $eventDispatcher): void {
297
-		foreach ($this->eventListeners as $registration) {
298
-			try {
299
-				if (isset($registration['priority'])) {
300
-					$eventDispatcher->addServiceListener(
301
-						$registration['event'],
302
-						$registration['listener'],
303
-						$registration['priority']
304
-					);
305
-				} else {
306
-					$eventDispatcher->addServiceListener(
307
-						$registration['event'],
308
-						$registration['listener']
309
-					);
310
-				}
311
-			} catch (Throwable $e) {
312
-				$appId = $registration['appId'];
313
-				$this->logger->logException($e, [
314
-					'message' => "Error during event listener registration of $appId: " . $e->getMessage(),
315
-					'level' => ILogger::ERROR,
316
-				]);
317
-			}
318
-		}
319
-	}
320
-
321
-	/**
322
-	 * @param App[] $apps
323
-	 */
324
-	public function delegateContainerRegistrations(array $apps): void {
325
-		foreach ($this->services as $registration) {
326
-			try {
327
-				/**
328
-				 * Register the service and convert the callable into a \Closure if necessary
329
-				 */
330
-				$apps[$registration['appId']]
331
-					->getContainer()
332
-					->registerService(
333
-						$registration['name'],
334
-						Closure::fromCallable($registration['factory']),
335
-						$registration['shared'] ?? true
336
-					);
337
-			} catch (Throwable $e) {
338
-				$appId = $registration['appId'];
339
-				$this->logger->logException($e, [
340
-					'message' => "Error during service registration of $appId: " . $e->getMessage(),
341
-					'level' => ILogger::ERROR,
342
-				]);
343
-			}
344
-		}
345
-
346
-		foreach ($this->aliases as $registration) {
347
-			try {
348
-				$apps[$registration['appId']]
349
-					->getContainer()
350
-					->registerAlias(
351
-						$registration['alias'],
352
-						$registration['target']
353
-					);
354
-			} catch (Throwable $e) {
355
-				$appId = $registration['appId'];
356
-				$this->logger->logException($e, [
357
-					'message' => "Error during service alias registration of $appId: " . $e->getMessage(),
358
-					'level' => ILogger::ERROR,
359
-				]);
360
-			}
361
-		}
362
-
363
-		foreach ($this->parameters as $registration) {
364
-			try {
365
-				$apps[$registration['appId']]
366
-					->getContainer()
367
-					->registerParameter(
368
-						$registration['name'],
369
-						$registration['value']
370
-					);
371
-			} catch (Throwable $e) {
372
-				$appId = $registration['appId'];
373
-				$this->logger->logException($e, [
374
-					'message' => "Error during service alias registration of $appId: " . $e->getMessage(),
375
-					'level' => ILogger::ERROR,
376
-				]);
377
-			}
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * @param App[] $apps
383
-	 */
384
-	public function delegateMiddlewareRegistrations(array $apps): void {
385
-		foreach ($this->middlewares as $middleware) {
386
-			try {
387
-				$apps[$middleware['appId']]
388
-					->getContainer()
389
-					->registerMiddleWare($middleware['class']);
390
-			} catch (Throwable $e) {
391
-				$appId = $middleware['appId'];
392
-				$this->logger->logException($e, [
393
-					'message' => "Error during capability registration of $appId: " . $e->getMessage(),
394
-					'level' => ILogger::ERROR,
395
-				]);
396
-			}
397
-		}
398
-	}
399
-
400
-	/**
401
-	 * @return array[]
402
-	 */
403
-	public function getSearchProviders(): array {
404
-		return $this->searchProviders;
405
-	}
406
-
407
-	/**
408
-	 * @return array[]
409
-	 */
410
-	public function getAlternativeLogins(): array {
411
-		return $this->alternativeLogins;
412
-	}
39
+    /** @var array[] */
40
+    private $capabilities = [];
41
+
42
+    /** @var array[] */
43
+    private $crashReporters = [];
44
+
45
+    /** @var array[] */
46
+    private $dashboardPanels = [];
47
+
48
+    /** @var array[] */
49
+    private $services = [];
50
+
51
+    /** @var array[] */
52
+    private $aliases = [];
53
+
54
+    /** @var array[] */
55
+    private $parameters = [];
56
+
57
+    /** @var array[] */
58
+    private $eventListeners = [];
59
+
60
+    /** @var array[] */
61
+    private $middlewares = [];
62
+
63
+    /** @var array[] */
64
+    private $searchProviders = [];
65
+
66
+    /** @var array[] */
67
+    private $alternativeLogins = [];
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    public function __construct(ILogger $logger) {
73
+        $this->logger = $logger;
74
+    }
75
+
76
+    public function for(string $appId): IRegistrationContext {
77
+        return new class($appId, $this) implements IRegistrationContext {
78
+            /** @var string */
79
+            private $appId;
80
+
81
+            /** @var RegistrationContext */
82
+            private $context;
83
+
84
+            public function __construct(string $appId, RegistrationContext $context) {
85
+                $this->appId = $appId;
86
+                $this->context = $context;
87
+            }
88
+
89
+            public function registerCapability(string $capability): void {
90
+                $this->context->registerCapability(
91
+                    $this->appId,
92
+                    $capability
93
+                );
94
+            }
95
+
96
+            public function registerCrashReporter(string $reporterClass): void {
97
+                $this->context->registerCrashReporter(
98
+                    $this->appId,
99
+                    $reporterClass
100
+                );
101
+            }
102
+
103
+            public function registerDashboardWidget(string $widgetClass): void {
104
+                $this->context->registerDashboardPanel(
105
+                    $this->appId,
106
+                    $widgetClass
107
+                );
108
+            }
109
+
110
+            public function registerService(string $name, callable $factory, bool $shared = true): void {
111
+                $this->context->registerService(
112
+                    $this->appId,
113
+                    $name,
114
+                    $factory,
115
+                    $shared
116
+                );
117
+            }
118
+
119
+            public function registerServiceAlias(string $alias, string $target): void {
120
+                $this->context->registerServiceAlias(
121
+                    $this->appId,
122
+                    $alias,
123
+                    $target
124
+                );
125
+            }
126
+
127
+            public function registerParameter(string $name, $value): void {
128
+                $this->context->registerParameter(
129
+                    $this->appId,
130
+                    $name,
131
+                    $value
132
+                );
133
+            }
134
+
135
+            public function registerEventListener(string $event, string $listener, int $priority = 0): void {
136
+                $this->context->registerEventListener(
137
+                    $this->appId,
138
+                    $event,
139
+                    $listener,
140
+                    $priority
141
+                );
142
+            }
143
+
144
+            public function registerMiddleware(string $class): void {
145
+                $this->context->registerMiddleware(
146
+                    $this->appId,
147
+                    $class
148
+                );
149
+            }
150
+
151
+            public function registerSearchProvider(string $class): void {
152
+                $this->context->registerSearchProvider(
153
+                    $this->appId,
154
+                    $class
155
+                );
156
+            }
157
+
158
+            public function registerAlternativeLogin(string $class): void {
159
+                $this->context->registerAlternativeLogin(
160
+                    $this->appId,
161
+                    $class
162
+                );
163
+            }
164
+        };
165
+    }
166
+
167
+    public function registerCapability(string $appId, string $capability): void {
168
+        $this->capabilities[] = [
169
+            'appId' => $appId,
170
+            'capability' => $capability
171
+        ];
172
+    }
173
+
174
+    public function registerCrashReporter(string $appId, string $reporterClass): void {
175
+        $this->crashReporters[] = [
176
+            'appId' => $appId,
177
+            'class' => $reporterClass,
178
+        ];
179
+    }
180
+
181
+    public function registerDashboardPanel(string $appId, string $panelClass): void {
182
+        $this->dashboardPanels[] = [
183
+            'appId' => $appId,
184
+            'class' => $panelClass
185
+        ];
186
+    }
187
+
188
+    public function registerService(string $appId, string $name, callable $factory, bool $shared = true): void {
189
+        $this->services[] = [
190
+            "appId" => $appId,
191
+            "name" => $name,
192
+            "factory" => $factory,
193
+            "sharred" => $shared,
194
+        ];
195
+    }
196
+
197
+    public function registerServiceAlias(string $appId, string $alias, string $target): void {
198
+        $this->aliases[] = [
199
+            "appId" => $appId,
200
+            "alias" => $alias,
201
+            "target" => $target,
202
+        ];
203
+    }
204
+
205
+    public function registerParameter(string $appId, string $name, $value): void {
206
+        $this->parameters[] = [
207
+            "appId" => $appId,
208
+            "name" => $name,
209
+            "value" => $value,
210
+        ];
211
+    }
212
+
213
+    public function registerEventListener(string $appId, string $event, string $listener, int $priority = 0): void {
214
+        $this->eventListeners[] = [
215
+            "appId" => $appId,
216
+            "event" => $event,
217
+            "listener" => $listener,
218
+            "priority" => $priority,
219
+        ];
220
+    }
221
+
222
+    public function registerMiddleware(string $appId, string $class): void {
223
+        $this->middlewares[] = [
224
+            "appId" => $appId,
225
+            "class" => $class,
226
+        ];
227
+    }
228
+
229
+    public function registerSearchProvider(string $appId, string $class) {
230
+        $this->searchProviders[] = [
231
+            'appId' => $appId,
232
+            'class' => $class,
233
+        ];
234
+    }
235
+
236
+    public function registerAlternativeLogin(string $appId, string $class): void {
237
+        $this->alternativeLogins[] = [
238
+            'appId' => $appId,
239
+            'class' => $class,
240
+        ];
241
+    }
242
+
243
+    /**
244
+     * @param App[] $apps
245
+     */
246
+    public function delegateCapabilityRegistrations(array $apps): void {
247
+        foreach ($this->capabilities as $registration) {
248
+            try {
249
+                $apps[$registration['appId']]
250
+                    ->getContainer()
251
+                    ->registerCapability($registration['capability']);
252
+            } catch (Throwable $e) {
253
+                $appId = $registration['appId'];
254
+                $this->logger->logException($e, [
255
+                    'message' => "Error during capability registration of $appId: " . $e->getMessage(),
256
+                    'level' => ILogger::ERROR,
257
+                ]);
258
+            }
259
+        }
260
+    }
261
+
262
+    /**
263
+     * @param App[] $apps
264
+     */
265
+    public function delegateCrashReporterRegistrations(array $apps, Registry $registry): void {
266
+        foreach ($this->crashReporters as $registration) {
267
+            try {
268
+                $registry->registerLazy($registration['class']);
269
+            } catch (Throwable $e) {
270
+                $appId = $registration['appId'];
271
+                $this->logger->logException($e, [
272
+                    'message' => "Error during crash reporter registration of $appId: " . $e->getMessage(),
273
+                    'level' => ILogger::ERROR,
274
+                ]);
275
+            }
276
+        }
277
+    }
278
+
279
+    /**
280
+     * @param App[] $apps
281
+     */
282
+    public function delegateDashboardPanelRegistrations(array $apps, IManager $dashboardManager): void {
283
+        foreach ($this->dashboardPanels as $panel) {
284
+            try {
285
+                $dashboardManager->lazyRegisterWidget($panel['class']);
286
+            } catch (Throwable $e) {
287
+                $appId = $panel['appId'];
288
+                $this->logger->logException($e, [
289
+                    'message' => "Error during dashboard registration of $appId: " . $e->getMessage(),
290
+                    'level' => ILogger::ERROR,
291
+                ]);
292
+            }
293
+        }
294
+    }
295
+
296
+    public function delegateEventListenerRegistrations(IEventDispatcher $eventDispatcher): void {
297
+        foreach ($this->eventListeners as $registration) {
298
+            try {
299
+                if (isset($registration['priority'])) {
300
+                    $eventDispatcher->addServiceListener(
301
+                        $registration['event'],
302
+                        $registration['listener'],
303
+                        $registration['priority']
304
+                    );
305
+                } else {
306
+                    $eventDispatcher->addServiceListener(
307
+                        $registration['event'],
308
+                        $registration['listener']
309
+                    );
310
+                }
311
+            } catch (Throwable $e) {
312
+                $appId = $registration['appId'];
313
+                $this->logger->logException($e, [
314
+                    'message' => "Error during event listener registration of $appId: " . $e->getMessage(),
315
+                    'level' => ILogger::ERROR,
316
+                ]);
317
+            }
318
+        }
319
+    }
320
+
321
+    /**
322
+     * @param App[] $apps
323
+     */
324
+    public function delegateContainerRegistrations(array $apps): void {
325
+        foreach ($this->services as $registration) {
326
+            try {
327
+                /**
328
+                 * Register the service and convert the callable into a \Closure if necessary
329
+                 */
330
+                $apps[$registration['appId']]
331
+                    ->getContainer()
332
+                    ->registerService(
333
+                        $registration['name'],
334
+                        Closure::fromCallable($registration['factory']),
335
+                        $registration['shared'] ?? true
336
+                    );
337
+            } catch (Throwable $e) {
338
+                $appId = $registration['appId'];
339
+                $this->logger->logException($e, [
340
+                    'message' => "Error during service registration of $appId: " . $e->getMessage(),
341
+                    'level' => ILogger::ERROR,
342
+                ]);
343
+            }
344
+        }
345
+
346
+        foreach ($this->aliases as $registration) {
347
+            try {
348
+                $apps[$registration['appId']]
349
+                    ->getContainer()
350
+                    ->registerAlias(
351
+                        $registration['alias'],
352
+                        $registration['target']
353
+                    );
354
+            } catch (Throwable $e) {
355
+                $appId = $registration['appId'];
356
+                $this->logger->logException($e, [
357
+                    'message' => "Error during service alias registration of $appId: " . $e->getMessage(),
358
+                    'level' => ILogger::ERROR,
359
+                ]);
360
+            }
361
+        }
362
+
363
+        foreach ($this->parameters as $registration) {
364
+            try {
365
+                $apps[$registration['appId']]
366
+                    ->getContainer()
367
+                    ->registerParameter(
368
+                        $registration['name'],
369
+                        $registration['value']
370
+                    );
371
+            } catch (Throwable $e) {
372
+                $appId = $registration['appId'];
373
+                $this->logger->logException($e, [
374
+                    'message' => "Error during service alias registration of $appId: " . $e->getMessage(),
375
+                    'level' => ILogger::ERROR,
376
+                ]);
377
+            }
378
+        }
379
+    }
380
+
381
+    /**
382
+     * @param App[] $apps
383
+     */
384
+    public function delegateMiddlewareRegistrations(array $apps): void {
385
+        foreach ($this->middlewares as $middleware) {
386
+            try {
387
+                $apps[$middleware['appId']]
388
+                    ->getContainer()
389
+                    ->registerMiddleWare($middleware['class']);
390
+            } catch (Throwable $e) {
391
+                $appId = $middleware['appId'];
392
+                $this->logger->logException($e, [
393
+                    'message' => "Error during capability registration of $appId: " . $e->getMessage(),
394
+                    'level' => ILogger::ERROR,
395
+                ]);
396
+            }
397
+        }
398
+    }
399
+
400
+    /**
401
+     * @return array[]
402
+     */
403
+    public function getSearchProviders(): array {
404
+        return $this->searchProviders;
405
+    }
406
+
407
+    /**
408
+     * @return array[]
409
+     */
410
+    public function getAlternativeLogins(): array {
411
+        return $this->alternativeLogins;
412
+    }
413 413
 }
Please login to merge, or discard this patch.
apps/dashboard/lib/Controller/DashboardController.php 2 patches
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -41,72 +41,72 @@
 block discarded – undo
41 41
 
42 42
 class DashboardController extends Controller {
43 43
 
44
-	/** @var IInitialStateService */
45
-	private $inititalStateService;
46
-	/** @var IEventDispatcher */
47
-	private $eventDispatcher;
48
-	/** @var IManager */
49
-	private $dashboardManager;
50
-	/** @var IConfig */
51
-	private $config;
52
-	/** @var string */
53
-	private $userId;
44
+    /** @var IInitialStateService */
45
+    private $inititalStateService;
46
+    /** @var IEventDispatcher */
47
+    private $eventDispatcher;
48
+    /** @var IManager */
49
+    private $dashboardManager;
50
+    /** @var IConfig */
51
+    private $config;
52
+    /** @var string */
53
+    private $userId;
54 54
 
55
-	public function __construct(
56
-		string $appName,
57
-		IRequest $request,
58
-		IInitialStateService $initialStateService,
59
-		IEventDispatcher $eventDispatcher,
60
-		IManager $dashboardManager,
61
-		IConfig $config,
62
-		$userId
63
-	) {
64
-		parent::__construct($appName, $request);
55
+    public function __construct(
56
+        string $appName,
57
+        IRequest $request,
58
+        IInitialStateService $initialStateService,
59
+        IEventDispatcher $eventDispatcher,
60
+        IManager $dashboardManager,
61
+        IConfig $config,
62
+        $userId
63
+    ) {
64
+        parent::__construct($appName, $request);
65 65
 
66
-		$this->inititalStateService = $initialStateService;
67
-		$this->eventDispatcher = $eventDispatcher;
68
-		$this->dashboardManager = $dashboardManager;
69
-		$this->config = $config;
70
-		$this->userId = $userId;
71
-	}
66
+        $this->inititalStateService = $initialStateService;
67
+        $this->eventDispatcher = $eventDispatcher;
68
+        $this->dashboardManager = $dashboardManager;
69
+        $this->config = $config;
70
+        $this->userId = $userId;
71
+    }
72 72
 
73
-	/**
74
-	 * @NoCSRFRequired
75
-	 * @NoAdminRequired
76
-	 * @return TemplateResponse
77
-	 */
78
-	public function index(): TemplateResponse {
79
-		$this->eventDispatcher->dispatchTyped(new LoadSidebar());
80
-		if (class_exists(LoadViewer::class)) {
81
-			$this->eventDispatcher->dispatchTyped(new LoadViewer());
82
-		}
73
+    /**
74
+     * @NoCSRFRequired
75
+     * @NoAdminRequired
76
+     * @return TemplateResponse
77
+     */
78
+    public function index(): TemplateResponse {
79
+        $this->eventDispatcher->dispatchTyped(new LoadSidebar());
80
+        if (class_exists(LoadViewer::class)) {
81
+            $this->eventDispatcher->dispatchTyped(new LoadViewer());
82
+        }
83 83
 
84
-		$this->eventDispatcher->dispatchTyped(new RegisterWidgetEvent($this->dashboardManager));
84
+        $this->eventDispatcher->dispatchTyped(new RegisterWidgetEvent($this->dashboardManager));
85 85
 
86
-		$userLayout = explode(',', $this->config->getUserValue($this->userId, 'dashboard', 'layout', 'recommendations,spreed,mail,calendar'));
87
-		$widgets = array_map(function (IWidget $widget) {
88
-			return [
89
-				'id' => $widget->getId(),
90
-				'title' => $widget->getTitle(),
91
-				'iconClass' => $widget->getIconClass(),
92
-				'url' => $widget->getUrl()
93
-			];
94
-		}, $this->dashboardManager->getWidgets());
95
-		$this->inititalStateService->provideInitialState('dashboard', 'panels', $widgets);
96
-		$this->inititalStateService->provideInitialState('dashboard', 'layout', $userLayout);
97
-		$this->inititalStateService->provideInitialState('dashboard', 'firstRun', $this->config->getUserValue($this->userId, 'dashboard', 'firstRun', '1') === '1');
98
-		$this->config->setUserValue($this->userId, 'dashboard', 'firstRun', '0');
86
+        $userLayout = explode(',', $this->config->getUserValue($this->userId, 'dashboard', 'layout', 'recommendations,spreed,mail,calendar'));
87
+        $widgets = array_map(function (IWidget $widget) {
88
+            return [
89
+                'id' => $widget->getId(),
90
+                'title' => $widget->getTitle(),
91
+                'iconClass' => $widget->getIconClass(),
92
+                'url' => $widget->getUrl()
93
+            ];
94
+        }, $this->dashboardManager->getWidgets());
95
+        $this->inititalStateService->provideInitialState('dashboard', 'panels', $widgets);
96
+        $this->inititalStateService->provideInitialState('dashboard', 'layout', $userLayout);
97
+        $this->inititalStateService->provideInitialState('dashboard', 'firstRun', $this->config->getUserValue($this->userId, 'dashboard', 'firstRun', '1') === '1');
98
+        $this->config->setUserValue($this->userId, 'dashboard', 'firstRun', '0');
99 99
 
100
-		return new TemplateResponse('dashboard', 'index');
101
-	}
100
+        return new TemplateResponse('dashboard', 'index');
101
+    }
102 102
 
103
-	/**
104
-	 * @NoAdminRequired
105
-	 * @param string $layout
106
-	 * @return JSONResponse
107
-	 */
108
-	public function updateLayout(string $layout): JSONResponse {
109
-		$this->config->setUserValue($this->userId, 'dashboard', 'layout', $layout);
110
-		return new JSONResponse(['layout' => $layout]);
111
-	}
103
+    /**
104
+     * @NoAdminRequired
105
+     * @param string $layout
106
+     * @return JSONResponse
107
+     */
108
+    public function updateLayout(string $layout): JSONResponse {
109
+        $this->config->setUserValue($this->userId, 'dashboard', 'layout', $layout);
110
+        return new JSONResponse(['layout' => $layout]);
111
+    }
112 112
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@
 block discarded – undo
84 84
 		$this->eventDispatcher->dispatchTyped(new RegisterWidgetEvent($this->dashboardManager));
85 85
 
86 86
 		$userLayout = explode(',', $this->config->getUserValue($this->userId, 'dashboard', 'layout', 'recommendations,spreed,mail,calendar'));
87
-		$widgets = array_map(function (IWidget $widget) {
87
+		$widgets = array_map(function(IWidget $widget) {
88 88
 			return [
89 89
 				'id' => $widget->getId(),
90 90
 				'title' => $widget->getTitle(),
Please login to merge, or discard this patch.
apps/dashboard/appinfo/routes.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -25,8 +25,8 @@
 block discarded – undo
25 25
  */
26 26
 
27 27
 return [
28
-	'routes' => [
29
-		['name' => 'dashboard#index', 'url' => '/', 'verb' => 'GET'],
30
-		['name' => 'dashboard#updateLayout', 'url' => '/layout', 'verb' => 'POST'],
31
-	]
28
+    'routes' => [
29
+        ['name' => 'dashboard#index', 'url' => '/', 'verb' => 'GET'],
30
+        ['name' => 'dashboard#updateLayout', 'url' => '/layout', 'verb' => 'POST'],
31
+    ]
32 32
 ];
Please login to merge, or discard this patch.