Completed
Pull Request — stable10 (#5732)
by Morris
14:18
created
lib/private/Memcache/APC.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -29,108 +29,108 @@
 block discarded – undo
29 29
 use OCP\IMemcache;
30 30
 
31 31
 class APC extends Cache implements IMemcache {
32
-	use CASTrait {
33
-		cas as casEmulated;
34
-	}
32
+    use CASTrait {
33
+        cas as casEmulated;
34
+    }
35 35
 
36
-	use CADTrait;
36
+    use CADTrait;
37 37
 
38
-	public function get($key) {
39
-		$result = apc_fetch($this->getPrefix() . $key, $success);
40
-		if (!$success) {
41
-			return null;
42
-		}
43
-		return $result;
44
-	}
38
+    public function get($key) {
39
+        $result = apc_fetch($this->getPrefix() . $key, $success);
40
+        if (!$success) {
41
+            return null;
42
+        }
43
+        return $result;
44
+    }
45 45
 
46
-	public function set($key, $value, $ttl = 0) {
47
-		return apc_store($this->getPrefix() . $key, $value, $ttl);
48
-	}
46
+    public function set($key, $value, $ttl = 0) {
47
+        return apc_store($this->getPrefix() . $key, $value, $ttl);
48
+    }
49 49
 
50
-	public function hasKey($key) {
51
-		return apc_exists($this->getPrefix() . $key);
52
-	}
50
+    public function hasKey($key) {
51
+        return apc_exists($this->getPrefix() . $key);
52
+    }
53 53
 
54
-	public function remove($key) {
55
-		return apc_delete($this->getPrefix() . $key);
56
-	}
54
+    public function remove($key) {
55
+        return apc_delete($this->getPrefix() . $key);
56
+    }
57 57
 
58
-	public function clear($prefix = '') {
59
-		$ns = $this->getPrefix() . $prefix;
60
-		$ns = preg_quote($ns, '/');
61
-		$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
-		return apc_delete($iter);
63
-	}
58
+    public function clear($prefix = '') {
59
+        $ns = $this->getPrefix() . $prefix;
60
+        $ns = preg_quote($ns, '/');
61
+        $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+        return apc_delete($iter);
63
+    }
64 64
 
65
-	/**
66
-	 * Set a value in the cache if it's not already stored
67
-	 *
68
-	 * @param string $key
69
-	 * @param mixed $value
70
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
71
-	 * @return bool
72
-	 */
73
-	public function add($key, $value, $ttl = 0) {
74
-		return apc_add($this->getPrefix() . $key, $value, $ttl);
75
-	}
65
+    /**
66
+     * Set a value in the cache if it's not already stored
67
+     *
68
+     * @param string $key
69
+     * @param mixed $value
70
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
71
+     * @return bool
72
+     */
73
+    public function add($key, $value, $ttl = 0) {
74
+        return apc_add($this->getPrefix() . $key, $value, $ttl);
75
+    }
76 76
 
77
-	/**
78
-	 * Increase a stored number
79
-	 *
80
-	 * @param string $key
81
-	 * @param int $step
82
-	 * @return int | bool
83
-	 */
84
-	public function inc($key, $step = 1) {
85
-		$this->add($key, 0);
86
-		return apc_inc($this->getPrefix() . $key, $step);
87
-	}
77
+    /**
78
+     * Increase a stored number
79
+     *
80
+     * @param string $key
81
+     * @param int $step
82
+     * @return int | bool
83
+     */
84
+    public function inc($key, $step = 1) {
85
+        $this->add($key, 0);
86
+        return apc_inc($this->getPrefix() . $key, $step);
87
+    }
88 88
 
89
-	/**
90
-	 * Decrease a stored number
91
-	 *
92
-	 * @param string $key
93
-	 * @param int $step
94
-	 * @return int | bool
95
-	 */
96
-	public function dec($key, $step = 1) {
97
-		return apc_dec($this->getPrefix() . $key, $step);
98
-	}
89
+    /**
90
+     * Decrease a stored number
91
+     *
92
+     * @param string $key
93
+     * @param int $step
94
+     * @return int | bool
95
+     */
96
+    public function dec($key, $step = 1) {
97
+        return apc_dec($this->getPrefix() . $key, $step);
98
+    }
99 99
 
100
-	/**
101
-	 * Compare and set
102
-	 *
103
-	 * @param string $key
104
-	 * @param mixed $old
105
-	 * @param mixed $new
106
-	 * @return bool
107
-	 */
108
-	public function cas($key, $old, $new) {
109
-		// apc only does cas for ints
110
-		if (is_int($old) and is_int($new)) {
111
-			return apc_cas($this->getPrefix() . $key, $old, $new);
112
-		} else {
113
-			return $this->casEmulated($key, $old, $new);
114
-		}
115
-	}
100
+    /**
101
+     * Compare and set
102
+     *
103
+     * @param string $key
104
+     * @param mixed $old
105
+     * @param mixed $new
106
+     * @return bool
107
+     */
108
+    public function cas($key, $old, $new) {
109
+        // apc only does cas for ints
110
+        if (is_int($old) and is_int($new)) {
111
+            return apc_cas($this->getPrefix() . $key, $old, $new);
112
+        } else {
113
+            return $this->casEmulated($key, $old, $new);
114
+        }
115
+    }
116 116
 
117
-	static public function isAvailable() {
118
-		if (!extension_loaded('apc')) {
119
-			return false;
120
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
121
-			return false;
122
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
123
-			return false;
124
-		} else {
125
-			return true;
126
-		}
127
-	}
117
+    static public function isAvailable() {
118
+        if (!extension_loaded('apc')) {
119
+            return false;
120
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
121
+            return false;
122
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
123
+            return false;
124
+        } else {
125
+            return true;
126
+        }
127
+    }
128 128
 }
129 129
 
130 130
 if (!function_exists('apc_exists')) {
131
-	function apc_exists($keys) {
132
-		$result = false;
133
-		apc_fetch($keys, $result);
134
-		return $result;
135
-	}
131
+    function apc_exists($keys) {
132
+        $result = false;
133
+        apc_fetch($keys, $result);
134
+        return $result;
135
+    }
136 136
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	use CADTrait;
37 37
 
38 38
 	public function get($key) {
39
-		$result = apc_fetch($this->getPrefix() . $key, $success);
39
+		$result = apc_fetch($this->getPrefix().$key, $success);
40 40
 		if (!$success) {
41 41
 			return null;
42 42
 		}
@@ -44,21 +44,21 @@  discard block
 block discarded – undo
44 44
 	}
45 45
 
46 46
 	public function set($key, $value, $ttl = 0) {
47
-		return apc_store($this->getPrefix() . $key, $value, $ttl);
47
+		return apc_store($this->getPrefix().$key, $value, $ttl);
48 48
 	}
49 49
 
50 50
 	public function hasKey($key) {
51
-		return apc_exists($this->getPrefix() . $key);
51
+		return apc_exists($this->getPrefix().$key);
52 52
 	}
53 53
 
54 54
 	public function remove($key) {
55
-		return apc_delete($this->getPrefix() . $key);
55
+		return apc_delete($this->getPrefix().$key);
56 56
 	}
57 57
 
58 58
 	public function clear($prefix = '') {
59
-		$ns = $this->getPrefix() . $prefix;
59
+		$ns = $this->getPrefix().$prefix;
60 60
 		$ns = preg_quote($ns, '/');
61
-		$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
61
+		$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
62 62
 		return apc_delete($iter);
63 63
 	}
64 64
 
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 	 * @return bool
72 72
 	 */
73 73
 	public function add($key, $value, $ttl = 0) {
74
-		return apc_add($this->getPrefix() . $key, $value, $ttl);
74
+		return apc_add($this->getPrefix().$key, $value, $ttl);
75 75
 	}
76 76
 
77 77
 	/**
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 	 */
84 84
 	public function inc($key, $step = 1) {
85 85
 		$this->add($key, 0);
86
-		return apc_inc($this->getPrefix() . $key, $step);
86
+		return apc_inc($this->getPrefix().$key, $step);
87 87
 	}
88 88
 
89 89
 	/**
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	 * @return int | bool
95 95
 	 */
96 96
 	public function dec($key, $step = 1) {
97
-		return apc_dec($this->getPrefix() . $key, $step);
97
+		return apc_dec($this->getPrefix().$key, $step);
98 98
 	}
99 99
 
100 100
 	/**
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 	public function cas($key, $old, $new) {
109 109
 		// apc only does cas for ints
110 110
 		if (is_int($old) and is_int($new)) {
111
-			return apc_cas($this->getPrefix() . $key, $old, $new);
111
+			return apc_cas($this->getPrefix().$key, $old, $new);
112 112
 		} else {
113 113
 			return $this->casEmulated($key, $old, $new);
114 114
 		}
Please login to merge, or discard this patch.
lib/private/Memcache/Memcached.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@
 block discarded – undo
155 155
 	 * Set a value in the cache if it's not already stored
156 156
 	 *
157 157
 	 * @param string $key
158
-	 * @param mixed $value
158
+	 * @param integer $value
159 159
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
160 160
 	 * @return bool
161 161
 	 * @throws \Exception
Please login to merge, or discard this patch.
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -33,190 +33,190 @@
 block discarded – undo
33 33
 use OCP\IMemcache;
34 34
 
35 35
 class Memcached extends Cache implements IMemcache {
36
-	use CASTrait;
37
-
38
-	/**
39
-	 * @var \Memcached $cache
40
-	 */
41
-	private static $cache = null;
42
-
43
-	use CADTrait;
44
-
45
-	public function __construct($prefix = '') {
46
-		parent::__construct($prefix);
47
-		if (is_null(self::$cache)) {
48
-			self::$cache = new \Memcached();
49
-			$servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
50
-			if (!$servers) {
51
-				$server = \OC::$server->getSystemConfig()->getValue('memcached_server');
52
-				if ($server) {
53
-					$servers = array($server);
54
-				} else {
55
-					$servers = array(array('localhost', 11211));
56
-				}
57
-			}
58
-			self::$cache->addServers($servers);
59
-
60
-			$defaultOptions = [
61
-				\Memcached::OPT_CONNECT_TIMEOUT => 50,
62
-				\Memcached::OPT_RETRY_TIMEOUT =>   50,
63
-				\Memcached::OPT_SEND_TIMEOUT =>    50,
64
-				\Memcached::OPT_RECV_TIMEOUT =>    50,
65
-				\Memcached::OPT_POLL_TIMEOUT =>    50,
66
-
67
-				// Enable compression
68
-				\Memcached::OPT_COMPRESSION =>          true,
69
-
70
-				// Turn on consistent hashing
71
-				\Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
72
-
73
-				// Enable Binary Protocol
74
-				\Memcached::OPT_BINARY_PROTOCOL =>      true,
75
-			];
76
-			// by default enable igbinary serializer if available
77
-			if (\Memcached::HAVE_IGBINARY) {
78
-				$defaultOptions[\Memcached::OPT_SERIALIZER] =
79
-					\Memcached::SERIALIZER_IGBINARY;
80
-			}
81
-			$options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
82
-			if (is_array($options)) {
83
-				$options = $options + $defaultOptions;
84
-				self::$cache->setOptions($options);
85
-			} else {
86
-				throw new HintException("Expected 'memcached_options' config to be an array, got $options");
87
-			}
88
-		}
89
-	}
90
-
91
-	/**
92
-	 * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
93
-	 */
94
-	protected function getNameSpace() {
95
-		return $this->prefix;
96
-	}
97
-
98
-	public function get($key) {
99
-		$result = self::$cache->get($this->getNamespace() . $key);
100
-		if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
101
-			return null;
102
-		} else {
103
-			return $result;
104
-		}
105
-	}
106
-
107
-	public function set($key, $value, $ttl = 0) {
108
-		if ($ttl > 0) {
109
-			$result =  self::$cache->set($this->getNamespace() . $key, $value, $ttl);
110
-		} else {
111
-			$result = self::$cache->set($this->getNamespace() . $key, $value);
112
-		}
113
-		$this->verifyReturnCode();
114
-		return $result;
115
-	}
116
-
117
-	public function hasKey($key) {
118
-		self::$cache->get($this->getNamespace() . $key);
119
-		return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
120
-	}
121
-
122
-	public function remove($key) {
123
-		$result= self::$cache->delete($this->getNamespace() . $key);
124
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
125
-			$this->verifyReturnCode();
126
-		}
127
-		return $result;
128
-	}
129
-
130
-	public function clear($prefix = '') {
131
-		$prefix = $this->getNamespace() . $prefix;
132
-		$allKeys = self::$cache->getAllKeys();
133
-		if ($allKeys === false) {
134
-			// newer Memcached doesn't like getAllKeys(), flush everything
135
-			self::$cache->flush();
136
-			return true;
137
-		}
138
-		$keys = array();
139
-		$prefixLength = strlen($prefix);
140
-		foreach ($allKeys as $key) {
141
-			if (substr($key, 0, $prefixLength) === $prefix) {
142
-				$keys[] = $key;
143
-			}
144
-		}
145
-		if (method_exists(self::$cache, 'deleteMulti')) {
146
-			self::$cache->deleteMulti($keys);
147
-		} else {
148
-			foreach ($keys as $key) {
149
-				self::$cache->delete($key);
150
-			}
151
-		}
152
-		return true;
153
-	}
154
-
155
-	/**
156
-	 * Set a value in the cache if it's not already stored
157
-	 *
158
-	 * @param string $key
159
-	 * @param mixed $value
160
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
161
-	 * @return bool
162
-	 * @throws \Exception
163
-	 */
164
-	public function add($key, $value, $ttl = 0) {
165
-		$result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
166
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
167
-			$this->verifyReturnCode();
168
-		}
169
-		return $result;
170
-	}
171
-
172
-	/**
173
-	 * Increase a stored number
174
-	 *
175
-	 * @param string $key
176
-	 * @param int $step
177
-	 * @return int | bool
178
-	 */
179
-	public function inc($key, $step = 1) {
180
-		$this->add($key, 0);
181
-		$result = self::$cache->increment($this->getPrefix() . $key, $step);
182
-
183
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
184
-			return false;
185
-		}
186
-
187
-		return $result;
188
-	}
189
-
190
-	/**
191
-	 * Decrease a stored number
192
-	 *
193
-	 * @param string $key
194
-	 * @param int $step
195
-	 * @return int | bool
196
-	 */
197
-	public function dec($key, $step = 1) {
198
-		$result = self::$cache->decrement($this->getPrefix() . $key, $step);
199
-
200
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
201
-			return false;
202
-		}
203
-
204
-		return $result;
205
-	}
206
-
207
-	static public function isAvailable() {
208
-		return extension_loaded('memcached');
209
-	}
210
-
211
-	/**
212
-	 * @throws \Exception
213
-	 */
214
-	private function verifyReturnCode() {
215
-		$code = self::$cache->getResultCode();
216
-		if ($code === \Memcached::RES_SUCCESS) {
217
-			return;
218
-		}
219
-		$message = self::$cache->getResultMessage();
220
-		throw new \Exception("Error $code interacting with memcached : $message");
221
-	}
36
+    use CASTrait;
37
+
38
+    /**
39
+     * @var \Memcached $cache
40
+     */
41
+    private static $cache = null;
42
+
43
+    use CADTrait;
44
+
45
+    public function __construct($prefix = '') {
46
+        parent::__construct($prefix);
47
+        if (is_null(self::$cache)) {
48
+            self::$cache = new \Memcached();
49
+            $servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
50
+            if (!$servers) {
51
+                $server = \OC::$server->getSystemConfig()->getValue('memcached_server');
52
+                if ($server) {
53
+                    $servers = array($server);
54
+                } else {
55
+                    $servers = array(array('localhost', 11211));
56
+                }
57
+            }
58
+            self::$cache->addServers($servers);
59
+
60
+            $defaultOptions = [
61
+                \Memcached::OPT_CONNECT_TIMEOUT => 50,
62
+                \Memcached::OPT_RETRY_TIMEOUT =>   50,
63
+                \Memcached::OPT_SEND_TIMEOUT =>    50,
64
+                \Memcached::OPT_RECV_TIMEOUT =>    50,
65
+                \Memcached::OPT_POLL_TIMEOUT =>    50,
66
+
67
+                // Enable compression
68
+                \Memcached::OPT_COMPRESSION =>          true,
69
+
70
+                // Turn on consistent hashing
71
+                \Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
72
+
73
+                // Enable Binary Protocol
74
+                \Memcached::OPT_BINARY_PROTOCOL =>      true,
75
+            ];
76
+            // by default enable igbinary serializer if available
77
+            if (\Memcached::HAVE_IGBINARY) {
78
+                $defaultOptions[\Memcached::OPT_SERIALIZER] =
79
+                    \Memcached::SERIALIZER_IGBINARY;
80
+            }
81
+            $options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
82
+            if (is_array($options)) {
83
+                $options = $options + $defaultOptions;
84
+                self::$cache->setOptions($options);
85
+            } else {
86
+                throw new HintException("Expected 'memcached_options' config to be an array, got $options");
87
+            }
88
+        }
89
+    }
90
+
91
+    /**
92
+     * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
93
+     */
94
+    protected function getNameSpace() {
95
+        return $this->prefix;
96
+    }
97
+
98
+    public function get($key) {
99
+        $result = self::$cache->get($this->getNamespace() . $key);
100
+        if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
101
+            return null;
102
+        } else {
103
+            return $result;
104
+        }
105
+    }
106
+
107
+    public function set($key, $value, $ttl = 0) {
108
+        if ($ttl > 0) {
109
+            $result =  self::$cache->set($this->getNamespace() . $key, $value, $ttl);
110
+        } else {
111
+            $result = self::$cache->set($this->getNamespace() . $key, $value);
112
+        }
113
+        $this->verifyReturnCode();
114
+        return $result;
115
+    }
116
+
117
+    public function hasKey($key) {
118
+        self::$cache->get($this->getNamespace() . $key);
119
+        return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
120
+    }
121
+
122
+    public function remove($key) {
123
+        $result= self::$cache->delete($this->getNamespace() . $key);
124
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
125
+            $this->verifyReturnCode();
126
+        }
127
+        return $result;
128
+    }
129
+
130
+    public function clear($prefix = '') {
131
+        $prefix = $this->getNamespace() . $prefix;
132
+        $allKeys = self::$cache->getAllKeys();
133
+        if ($allKeys === false) {
134
+            // newer Memcached doesn't like getAllKeys(), flush everything
135
+            self::$cache->flush();
136
+            return true;
137
+        }
138
+        $keys = array();
139
+        $prefixLength = strlen($prefix);
140
+        foreach ($allKeys as $key) {
141
+            if (substr($key, 0, $prefixLength) === $prefix) {
142
+                $keys[] = $key;
143
+            }
144
+        }
145
+        if (method_exists(self::$cache, 'deleteMulti')) {
146
+            self::$cache->deleteMulti($keys);
147
+        } else {
148
+            foreach ($keys as $key) {
149
+                self::$cache->delete($key);
150
+            }
151
+        }
152
+        return true;
153
+    }
154
+
155
+    /**
156
+     * Set a value in the cache if it's not already stored
157
+     *
158
+     * @param string $key
159
+     * @param mixed $value
160
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
161
+     * @return bool
162
+     * @throws \Exception
163
+     */
164
+    public function add($key, $value, $ttl = 0) {
165
+        $result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
166
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
167
+            $this->verifyReturnCode();
168
+        }
169
+        return $result;
170
+    }
171
+
172
+    /**
173
+     * Increase a stored number
174
+     *
175
+     * @param string $key
176
+     * @param int $step
177
+     * @return int | bool
178
+     */
179
+    public function inc($key, $step = 1) {
180
+        $this->add($key, 0);
181
+        $result = self::$cache->increment($this->getPrefix() . $key, $step);
182
+
183
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
184
+            return false;
185
+        }
186
+
187
+        return $result;
188
+    }
189
+
190
+    /**
191
+     * Decrease a stored number
192
+     *
193
+     * @param string $key
194
+     * @param int $step
195
+     * @return int | bool
196
+     */
197
+    public function dec($key, $step = 1) {
198
+        $result = self::$cache->decrement($this->getPrefix() . $key, $step);
199
+
200
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
201
+            return false;
202
+        }
203
+
204
+        return $result;
205
+    }
206
+
207
+    static public function isAvailable() {
208
+        return extension_loaded('memcached');
209
+    }
210
+
211
+    /**
212
+     * @throws \Exception
213
+     */
214
+    private function verifyReturnCode() {
215
+        $code = self::$cache->getResultCode();
216
+        if ($code === \Memcached::RES_SUCCESS) {
217
+            return;
218
+        }
219
+        $message = self::$cache->getResultMessage();
220
+        throw new \Exception("Error $code interacting with memcached : $message");
221
+    }
222 222
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 	}
97 97
 
98 98
 	public function get($key) {
99
-		$result = self::$cache->get($this->getNamespace() . $key);
99
+		$result = self::$cache->get($this->getNamespace().$key);
100 100
 		if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
101 101
 			return null;
102 102
 		} else {
@@ -106,21 +106,21 @@  discard block
 block discarded – undo
106 106
 
107 107
 	public function set($key, $value, $ttl = 0) {
108 108
 		if ($ttl > 0) {
109
-			$result =  self::$cache->set($this->getNamespace() . $key, $value, $ttl);
109
+			$result = self::$cache->set($this->getNamespace().$key, $value, $ttl);
110 110
 		} else {
111
-			$result = self::$cache->set($this->getNamespace() . $key, $value);
111
+			$result = self::$cache->set($this->getNamespace().$key, $value);
112 112
 		}
113 113
 		$this->verifyReturnCode();
114 114
 		return $result;
115 115
 	}
116 116
 
117 117
 	public function hasKey($key) {
118
-		self::$cache->get($this->getNamespace() . $key);
118
+		self::$cache->get($this->getNamespace().$key);
119 119
 		return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
120 120
 	}
121 121
 
122 122
 	public function remove($key) {
123
-		$result= self::$cache->delete($this->getNamespace() . $key);
123
+		$result = self::$cache->delete($this->getNamespace().$key);
124 124
 		if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
125 125
 			$this->verifyReturnCode();
126 126
 		}
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 	}
129 129
 
