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