130 130
 	public function clear($prefix = '') {
131
-		$prefix = $this->getNamespace() . $prefix;
131
+		$prefix = $this->getNamespace().$prefix;
132 132
 		$allKeys = self::$cache->getAllKeys();
133 133
 		if ($allKeys === false) {
134 134
 			// newer Memcached doesn't like getAllKeys(), flush everything
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 	 * @throws \Exception
163 163
 	 */
164 164
 	public function add($key, $value, $ttl = 0) {
165
-		$result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
165
+		$result = self::$cache->add($this->getPrefix().$key, $value, $ttl);
166 166
 		if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
167 167
 			$this->verifyReturnCode();
168 168
 		}
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	 */
179 179
 	public function inc($key, $step = 1) {
180 180
 		$this->add($key, 0);
181
-		$result = self::$cache->increment($this->getPrefix() . $key, $step);
181
+		$result = self::$cache->increment($this->getPrefix().$key, $step);
182 182
 
183 183
 		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
184 184
 			return false;
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 	 * @return int | bool
196 196
 	 */
197 197
 	public function dec($key, $step = 1) {
198
-		$result = self::$cache->decrement($this->getPrefix() . $key, $step);
198
+		$result = self::$cache->decrement($this->getPrefix().$key, $step);
199 199
 
200 200
 		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
201 201
 			return false;
Please login to merge, or discard this patch.
lib/private/Preview.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -923,7 +923,7 @@
 block discarded – undo
923 923
 	 * @param int $previewWidth
924 924
 	 * @param int $previewHeight
925 925
 	 *
926
-	 * @return int[]
926
+	 * @return double[]
927 927
 	 */
928 928
 	private function scale($image, $askedWidth, $askedHeight, $previewWidth, $previewHeight) {
929 929
 		$scalingUp = $this->getScalingUp();
Please login to merge, or discard this patch.
Indentation   +1308 added lines, -1308 removed lines patch added patch discarded remove patch
@@ -37,1313 +37,1313 @@
 block discarded – undo
37 37
 use OCP\Files\NotFoundException;
38 38
 
39 39
 class Preview {
40
-	//the thumbnail folder
41
-	const THUMBNAILS_FOLDER = 'thumbnails';
42
-
43
-	const MODE_FILL = 'fill';
44
-	const MODE_COVER = 'cover';
45
-
46
-	//config
47
-	private $maxScaleFactor;
48
-	/** @var int maximum width allowed for a preview */
49
-	private $configMaxWidth;
50
-	/** @var int maximum height allowed for a preview */
51
-	private $configMaxHeight;
52
-
53
-	//fileview object
54
-	private $fileView = null;
55
-	private $userView = null;
56
-
57
-	//vars
58
-	private $file;
59
-	private $maxX;
60
-	private $maxY;
61
-	private $scalingUp;
62
-	private $mimeType;
63
-	private $keepAspect = false;
64
-	private $mode = self::MODE_FILL;
65
-
66
-	//used to calculate the size of the preview to generate
67
-	/** @var int $maxPreviewWidth max width a preview can have */
68
-	private $maxPreviewWidth;
69
-	/** @var int $maxPreviewHeight max height a preview can have */
70
-	private $maxPreviewHeight;
71
-	/** @var int $previewWidth calculated width of the preview we're looking for */
72
-	private $previewWidth;
73
-	/** @var int $previewHeight calculated height of the preview we're looking for */
74
-	private $previewHeight;
75
-
76
-	//filemapper used for deleting previews
77
-	// index is path, value is fileinfo
78
-	static public $deleteFileMapper = array();
79
-	static public $deleteChildrenMapper = array();
80
-
81
-	/**
82
-	 * preview images object
83
-	 *
84
-	 * @var \OCP\IImage
85
-	 */
86
-	private $preview;
87
-
88
-	/**
89
-	 * @var \OCP\Files\FileInfo
90
-	 */
91
-	protected $info;
92
-
93
-	/**
94
-	 * check if thumbnail or bigger version of thumbnail of file is cached
95
-	 *
96
-	 * @param string $user userid - if no user is given, OC_User::getUser will be used
97
-	 * @param string $root path of root
98
-	 * @param string $file The path to the file where you want a thumbnail from
99
-	 * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the
100
-	 *     shape of the image
101
-	 * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the
102
-	 *     shape of the image
103
-	 * @param bool $scalingUp Disable/Enable upscaling of previews
104
-	 *
105
-	 * @throws \Exception
106
-	 * @return mixed (bool / string)
107
-	 *                    false if thumbnail does not exist
108
-	 *                    path to thumbnail if thumbnail exists
109
-	 */
110
-	public function __construct(
111
-		$user = '',
112
-		$root = '/',
113
-		$file = '', $maxX = 1,
114
-		$maxY = 1,
115
-		$scalingUp = true
116
-	) {
117
-		//init fileviews
118
-		if ($user === '') {
119
-			$user = \OC_User::getUser();
120
-		}
121
-		$this->fileView = new \OC\Files\View('/' . $user . '/' . $root);
122
-		$this->userView = new \OC\Files\View('/' . $user);
123
-
124
-		//set config
125
-		$sysConfig = \OC::$server->getConfig();
126
-		$this->configMaxWidth = $sysConfig->getSystemValue('preview_max_x', 2048);
127
-		$this->configMaxHeight = $sysConfig->getSystemValue('preview_max_y', 2048);
128
-		$this->maxScaleFactor = $sysConfig->getSystemValue('preview_max_scale_factor', 2);
129
-
130
-		//save parameters
131
-		$this->setFile($file);
132
-		$this->setMaxX((int)$maxX);
133
-		$this->setMaxY((int)$maxY);
134
-		$this->setScalingUp($scalingUp);
135
-
136
-		$this->preview = null;
137
-
138
-		//check if there are preview backends
139
-		if (!\OC::$server->getPreviewManager()
140
-				->hasProviders()
141
-			&& \OC::$server->getConfig()
142
-				->getSystemValue('enable_previews', true)
143
-		) {
144
-			\OCP\Util::writeLog('core', 'No preview providers exist', \OCP\Util::ERROR);
145
-			throw new \Exception('No preview providers');
146
-		}
147
-	}
148
-
149
-	/**
150
-	 * returns the path of the file you want a thumbnail from
151
-	 *
152
-	 * @return string
153
-	 */
154
-	public function getFile() {
155
-		return $this->file;
156
-	}
157
-
158
-	/**
159
-	 * returns the max width of the preview
160
-	 *
161
-	 * @return integer
162
-	 */
163
-	public function getMaxX() {
164
-		return $this->maxX;
165
-	}
166
-
167
-	/**
168
-	 * returns the max height of the preview
169
-	 *
170
-	 * @return integer
171
-	 */
172
-	public function getMaxY() {
173
-		return $this->maxY;
174
-	}
175
-
176
-	/**
177
-	 * returns whether or not scalingup is enabled
178
-	 *
179
-	 * @return bool
180
-	 */
181
-	public function getScalingUp() {
182
-		return $this->scalingUp;
183
-	}
184
-
185
-	/**
186
-	 * returns the name of the thumbnailfolder
187
-	 *
188
-	 * @return string
189
-	 */
190
-	public function getThumbnailsFolder() {
191
-		return self::THUMBNAILS_FOLDER;
192
-	}
193
-
194
-	/**
195
-	 * returns the max scale factor
196
-	 *
197
-	 * @return string
198
-	 */
199
-	public function getMaxScaleFactor() {
200
-		return $this->maxScaleFactor;
201
-	}
202
-
203
-	/**
204
-	 * returns the max width set in ownCloud's config
205
-	 *
206
-	 * @return integer
207
-	 */
208
-	public function getConfigMaxX() {
209
-		return $this->configMaxWidth;
210
-	}
211
-
212
-	/**
213
-	 * returns the max height set in ownCloud's config
214
-	 *
215
-	 * @return integer
216
-	 */
217
-	public function getConfigMaxY() {
218
-		return $this->configMaxHeight;
219
-	}
220
-
221
-	/**
222
-	 * Returns the FileInfo object associated with the file to preview
223
-	 *
224
-	 * @return false|Files\FileInfo|\OCP\Files\FileInfo
225
-	 */
226
-	protected function getFileInfo() {
227
-		$absPath = $this->fileView->getAbsolutePath($this->file);
228
-		$absPath = Files\Filesystem::normalizePath($absPath);
229
-		if (array_key_exists($absPath, self::$deleteFileMapper)) {
230
-			$this->info = self::$deleteFileMapper[$absPath];
231
-		} else if (!$this->info) {
232
-			$this->info = $this->fileView->getFileInfo($this->file);
233
-		}
234
-
235
-		return $this->info;
236
-	}
237
-
238
-
239
-	/**
240
-	 * @return array|null
241
-	 */
242
-	private function getChildren() {
243
-		$absPath = $this->fileView->getAbsolutePath($this->file);
244
-		$absPath = Files\Filesystem::normalizePath($absPath);
245
-
246
-		if (array_key_exists($absPath, self::$deleteChildrenMapper)) {
247
-			return self::$deleteChildrenMapper[$absPath];
248
-		}
249
-
250
-		return null;
251
-	}
252
-
253
-	/**
254
-	 * Sets the path of the file you want a preview of
255
-	 *
256
-	 * @param string $file
257
-	 * @param \OCP\Files\FileInfo|null $info
258
-	 *
259
-	 * @return \OC\Preview
260
-	 */
261
-	public function setFile($file, $info = null) {
262
-		$this->file = $file;
263
-		$this->info = $info;
264
-
265
-		if ($file !== '') {
266
-			$this->getFileInfo();
267
-			if ($this->info instanceof \OCP\Files\FileInfo) {
268
-				$this->mimeType = $this->info->getMimetype();
269
-			}
270
-		}
271
-
272
-		return $this;
273
-	}
274
-
275
-	/**
276
-	 * Forces the use of a specific media type
277
-	 *
278
-	 * @param string $mimeType
279
-	 */
280
-	public function setMimetype($mimeType) {
281
-		$this->mimeType = $mimeType;
282
-	}
283
-
284
-	/**
285
-	 * Sets the max width of the preview. It's capped by the maximum allowed size set in the
286
-	 * configuration
287
-	 *
288
-	 * @param int $maxX
289
-	 *
290
-	 * @throws \Exception
291
-	 * @return \OC\Preview
292
-	 */
293
-	public function setMaxX($maxX = 1) {
294
-		if ($maxX <= 0) {
295
-			throw new \Exception('Cannot set width of 0 or smaller!');
296
-		}
297
-		$configMaxX = $this->getConfigMaxX();
298
-		$maxX = $this->limitMaxDim($maxX, $configMaxX, 'maxX');
299
-		$this->maxX = $maxX;
300
-
301
-		return $this;
302
-	}
303
-
304
-	/**
305
-	 * Sets the max height of the preview. It's capped by the maximum allowed size set in the
306
-	 * configuration
307
-	 *
308
-	 * @param int $maxY
309
-	 *
310
-	 * @throws \Exception
311
-	 * @return \OC\Preview
312
-	 */
313
-	public function setMaxY($maxY = 1) {
314
-		if ($maxY <= 0) {
315
-			throw new \Exception('Cannot set height of 0 or smaller!');
316
-		}
317
-		$configMaxY = $this->getConfigMaxY();
318
-		$maxY = $this->limitMaxDim($maxY, $configMaxY, 'maxY');
319
-		$this->maxY = $maxY;
320
-
321
-		return $this;
322
-	}
323
-
324
-	/**
325
-	 * Sets whether we're allowed to scale up when generating a preview. It's capped by the maximum
326
-	 * allowed scale factor set in the configuration
327
-	 *
328
-	 * @param bool $scalingUp
329
-	 *
330
-	 * @return \OC\Preview
331
-	 */
332
-	public function setScalingup($scalingUp) {
333
-		if ($this->getMaxScaleFactor() === 1) {
334
-			$scalingUp = false;
335
-		}
336
-		$this->scalingUp = $scalingUp;
337
-
338
-		return $this;
339
-	}
340
-
341
-	/**
342
-	 * Set whether to cover or fill the specified dimensions
343
-	 *
344
-	 * @param string $mode
345
-	 *
346
-	 * @return \OC\Preview
347
-	 */
348
-	public function setMode($mode) {
349
-		$this->mode = $mode;
350
-
351
-		return $this;
352
-	}
353
-
354
-	/**
355
-	 * Sets whether we need to generate a preview which keeps the aspect ratio of the original file
356
-	 *
357
-	 * @param bool $keepAspect
358
-	 *
359
-	 * @return \OC\Preview
360
-	 */
361
-	public function setKeepAspect($keepAspect) {
362
-		$this->keepAspect = $keepAspect;
363
-
364
-		return $this;
365
-	}
366
-
367
-	/**
368
-	 * Makes sure we were given a file to preview and that it exists in the filesystem
369
-	 *
370
-	 * @return bool
371
-	 */
372
-	public function isFileValid() {
373
-		$file = $this->getFile();
374
-		if ($file === '') {
375
-			\OCP\Util::writeLog('core', 'No filename passed', \OCP\Util::DEBUG);
376
-
377
-			return false;
378
-		}
379
-
380
-		if (!$this->getFileInfo() instanceof FileInfo) {
381
-			\OCP\Util::writeLog('core', 'File:"' . $file . '" not found', \OCP\Util::DEBUG);
382
-
383
-			return false;
384
-		}
385
-
386
-		return true;
387
-	}
388
-
389
-	/**
390
-	 * Deletes the preview of a file with specific width and height
391
-	 *
392
-	 * This should never delete the max preview, use deleteAllPreviews() instead
393
-	 *
394
-	 * @return bool
395
-	 */
396
-	public function deletePreview() {
397
-		$fileInfo = $this->getFileInfo();
398
-		if ($fileInfo !== null && $fileInfo !== false) {
399
-			$fileId = $fileInfo->getId();
400
-
401
-			$previewPath = $this->buildCachePath($fileId);
402
-			if (!strpos($previewPath, 'max')) {
403
-				return $this->userView->unlink($previewPath);
404
-			}
405
-		}
406
-
407
-		return false;
408
-	}
409
-
410
-	/**
411
-	 * Deletes all previews of a file
412
-	 */
413
-	public function deleteAllPreviews() {
414
-		$thumbnailMount = $this->userView->getMount($this->getThumbnailsFolder());
415
-		$propagator = $thumbnailMount->getStorage()->getPropagator();
416
-		$propagator->beginBatch();
417
-
418
-		$toDelete = $this->getChildren();
419
-		$toDelete[] = $this->getFileInfo();
420
-
421
-		foreach ($toDelete as $delete) {
422
-			if ($delete instanceof FileInfo) {
423
-				/** @var \OCP\Files\FileInfo $delete */
424
-				$fileId = $delete->getId();
425
-
426
-				// getId() might return null, e.g. when the file is a
427
-				// .ocTransferId*.part file from chunked file upload.
428
-				if (!empty($fileId)) {
429
-					$previewPath = $this->getPreviewPath($fileId);
430
-					$this->userView->rmdir($previewPath);
431
-				}
432
-			}
433
-		}
434
-
435
-		$propagator->commitBatch();
436
-	}
437
-
438
-	/**
439
-	 * Checks if a preview matching the asked dimensions or a bigger version is already cached
440
-	 *
441
-	 *    * We first retrieve the size of the max preview since this is what we be used to create
442
-	 * all our preview. If it doesn't exist we return false, so that it can be generated
443
-	 *    * Using the dimensions of the max preview, we calculate what the size of the new
444
-	 * thumbnail should be
445
-	 *    * And finally, we look for a suitable candidate in the cache
446
-	 *
447
-	 * @param int $fileId fileId of the original file we need a preview of
448
-	 *
449
-	 * @return string|false path to the cached preview if it exists or false
450
-	 */
451
-	public function isCached($fileId) {
452
-		if (is_null($fileId)) {
453
-			return false;
454
-		}
455
-
456
-		/**
457
-		 * Phase 1: Looking for the max preview
458
-		 */
459
-		$previewPath = $this->getPreviewPath($fileId);
460
-		// We currently can't look for a single file due to bugs related to #16478
461
-		$allThumbnails = $this->userView->getDirectoryContent($previewPath);
462
-		list($maxPreviewWidth, $maxPreviewHeight) = $this->getMaxPreviewSize($allThumbnails);
463
-
464
-		// Only use the cache if we have a max preview
465
-		if (!is_null($maxPreviewWidth) && !is_null($maxPreviewHeight)) {
466
-
467
-			/**
468
-			 * Phase 2: Calculating the size of the preview we need to send back
469
-			 */
470
-			$this->maxPreviewWidth = $maxPreviewWidth;
471
-			$this->maxPreviewHeight = $maxPreviewHeight;
472
-
473
-			list($previewWidth, $previewHeight) = $this->simulatePreviewDimensions();
474
-			if (empty($previewWidth) || empty($previewHeight)) {
475
-				return false;
476
-			}
477
-
478
-			$this->previewWidth = $previewWidth;
479
-			$this->previewHeight = $previewHeight;
480
-
481
-			/**
482
-			 * Phase 3: We look for a preview of the exact size
483
-			 */
484
-			// This gives us a calculated path to a preview of asked dimensions
485
-			// thumbnailFolder/fileId/<maxX>-<maxY>(-max|-with-aspect).png
486
-			$preview = $this->buildCachePath($fileId, $previewWidth, $previewHeight);
487
-
488
-			// This checks if we have a preview of those exact dimensions in the cache
489
-			if ($this->thumbnailSizeExists($allThumbnails, basename($preview))) {
490
-				return $preview;
491
-			}
492
-
493
-			/**
494
-			 * Phase 4: We look for a larger preview, matching the aspect ratio
495
-			 */
496
-			if (($this->getMaxX() >= $maxPreviewWidth)
497
-				&& ($this->getMaxY() >= $maxPreviewHeight)
498
-			) {
499
-				// The preview we-re looking for is the exact size or larger than the max preview,
500
-				// so return that
501
-				return $this->buildCachePath($fileId, $maxPreviewWidth, $maxPreviewHeight);
502
-			} else {
503
-				// The last resort is to look for something bigger than what we've calculated,
504
-				// but still smaller than the max preview
505
-				return $this->isCachedBigger($fileId, $allThumbnails);
506
-			}
507
-		}
508
-
509
-		return false;
510
-	}
511
-
512
-	/**
513
-	 * Returns the dimensions of the max preview
514
-	 *
515
-	 * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
516
-	 *
517
-	 * @return int[]
518
-	 */
519
-	private function getMaxPreviewSize($allThumbnails) {
520
-		$maxPreviewX = null;
521
-		$maxPreviewY = null;
522
-
523
-		foreach ($allThumbnails as $thumbnail) {
524
-			$name = $thumbnail['name'];
525
-			if (strpos($name, 'max')) {
526
-				list($maxPreviewX, $maxPreviewY) = $this->getDimensionsFromFilename($name);
527
-				break;
528
-			}
529
-		}
530
-
531
-		return [$maxPreviewX, $maxPreviewY];
532
-	}
533
-
534
-	/**
535
-	 * Check if a specific thumbnail size is cached
536
-	 *
537
-	 * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
538
-	 * @param string $name
539
-	 * @return bool
540
-	 */
541
-	private function thumbnailSizeExists(array $allThumbnails, $name) {
542
-
543
-		foreach ($allThumbnails as $thumbnail) {
544
-			if ($name === $thumbnail->getName()) {
545
-				return true;
546
-			}
547
-		}
548
-
549
-		return false;
550
-	}
551
-
552
-	/**
553
-	 * Determines the size of the preview we should be looking for in the cache
554
-	 *
555
-	 * @return integer[]
556
-	 */
557
-	private function simulatePreviewDimensions() {
558
-		$askedWidth = $this->getMaxX();
559
-		$askedHeight = $this->getMaxY();
560
-
561
-		if ($this->keepAspect) {
562
-			list($newPreviewWidth, $newPreviewHeight) =
563
-				$this->applyAspectRatio($askedWidth, $askedHeight);
564
-		} else {
565
-			list($newPreviewWidth, $newPreviewHeight) = $this->fixSize($askedWidth, $askedHeight);
566
-		}
567
-
568
-		return [(int)$newPreviewWidth, (int)$newPreviewHeight];
569
-	}
570
-
571
-	/**
572
-	 * Resizes the boundaries to match the aspect ratio
573
-	 *
574
-	 * @param int $askedWidth
575
-	 * @param int $askedHeight
576
-	 *
577
-	 * @param int $originalWidth
578
-	 * @param int $originalHeight
579
-	 * @return integer[]
580
-	 */
581
-	private function applyAspectRatio($askedWidth, $askedHeight, $originalWidth = 0, $originalHeight = 0) {
582
-		if (!$originalWidth) {
583
-			$originalWidth = $this->maxPreviewWidth;
584
-		}
585
-		if (!$originalHeight) {
586
-			$originalHeight = $this->maxPreviewHeight;
587
-		}
588
-		$originalRatio = $originalWidth / $originalHeight;
589
-		// Defines the box in which the preview has to fit
590
-		$scaleFactor = $this->scalingUp ? $this->maxScaleFactor : 1;
591
-		$askedWidth = min($askedWidth, $originalWidth * $scaleFactor);
592
-		$askedHeight = min($askedHeight, $originalHeight * $scaleFactor);
593
-
594
-		if ($askedWidth / $originalRatio < $askedHeight) {
595
-			// width restricted
596
-			$askedHeight = round($askedWidth / $originalRatio);
597
-		} else {
598
-			$askedWidth = round($askedHeight * $originalRatio);
599
-		}
600
-
601
-		return [(int)$askedWidth, (int)$askedHeight];
602
-	}
603
-
604
-	/**
605
-	 * Resizes the boundaries to cover the area
606
-	 *
607
-	 * @param int $askedWidth
608
-	 * @param int $askedHeight
609
-	 * @param int $previewWidth
610
-	 * @param int $previewHeight
611
-	 * @return integer[]
612
-	 */
613
-	private function applyCover($askedWidth, $askedHeight, $previewWidth, $previewHeight) {
614
-		$originalRatio = $previewWidth / $previewHeight;
615
-		// Defines the box in which the preview has to fit
616
-		$scaleFactor = $this->scalingUp ? $this->maxScaleFactor : 1;
617
-		$askedWidth = min($askedWidth, $previewWidth * $scaleFactor);
618
-		$askedHeight = min($askedHeight, $previewHeight * $scaleFactor);
619
-
620
-		if ($askedWidth / $originalRatio > $askedHeight) {
621
-			// height restricted
622
-			$askedHeight = round($askedWidth / $originalRatio);
623
-		} else {
624
-			$askedWidth = round($askedHeight * $originalRatio);
625
-		}
626
-
627
-		return [(int)$askedWidth, (int)$askedHeight];
628
-	}
629
-
630
-	/**
631
-	 * Makes sure an upscaled preview doesn't end up larger than the max dimensions defined in the
632
-	 * config
633
-	 *
634
-	 * @param int $askedWidth
635
-	 * @param int $askedHeight
636
-	 *
637
-	 * @return integer[]
638
-	 */
639
-	private function fixSize($askedWidth, $askedHeight) {
640
-		if ($this->scalingUp) {
641
-			$askedWidth = min($this->configMaxWidth, $askedWidth);
642
-			$askedHeight = min($this->configMaxHeight, $askedHeight);
643
-		}
644
-
645
-		return [(int)$askedWidth, (int)$askedHeight];
646
-	}
647
-
648
-	/**
649
-	 * Checks if a bigger version of a file preview is cached and if not
650
-	 * return the preview of max allowed dimensions
651
-	 *
652
-	 * @param int $fileId fileId of the original image
653
-	 * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
654
-	 *
655
-	 * @return string path to bigger thumbnail
656
-	 */
657
-	private function isCachedBigger($fileId, $allThumbnails) {
658
-		// This is used to eliminate any thumbnail narrower than what we need
659
-		$maxX = $this->getMaxX();
660
-
661
-		//array for usable cached thumbnails
662
-		$possibleThumbnails = $this->getPossibleThumbnails($allThumbnails);
663
-
664
-		foreach ($possibleThumbnails as $width => $path) {
665
-			if ($width < $maxX) {
666
-				continue;
667
-			} else {
668
-				return $path;
669
-			}
670
-		}
671
-
672
-		// At this stage, we didn't find a preview, so we return the max preview
673
-		return $this->buildCachePath($fileId, $this->maxPreviewWidth, $this->maxPreviewHeight);
674
-	}
675
-
676
-	/**
677
-	 * Get possible bigger thumbnails of the given image with the proper aspect ratio
678
-	 *
679
-	 * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
680
-	 *
681
-	 * @return string[] an array of paths to bigger thumbnails
682
-	 */
683
-	private function getPossibleThumbnails($allThumbnails) {
684
-		if ($this->keepAspect) {
685
-			$wantedAspectRatio = (float)($this->maxPreviewWidth / $this->maxPreviewHeight);
686
-		} else {
687
-			$wantedAspectRatio = (float)($this->getMaxX() / $this->getMaxY());
688
-		}
689
-
690
-		//array for usable cached thumbnails
691
-		$possibleThumbnails = array();
692
-		foreach ($allThumbnails as $thumbnail) {
693
-			$name = rtrim($thumbnail['name'], '.png');
694
-			list($x, $y, $aspectRatio) = $this->getDimensionsFromFilename($name);
695
-			if (abs($aspectRatio - $wantedAspectRatio) >= 0.000001
696
-				|| $this->unscalable($x, $y)
697
-			) {
698
-				continue;
699
-			}
700
-			$possibleThumbnails[$x] = $thumbnail['path'];
701
-		}
702
-
703
-		ksort($possibleThumbnails);
704
-
705
-		return $possibleThumbnails;
706
-	}
707
-
708
-	/**
709
-	 * Looks at the preview filename from the cache and extracts the size of the preview
710
-	 *
711
-	 * @param string $name
712
-	 *
713
-	 * @return array<int,int,float>
714
-	 */
715
-	private function getDimensionsFromFilename($name) {
716
-		$size = explode('-', $name);
717
-		$x = (int)$size[0];
718
-		$y = (int)$size[1];
719
-		$aspectRatio = (float)($x / $y);
720
-
721
-		return array($x, $y, $aspectRatio);
722
-	}
723
-
724
-	/**
725
-	 * @param int $x
726
-	 * @param int $y
727
-	 *
728
-	 * @return bool
729
-	 */
730
-	private function unscalable($x, $y) {
731
-
732
-		$maxX = $this->getMaxX();
733
-		$maxY = $this->getMaxY();
734
-		$scalingUp = $this->getScalingUp();
735
-		$maxScaleFactor = $this->getMaxScaleFactor();
736
-
737
-		if ($x < $maxX || $y < $maxY) {
738
-			if ($scalingUp) {
739
-				$scaleFactor = $maxX / $x;
740
-				if ($scaleFactor > $maxScaleFactor) {
741
-					return true;
742
-				}
743
-			} else {
744
-				return true;
745
-			}
746
-		}
747
-
748
-		return false;
749
-	}
750
-
751
-	/**
752
-	 * Returns a preview of a file
753
-	 *
754
-	 * The cache is searched first and if nothing usable was found then a preview is
755
-	 * generated by one of the providers
756
-	 *
757
-	 * @return \OCP\IImage
758
-	 */
759
-	public function getPreview() {
760
-		if (!is_null($this->preview) && $this->preview->valid()) {
761
-			return $this->preview;
762
-		}
763
-
764
-		$this->preview = null;
765
-		$fileInfo = $this->getFileInfo();
766
-		if ($fileInfo === null || $fileInfo === false || !$fileInfo->isReadable()) {
767
-			return new \OC_Image();
768
-		}
769
-
770
-		$fileId = $fileInfo->getId();
771
-		$cached = $this->isCached($fileId);
772
-		if ($cached) {
773
-			$this->getCachedPreview($fileId, $cached);
774
-		}
775
-
776
-		if (is_null($this->preview)) {
777
-			$this->generatePreview($fileId);
778
-		}
779
-
780
-		// We still don't have a preview, so we send back an empty object
781
-		if (is_null($this->preview)) {
782
-			$this->preview = new \OC_Image();
783
-		}
784
-
785
-		return $this->preview;
786
-	}
787
-
788
-	/**
789
-	 * Sends the preview, including the headers to client which requested it
790
-	 *
791
-	 * @param null|string $mimeTypeForHeaders the media type to use when sending back the reply
792
-	 *
793
-	 * @throws NotFoundException
794
-	 * @throws PreviewNotAvailableException
795
-	 */
796
-	public function showPreview($mimeTypeForHeaders = null) {
797
-		// Check if file is valid
798
-		if ($this->isFileValid() === false) {
799
-			throw new NotFoundException('File not found.');
800
-		}
801
-
802
-		if (is_null($this->preview)) {
803
-			$this->getPreview();
804
-		}
805
-		if ($this->preview instanceof \OCP\IImage) {
806
-			if ($this->preview->valid()) {
807
-				\OCP\Response::enableCaching(3600 * 24); // 24 hours
808
-			} else {
809
-				$this->getMimeIcon();
810
-			}
811
-			$this->preview->show($mimeTypeForHeaders);
812
-		}
813
-	}
814
-
815
-	/**
816
-	 * Retrieves the preview from the cache and resizes it if necessary
817
-	 *
818
-	 * @param int $fileId fileId of the original image
819
-	 * @param string $cached the path to the cached preview
820
-	 */
821
-	private function getCachedPreview($fileId, $cached) {
822
-		$stream = $this->userView->fopen($cached, 'r');
823
-		$this->preview = null;
824
-		if ($stream) {
825
-			$image = new \OC_Image();
826
-			$image->loadFromFileHandle($stream);
827
-
828
-			$this->preview = $image->valid() ? $image : null;
829
-
830
-			if (!is_null($this->preview)) {
831
-				// Size of the preview we calculated
832
-				$maxX = $this->previewWidth;
833
-				$maxY = $this->previewHeight;
834
-				// Size of the preview we retrieved from the cache
835
-				$previewX = (int)$this->preview->width();
836
-				$previewY = (int)$this->preview->height();
837
-
838
-				// We don't have an exact match
839
-				if ($previewX !== $maxX || $previewY !== $maxY) {
840
-					$this->resizeAndStore($fileId);
841
-				}
842
-			}
843
-
844
-			fclose($stream);
845
-		}
846
-	}
847
-
848
-	/**
849
-	 * Resizes, crops, fixes orientation and stores in the cache
850
-	 *
851
-	 * @param int $fileId fileId of the original image
852
-	 */
853
-	private function resizeAndStore($fileId) {
854
-		$image = $this->preview;
855
-		if (!($image instanceof \OCP\IImage)) {
856
-			\OCP\Util::writeLog(
857
-				'core', '$this->preview is not an instance of \OCP\IImage', \OCP\Util::DEBUG
858
-			);
859
-
860
-			return;
861
-		}
862
-		$previewWidth = (int)$image->width();
863
-		$previewHeight = (int)$image->height();
864
-		$askedWidth = $this->getMaxX();
865
-		$askedHeight = $this->getMaxY();
866
-
867
-		if ($this->mode === self::MODE_COVER) {
868
-			list($askedWidth, $askedHeight) =
869
-				$this->applyCover($askedWidth, $askedHeight, $previewWidth, $previewHeight);
870
-		}
871
-
872
-		/**
873
-		 * Phase 1: If required, adjust boundaries to keep aspect ratio
874
-		 */
875
-		if ($this->keepAspect) {
876
-			list($askedWidth, $askedHeight) =
877
-				$this->applyAspectRatio($askedWidth, $askedHeight, $previewWidth, $previewHeight);
878
-		}
879
-
880
-		/**
881
-		 * Phase 2: Resizes preview to try and match requirements.
882
-		 * Takes the scaling ratio into consideration
883
-		 */
884
-		list($newPreviewWidth, $newPreviewHeight) = $this->scale(
885
-			$image, $askedWidth, $askedHeight, $previewWidth, $previewHeight
886
-		);
887
-
888
-		// The preview has been resized and should now have the asked dimensions
889
-		if ($newPreviewWidth === $askedWidth && $newPreviewHeight === $askedHeight) {
890
-			$this->storePreview($fileId, $newPreviewWidth, $newPreviewHeight);
891
-
892
-			return;
893
-		}
894
-
895
-		/**
896
-		 * Phase 3: We're still not there yet, so we're clipping and filling
897
-		 * to match the asked dimensions
898
-		 */
899
-		// It turns out the scaled preview is now too big, so we crop the image
900
-		if ($newPreviewWidth >= $askedWidth && $newPreviewHeight >= $askedHeight) {
901
-			$this->crop($image, $askedWidth, $askedHeight, $newPreviewWidth, $newPreviewHeight);
902
-			$this->storePreview($fileId, $askedWidth, $askedHeight);
903
-
904
-			return;
905
-		}
906
-
907
-		// At least one dimension of the scaled preview is too small,
908
-		// so we fill the space with a transparent background
909
-		if (($newPreviewWidth < $askedWidth || $newPreviewHeight < $askedHeight)) {
910
-			$this->cropAndFill(
911
-				$image, $askedWidth, $askedHeight, $newPreviewWidth, $newPreviewHeight
912
-			);
913
-			$this->storePreview($fileId, $askedWidth, $askedHeight);
914
-
915
-			return;
916
-		}
917
-
918
-		// The preview is smaller, but we can't touch it
919
-		$this->storePreview($fileId, $newPreviewWidth, $newPreviewHeight);
920
-	}
921
-
922
-	/**
923
-	 * Calculates the new dimensions of the preview
924
-	 *
925
-	 * The new dimensions can be larger or smaller than the ones of the preview we have to resize
926
-	 *
927
-	 * @param \OCP\IImage $image
928
-	 * @param int $askedWidth
929
-	 * @param int $askedHeight
930
-	 * @param int $previewWidth
931
-	 * @param int $previewHeight
932
-	 *
933
-	 * @return int[]
934
-	 */
935
-	private function scale($image, $askedWidth, $askedHeight, $previewWidth, $previewHeight) {
936
-		$scalingUp = $this->getScalingUp();
937
-		$maxScaleFactor = $this->getMaxScaleFactor();
938
-
939
-		$factorX = $askedWidth / $previewWidth;
940
-		$factorY = $askedHeight / $previewHeight;
941
-
942
-		if ($factorX >= $factorY) {
943
-			$factor = $factorX;
944
-		} else {
945
-			$factor = $factorY;
946
-		}
947
-
948
-		if ($scalingUp === false) {
949
-			if ($factor > 1) {
950
-				$factor = 1;
951
-			}
952
-		}
953
-
954
-		// We cap when upscaling
955
-		if (!is_null($maxScaleFactor)) {
956
-			if ($factor > $maxScaleFactor) {
957
-				\OCP\Util::writeLog(
958
-					'core', 'scale factor reduced from ' . $factor . ' to ' . $maxScaleFactor,
959
-					\OCP\Util::DEBUG
960
-				);
961
-				$factor = $maxScaleFactor;
962
-			}
963
-		}
964
-
965
-		$newPreviewWidth = round($previewWidth * $factor);
966
-		$newPreviewHeight = round($previewHeight * $factor);
967
-
968
-		$image->preciseResize($newPreviewWidth, $newPreviewHeight);
969
-		$this->preview = $image;
970
-
971
-		return [$newPreviewWidth, $newPreviewHeight];
972
-	}
973
-
974
-	/**
975
-	 * Crops a preview which is larger than the dimensions we've received
976
-	 *
977
-	 * @param \OCP\IImage $image
978
-	 * @param int $askedWidth
979
-	 * @param int $askedHeight
980
-	 * @param int $previewWidth
981
-	 * @param int $previewHeight
982
-	 */
983
-	private function crop($image, $askedWidth, $askedHeight, $previewWidth, $previewHeight = null) {
984
-		$cropX = floor(abs($askedWidth - $previewWidth) * 0.5);
985
-		//don't crop previews on the Y axis, this sucks if it's a document.
986
-		//$cropY = floor(abs($y - $newPreviewHeight) * 0.5);
987
-		$cropY = 0;
988
-		$image->crop($cropX, $cropY, $askedWidth, $askedHeight);
989
-		$this->preview = $image;
990
-	}
991
-
992
-	/**
993
-	 * Crops an image if it's larger than the dimensions we've received and fills the empty space
994
-	 * with a transparent background
995
-	 *
996
-	 * @param \OCP\IImage $image
997
-	 * @param int $askedWidth
998
-	 * @param int $askedHeight
999
-	 * @param int $previewWidth
1000
-	 * @param int $previewHeight
1001
-	 */
1002
-	private function cropAndFill($image, $askedWidth, $askedHeight, $previewWidth, $previewHeight) {
1003
-		if ($previewWidth > $askedWidth) {
1004
-			$cropX = floor(($previewWidth - $askedWidth) * 0.5);
1005
-			$image->crop($cropX, 0, $askedWidth, $previewHeight);
1006
-			$previewWidth = $askedWidth;
1007
-		}
1008
-
1009
-		if ($previewHeight > $askedHeight) {
1010
-			$cropY = floor(($previewHeight - $askedHeight) * 0.5);
1011
-			$image->crop(0, $cropY, $previewWidth, $askedHeight);
1012
-			$previewHeight = $askedHeight;
1013
-		}
1014
-
1015
-		// Creates a transparent background
1016
-		$backgroundLayer = imagecreatetruecolor($askedWidth, $askedHeight);
1017
-		imagealphablending($backgroundLayer, false);
1018
-		$transparency = imagecolorallocatealpha($backgroundLayer, 0, 0, 0, 127);
1019
-		imagefill($backgroundLayer, 0, 0, $transparency);
1020
-		imagesavealpha($backgroundLayer, true);
1021
-
1022
-		$image = $image->resource();
1023
-
1024
-		$mergeX = floor(abs($askedWidth - $previewWidth) * 0.5);
1025
-		$mergeY = floor(abs($askedHeight - $previewHeight) * 0.5);
1026
-
1027
-		// Pastes the preview on top of the background
1028
-		imagecopy(
1029
-			$backgroundLayer, $image, $mergeX, $mergeY, 0, 0, $previewWidth,
1030
-			$previewHeight
1031
-		);
1032
-
1033
-		$image = new \OC_Image($backgroundLayer);
1034
-
1035
-		$this->preview = $image;
1036
-	}
1037
-
1038
-	/**
1039
-	 * Saves a preview in the cache to speed up future calls
1040
-	 *
1041
-	 * Do not nullify the preview as it might send the whole process in a loop
1042
-	 *
1043
-	 * @param int $fileId fileId of the original image
1044
-	 * @param int $previewWidth
1045
-	 * @param int $previewHeight
1046
-	 */
1047
-	private function storePreview($fileId, $previewWidth, $previewHeight) {
1048
-		if (empty($previewWidth) || empty($previewHeight)) {
1049
-			\OCP\Util::writeLog(
1050
-				'core', 'Cannot save preview of dimension ' . $previewWidth . 'x' . $previewHeight,
1051
-				\OCP\Util::DEBUG
1052
-			);
1053
-
1054
-		} else {
1055
-			$cachePath = $this->buildCachePath($fileId, $previewWidth, $previewHeight);
1056
-			$this->userView->file_put_contents($cachePath, $this->preview->data());
1057
-		}
1058
-	}
1059
-
1060
-	/**
1061
-	 * Returns the path to a preview based on its dimensions and aspect
1062
-	 *
1063
-	 * @param int $fileId
1064
-	 * @param int|null $maxX
1065
-	 * @param int|null $maxY
1066
-	 *
1067
-	 * @return string
1068
-	 */
1069
-	private function buildCachePath($fileId, $maxX = null, $maxY = null) {
1070
-		if (is_null($maxX)) {
1071
-			$maxX = $this->getMaxX();
1072
-		}
1073
-		if (is_null($maxY)) {
1074
-			$maxY = $this->getMaxY();
1075
-		}
1076
-
1077
-		$previewPath = $this->getPreviewPath($fileId);
1078
-		$previewPath = $previewPath . strval($maxX) . '-' . strval($maxY);
1079
-		$isMaxPreview =
1080
-			($maxX === $this->maxPreviewWidth && $maxY === $this->maxPreviewHeight) ? true : false;
1081
-		if ($isMaxPreview) {
1082
-			$previewPath .= '-max';
1083
-		}
1084
-		if ($this->keepAspect && !$isMaxPreview) {
1085
-			$previewPath .= '-with-aspect';
1086
-		}
1087
-		if ($this->mode === self::MODE_COVER) {
1088
-			$previewPath .= '-cover';
1089
-		}
1090
-		$previewPath .= '.png';
1091
-
1092
-		return $previewPath;
1093
-	}
1094
-
1095
-	/**
1096
-	 * Returns the path to the folder where the previews are stored, identified by the fileId
1097
-	 *
1098
-	 * @param int $fileId
1099
-	 *
1100
-	 * @return string
1101
-	 */
1102
-	private function getPreviewPath($fileId) {
1103
-		return $this->getThumbnailsFolder() . '/' . $fileId . '/';
1104
-	}
1105
-
1106
-	/**
1107
-	 * Asks the provider to send a preview of the file which respects the maximum dimensions
1108
-	 * defined in the configuration and after saving it in the cache, it is then resized to the
1109
-	 * asked dimensions
1110
-	 *
1111
-	 * This is only called once in order to generate a large PNG of dimensions defined in the
1112
-	 * configuration file. We'll be able to quickly resize it later on.
1113
-	 * We never upscale the original conversion as this will be done later by the resizing
1114
-	 * operation
1115
-	 *
1116
-	 * @param int $fileId fileId of the original image
1117
-	 */
1118
-	private function generatePreview($fileId) {
1119
-		$file = $this->getFile();
1120
-		$preview = null;
1121
-
1122
-		$previewProviders = \OC::$server->getPreviewManager()
1123
-			->getProviders();
1124
-		foreach ($previewProviders as $supportedMimeType => $providers) {
1125
-			if (!preg_match($supportedMimeType, $this->mimeType)) {
1126
-				continue;
1127
-			}
1128
-
1129
-			foreach ($providers as $closure) {
1130
-				$provider = $closure();
1131
-				if (!($provider instanceof \OCP\Preview\IProvider)) {
1132
-					continue;
1133
-				}
1134
-
1135
-				\OCP\Util::writeLog(
1136
-					'core', 'Generating preview for "' . $file . '" with "' . get_class($provider)
1137
-					. '"', \OCP\Util::DEBUG
1138
-				);
1139
-
1140
-				/** @var $provider Provider */
1141
-				$preview = $provider->getThumbnail(
1142
-					$file, $this->configMaxWidth, $this->configMaxHeight, $scalingUp = false,
1143
-					$this->fileView
1144
-				);
1145
-
1146
-				if (!($preview instanceof \OCP\IImage)) {
1147
-					continue;
1148
-				}
1149
-
1150
-				$this->preview = $preview;
1151
-				$previewPath = $this->getPreviewPath($fileId);
1152
-
1153
-				if ($this->userView->is_dir($this->getThumbnailsFolder() . '/') === false) {
1154
-					$this->userView->mkdir($this->getThumbnailsFolder() . '/');
1155
-				}
1156
-
1157
-				if ($this->userView->is_dir($previewPath) === false) {
1158
-					$this->userView->mkdir($previewPath);
1159
-				}
1160
-
1161
-				// This stores our large preview so that it can be used in subsequent resizing requests
1162
-				$this->storeMaxPreview($previewPath);
1163
-
1164
-				break 2;
1165
-			}
1166
-		}
1167
-
1168
-		// The providers have been kind enough to give us a preview
1169
-		if ($preview) {
1170
-			$this->resizeAndStore($fileId);
1171
-		}
1172
-	}
1173
-
1174
-	/**
1175
-	 * Defines the media icon, for the media type of the original file, as the preview
1176
-	 * @throws PreviewNotAvailableException
1177
-	 */
1178
-	private function getMimeIcon() {
1179
-		$image = new \OC_Image();
1180
-		$mimeIconWebPath = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($this->mimeType);
1181
-		if (empty(\OC::$WEBROOT)) {
1182
-			$mimeIconServerPath = \OC::$SERVERROOT . $mimeIconWebPath;
1183
-		} else {
1184
-			$mimeIconServerPath = str_replace(\OC::$WEBROOT, \OC::$SERVERROOT, $mimeIconWebPath);
1185
-		}
1186
-		// we can't load SVGs into an image
1187
-		if (substr($mimeIconWebPath, -4) === '.svg') {
1188
-			throw new PreviewNotAvailableException('SVG mimetype cannot be rendered');
1189
-		}
1190
-		$image->loadFromFile($mimeIconServerPath);
1191
-
1192
-		$this->preview = $image;
1193
-	}
1194
-
1195
-	/**
1196
-	 * Stores the max preview in the cache
1197
-	 *
1198
-	 * @param string $previewPath path to the preview
1199
-	 */
1200
-	private function storeMaxPreview($previewPath) {
1201
-		$maxPreviewExists = false;
1202
-		$preview = $this->preview;
1203
-
1204
-		$allThumbnails = $this->userView->getDirectoryContent($previewPath);
1205
-		// This is so that the cache doesn't need emptying when upgrading
1206
-		// Can be replaced by an upgrade script...
1207
-		foreach ($allThumbnails as $thumbnail) {
1208
-			$name = rtrim($thumbnail['name'], '.png');
1209
-			if (strpos($name, 'max')) {
1210
-				$maxPreviewExists = true;
1211
-				break;
1212
-			}
1213
-		}
1214
-		// We haven't found the max preview, so we create it
1215
-		if (!$maxPreviewExists) {
1216
-			$previewWidth = $preview->width();
1217
-			$previewHeight = $preview->height();
1218
-			$previewPath = $previewPath . strval($previewWidth) . '-' . strval($previewHeight);
1219
-			$previewPath .= '-max.png';
1220
-			$this->userView->file_put_contents($previewPath, $preview->data());
1221
-			$this->maxPreviewWidth = $previewWidth;
1222
-			$this->maxPreviewHeight = $previewHeight;
1223
-		}
1224
-	}
1225
-
1226
-	/**
1227
-	 * Limits a dimension to the maximum dimension provided as argument
1228
-	 *
1229
-	 * @param int $dim
1230
-	 * @param int $maxDim
1231
-	 * @param string $dimName
1232
-	 *
1233
-	 * @return integer
1234
-	 */
1235
-	private function limitMaxDim($dim, $maxDim, $dimName) {
1236
-		if (!is_null($maxDim)) {
1237
-			if ($dim > $maxDim) {
1238
-				\OCP\Util::writeLog(
1239
-					'core', $dimName . ' reduced from ' . $dim . ' to ' . $maxDim, \OCP\Util::DEBUG
1240
-				);
1241
-				$dim = $maxDim;
1242
-			}
1243
-		}
1244
-
1245
-		return $dim;
1246
-	}
1247
-
1248
-	/**
1249
-	 * @param array $args
1250
-	 */
1251
-	public static function post_write($args) {
1252
-		self::post_delete($args, 'files/');
1253
-	}
1254
-
1255
-	/**
1256
-	 * @param array $args
1257
-	 */
1258
-	public static function prepare_delete_files($args) {
1259
-		self::prepare_delete($args, 'files/');
1260
-	}
1261
-
1262
-	/**
1263
-	 * @param array $args
1264
-	 * @param string $prefix
1265
-	 */
1266
-	public static function prepare_delete(array $args, $prefix = '') {
1267
-		$path = $args['path'];
1268
-		if (substr($path, 0, 1) === '/') {
1269
-			$path = substr($path, 1);
1270
-		}
1271
-
1272
-		$view = new \OC\Files\View('/' . \OC_User::getUser() . '/' . $prefix);
1273
-
1274
-		$absPath = Files\Filesystem::normalizePath($view->getAbsolutePath($path));
1275
-		$fileInfo = $view->getFileInfo($path);
1276
-		if ($fileInfo === false) {
1277
-			return;
1278
-		}
1279
-		self::addPathToDeleteFileMapper($absPath, $fileInfo);
1280
-		if ($view->is_dir($path)) {
1281
-			$children = self::getAllChildren($view, $path);
1282
-			self::$deleteChildrenMapper[$absPath] = $children;
1283
-		}
1284
-	}
1285
-
1286
-	/**
1287
-	 * @param string $absolutePath
1288
-	 * @param \OCP\Files\FileInfo $info
1289
-	 */
1290
-	private static function addPathToDeleteFileMapper($absolutePath, $info) {
1291
-		self::$deleteFileMapper[$absolutePath] = $info;
1292
-	}
1293
-
1294
-	/**
1295
-	 * @param \OC\Files\View $view
1296
-	 * @param string $path
1297
-	 *
1298
-	 * @return array
1299
-	 */
1300
-	private static function getAllChildren($view, $path) {
1301
-		$children = $view->getDirectoryContent($path);
1302
-		$childrensFiles = array();
1303
-
1304
-		$fakeRootLength = strlen($view->getRoot());
1305
-
1306
-		for ($i = 0; $i < count($children); $i++) {
1307
-			$child = $children[$i];
1308
-
1309
-			$childsPath = substr($child->getPath(), $fakeRootLength);
1310
-
1311
-			if ($view->is_dir($childsPath)) {
1312
-				$children = array_merge(
1313
-					$children,
1314
-					$view->getDirectoryContent($childsPath)
1315
-				);
1316
-			} else {
1317
-				$childrensFiles[] = $child;
1318
-			}
1319
-		}
1320
-
1321
-		return $childrensFiles;
1322
-	}
1323
-
1324
-	/**
1325
-	 * @param array $args
1326
-	 */
1327
-	public static function post_delete_files($args) {
1328
-		self::post_delete($args, 'files/');
1329
-	}
1330
-
1331
-	/**
1332
-	 * @param array $args
1333
-	 */
1334
-	public static function post_delete_versions($args) {
1335
-		self::post_delete($args, 'files/');
1336
-	}
1337
-
1338
-	/**
1339
-	 * @param array $args
1340
-	 * @param string $prefix
1341
-	 */
1342
-	public static function post_delete($args, $prefix = '') {
1343
-		$path = Files\Filesystem::normalizePath($args['path']);
1344
-
1345
-		$preview = new Preview(\OC_User::getUser(), $prefix, $path);
1346
-		$preview->deleteAllPreviews();
1347
-	}
40
+    //the thumbnail folder
41
+    const THUMBNAILS_FOLDER = 'thumbnails';
42
+
43
+    const MODE_FILL = 'fill';
44
+    const MODE_COVER = 'cover';
45
+
46
+    //config
47
+    private $maxScaleFactor;
48
+    /** @var int maximum width allowed for a preview */
49
+    private $configMaxWidth;
50
+    /** @var int maximum height allowed for a preview */
51
+    private $configMaxHeight;
52
+
53
+    //fileview object
54
+    private $fileView = null;
55
+    private $userView = null;
56
+
57
+    //vars
58
+    private $file;
59
+    private $maxX;
60
+    private $maxY;
61
+    private $scalingUp;
62
+    private $mimeType;
63
+    private $keepAspect = false;
64
+    private $mode = self::MODE_FILL;
65
+
66
+    //used to calculate the size of the preview to generate
67
+    /** @var int $maxPreviewWidth max width a preview can have */
68
+    private $maxPreviewWidth;
69
+    /** @var int $maxPreviewHeight max height a preview can have */
70
+    private $maxPreviewHeight;
71
+    /** @var int $previewWidth calculated width of the preview we're looking for */
72
+    private $previewWidth;
73
+    /** @var int $previewHeight calculated height of the preview we're looking for */
74
+    private $previewHeight;
75
+
76
+    //filemapper used for deleting previews
77
+    // index is path, value is fileinfo
78
+    static public $deleteFileMapper = array();
79
+    static public $deleteChildrenMapper = array();
80
+
81
+    /**
82
+     * preview images object
83
+     *
84
+     * @var \OCP\IImage
85
+     */
86
+    private $preview;
87
+
88
+    /**
89
+     * @var \OCP\Files\FileInfo
90
+     */
91
+    protected $info;
92
+
93
+    /**
94
+     * check if thumbnail or bigger version of thumbnail of file is cached
95
+     *
96
+     * @param string $user userid - if no user is given, OC_User::getUser will be used
97
+     * @param string $root path of root
98
+     * @param string $file The path to the file where you want a thumbnail from
99
+     * @param int $maxX The maximum X size of the thumbnail. It can be smaller depending on the
100
+     *     shape of the image
101
+     * @param int $maxY The maximum Y size of the thumbnail. It can be smaller depending on the
102
+     *     shape of the image
103
+     * @param bool $scalingUp Disable/Enable upscaling of previews
104
+     *
105
+     * @throws \Exception
106
+     * @return mixed (bool / string)
107
+     *                    false if thumbnail does not exist
108
+     *                    path to thumbnail if thumbnail exists
109
+     */
110
+    public function __construct(
111
+        $user = '',
112
+        $root = '/',
113
+        $file = '', $maxX = 1,
114
+        $maxY = 1,
115
+        $scalingUp = true
116
+    ) {
117
+        //init fileviews
118
+        if ($user === '') {
119
+            $user = \OC_User::getUser();
120
+        }
121
+        $this->fileView = new \OC\Files\View('/' . $user . '/' . $root);
122
+        $this->userView = new \OC\Files\View('/' . $user);
123
+
124
+        //set config
125
+        $sysConfig = \OC::$server->getConfig();
126
+        $this->configMaxWidth = $sysConfig->getSystemValue('preview_max_x', 2048);
127
+        $this->configMaxHeight = $sysConfig->getSystemValue('preview_max_y', 2048);
128
+        $this->maxScaleFactor = $sysConfig->getSystemValue('preview_max_scale_factor', 2);
129
+
130
+        //save parameters
131
+        $this->setFile($file);
132
+        $this->setMaxX((int)$maxX);
133
+        $this->setMaxY((int)$maxY);
134
+        $this->setScalingUp($scalingUp);
135
+
136
+        $this->preview = null;
137
+
138
+        //check if there are preview backends
139
+        if (!\OC::$server->getPreviewManager()
140
+                ->hasProviders()
141
+            && \OC::$server->getConfig()
142
+                ->getSystemValue('enable_previews', true)
143
+        ) {
144
+            \OCP\Util::writeLog('core', 'No preview providers exist', \OCP\Util::ERROR);
145
+            throw new \Exception('No preview providers');
146
+        }
147
+    }
148
+
149
+    /**
150
+     * returns the path of the file you want a thumbnail from
151
+     *
152
+     * @return string
153
+     */
154
+    public function getFile() {
155
+        return $this->file;
156
+    }
157
+
158
+    /**
159
+     * returns the max width of the preview
160
+     *
161
+     * @return integer
162
+     */
163
+    public function getMaxX() {
164
+        return $this->maxX;
165
+    }
166
+
167
+    /**
168
+     * returns the max height of the preview
169
+     *
170
+     * @return integer
171
+     */
172
+    public function getMaxY() {
173
+        return $this->maxY;
174
+    }
175
+
176
+    /**
177
+     * returns whether or not scalingup is enabled
178
+     *
179
+     * @return bool
180
+     */
181
+    public function getScalingUp() {
182
+        return $this->scalingUp;
183
+    }
184
+
185
+    /**
186
+     * returns the name of the thumbnailfolder
187
+     *
188
+     * @return string
189
+     */
190
+    public function getThumbnailsFolder() {
191
+        return self::THUMBNAILS_FOLDER;
192
+    }
193
+
194
+    /**
195
+     * returns the max scale factor
196
+     *
197
+     * @return string
198
+     */
199
+    public function getMaxScaleFactor() {
200
+        return $this->maxScaleFactor;
201
+    }
202
+
203
+    /**
204
+     * returns the max width set in ownCloud's config
205
+     *
206
+     * @return integer
207
+     */
208
+    public function getConfigMaxX() {
209
+        return $this->configMaxWidth;
210
+    }
211
+
212
+    /**
213
+     * returns the max height set in ownCloud's config
214
+     *
215
+     * @return integer
216
+     */
217
+    public function getConfigMaxY() {
218
+        return $this->configMaxHeight;
219
+    }
220
+
221
+    /**
222
+     * Returns the FileInfo object associated with the file to preview
223
+     *
224
+     * @return false|Files\FileInfo|\OCP\Files\FileInfo
225
+     */
226
+    protected function getFileInfo() {
227
+        $absPath = $this->fileView->getAbsolutePath($this->file);
228
+        $absPath = Files\Filesystem::normalizePath($absPath);
229
+        if (array_key_exists($absPath, self::$deleteFileMapper)) {
230
+            $this->info = self::$deleteFileMapper[$absPath];
231
+        } else if (!$this->info) {
232
+            $this->info = $this->fileView->getFileInfo($this->file);
233
+        }
234
+
235
+        return $this->info;
236
+    }
237
+
238
+
239
+    /**
240
+     * @return array|null
241
+     */
242
+    private function getChildren() {
243
+        $absPath = $this->fileView->getAbsolutePath($this->file);
244
+        $absPath = Files\Filesystem::normalizePath($absPath);
245
+
246
+        if (array_key_exists($absPath, self::$deleteChildrenMapper)) {
247
+            return self::$deleteChildrenMapper[$absPath];
248
+        }
249
+
250
+        return null;
251
+    }
252
+
253
+    /**
254
+     * Sets the path of the file you want a preview of
255
+     *
256
+     * @param string $file
257
+     * @param \OCP\Files\FileInfo|null $info
258
+     *
259
+     * @return \OC\Preview
260
+     */
261
+    public function setFile($file, $info = null) {
262
+        $this->file = $file;
263
+        $this->info = $info;
264
+
265
+        if ($file !== '') {
266
+            $this->getFileInfo();
267
+            if ($this->info instanceof \OCP\Files\FileInfo) {
268
+                $this->mimeType = $this->info->getMimetype();
269
+            }
270
+        }
271
+
272
+        return $this;
273
+    }
274
+
275
+    /**
276
+     * Forces the use of a specific media type
277
+     *
278
+     * @param string $mimeType
279
+     */
280
+    public function setMimetype($mimeType) {
281
+        $this->mimeType = $mimeType;
282
+    }
283
+
284
+    /**
285
+     * Sets the max width of the preview. It's capped by the maximum allowed size set in the
286
+     * configuration
287
+     *
288
+     * @param int $maxX
289
+     *
290
+     * @throws \Exception
291
+     * @return \OC\Preview
292
+     */
293
+    public function setMaxX($maxX = 1) {
294
+        if ($maxX <= 0) {
295
+            throw new \Exception('Cannot set width of 0 or smaller!');
296
+        }
297
+        $configMaxX = $this->getConfigMaxX();
298
+        $maxX = $this->limitMaxDim($maxX, $configMaxX, 'maxX');
299
+        $this->maxX = $maxX;
300
+
301
+        return $this;
302
+    }
303
+
304
+    /**
305
+     * Sets the max height of the preview. It's capped by the maximum allowed size set in the
306
+     * configuration
307
+     *
308
+     * @param int $maxY
309
+     *
310
+     * @throws \Exception
311
+     * @return \OC\Preview
312
+     */
313
+    public function setMaxY($maxY = 1) {
314
+        if ($maxY <= 0) {
315
+            throw new \Exception('Cannot set height of 0 or smaller!');
316
+        }
317
+        $configMaxY = $this->getConfigMaxY();
318
+        $maxY = $this->limitMaxDim($maxY, $configMaxY, 'maxY');
319
+        $this->maxY = $maxY;
320
+
321
+        return $this;
322
+    }
323
+
324
+    /**
325
+     * Sets whether we're allowed to scale up when generating a preview. It's capped by the maximum
326
+     * allowed scale factor set in the configuration
327
+     *
328
+     * @param bool $scalingUp
329
+     *
330
+     * @return \OC\Preview
331
+     */
332
+    public function setScalingup($scalingUp) {
333
+        if ($this->getMaxScaleFactor() === 1) {
334
+            $scalingUp = false;
335
+        }
336
+        $this->scalingUp = $scalingUp;
337
+
338
+        return $this;
339
+    }
340
+
341
+    /**
342
+     * Set whether to cover or fill the specified dimensions
343
+     *
344
+     * @param string $mode
345
+     *
346
+     * @return \OC\Preview
347
+     */
348
+    public function setMode($mode) {
349
+        $this->mode = $mode;
350
+
351
+        return $this;
352
+    }
353
+
354
+    /**
355
+     * Sets whether we need to generate a preview which keeps the aspect ratio of the original file
356
+     *
357
+     * @param bool $keepAspect
358
+     *
359
+     * @return \OC\Preview
360
+     */
361
+    public function setKeepAspect($keepAspect) {
362
+        $this->keepAspect = $keepAspect;
363
+
364
+        return $this;
365
+    }
366
+
367
+    /**
368
+     * Makes sure we were given a file to preview and that it exists in the filesystem
369
+     *
370
+     * @return bool
371
+     */
372
+    public function isFileValid() {
373
+        $file = $this->getFile();
374
+        if ($file === '') {
375
+            \OCP\Util::writeLog('core', 'No filename passed', \OCP\Util::DEBUG);
376
+
377
+            return false;
378
+        }
379
+
380
+        if (!$this->getFileInfo() instanceof FileInfo) {
381
+            \OCP\Util::writeLog('core', 'File:"' . $file . '" not found', \OCP\Util::DEBUG);
382
+
383
+            return false;
384
+        }
385
+
386
+        return true;
387
+    }
388
+
389
+    /**
390
+     * Deletes the preview of a file with specific width and height
391
+     *
392
+     * This should never delete the max preview, use deleteAllPreviews() instead
393
+     *
394
+     * @return bool
395
+     */
396
+    public function deletePreview() {
397
+        $fileInfo = $this->getFileInfo();
398
+        if ($fileInfo !== null && $fileInfo !== false) {
399
+            $fileId = $fileInfo->getId();
400
+
401
+            $previewPath = $this->buildCachePath($fileId);
402
+            if (!strpos($previewPath, 'max')) {
403
+                return $this->userView->unlink($previewPath);
404
+            }
405
+        }
406
+
407
+        return false;
408
+    }
409
+
410
+    /**
411
+     * Deletes all previews of a file
412
+     */
413
+    public function deleteAllPreviews() {
414
+        $thumbnailMount = $this->userView->getMount($this->getThumbnailsFolder());
415
+        $propagator = $thumbnailMount->getStorage()->getPropagator();
416
+        $propagator->beginBatch();
417
+
418
+        $toDelete = $this->getChildren();
419
+        $toDelete[] = $this->getFileInfo();
420
+
421
+        foreach ($toDelete as $delete) {
422
+            if ($delete instanceof FileInfo) {
423
+                /** @var \OCP\Files\FileInfo $delete */
424
+                $fileId = $delete->getId();
425
+
426
+                // getId() might return null, e.g. when the file is a
427
+                // .ocTransferId*.part file from chunked file upload.
428
+                if (!empty($fileId)) {
429
+                    $previewPath = $this->getPreviewPath($fileId);
430
+                    $this->userView->rmdir($previewPath);
431
+                }
432
+            }
433
+        }
434
+
435
+        $propagator->commitBatch();
436
+    }
437
+
438
+    /**
439
+     * Checks if a preview matching the asked dimensions or a bigger version is already cached
440
+     *
441
+     *    * We first retrieve the size of the max preview since this is what we be used to create
442
+     * all our preview. If it doesn't exist we return false, so that it can be generated
443
+     *    * Using the dimensions of the max preview, we calculate what the size of the new
444
+     * thumbnail should be
445
+     *    * And finally, we look for a suitable candidate in the cache
446
+     *
447
+     * @param int $fileId fileId of the original file we need a preview of
448
+     *
449
+     * @return string|false path to the cached preview if it exists or false
450
+     */
451
+    public function isCached($fileId) {
452
+        if (is_null($fileId)) {
453
+            return false;
454
+        }
455
+
456
+        /**
457
+         * Phase 1: Looking for the max preview
458
+         */
459
+        $previewPath = $this->getPreviewPath($fileId);
460
+        // We currently can't look for a single file due to bugs related to #16478
461
+        $allThumbnails = $this->userView->getDirectoryContent($previewPath);
462
+        list($maxPreviewWidth, $maxPreviewHeight) = $this->getMaxPreviewSize($allThumbnails);
463
+
464
+        // Only use the cache if we have a max preview
465
+        if (!is_null($maxPreviewWidth) && !is_null($maxPreviewHeight)) {
466
+
467
+            /**
468
+             * Phase 2: Calculating the size of the preview we need to send back
469
+             */
470
+            $this->maxPreviewWidth = $maxPreviewWidth;
471
+            $this->maxPreviewHeight = $maxPreviewHeight;
472
+
473
+            list($previewWidth, $previewHeight) = $this->simulatePreviewDimensions();
474
+            if (empty($previewWidth) || empty($previewHeight)) {
475
+                return false;
476
+            }
477
+
478
+            $this->previewWidth = $previewWidth;
479
+            $this->previewHeight = $previewHeight;
480
+
481
+            /**
482
+             * Phase 3: We look for a preview of the exact size
483
+             */
484
+            // This gives us a calculated path to a preview of asked dimensions
485
+            // thumbnailFolder/fileId/<maxX>-<maxY>(-max|-with-aspect).png
486
+            $preview = $this->buildCachePath($fileId, $previewWidth, $previewHeight);
487
+
488
+            // This checks if we have a preview of those exact dimensions in the cache
489
+            if ($this->thumbnailSizeExists($allThumbnails, basename($preview))) {
490
+                return $preview;
491
+            }
492
+
493
+            /**
494
+             * Phase 4: We look for a larger preview, matching the aspect ratio
495
+             */
496
+            if (($this->getMaxX() >= $maxPreviewWidth)
497
+                && ($this->getMaxY() >= $maxPreviewHeight)
498
+            ) {
499
+                // The preview we-re looking for is the exact size or larger than the max preview,
500
+                // so return that
501
+                return $this->buildCachePath($fileId, $maxPreviewWidth, $maxPreviewHeight);
502
+            } else {
503
+                // The last resort is to look for something bigger than what we've calculated,
504
+                // but still smaller than the max preview
505
+                return $this->isCachedBigger($fileId, $allThumbnails);
506
+            }
507
+        }
508
+
509
+        return false;
510
+    }
511
+
512
+    /**
513
+     * Returns the dimensions of the max preview
514
+     *
515
+     * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
516
+     *
517
+     * @return int[]
518
+     */
519
+    private function getMaxPreviewSize($allThumbnails) {
520
+        $maxPreviewX = null;
521
+        $maxPreviewY = null;
522
+
523
+        foreach ($allThumbnails as $thumbnail) {
524
+            $name = $thumbnail['name'];
525
+            if (strpos($name, 'max')) {
526
+                list($maxPreviewX, $maxPreviewY) = $this->getDimensionsFromFilename($name);
527
+                break;
528
+            }
529
+        }
530
+
531
+        return [$maxPreviewX, $maxPreviewY];
532
+    }
533
+
534
+    /**
535
+     * Check if a specific thumbnail size is cached
536
+     *
537
+     * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
538
+     * @param string $name
539
+     * @return bool
540
+     */
541
+    private function thumbnailSizeExists(array $allThumbnails, $name) {
542
+
543
+        foreach ($allThumbnails as $thumbnail) {
544
+            if ($name === $thumbnail->getName()) {
545
+                return true;
546
+            }
547
+        }
548
+
549
+        return false;
550
+    }
551
+
552
+    /**
553
+     * Determines the size of the preview we should be looking for in the cache
554
+     *
555
+     * @return integer[]
556
+     */
557
+    private function simulatePreviewDimensions() {
558
+        $askedWidth = $this->getMaxX();
559
+        $askedHeight = $this->getMaxY();
560
+
561
+        if ($this->keepAspect) {
562
+            list($newPreviewWidth, $newPreviewHeight) =
563
+                $this->applyAspectRatio($askedWidth, $askedHeight);
564
+        } else {
565
+            list($newPreviewWidth, $newPreviewHeight) = $this->fixSize($askedWidth, $askedHeight);
566
+        }
567
+
568
+        return [(int)$newPreviewWidth, (int)$newPreviewHeight];
569
+    }
570
+
571
+    /**
572
+     * Resizes the boundaries to match the aspect ratio
573
+     *
574
+     * @param int $askedWidth
575
+     * @param int $askedHeight
576
+     *
577
+     * @param int $originalWidth
578
+     * @param int $originalHeight
579
+     * @return integer[]
580
+     */
581
+    private function applyAspectRatio($askedWidth, $askedHeight, $originalWidth = 0, $originalHeight = 0) {
582
+        if (!$originalWidth) {
583
+            $originalWidth = $this->maxPreviewWidth;
584
+        }
585
+        if (!$originalHeight) {
586
+            $originalHeight = $this->maxPreviewHeight;
587
+        }
588
+        $originalRatio = $originalWidth / $originalHeight;
589
+        // Defines the box in which the preview has to fit
590
+        $scaleFactor = $this->scalingUp ? $this->maxScaleFactor : 1;
591
+        $askedWidth = min($askedWidth, $originalWidth * $scaleFactor);
592
+        $askedHeight = min($askedHeight, $originalHeight * $scaleFactor);
593
+
594
+        if ($askedWidth / $originalRatio < $askedHeight) {
595
+            // width restricted
596
+            $askedHeight = round($askedWidth / $originalRatio);
597
+        } else {
598
+            $askedWidth = round($askedHeight * $originalRatio);
599
+        }
600
+
601
+        return [(int)$askedWidth, (int)$askedHeight];
602
+    }
603
+
604
+    /**
605
+     * Resizes the boundaries to cover the area
606
+     *
607
+     * @param int $askedWidth
608
+     * @param int $askedHeight
609
+     * @param int $previewWidth
610
+     * @param int $previewHeight
611
+     * @return integer[]
612
+     */
613
+    private function applyCover($askedWidth, $askedHeight, $previewWidth, $previewHeight) {
614
+        $originalRatio = $previewWidth / $previewHeight;
615
+        // Defines the box in which the preview has to fit
616
+        $scaleFactor = $this->scalingUp ? $this->maxScaleFactor : 1;
617
+        $askedWidth = min($askedWidth, $previewWidth * $scaleFactor);
618
+        $askedHeight = min($askedHeight, $previewHeight * $scaleFactor);
619
+
620
+        if ($askedWidth / $originalRatio > $askedHeight) {
621
+            // height restricted
622
+            $askedHeight = round($askedWidth / $originalRatio);
623
+        } else {
624
+            $askedWidth = round($askedHeight * $originalRatio);
625
+        }
626
+
627
+        return [(int)$askedWidth, (int)$askedHeight];
628
+    }
629
+
630
+    /**
631
+     * Makes sure an upscaled preview doesn't end up larger than the max dimensions defined in the
632
+     * config
633
+     *
634
+     * @param int $askedWidth
635
+     * @param int $askedHeight
636
+     *
637
+     * @return integer[]
638
+     */
639
+    private function fixSize($askedWidth, $askedHeight) {
640
+        if ($this->scalingUp) {
641
+            $askedWidth = min($this->configMaxWidth, $askedWidth);
642
+            $askedHeight = min($this->configMaxHeight, $askedHeight);
643
+        }
644
+
645
+        return [(int)$askedWidth, (int)$askedHeight];
646
+    }
647
+
648
+    /**
649
+     * Checks if a bigger version of a file preview is cached and if not
650
+     * return the preview of max allowed dimensions
651
+     *
652
+     * @param int $fileId fileId of the original image
653
+     * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
654
+     *
655
+     * @return string path to bigger thumbnail
656
+     */
657
+    private function isCachedBigger($fileId, $allThumbnails) {
658
+        // This is used to eliminate any thumbnail narrower than what we need
659
+        $maxX = $this->getMaxX();
660
+
661
+        //array for usable cached thumbnails
662
+        $possibleThumbnails = $this->getPossibleThumbnails($allThumbnails);
663
+
664
+        foreach ($possibleThumbnails as $width => $path) {
665
+            if ($width < $maxX) {
666
+                continue;
667
+            } else {
668
+                return $path;
669
+            }
670
+        }
671
+
672
+        // At this stage, we didn't find a preview, so we return the max preview
673
+        return $this->buildCachePath($fileId, $this->maxPreviewWidth, $this->maxPreviewHeight);
674
+    }
675
+
676
+    /**
677
+     * Get possible bigger thumbnails of the given image with the proper aspect ratio
678
+     *
679
+     * @param FileInfo[] $allThumbnails the list of all our cached thumbnails
680
+     *
681
+     * @return string[] an array of paths to bigger thumbnails
682
+     */
683
+    private function getPossibleThumbnails($allThumbnails) {
684
+        if ($this->keepAspect) {
685
+            $wantedAspectRatio = (float)($this->maxPreviewWidth / $this->maxPreviewHeight);
686
+        } else {
687
+            $wantedAspectRatio = (float)($this->getMaxX() / $this->getMaxY());
688
+        }
689
+
690
+        //array for usable cached thumbnails
691
+        $possibleThumbnails = array();
692
+        foreach ($allThumbnails as $thumbnail) {
693
+            $name = rtrim($thumbnail['name'], '.png');
694
+            list($x, $y, $aspectRatio) = $this->getDimensionsFromFilename($name);
695
+            if (abs($aspectRatio - $wantedAspectRatio) >= 0.000001
696
+                || $this->unscalable($x, $y)
697
+            ) {
698
+                continue;
699
+            }
700
+            $possibleThumbnails[$x] = $thumbnail['path'];
701
+        }
702
+
703
+        ksort($possibleThumbnails);
704
+
705
+        return $possibleThumbnails;
706
+    }
707
+
708
+    /**
709
+     * Looks at the preview filename from the cache and extracts the size of the preview
710
+     *
711
+     * @param string $name
712
+     *
713
+     * @return array<int,int,float>
714
+     */
715
+    private function getDimensionsFromFilename($name) {
716
+        $size = explode('-', $name);
717
+        $x = (int)$size[0];
718
+        $y = (int)$size[1];
719
+        $aspectRatio = (float)($x / $y);
720
+
721
+        return array($x, $y, $aspectRatio);
722
+    }
723
+
724
+    /**
725
+     * @param int $x
726
+     * @param int $y
727
+     *
728
+     * @return bool
729
+     */
730
+    private function unscalable($x, $y) {
731
+
732
+        $maxX = $this->getMaxX();
733
+        $maxY = $this->getMaxY();
734
+        $scalingUp = $this->getScalingUp();
735
+        $maxScaleFactor = $this->getMaxScaleFactor();
736
+
737
+        if ($x < $maxX || $y < $maxY) {
738
+            if ($scalingUp) {
739
+                $scaleFactor = $maxX / $x;
740
+                if ($scaleFactor > $maxScaleFactor) {
741
+                    return true;
742
+                }
743
+            } else {
744
+                return true;
745
+            }
746
+        }
747
+
748
+        return false;
749
+    }
750
+
751
+    /**
752
+     * Returns a preview of a file
753
+     *
754
+     * The cache is searched first and if nothing usable was found then a preview is
755
+     * generated by one of the providers
756
+     *
757
+     * @return \OCP\IImage
758
+     */
759
+    public function getPreview() {
760
+        if (!is_null($this->preview) && $this->preview->valid()) {
761
+            return $this->preview;
762
+        }
763
+
764
+        $this->preview = null;
765
+        $fileInfo = $this->getFileInfo();
766
+        if ($fileInfo === null || $fileInfo === false || !$fileInfo->isReadable()) {
767
+            return new \OC_Image();
768
+        }
769
+
770
+        $fileId = $fileInfo->getId();
771
+        $cached = $this->isCached($fileId);
772
+        if ($cached) {
773
+            $this->getCachedPreview($fileId, $cached);
774
+        }
775
+
776
+        if (is_null($this->preview)) {
777
+            $this->generatePreview($fileId);
778
+        }
779
+
780
+        // We still don't have a preview, so we send back an empty object
781
+        if (is_null($this->preview)) {
782
+            $this->preview = new \OC_Image();
783
+        }
784
+
785
+        return $this->preview;
786
+    }
787
+
788
+    /**
789
+     * Sends the preview, including the headers to client which requested it
790
+     *
791
+     * @param null|string $mimeTypeForHeaders the media type to use when sending back the reply
792
+     *
793
+     * @throws NotFoundException
794
+     * @throws PreviewNotAvailableException
795
+     */
796
+    public function showPreview($mimeTypeForHeaders = null) {
797
+        // Check if file is valid
798
+        if ($this->isFileValid() === false) {
799
+            throw new NotFoundException('File not found.');
800
+        }
801
+
802
+        if (is_null($this->preview)) {
803
+            $this->getPreview();
804
+        }
805
+        if ($this->preview instanceof \OCP\IImage) {
806
+            if ($this->preview->valid()) {
807
+                \OCP\Response::enableCaching(3600 * 24); // 24 hours
808
+            } else {
809
+                $this->getMimeIcon();
810
+            }
811
+            $this->preview->show($mimeTypeForHeaders);
812
+        }
813
+    }
814
+
815
+    /**
816
+     * Retrieves the preview from the cache and resizes it if necessary
817
+     *
818
+     * @param int $fileId fileId of the original image
819
+     * @param string $cached the path to the cached preview
820
+     */
821
+    private function getCachedPreview($fileId, $cached) {
822
+        $stream = $this->userView->fopen($cached, 'r');
823
+        $this->preview = null;
824
+        if ($stream) {
825
+            $image = new \OC_Image();
826
+            $image->loadFromFileHandle($stream);
827
+
828
+            $this->preview = $image->valid() ? $image : null;
829
+
830
+            if (!is_null($this->preview)) {
831
+                // Size of the preview we calculated
832
+                $maxX = $this->previewWidth;
833
+                $maxY = $this->previewHeight;
834
+                // Size of the preview we retrieved from the cache
835
+                $previewX = (int)$this->preview->width();
836
+                $previewY = (int)$this->preview->height();
837
+
838
+                // We don't have an exact match
839
+                if ($previewX !== $maxX || $previewY !== $maxY) {
840
+                    $this->resizeAndStore($fileId);
841
+                }
842
+            }
843
+
844
+            fclose($stream);
845
+        }
846
+    }
847
+
848
+    /**
849
+     * Resizes, crops, fixes orientation and stores in the cache
850
+     *
851
+     * @param int $fileId fileId of the original image
852
+     */
853
+    private function resizeAndStore($fileId) {
854
+        $image = $this->preview;
855
+        if (!($image instanceof \OCP\IImage)) {
856
+            \OCP\Util::writeLog(
857
+                'core', '$this->preview is not an instance of \OCP\IImage', \OCP\Util::DEBUG
858
+            );
859
+
860
+            return;
861
+        }
862
+        $previewWidth = (int)$image->width();
863
+        $previewHeight = (int)$image->height();
864
+        $askedWidth = $this->getMaxX();
865
+        $askedHeight = $this->getMaxY();
866
+
867
+        if ($this->mode === self::MODE_COVER) {
868
+            list($askedWidth, $askedHeight) =
869
+                $this->applyCover($askedWidth, $askedHeight, $previewWidth, $previewHeight);
870
+        }
871
+
872
+        /**
873
+         * Phase 1: If required, adjust boundaries to keep aspect ratio
874
+         */
875
+        if ($this->keepAspect) {
876
+            list($askedWidth, $askedHeight) =
877
+                $this->applyAspectRatio($askedWidth, $askedHeight, $previewWidth, $previewHeight);
878
+        }
879
+
880
+        /**
881
+         * Phase 2: Resizes preview to try and match requirements.
882
+         * Takes the scaling ratio into consideration
883
+         */
884
+        list($newPreviewWidth, $newPreviewHeight) = $this->scale(
885
+            $image, $askedWidth, $askedHeight, $previewWidth, $previewHeight
886
+        );
887
+
888
+        // The preview has been resized and should now have the asked dimensions
889
+        if ($newPreviewWidth === $askedWidth && $newPreviewHeight === $askedHeight) {
890
+            $this->storePreview($fileId, $newPreviewWidth, $newPreviewHeight);
891
+
892
+            return;
893
+        }
894
+
895
+        /**
896
+         * Phase 3: We're still not there yet, so we're clipping and filling
897
+         * to match the asked dimensions
898
+         */
899
+        // It turns out the scaled preview is now too big, so we crop the image
900
+        if ($newPreviewWidth >= $askedWidth && $newPreviewHeight >= $askedHeight) {
901
+            $this->crop($image, $askedWidth, $askedHeight, $newPreviewWidth, $newPreviewHeight);
902
+            $this->storePreview($fileId, $askedWidth, $askedHeight);
903
+
904
+            return;
905
+        }
906
+
907
+        // At least one dimension of the scaled preview is too small,
908
+        // so we fill the space with a transparent background
909
+        if (($newPreviewWidth < $askedWidth || $newPreviewHeight < $askedHeight)) {
910
+            $this->cropAndFill(
911
+                $image, $askedWidth, $askedHeight, $newPreviewWidth, $newPreviewHeight
912
+            );
913
+            $this->storePreview($fileId, $askedWidth, $askedHeight);
914
+
915
+            return;
916
+        }
917
+
918
+        // The preview is smaller, but we can't touch it
919
+        $this->storePreview($fileId, $newPreviewWidth, $newPreviewHeight);
920
+    }
921
+
922
+    /**
923
+     * Calculates the new dimensions of the preview
924
+     *
925
+     * The new dimensions can be larger or smaller than the ones of the preview we have to resize
926
+     *
927
+     * @param \OCP\IImage $image
928
+     * @param int $askedWidth
929
+     * @param int $askedHeight
930
+     * @param int $previewWidth
931
+     * @param int $previewHeight
932
+     *
933
+     * @return int[]
934
+     */
935
+    private function scale($image, $askedWidth, $askedHeight, $previewWidth, $previewHeight) {
936
+        $scalingUp = $this->getScalingUp();
937
+        $maxScaleFactor = $this->getMaxScaleFactor();
938
+
939
+        $factorX = $askedWidth / $previewWidth;
940
+        $factorY = $askedHeight / $previewHeight;
941
+
942
+        if ($factorX >= $factorY) {
943
+            $factor = $factorX;
944
+        } else {
945
+            $factor = $factorY;
946
+        }
947
+
948
+        if ($scalingUp === false) {
949
+            if ($factor > 1) {
950
+                $factor = 1;
951
+            }
952
+        }
953
+
954
+        // We cap when upscaling
955
+        if (!is_null($maxScaleFactor)) {
956
+            if ($factor > $maxScaleFactor) {
957
+                \OCP\Util::writeLog(
958
+                    'core', 'scale factor reduced from ' . $factor . ' to ' . $maxScaleFactor,
959
+                    \OCP\Util::DEBUG
960
+                );
961
+                $factor = $maxScaleFactor;
962
+            }
963
+        }
964
+
965
+        $newPreviewWidth = round($previewWidth * $factor);
966
+        $newPreviewHeight = round($previewHeight * $factor);
967
+
968
+        $image->preciseResize($newPreviewWidth, $newPreviewHeight);
969
+        $this->preview = $image;
970
+
971
+        return [$newPreviewWidth, $newPreviewHeight];
972
+    }
973
+
974
+    /**
975
+     * Crops a preview which is larger than the dimensions we've received
976
+     *
977
+     * @param \OCP\IImage $image
978
+     * @param int $askedWidth
979
+     * @param int $askedHeight
980
+     * @param int $previewWidth
981
+     * @param int $previewHeight
982
+     */
983
+    private function crop($image, $askedWidth, $askedHeight, $previewWidth, $previewHeight = null) {
984
+        $cropX = floor(abs($askedWidth - $previewWidth) * 0.5);
985
+        //don't crop previews on the Y axis, this sucks if it's a document.
986
+        //$cropY = floor(abs($y - $newPreviewHeight) * 0.5);
987
+        $cropY = 0;
988
+        $image->crop($cropX, $cropY, $askedWidth, $askedHeight);
989
+        $this->preview = $image;
990
+    }
991
+
992
+    /**
993
+     * Crops an image if it's larger than the dimensions we've received and fills the empty space
994
+     * with a transparent background
995
+     *
996
+     * @param \OCP\IImage $image
997
+     * @param int $askedWidth
998
+     * @param int $askedHeight
999
+     * @param int $previewWidth
1000
+     * @param int $previewHeight
1001
+     */
1002
+    private function cropAndFill($image, $askedWidth, $askedHeight, $previewWidth, $previewHeight) {
1003
+        if ($previewWidth > $askedWidth) {
1004
+            $cropX = floor(($previewWidth - $askedWidth) * 0.5);
1005
+            $image->crop($cropX, 0, $askedWidth, $previewHeight);
1006
+            $previewWidth = $askedWidth;
1007
+        }
1008
+
1009
+        if ($previewHeight > $askedHeight) {
1010
+            $cropY = floor(($previewHeight - $askedHeight) * 0.5);
1011
+            $image->crop(0, $cropY, $previewWidth, $askedHeight);
1012
+            $previewHeight = $askedHeight;
1013
+        }
1014
+
1015
+        // Creates a transparent background
1016
+        $backgroundLayer = imagecreatetruecolor($askedWidth, $askedHeight);
1017
+        imagealphablending($backgroundLayer, false);
1018
+        $transparency = imagecolorallocatealpha($backgroundLayer, 0, 0, 0, 127);
1019
+        imagefill($backgroundLayer, 0, 0, $transparency);
1020
+        imagesavealpha($backgroundLayer, true);
1021
+
1022
+        $image = $image->resource();
1023
+
1024
+        $mergeX = floor(abs($askedWidth - $previewWidth) * 0.5);
1025
+        $mergeY = floor(abs($askedHeight - $previewHeight) * 0.5);
1026
+
1027
+        // Pastes the preview on top of the background
1028
+        imagecopy(
1029
+            $backgroundLayer, $image, $mergeX, $mergeY, 0, 0, $previewWidth,
1030
+            $previewHeight
1031
+        );
1032
+
1033
+        $image = new \OC_Image($backgroundLayer);
1034
+
1035
+        $this->preview = $image;
1036
+    }
1037
+
1038
+    /**
1039
+     * Saves a preview in the cache to speed up future calls
1040
+     *
1041
+     * Do not nullify the preview as it might send the whole process in a loop
1042
+     *
1043
+     * @param int $fileId fileId of the original image
1044
+     * @param int $previewWidth
1045
+     * @param int $previewHeight
1046
+     */
1047
+    private function storePreview($fileId, $previewWidth, $previewHeight) {
1048
+        if (empty($previewWidth) || empty($previewHeight)) {
1049
+            \OCP\Util::writeLog(
1050
+                'core', 'Cannot save preview of dimension ' . $previewWidth . 'x' . $previewHeight,
1051
+                \OCP\Util::DEBUG
1052
+            );
1053
+
1054
+        } else {
1055
+            $cachePath = $this->buildCachePath($fileId, $previewWidth, $previewHeight);
1056
+            $this->userView->file_put_contents($cachePath, $this->preview->data());
1057
+        }
1058
+    }
1059
+
1060
+    /**
1061
+     * Returns the path to a preview based on its dimensions and aspect
1062
+     *
1063
+     * @param int $fileId
1064
+     * @param int|null $maxX
1065
+     * @param int|null $maxY
1066
+     *
1067
+     * @return string
1068
+     */
1069
+    private function buildCachePath($fileId, $maxX = null, $maxY = null) {
1070
+        if (is_null($maxX)) {
1071
+            $maxX = $this->getMaxX();
1072
+        }
1073
+        if (is_null($maxY)) {
1074
+            $maxY = $this->getMaxY();
1075
+        }
1076
+
1077
+        $previewPath = $this->getPreviewPath($fileId);
1078
+        $previewPath = $previewPath . strval($maxX) . '-' . strval($maxY);
1079
+        $isMaxPreview =
1080
+            ($maxX === $this->maxPreviewWidth && $maxY === $this->maxPreviewHeight) ? true : false;
1081
+        if ($isMaxPreview) {
1082
+            $previewPath .= '-max';
1083
+        }
1084
+        if ($this->keepAspect && !$isMaxPreview) {
1085
+            $previewPath .= '-with-aspect';
1086
+        }
1087
+        if ($this->mode === self::MODE_COVER) {
1088
+            $previewPath .= '-cover';
1089
+        }
1090
+        $previewPath .= '.png';
1091
+
1092
+        return $previewPath;
1093
+    }
1094
+
1095
+    /**
1096
+     * Returns the path to the folder where the previews are stored, identified by the fileId
1097
+     *
1098
+     * @param int $fileId
1099
+     *
1100
+     * @return string
1101
+     */
1102
+    private function getPreviewPath($fileId) {
1103
+        return $this->getThumbnailsFolder() . '/' . $fileId . '/';
1104
+    }
1105
+
1106
+    /**
1107
+     * Asks the provider to send a preview of the file which respects the maximum dimensions
1108
+     * defined in the configuration and after saving it in the cache, it is then resized to the
1109
+     * asked dimensions
1110
+     *
1111
+     * This is only called once in order to generate a large PNG of dimensions defined in the
1112
+     * configuration file. We'll be able to quickly resize it later on.
1113
+     * We never upscale the original conversion as this will be done later by the resizing
1114
+     * operation
1115
+     *
1116
+     * @param int $fileId fileId of the original image
1117
+     */
1118
+    private function generatePreview($fileId) {
1119
+        $file = $this->getFile();
1120
+        $preview = null;
1121
+
1122
+        $previewProviders = \OC::$server->getPreviewManager()
1123
+            ->getProviders();
1124
+        foreach ($previewProviders as $supportedMimeType => $providers) {
1125
+            if (!preg_match($supportedMimeType, $this->mimeType)) {
1126
+                continue;
1127
+            }
1128
+
1129
+            foreach ($providers as $closure) {
1130
+                $provider = $closure();
1131
+                if (!($provider instanceof \OCP\Preview\IProvider)) {
1132
+                    continue;
1133
+                }
1134
+
1135
+                \OCP\Util::writeLog(
1136
+                    'core', 'Generating preview for "' . $file . '" with "' . get_class($provider)
1137
+                    . '"', \OCP\Util::DEBUG
1138
+                );
1139
+
1140
+                /** @var $provider Provider */
1141
+                $preview = $provider->getThumbnail(
1142
+                    $file, $this->configMaxWidth, $this->configMaxHeight, $scalingUp = false,
1143
+                    $this->fileView
1144
+                );
1145
+
1146
+                if (!($preview instanceof \OCP\IImage)) {
1147
+                    continue;
1148
+                }
1149
+
1150
+                $this->preview = $preview;
1151
+                $previewPath = $this->getPreviewPath($fileId);
1152
+
1153
+                if ($this->userView->is_dir($this->getThumbnailsFolder() . '/') === false) {
1154
+                    $this->userView->mkdir($this->getThumbnailsFolder() . '/');
1155
+                }
1156
+
1157
+                if ($this->userView->is_dir($previewPath) === false) {
1158
+                    $this->userView->mkdir($previewPath);
1159
+                }
1160
+
1161
+                // This stores our large preview so that it can be used in subsequent resizing requests
1162
+                $this->storeMaxPreview($previewPath);
1163
+
1164
+                break 2;
1165
+            }
1166
+        }
1167
+
1168
+        // The providers have been kind enough to give us a preview
1169
+        if ($preview) {
1170
+            $this->resizeAndStore($fileId);
1171
+        }
1172
+    }
1173
+
1174
+    /**
1175
+     * Defines the media icon, for the media type of the original file, as the preview
1176
+     * @throws PreviewNotAvailableException
1177
+     */
1178
+    private function getMimeIcon() {
1179
+        $image = new \OC_Image();
1180
+        $mimeIconWebPath = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($this->mimeType);
1181
+        if (empty(\OC::$WEBROOT)) {
1182
+            $mimeIconServerPath = \OC::$SERVERROOT . $mimeIconWebPath;
1183
+        } else {
1184
+            $mimeIconServerPath = str_replace(\OC::$WEBROOT, \OC::$SERVERROOT, $mimeIconWebPath);
1185
+        }
1186
+        // we can't load SVGs into an image
1187
+        if (substr($mimeIconWebPath, -4) === '.svg') {
1188
+            throw new PreviewNotAvailableException('SVG mimetype cannot be rendered');
1189
+        }
1190
+        $image->loadFromFile($mimeIconServerPath);
1191
+
1192
+        $this->preview = $image;
1193
+    }
1194
+
1195
+    /**
1196
+     * Stores the max preview in the cache
1197
+     *
1198
+     * @param string $previewPath path to the preview
1199
+     */
1200
+    private function storeMaxPreview($previewPath) {
1201
+        $maxPreviewExists = false;
1202
+        $preview = $this->preview;
1203
+
1204
+        $allThumbnails = $this->userView->getDirectoryContent($previewPath);
1205
+        // This is so that the cache doesn't need emptying when upgrading
1206
+        // Can be replaced by an upgrade script...
1207
+        foreach ($allThumbnails as $thumbnail) {
1208
+            $name = rtrim($thumbnail['name'], '.png');
1209
+            if (strpos($name, 'max')) {
1210
+                $maxPreviewExists = true;
1211
+                break;
1212
+            }
1213
+        }
1214
+        // We haven't found the max preview, so we create it
1215
+        if (!$maxPreviewExists) {
1216
+            $previewWidth = $preview->width();
1217
+            $previewHeight = $preview->height();
1218
+            $previewPath = $previewPath . strval($previewWidth) . '-' . strval($previewHeight);
1219
+            $previewPath .= '-max.png';
1220
+            $this->userView->file_put_contents($previewPath, $preview->data());
1221
+            $this->maxPreviewWidth = $previewWidth;
1222
+            $this->maxPreviewHeight = $previewHeight;
1223
+        }
1224
+    }
1225
+
1226
+    /**
1227
+     * Limits a dimension to the maximum dimension provided as argument
1228
+     *
1229
+     * @param int $dim
1230
+     * @param int $maxDim
1231
+     * @param string $dimName
1232
+     *
1233
+     * @return integer
1234
+     */
1235
+    private function limitMaxDim($dim, $maxDim, $dimName) {
1236
+        if (!is_null($maxDim)) {
1237
+            if ($dim > $maxDim) {
1238
+                \OCP\Util::writeLog(
1239
+                    'core', $dimName . ' reduced from ' . $dim . ' to ' . $maxDim, \OCP\Util::DEBUG
1240
+                );
1241
+                $dim = $maxDim;
1242
+            }
1243
+        }
1244
+
1245
+        return $dim;
1246
+    }
1247
+
1248
+    /**
1249
+     * @param array $args
1250
+     */
1251
+    public static function post_write($args) {
1252
+        self::post_delete($args, 'files/');
1253
+    }
1254
+
1255
+    /**
1256
+     * @param array $args
1257
+     */
1258
+    public static function prepare_delete_files($args) {
1259
+        self::prepare_delete($args, 'files/');
1260
+    }
1261
+
1262
+    /**
1263
+     * @param array $args
1264
+     * @param string $prefix
1265
+     */
1266
+    public static function prepare_delete(array $args, $prefix = '') {
1267
+        $path = $args['path'];
1268
+        if (substr($path, 0, 1) === '/') {
1269
+            $path = substr($path, 1);
1270
+        }
1271
+
1272
+        $view = new \OC\Files\View('/' . \OC_User::getUser() . '/' . $prefix);
1273
+
1274
+        $absPath = Files\Filesystem::normalizePath($view->getAbsolutePath($path));
1275
+        $fileInfo = $view->getFileInfo($path);
1276
+        if ($fileInfo === false) {
1277
+            return;
1278
+        }
1279
+        self::addPathToDeleteFileMapper($absPath, $fileInfo);
1280
+        if ($view->is_dir($path)) {
1281
+            $children = self::getAllChildren($view, $path);
1282
+            self::$deleteChildrenMapper[$absPath] = $children;
1283
+        }
1284
+    }
1285
+
1286
+    /**
1287
+     * @param string $absolutePath
1288
+     * @param \OCP\Files\FileInfo $info
1289
+     */
1290
+    private static function addPathToDeleteFileMapper($absolutePath, $info) {
1291
+        self::$deleteFileMapper[$absolutePath] = $info;
1292
+    }
1293
+
1294
+    /**
1295
+     * @param \OC\Files\View $view
1296
+     * @param string $path
1297
+     *
1298
+     * @return array
1299
+     */
1300
+    private static function getAllChildren($view, $path) {
1301
+        $children = $view->getDirectoryContent($path);
1302
+        $childrensFiles = array();
1303
+
1304
+        $fakeRootLength = strlen($view->getRoot());
1305
+
1306
+        for ($i = 0; $i < count($children); $i++) {
1307
+            $child = $children[$i];
1308
+
1309
+            $childsPath = substr($child->getPath(), $fakeRootLength);
1310
+
1311
+            if ($view->is_dir($childsPath)) {
1312
+                $children = array_merge(
1313
+                    $children,
1314
+                    $view->getDirectoryContent($childsPath)
1315
+                );
1316
+            } else {
1317
+                $childrensFiles[] = $child;
1318
+            }
1319
+        }
1320
+
1321
+        return $childrensFiles;
1322
+    }
1323
+
1324
+    /**
1325
+     * @param array $args
1326
+     */
1327
+    public static function post_delete_files($args) {
1328
+        self::post_delete($args, 'files/');
1329
+    }
1330
+
1331
+    /**
1332
+     * @param array $args
1333
+     */
1334
+    public static function post_delete_versions($args) {
1335
+        self::post_delete($args, 'files/');
1336
+    }
1337
+
1338
+    /**
1339
+     * @param array $args
1340
+     * @param string $prefix
1341
+     */
1342
+    public static function post_delete($args, $prefix = '') {
1343
+        $path = Files\Filesystem::normalizePath($args['path']);
1344
+
1345
+        $preview = new Preview(\OC_User::getUser(), $prefix, $path);
1346
+        $preview->deleteAllPreviews();
1347
+    }
1348 1348
 
1349 1349
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -118,8 +118,8 @@  discard block
 block discarded – undo
118 118
 		if ($user === '') {
119 119
 			$user = \OC_User::getUser();
120 120
 		}
121
-		$this->fileView = new \OC\Files\View('/' . $user . '/' . $root);
122
-		$this->userView = new \OC\Files\View('/' . $user);
121
+		$this->fileView = new \OC\Files\View('/'.$user.'/'.$root);
122
+		$this->userView = new \OC\Files\View('/'.$user);
123 123
 
124 124
 		//set config
125 125
 		$sysConfig = \OC::$server->getConfig();
@@ -129,8 +129,8 @@  discard block
 block discarded – undo
129 129
 
130 130
 		//save parameters
131 131
 		$this->setFile($file);
132
-		$this->setMaxX((int)$maxX);
133
-		$this->setMaxY((int)$maxY);
132
+		$this->setMaxX((int) $maxX);
133
+		$this->setMaxY((int) $maxY);
134 134
 		$this->setScalingUp($scalingUp);
135 135
 
136 136
 		$this->preview = null;
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
 		}
379 379
 
380 380
 		if (!$this->getFileInfo() instanceof FileInfo) {
381
-			\OCP\Util::writeLog('core', 'File:"' . $file . '" not found', \OCP\Util::DEBUG);
381
+			\OCP\Util::writeLog('core', 'File:"'.$file.'" not found', \OCP\Util::DEBUG);
382 382
 
383 383
 			return false;
384 384
 		}
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 			list($newPreviewWidth, $newPreviewHeight) = $this->fixSize($askedWidth, $askedHeight);
566 566
 		}
567 567
 
568
-		return [(int)$newPreviewWidth, (int)$newPreviewHeight];
568
+		return [(int) $newPreviewWidth, (int) $newPreviewHeight];
569 569
 	}
570 570
 
571 571
 	/**
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
 			$askedWidth = round($askedHeight * $originalRatio);
599 599
 		}
600 600
 
601
-		return [(int)$askedWidth, (int)$askedHeight];
601
+		return [(int) $askedWidth, (int) $askedHeight];
602 602
 	}
603 603
 
604 604
 	/**
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
 			$askedWidth = round($askedHeight * $originalRatio);
625 625
 		}
626 626
 
627
-		return [(int)$askedWidth, (int)$askedHeight];
627
+		return [(int) $askedWidth, (int) $askedHeight];
628 628
 	}
629 629
 
630 630
 	/**
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
 			$askedHeight = min($this->configMaxHeight, $askedHeight);
643 643
 		}
644 644
 
645
-		return [(int)$askedWidth, (int)$askedHeight];
645
+		return [(int) $askedWidth, (int) $askedHeight];
646 646
 	}
647 647
 
648 648
 	/**
@@ -682,9 +682,9 @@  discard block
 block discarded – undo
682 682
 	 */
683 683
 	private function getPossibleThumbnails($allThumbnails) {
684 684
 		if ($this->keepAspect) {
685
-			$wantedAspectRatio = (float)($this->maxPreviewWidth / $this->maxPreviewHeight);
685
+			$wantedAspectRatio = (float) ($this->maxPreviewWidth / $this->maxPreviewHeight);
686 686
 		} else {
687
-			$wantedAspectRatio = (float)($this->getMaxX() / $this->getMaxY());
687
+			$wantedAspectRatio = (float) ($this->getMaxX() / $this->getMaxY());
688 688
 		}
689 689
 
690 690
 		//array for usable cached thumbnails
@@ -714,9 +714,9 @@  discard block
 block discarded – undo
714 714
 	 */
715 715
 	private function getDimensionsFromFilename($name) {
716 716
 		$size = explode('-', $name);
717
-		$x = (int)$size[0];
718
-		$y = (int)$size[1];
719
-		$aspectRatio = (float)($x / $y);
717
+		$x = (int) $size[0];
718
+		$y = (int) $size[1];
719
+		$aspectRatio = (float) ($x / $y);
720 720
 
721 721
 		return array($x, $y, $aspectRatio);
722 722
 	}
@@ -832,8 +832,8 @@  discard block
 block discarded – undo
832 832
 				$maxX = $this->previewWidth;
833 833
 				$maxY = $this->previewHeight;
834 834
 				// Size of the preview we retrieved from the cache
835
-				$previewX = (int)$this->preview->width();
836
-				$previewY = (int)$this->preview->height();
835
+				$previewX = (int) $this->preview->width();
836
+				$previewY = (int) $this->preview->height();
837 837
 
838 838
 				// We don't have an exact match
839 839
 				if ($previewX !== $maxX || $previewY !== $maxY) {
@@ -859,8 +859,8 @@  discard block
 block discarded – undo
859 859
 
860 860
 			return;
861 861
 		}
862
-		$previewWidth = (int)$image->width();
863
-		$previewHeight = (int)$image->height();
862
+		$previewWidth = (int) $image->width();
863
+		$previewHeight = (int) $image->height();
864 864
 		$askedWidth = $this->getMaxX();
865 865
 		$askedHeight = $this->getMaxY();
866 866
 
@@ -955,7 +955,7 @@  discard block
 block discarded – undo
955 955
 		if (!is_null($maxScaleFactor)) {
956 956
 			if ($factor > $maxScaleFactor) {
957 957
 				\OCP\Util::writeLog(
958
-					'core', 'scale factor reduced from ' . $factor . ' to ' . $maxScaleFactor,
958
+					'core', 'scale factor reduced from '.$factor.' to '.$maxScaleFactor,
959 959
 					\OCP\Util::DEBUG
960 960
 				);
961 961
 				$factor = $maxScaleFactor;
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
 	private function storePreview($fileId, $previewWidth, $previewHeight) {
1048 1048
 		if (empty($previewWidth) || empty($previewHeight)) {
1049 1049
 			\OCP\Util::writeLog(
1050
-				'core', 'Cannot save preview of dimension ' . $previewWidth . 'x' . $previewHeight,
1050
+				'core', 'Cannot save preview of dimension '.$previewWidth.'x'.$previewHeight,
1051 1051
 				\OCP\Util::DEBUG
1052 1052
 			);
1053 1053
 
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
 		}
1076 1076
 
1077 1077
 		$previewPath = $this->getPreviewPath($fileId);
1078
-		$previewPath = $previewPath . strval($maxX) . '-' . strval($maxY);
1078
+		$previewPath = $previewPath.strval($maxX).'-'.strval($maxY);
1079 1079
 		$isMaxPreview =
1080 1080
 			($maxX === $this->maxPreviewWidth && $maxY === $this->maxPreviewHeight) ? true : false;
1081 1081
 		if ($isMaxPreview) {
@@ -1100,7 +1100,7 @@  discard block
 block discarded – undo
1100 1100
 	 * @return string
1101 1101
 	 */
1102 1102
 	private function getPreviewPath($fileId) {
1103
-		return $this->getThumbnailsFolder() . '/' . $fileId . '/';
1103
+		return $this->getThumbnailsFolder().'/'.$fileId.'/';
1104 1104
 	}
1105 1105
 
1106 1106
 	/**
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 				}
1134 1134
 
1135 1135
 				\OCP\Util::writeLog(
1136
-					'core', 'Generating preview for "' . $file . '" with "' . get_class($provider)
1136
+					'core', 'Generating preview for "'.$file.'" with "'.get_class($provider)
1137 1137
 					. '"', \OCP\Util::DEBUG
1138 1138
 				);
1139 1139
 
@@ -1150,8 +1150,8 @@  discard block
 block discarded – undo
1150 1150
 				$this->preview = $preview;
1151 1151
 				$previewPath = $this->getPreviewPath($fileId);
1152 1152
 
1153
-				if ($this->userView->is_dir($this->getThumbnailsFolder() . '/') === false) {
1154
-					$this->userView->mkdir($this->getThumbnailsFolder() . '/');
1153
+				if ($this->userView->is_dir($this->getThumbnailsFolder().'/') === false) {
1154
+					$this->userView->mkdir($this->getThumbnailsFolder().'/');
1155 1155
 				}
1156 1156
 
1157 1157
 				if ($this->userView->is_dir($previewPath) === false) {
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
 		$image = new \OC_Image();
1180 1180
 		$mimeIconWebPath = \OC::$server->getMimeTypeDetector()->mimeTypeIcon($this->mimeType);
1181 1181
 		if (empty(\OC::$WEBROOT)) {
1182
-			$mimeIconServerPath = \OC::$SERVERROOT . $mimeIconWebPath;
1182
+			$mimeIconServerPath = \OC::$SERVERROOT.$mimeIconWebPath;
1183 1183
 		} else {
1184 1184
 			$mimeIconServerPath = str_replace(\OC::$WEBROOT, \OC::$SERVERROOT, $mimeIconWebPath);
1185 1185
 		}
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
 		if (!$maxPreviewExists) {
1216 1216
 			$previewWidth = $preview->width();
1217 1217
 			$previewHeight = $preview->height();
1218
-			$previewPath = $previewPath . strval($previewWidth) . '-' . strval($previewHeight);
1218
+			$previewPath = $previewPath.strval($previewWidth).'-'.strval($previewHeight);
1219 1219
 			$previewPath .= '-max.png';
1220 1220
 			$this->userView->file_put_contents($previewPath, $preview->data());
1221 1221
 			$this->maxPreviewWidth = $previewWidth;
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
 		if (!is_null($maxDim)) {
1237 1237
 			if ($dim > $maxDim) {
1238 1238
 				\OCP\Util::writeLog(
1239
-					'core', $dimName . ' reduced from ' . $dim . ' to ' . $maxDim, \OCP\Util::DEBUG
1239
+					'core', $dimName.' reduced from '.$dim.' to '.$maxDim, \OCP\Util::DEBUG
1240 1240
 				);
1241 1241
 				$dim = $maxDim;
1242 1242
 			}
@@ -1269,7 +1269,7 @@  discard block
 block discarded – undo
1269 1269
 			$path = substr($path, 1);
1270 1270
 		}
1271 1271
 
1272
-		$view = new \OC\Files\View('/' . \OC_User::getUser() . '/' . $prefix);
1272
+		$view = new \OC\Files\View('/'.\OC_User::getUser().'/'.$prefix);
1273 1273
 
1274 1274
 		$absPath = Files\Filesystem::normalizePath($view->getAbsolutePath($path));
1275 1275
 		$fileInfo = $view->getFileInfo($path);
Please login to merge, or discard this patch.
lib/private/Repair.php 3 patches
Doc Comments   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 	 * Returns expensive repair steps to be run on the
140 140
 	 * command line with a special option.
141 141
 	 *
142
-	 * @return IRepairStep[]
142
+	 * @return OldGroupMembershipShares[]
143 143
 	 */
144 144
 	public static function getExpensiveRepairSteps() {
145 145
 		return [
@@ -216,7 +216,6 @@  discard block
 block discarded – undo
216 216
 	}
217 217
 
218 218
 	/**
219
-	 * @param int $max
220 219
 	 */
221 220
 	public function finishProgress() {
222 221
 		// for now just emit as we did in the past
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@
 block discarded – undo
58 58
 use Symfony\Component\EventDispatcher\EventDispatcher;
59 59
 use Symfony\Component\EventDispatcher\GenericEvent;
60 60
 
61
-class Repair implements IOutput{
61
+class Repair implements IOutput {
62 62
 	/* @var IRepairStep[] */
63 63
 	private $repairSteps;
64 64
 	/** @var EventDispatcher */
Please login to merge, or discard this patch.
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -58,185 +58,185 @@
 block discarded – undo
58 58
 use Symfony\Component\EventDispatcher\GenericEvent;
59 59
 
60 60
 class Repair implements IOutput{
61
-	/* @var IRepairStep[] */
62
-	private $repairSteps;
63
-	/** @var EventDispatcher */
64
-	private $dispatcher;
65
-	/** @var string */
66
-	private $currentStep;
67
-
68
-	/**
69
-	 * Creates a new repair step runner
70
-	 *
71
-	 * @param IRepairStep[] $repairSteps array of RepairStep instances
72
-	 * @param EventDispatcher $dispatcher
73
-	 */
74
-	public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
75
-		$this->repairSteps = $repairSteps;
76
-		$this->dispatcher = $dispatcher;
77
-	}
78
-
79
-	/**
80
-	 * Run a series of repair steps for common problems
81
-	 */
82
-	public function run() {
83
-		if (count($this->repairSteps) === 0) {
84
-			$this->emit('\OC\Repair', 'info', array('No repair steps available'));
85
-			return;
86
-		}
87
-		// run each repair step
88
-		foreach ($this->repairSteps as $step) {
89
-			$this->currentStep = $step->getName();
90
-			$this->emit('\OC\Repair', 'step', [$this->currentStep]);
91
-			$step->run($this);
92
-		}
93
-	}
94
-
95
-	/**
96
-	 * Add repair step
97
-	 *
98
-	 * @param IRepairStep|string $repairStep repair step
99
-	 * @throws \Exception
100
-	 */
101
-	public function addStep($repairStep) {
102
-		if (is_string($repairStep)) {
103
-			try {
104
-				$s = \OC::$server->query($repairStep);
105
-			} catch (QueryException $e) {
106
-				if (class_exists($repairStep)) {
107
-					$s = new $repairStep();
108
-				} else {
109
-					throw new \Exception("Repair step '$repairStep' is unknown");
110
-				}
111
-			}
112
-
113
-			if ($s instanceof IRepairStep) {
114
-				$this->repairSteps[] = $s;
115
-			} else {
116
-				throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
117
-			}
118
-		} else {
119
-			$this->repairSteps[] = $repairStep;
120
-		}
121
-	}
122
-
123
-	/**
124
-	 * Returns the default repair steps to be run on the
125
-	 * command line or after an upgrade.
126
-	 *
127
-	 * @return IRepairStep[]
128
-	 */
129
-	public static function getRepairSteps() {
130
-		return [
131
-			new RepairMimeTypes(\OC::$server->getConfig()),
132
-			new RepairLegacyStorages(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
133
-			new AssetCache(),
134
-			new FillETags(\OC::$server->getDatabaseConnection()),
135
-			new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
136
-			new DropOldTables(\OC::$server->getDatabaseConnection()),
137
-			new DropOldJobs(\OC::$server->getJobList()),
138
-			new RemoveGetETagEntries(\OC::$server->getDatabaseConnection()),
139
-			new UpdateOutdatedOcsIds(\OC::$server->getConfig()),
140
-			new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
141
-			new SharePropagation(\OC::$server->getConfig()),
142
-			new RemoveOldShares(\OC::$server->getDatabaseConnection()),
143
-			new AvatarPermissions(\OC::$server->getDatabaseConnection()),
144
-			new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
145
-			new RepairUnmergedShares(
146
-				\OC::$server->getConfig(),
147
-				\OC::$server->getDatabaseConnection(),
148
-				\OC::$server->getUserManager(),
149
-				\OC::$server->getGroupManager()
150
-			),
151
-			new MoveUpdaterStepFile(\OC::$server->getConfig()),
152
-		];
153
-	}
154
-
155
-	/**
156
-	 * Returns expensive repair steps to be run on the
157
-	 * command line with a special option.
158
-	 *
159
-	 * @return IRepairStep[]
160
-	 */
161
-	public static function getExpensiveRepairSteps() {
162
-		return [
163
-			new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
164
-		];
165
-	}
166
-
167
-	/**
168
-	 * Returns the repair steps to be run before an
169
-	 * upgrade.
170
-	 *
171
-	 * @return IRepairStep[]
172
-	 */
173
-	public static function getBeforeUpgradeRepairSteps() {
174
-		$connection = \OC::$server->getDatabaseConnection();
175
-		$steps = [
176
-			new InnoDB(),
177
-			new Collation(\OC::$server->getConfig(), $connection),
178
-			new SqliteAutoincrement($connection),
179
-			new SearchLuceneTables(),
180
-		];
181
-
182
-		//There is no need to delete all previews on every single update
183
-		//only 7.0.0 through 7.0.2 generated broken previews
184
-		$currentVersion = \OC::$server->getConfig()->getSystemValue('version');
185
-		if (version_compare($currentVersion, '7.0.0.0', '>=') &&
186
-			version_compare($currentVersion, '7.0.3.4', '<=')) {
187
-			$steps[] = new \OC\Repair\Preview();
188
-		}
189
-
190
-		return $steps;
191
-	}
192
-
193
-	/**
194
-	 * @param string $scope
195
-	 * @param string $method
196
-	 * @param array $arguments
197
-	 */
198
-	public function emit($scope, $method, array $arguments = []) {
199
-		if (!is_null($this->dispatcher)) {
200
-			$this->dispatcher->dispatch("$scope::$method",
201
-				new GenericEvent("$scope::$method", $arguments));
202
-		}
203
-	}
204
-
205
-	public function info($string) {
206
-		// for now just emit as we did in the past
207
-		$this->emit('\OC\Repair', 'info', array($string));
208
-	}
209
-
210
-	/**
211
-	 * @param string $message
212
-	 */
213
-	public function warning($message) {
214
-		// for now just emit as we did in the past
215
-		$this->emit('\OC\Repair', 'warning', [$message]);
216
-	}
217
-
218
-	/**
219
-	 * @param int $max
220
-	 */
221
-	public function startProgress($max = 0) {
222
-		// for now just emit as we did in the past
223
-		$this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
224
-	}
225
-
226
-	/**
227
-	 * @param int $step
228
-	 * @param string $description
229
-	 */
230
-	public function advance($step = 1, $description = '') {
231
-		// for now just emit as we did in the past
232
-		$this->emit('\OC\Repair', 'advance', [$step, $description]);
233
-	}
234
-
235
-	/**
236
-	 * @param int $max
237
-	 */
238
-	public function finishProgress() {
239
-		// for now just emit as we did in the past
240
-		$this->emit('\OC\Repair', 'finishProgress', []);
241
-	}
61
+    /* @var IRepairStep[] */
62
+    private $repairSteps;
63
+    /** @var EventDispatcher */
64
+    private $dispatcher;
65
+    /** @var string */
66
+    private $currentStep;
67
+
68
+    /**
69
+     * Creates a new repair step runner
70
+     *
71
+     * @param IRepairStep[] $repairSteps array of RepairStep instances
72
+     * @param EventDispatcher $dispatcher
73
+     */
74
+    public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
75
+        $this->repairSteps = $repairSteps;
76
+        $this->dispatcher = $dispatcher;
77
+    }
78
+
79
+    /**
80
+     * Run a series of repair steps for common problems
81
+     */
82
+    public function run() {
83
+        if (count($this->repairSteps) === 0) {
84
+            $this->emit('\OC\Repair', 'info', array('No repair steps available'));
85
+            return;
86
+        }
87
+        // run each repair step
88
+        foreach ($this->repairSteps as $step) {
89
+            $this->currentStep = $step->getName();
90
+            $this->emit('\OC\Repair', 'step', [$this->currentStep]);
91
+            $step->run($this);
92
+        }
93
+    }
94
+
95
+    /**
96
+     * Add repair step
97
+     *
98
+     * @param IRepairStep|string $repairStep repair step
99
+     * @throws \Exception
100
+     */
101
+    public function addStep($repairStep) {
102
+        if (is_string($repairStep)) {
103
+            try {
104
+                $s = \OC::$server->query($repairStep);
105
+            } catch (QueryException $e) {
106
+                if (class_exists($repairStep)) {
107
+                    $s = new $repairStep();
108
+                } else {
109
+                    throw new \Exception("Repair step '$repairStep' is unknown");
110
+                }
111
+            }
112
+
113
+            if ($s instanceof IRepairStep) {
114
+                $this->repairSteps[] = $s;
115
+            } else {
116
+                throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
117
+            }
118
+        } else {
119
+            $this->repairSteps[] = $repairStep;
120
+        }
121
+    }
122
+
123
+    /**
124
+     * Returns the default repair steps to be run on the
125
+     * command line or after an upgrade.
126
+     *
127
+     * @return IRepairStep[]
128
+     */
129
+    public static function getRepairSteps() {
130
+        return [
131
+            new RepairMimeTypes(\OC::$server->getConfig()),
132
+            new RepairLegacyStorages(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
133
+            new AssetCache(),
134
+            new FillETags(\OC::$server->getDatabaseConnection()),
135
+            new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
136
+            new DropOldTables(\OC::$server->getDatabaseConnection()),
137
+            new DropOldJobs(\OC::$server->getJobList()),
138
+            new RemoveGetETagEntries(\OC::$server->getDatabaseConnection()),
139
+            new UpdateOutdatedOcsIds(\OC::$server->getConfig()),
140
+            new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
141
+            new SharePropagation(\OC::$server->getConfig()),
142
+            new RemoveOldShares(\OC::$server->getDatabaseConnection()),
143
+            new AvatarPermissions(\OC::$server->getDatabaseConnection()),
144
+            new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
145
+            new RepairUnmergedShares(
146
+                \OC::$server->getConfig(),
147
+                \OC::$server->getDatabaseConnection(),
148
+                \OC::$server->getUserManager(),
149
+                \OC::$server->getGroupManager()
150
+            ),
151
+            new MoveUpdaterStepFile(\OC::$server->getConfig()),
152
+        ];
153
+    }
154
+
155
+    /**
156
+     * Returns expensive repair steps to be run on the
157
+     * command line with a special option.
158
+     *
159
+     * @return IRepairStep[]
160
+     */
161
+    public static function getExpensiveRepairSteps() {
162
+        return [
163
+            new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
164
+        ];
165
+    }
166
+
167
+    /**
168
+     * Returns the repair steps to be run before an
169
+     * upgrade.
170
+     *
171
+     * @return IRepairStep[]
172
+     */
173
+    public static function getBeforeUpgradeRepairSteps() {
174
+        $connection = \OC::$server->getDatabaseConnection();
175
+        $steps = [
176
+            new InnoDB(),
177
+            new Collation(\OC::$server->getConfig(), $connection),
178
+            new SqliteAutoincrement($connection),
179
+            new SearchLuceneTables(),
180
+        ];
181
+
182
+        //There is no need to delete all previews on every single update
183
+        //only 7.0.0 through 7.0.2 generated broken previews
184
+        $currentVersion = \OC::$server->getConfig()->getSystemValue('version');
185
+        if (version_compare($currentVersion, '7.0.0.0', '>=') &&
186
+            version_compare($currentVersion, '7.0.3.4', '<=')) {
187
+            $steps[] = new \OC\Repair\Preview();
188
+        }
189
+
190
+        return $steps;
191
+    }
192
+
193
+    /**
194
+     * @param string $scope
195
+     * @param string $method
196
+     * @param array $arguments
197
+     */
198
+    public function emit($scope, $method, array $arguments = []) {
199
+        if (!is_null($this->dispatcher)) {
200
+            $this->dispatcher->dispatch("$scope::$method",
201
+                new GenericEvent("$scope::$method", $arguments));
202
+        }
203
+    }
204
+
205
+    public function info($string) {
206
+        // for now just emit as we did in the past
207
+        $this->emit('\OC\Repair', 'info', array($string));
208
+    }
209
+
210
+    /**
211
+     * @param string $message
212
+     */
213
+    public function warning($message) {
214
+        // for now just emit as we did in the past
215
+        $this->emit('\OC\Repair', 'warning', [$message]);
216
+    }
217
+
218
+    /**
219
+     * @param int $max
220
+     */
221
+    public function startProgress($max = 0) {
222
+        // for now just emit as we did in the past
223
+        $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
224
+    }
225
+
226
+    /**
227
+     * @param int $step
228
+     * @param string $description
229
+     */
230
+    public function advance($step = 1, $description = '') {
231
+        // for now just emit as we did in the past
232
+        $this->emit('\OC\Repair', 'advance', [$step, $description]);
233
+    }
234
+
235
+    /**
236
+     * @param int $max
237
+     */
238
+    public function finishProgress() {
239
+        // for now just emit as we did in the past
240
+        $this->emit('\OC\Repair', 'finishProgress', []);
241
+    }
242 242
 }
Please login to merge, or discard this patch.
lib/private/Repair/Collation.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@
 block discarded – undo
69 69
 	}
70 70
 
71 71
 	/**
72
-	 * @param \Doctrine\DBAL\Connection $connection
72
+	 * @param \OC\DB\Connection $connection
73 73
 	 * @return string[]
74 74
 	 */
75 75
 	protected function getAllNonUTF8BinTables($connection) {
Please login to merge, or discard this patch.
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -29,65 +29,65 @@
 block discarded – undo
29 29
 use OCP\Migration\IRepairStep;
30 30
 
31 31
 class Collation implements IRepairStep {
32
-	/**
33
-	 * @var \OCP\IConfig
34
-	 */
35
-	protected $config;
32
+    /**
33
+     * @var \OCP\IConfig
34
+     */
35
+    protected $config;
36 36
 
37
-	/**
38
-	 * @var \OC\DB\Connection
39
-	 */
40
-	protected $connection;
37
+    /**
38
+     * @var \OC\DB\Connection
39
+     */
40
+    protected $connection;
41 41
 
42
-	/**
43
-	 * @param \OCP\IConfig $config
44
-	 * @param \OC\DB\Connection $connection
45
-	 */
46
-	public function __construct($config, $connection) {
47
-		$this->connection = $connection;
48
-		$this->config = $config;
49
-	}
42
+    /**
43
+     * @param \OCP\IConfig $config
44
+     * @param \OC\DB\Connection $connection
45
+     */
46
+    public function __construct($config, $connection) {
47
+        $this->connection = $connection;
48
+        $this->config = $config;
49
+    }
50 50
 
51
-	public function getName() {
52
-		return 'Repair MySQL collation';
53
-	}
51
+    public function getName() {
52
+        return 'Repair MySQL collation';
53
+    }
54 54
 
55
-	/**
56
-	 * Fix mime types
57
-	 */
58
-	public function run(IOutput $output) {
59
-		if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
60
-			$output->info('Not a mysql database -> nothing to no');
61
-			return;
62
-		}
55
+    /**
56
+     * Fix mime types
57
+     */
58
+    public function run(IOutput $output) {
59
+        if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
60
+            $output->info('Not a mysql database -> nothing to no');
61
+            return;
62
+        }
63 63
 
64
-		$tables = $this->getAllNonUTF8BinTables($this->connection);
65
-		foreach ($tables as $table) {
66
-			$output->info("Change collation for $table ...");
67
-			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;');
68
-			$query->execute();
69
-		}
70
-	}
64
+        $tables = $this->getAllNonUTF8BinTables($this->connection);
65
+        foreach ($tables as $table) {
66
+            $output->info("Change collation for $table ...");
67
+            $query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;');
68
+            $query->execute();
69
+        }
70
+    }
71 71
 
72
-	/**
73
-	 * @param \Doctrine\DBAL\Connection $connection
74
-	 * @return string[]
75
-	 */
76
-	protected function getAllNonUTF8BinTables($connection) {
77
-		$dbName = $this->config->getSystemValue("dbname");
78
-		$rows = $connection->fetchAll(
79
-			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
80
-			"	FROM INFORMATION_SCHEMA . COLUMNS" .
81
-			"	WHERE TABLE_SCHEMA = ?" .
82
-			"	AND (COLLATION_NAME <> 'utf8_bin' OR CHARACTER_SET_NAME <> 'utf8')" .
83
-			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
84
-			array($dbName)
85
-		);
86
-		$result = array();
87
-		foreach ($rows as $row) {
88
-			$result[] = $row['table'];
89
-		}
90
-		return $result;
91
-	}
72
+    /**
73
+     * @param \Doctrine\DBAL\Connection $connection
74
+     * @return string[]
75
+     */
76
+    protected function getAllNonUTF8BinTables($connection) {
77
+        $dbName = $this->config->getSystemValue("dbname");
78
+        $rows = $connection->fetchAll(
79
+            "SELECT DISTINCT(TABLE_NAME) AS `table`" .
80
+            "	FROM INFORMATION_SCHEMA . COLUMNS" .
81
+            "	WHERE TABLE_SCHEMA = ?" .
82
+            "	AND (COLLATION_NAME <> 'utf8_bin' OR CHARACTER_SET_NAME <> 'utf8')" .
83
+            "	AND TABLE_NAME LIKE \"*PREFIX*%\"",
84
+            array($dbName)
85
+        );
86
+        $result = array();
87
+        foreach ($rows as $row) {
88
+            $result[] = $row['table'];
89
+        }
90
+        return $result;
91
+    }
92 92
 }
93 93
 
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 		$tables = $this->getAllNonUTF8BinTables($this->connection);
65 65
 		foreach ($tables as $table) {
66 66
 			$output->info("Change collation for $table ...");
67
-			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;');
67
+			$query = $this->connection->prepare('ALTER TABLE `'.$table.'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;');
68 68
 			$query->execute();
69 69
 		}
70 70
 	}
@@ -76,10 +76,10 @@  discard block
 block discarded – undo
76 76
 	protected function getAllNonUTF8BinTables($connection) {
77 77
 		$dbName = $this->config->getSystemValue("dbname");
78 78
 		$rows = $connection->fetchAll(
79
-			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
80
-			"	FROM INFORMATION_SCHEMA . COLUMNS" .
81
-			"	WHERE TABLE_SCHEMA = ?" .
82
-			"	AND (COLLATION_NAME <> 'utf8_bin' OR CHARACTER_SET_NAME <> 'utf8')" .
79
+			"SELECT DISTINCT(TABLE_NAME) AS `table`".
80
+			"	FROM INFORMATION_SCHEMA . COLUMNS".
81
+			"	WHERE TABLE_SCHEMA = ?".
82
+			"	AND (COLLATION_NAME <> 'utf8_bin' OR CHARACTER_SET_NAME <> 'utf8')".
83 83
 			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
84 84
 			array($dbName)
85 85
 		);
Please login to merge, or discard this patch.
lib/private/Repair/InnoDB.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@
 block discarded – undo
53 53
 	}
54 54
 
55 55
 	/**
56
-	 * @param \Doctrine\DBAL\Connection $connection
56
+	 * @param \OCP\IDBConnection $connection
57 57
 	 * @return string[]
58 58
 	 */
59 59
 	private function getAllMyIsamTables($connection) {
Please login to merge, or discard this patch.
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -30,41 +30,41 @@
 block discarded – undo
30 30
 
31 31
 class InnoDB implements IRepairStep {
32 32
 
33
-	public function getName() {
34
-		return 'Repair MySQL database engine';
35
-	}
33
+    public function getName() {
34
+        return 'Repair MySQL database engine';
35
+    }
36 36
 
37
-	/**
38
-	 * Fix mime types
39
-	 */
40
-	public function run(IOutput $output) {
41
-		$connection = \OC::$server->getDatabaseConnection();
42
-		if (!$connection->getDatabasePlatform() instanceof MySqlPlatform) {
43
-			$output->info('Not a mysql database -> nothing to do');
44
-			return;
45
-		}
37
+    /**
38
+     * Fix mime types
39
+     */
40
+    public function run(IOutput $output) {
41
+        $connection = \OC::$server->getDatabaseConnection();
42
+        if (!$connection->getDatabasePlatform() instanceof MySqlPlatform) {
43
+            $output->info('Not a mysql database -> nothing to do');
44
+            return;
45
+        }
46 46
 
47
-		$tables = $this->getAllMyIsamTables($connection);
48
-		if (is_array($tables)) {
49
-			foreach ($tables as $table) {
50
-				$connection->exec("ALTER TABLE $table ENGINE=InnoDB;");
51
-				$output->info("Fixed $table");
52
-			}
53
-		}
54
-	}
47
+        $tables = $this->getAllMyIsamTables($connection);
48
+        if (is_array($tables)) {
49
+            foreach ($tables as $table) {
50
+                $connection->exec("ALTER TABLE $table ENGINE=InnoDB;");
51
+                $output->info("Fixed $table");
52
+            }
53
+        }
54
+    }
55 55
 
56
-	/**
57
-	 * @param \Doctrine\DBAL\Connection $connection
58
-	 * @return string[]
59
-	 */
60
-	private function getAllMyIsamTables($connection) {
61
-		$dbName = \OC::$server->getConfig()->getSystemValue("dbname");
62
-		$result = $connection->fetchArray(
63
-			"SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND engine = 'MyISAM' AND TABLE_NAME LIKE \"*PREFIX*%\"",
64
-			array($dbName)
65
-		);
56
+    /**
57
+     * @param \Doctrine\DBAL\Connection $connection
58
+     * @return string[]
59
+     */
60
+    private function getAllMyIsamTables($connection) {
61
+        $dbName = \OC::$server->getConfig()->getSystemValue("dbname");
62
+        $result = $connection->fetchArray(
63
+            "SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND engine = 'MyISAM' AND TABLE_NAME LIKE \"*PREFIX*%\"",
64
+            array($dbName)
65
+        );
66 66
 
67
-		return $result;
68
-	}
67
+        return $result;
68
+    }
69 69
 }
70 70
 
Please login to merge, or discard this patch.
lib/private/Security/CredentialsManager.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 use OCP\Security\ICrypto;
25 25
 use OCP\IDBConnection;
26 26
 use OCP\Security\ICredentialsManager;
27
-use OCP\IConfig;
28 27
 
29 28
 /**
30 29
  * Store and retrieve credentials for external services
Please login to merge, or discard this patch.
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -34,93 +34,93 @@
 block discarded – undo
34 34
  */
35 35
 class CredentialsManager implements ICredentialsManager {
36 36
 
37
-	const DB_TABLE = 'credentials';
37
+    const DB_TABLE = 'credentials';
38 38
 
39
-	/** @var ICrypto */
40
-	protected $crypto;
39
+    /** @var ICrypto */
40
+    protected $crypto;
41 41
 
42
-	/** @var IDBConnection */
43
-	protected $dbConnection;
42
+    /** @var IDBConnection */
43
+    protected $dbConnection;
44 44
 
45
-	/**
46
-	 * @param ICrypto $crypto
47
-	 * @param IDBConnection $dbConnection
48
-	 */
49
-	public function __construct(ICrypto $crypto, IDBConnection $dbConnection) {
50
-		$this->crypto = $crypto;
51
-		$this->dbConnection = $dbConnection;
52
-	}
45
+    /**
46
+     * @param ICrypto $crypto
47
+     * @param IDBConnection $dbConnection
48
+     */
49
+    public function __construct(ICrypto $crypto, IDBConnection $dbConnection) {
50
+        $this->crypto = $crypto;
51
+        $this->dbConnection = $dbConnection;
52
+    }
53 53
 
54
-	/**
55
-	 * Store a set of credentials
56
-	 *
57
-	 * @param string|null $userId Null for system-wide credentials
58
-	 * @param string $identifier
59
-	 * @param mixed $credentials
60
-	 */
61
-	public function store($userId, $identifier, $credentials) {
62
-		$value = $this->crypto->encrypt(json_encode($credentials));
54
+    /**
55
+     * Store a set of credentials
56
+     *
57
+     * @param string|null $userId Null for system-wide credentials
58
+     * @param string $identifier
59
+     * @param mixed $credentials
60
+     */
61
+    public function store($userId, $identifier, $credentials) {
62
+        $value = $this->crypto->encrypt(json_encode($credentials));
63 63
 
64
-		$this->dbConnection->setValues(self::DB_TABLE, [
65
-			'user' => $userId,
66
-			'identifier' => $identifier,
67
-		], [
68
-			'credentials' => $value,
69
-		]);
70
-	}
64
+        $this->dbConnection->setValues(self::DB_TABLE, [
65
+            'user' => $userId,
66
+            'identifier' => $identifier,
67
+        ], [
68
+            'credentials' => $value,
69
+        ]);
70
+    }
71 71
 
72
-	/**
73
-	 * Retrieve a set of credentials
74
-	 *
75
-	 * @param string|null $userId Null for system-wide credentials
76
-	 * @param string $identifier
77
-	 * @return mixed
78
-	 */
79
-	public function retrieve($userId, $identifier) {
80
-		$qb = $this->dbConnection->getQueryBuilder();
81
-		$qb->select('credentials')
82
-			->from(self::DB_TABLE)
83
-			->where($qb->expr()->eq('user', $qb->createNamedParameter($userId)))
84
-			->andWhere($qb->expr()->eq('identifier', $qb->createNamedParameter($identifier)))
85
-		;
86
-		$result = $qb->execute()->fetch();
72
+    /**
73
+     * Retrieve a set of credentials
74
+     *
75
+     * @param string|null $userId Null for system-wide credentials
76
+     * @param string $identifier
77
+     * @return mixed
78
+     */
79
+    public function retrieve($userId, $identifier) {
80
+        $qb = $this->dbConnection->getQueryBuilder();
81
+        $qb->select('credentials')
82
+            ->from(self::DB_TABLE)
83
+            ->where($qb->expr()->eq('user', $qb->createNamedParameter($userId)))
84
+            ->andWhere($qb->expr()->eq('identifier', $qb->createNamedParameter($identifier)))
85
+        ;
86
+        $result = $qb->execute()->fetch();
87 87
 
88
-		if (!$result) {
89
-			return null;
90
-		}
91
-		$value = $result['credentials'];
88
+        if (!$result) {
89
+            return null;
90
+        }
91
+        $value = $result['credentials'];
92 92
 
93
-		return json_decode($this->crypto->decrypt($value), true);
94
-	}
93
+        return json_decode($this->crypto->decrypt($value), true);
94
+    }
95 95
 
96
-	/**
97
-	 * Delete a set of credentials
98
-	 *
99
-	 * @param string|null $userId Null for system-wide credentials
100
-	 * @param string $identifier
101
-	 * @return int rows removed
102
-	 */
103
-	public function delete($userId, $identifier) {
104
-		$qb = $this->dbConnection->getQueryBuilder();
105
-		$qb->delete(self::DB_TABLE)
106
-			->where($qb->expr()->eq('user', $qb->createNamedParameter($userId)))
107
-			->andWhere($qb->expr()->eq('identifier', $qb->createNamedParameter($identifier)))
108
-		;
109
-		return $qb->execute();
110
-	}
96
+    /**
97
+     * Delete a set of credentials
98
+     *
99
+     * @param string|null $userId Null for system-wide credentials
100
+     * @param string $identifier
101
+     * @return int rows removed
102
+     */
103
+    public function delete($userId, $identifier) {
104
+        $qb = $this->dbConnection->getQueryBuilder();
105
+        $qb->delete(self::DB_TABLE)
106
+            ->where($qb->expr()->eq('user', $qb->createNamedParameter($userId)))
107
+            ->andWhere($qb->expr()->eq('identifier', $qb->createNamedParameter($identifier)))
108
+        ;
109
+        return $qb->execute();
110
+    }
111 111
 
112
-	/**
113
-	 * Erase all credentials stored for a user
114
-	 *
115
-	 * @param string $userId
116
-	 * @return int rows removed
117
-	 */
118
-	public function erase($userId) {
119
-		$qb = $this->dbConnection->getQueryBuilder();
120
-		$qb->delete(self::DB_TABLE)
121
-			->where($qb->expr()->eq('user', $qb->createNamedParameter($userId)))
122
-		;
123
-		return $qb->execute();
124
-	}
112
+    /**
113
+     * Erase all credentials stored for a user
114
+     *
115
+     * @param string $userId
116
+     * @return int rows removed
117
+     */
118
+    public function erase($userId) {
119
+        $qb = $this->dbConnection->getQueryBuilder();
120
+        $qb->delete(self::DB_TABLE)
121
+            ->where($qb->expr()->eq('user', $qb->createNamedParameter($userId)))
122
+        ;
123
+        return $qb->execute();
124
+    }
125 125
 
126 126
 }
Please login to merge, or discard this patch.
lib/private/Server.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1074,7 +1074,7 @@
 block discarded – undo
1074 1074
 	 * Get the certificate manager for the user
1075 1075
 	 *
1076 1076
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1077
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1077
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1078 1078
 	 */
1079 1079
 	public function getCertificateManager($userId = '') {
1080 1080
 		if ($userId === '') {
Please login to merge, or discard this patch.
Indentation   +1352 added lines, -1352 removed lines patch added patch discarded remove patch
@@ -97,1361 +97,1361 @@
 block discarded – undo
97 97
  * TODO: hookup all manager classes
98 98
  */
99 99
 class Server extends ServerContainer implements IServerContainer {
100
-	/** @var string */
101
-	private $webRoot;
102
-
103
-	/**
104
-	 * @param string $webRoot
105
-	 * @param \OC\Config $config
106
-	 */
107
-	public function __construct($webRoot, \OC\Config $config) {
108
-		parent::__construct();
109
-		$this->webRoot = $webRoot;
110
-
111
-		$this->registerService('ContactsManager', function ($c) {
112
-			return new ContactsManager();
113
-		});
114
-
115
-		$this->registerService('PreviewManager', function (Server $c) {
116
-			return new PreviewManager($c->getConfig());
117
-		});
118
-
119
-		$this->registerService('EncryptionManager', function (Server $c) {
120
-			$view = new View();
121
-			$util = new Encryption\Util(
122
-				$view,
123
-				$c->getUserManager(),
124
-				$c->getGroupManager(),
125
-				$c->getConfig()
126
-			);
127
-			return new Encryption\Manager(
128
-				$c->getConfig(),
129
-				$c->getLogger(),
130
-				$c->getL10N('core'),
131
-				new View(),
132
-				$util,
133
-				new ArrayCache()
134
-			);
135
-		});
136
-
137
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
138
-			$util = new Encryption\Util(
139
-				new View(),
140
-				$c->getUserManager(),
141
-				$c->getGroupManager(),
142
-				$c->getConfig()
143
-			);
144
-			return new Encryption\File($util);
145
-		});
146
-
147
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
148
-			$view = new View();
149
-			$util = new Encryption\Util(
150
-				$view,
151
-				$c->getUserManager(),
152
-				$c->getGroupManager(),
153
-				$c->getConfig()
154
-			);
155
-
156
-			return new Encryption\Keys\Storage($view, $util);
157
-		});
158
-		$this->registerService('TagMapper', function (Server $c) {
159
-			return new TagMapper($c->getDatabaseConnection());
160
-		});
161
-		$this->registerService('TagManager', function (Server $c) {
162
-			$tagMapper = $c->query('TagMapper');
163
-			return new TagManager($tagMapper, $c->getUserSession());
164
-		});
165
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
166
-			$config = $c->getConfig();
167
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
168
-			/** @var \OC\SystemTag\ManagerFactory $factory */
169
-			$factory = new $factoryClass($this);
170
-			return $factory;
171
-		});
172
-		$this->registerService('SystemTagManager', function (Server $c) {
173
-			return $c->query('SystemTagManagerFactory')->getManager();
174
-		});
175
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
176
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
177
-		});
178
-		$this->registerService('RootFolder', function () {
179
-			$manager = \OC\Files\Filesystem::getMountManager(null);
180
-			$view = new View();
181
-			$root = new Root($manager, $view, null);
182
-			$connector = new HookConnector($root, $view);
183
-			$connector->viewToNode();
184
-			return $root;
185
-		});
186
-		$this->registerService('LazyRootFolder', function(Server $c) {
187
-			return new LazyRoot(function() use ($c) {
188
-				return $c->getRootFolder();
189
-			});
190
-		});
191
-		$this->registerService('UserManager', function (Server $c) {
192
-			$config = $c->getConfig();
193
-			return new \OC\User\Manager($config);
194
-		});
195
-		$this->registerService('GroupManager', function (Server $c) {
196
-			$groupManager = new \OC\Group\Manager($this->getUserManager());
197
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
198
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
199
-			});
200
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
201
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
202
-			});
203
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
204
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
205
-			});
206
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
207
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
208
-			});
209
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
210
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
211
-			});
212
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
213
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
214
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
215
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
216
-			});
217
-			return $groupManager;
218
-		});
219
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
220
-			$dbConnection = $c->getDatabaseConnection();
221
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
222
-		});
223
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
224
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
225
-			$crypto = $c->getCrypto();
226
-			$config = $c->getConfig();
227
-			$logger = $c->getLogger();
228
-			$timeFactory = new TimeFactory();
229
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
230
-		});
231
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
232
-		$this->registerService('UserSession', function (Server $c) {
233
-			$manager = $c->getUserManager();
234
-			$session = new \OC\Session\Memory('');
235
-			$timeFactory = new TimeFactory();
236
-			// Token providers might require a working database. This code
237
-			// might however be called when ownCloud is not yet setup.
238
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
239
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
240
-			} else {
241
-				$defaultTokenProvider = null;
242
-			}
243
-
244
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig());
245
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
246
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
247
-			});
248
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
249
-				/** @var $user \OC\User\User */
250
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
251
-			});
252
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
253
-				/** @var $user \OC\User\User */
254
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
255
-			});
256
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
257
-				/** @var $user \OC\User\User */
258
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
259
-			});
260
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
261
-				/** @var $user \OC\User\User */
262
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
263
-			});
264
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
265
-				/** @var $user \OC\User\User */
266
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
267
-			});
268
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
269
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
270
-			});
271
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
272
-				/** @var $user \OC\User\User */
273
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
274
-			});
275
-			$userSession->listen('\OC\User', 'logout', function () {
276
-				\OC_Hook::emit('OC_User', 'logout', array());
277
-			});
278
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
279
-				/** @var $user \OC\User\User */
280
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
281
-			});
282
-			return $userSession;
283
-		});
284
-
285
-		$this->registerService('\OC\Authentication\TwoFactorAuth\Manager', function (Server $c) {
286
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig());
287
-		});
288
-
289
-		$this->registerService('NavigationManager', function ($c) {
290
-			return new \OC\NavigationManager();
291
-		});
292
-		$this->registerService('AllConfig', function (Server $c) {
293
-			return new \OC\AllConfig(
294
-				$c->getSystemConfig()
295
-			);
296
-		});
297
-		$this->registerService('SystemConfig', function ($c) use ($config) {
298
-			return new \OC\SystemConfig($config);
299
-		});
300
-		$this->registerService('AppConfig', function (Server $c) {
301
-			return new \OC\AppConfig($c->getDatabaseConnection());
302
-		});
303
-		$this->registerService('L10NFactory', function (Server $c) {
304
-			return new \OC\L10N\Factory(
305
-				$c->getConfig(),
306
-				$c->getRequest(),
307
-				$c->getUserSession(),
308
-				\OC::$SERVERROOT
309
-			);
310
-		});
311
-		$this->registerService('URLGenerator', function (Server $c) {
312
-			$config = $c->getConfig();
313
-			$cacheFactory = $c->getMemCacheFactory();
314
-			return new \OC\URLGenerator(
315
-				$config,
316
-				$cacheFactory
317
-			);
318
-		});
319
-		$this->registerService('AppHelper', function ($c) {
320
-			return new \OC\AppHelper();
321
-		});
322
-		$this->registerService('UserCache', function ($c) {
323
-			return new Cache\File();
324
-		});
325
-		$this->registerService('MemCacheFactory', function (Server $c) {
326
-			$config = $c->getConfig();
327
-
328
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
329
-				$v = \OC_App::getAppVersions();
330
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
331
-				$version = implode(',', $v);
332
-				$instanceId = \OC_Util::getInstanceId();
333
-				$path = \OC::$SERVERROOT;
334
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
335
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
336
-					$config->getSystemValue('memcache.local', null),
337
-					$config->getSystemValue('memcache.distributed', null),
338
-					$config->getSystemValue('memcache.locking', null)
339
-				);
340
-			}
341
-
342
-			return new \OC\Memcache\Factory('', $c->getLogger(),
343
-				'\\OC\\Memcache\\ArrayCache',
344
-				'\\OC\\Memcache\\ArrayCache',
345
-				'\\OC\\Memcache\\ArrayCache'
346
-			);
347
-		});
348
-		$this->registerService('RedisFactory', function (Server $c) {
349
-			$systemConfig = $c->getSystemConfig();
350
-			return new RedisFactory($systemConfig);
351
-		});
352
-		$this->registerService('ActivityManager', function (Server $c) {
353
-			return new \OC\Activity\Manager(
354
-				$c->getRequest(),
355
-				$c->getUserSession(),
356
-				$c->getConfig()
357
-			);
358
-		});
359
-		$this->registerService('AvatarManager', function (Server $c) {
360
-			return new AvatarManager(
361
-				$c->getUserManager(),
362
-				$c->getLazyRootFolder(),
363
-				$c->getL10N('lib'),
364
-				$c->getLogger()
365
-			);
366
-		});
367
-		$this->registerService('Logger', function (Server $c) {
368
-			$logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud');
369
-			$logger = 'OC\\Log\\' . ucfirst($logClass);
370
-			call_user_func(array($logger, 'init'));
371
-
372
-			return new Log($logger);
373
-		});
374
-		$this->registerService('JobList', function (Server $c) {
375
-			$config = $c->getConfig();
376
-			return new \OC\BackgroundJob\JobList(
377
-				$c->getDatabaseConnection(),
378
-				$config,
379
-				new TimeFactory()
380
-			);
381
-		});
382
-		$this->registerService('Router', function (Server $c) {
383
-			$cacheFactory = $c->getMemCacheFactory();
384
-			$logger = $c->getLogger();
385
-			if ($cacheFactory->isAvailable()) {
386
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
387
-			} else {
388
-				$router = new \OC\Route\Router($logger);
389
-			}
390
-			return $router;
391
-		});
392
-		$this->registerService('Search', function ($c) {
393
-			return new Search();
394
-		});
395
-		$this->registerService('SecureRandom', function ($c) {
396
-			return new SecureRandom();
397
-		});
398
-		$this->registerService('Crypto', function (Server $c) {
399
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
400
-		});
401
-		$this->registerService('Hasher', function (Server $c) {
402
-			return new Hasher($c->getConfig());
403
-		});
404
-		$this->registerService('CredentialsManager', function (Server $c) {
405
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
406
-		});
407
-		$this->registerService('DatabaseConnection', function (Server $c) {
408
-			$factory = new \OC\DB\ConnectionFactory();
409
-			$systemConfig = $c->getSystemConfig();
410
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
411
-			if (!$factory->isValidType($type)) {
412
-				throw new \OC\DatabaseException('Invalid database type');
413
-			}
414
-			$connectionParams = $factory->createConnectionParams($systemConfig);
415
-			$connection = $factory->getConnection($type, $connectionParams);
416
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
417
-			return $connection;
418
-		});
419
-		$this->registerService('Db', function (Server $c) {
420
-			return new Db($c->getDatabaseConnection());
421
-		});
422
-		$this->registerService('HTTPHelper', function (Server $c) {
423
-			$config = $c->getConfig();
424
-			return new HTTPHelper(
425
-				$config,
426
-				$c->getHTTPClientService()
427
-			);
428
-		});
429
-		$this->registerService('HttpClientService', function (Server $c) {
430
-			$user = \OC_User::getUser();
431
-			$uid = $user ? $user : null;
432
-			return new ClientService(
433
-				$c->getConfig(),
434
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig())
435
-			);
436
-		});
437
-		$this->registerService('EventLogger', function (Server $c) {
438
-			if ($c->getSystemConfig()->getValue('debug', false)) {
439
-				return new EventLogger();
440
-			} else {
441
-				return new NullEventLogger();
442
-			}
443
-		});
444
-		$this->registerService('QueryLogger', function (Server $c) {
445
-			if ($c->getSystemConfig()->getValue('debug', false)) {
446
-				return new QueryLogger();
447
-			} else {
448
-				return new NullQueryLogger();
449
-			}
450
-		});
451
-		$this->registerService('TempManager', function (Server $c) {
452
-			return new TempManager(
453
-				$c->getLogger(),
454
-				$c->getConfig()
455
-			);
456
-		});
457
-		$this->registerService('AppManager', function (Server $c) {
458
-			return new \OC\App\AppManager(
459
-				$c->getUserSession(),
460
-				$c->getAppConfig(),
461
-				$c->getGroupManager(),
462
-				$c->getMemCacheFactory(),
463
-				$c->getEventDispatcher()
464
-			);
465
-		});
466
-		$this->registerService('DateTimeZone', function (Server $c) {
467
-			return new DateTimeZone(
468
-				$c->getConfig(),
469
-				$c->getSession()
470
-			);
471
-		});
472
-		$this->registerService('DateTimeFormatter', function (Server $c) {
473
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
474
-
475
-			return new DateTimeFormatter(
476
-				$c->getDateTimeZone()->getTimeZone(),
477
-				$c->getL10N('lib', $language)
478
-			);
479
-		});
480
-		$this->registerService('UserMountCache', function (Server $c) {
481
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
482
-			$listener = new UserMountCacheListener($mountCache);
483
-			$listener->listen($c->getUserManager());
484
-			return $mountCache;
485
-		});
486
-		$this->registerService('MountConfigManager', function (Server $c) {
487
-			$loader = \OC\Files\Filesystem::getLoader();
488
-			$mountCache = $c->query('UserMountCache');
489
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
490
-
491
-			// builtin providers
492
-
493
-			$config = $c->getConfig();
494
-			$manager->registerProvider(new CacheMountProvider($config));
495
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
496
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
497
-
498
-			return $manager;
499
-		});
500
-		$this->registerService('IniWrapper', function ($c) {
501
-			return new IniGetWrapper();
502
-		});
503
-		$this->registerService('AsyncCommandBus', function (Server $c) {
504
-			$jobList = $c->getJobList();
505
-			return new AsyncBus($jobList);
506
-		});
507
-		$this->registerService('TrustedDomainHelper', function ($c) {
508
-			return new TrustedDomainHelper($this->getConfig());
509
-		});
510
-		$this->registerService('Throttler', function(Server $c) {
511
-			return new Throttler(
512
-				$c->getDatabaseConnection(),
513
-				new TimeFactory(),
514
-				$c->getLogger(),
515
-				$c->getConfig()
516
-			);
517
-		});
518
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
519
-			// IConfig and IAppManager requires a working database. This code
520
-			// might however be called when ownCloud is not yet setup.
521
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
522
-				$config = $c->getConfig();
523
-				$appManager = $c->getAppManager();
524
-			} else {
525
-				$config = null;
526
-				$appManager = null;
527
-			}
528
-
529
-			return new Checker(
530
-					new EnvironmentHelper(),
531
-					new FileAccessHelper(),
532
-					new AppLocator(),
533
-					$config,
534
-					$c->getMemCacheFactory(),
535
-					$appManager,
536
-					$c->getTempManager()
537
-			);
538
-		});
539
-		$this->registerService('Request', function ($c) {
540
-			if (isset($this['urlParams'])) {
541
-				$urlParams = $this['urlParams'];
542
-			} else {
543
-				$urlParams = [];
544
-			}
545
-
546
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
547
-				&& in_array('fakeinput', stream_get_wrappers())
548
-			) {
549
-				$stream = 'fakeinput://data';
550
-			} else {
551
-				$stream = 'php://input';
552
-			}
553
-
554
-			return new Request(
555
-				[
556
-					'get' => $_GET,
557
-					'post' => $_POST,
558
-					'files' => $_FILES,
559
-					'server' => $_SERVER,
560
-					'env' => $_ENV,
561
-					'cookies' => $_COOKIE,
562
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
563
-						? $_SERVER['REQUEST_METHOD']
564
-						: null,
565
-					'urlParams' => $urlParams,
566
-				],
567
-				$this->getSecureRandom(),
568
-				$this->getConfig(),
569
-				$this->getCsrfTokenManager(),
570
-				$stream
571
-			);
572
-		});
573
-		$this->registerService('Mailer', function (Server $c) {
574
-			return new Mailer(
575
-				$c->getConfig(),
576
-				$c->getLogger(),
577
-				$c->getThemingDefaults()
578
-			);
579
-		});
580
-		$this->registerService('OcsClient', function (Server $c) {
581
-			return new OCSClient(
582
-				$this->getHTTPClientService(),
583
-				$this->getConfig(),
584
-				$this->getLogger()
585
-			);
586
-		});
587
-		$this->registerService('LDAPProvider', function(Server $c) {
588
-			$config = $c->getConfig();
589
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
590
-			if(is_null($factoryClass)) {
591
-				throw new \Exception('ldapProviderFactory not set');
592
-			}
593
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
594
-			$factory = new $factoryClass($this);
595
-			return $factory->getLDAPProvider();
596
-		});
597
-		$this->registerService('LockingProvider', function (Server $c) {
598
-			$ini = $c->getIniWrapper();
599
-			$config = $c->getConfig();
600
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
601
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
602
-				/** @var \OC\Memcache\Factory $memcacheFactory */
603
-				$memcacheFactory = $c->getMemCacheFactory();
604
-				$memcache = $memcacheFactory->createLocking('lock');
605
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
606
-					return new MemcacheLockingProvider($memcache, $ttl);
607
-				}
608
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
609
-			}
610
-			return new NoopLockingProvider();
611
-		});
612
-		$this->registerService('MountManager', function () {
613
-			return new \OC\Files\Mount\Manager();
614
-		});
615
-		$this->registerService('MimeTypeDetector', function (Server $c) {
616
-			return new \OC\Files\Type\Detection(
617
-				$c->getURLGenerator(),
618
-				\OC::$configDir,
619
-				\OC::$SERVERROOT . '/resources/config/'
620
-			);
621
-		});
622
-		$this->registerService('MimeTypeLoader', function (Server $c) {
623
-			return new \OC\Files\Type\Loader(
624
-				$c->getDatabaseConnection()
625
-			);
626
-		});
627
-		$this->registerService('NotificationManager', function () {
628
-			return new Manager();
629
-		});
630
-		$this->registerService('CapabilitiesManager', function (Server $c) {
631
-			$manager = new \OC\CapabilitiesManager();
632
-			$manager->registerCapability(function () use ($c) {
633
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
634
-			});
635
-			return $manager;
636
-		});
637
-		$this->registerService('CommentsManager', function(Server $c) {
638
-			$config = $c->getConfig();
639
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
640
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
641
-			$factory = new $factoryClass($this);
642
-			return $factory->getManager();
643
-		});
644
-		$this->registerService('ThemingDefaults', function(Server $c) {
645
-			/*
100
+    /** @var string */
101
+    private $webRoot;
102
+
103
+    /**
104
+     * @param string $webRoot
105
+     * @param \OC\Config $config
106
+     */
107
+    public function __construct($webRoot, \OC\Config $config) {
108
+        parent::__construct();
109
+        $this->webRoot = $webRoot;
110
+
111
+        $this->registerService('ContactsManager', function ($c) {
112
+            return new ContactsManager();
113
+        });
114
+
115
+        $this->registerService('PreviewManager', function (Server $c) {
116
+            return new PreviewManager($c->getConfig());
117
+        });
118
+
119
+        $this->registerService('EncryptionManager', function (Server $c) {
120
+            $view = new View();
121
+            $util = new Encryption\Util(
122
+                $view,
123
+                $c->getUserManager(),
124
+                $c->getGroupManager(),
125
+                $c->getConfig()
126
+            );
127
+            return new Encryption\Manager(
128
+                $c->getConfig(),
129
+                $c->getLogger(),
130
+                $c->getL10N('core'),
131
+                new View(),
132
+                $util,
133
+                new ArrayCache()
134
+            );
135
+        });
136
+
137
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
138
+            $util = new Encryption\Util(
139
+                new View(),
140
+                $c->getUserManager(),
141
+                $c->getGroupManager(),
142
+                $c->getConfig()
143
+            );
144
+            return new Encryption\File($util);
145
+        });
146
+
147
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
148
+            $view = new View();
149
+            $util = new Encryption\Util(
150
+                $view,
151
+                $c->getUserManager(),
152
+                $c->getGroupManager(),
153
+                $c->getConfig()
154
+            );
155
+
156
+            return new Encryption\Keys\Storage($view, $util);
157
+        });
158
+        $this->registerService('TagMapper', function (Server $c) {
159
+            return new TagMapper($c->getDatabaseConnection());
160
+        });
161
+        $this->registerService('TagManager', function (Server $c) {
162
+            $tagMapper = $c->query('TagMapper');
163
+            return new TagManager($tagMapper, $c->getUserSession());
164
+        });
165
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
166
+            $config = $c->getConfig();
167
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
168
+            /** @var \OC\SystemTag\ManagerFactory $factory */
169
+            $factory = new $factoryClass($this);
170
+            return $factory;
171
+        });
172
+        $this->registerService('SystemTagManager', function (Server $c) {
173
+            return $c->query('SystemTagManagerFactory')->getManager();
174
+        });
175
+        $this->registerService('SystemTagObjectMapper', function (Server $c) {
176
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
177
+        });
178
+        $this->registerService('RootFolder', function () {
179
+            $manager = \OC\Files\Filesystem::getMountManager(null);
180
+            $view = new View();
181
+            $root = new Root($manager, $view, null);
182
+            $connector = new HookConnector($root, $view);
183
+            $connector->viewToNode();
184
+            return $root;
185
+        });
186
+        $this->registerService('LazyRootFolder', function(Server $c) {
187
+            return new LazyRoot(function() use ($c) {
188
+                return $c->getRootFolder();
189
+            });
190
+        });
191
+        $this->registerService('UserManager', function (Server $c) {
192
+            $config = $c->getConfig();
193
+            return new \OC\User\Manager($config);
194
+        });
195
+        $this->registerService('GroupManager', function (Server $c) {
196
+            $groupManager = new \OC\Group\Manager($this->getUserManager());
197
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
198
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
199
+            });
200
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
201
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
202
+            });
203
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
204
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
205
+            });
206
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
207
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
208
+            });
209
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
210
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
211
+            });
212
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
213
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
214
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
215
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
216
+            });
217
+            return $groupManager;
218
+        });
219
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
220
+            $dbConnection = $c->getDatabaseConnection();
221
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
222
+        });
223
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
224
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
225
+            $crypto = $c->getCrypto();
226
+            $config = $c->getConfig();
227
+            $logger = $c->getLogger();
228
+            $timeFactory = new TimeFactory();
229
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
230
+        });
231
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
232
+        $this->registerService('UserSession', function (Server $c) {
233
+            $manager = $c->getUserManager();
234
+            $session = new \OC\Session\Memory('');
235
+            $timeFactory = new TimeFactory();
236
+            // Token providers might require a working database. This code
237
+            // might however be called when ownCloud is not yet setup.
238
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
239
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
240
+            } else {
241
+                $defaultTokenProvider = null;
242
+            }
243
+
244
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig());
245
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
246
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
247
+            });
248
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
249
+                /** @var $user \OC\User\User */
250
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
251
+            });
252
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
253
+                /** @var $user \OC\User\User */
254
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
255
+            });
256
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
257
+                /** @var $user \OC\User\User */
258
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
259
+            });
260
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
261
+                /** @var $user \OC\User\User */
262
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
263
+            });
264
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
265
+                /** @var $user \OC\User\User */
266
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
267
+            });
268
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
269
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
270
+            });
271
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
272
+                /** @var $user \OC\User\User */
273
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
274
+            });
275
+            $userSession->listen('\OC\User', 'logout', function () {
276
+                \OC_Hook::emit('OC_User', 'logout', array());
277
+            });
278
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
279
+                /** @var $user \OC\User\User */
280
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
281
+            });
282
+            return $userSession;
283
+        });
284
+
285
+        $this->registerService('\OC\Authentication\TwoFactorAuth\Manager', function (Server $c) {
286
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig());
287
+        });
288
+
289
+        $this->registerService('NavigationManager', function ($c) {
290
+            return new \OC\NavigationManager();
291
+        });
292
+        $this->registerService('AllConfig', function (Server $c) {
293
+            return new \OC\AllConfig(
294
+                $c->getSystemConfig()
295
+            );
296
+        });
297
+        $this->registerService('SystemConfig', function ($c) use ($config) {
298
+            return new \OC\SystemConfig($config);
299
+        });
300
+        $this->registerService('AppConfig', function (Server $c) {
301
+            return new \OC\AppConfig($c->getDatabaseConnection());
302
+        });
303
+        $this->registerService('L10NFactory', function (Server $c) {
304
+            return new \OC\L10N\Factory(
305
+                $c->getConfig(),
306
+                $c->getRequest(),
307
+                $c->getUserSession(),
308
+                \OC::$SERVERROOT
309
+            );
310
+        });
311
+        $this->registerService('URLGenerator', function (Server $c) {
312
+            $config = $c->getConfig();
313
+            $cacheFactory = $c->getMemCacheFactory();
314
+            return new \OC\URLGenerator(
315
+                $config,
316
+                $cacheFactory
317
+            );
318
+        });
319
+        $this->registerService('AppHelper', function ($c) {
320
+            return new \OC\AppHelper();
321
+        });
322
+        $this->registerService('UserCache', function ($c) {
323
+            return new Cache\File();
324
+        });
325
+        $this->registerService('MemCacheFactory', function (Server $c) {
326
+            $config = $c->getConfig();
327
+
328
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
329
+                $v = \OC_App::getAppVersions();
330
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
331
+                $version = implode(',', $v);
332
+                $instanceId = \OC_Util::getInstanceId();
333
+                $path = \OC::$SERVERROOT;
334
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
335
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
336
+                    $config->getSystemValue('memcache.local', null),
337
+                    $config->getSystemValue('memcache.distributed', null),
338
+                    $config->getSystemValue('memcache.locking', null)
339
+                );
340
+            }
341
+
342
+            return new \OC\Memcache\Factory('', $c->getLogger(),
343
+                '\\OC\\Memcache\\ArrayCache',
344
+                '\\OC\\Memcache\\ArrayCache',
345
+                '\\OC\\Memcache\\ArrayCache'
346
+            );
347
+        });
348
+        $this->registerService('RedisFactory', function (Server $c) {
349
+            $systemConfig = $c->getSystemConfig();
350
+            return new RedisFactory($systemConfig);
351
+        });
352
+        $this->registerService('ActivityManager', function (Server $c) {
353
+            return new \OC\Activity\Manager(
354
+                $c->getRequest(),
355
+                $c->getUserSession(),
356
+                $c->getConfig()
357
+            );
358
+        });
359
+        $this->registerService('AvatarManager', function (Server $c) {
360
+            return new AvatarManager(
361
+                $c->getUserManager(),
362
+                $c->getLazyRootFolder(),
363
+                $c->getL10N('lib'),
364
+                $c->getLogger()
365
+            );
366
+        });
367
+        $this->registerService('Logger', function (Server $c) {
368
+            $logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud');
369
+            $logger = 'OC\\Log\\' . ucfirst($logClass);
370
+            call_user_func(array($logger, 'init'));
371
+
372
+            return new Log($logger);
373
+        });
374
+        $this->registerService('JobList', function (Server $c) {
375
+            $config = $c->getConfig();
376
+            return new \OC\BackgroundJob\JobList(
377
+                $c->getDatabaseConnection(),
378
+                $config,
379
+                new TimeFactory()
380
+            );
381
+        });
382
+        $this->registerService('Router', function (Server $c) {
383
+            $cacheFactory = $c->getMemCacheFactory();
384
+            $logger = $c->getLogger();
385
+            if ($cacheFactory->isAvailable()) {
386
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
387
+            } else {
388
+                $router = new \OC\Route\Router($logger);
389
+            }
390
+            return $router;
391
+        });
392
+        $this->registerService('Search', function ($c) {
393
+            return new Search();
394
+        });
395
+        $this->registerService('SecureRandom', function ($c) {
396
+            return new SecureRandom();
397
+        });
398
+        $this->registerService('Crypto', function (Server $c) {
399
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
400
+        });
401
+        $this->registerService('Hasher', function (Server $c) {
402
+            return new Hasher($c->getConfig());
403
+        });
404
+        $this->registerService('CredentialsManager', function (Server $c) {
405
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
406
+        });
407
+        $this->registerService('DatabaseConnection', function (Server $c) {
408
+            $factory = new \OC\DB\ConnectionFactory();
409
+            $systemConfig = $c->getSystemConfig();
410
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
411
+            if (!$factory->isValidType($type)) {
412
+                throw new \OC\DatabaseException('Invalid database type');
413
+            }
414
+            $connectionParams = $factory->createConnectionParams($systemConfig);
415
+            $connection = $factory->getConnection($type, $connectionParams);
416
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
417
+            return $connection;
418
+        });
419
+        $this->registerService('Db', function (Server $c) {
420
+            return new Db($c->getDatabaseConnection());
421
+        });
422
+        $this->registerService('HTTPHelper', function (Server $c) {
423
+            $config = $c->getConfig();
424
+            return new HTTPHelper(
425
+                $config,
426
+                $c->getHTTPClientService()
427
+            );
428
+        });
429
+        $this->registerService('HttpClientService', function (Server $c) {
430
+            $user = \OC_User::getUser();
431
+            $uid = $user ? $user : null;
432
+            return new ClientService(
433
+                $c->getConfig(),
434
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig())
435
+            );
436
+        });
437
+        $this->registerService('EventLogger', function (Server $c) {
438
+            if ($c->getSystemConfig()->getValue('debug', false)) {
439
+                return new EventLogger();
440
+            } else {
441
+                return new NullEventLogger();
442
+            }
443
+        });
444
+        $this->registerService('QueryLogger', function (Server $c) {
445
+            if ($c->getSystemConfig()->getValue('debug', false)) {
446
+                return new QueryLogger();
447
+            } else {
448
+                return new NullQueryLogger();
449
+            }
450
+        });
451
+        $this->registerService('TempManager', function (Server $c) {
452
+            return new TempManager(
453
+                $c->getLogger(),
454
+                $c->getConfig()
455
+            );
456
+        });
457
+        $this->registerService('AppManager', function (Server $c) {
458
+            return new \OC\App\AppManager(
459
+                $c->getUserSession(),
460
+                $c->getAppConfig(),
461
+                $c->getGroupManager(),
462
+                $c->getMemCacheFactory(),
463
+                $c->getEventDispatcher()
464
+            );
465
+        });
466
+        $this->registerService('DateTimeZone', function (Server $c) {
467
+            return new DateTimeZone(
468
+                $c->getConfig(),
469
+                $c->getSession()
470
+            );
471
+        });
472
+        $this->registerService('DateTimeFormatter', function (Server $c) {
473
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
474
+
475
+            return new DateTimeFormatter(
476
+                $c->getDateTimeZone()->getTimeZone(),
477
+                $c->getL10N('lib', $language)
478
+            );
479
+        });
480
+        $this->registerService('UserMountCache', function (Server $c) {
481
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
482
+            $listener = new UserMountCacheListener($mountCache);
483
+            $listener->listen($c->getUserManager());
484
+            return $mountCache;
485
+        });
486
+        $this->registerService('MountConfigManager', function (Server $c) {
487
+            $loader = \OC\Files\Filesystem::getLoader();
488
+            $mountCache = $c->query('UserMountCache');
489
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
490
+
491
+            // builtin providers
492
+
493
+            $config = $c->getConfig();
494
+            $manager->registerProvider(new CacheMountProvider($config));
495
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
496
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
497
+
498
+            return $manager;
499
+        });
500
+        $this->registerService('IniWrapper', function ($c) {
501
+            return new IniGetWrapper();
502
+        });
503
+        $this->registerService('AsyncCommandBus', function (Server $c) {
504
+            $jobList = $c->getJobList();
505
+            return new AsyncBus($jobList);
506
+        });
507
+        $this->registerService('TrustedDomainHelper', function ($c) {
508
+            return new TrustedDomainHelper($this->getConfig());
509
+        });
510
+        $this->registerService('Throttler', function(Server $c) {
511
+            return new Throttler(
512
+                $c->getDatabaseConnection(),
513
+                new TimeFactory(),
514
+                $c->getLogger(),
515
+                $c->getConfig()
516
+            );
517
+        });
518
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
519
+            // IConfig and IAppManager requires a working database. This code
520
+            // might however be called when ownCloud is not yet setup.
521
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
522
+                $config = $c->getConfig();
523
+                $appManager = $c->getAppManager();
524
+            } else {
525
+                $config = null;
526
+                $appManager = null;
527
+            }
528
+
529
+            return new Checker(
530
+                    new EnvironmentHelper(),
531
+                    new FileAccessHelper(),
532
+                    new AppLocator(),
533
+                    $config,
534
+                    $c->getMemCacheFactory(),
535
+                    $appManager,
536
+                    $c->getTempManager()
537
+            );
538
+        });
539
+        $this->registerService('Request', function ($c) {
540
+            if (isset($this['urlParams'])) {
541
+                $urlParams = $this['urlParams'];
542
+            } else {
543
+                $urlParams = [];
544
+            }
545
+
546
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
547
+                && in_array('fakeinput', stream_get_wrappers())
548
+            ) {
549
+                $stream = 'fakeinput://data';
550
+            } else {
551
+                $stream = 'php://input';
552
+            }
553
+
554
+            return new Request(
555
+                [
556
+                    'get' => $_GET,
557
+                    'post' => $_POST,
558
+                    'files' => $_FILES,
559
+                    'server' => $_SERVER,
560
+                    'env' => $_ENV,
561
+                    'cookies' => $_COOKIE,
562
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
563
+                        ? $_SERVER['REQUEST_METHOD']
564
+                        : null,
565
+                    'urlParams' => $urlParams,
566
+                ],
567
+                $this->getSecureRandom(),
568
+                $this->getConfig(),
569
+                $this->getCsrfTokenManager(),
570
+                $stream
571
+            );
572
+        });
573
+        $this->registerService('Mailer', function (Server $c) {
574
+            return new Mailer(
575
+                $c->getConfig(),
576
+                $c->getLogger(),
577
+                $c->getThemingDefaults()
578
+            );
579
+        });
580
+        $this->registerService('OcsClient', function (Server $c) {
581
+            return new OCSClient(
582
+                $this->getHTTPClientService(),
583
+                $this->getConfig(),
584
+                $this->getLogger()
585
+            );
586
+        });
587
+        $this->registerService('LDAPProvider', function(Server $c) {
588
+            $config = $c->getConfig();
589
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
590
+            if(is_null($factoryClass)) {
591
+                throw new \Exception('ldapProviderFactory not set');
592
+            }
593
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
594
+            $factory = new $factoryClass($this);
595
+            return $factory->getLDAPProvider();
596
+        });
597
+        $this->registerService('LockingProvider', function (Server $c) {
598
+            $ini = $c->getIniWrapper();
599
+            $config = $c->getConfig();
600
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
601
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
602
+                /** @var \OC\Memcache\Factory $memcacheFactory */
603
+                $memcacheFactory = $c->getMemCacheFactory();
604
+                $memcache = $memcacheFactory->createLocking('lock');
605
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
606
+                    return new MemcacheLockingProvider($memcache, $ttl);
607
+                }
608
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
609
+            }
610
+            return new NoopLockingProvider();
611
+        });
612
+        $this->registerService('MountManager', function () {
613
+            return new \OC\Files\Mount\Manager();
614
+        });
615
+        $this->registerService('MimeTypeDetector', function (Server $c) {
616
+            return new \OC\Files\Type\Detection(
617
+                $c->getURLGenerator(),
618
+                \OC::$configDir,
619
+                \OC::$SERVERROOT . '/resources/config/'
620
+            );
621
+        });
622
+        $this->registerService('MimeTypeLoader', function (Server $c) {
623
+            return new \OC\Files\Type\Loader(
624
+                $c->getDatabaseConnection()
625
+            );
626
+        });
627
+        $this->registerService('NotificationManager', function () {
628
+            return new Manager();
629
+        });
630
+        $this->registerService('CapabilitiesManager', function (Server $c) {
631
+            $manager = new \OC\CapabilitiesManager();
632
+            $manager->registerCapability(function () use ($c) {
633
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
634
+            });
635
+            return $manager;
636
+        });
637
+        $this->registerService('CommentsManager', function(Server $c) {
638
+            $config = $c->getConfig();
639
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
640
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
641
+            $factory = new $factoryClass($this);
642
+            return $factory->getManager();
643
+        });
644
+        $this->registerService('ThemingDefaults', function(Server $c) {
645
+            /*
646 646
 			 * Dark magic for autoloader.
647 647
 			 * If we do a class_exists it will try to load the class which will
648 648
 			 * make composer cache the result. Resulting in errors when enabling
649 649
 			 * the theming app.
650 650
 			 */
651
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
652
-			if (isset($prefixes['OCA\\Theming\\'])) {
653
-				$classExists = true;
654
-			} else {
655
-				$classExists = false;
656
-			}
657
-
658
-			if ($classExists && $this->getConfig()->getSystemValue('installed', false) && $this->getAppManager()->isInstalled('theming')) {
659
-				return new ThemingDefaults(
660
-					$this->getConfig(),
661
-					$this->getL10N('theming'),
662
-					$this->getURLGenerator(),
663
-					new \OC_Defaults()
664
-				);
665
-			}
666
-			return new \OC_Defaults();
667
-		});
668
-		$this->registerService('EventDispatcher', function () {
669
-			return new EventDispatcher();
670
-		});
671
-		$this->registerService('CryptoWrapper', function (Server $c) {
672
-			// FIXME: Instantiiated here due to cyclic dependency
673
-			$request = new Request(
674
-				[
675
-					'get' => $_GET,
676
-					'post' => $_POST,
677
-					'files' => $_FILES,
678
-					'server' => $_SERVER,
679
-					'env' => $_ENV,
680
-					'cookies' => $_COOKIE,
681
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
682
-						? $_SERVER['REQUEST_METHOD']
683
-						: null,
684
-				],
685
-				$c->getSecureRandom(),
686
-				$c->getConfig()
687
-			);
688
-
689
-			return new CryptoWrapper(
690
-				$c->getConfig(),
691
-				$c->getCrypto(),
692
-				$c->getSecureRandom(),
693
-				$request
694
-			);
695
-		});
696
-		$this->registerService('CsrfTokenManager', function (Server $c) {
697
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
698
-			$sessionStorage = new SessionStorage($c->getSession());
699
-
700
-			return new CsrfTokenManager(
701
-				$tokenGenerator,
702
-				$sessionStorage
703
-			);
704
-		});
705
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
706
-			return new ContentSecurityPolicyManager();
707
-		});
708
-		$this->registerService('ShareManager', function(Server $c) {
709
-			$config = $c->getConfig();
710
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
711
-			/** @var \OCP\Share\IProviderFactory $factory */
712
-			$factory = new $factoryClass($this);
713
-
714
-			$manager = new \OC\Share20\Manager(
715
-				$c->getLogger(),
716
-				$c->getConfig(),
717
-				$c->getSecureRandom(),
718
-				$c->getHasher(),
719
-				$c->getMountManager(),
720
-				$c->getGroupManager(),
721
-				$c->getL10N('core'),
722
-				$factory,
723
-				$c->getUserManager(),
724
-				$c->getLazyRootFolder(),
725
-				$c->getEventDispatcher()
726
-			);
727
-
728
-			return $manager;
729
-		});
730
-		$this->registerService('SettingsManager', function(Server $c) {
731
-			$manager = new \OC\Settings\Manager(
732
-				$c->getLogger(),
733
-				$c->getDatabaseConnection(),
734
-				$c->getL10N('lib'),
735
-				$c->getConfig(),
736
-				$c->getEncryptionManager(),
737
-				$c->getUserManager(),
738
-				$c->getLockingProvider()
739
-			);
740
-			return $manager;
741
-		});
742
-	}
743
-
744
-	/**
745
-	 * @return \OCP\Contacts\IManager
746
-	 */
747
-	public function getContactsManager() {
748
-		return $this->query('ContactsManager');
749
-	}
750
-
751
-	/**
752
-	 * @return \OC\Encryption\Manager
753
-	 */
754
-	public function getEncryptionManager() {
755
-		return $this->query('EncryptionManager');
756
-	}
757
-
758
-	/**
759
-	 * @return \OC\Encryption\File
760
-	 */
761
-	public function getEncryptionFilesHelper() {
762
-		return $this->query('EncryptionFileHelper');
763
-	}
764
-
765
-	/**
766
-	 * @return \OCP\Encryption\Keys\IStorage
767
-	 */
768
-	public function getEncryptionKeyStorage() {
769
-		return $this->query('EncryptionKeyStorage');
770
-	}
771
-
772
-	/**
773
-	 * The current request object holding all information about the request
774
-	 * currently being processed is returned from this method.
775
-	 * In case the current execution was not initiated by a web request null is returned
776
-	 *
777
-	 * @return \OCP\IRequest
778
-	 */
779
-	public function getRequest() {
780
-		return $this->query('Request');
781
-	}
782
-
783
-	/**
784
-	 * Returns the preview manager which can create preview images for a given file
785
-	 *
786
-	 * @return \OCP\IPreview
787
-	 */
788
-	public function getPreviewManager() {
789
-		return $this->query('PreviewManager');
790
-	}
791
-
792
-	/**
793
-	 * Returns the tag manager which can get and set tags for different object types
794
-	 *
795
-	 * @see \OCP\ITagManager::load()
796
-	 * @return \OCP\ITagManager
797
-	 */
798
-	public function getTagManager() {
799
-		return $this->query('TagManager');
800
-	}
801
-
802
-	/**
803
-	 * Returns the system-tag manager
804
-	 *
805
-	 * @return \OCP\SystemTag\ISystemTagManager
806
-	 *
807
-	 * @since 9.0.0
808
-	 */
809
-	public function getSystemTagManager() {
810
-		return $this->query('SystemTagManager');
811
-	}
812
-
813
-	/**
814
-	 * Returns the system-tag object mapper
815
-	 *
816
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
817
-	 *
818
-	 * @since 9.0.0
819
-	 */
820
-	public function getSystemTagObjectMapper() {
821
-		return $this->query('SystemTagObjectMapper');
822
-	}
823
-
824
-
825
-	/**
826
-	 * Returns the avatar manager, used for avatar functionality
827
-	 *
828
-	 * @return \OCP\IAvatarManager
829
-	 */
830
-	public function getAvatarManager() {
831
-		return $this->query('AvatarManager');
832
-	}
833
-
834
-	/**
835
-	 * Returns the root folder of ownCloud's data directory
836
-	 *
837
-	 * @return \OCP\Files\IRootFolder
838
-	 */
839
-	public function getRootFolder() {
840
-		return $this->query('RootFolder');
841
-	}
842
-
843
-	/**
844
-	 * Returns the root folder of ownCloud's data directory
845
-	 * This is the lazy variant so this gets only initialized once it
846
-	 * is actually used.
847
-	 *
848
-	 * @return \OCP\Files\IRootFolder
849
-	 */
850
-	public function getLazyRootFolder() {
851
-		return $this->query('LazyRootFolder');
852
-	}
853
-
854
-	/**
855
-	 * Returns a view to ownCloud's files folder
856
-	 *
857
-	 * @param string $userId user ID
858
-	 * @return \OCP\Files\Folder|null
859
-	 */
860
-	public function getUserFolder($userId = null) {
861
-		if ($userId === null) {
862
-			$user = $this->getUserSession()->getUser();
863
-			if (!$user) {
864
-				return null;
865
-			}
866
-			$userId = $user->getUID();
867
-		}
868
-		$root = $this->getRootFolder();
869
-		return $root->getUserFolder($userId);
870
-	}
871
-
872
-	/**
873
-	 * Returns an app-specific view in ownClouds data directory
874
-	 *
875
-	 * @return \OCP\Files\Folder
876
-	 */
877
-	public function getAppFolder() {
878
-		$dir = '/' . \OC_App::getCurrentApp();
879
-		$root = $this->getRootFolder();
880
-		if (!$root->nodeExists($dir)) {
881
-			$folder = $root->newFolder($dir);
882
-		} else {
883
-			$folder = $root->get($dir);
884
-		}
885
-		return $folder;
886
-	}
887
-
888
-	/**
889
-	 * @return \OC\User\Manager
890
-	 */
891
-	public function getUserManager() {
892
-		return $this->query('UserManager');
893
-	}
894
-
895
-	/**
896
-	 * @return \OC\Group\Manager
897
-	 */
898
-	public function getGroupManager() {
899
-		return $this->query('GroupManager');
900
-	}
901
-
902
-	/**
903
-	 * @return \OC\User\Session
904
-	 */
905
-	public function getUserSession() {
906
-		return $this->query('UserSession');
907
-	}
908
-
909
-	/**
910
-	 * @return \OCP\ISession
911
-	 */
912
-	public function getSession() {
913
-		return $this->query('UserSession')->getSession();
914
-	}
915
-
916
-	/**
917
-	 * @param \OCP\ISession $session
918
-	 */
919
-	public function setSession(\OCP\ISession $session) {
920
-		return $this->query('UserSession')->setSession($session);
921
-	}
922
-
923
-	/**
924
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
925
-	 */
926
-	public function getTwoFactorAuthManager() {
927
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
928
-	}
929
-
930
-	/**
931
-	 * @return \OC\NavigationManager
932
-	 */
933
-	public function getNavigationManager() {
934
-		return $this->query('NavigationManager');
935
-	}
936
-
937
-	/**
938
-	 * @return \OCP\IConfig
939
-	 */
940
-	public function getConfig() {
941
-		return $this->query('AllConfig');
942
-	}
943
-
944
-	/**
945
-	 * @internal For internal use only
946
-	 * @return \OC\SystemConfig
947
-	 */
948
-	public function getSystemConfig() {
949
-		return $this->query('SystemConfig');
950
-	}
951
-
952
-	/**
953
-	 * Returns the app config manager
954
-	 *
955
-	 * @return \OCP\IAppConfig
956
-	 */
957
-	public function getAppConfig() {
958
-		return $this->query('AppConfig');
959
-	}
960
-
961
-	/**
962
-	 * @return \OCP\L10N\IFactory
963
-	 */
964
-	public function getL10NFactory() {
965
-		return $this->query('L10NFactory');
966
-	}
967
-
968
-	/**
969
-	 * get an L10N instance
970
-	 *
971
-	 * @param string $app appid
972
-	 * @param string $lang
973
-	 * @return IL10N
974
-	 */
975
-	public function getL10N($app, $lang = null) {
976
-		return $this->getL10NFactory()->get($app, $lang);
977
-	}
978
-
979
-	/**
980
-	 * @return \OCP\IURLGenerator
981
-	 */
982
-	public function getURLGenerator() {
983
-		return $this->query('URLGenerator');
984
-	}
985
-
986
-	/**
987
-	 * @return \OCP\IHelper
988
-	 */
989
-	public function getHelper() {
990
-		return $this->query('AppHelper');
991
-	}
992
-
993
-	/**
994
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
995
-	 * getMemCacheFactory() instead.
996
-	 *
997
-	 * @return \OCP\ICache
998
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
999
-	 */
1000
-	public function getCache() {
1001
-		return $this->query('UserCache');
1002
-	}
1003
-
1004
-	/**
1005
-	 * Returns an \OCP\CacheFactory instance
1006
-	 *
1007
-	 * @return \OCP\ICacheFactory
1008
-	 */
1009
-	public function getMemCacheFactory() {
1010
-		return $this->query('MemCacheFactory');
1011
-	}
1012
-
1013
-	/**
1014
-	 * Returns an \OC\RedisFactory instance
1015
-	 *
1016
-	 * @return \OC\RedisFactory
1017
-	 */
1018
-	public function getGetRedisFactory() {
1019
-		return $this->query('RedisFactory');
1020
-	}
1021
-
1022
-
1023
-	/**
1024
-	 * Returns the current session
1025
-	 *
1026
-	 * @return \OCP\IDBConnection
1027
-	 */
1028
-	public function getDatabaseConnection() {
1029
-		return $this->query('DatabaseConnection');
1030
-	}
1031
-
1032
-	/**
1033
-	 * Returns the activity manager
1034
-	 *
1035
-	 * @return \OCP\Activity\IManager
1036
-	 */
1037
-	public function getActivityManager() {
1038
-		return $this->query('ActivityManager');
1039
-	}
1040
-
1041
-	/**
1042
-	 * Returns an job list for controlling background jobs
1043
-	 *
1044
-	 * @return \OCP\BackgroundJob\IJobList
1045
-	 */
1046
-	public function getJobList() {
1047
-		return $this->query('JobList');
1048
-	}
1049
-
1050
-	/**
1051
-	 * Returns a logger instance
1052
-	 *
1053
-	 * @return \OCP\ILogger
1054
-	 */
1055
-	public function getLogger() {
1056
-		return $this->query('Logger');
1057
-	}
1058
-
1059
-	/**
1060
-	 * Returns a router for generating and matching urls
1061
-	 *
1062
-	 * @return \OCP\Route\IRouter
1063
-	 */
1064
-	public function getRouter() {
1065
-		return $this->query('Router');
1066
-	}
1067
-
1068
-	/**
1069
-	 * Returns a search instance
1070
-	 *
1071
-	 * @return \OCP\ISearch
1072
-	 */
1073
-	public function getSearch() {
1074
-		return $this->query('Search');
1075
-	}
1076
-
1077
-	/**
1078
-	 * Returns a SecureRandom instance
1079
-	 *
1080
-	 * @return \OCP\Security\ISecureRandom
1081
-	 */
1082
-	public function getSecureRandom() {
1083
-		return $this->query('SecureRandom');
1084
-	}
1085
-
1086
-	/**
1087
-	 * Returns a Crypto instance
1088
-	 *
1089
-	 * @return \OCP\Security\ICrypto
1090
-	 */
1091
-	public function getCrypto() {
1092
-		return $this->query('Crypto');
1093
-	}
1094
-
1095
-	/**
1096
-	 * Returns a Hasher instance
1097
-	 *
1098
-	 * @return \OCP\Security\IHasher
1099
-	 */
1100
-	public function getHasher() {
1101
-		return $this->query('Hasher');
1102
-	}
1103
-
1104
-	/**
1105
-	 * Returns a CredentialsManager instance
1106
-	 *
1107
-	 * @return \OCP\Security\ICredentialsManager
1108
-	 */
1109
-	public function getCredentialsManager() {
1110
-		return $this->query('CredentialsManager');
1111
-	}
1112
-
1113
-	/**
1114
-	 * Returns an instance of the db facade
1115
-	 *
1116
-	 * @deprecated use getDatabaseConnection, will be removed in ownCloud 10
1117
-	 * @return \OCP\IDb
1118
-	 */
1119
-	public function getDb() {
1120
-		return $this->query('Db');
1121
-	}
1122
-
1123
-	/**
1124
-	 * Returns an instance of the HTTP helper class
1125
-	 *
1126
-	 * @deprecated Use getHTTPClientService()
1127
-	 * @return \OC\HTTPHelper
1128
-	 */
1129
-	public function getHTTPHelper() {
1130
-		return $this->query('HTTPHelper');
1131
-	}
1132
-
1133
-	/**
1134
-	 * Get the certificate manager for the user
1135
-	 *
1136
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1137
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1138
-	 */
1139
-	public function getCertificateManager($userId = '') {
1140
-		if ($userId === '') {
1141
-			$userSession = $this->getUserSession();
1142
-			$user = $userSession->getUser();
1143
-			if (is_null($user)) {
1144
-				return null;
1145
-			}
1146
-			$userId = $user->getUID();
1147
-		}
1148
-		return new CertificateManager($userId, new View(), $this->getConfig());
1149
-	}
1150
-
1151
-	/**
1152
-	 * Returns an instance of the HTTP client service
1153
-	 *
1154
-	 * @return \OCP\Http\Client\IClientService
1155
-	 */
1156
-	public function getHTTPClientService() {
1157
-		return $this->query('HttpClientService');
1158
-	}
1159
-
1160
-	/**
1161
-	 * Create a new event source
1162
-	 *
1163
-	 * @return \OCP\IEventSource
1164
-	 */
1165
-	public function createEventSource() {
1166
-		return new \OC_EventSource();
1167
-	}
1168
-
1169
-	/**
1170
-	 * Get the active event logger
1171
-	 *
1172
-	 * The returned logger only logs data when debug mode is enabled
1173
-	 *
1174
-	 * @return \OCP\Diagnostics\IEventLogger
1175
-	 */
1176
-	public function getEventLogger() {
1177
-		return $this->query('EventLogger');
1178
-	}
1179
-
1180
-	/**
1181
-	 * Get the active query logger
1182
-	 *
1183
-	 * The returned logger only logs data when debug mode is enabled
1184
-	 *
1185
-	 * @return \OCP\Diagnostics\IQueryLogger
1186
-	 */
1187
-	public function getQueryLogger() {
1188
-		return $this->query('QueryLogger');
1189
-	}
1190
-
1191
-	/**
1192
-	 * Get the manager for temporary files and folders
1193
-	 *
1194
-	 * @return \OCP\ITempManager
1195
-	 */
1196
-	public function getTempManager() {
1197
-		return $this->query('TempManager');
1198
-	}
1199
-
1200
-	/**
1201
-	 * Get the app manager
1202
-	 *
1203
-	 * @return \OCP\App\IAppManager
1204
-	 */
1205
-	public function getAppManager() {
1206
-		return $this->query('AppManager');
1207
-	}
1208
-
1209
-	/**
1210
-	 * Creates a new mailer
1211
-	 *
1212
-	 * @return \OCP\Mail\IMailer
1213
-	 */
1214
-	public function getMailer() {
1215
-		return $this->query('Mailer');
1216
-	}
1217
-
1218
-	/**
1219
-	 * Get the webroot
1220
-	 *
1221
-	 * @return string
1222
-	 */
1223
-	public function getWebRoot() {
1224
-		return $this->webRoot;
1225
-	}
1226
-
1227
-	/**
1228
-	 * @return \OC\OCSClient
1229
-	 */
1230
-	public function getOcsClient() {
1231
-		return $this->query('OcsClient');
1232
-	}
1233
-
1234
-	/**
1235
-	 * @return \OCP\IDateTimeZone
1236
-	 */
1237
-	public function getDateTimeZone() {
1238
-		return $this->query('DateTimeZone');
1239
-	}
1240
-
1241
-	/**
1242
-	 * @return \OCP\IDateTimeFormatter
1243
-	 */
1244
-	public function getDateTimeFormatter() {
1245
-		return $this->query('DateTimeFormatter');
1246
-	}
1247
-
1248
-	/**
1249
-	 * @return \OCP\Files\Config\IMountProviderCollection
1250
-	 */
1251
-	public function getMountProviderCollection() {
1252
-		return $this->query('MountConfigManager');
1253
-	}
1254
-
1255
-	/**
1256
-	 * Get the IniWrapper
1257
-	 *
1258
-	 * @return IniGetWrapper
1259
-	 */
1260
-	public function getIniWrapper() {
1261
-		return $this->query('IniWrapper');
1262
-	}
1263
-
1264
-	/**
1265
-	 * @return \OCP\Command\IBus
1266
-	 */
1267
-	public function getCommandBus() {
1268
-		return $this->query('AsyncCommandBus');
1269
-	}
1270
-
1271
-	/**
1272
-	 * Get the trusted domain helper
1273
-	 *
1274
-	 * @return TrustedDomainHelper
1275
-	 */
1276
-	public function getTrustedDomainHelper() {
1277
-		return $this->query('TrustedDomainHelper');
1278
-	}
1279
-
1280
-	/**
1281
-	 * Get the locking provider
1282
-	 *
1283
-	 * @return \OCP\Lock\ILockingProvider
1284
-	 * @since 8.1.0
1285
-	 */
1286
-	public function getLockingProvider() {
1287
-		return $this->query('LockingProvider');
1288
-	}
1289
-
1290
-	/**
1291
-	 * @return \OCP\Files\Mount\IMountManager
1292
-	 **/
1293
-	function getMountManager() {
1294
-		return $this->query('MountManager');
1295
-	}
1296
-
1297
-	/** @return \OCP\Files\Config\IUserMountCache */
1298
-	function getUserMountCache() {
1299
-		return $this->query('UserMountCache');
1300
-	}
1301
-
1302
-	/**
1303
-	 * Get the MimeTypeDetector
1304
-	 *
1305
-	 * @return \OCP\Files\IMimeTypeDetector
1306
-	 */
1307
-	public function getMimeTypeDetector() {
1308
-		return $this->query('MimeTypeDetector');
1309
-	}
1310
-
1311
-	/**
1312
-	 * Get the MimeTypeLoader
1313
-	 *
1314
-	 * @return \OCP\Files\IMimeTypeLoader
1315
-	 */
1316
-	public function getMimeTypeLoader() {
1317
-		return $this->query('MimeTypeLoader');
1318
-	}
1319
-
1320
-	/**
1321
-	 * Get the manager of all the capabilities
1322
-	 *
1323
-	 * @return \OC\CapabilitiesManager
1324
-	 */
1325
-	public function getCapabilitiesManager() {
1326
-		return $this->query('CapabilitiesManager');
1327
-	}
1328
-
1329
-	/**
1330
-	 * Get the EventDispatcher
1331
-	 *
1332
-	 * @return EventDispatcherInterface
1333
-	 * @since 8.2.0
1334
-	 */
1335
-	public function getEventDispatcher() {
1336
-		return $this->query('EventDispatcher');
1337
-	}
1338
-
1339
-	/**
1340
-	 * Get the Notification Manager
1341
-	 *
1342
-	 * @return \OCP\Notification\IManager
1343
-	 * @since 8.2.0
1344
-	 */
1345
-	public function getNotificationManager() {
1346
-		return $this->query('NotificationManager');
1347
-	}
1348
-
1349
-	/**
1350
-	 * @return \OCP\Comments\ICommentsManager
1351
-	 */
1352
-	public function getCommentsManager() {
1353
-		return $this->query('CommentsManager');
1354
-	}
1355
-
1356
-	/**
1357
-	 * @internal Not public by intention.
1358
-	 * @return \OC_Defaults
1359
-	 */
1360
-	public function getThemingDefaults() {
1361
-		return $this->query('ThemingDefaults');
1362
-	}
1363
-
1364
-	/**
1365
-	 * @return \OC\IntegrityCheck\Checker
1366
-	 */
1367
-	public function getIntegrityCodeChecker() {
1368
-		return $this->query('IntegrityCodeChecker');
1369
-	}
1370
-
1371
-	/**
1372
-	 * @return \OC\Session\CryptoWrapper
1373
-	 */
1374
-	public function getSessionCryptoWrapper() {
1375
-		return $this->query('CryptoWrapper');
1376
-	}
1377
-
1378
-	/**
1379
-	 * @return CsrfTokenManager
1380
-	 */
1381
-	public function getCsrfTokenManager() {
1382
-		return $this->query('CsrfTokenManager');
1383
-	}
1384
-
1385
-	/**
1386
-	 * @return Throttler
1387
-	 */
1388
-	public function getBruteForceThrottler() {
1389
-		return $this->query('Throttler');
1390
-	}
1391
-
1392
-	/**
1393
-	 * @return IContentSecurityPolicyManager
1394
-	 */
1395
-	public function getContentSecurityPolicyManager() {
1396
-		return $this->query('ContentSecurityPolicyManager');
1397
-	}
1398
-
1399
-	/**
1400
-	 * Not a public API as of 8.2, wait for 9.0
1401
-	 *
1402
-	 * @return \OCA\Files_External\Service\BackendService
1403
-	 */
1404
-	public function getStoragesBackendService() {
1405
-		return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\BackendService');
1406
-	}
1407
-
1408
-	/**
1409
-	 * Not a public API as of 8.2, wait for 9.0
1410
-	 *
1411
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1412
-	 */
1413
-	public function getGlobalStoragesService() {
1414
-		return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1415
-	}
1416
-
1417
-	/**
1418
-	 * Not a public API as of 8.2, wait for 9.0
1419
-	 *
1420
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1421
-	 */
1422
-	public function getUserGlobalStoragesService() {
1423
-		return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1424
-	}
1425
-
1426
-	/**
1427
-	 * Not a public API as of 8.2, wait for 9.0
1428
-	 *
1429
-	 * @return \OCA\Files_External\Service\UserStoragesService
1430
-	 */
1431
-	public function getUserStoragesService() {
1432
-		return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\UserStoragesService');
1433
-	}
1434
-
1435
-	/**
1436
-	 * @return \OCP\Share\IManager
1437
-	 */
1438
-	public function getShareManager() {
1439
-		return $this->query('ShareManager');
1440
-	}
1441
-
1442
-	/**
1443
-	 * Returns the LDAP Provider
1444
-	 *
1445
-	 * @return \OCP\LDAP\ILDAPProvider
1446
-	 */
1447
-	public function getLDAPProvider() {
1448
-		return $this->query('LDAPProvider');
1449
-	}
1450
-
1451
-	/**
1452
-	 * @return \OCP\Settings\IManager
1453
-	 */
1454
-	public function getSettingsManager() {
1455
-		return $this->query('SettingsManager');
1456
-	}
651
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
652
+            if (isset($prefixes['OCA\\Theming\\'])) {
653
+                $classExists = true;
654
+            } else {
655
+                $classExists = false;
656
+            }
657
+
658
+            if ($classExists && $this->getConfig()->getSystemValue('installed', false) && $this->getAppManager()->isInstalled('theming')) {
659
+                return new ThemingDefaults(
660
+                    $this->getConfig(),
661
+                    $this->getL10N('theming'),
662
+                    $this->getURLGenerator(),
663
+                    new \OC_Defaults()
664
+                );
665
+            }
666
+            return new \OC_Defaults();
667
+        });
668
+        $this->registerService('EventDispatcher', function () {
669
+            return new EventDispatcher();
670
+        });
671
+        $this->registerService('CryptoWrapper', function (Server $c) {
672
+            // FIXME: Instantiiated here due to cyclic dependency
673
+            $request = new Request(
674
+                [
675
+                    'get' => $_GET,
676
+                    'post' => $_POST,
677
+                    'files' => $_FILES,
678
+                    'server' => $_SERVER,
679
+                    'env' => $_ENV,
680
+                    'cookies' => $_COOKIE,
681
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
682
+                        ? $_SERVER['REQUEST_METHOD']
683
+                        : null,
684
+                ],
685
+                $c->getSecureRandom(),
686
+                $c->getConfig()
687
+            );
688
+
689
+            return new CryptoWrapper(
690
+                $c->getConfig(),
691
+                $c->getCrypto(),
692
+                $c->getSecureRandom(),
693
+                $request
694
+            );
695
+        });
696
+        $this->registerService('CsrfTokenManager', function (Server $c) {
697
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
698
+            $sessionStorage = new SessionStorage($c->getSession());
699
+
700
+            return new CsrfTokenManager(
701
+                $tokenGenerator,
702
+                $sessionStorage
703
+            );
704
+        });
705
+        $this->registerService('ContentSecurityPolicyManager', function (Server $c) {
706
+            return new ContentSecurityPolicyManager();
707
+        });
708
+        $this->registerService('ShareManager', function(Server $c) {
709
+            $config = $c->getConfig();
710
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
711
+            /** @var \OCP\Share\IProviderFactory $factory */
712
+            $factory = new $factoryClass($this);
713
+
714
+            $manager = new \OC\Share20\Manager(
715
+                $c->getLogger(),
716
+                $c->getConfig(),
717
+                $c->getSecureRandom(),
718
+                $c->getHasher(),
719
+                $c->getMountManager(),
720
+                $c->getGroupManager(),
721
+                $c->getL10N('core'),
722
+                $factory,
723
+                $c->getUserManager(),
724
+                $c->getLazyRootFolder(),
725
+                $c->getEventDispatcher()
726
+            );
727
+
728
+            return $manager;
729
+        });
730
+        $this->registerService('SettingsManager', function(Server $c) {
731
+            $manager = new \OC\Settings\Manager(
732
+                $c->getLogger(),
733
+                $c->getDatabaseConnection(),
734
+                $c->getL10N('lib'),
735
+                $c->getConfig(),
736
+                $c->getEncryptionManager(),
737
+                $c->getUserManager(),
738
+                $c->getLockingProvider()
739
+            );
740
+            return $manager;
741
+        });
742
+    }
743
+
744
+    /**
745
+     * @return \OCP\Contacts\IManager
746
+     */
747
+    public function getContactsManager() {
748
+        return $this->query('ContactsManager');
749
+    }
750
+
751
+    /**
752
+     * @return \OC\Encryption\Manager
753
+     */
754
+    public function getEncryptionManager() {
755
+        return $this->query('EncryptionManager');
756
+    }
757
+
758
+    /**
759
+     * @return \OC\Encryption\File
760
+     */
761
+    public function getEncryptionFilesHelper() {
762
+        return $this->query('EncryptionFileHelper');
763
+    }
764
+
765
+    /**
766
+     * @return \OCP\Encryption\Keys\IStorage
767
+     */
768
+    public function getEncryptionKeyStorage() {
769
+        return $this->query('EncryptionKeyStorage');
770
+    }
771
+
772
+    /**
773
+     * The current request object holding all information about the request
774
+     * currently being processed is returned from this method.
775
+     * In case the current execution was not initiated by a web request null is returned
776
+     *
777
+     * @return \OCP\IRequest
778
+     */
779
+    public function getRequest() {
780
+        return $this->query('Request');
781
+    }
782
+
783
+    /**
784
+     * Returns the preview manager which can create preview images for a given file
785
+     *
786
+     * @return \OCP\IPreview
787
+     */
788
+    public function getPreviewManager() {
789
+        return $this->query('PreviewManager');
790
+    }
791
+
792
+    /**
793
+     * Returns the tag manager which can get and set tags for different object types
794
+     *
795
+     * @see \OCP\ITagManager::load()
796
+     * @return \OCP\ITagManager
797
+     */
798
+    public function getTagManager() {
799
+        return $this->query('TagManager');
800
+    }
801
+
802
+    /**
803
+     * Returns the system-tag manager
804
+     *
805
+     * @return \OCP\SystemTag\ISystemTagManager
806
+     *
807
+     * @since 9.0.0
808
+     */
809
+    public function getSystemTagManager() {
810
+        return $this->query('SystemTagManager');
811
+    }
812
+
813
+    /**
814
+     * Returns the system-tag object mapper
815
+     *
816
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
817
+     *
818
+     * @since 9.0.0
819
+     */
820
+    public function getSystemTagObjectMapper() {
821
+        return $this->query('SystemTagObjectMapper');
822
+    }
823
+
824
+
825
+    /**
826
+     * Returns the avatar manager, used for avatar functionality
827
+     *
828
+     * @return \OCP\IAvatarManager
829
+     */
830
+    public function getAvatarManager() {
831
+        return $this->query('AvatarManager');
832
+    }
833
+
834
+    /**
835
+     * Returns the root folder of ownCloud's data directory
836
+     *
837
+     * @return \OCP\Files\IRootFolder
838
+     */
839
+    public function getRootFolder() {
840
+        return $this->query('RootFolder');
841
+    }
842
+
843
+    /**
844
+     * Returns the root folder of ownCloud's data directory
845
+     * This is the lazy variant so this gets only initialized once it
846
+     * is actually used.
847
+     *
848
+     * @return \OCP\Files\IRootFolder
849
+     */
850
+    public function getLazyRootFolder() {
851
+        return $this->query('LazyRootFolder');
852
+    }
853
+
854
+    /**
855
+     * Returns a view to ownCloud's files folder
856
+     *
857
+     * @param string $userId user ID
858
+     * @return \OCP\Files\Folder|null
859
+     */
860
+    public function getUserFolder($userId = null) {
861
+        if ($userId === null) {
862
+            $user = $this->getUserSession()->getUser();
863
+            if (!$user) {
864
+                return null;
865
+            }
866
+            $userId = $user->getUID();
867
+        }
868
+        $root = $this->getRootFolder();
869
+        return $root->getUserFolder($userId);
870
+    }
871
+
872
+    /**
873
+     * Returns an app-specific view in ownClouds data directory
874
+     *
875
+     * @return \OCP\Files\Folder
876
+     */
877
+    public function getAppFolder() {
878
+        $dir = '/' . \OC_App::getCurrentApp();
879
+        $root = $this->getRootFolder();
880
+        if (!$root->nodeExists($dir)) {
881
+            $folder = $root->newFolder($dir);
882
+        } else {
883
+            $folder = $root->get($dir);
884
+        }
885
+        return $folder;
886
+    }
887
+
888
+    /**
889
+     * @return \OC\User\Manager
890
+     */
891
+    public function getUserManager() {
892
+        return $this->query('UserManager');
893
+    }
894
+
895
+    /**
896
+     * @return \OC\Group\Manager
897
+     */
898
+    public function getGroupManager() {
899
+        return $this->query('GroupManager');
900
+    }
901
+
902
+    /**
903
+     * @return \OC\User\Session
904
+     */
905
+    public function getUserSession() {
906
+        return $this->query('UserSession');
907
+    }
908
+
909
+    /**
910
+     * @return \OCP\ISession
911
+     */
912
+    public function getSession() {
913
+        return $this->query('UserSession')->getSession();
914
+    }
915
+
916
+    /**
917
+     * @param \OCP\ISession $session
918
+     */
919
+    public function setSession(\OCP\ISession $session) {
920
+        return $this->query('UserSession')->setSession($session);
921
+    }
922
+
923
+    /**
924
+     * @return \OC\Authentication\TwoFactorAuth\Manager
925
+     */
926
+    public function getTwoFactorAuthManager() {
927
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
928
+    }
929
+
930
+    /**
931
+     * @return \OC\NavigationManager
932
+     */
933
+    public function getNavigationManager() {
934
+        return $this->query('NavigationManager');
935
+    }
936
+
937
+    /**
938
+     * @return \OCP\IConfig
939
+     */
940
+    public function getConfig() {
941
+        return $this->query('AllConfig');
942
+    }
943
+
944
+    /**
945
+     * @internal For internal use only
946
+     * @return \OC\SystemConfig
947
+     */
948
+    public function getSystemConfig() {
949
+        return $this->query('SystemConfig');
950
+    }
951
+
952
+    /**
953
+     * Returns the app config manager
954
+     *
955
+     * @return \OCP\IAppConfig
956
+     */
957
+    public function getAppConfig() {
958
+        return $this->query('AppConfig');
959
+    }
960
+
961
+    /**
962
+     * @return \OCP\L10N\IFactory
963
+     */
964
+    public function getL10NFactory() {
965
+        return $this->query('L10NFactory');
966
+    }
967
+
968
+    /**
969
+     * get an L10N instance
970
+     *
971
+     * @param string $app appid
972
+     * @param string $lang
973
+     * @return IL10N
974
+     */
975
+    public function getL10N($app, $lang = null) {
976
+        return $this->getL10NFactory()->get($app, $lang);
977
+    }
978
+
979
+    /**
980
+     * @return \OCP\IURLGenerator
981
+     */
982
+    public function getURLGenerator() {
983
+        return $this->query('URLGenerator');
984
+    }
985
+
986
+    /**
987
+     * @return \OCP\IHelper
988
+     */
989
+    public function getHelper() {
990
+        return $this->query('AppHelper');
991
+    }
992
+
993
+    /**
994
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
995
+     * getMemCacheFactory() instead.
996
+     *
997
+     * @return \OCP\ICache
998
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
999
+     */
1000
+    public function getCache() {
1001
+        return $this->query('UserCache');
1002
+    }
1003
+
1004
+    /**
1005
+     * Returns an \OCP\CacheFactory instance
1006
+     *
1007
+     * @return \OCP\ICacheFactory
1008
+     */
1009
+    public function getMemCacheFactory() {
1010
+        return $this->query('MemCacheFactory');
1011
+    }
1012
+
1013
+    /**
1014
+     * Returns an \OC\RedisFactory instance
1015
+     *
1016
+     * @return \OC\RedisFactory
1017
+     */
1018
+    public function getGetRedisFactory() {
1019
+        return $this->query('RedisFactory');
1020
+    }
1021
+
1022
+
1023
+    /**
1024
+     * Returns the current session
1025
+     *
1026
+     * @return \OCP\IDBConnection
1027
+     */
1028
+    public function getDatabaseConnection() {
1029
+        return $this->query('DatabaseConnection');
1030
+    }
1031
+
1032
+    /**
1033
+     * Returns the activity manager
1034
+     *
1035
+     * @return \OCP\Activity\IManager
1036
+     */
1037
+    public function getActivityManager() {
1038
+        return $this->query('ActivityManager');
1039
+    }
1040
+
1041
+    /**
1042
+     * Returns an job list for controlling background jobs
1043
+     *
1044
+     * @return \OCP\BackgroundJob\IJobList
1045
+     */
1046
+    public function getJobList() {
1047
+        return $this->query('JobList');
1048
+    }
1049
+
1050
+    /**
1051
+     * Returns a logger instance
1052
+     *
1053
+     * @return \OCP\ILogger
1054
+     */
1055
+    public function getLogger() {
1056
+        return $this->query('Logger');
1057
+    }
1058
+
1059
+    /**
1060
+     * Returns a router for generating and matching urls
1061
+     *
1062
+     * @return \OCP\Route\IRouter
1063
+     */
1064
+    public function getRouter() {
1065
+        return $this->query('Router');
1066
+    }
1067
+
1068
+    /**
1069
+     * Returns a search instance
1070
+     *
1071
+     * @return \OCP\ISearch
1072
+     */
1073
+    public function getSearch() {
1074
+        return $this->query('Search');
1075
+    }
1076
+
1077
+    /**
1078
+     * Returns a SecureRandom instance
1079
+     *
1080
+     * @return \OCP\Security\ISecureRandom
1081
+     */
1082
+    public function getSecureRandom() {
1083
+        return $this->query('SecureRandom');
1084
+    }
1085
+
1086
+    /**
1087
+     * Returns a Crypto instance
1088
+     *
1089
+     * @return \OCP\Security\ICrypto
1090
+     */
1091
+    public function getCrypto() {
1092
+        return $this->query('Crypto');
1093
+    }
1094
+
1095
+    /**
1096
+     * Returns a Hasher instance
1097
+     *
1098
+     * @return \OCP\Security\IHasher
1099
+     */
1100
+    public function getHasher() {
1101
+        return $this->query('Hasher');
1102
+    }
1103
+
1104
+    /**
1105
+     * Returns a CredentialsManager instance
1106
+     *
1107
+     * @return \OCP\Security\ICredentialsManager
1108
+     */
1109
+    public function getCredentialsManager() {
1110
+        return $this->query('CredentialsManager');
1111
+    }
1112
+
1113
+    /**
1114
+     * Returns an instance of the db facade
1115
+     *
1116
+     * @deprecated use getDatabaseConnection, will be removed in ownCloud 10
1117
+     * @return \OCP\IDb
1118
+     */
1119
+    public function getDb() {
1120
+        return $this->query('Db');
1121
+    }
1122
+
1123
+    /**
1124
+     * Returns an instance of the HTTP helper class
1125
+     *
1126
+     * @deprecated Use getHTTPClientService()
1127
+     * @return \OC\HTTPHelper
1128
+     */
1129
+    public function getHTTPHelper() {
1130
+        return $this->query('HTTPHelper');
1131
+    }
1132
+
1133
+    /**
1134
+     * Get the certificate manager for the user
1135
+     *
1136
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1137
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1138
+     */
1139
+    public function getCertificateManager($userId = '') {
1140
+        if ($userId === '') {
1141
+            $userSession = $this->getUserSession();
1142
+            $user = $userSession->getUser();
1143
+            if (is_null($user)) {
1144
+                return null;
1145
+            }
1146
+            $userId = $user->getUID();
1147
+        }
1148
+        return new CertificateManager($userId, new View(), $this->getConfig());
1149
+    }
1150
+
1151
+    /**
1152
+     * Returns an instance of the HTTP client service
1153
+     *
1154
+     * @return \OCP\Http\Client\IClientService
1155
+     */
1156
+    public function getHTTPClientService() {
1157
+        return $this->query('HttpClientService');
1158
+    }
1159
+
1160
+    /**
1161
+     * Create a new event source
1162
+     *
1163
+     * @return \OCP\IEventSource
1164
+     */
1165
+    public function createEventSource() {
1166
+        return new \OC_EventSource();
1167
+    }
1168
+
1169
+    /**
1170
+     * Get the active event logger
1171
+     *
1172
+     * The returned logger only logs data when debug mode is enabled
1173
+     *
1174
+     * @return \OCP\Diagnostics\IEventLogger
1175
+     */
1176
+    public function getEventLogger() {
1177
+        return $this->query('EventLogger');
1178
+    }
1179
+
1180
+    /**
1181
+     * Get the active query logger
1182
+     *
1183
+     * The returned logger only logs data when debug mode is enabled
1184
+     *
1185
+     * @return \OCP\Diagnostics\IQueryLogger
1186
+     */
1187
+    public function getQueryLogger() {
1188
+        return $this->query('QueryLogger');
1189
+    }
1190
+
1191
+    /**
1192
+     * Get the manager for temporary files and folders
1193
+     *
1194
+     * @return \OCP\ITempManager
1195
+     */
1196
+    public function getTempManager() {
1197
+        return $this->query('TempManager');
1198
+    }
1199
+
1200
+    /**
1201
+     * Get the app manager
1202
+     *
1203
+     * @return \OCP\App\IAppManager
1204
+     */
1205
+    public function getAppManager() {
1206
+        return $this->query('AppManager');
1207
+    }
1208
+
1209
+    /**
1210
+     * Creates a new mailer
1211
+     *
1212
+     * @return \OCP\Mail\IMailer
1213
+     */
1214
+    public function getMailer() {
1215
+        return $this->query('Mailer');
1216
+    }
1217
+
1218
+    /**
1219
+     * Get the webroot
1220
+     *
1221
+     * @return string
1222
+     */
1223
+    public function getWebRoot() {
1224
+        return $this->webRoot;
1225
+    }
1226
+
1227
+    /**
1228
+     * @return \OC\OCSClient
1229
+     */
1230
+    public function getOcsClient() {
1231
+        return $this->query('OcsClient');
1232
+    }
1233
+
1234
+    /**
1235
+     * @return \OCP\IDateTimeZone
1236
+     */
1237
+    public function getDateTimeZone() {
1238
+        return $this->query('DateTimeZone');
1239
+    }
1240
+
1241
+    /**
1242
+     * @return \OCP\IDateTimeFormatter
1243
+     */
1244
+    public function getDateTimeFormatter() {
1245
+        return $this->query('DateTimeFormatter');
1246
+    }
1247
+
1248
+    /**
1249
+     * @return \OCP\Files\Config\IMountProviderCollection
1250
+     */
1251
+    public function getMountProviderCollection() {
1252
+        return $this->query('MountConfigManager');
1253
+    }
1254
+
1255
+    /**
1256
+     * Get the IniWrapper
1257
+     *
1258
+     * @return IniGetWrapper
1259
+     */
1260
+    public function getIniWrapper() {
1261
+        return $this->query('IniWrapper');
1262
+    }
1263
+
1264
+    /**
1265
+     * @return \OCP\Command\IBus
1266
+     */
1267
+    public function getCommandBus() {
1268
+        return $this->query('AsyncCommandBus');
1269
+    }
1270
+
1271
+    /**
1272
+     * Get the trusted domain helper
1273
+     *
1274
+     * @return TrustedDomainHelper
1275
+     */
1276
+    public function getTrustedDomainHelper() {
1277
+        return $this->query('TrustedDomainHelper');
1278
+    }
1279
+
1280
+    /**
1281
+     * Get the locking provider
1282
+     *
1283
+     * @return \OCP\Lock\ILockingProvider
1284
+     * @since 8.1.0
1285
+     */
1286
+    public function getLockingProvider() {
1287
+        return $this->query('LockingProvider');
1288
+    }
1289
+
1290
+    /**
1291
+     * @return \OCP\Files\Mount\IMountManager
1292
+     **/
1293
+    function getMountManager() {
1294
+        return $this->query('MountManager');
1295
+    }
1296
+
1297
+    /** @return \OCP\Files\Config\IUserMountCache */
1298
+    function getUserMountCache() {
1299
+        return $this->query('UserMountCache');
1300
+    }
1301
+
1302
+    /**
1303
+     * Get the MimeTypeDetector
1304
+     *
1305
+     * @return \OCP\Files\IMimeTypeDetector
1306
+     */
1307
+    public function getMimeTypeDetector() {
1308
+        return $this->query('MimeTypeDetector');
1309
+    }
1310
+
1311
+    /**
1312
+     * Get the MimeTypeLoader
1313
+     *
1314
+     * @return \OCP\Files\IMimeTypeLoader
1315
+     */
1316
+    public function getMimeTypeLoader() {
1317
+        return $this->query('MimeTypeLoader');
1318
+    }
1319
+
1320
+    /**
1321
+     * Get the manager of all the capabilities
1322
+     *
1323
+     * @return \OC\CapabilitiesManager
1324
+     */
1325
+    public function getCapabilitiesManager() {
1326
+        return $this->query('CapabilitiesManager');
1327
+    }
1328
+
1329
+    /**
1330
+     * Get the EventDispatcher
1331
+     *
1332
+     * @return EventDispatcherInterface
1333
+     * @since 8.2.0
1334
+     */
1335
+    public function getEventDispatcher() {
1336
+        return $this->query('EventDispatcher');
1337
+    }
1338
+
1339
+    /**
1340
+     * Get the Notification Manager
1341
+     *
1342
+     * @return \OCP\Notification\IManager
1343
+     * @since 8.2.0
1344
+     */
1345
+    public function getNotificationManager() {
1346
+        return $this->query('NotificationManager');
1347
+    }
1348
+
1349
+    /**
1350
+     * @return \OCP\Comments\ICommentsManager
1351
+     */
1352
+    public function getCommentsManager() {
1353
+        return $this->query('CommentsManager');
1354
+    }
1355
+
1356
+    /**
1357
+     * @internal Not public by intention.
1358
+     * @return \OC_Defaults
1359
+     */
1360
+    public function getThemingDefaults() {
1361
+        return $this->query('ThemingDefaults');
1362
+    }
1363
+
1364
+    /**
1365
+     * @return \OC\IntegrityCheck\Checker
1366
+     */
1367
+    public function getIntegrityCodeChecker() {
1368
+        return $this->query('IntegrityCodeChecker');
1369
+    }
1370
+
1371
+    /**
1372
+     * @return \OC\Session\CryptoWrapper
1373
+     */
1374
+    public function getSessionCryptoWrapper() {
1375
+        return $this->query('CryptoWrapper');
1376
+    }
1377
+
1378
+    /**
1379
+     * @return CsrfTokenManager
1380
+     */
1381
+    public function getCsrfTokenManager() {
1382
+        return $this->query('CsrfTokenManager');
1383
+    }
1384
+
1385
+    /**
1386
+     * @return Throttler
1387
+     */
1388
+    public function getBruteForceThrottler() {
1389
+        return $this->query('Throttler');
1390
+    }
1391
+
1392
+    /**
1393
+     * @return IContentSecurityPolicyManager
1394
+     */
1395
+    public function getContentSecurityPolicyManager() {
1396
+        return $this->query('ContentSecurityPolicyManager');
1397
+    }
1398
+
1399
+    /**
1400
+     * Not a public API as of 8.2, wait for 9.0
1401
+     *
1402
+     * @return \OCA\Files_External\Service\BackendService
1403
+     */
1404
+    public function getStoragesBackendService() {
1405
+        return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\BackendService');
1406
+    }
1407
+
1408
+    /**
1409
+     * Not a public API as of 8.2, wait for 9.0
1410
+     *
1411
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1412
+     */
1413
+    public function getGlobalStoragesService() {
1414
+        return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1415
+    }
1416
+
1417
+    /**
1418
+     * Not a public API as of 8.2, wait for 9.0
1419
+     *
1420
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1421
+     */
1422
+    public function getUserGlobalStoragesService() {
1423
+        return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1424
+    }
1425
+
1426
+    /**
1427
+     * Not a public API as of 8.2, wait for 9.0
1428
+     *
1429
+     * @return \OCA\Files_External\Service\UserStoragesService
1430
+     */
1431
+    public function getUserStoragesService() {
1432
+        return \OC_Mount_Config::$app->getContainer()->query('OCA\\Files_External\\Service\\UserStoragesService');
1433
+    }
1434
+
1435
+    /**
1436
+     * @return \OCP\Share\IManager
1437
+     */
1438
+    public function getShareManager() {
1439
+        return $this->query('ShareManager');
1440
+    }
1441
+
1442
+    /**
1443
+     * Returns the LDAP Provider
1444
+     *
1445
+     * @return \OCP\LDAP\ILDAPProvider
1446
+     */
1447
+    public function getLDAPProvider() {
1448
+        return $this->query('LDAPProvider');
1449
+    }
1450
+
1451
+    /**
1452
+     * @return \OCP\Settings\IManager
1453
+     */
1454
+    public function getSettingsManager() {
1455
+        return $this->query('SettingsManager');
1456
+    }
1457 1457
 }
Please login to merge, or discard this patch.
Spacing   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -108,15 +108,15 @@  discard block
 block discarded – undo
108 108
 		parent::__construct();
109 109
 		$this->webRoot = $webRoot;
110 110
 
111
-		$this->registerService('ContactsManager', function ($c) {
111
+		$this->registerService('ContactsManager', function($c) {
112 112
 			return new ContactsManager();
113 113
 		});
114 114
 
115
-		$this->registerService('PreviewManager', function (Server $c) {
115
+		$this->registerService('PreviewManager', function(Server $c) {
116 116
 			return new PreviewManager($c->getConfig());
117 117
 		});
118 118
 
119
-		$this->registerService('EncryptionManager', function (Server $c) {
119
+		$this->registerService('EncryptionManager', function(Server $c) {
120 120
 			$view = new View();
121 121
 			$util = new Encryption\Util(
122 122
 				$view,
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 			);
135 135
 		});
136 136
 
137
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
137
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
138 138
 			$util = new Encryption\Util(
139 139
 				new View(),
140 140
 				$c->getUserManager(),
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 			return new Encryption\File($util);
145 145
 		});
146 146
 
147
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
147
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
148 148
 			$view = new View();
149 149
 			$util = new Encryption\Util(
150 150
 				$view,
@@ -155,27 +155,27 @@  discard block
 block discarded – undo
155 155
 
156 156
 			return new Encryption\Keys\Storage($view, $util);
157 157
 		});
158
-		$this->registerService('TagMapper', function (Server $c) {
158
+		$this->registerService('TagMapper', function(Server $c) {
159 159
 			return new TagMapper($c->getDatabaseConnection());
160 160
 		});
161
-		$this->registerService('TagManager', function (Server $c) {
161
+		$this->registerService('TagManager', function(Server $c) {
162 162
 			$tagMapper = $c->query('TagMapper');
163 163
 			return new TagManager($tagMapper, $c->getUserSession());
164 164
 		});
165
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
165
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
166 166
 			$config = $c->getConfig();
167 167
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
168 168
 			/** @var \OC\SystemTag\ManagerFactory $factory */
169 169
 			$factory = new $factoryClass($this);
170 170
 			return $factory;
171 171
 		});
172
-		$this->registerService('SystemTagManager', function (Server $c) {
172
+		$this->registerService('SystemTagManager', function(Server $c) {
173 173
 			return $c->query('SystemTagManagerFactory')->getManager();
174 174
 		});
175
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
175
+		$this->registerService('SystemTagObjectMapper', function(Server $c) {
176 176
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
177 177
 		});
178
-		$this->registerService('RootFolder', function () {
178
+		$this->registerService('RootFolder', function() {
179 179
 			$manager = \OC\Files\Filesystem::getMountManager(null);
180 180
 			$view = new View();
181 181
 			$root = new Root($manager, $view, null);
@@ -188,39 +188,39 @@  discard block
 block discarded – undo
188 188
 				return $c->getRootFolder();
189 189
 			});
190 190
 		});
191
-		$this->registerService('UserManager', function (Server $c) {
191
+		$this->registerService('UserManager', function(Server $c) {
192 192
 			$config = $c->getConfig();
193 193
 			return new \OC\User\Manager($config);
194 194
 		});
195
-		$this->registerService('GroupManager', function (Server $c) {
195
+		$this->registerService('GroupManager', function(Server $c) {
196 196
 			$groupManager = new \OC\Group\Manager($this->getUserManager());
197
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
197
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
198 198
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
199 199
 			});
200
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
200
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
201 201
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
202 202
 			});
203
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
203
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
204 204
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
205 205
 			});
206
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
206
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
207 207
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
208 208
 			});
209
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
209
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
210 210
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
211 211
 			});
212
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
212
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
213 213
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
214 214
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
215 215
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
216 216
 			});
217 217
 			return $groupManager;
218 218
 		});
219
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
219
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
220 220
 			$dbConnection = $c->getDatabaseConnection();
221 221
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
222 222
 		});
223
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
223
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
224 224
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
225 225
 			$crypto = $c->getCrypto();
226 226
 			$config = $c->getConfig();
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
230 230
 		});
231 231
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
232
-		$this->registerService('UserSession', function (Server $c) {
232
+		$this->registerService('UserSession', function(Server $c) {
233 233
 			$manager = $c->getUserManager();
234 234
 			$session = new \OC\Session\Memory('');
235 235
 			$timeFactory = new TimeFactory();
@@ -242,65 +242,65 @@  discard block
 block discarded – undo
242 242
 			}
243 243
 
244 244
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig());
245
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
245
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
246 246
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
247 247
 			});
248
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
248
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
249 249
 				/** @var $user \OC\User\User */
250 250
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
251 251
 			});
252
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
252
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
253 253
 				/** @var $user \OC\User\User */
254 254
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
255 255
 			});
256
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
256
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
257 257
 				/** @var $user \OC\User\User */
258 258
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
259 259
 			});
260
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
260
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
261 261
 				/** @var $user \OC\User\User */
262 262
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
263 263
 			});
264
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
264
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
265 265
 				/** @var $user \OC\User\User */
266 266
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
267 267
 			});
268
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
268
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
269 269
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
270 270
 			});
271
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
271
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
272 272
 				/** @var $user \OC\User\User */
273 273
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
274 274
 			});
275
-			$userSession->listen('\OC\User', 'logout', function () {
275
+			$userSession->listen('\OC\User', 'logout', function() {
276 276
 				\OC_Hook::emit('OC_User', 'logout', array());
277 277
 			});
278
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
278
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
279 279
 				/** @var $user \OC\User\User */
280 280
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
281 281
 			});
282 282
 			return $userSession;
283 283
 		});
284 284
 
285
-		$this->registerService('\OC\Authentication\TwoFactorAuth\Manager', function (Server $c) {
285
+		$this->registerService('\OC\Authentication\TwoFactorAuth\Manager', function(Server $c) {
286 286
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig());
287 287
 		});
288 288
 
289
-		$this->registerService('NavigationManager', function ($c) {
289
+		$this->registerService('NavigationManager', function($c) {
290 290
 			return new \OC\NavigationManager();
291 291
 		});
292
-		$this->registerService('AllConfig', function (Server $c) {
292
+		$this->registerService('AllConfig', function(Server $c) {
293 293
 			return new \OC\AllConfig(
294 294
 				$c->getSystemConfig()
295 295
 			);
296 296
 		});
297
-		$this->registerService('SystemConfig', function ($c) use ($config) {
297
+		$this->registerService('SystemConfig', function($c) use ($config) {
298 298
 			return new \OC\SystemConfig($config);
299 299
 		});
300
-		$this->registerService('AppConfig', function (Server $c) {
300
+		$this->registerService('AppConfig', function(Server $c) {
301 301
 			return new \OC\AppConfig($c->getDatabaseConnection());
302 302
 		});
303
-		$this->registerService('L10NFactory', function (Server $c) {
303
+		$this->registerService('L10NFactory', function(Server $c) {
304 304
 			return new \OC\L10N\Factory(
305 305
 				$c->getConfig(),
306 306
 				$c->getRequest(),
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 				\OC::$SERVERROOT
309 309
 			);
310 310
 		});
311
-		$this->registerService('URLGenerator', function (Server $c) {
311
+		$this->registerService('URLGenerator', function(Server $c) {
312 312
 			$config = $c->getConfig();
313 313
 			$cacheFactory = $c->getMemCacheFactory();
314 314
 			return new \OC\URLGenerator(
@@ -316,22 +316,22 @@  discard block
 block discarded – undo
316 316
 				$cacheFactory
317 317
 			);
318 318
 		});
319
-		$this->registerService('AppHelper', function ($c) {
319
+		$this->registerService('AppHelper', function($c) {
320 320
 			return new \OC\AppHelper();
321 321
 		});
322
-		$this->registerService('UserCache', function ($c) {
322
+		$this->registerService('UserCache', function($c) {
323 323
 			return new Cache\File();
324 324
 		});
325
-		$this->registerService('MemCacheFactory', function (Server $c) {
325
+		$this->registerService('MemCacheFactory', function(Server $c) {
326 326
 			$config = $c->getConfig();
327 327
 
328 328
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
329 329
 				$v = \OC_App::getAppVersions();
330
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
330
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
331 331
 				$version = implode(',', $v);
332 332
 				$instanceId = \OC_Util::getInstanceId();
333 333
 				$path = \OC::$SERVERROOT;
334
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
334
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
335 335
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
336 336
 					$config->getSystemValue('memcache.local', null),
337 337
 					$config->getSystemValue('memcache.distributed', null),
@@ -345,18 +345,18 @@  discard block
 block discarded – undo
345 345
 				'\\OC\\Memcache\\ArrayCache'
346 346
 			);
347 347
 		});
348
-		$this->registerService('RedisFactory', function (Server $c) {
348
+		$this->registerService('RedisFactory', function(Server $c) {
349 349
 			$systemConfig = $c->getSystemConfig();
350 350
 			return new RedisFactory($systemConfig);
351 351
 		});
352
-		$this->registerService('ActivityManager', function (Server $c) {
352
+		$this->registerService('ActivityManager', function(Server $c) {
353 353
 			return new \OC\Activity\Manager(
354 354
 				$c->getRequest(),
355 355
 				$c->getUserSession(),
356 356
 				$c->getConfig()
357 357
 			);
358 358
 		});
359
-		$this->registerService('AvatarManager', function (Server $c) {
359
+		$this->registerService('AvatarManager', function(Server $c) {
360 360
 			return new AvatarManager(
361 361
 				$c->getUserManager(),
362 362
 				$c->getLazyRootFolder(),
@@ -364,14 +364,14 @@  discard block
 block discarded – undo
364 364
 				$c->getLogger()
365 365
 			);
366 366
 		});
367
-		$this->registerService('Logger', function (Server $c) {
367
+		$this->registerService('Logger', function(Server $c) {
368 368
 			$logClass = $c->query('AllConfig')->getSystemValue('log_type', 'owncloud');
369
-			$logger = 'OC\\Log\\' . ucfirst($logClass);
369
+			$logger = 'OC\\Log\\'.ucfirst($logClass);
370 370
 			call_user_func(array($logger, 'init'));
371 371
 
372 372
 			return new Log($logger);
373 373
 		});
374
-		$this->registerService('JobList', function (Server $c) {
374
+		$this->registerService('JobList', function(Server $c) {
375 375
 			$config = $c->getConfig();
376 376
 			return new \OC\BackgroundJob\JobList(
377 377
 				$c->getDatabaseConnection(),
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 				new TimeFactory()
380 380
 			);
381 381
 		});
382
-		$this->registerService('Router', function (Server $c) {
382
+		$this->registerService('Router', function(Server $c) {
383 383
 			$cacheFactory = $c->getMemCacheFactory();
384 384
 			$logger = $c->getLogger();
385 385
 			if ($cacheFactory->isAvailable()) {
@@ -389,22 +389,22 @@  discard block
 block discarded – undo
389 389
 			}
390 390
 			return $router;
391 391
 		});
392
-		$this->registerService('Search', function ($c) {
392
+		$this->registerService('Search', function($c) {
393 393
 			return new Search();
394 394
 		});
395
-		$this->registerService('SecureRandom', function ($c) {
395
+		$this->registerService('SecureRandom', function($c) {
396 396
 			return new SecureRandom();
397 397
 		});
398
-		$this->registerService('Crypto', function (Server $c) {
398
+		$this->registerService('Crypto', function(Server $c) {
399 399
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
400 400
 		});
401
-		$this->registerService('Hasher', function (Server $c) {
401
+		$this->registerService('Hasher', function(Server $c) {
402 402
 			return new Hasher($c->getConfig());
403 403
 		});
404
-		$this->registerService('CredentialsManager', function (Server $c) {
404
+		$this->registerService('CredentialsManager', function(Server $c) {
405 405
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
406 406
 		});
407
-		$this->registerService('DatabaseConnection', function (Server $c) {
407
+		$this->registerService('DatabaseConnection', function(Server $c) {
408 408
 			$factory = new \OC\DB\ConnectionFactory();
409 409
 			$systemConfig = $c->getSystemConfig();
410 410
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -416,17 +416,17 @@  discard block
 block discarded – undo
416 416
 			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
417 417
 			return $connection;
418 418
 		});
419
-		$this->registerService('Db', function (Server $c) {
419
+		$this->registerService('Db', function(Server $c) {
420 420
 			return new Db($c->getDatabaseConnection());
421 421
 		});
422
-		$this->registerService('HTTPHelper', function (Server $c) {
422
+		$this->registerService('HTTPHelper', function(Server $c) {
423 423
 			$config = $c->getConfig();
424 424
 			return new HTTPHelper(
425 425
 				$config,
426 426
 				$c->getHTTPClientService()
427 427
 			);
428 428
 		});
429
-		$this->registerService('HttpClientService', function (Server $c) {
429
+		$this->registerService('HttpClientService', function(Server $c) {
430 430
 			$user = \OC_User::getUser();
431 431
 			$uid = $user ? $user : null;
432 432
 			return new ClientService(
@@ -434,27 +434,27 @@  discard block
 block discarded – undo
434 434
 				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig())
435 435
 			);
436 436
 		});
437
-		$this->registerService('EventLogger', function (Server $c) {
437
+		$this->registerService('EventLogger', function(Server $c) {
438 438
 			if ($c->getSystemConfig()->getValue('debug', false)) {
439 439
 				return new EventLogger();
440 440
 			} else {
441 441
 				return new NullEventLogger();
442 442
 			}
443 443
 		});
444
-		$this->registerService('QueryLogger', function (Server $c) {
444
+		$this->registerService('QueryLogger', function(Server $c) {
445 445
 			if ($c->getSystemConfig()->getValue('debug', false)) {
446 446
 				return new QueryLogger();
447 447
 			} else {
448 448
 				return new NullQueryLogger();
449 449
 			}
450 450
 		});
451
-		$this->registerService('TempManager', function (Server $c) {
451
+		$this->registerService('TempManager', function(Server $c) {
452 452
 			return new TempManager(
453 453
 				$c->getLogger(),
454 454
 				$c->getConfig()
455 455
 			);
456 456
 		});
457
-		$this->registerService('AppManager', function (Server $c) {
457
+		$this->registerService('AppManager', function(Server $c) {
458 458
 			return new \OC\App\AppManager(
459 459
 				$c->getUserSession(),
460 460
 				$c->getAppConfig(),
@@ -463,13 +463,13 @@  discard block
 block discarded – undo
463 463
 				$c->getEventDispatcher()
464 464
 			);
465 465
 		});
466
-		$this->registerService('DateTimeZone', function (Server $c) {
466
+		$this->registerService('DateTimeZone', function(Server $c) {
467 467
 			return new DateTimeZone(
468 468
 				$c->getConfig(),
469 469
 				$c->getSession()
470 470
 			);
471 471
 		});
472
-		$this->registerService('DateTimeFormatter', function (Server $c) {
472
+		$this->registerService('DateTimeFormatter', function(Server $c) {
473 473
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
474 474
 
475 475
 			return new DateTimeFormatter(
@@ -477,16 +477,16 @@  discard block
 block discarded – undo
477 477
 				$c->getL10N('lib', $language)
478 478
 			);
479 479
 		});
480
-		$this->registerService('UserMountCache', function (Server $c) {
480
+		$this->registerService('UserMountCache', function(Server $c) {
481 481
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
482 482
 			$listener = new UserMountCacheListener($mountCache);
483 483
 			$listener->listen($c->getUserManager());
484 484
 			return $mountCache;
485 485
 		});
486
-		$this->registerService('MountConfigManager', function (Server $c) {
486
+		$this->registerService('MountConfigManager', function(Server $c) {
487 487
 			$loader = \OC\Files\Filesystem::getLoader();
488 488
 			$mountCache = $c->query('UserMountCache');
489
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
489
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
490 490
 
491 491
 			// builtin providers
492 492
 
@@ -497,14 +497,14 @@  discard block
 block discarded – undo
497 497
 
498 498
 			return $manager;
499 499
 		});
500
-		$this->registerService('IniWrapper', function ($c) {
500
+		$this->registerService('IniWrapper', function($c) {
501 501
 			return new IniGetWrapper();
502 502
 		});
503
-		$this->registerService('AsyncCommandBus', function (Server $c) {
503
+		$this->registerService('AsyncCommandBus', function(Server $c) {
504 504
 			$jobList = $c->getJobList();
505 505
 			return new AsyncBus($jobList);
506 506
 		});
507
-		$this->registerService('TrustedDomainHelper', function ($c) {
507
+		$this->registerService('TrustedDomainHelper', function($c) {
508 508
 			return new TrustedDomainHelper($this->getConfig());
509 509
 		});
510 510
 		$this->registerService('Throttler', function(Server $c) {
@@ -515,10 +515,10 @@  discard block
 block discarded – undo
515 515
 				$c->getConfig()
516 516
 			);
517 517
 		});
518
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
518
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
519 519
 			// IConfig and IAppManager requires a working database. This code
520 520
 			// might however be called when ownCloud is not yet setup.
521
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
521
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
522 522
 				$config = $c->getConfig();
523 523
 				$appManager = $c->getAppManager();
524 524
 			} else {
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
 					$c->getTempManager()
537 537
 			);
538 538
 		});
539
-		$this->registerService('Request', function ($c) {
539
+		$this->registerService('Request', function($c) {
540 540
 			if (isset($this['urlParams'])) {
541 541
 				$urlParams = $this['urlParams'];
542 542
 			} else {
@@ -570,14 +570,14 @@  discard block
 block discarded – undo
570 570
 				$stream
571 571
 			);
572 572
 		});
573
-		$this->registerService('Mailer', function (Server $c) {
573
+		$this->registerService('Mailer', function(Server $c) {
574 574
 			return new Mailer(
575 575
 				$c->getConfig(),
576 576
 				$c->getLogger(),
577 577
 				$c->getThemingDefaults()
578 578
 			);
579 579
 		});
580
-		$this->registerService('OcsClient', function (Server $c) {
580
+		$this->registerService('OcsClient', function(Server $c) {
581 581
 			return new OCSClient(
582 582
 				$this->getHTTPClientService(),
583 583
 				$this->getConfig(),
@@ -587,14 +587,14 @@  discard block
 block discarded – undo
587 587
 		$this->registerService('LDAPProvider', function(Server $c) {
588 588
 			$config = $c->getConfig();
589 589
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
590
-			if(is_null($factoryClass)) {
590
+			if (is_null($factoryClass)) {
591 591
 				throw new \Exception('ldapProviderFactory not set');
592 592
 			}
593 593
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
594 594
 			$factory = new $factoryClass($this);
595 595
 			return $factory->getLDAPProvider();
596 596
 		});
597
-		$this->registerService('LockingProvider', function (Server $c) {
597
+		$this->registerService('LockingProvider', function(Server $c) {
598 598
 			$ini = $c->getIniWrapper();
599 599
 			$config = $c->getConfig();
600 600
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -609,27 +609,27 @@  discard block
 block discarded – undo
609 609
 			}
610 610
 			return new NoopLockingProvider();
611 611
 		});
612
-		$this->registerService('MountManager', function () {
612
+		$this->registerService('MountManager', function() {
613 613
 			return new \OC\Files\Mount\Manager();
614 614
 		});
615
-		$this->registerService('MimeTypeDetector', function (Server $c) {
615
+		$this->registerService('MimeTypeDetector', function(Server $c) {
616 616
 			return new \OC\Files\Type\Detection(
617 617
 				$c->getURLGenerator(),
618 618
 				\OC::$configDir,
619
-				\OC::$SERVERROOT . '/resources/config/'
619
+				\OC::$SERVERROOT.'/resources/config/'
620 620
 			);
621 621
 		});
622
-		$this->registerService('MimeTypeLoader', function (Server $c) {
622
+		$this->registerService('MimeTypeLoader', function(Server $c) {
623 623
 			return new \OC\Files\Type\Loader(
624 624
 				$c->getDatabaseConnection()
625 625
 			);
626 626
 		});
627
-		$this->registerService('NotificationManager', function () {
627
+		$this->registerService('NotificationManager', function() {
628 628
 			return new Manager();
629 629
 		});
630
-		$this->registerService('CapabilitiesManager', function (Server $c) {
630
+		$this->registerService('CapabilitiesManager', function(Server $c) {
631 631
 			$manager = new \OC\CapabilitiesManager();
632
-			$manager->registerCapability(function () use ($c) {
632
+			$manager->registerCapability(function() use ($c) {
633 633
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
634 634
 			});
635 635
 			return $manager;
@@ -665,10 +665,10 @@  discard block
 block discarded – undo
665 665
 			}
666 666
 			return new \OC_Defaults();
667 667
 		});
668
-		$this->registerService('EventDispatcher', function () {
668
+		$this->registerService('EventDispatcher', function() {
669 669
 			return new EventDispatcher();
670 670
 		});
671
-		$this->registerService('CryptoWrapper', function (Server $c) {
671
+		$this->registerService('CryptoWrapper', function(Server $c) {
672 672
 			// FIXME: Instantiiated here due to cyclic dependency
673 673
 			$request = new Request(
674 674
 				[
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
 				$request
694 694
 			);
695 695
 		});
696
-		$this->registerService('CsrfTokenManager', function (Server $c) {
696
+		$this->registerService('CsrfTokenManager', function(Server $c) {
697 697
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
698 698
 			$sessionStorage = new SessionStorage($c->getSession());
699 699
 
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 				$sessionStorage
703 703
 			);
704 704
 		});
705
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
705
+		$this->registerService('ContentSecurityPolicyManager', function(Server $c) {
706 706
 			return new ContentSecurityPolicyManager();
707 707
 		});
708 708
 		$this->registerService('ShareManager', function(Server $c) {
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
 	 * @return \OCP\Files\Folder
876 876
 	 */
877 877
 	public function getAppFolder() {
878
-		$dir = '/' . \OC_App::getCurrentApp();
878
+		$dir = '/'.\OC_App::getCurrentApp();
879 879
 		$root = $this->getRootFolder();
880 880
 		if (!$root->nodeExists($dir)) {
881 881
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
lib/private/Session/CryptoSessionData.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@
 block discarded – undo
176 176
 
177 177
 	/**
178 178
 	 * @param mixed $offset
179
-	 * @return mixed
179
+	 * @return string|null
180 180
 	 */
181 181
 	public function offsetGet($offset) {
182 182
 		return $this->get($offset);
Please login to merge, or discard this patch.
Indentation   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -34,167 +34,167 @@
 block discarded – undo
34 34
  * @package OC\Session
35 35
  */
36 36
 class CryptoSessionData implements \ArrayAccess, ISession {
37
-	/** @var ISession */
38
-	protected $session;
39
-	/** @var \OCP\Security\ICrypto */
40
-	protected $crypto;
41
-	/** @var string */
42
-	protected $passphrase;
43
-	/** @var array */
44
-	protected $sessionValues;
45
-	/** @var bool */
46
-	protected $isModified = false;
47
-	CONST encryptedSessionName = 'encrypted_session_data';
48
-
49
-	/**
50
-	 * @param ISession $session
51
-	 * @param ICrypto $crypto
52
-	 * @param string $passphrase
53
-	 */
54
-	public function __construct(ISession $session,
55
-								ICrypto $crypto,
56
-								$passphrase) {
57
-		$this->crypto = $crypto;
58
-		$this->session = $session;
59
-		$this->passphrase = $passphrase;
60
-		$this->initializeSession();
61
-	}
62
-
63
-	/**
64
-	 * Close session if class gets destructed
65
-	 */
66
-	public function __destruct() {
67
-		$this->close();
68
-	}
69
-
70
-	protected function initializeSession() {
71
-		$encryptedSessionData = $this->session->get(self::encryptedSessionName);
72
-		try {
73
-			$this->sessionValues = json_decode(
74
-				$this->crypto->decrypt($encryptedSessionData, $this->passphrase),
75
-				true
76
-			);
77
-		} catch (\Exception $e) {
78
-			$this->sessionValues = [];
79
-		}
80
-	}
81
-
82
-	/**
83
-	 * Set a value in the session
84
-	 *
85
-	 * @param string $key
86
-	 * @param mixed $value
87
-	 */
88
-	public function set($key, $value) {
89
-		$this->sessionValues[$key] = $value;
90
-		$this->isModified = true;
91
-	}
92
-
93
-	/**
94
-	 * Get a value from the session
95
-	 *
96
-	 * @param string $key
97
-	 * @return string|null Either the value or null
98
-	 */
99
-	public function get($key) {
100
-		if(isset($this->sessionValues[$key])) {
101
-			return $this->sessionValues[$key];
102
-		}
103
-
104
-		return null;
105
-	}
106
-
107
-	/**
108
-	 * Check if a named key exists in the session
109
-	 *
110
-	 * @param string $key
111
-	 * @return bool
112
-	 */
113
-	public function exists($key) {
114
-		return isset($this->sessionValues[$key]);
115
-	}
116
-
117
-	/**
118
-	 * Remove a $key/$value pair from the session
119
-	 *
120
-	 * @param string $key
121
-	 */
122
-	public function remove($key) {
123
-		$this->isModified = true;
124
-		unset($this->sessionValues[$key]);
125
-		$this->session->remove(self::encryptedSessionName);
126
-	}
127
-
128
-	/**
129
-	 * Reset and recreate the session
130
-	 */
131
-	public function clear() {
132
-		$this->sessionValues = [];
133
-		$this->isModified = true;
134
-		$this->session->clear();
135
-	}
136
-
137
-	/**
138
-	 * Wrapper around session_regenerate_id
139
-	 *
140
-	 * @param bool $deleteOldSession Whether to delete the old associated session file or not.
141
-	 * @return void
142
-	 */
143
-	public function regenerateId($deleteOldSession = true) {
144
-		$this->session->regenerateId($deleteOldSession);
145
-	}
146
-
147
-	/**
148
-	 * Wrapper around session_id
149
-	 *
150
-	 * @return string
151
-	 * @throws SessionNotAvailableException
152
-	 * @since 9.1.0
153
-	 */
154
-	public function getId() {
155
-		return $this->session->getId();
156
-	}
157
-
158
-	/**
159
-	 * Close the session and release the lock, also writes all changed data in batch
160
-	 */
161
-	public function close() {
162
-		if($this->isModified) {
163
-			$encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
164
-			$this->session->set(self::encryptedSessionName, $encryptedValue);
165
-			$this->isModified = false;
166
-		}
167
-		$this->session->close();
168
-	}
169
-
170
-	/**
171
-	 * @param mixed $offset
172
-	 * @return bool
173
-	 */
174
-	public function offsetExists($offset) {
175
-		return $this->exists($offset);
176
-	}
177
-
178
-	/**
179
-	 * @param mixed $offset
180
-	 * @return mixed
181
-	 */
182
-	public function offsetGet($offset) {
183
-		return $this->get($offset);
184
-	}
185
-
186
-	/**
187
-	 * @param mixed $offset
188
-	 * @param mixed $value
189
-	 */
190
-	public function offsetSet($offset, $value) {
191
-		$this->set($offset, $value);
192
-	}
193
-
194
-	/**
195
-	 * @param mixed $offset
196
-	 */
197
-	public function offsetUnset($offset) {
198
-		$this->remove($offset);
199
-	}
37
+    /** @var ISession */
38
+    protected $session;
39
+    /** @var \OCP\Security\ICrypto */
40
+    protected $crypto;
41
+    /** @var string */
42
+    protected $passphrase;
43
+    /** @var array */
44
+    protected $sessionValues;
45
+    /** @var bool */
46
+    protected $isModified = false;
47
+    CONST encryptedSessionName = 'encrypted_session_data';
48
+
49
+    /**
50
+     * @param ISession $session
51
+     * @param ICrypto $crypto
52
+     * @param string $passphrase
53
+     */
54
+    public function __construct(ISession $session,
55
+                                ICrypto $crypto,
56
+                                $passphrase) {
57
+        $this->crypto = $crypto;
58
+        $this->session = $session;
59
+        $this->passphrase = $passphrase;
60
+        $this->initializeSession();
61
+    }
62
+
63
+    /**
64
+     * Close session if class gets destructed
65
+     */
66
+    public function __destruct() {
67
+        $this->close();
68
+    }
69
+
70
+    protected function initializeSession() {
71
+        $encryptedSessionData = $this->session->get(self::encryptedSessionName);
72
+        try {
73
+            $this->sessionValues = json_decode(
74
+                $this->crypto->decrypt($encryptedSessionData, $this->passphrase),
75
+                true
76
+            );
77
+        } catch (\Exception $e) {
78
+            $this->sessionValues = [];
79
+        }
80
+    }
81
+
82
+    /**
83
+     * Set a value in the session
84
+     *
85
+     * @param string $key
86
+     * @param mixed $value
87
+     */
88
+    public function set($key, $value) {
89
+        $this->sessionValues[$key] = $value;
90
+        $this->isModified = true;
91
+    }
92
+
93
+    /**
94
+     * Get a value from the session
95
+     *
96
+     * @param string $key
97
+     * @return string|null Either the value or null
98
+     */
99
+    public function get($key) {
100
+        if(isset($this->sessionValues[$key])) {
101
+            return $this->sessionValues[$key];
102
+        }
103
+
104
+        return null;
105
+    }
106
+
107
+    /**
108
+     * Check if a named key exists in the session
109
+     *
110
+     * @param string $key
111
+     * @return bool
112
+     */
113
+    public function exists($key) {
114
+        return isset($this->sessionValues[$key]);
115
+    }
116
+
117
+    /**
118
+     * Remove a $key/$value pair from the session
119
+     *
120
+     * @param string $key
121
+     */
122
+    public function remove($key) {
123
+        $this->isModified = true;
124
+        unset($this->sessionValues[$key]);
125
+        $this->session->remove(self::encryptedSessionName);
126
+    }
127
+
128
+    /**
129
+     * Reset and recreate the session
130
+     */
131
+    public function clear() {
132
+        $this->sessionValues = [];
133
+        $this->isModified = true;
134
+        $this->session->clear();
135
+    }
136
+
137
+    /**
138
+     * Wrapper around session_regenerate_id
139
+     *
140
+     * @param bool $deleteOldSession Whether to delete the old associated session file or not.
141
+     * @return void
142
+     */
143
+    public function regenerateId($deleteOldSession = true) {
144
+        $this->session->regenerateId($deleteOldSession);
145
+    }
146
+
147
+    /**
148
+     * Wrapper around session_id
149
+     *
150
+     * @return string
151
+     * @throws SessionNotAvailableException
152
+     * @since 9.1.0
153
+     */
154
+    public function getId() {
155
+        return $this->session->getId();
156
+    }
157
+
158
+    /**
159
+     * Close the session and release the lock, also writes all changed data in batch
160
+     */
161
+    public function close() {
162
+        if($this->isModified) {
163
+            $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
164
+            $this->session->set(self::encryptedSessionName, $encryptedValue);
165
+            $this->isModified = false;
166
+        }
167
+        $this->session->close();
168
+    }
169
+
170
+    /**
171
+     * @param mixed $offset
172
+     * @return bool
173
+     */
174
+    public function offsetExists($offset) {
175
+        return $this->exists($offset);
176
+    }
177
+
178
+    /**
179
+     * @param mixed $offset
180
+     * @return mixed
181
+     */
182
+    public function offsetGet($offset) {
183
+        return $this->get($offset);
184
+    }
185
+
186
+    /**
187
+     * @param mixed $offset
188
+     * @param mixed $value
189
+     */
190
+    public function offsetSet($offset, $value) {
191
+        $this->set($offset, $value);
192
+    }
193
+
194
+    /**
195
+     * @param mixed $offset
196
+     */
197
+    public function offsetUnset($offset) {
198
+        $this->remove($offset);
199
+    }
200 200
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 	 * @return string|null Either the value or null
98 98
 	 */
99 99
 	public function get($key) {
100
-		if(isset($this->sessionValues[$key])) {
100
+		if (isset($this->sessionValues[$key])) {
101 101
 			return $this->sessionValues[$key];
102 102
 		}
103 103
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 	 * Close the session and release the lock, also writes all changed data in batch
160 160
 	 */
161 161
 	public function close() {
162
-		if($this->isModified) {
162
+		if ($this->isModified) {
163 163
 			$encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
164 164
 			$this->session->set(self::encryptedSessionName, $encryptedValue);
165 165
 			$this->isModified = false;
Please login to merge, or discard this patch.