Completed
Pull Request — master (#7994)
by Robin
21:10
created
lib/private/Files/Storage/Flysystem.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -54,6 +54,9 @@
 block discarded – undo
54 54
 		$this->flysystem->addPlugin(new GetWithMetadata());
55 55
 	}
56 56
 
57
+	/**
58
+	 * @param string $path
59
+	 */
57 60
 	protected function buildPath($path) {
58 61
 		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59 62
 		return ltrim($fullPath, '/');
Please login to merge, or discard this patch.
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -35,223 +35,223 @@
 block discarded – undo
35 35
  * To use: subclass and call $this->buildFlysystem with the flysystem adapter of choice
36 36
  */
37 37
 abstract class Flysystem extends Common {
38
-	/**
39
-	 * @var Filesystem
40
-	 */
41
-	protected $flysystem;
38
+    /**
39
+     * @var Filesystem
40
+     */
41
+    protected $flysystem;
42 42
 
43
-	/**
44
-	 * @var string
45
-	 */
46
-	protected $root = '';
43
+    /**
44
+     * @var string
45
+     */
46
+    protected $root = '';
47 47
 
48
-	/**
49
-	 * Initialize the storage backend with a flyssytem adapter
50
-	 *
51
-	 * @param \League\Flysystem\AdapterInterface $adapter
52
-	 */
53
-	protected function buildFlySystem(AdapterInterface $adapter) {
54
-		$this->flysystem = new Filesystem($adapter);
55
-		$this->flysystem->addPlugin(new GetWithMetadata());
56
-	}
48
+    /**
49
+     * Initialize the storage backend with a flyssytem adapter
50
+     *
51
+     * @param \League\Flysystem\AdapterInterface $adapter
52
+     */
53
+    protected function buildFlySystem(AdapterInterface $adapter) {
54
+        $this->flysystem = new Filesystem($adapter);
55
+        $this->flysystem->addPlugin(new GetWithMetadata());
56
+    }
57 57
 
58
-	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
-		return ltrim($fullPath, '/');
61
-	}
58
+    protected function buildPath($path) {
59
+        $fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
+        return ltrim($fullPath, '/');
61
+    }
62 62
 
63
-	/**
64
-	 * {@inheritdoc}
65
-	 */
66
-	public function file_get_contents($path) {
67
-		return $this->flysystem->read($this->buildPath($path));
68
-	}
63
+    /**
64
+     * {@inheritdoc}
65
+     */
66
+    public function file_get_contents($path) {
67
+        return $this->flysystem->read($this->buildPath($path));
68
+    }
69 69
 
70
-	/**
71
-	 * {@inheritdoc}
72
-	 */
73
-	public function file_put_contents($path, $data) {
74
-		return $this->flysystem->put($this->buildPath($path), $data);
75
-	}
70
+    /**
71
+     * {@inheritdoc}
72
+     */
73
+    public function file_put_contents($path, $data) {
74
+        return $this->flysystem->put($this->buildPath($path), $data);
75
+    }
76 76
 
77
-	/**
78
-	 * {@inheritdoc}
79
-	 */
80
-	public function file_exists($path) {
81
-		return $this->flysystem->has($this->buildPath($path));
82
-	}
77
+    /**
78
+     * {@inheritdoc}
79
+     */
80
+    public function file_exists($path) {
81
+        return $this->flysystem->has($this->buildPath($path));
82
+    }
83 83
 
84
-	/**
85
-	 * {@inheritdoc}
86
-	 */
87
-	public function unlink($path) {
88
-		if ($this->is_dir($path)) {
89
-			return $this->rmdir($path);
90
-		}
91
-		try {
92
-			return $this->flysystem->delete($this->buildPath($path));
93
-		} catch (FileNotFoundException $e) {
94
-			return false;
95
-		}
96
-	}
84
+    /**
85
+     * {@inheritdoc}
86
+     */
87
+    public function unlink($path) {
88
+        if ($this->is_dir($path)) {
89
+            return $this->rmdir($path);
90
+        }
91
+        try {
92
+            return $this->flysystem->delete($this->buildPath($path));
93
+        } catch (FileNotFoundException $e) {
94
+            return false;
95
+        }
96
+    }
97 97
 
98
-	/**
99
-	 * {@inheritdoc}
100
-	 */
101
-	public function rename($source, $target) {
102
-		if ($this->file_exists($target)) {
103
-			$this->unlink($target);
104
-		}
105
-		return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
-	}
98
+    /**
99
+     * {@inheritdoc}
100
+     */
101
+    public function rename($source, $target) {
102
+        if ($this->file_exists($target)) {
103
+            $this->unlink($target);
104
+        }
105
+        return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
+    }
107 107
 
108
-	/**
109
-	 * {@inheritdoc}
110
-	 */
111
-	public function copy($source, $target) {
112
-		if ($this->file_exists($target)) {
113
-			$this->unlink($target);
114
-		}
115
-		return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
-	}
108
+    /**
109
+     * {@inheritdoc}
110
+     */
111
+    public function copy($source, $target) {
112
+        if ($this->file_exists($target)) {
113
+            $this->unlink($target);
114
+        }
115
+        return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
+    }
117 117
 
118
-	/**
119
-	 * {@inheritdoc}
120
-	 */
121
-	public function filesize($path) {
122
-		if ($this->is_dir($path)) {
123
-			return 0;
124
-		} else {
125
-			return $this->flysystem->getSize($this->buildPath($path));
126
-		}
127
-	}
118
+    /**
119
+     * {@inheritdoc}
120
+     */
121
+    public function filesize($path) {
122
+        if ($this->is_dir($path)) {
123
+            return 0;
124
+        } else {
125
+            return $this->flysystem->getSize($this->buildPath($path));
126
+        }
127
+    }
128 128
 
129
-	/**
130
-	 * {@inheritdoc}
131
-	 */
132
-	public function mkdir($path) {
133
-		if ($this->file_exists($path)) {
134
-			return false;
135
-		}
136
-		return $this->flysystem->createDir($this->buildPath($path));
137
-	}
129
+    /**
130
+     * {@inheritdoc}
131
+     */
132
+    public function mkdir($path) {
133
+        if ($this->file_exists($path)) {
134
+            return false;
135
+        }
136
+        return $this->flysystem->createDir($this->buildPath($path));
137
+    }
138 138
 
139
-	/**
140
-	 * {@inheritdoc}
141
-	 */
142
-	public function filemtime($path) {
143
-		return $this->flysystem->getTimestamp($this->buildPath($path));
144
-	}
139
+    /**
140
+     * {@inheritdoc}
141
+     */
142
+    public function filemtime($path) {
143
+        return $this->flysystem->getTimestamp($this->buildPath($path));
144
+    }
145 145
 
146
-	/**
147
-	 * {@inheritdoc}
148
-	 */
149
-	public function rmdir($path) {
150
-		try {
151
-			return @$this->flysystem->deleteDir($this->buildPath($path));
152
-		} catch (FileNotFoundException $e) {
153
-			return false;
154
-		}
155
-	}
146
+    /**
147
+     * {@inheritdoc}
148
+     */
149
+    public function rmdir($path) {
150
+        try {
151
+            return @$this->flysystem->deleteDir($this->buildPath($path));
152
+        } catch (FileNotFoundException $e) {
153
+            return false;
154
+        }
155
+    }
156 156
 
157
-	/**
158
-	 * {@inheritdoc}
159
-	 */
160
-	public function opendir($path) {
161
-		try {
162
-			$content = $this->flysystem->listContents($this->buildPath($path));
163
-		} catch (FileNotFoundException $e) {
164
-			return false;
165
-		}
166
-		$names = array_map(function ($object) {
167
-			return $object['basename'];
168
-		}, $content);
169
-		return IteratorDirectory::wrap($names);
170
-	}
157
+    /**
158
+     * {@inheritdoc}
159
+     */
160
+    public function opendir($path) {
161
+        try {
162
+            $content = $this->flysystem->listContents($this->buildPath($path));
163
+        } catch (FileNotFoundException $e) {
164
+            return false;
165
+        }
166
+        $names = array_map(function ($object) {
167
+            return $object['basename'];
168
+        }, $content);
169
+        return IteratorDirectory::wrap($names);
170
+    }
171 171
 
172
-	/**
173
-	 * {@inheritdoc}
174
-	 */
175
-	public function fopen($path, $mode) {
176
-		$fullPath = $this->buildPath($path);
177
-		$useExisting = true;
178
-		switch ($mode) {
179
-			case 'r':
180
-			case 'rb':
181
-				try {
182
-					return $this->flysystem->readStream($fullPath);
183
-				} catch (FileNotFoundException $e) {
184
-					return false;
185
-				}
186
-			case 'w':
187
-			case 'w+':
188
-			case 'wb':
189
-			case 'wb+':
190
-				$useExisting = false;
191
-			case 'a':
192
-			case 'ab':
193
-			case 'r+':
194
-			case 'a+':
195
-			case 'x':
196
-			case 'x+':
197
-			case 'c':
198
-			case 'c+':
199
-				//emulate these
200
-				if ($useExisting and $this->file_exists($path)) {
201
-					if (!$this->isUpdatable($path)) {
202
-						return false;
203
-					}
204
-					$tmpFile = $this->getCachedFile($path);
205
-				} else {
206
-					if (!$this->isCreatable(dirname($path))) {
207
-						return false;
208
-					}
209
-					$tmpFile = \OCP\Files::tmpFile();
210
-				}
211
-				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
-					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
-					unlink($tmpFile);
215
-				});
216
-		}
217
-		return false;
218
-	}
172
+    /**
173
+     * {@inheritdoc}
174
+     */
175
+    public function fopen($path, $mode) {
176
+        $fullPath = $this->buildPath($path);
177
+        $useExisting = true;
178
+        switch ($mode) {
179
+            case 'r':
180
+            case 'rb':
181
+                try {
182
+                    return $this->flysystem->readStream($fullPath);
183
+                } catch (FileNotFoundException $e) {
184
+                    return false;
185
+                }
186
+            case 'w':
187
+            case 'w+':
188
+            case 'wb':
189
+            case 'wb+':
190
+                $useExisting = false;
191
+            case 'a':
192
+            case 'ab':
193
+            case 'r+':
194
+            case 'a+':
195
+            case 'x':
196
+            case 'x+':
197
+            case 'c':
198
+            case 'c+':
199
+                //emulate these
200
+                if ($useExisting and $this->file_exists($path)) {
201
+                    if (!$this->isUpdatable($path)) {
202
+                        return false;
203
+                    }
204
+                    $tmpFile = $this->getCachedFile($path);
205
+                } else {
206
+                    if (!$this->isCreatable(dirname($path))) {
207
+                        return false;
208
+                    }
209
+                    $tmpFile = \OCP\Files::tmpFile();
210
+                }
211
+                $source = fopen($tmpFile, $mode);
212
+                return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
+                    $this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
+                    unlink($tmpFile);
215
+                });
216
+        }
217
+        return false;
218
+    }
219 219
 
220
-	/**
221
-	 * {@inheritdoc}
222
-	 */
223
-	public function touch($path, $mtime = null) {
224
-		if ($this->file_exists($path)) {
225
-			return false;
226
-		} else {
227
-			$this->file_put_contents($path, '');
228
-			return true;
229
-		}
230
-	}
220
+    /**
221
+     * {@inheritdoc}
222
+     */
223
+    public function touch($path, $mtime = null) {
224
+        if ($this->file_exists($path)) {
225
+            return false;
226
+        } else {
227
+            $this->file_put_contents($path, '');
228
+            return true;
229
+        }
230
+    }
231 231
 
232
-	/**
233
-	 * {@inheritdoc}
234
-	 */
235
-	public function stat($path) {
236
-		$info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
-		return [
238
-			'mtime' => $info['timestamp'],
239
-			'size' => $info['size']
240
-		];
241
-	}
232
+    /**
233
+     * {@inheritdoc}
234
+     */
235
+    public function stat($path) {
236
+        $info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
+        return [
238
+            'mtime' => $info['timestamp'],
239
+            'size' => $info['size']
240
+        ];
241
+    }
242 242
 
243
-	/**
244
-	 * {@inheritdoc}
245
-	 */
246
-	public function filetype($path) {
247
-		if ($path === '' or $path === '/' or $path === '.') {
248
-			return 'dir';
249
-		}
250
-		try {
251
-			$info = $this->flysystem->getMetadata($this->buildPath($path));
252
-		} catch (FileNotFoundException $e) {
253
-			return false;
254
-		}
255
-		return $info['type'];
256
-	}
243
+    /**
244
+     * {@inheritdoc}
245
+     */
246
+    public function filetype($path) {
247
+        if ($path === '' or $path === '/' or $path === '.') {
248
+            return 'dir';
249
+        }
250
+        try {
251
+            $info = $this->flysystem->getMetadata($this->buildPath($path));
252
+        } catch (FileNotFoundException $e) {
253
+            return false;
254
+        }
255
+        return $info['type'];
256
+    }
257 257
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	}
57 57
 
58 58
 	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59
+		$fullPath = \OC\Files\Filesystem::normalizePath($this->root.'/'.$path);
60 60
 		return ltrim($fullPath, '/');
61 61
 	}
62 62
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		} catch (FileNotFoundException $e) {
164 164
 			return false;
165 165
 		}
166
-		$names = array_map(function ($object) {
166
+		$names = array_map(function($object) {
167 167
 			return $object['basename'];
168 168
 		}, $content);
169 169
 		return IteratorDirectory::wrap($names);
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 					$tmpFile = \OCP\Files::tmpFile();
210 210
 				}
211 211
 				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
212
+				return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath) {
213 213
 					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214 214
 					unlink($tmpFile);
215 215
 				});
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Quota.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@
 block discarded – undo
159 159
 	 * Checks whether the given path is a part file
160 160
 	 *
161 161
 	 * @param string $path Path that may identify a .part file
162
-	 * @return string File path without .part extension
162
+	 * @return boolean File path without .part extension
163 163
 	 * @note this is needed for reusing keys
164 164
 	 */
165 165
 	private function isPartFile($path) {
Please login to merge, or discard this patch.
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -31,172 +31,172 @@
 block discarded – undo
31 31
 
32 32
 class Quota extends Wrapper {
33 33
 
34
-	/**
35
-	 * @var int $quota
36
-	 */
37
-	protected $quota;
38
-
39
-	/**
40
-	 * @var string $sizeRoot
41
-	 */
42
-	protected $sizeRoot;
43
-
44
-	/**
45
-	 * @param array $parameters
46
-	 */
47
-	public function __construct($parameters) {
48
-		$this->storage = $parameters['storage'];
49
-		$this->quota = $parameters['quota'];
50
-		$this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
51
-	}
52
-
53
-	/**
54
-	 * @return int quota value
55
-	 */
56
-	public function getQuota() {
57
-		return $this->quota;
58
-	}
59
-
60
-	/**
61
-	 * @param string $path
62
-	 * @param \OC\Files\Storage\Storage $storage
63
-	 */
64
-	protected function getSize($path, $storage = null) {
65
-		if (is_null($storage)) {
66
-			$cache = $this->getCache();
67
-		} else {
68
-			$cache = $storage->getCache();
69
-		}
70
-		$data = $cache->get($path);
71
-		if ($data instanceof ICacheEntry and isset($data['size'])) {
72
-			return $data['size'];
73
-		} else {
74
-			return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
75
-		}
76
-	}
77
-
78
-	/**
79
-	 * Get free space as limited by the quota
80
-	 *
81
-	 * @param string $path
82
-	 * @return int
83
-	 */
84
-	public function free_space($path) {
85
-		if ($this->quota < 0) {
86
-			return $this->storage->free_space($path);
87
-		} else {
88
-			$used = $this->getSize($this->sizeRoot);
89
-			if ($used < 0) {
90
-				return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
91
-			} else {
92
-				$free = $this->storage->free_space($path);
93
-				$quotaFree = max($this->quota - $used, 0);
94
-				// if free space is known
95
-				if ($free >= 0) {
96
-					$free = min($free, $quotaFree);
97
-				} else {
98
-					$free = $quotaFree;
99
-				}
100
-				return $free;
101
-			}
102
-		}
103
-	}
104
-
105
-	/**
106
-	 * see http://php.net/manual/en/function.file_put_contents.php
107
-	 *
108
-	 * @param string $path
109
-	 * @param string $data
110
-	 * @return bool
111
-	 */
112
-	public function file_put_contents($path, $data) {
113
-		$free = $this->free_space('');
114
-		if ($free < 0 or strlen($data) < $free) {
115
-			return $this->storage->file_put_contents($path, $data);
116
-		} else {
117
-			return false;
118
-		}
119
-	}
120
-
121
-	/**
122
-	 * see http://php.net/manual/en/function.copy.php
123
-	 *
124
-	 * @param string $source
125
-	 * @param string $target
126
-	 * @return bool
127
-	 */
128
-	public function copy($source, $target) {
129
-		$free = $this->free_space('');
130
-		if ($free < 0 or $this->getSize($source) < $free) {
131
-			return $this->storage->copy($source, $target);
132
-		} else {
133
-			return false;
134
-		}
135
-	}
136
-
137
-	/**
138
-	 * see http://php.net/manual/en/function.fopen.php
139
-	 *
140
-	 * @param string $path
141
-	 * @param string $mode
142
-	 * @return resource
143
-	 */
144
-	public function fopen($path, $mode) {
145
-		$source = $this->storage->fopen($path, $mode);
146
-
147
-		// don't apply quota for part files
148
-		if (!$this->isPartFile($path)) {
149
-			$free = $this->free_space('');
150
-			if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
151
-				// only apply quota for files, not metadata, trash or others
152
-				if (strpos(ltrim($path, '/'), 'files/') === 0) {
153
-					return \OC\Files\Stream\Quota::wrap($source, $free);
154
-				}
155
-			}
156
-		}
157
-		return $source;
158
-	}
159
-
160
-	/**
161
-	 * Checks whether the given path is a part file
162
-	 *
163
-	 * @param string $path Path that may identify a .part file
164
-	 * @return string File path without .part extension
165
-	 * @note this is needed for reusing keys
166
-	 */
167
-	private function isPartFile($path) {
168
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
169
-
170
-		return ($extension === 'part');
171
-	}
172
-
173
-	/**
174
-	 * @param IStorage $sourceStorage
175
-	 * @param string $sourceInternalPath
176
-	 * @param string $targetInternalPath
177
-	 * @return bool
178
-	 */
179
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
180
-		$free = $this->free_space('');
181
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
182
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
183
-		} else {
184
-			return false;
185
-		}
186
-	}
187
-
188
-	/**
189
-	 * @param IStorage $sourceStorage
190
-	 * @param string $sourceInternalPath
191
-	 * @param string $targetInternalPath
192
-	 * @return bool
193
-	 */
194
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
195
-		$free = $this->free_space('');
196
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
197
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
198
-		} else {
199
-			return false;
200
-		}
201
-	}
34
+    /**
35
+     * @var int $quota
36
+     */
37
+    protected $quota;
38
+
39
+    /**
40
+     * @var string $sizeRoot
41
+     */
42
+    protected $sizeRoot;
43
+
44
+    /**
45
+     * @param array $parameters
46
+     */
47
+    public function __construct($parameters) {
48
+        $this->storage = $parameters['storage'];
49
+        $this->quota = $parameters['quota'];
50
+        $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
51
+    }
52
+
53
+    /**
54
+     * @return int quota value
55
+     */
56
+    public function getQuota() {
57
+        return $this->quota;
58
+    }
59
+
60
+    /**
61
+     * @param string $path
62
+     * @param \OC\Files\Storage\Storage $storage
63
+     */
64
+    protected function getSize($path, $storage = null) {
65
+        if (is_null($storage)) {
66
+            $cache = $this->getCache();
67
+        } else {
68
+            $cache = $storage->getCache();
69
+        }
70
+        $data = $cache->get($path);
71
+        if ($data instanceof ICacheEntry and isset($data['size'])) {
72
+            return $data['size'];
73
+        } else {
74
+            return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
75
+        }
76
+    }
77
+
78
+    /**
79
+     * Get free space as limited by the quota
80
+     *
81
+     * @param string $path
82
+     * @return int
83
+     */
84
+    public function free_space($path) {
85
+        if ($this->quota < 0) {
86
+            return $this->storage->free_space($path);
87
+        } else {
88
+            $used = $this->getSize($this->sizeRoot);
89
+            if ($used < 0) {
90
+                return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
91
+            } else {
92
+                $free = $this->storage->free_space($path);
93
+                $quotaFree = max($this->quota - $used, 0);
94
+                // if free space is known
95
+                if ($free >= 0) {
96
+                    $free = min($free, $quotaFree);
97
+                } else {
98
+                    $free = $quotaFree;
99
+                }
100
+                return $free;
101
+            }
102
+        }
103
+    }
104
+
105
+    /**
106
+     * see http://php.net/manual/en/function.file_put_contents.php
107
+     *
108
+     * @param string $path
109
+     * @param string $data
110
+     * @return bool
111
+     */
112
+    public function file_put_contents($path, $data) {
113
+        $free = $this->free_space('');
114
+        if ($free < 0 or strlen($data) < $free) {
115
+            return $this->storage->file_put_contents($path, $data);
116
+        } else {
117
+            return false;
118
+        }
119
+    }
120
+
121
+    /**
122
+     * see http://php.net/manual/en/function.copy.php
123
+     *
124
+     * @param string $source
125
+     * @param string $target
126
+     * @return bool
127
+     */
128
+    public function copy($source, $target) {
129
+        $free = $this->free_space('');
130
+        if ($free < 0 or $this->getSize($source) < $free) {
131
+            return $this->storage->copy($source, $target);
132
+        } else {
133
+            return false;
134
+        }
135
+    }
136
+
137
+    /**
138
+     * see http://php.net/manual/en/function.fopen.php
139
+     *
140
+     * @param string $path
141
+     * @param string $mode
142
+     * @return resource
143
+     */
144
+    public function fopen($path, $mode) {
145
+        $source = $this->storage->fopen($path, $mode);
146
+
147
+        // don't apply quota for part files
148
+        if (!$this->isPartFile($path)) {
149
+            $free = $this->free_space('');
150
+            if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
151
+                // only apply quota for files, not metadata, trash or others
152
+                if (strpos(ltrim($path, '/'), 'files/') === 0) {
153
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
154
+                }
155
+            }
156
+        }
157
+        return $source;
158
+    }
159
+
160
+    /**
161
+     * Checks whether the given path is a part file
162
+     *
163
+     * @param string $path Path that may identify a .part file
164
+     * @return string File path without .part extension
165
+     * @note this is needed for reusing keys
166
+     */
167
+    private function isPartFile($path) {
168
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
169
+
170
+        return ($extension === 'part');
171
+    }
172
+
173
+    /**
174
+     * @param IStorage $sourceStorage
175
+     * @param string $sourceInternalPath
176
+     * @param string $targetInternalPath
177
+     * @return bool
178
+     */
179
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
180
+        $free = $this->free_space('');
181
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
182
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
183
+        } else {
184
+            return false;
185
+        }
186
+    }
187
+
188
+    /**
189
+     * @param IStorage $sourceStorage
190
+     * @param string $sourceInternalPath
191
+     * @param string $targetInternalPath
192
+     * @return bool
193
+     */
194
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
195
+        $free = $this->free_space('');
196
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
197
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
198
+        } else {
199
+            return false;
200
+        }
201
+    }
202 202
 }
Please login to merge, or discard this patch.
lib/private/L10N/L10N.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@
 block discarded – undo
176 176
 	 * Returns an associative array with all translations
177 177
 	 *
178 178
 	 * Called by \OC_L10N_String
179
-	 * @return array
179
+	 * @return string[]
180 180
 	 */
181 181
 	public function getTranslations() {
182 182
 		return $this->translations;
Please login to merge, or discard this patch.
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -29,196 +29,196 @@
 block discarded – undo
29 29
 
30 30
 class L10N implements IL10N {
31 31
 
32
-	/** @var IFactory */
33
-	protected $factory;
34
-
35
-	/** @var string App of this object */
36
-	protected $app;
37
-
38
-	/** @var string Language of this object */
39
-	protected $lang;
40
-
41
-	/** @var string Plural forms (string) */
42
-	private $pluralFormString = 'nplurals=2; plural=(n != 1);';
43
-
44
-	/** @var string Plural forms (function) */
45
-	private $pluralFormFunction = null;
46
-
47
-	/** @var string[] */
48
-	private $translations = [];
49
-
50
-	/**
51
-	 * @param IFactory $factory
52
-	 * @param string $app
53
-	 * @param string $lang
54
-	 * @param array $files
55
-	 */
56
-	public function __construct(IFactory $factory, $app, $lang, array $files) {
57
-		$this->factory = $factory;
58
-		$this->app = $app;
59
-		$this->lang = $lang;
60
-
61
-		$this->translations = [];
62
-		foreach ($files as $languageFile) {
63
-			$this->load($languageFile);
64
-		}
65
-	}
66
-
67
-	/**
68
-	 * The code (en, de, ...) of the language that is used for this instance
69
-	 *
70
-	 * @return string language
71
-	 */
72
-	public function getLanguageCode() {
73
-		return $this->lang;
74
-	}
75
-
76
-	/**
77
-	 * Translating
78
-	 * @param string $text The text we need a translation for
79
-	 * @param array $parameters default:array() Parameters for sprintf
80
-	 * @return string Translation or the same text
81
-	 *
82
-	 * Returns the translation. If no translation is found, $text will be
83
-	 * returned.
84
-	 */
85
-	public function t($text, $parameters = array()) {
86
-		return (string) new L10NString($this, $text, $parameters);
87
-	}
88
-
89
-	/**
90
-	 * Translating
91
-	 * @param string $text_singular the string to translate for exactly one object
92
-	 * @param string $text_plural the string to translate for n objects
93
-	 * @param integer $count Number of objects
94
-	 * @param array $parameters default:array() Parameters for sprintf
95
-	 * @return string Translation or the same text
96
-	 *
97
-	 * Returns the translation. If no translation is found, $text will be
98
-	 * returned. %n will be replaced with the number of objects.
99
-	 *
100
-	 * The correct plural is determined by the plural_forms-function
101
-	 * provided by the po file.
102
-	 *
103
-	 */
104
-	public function n($text_singular, $text_plural, $count, $parameters = array()) {
105
-		$identifier = "_${text_singular}_::_${text_plural}_";
106
-		if (isset($this->translations[$identifier])) {
107
-			return (string) new L10NString($this, $identifier, $parameters, $count);
108
-		} else {
109
-			if ($count === 1) {
110
-				return (string) new L10NString($this, $text_singular, $parameters, $count);
111
-			} else {
112
-				return (string) new L10NString($this, $text_plural, $parameters, $count);
113
-			}
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * Localization
119
-	 * @param string $type Type of localization
120
-	 * @param \DateTime|int|string $data parameters for this localization
121
-	 * @param array $options
122
-	 * @return string|int|false
123
-	 *
124
-	 * Returns the localized data.
125
-	 *
126
-	 * Implemented types:
127
-	 *  - date
128
-	 *    - Creates a date
129
-	 *    - params: timestamp (int/string)
130
-	 *  - datetime
131
-	 *    - Creates date and time
132
-	 *    - params: timestamp (int/string)
133
-	 *  - time
134
-	 *    - Creates a time
135
-	 *    - params: timestamp (int/string)
136
-	 *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
137
-	 *  - jsdate: Returns the short JS date format
138
-	 */
139
-	public function l($type, $data = null, $options = array()) {
140
-		// Use the language of the instance
141
-		$locale = $this->getLanguageCode();
142
-		if ($locale === 'sr@latin') {
143
-			$locale = 'sr_latn';
144
-		}
145
-
146
-		if ($type === 'firstday') {
147
-			return (int) Calendar::getFirstWeekday($locale);
148
-		}
149
-		if ($type === 'jsdate') {
150
-			return (string) Calendar::getDateFormat('short', $locale);
151
-		}
152
-
153
-		$value = new \DateTime();
154
-		if ($data instanceof \DateTime) {
155
-			$value = $data;
156
-		} else if (is_string($data) && !is_numeric($data)) {
157
-			$data = strtotime($data);
158
-			$value->setTimestamp($data);
159
-		} else if ($data !== null) {
160
-			$value->setTimestamp($data);
161
-		}
162
-
163
-		$options = array_merge(array('width' => 'long'), $options);
164
-		$width = $options['width'];
165
-		switch ($type) {
166
-			case 'date':
167
-				return (string) Calendar::formatDate($value, $width, $locale);
168
-			case 'datetime':
169
-				return (string) Calendar::formatDatetime($value, $width, $locale);
170
-			case 'time':
171
-				return (string) Calendar::formatTime($value, $width, $locale);
172
-			case 'weekdayName':
173
-				return (string) Calendar::getWeekdayName($value, $width, $locale);
174
-			default:
175
-				return false;
176
-		}
177
-	}
178
-
179
-	/**
180
-	 * Returns an associative array with all translations
181
-	 *
182
-	 * Called by \OC_L10N_String
183
-	 * @return array
184
-	 */
185
-	public function getTranslations() {
186
-		return $this->translations;
187
-	}
188
-
189
-	/**
190
-	 * Returnsed function accepts the argument $n
191
-	 *
192
-	 * Called by \OC_L10N_String
193
-	 * @return string the plural form function
194
-	 */
195
-	public function getPluralFormFunction() {
196
-		if (is_null($this->pluralFormFunction)) {
197
-			$lang = $this->getLanguageCode();
198
-			$this->pluralFormFunction = function($n) use ($lang) {
199
-				return PluralizationRules::get($n, $lang);
200
-			};
201
-		}
202
-
203
-		return $this->pluralFormFunction;
204
-	}
205
-
206
-	/**
207
-	 * @param $translationFile
208
-	 * @return bool
209
-	 */
210
-	protected function load($translationFile) {
211
-		$json = json_decode(file_get_contents($translationFile), true);
212
-		if (!is_array($json)) {
213
-			$jsonError = json_last_error();
214
-			\OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
215
-			return false;
216
-		}
217
-
218
-		if (!empty($json['pluralForm'])) {
219
-			$this->pluralFormString = $json['pluralForm'];
220
-		}
221
-		$this->translations = array_merge($this->translations, $json['translations']);
222
-		return true;
223
-	}
32
+    /** @var IFactory */
33
+    protected $factory;
34
+
35
+    /** @var string App of this object */
36
+    protected $app;
37
+
38
+    /** @var string Language of this object */
39
+    protected $lang;
40
+
41
+    /** @var string Plural forms (string) */
42
+    private $pluralFormString = 'nplurals=2; plural=(n != 1);';
43
+
44
+    /** @var string Plural forms (function) */
45
+    private $pluralFormFunction = null;
46
+
47
+    /** @var string[] */
48
+    private $translations = [];
49
+
50
+    /**
51
+     * @param IFactory $factory
52
+     * @param string $app
53
+     * @param string $lang
54
+     * @param array $files
55
+     */
56
+    public function __construct(IFactory $factory, $app, $lang, array $files) {
57
+        $this->factory = $factory;
58
+        $this->app = $app;
59
+        $this->lang = $lang;
60
+
61
+        $this->translations = [];
62
+        foreach ($files as $languageFile) {
63
+            $this->load($languageFile);
64
+        }
65
+    }
66
+
67
+    /**
68
+     * The code (en, de, ...) of the language that is used for this instance
69
+     *
70
+     * @return string language
71
+     */
72
+    public function getLanguageCode() {
73
+        return $this->lang;
74
+    }
75
+
76
+    /**
77
+     * Translating
78
+     * @param string $text The text we need a translation for
79
+     * @param array $parameters default:array() Parameters for sprintf
80
+     * @return string Translation or the same text
81
+     *
82
+     * Returns the translation. If no translation is found, $text will be
83
+     * returned.
84
+     */
85
+    public function t($text, $parameters = array()) {
86
+        return (string) new L10NString($this, $text, $parameters);
87
+    }
88
+
89
+    /**
90
+     * Translating
91
+     * @param string $text_singular the string to translate for exactly one object
92
+     * @param string $text_plural the string to translate for n objects
93
+     * @param integer $count Number of objects
94
+     * @param array $parameters default:array() Parameters for sprintf
95
+     * @return string Translation or the same text
96
+     *
97
+     * Returns the translation. If no translation is found, $text will be
98
+     * returned. %n will be replaced with the number of objects.
99
+     *
100
+     * The correct plural is determined by the plural_forms-function
101
+     * provided by the po file.
102
+     *
103
+     */
104
+    public function n($text_singular, $text_plural, $count, $parameters = array()) {
105
+        $identifier = "_${text_singular}_::_${text_plural}_";
106
+        if (isset($this->translations[$identifier])) {
107
+            return (string) new L10NString($this, $identifier, $parameters, $count);
108
+        } else {
109
+            if ($count === 1) {
110
+                return (string) new L10NString($this, $text_singular, $parameters, $count);
111
+            } else {
112
+                return (string) new L10NString($this, $text_plural, $parameters, $count);
113
+            }
114
+        }
115
+    }
116
+
117
+    /**
118
+     * Localization
119
+     * @param string $type Type of localization
120
+     * @param \DateTime|int|string $data parameters for this localization
121
+     * @param array $options
122
+     * @return string|int|false
123
+     *
124
+     * Returns the localized data.
125
+     *
126
+     * Implemented types:
127
+     *  - date
128
+     *    - Creates a date
129
+     *    - params: timestamp (int/string)
130
+     *  - datetime
131
+     *    - Creates date and time
132
+     *    - params: timestamp (int/string)
133
+     *  - time
134
+     *    - Creates a time
135
+     *    - params: timestamp (int/string)
136
+     *  - firstday: Returns the first day of the week (0 sunday - 6 saturday)
137
+     *  - jsdate: Returns the short JS date format
138
+     */
139
+    public function l($type, $data = null, $options = array()) {
140
+        // Use the language of the instance
141
+        $locale = $this->getLanguageCode();
142
+        if ($locale === 'sr@latin') {
143
+            $locale = 'sr_latn';
144
+        }
145
+
146
+        if ($type === 'firstday') {
147
+            return (int) Calendar::getFirstWeekday($locale);
148
+        }
149
+        if ($type === 'jsdate') {
150
+            return (string) Calendar::getDateFormat('short', $locale);
151
+        }
152
+
153
+        $value = new \DateTime();
154
+        if ($data instanceof \DateTime) {
155
+            $value = $data;
156
+        } else if (is_string($data) && !is_numeric($data)) {
157
+            $data = strtotime($data);
158
+            $value->setTimestamp($data);
159
+        } else if ($data !== null) {
160
+            $value->setTimestamp($data);
161
+        }
162
+
163
+        $options = array_merge(array('width' => 'long'), $options);
164
+        $width = $options['width'];
165
+        switch ($type) {
166
+            case 'date':
167
+                return (string) Calendar::formatDate($value, $width, $locale);
168
+            case 'datetime':
169
+                return (string) Calendar::formatDatetime($value, $width, $locale);
170
+            case 'time':
171
+                return (string) Calendar::formatTime($value, $width, $locale);
172
+            case 'weekdayName':
173
+                return (string) Calendar::getWeekdayName($value, $width, $locale);
174
+            default:
175
+                return false;
176
+        }
177
+    }
178
+
179
+    /**
180
+     * Returns an associative array with all translations
181
+     *
182
+     * Called by \OC_L10N_String
183
+     * @return array
184
+     */
185
+    public function getTranslations() {
186
+        return $this->translations;
187
+    }
188
+
189
+    /**
190
+     * Returnsed function accepts the argument $n
191
+     *
192
+     * Called by \OC_L10N_String
193
+     * @return string the plural form function
194
+     */
195
+    public function getPluralFormFunction() {
196
+        if (is_null($this->pluralFormFunction)) {
197
+            $lang = $this->getLanguageCode();
198
+            $this->pluralFormFunction = function($n) use ($lang) {
199
+                return PluralizationRules::get($n, $lang);
200
+            };
201
+        }
202
+
203
+        return $this->pluralFormFunction;
204
+    }
205
+
206
+    /**
207
+     * @param $translationFile
208
+     * @return bool
209
+     */
210
+    protected function load($translationFile) {
211
+        $json = json_decode(file_get_contents($translationFile), true);
212
+        if (!is_array($json)) {
213
+            $jsonError = json_last_error();
214
+            \OC::$server->getLogger()->warning("Failed to load $translationFile - json error code: $jsonError", ['app' => 'l10n']);
215
+            return false;
216
+        }
217
+
218
+        if (!empty($json['pluralForm'])) {
219
+            $this->pluralFormString = $json['pluralForm'];
220
+        }
221
+        $this->translations = array_merge($this->translations, $json['translations']);
222
+        return true;
223
+    }
224 224
 }
Please login to merge, or discard this patch.
lib/private/legacy/api.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -331,7 +331,7 @@
 block discarded – undo
331 331
 
332 332
 	/**
333 333
 	 * http basic auth
334
-	 * @return string|false (username, or false on failure)
334
+	 * @return string (username, or false on failure)
335 335
 	 */
336 336
 	private static function loginUser() {
337 337
 		if(self::$isLoggedIn === true) {
Please login to merge, or discard this patch.
Indentation   +459 added lines, -459 removed lines patch added patch discarded remove patch
@@ -37,463 +37,463 @@
 block discarded – undo
37 37
 
38 38
 class OC_API {
39 39
 
40
-	/**
41
-	 * API authentication levels
42
-	 */
43
-
44
-	/** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
-	const GUEST_AUTH = 0;
46
-
47
-	/** @deprecated Use \OCP\API::USER_AUTH instead */
48
-	const USER_AUTH = 1;
49
-
50
-	/** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
-	const SUBADMIN_AUTH = 2;
52
-
53
-	/** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
-	const ADMIN_AUTH = 3;
55
-
56
-	/**
57
-	 * API Response Codes
58
-	 */
59
-
60
-	/** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
-	const RESPOND_UNAUTHORISED = 997;
62
-
63
-	/** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
-	const RESPOND_SERVER_ERROR = 996;
65
-
66
-	/** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
-	const RESPOND_NOT_FOUND = 998;
68
-
69
-	/** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
-	const RESPOND_UNKNOWN_ERROR = 999;
71
-
72
-	/**
73
-	 * api actions
74
-	 */
75
-	protected static $actions = array();
76
-	private static $logoutRequired = false;
77
-	private static $isLoggedIn = false;
78
-
79
-	/**
80
-	 * registers an api call
81
-	 * @param string $method the http method
82
-	 * @param string $url the url to match
83
-	 * @param callable $action the function to run
84
-	 * @param string $app the id of the app registering the call
85
-	 * @param int $authLevel the level of authentication required for the call
86
-	 * @param array $defaults
87
-	 * @param array $requirements
88
-	 */
89
-	public static function register($method, $url, $action, $app,
90
-				$authLevel = API::USER_AUTH,
91
-				$defaults = array(),
92
-				$requirements = array()) {
93
-		$name = strtolower($method).$url;
94
-		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
96
-			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
-			OC::$server->getRouter()->useCollection('ocs');
98
-			OC::$server->getRouter()->create($name, $url)
99
-				->method($method)
100
-				->defaults($defaults)
101
-				->requirements($requirements)
102
-				->action('OC_API', 'call');
103
-			self::$actions[$name] = array();
104
-			OC::$server->getRouter()->useCollection($oldCollection);
105
-		}
106
-		self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
-	}
108
-
109
-	/**
110
-	 * handles an api call
111
-	 * @param array $parameters
112
-	 */
113
-	public static function call($parameters) {
114
-		$request = \OC::$server->getRequest();
115
-		$method = $request->getMethod();
116
-
117
-		// Prepare the request variables
118
-		if($method === 'PUT') {
119
-			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
121
-			$parameters['_delete'] = $request->getParams();
122
-		}
123
-		$name = $parameters['_route'];
124
-		// Foreach registered action
125
-		$responses = array();
126
-		$appManager = \OC::$server->getAppManager();
127
-		foreach(self::$actions[$name] as $action) {
128
-			// Check authentication and availability
129
-			if(!self::isAuthorised($action)) {
130
-				$responses[] = array(
131
-					'app' => $action['app'],
132
-					'response' => new \OC\OCS\Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
133
-					'shipped' => $appManager->isShipped($action['app']),
134
-					);
135
-				continue;
136
-			}
137
-			if(!is_callable($action['action'])) {
138
-				$responses[] = array(
139
-					'app' => $action['app'],
140
-					'response' => new \OC\OCS\Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
141
-					'shipped' => $appManager->isShipped($action['app']),
142
-					);
143
-				continue;
144
-			}
145
-			// Run the action
146
-			$responses[] = array(
147
-				'app' => $action['app'],
148
-				'response' => call_user_func($action['action'], $parameters),
149
-				'shipped' => $appManager->isShipped($action['app']),
150
-				);
151
-		}
152
-		$response = self::mergeResponses($responses);
153
-		$format = self::requestedFormat();
154
-		if (self::$logoutRequired) {
155
-			\OC::$server->getUserSession()->logout();
156
-		}
157
-
158
-		self::respond($response, $format);
159
-	}
160
-
161
-	/**
162
-	 * merge the returned result objects into one response
163
-	 * @param array $responses
164
-	 * @return \OC\OCS\Result
165
-	 */
166
-	public static function mergeResponses($responses) {
167
-		// Sort into shipped and third-party
168
-		$shipped = array(
169
-			'succeeded' => array(),
170
-			'failed' => array(),
171
-			);
172
-		$thirdparty = array(
173
-			'succeeded' => array(),
174
-			'failed' => array(),
175
-			);
176
-
177
-		foreach($responses as $response) {
178
-			if($response['shipped'] || ($response['app'] === 'core')) {
179
-				if($response['response']->succeeded()) {
180
-					$shipped['succeeded'][$response['app']] = $response;
181
-				} else {
182
-					$shipped['failed'][$response['app']] = $response;
183
-				}
184
-			} else {
185
-				if($response['response']->succeeded()) {
186
-					$thirdparty['succeeded'][$response['app']] = $response;
187
-				} else {
188
-					$thirdparty['failed'][$response['app']] = $response;
189
-				}
190
-			}
191
-		}
192
-
193
-		// Remove any error responses if there is one shipped response that succeeded
194
-		if(!empty($shipped['failed'])) {
195
-			// Which shipped response do we use if they all failed?
196
-			// They may have failed for different reasons (different status codes)
197
-			// Which response code should we return?
198
-			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
199
-			// Merge failed responses if more than one
200
-			$data = array();
201
-			foreach($shipped['failed'] as $failure) {
202
-				$data = array_merge_recursive($data, $failure['response']->getData());
203
-			}
204
-			$picked = reset($shipped['failed']);
205
-			$code = $picked['response']->getStatusCode();
206
-			$meta = $picked['response']->getMeta();
207
-			$headers = $picked['response']->getHeaders();
208
-			$response = new \OC\OCS\Result($data, $code, $meta['message'], $headers);
209
-			return $response;
210
-		} elseif(!empty($shipped['succeeded'])) {
211
-			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
212
-		} elseif(!empty($thirdparty['failed'])) {
213
-			// Merge failed responses if more than one
214
-			$data = array();
215
-			foreach($thirdparty['failed'] as $failure) {
216
-				$data = array_merge_recursive($data, $failure['response']->getData());
217
-			}
218
-			$picked = reset($thirdparty['failed']);
219
-			$code = $picked['response']->getStatusCode();
220
-			$meta = $picked['response']->getMeta();
221
-			$headers = $picked['response']->getHeaders();
222
-			$response = new \OC\OCS\Result($data, $code, $meta['message'], $headers);
223
-			return $response;
224
-		} else {
225
-			$responses = $thirdparty['succeeded'];
226
-		}
227
-		// Merge the successful responses
228
-		$data = [];
229
-		$codes = [];
230
-		$header = [];
231
-
232
-		foreach($responses as $response) {
233
-			if($response['shipped']) {
234
-				$data = array_merge_recursive($response['response']->getData(), $data);
235
-			} else {
236
-				$data = array_merge_recursive($data, $response['response']->getData());
237
-			}
238
-			$header = array_merge_recursive($header, $response['response']->getHeaders());
239
-			$codes[] = ['code' => $response['response']->getStatusCode(),
240
-				'meta' => $response['response']->getMeta()];
241
-		}
242
-
243
-		// Use any non 100 status codes
244
-		$statusCode = 100;
245
-		$statusMessage = null;
246
-		foreach($codes as $code) {
247
-			if($code['code'] != 100) {
248
-				$statusCode = $code['code'];
249
-				$statusMessage = $code['meta']['message'];
250
-				break;
251
-			}
252
-		}
253
-
254
-		return new \OC\OCS\Result($data, $statusCode, $statusMessage, $header);
255
-	}
256
-
257
-	/**
258
-	 * authenticate the api call
259
-	 * @param array $action the action details as supplied to OC_API::register()
260
-	 * @return bool
261
-	 */
262
-	private static function isAuthorised($action) {
263
-		$level = $action['authlevel'];
264
-		switch($level) {
265
-			case API::GUEST_AUTH:
266
-				// Anyone can access
267
-				return true;
268
-			case API::USER_AUTH:
269
-				// User required
270
-				return self::loginUser();
271
-			case API::SUBADMIN_AUTH:
272
-				// Check for subadmin
273
-				$user = self::loginUser();
274
-				if(!$user) {
275
-					return false;
276
-				} else {
277
-					$userObject = \OC::$server->getUserSession()->getUser();
278
-					if($userObject === null) {
279
-						return false;
280
-					}
281
-					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
282
-					$admin = OC_User::isAdminUser($user);
283
-					if($isSubAdmin || $admin) {
284
-						return true;
285
-					} else {
286
-						return false;
287
-					}
288
-				}
289
-			case API::ADMIN_AUTH:
290
-				// Check for admin
291
-				$user = self::loginUser();
292
-				if(!$user) {
293
-					return false;
294
-				} else {
295
-					return OC_User::isAdminUser($user);
296
-				}
297
-			default:
298
-				// oops looks like invalid level supplied
299
-				return false;
300
-		}
301
-	}
302
-
303
-	/**
304
-	 * http basic auth
305
-	 * @return string|false (username, or false on failure)
306
-	 */
307
-	private static function loginUser() {
308
-		if(self::$isLoggedIn === true) {
309
-			return \OC_User::getUser();
310
-		}
311
-
312
-		// reuse existing login
313
-		$loggedIn = \OC::$server->getUserSession()->isLoggedIn();
314
-		if ($loggedIn === true) {
315
-			if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
316
-				// Do not allow access to OCS until the 2FA challenge was solved successfully
317
-				return false;
318
-			}
319
-			$ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
320
-			if ($ocsApiRequest) {
321
-
322
-				// initialize the user's filesystem
323
-				\OC_Util::setupFS(\OC_User::getUser());
324
-				self::$isLoggedIn = true;
325
-
326
-				return OC_User::getUser();
327
-			}
328
-			return false;
329
-		}
330
-
331
-		// basic auth - because OC_User::login will create a new session we shall only try to login
332
-		// if user and pass are set
333
-		$userSession = \OC::$server->getUserSession();
334
-		$request = \OC::$server->getRequest();
335
-		try {
336
-			if ($userSession->tryTokenLogin($request)
337
-				|| $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
338
-				self::$logoutRequired = true;
339
-			} else {
340
-				return false;
341
-			}
342
-			// initialize the user's filesystem
343
-			\OC_Util::setupFS(\OC_User::getUser());
344
-			self::$isLoggedIn = true;
345
-
346
-			return \OC_User::getUser();
347
-		} catch (\OC\User\LoginException $e) {
348
-			return false;
349
-		}
350
-	}
351
-
352
-	/**
353
-	 * respond to a call
354
-	 * @param \OC\OCS\Result $result
355
-	 * @param string $format the format xml|json
356
-	 */
357
-	public static function respond($result, $format='xml') {
358
-		$request = \OC::$server->getRequest();
359
-
360
-		// Send 401 headers if unauthorised
361
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
362
-			// If request comes from JS return dummy auth request
363
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
364
-				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
365
-			} else {
366
-				header('WWW-Authenticate: Basic realm="Authorisation Required"');
367
-			}
368
-			header('HTTP/1.0 401 Unauthorized');
369
-		}
370
-
371
-		foreach($result->getHeaders() as $name => $value) {
372
-			header($name . ': ' . $value);
373
-		}
374
-
375
-		$meta = $result->getMeta();
376
-		$data = $result->getData();
377
-		if (self::isV2($request)) {
378
-			$statusCode = self::mapStatusCodes($result->getStatusCode());
379
-			if (!is_null($statusCode)) {
380
-				$meta['statuscode'] = $statusCode;
381
-				OC_Response::setStatus($statusCode);
382
-			}
383
-		}
384
-
385
-		self::setContentType($format);
386
-		$body = self::renderResult($format, $meta, $data);
387
-		echo $body;
388
-	}
389
-
390
-	/**
391
-	 * @param XMLWriter $writer
392
-	 */
393
-	private static function toXML($array, $writer) {
394
-		foreach($array as $k => $v) {
395
-			if ($k[0] === '@') {
396
-				$writer->writeAttribute(substr($k, 1), $v);
397
-				continue;
398
-			} else if (is_numeric($k)) {
399
-				$k = 'element';
400
-			}
401
-			if(is_array($v)) {
402
-				$writer->startElement($k);
403
-				self::toXML($v, $writer);
404
-				$writer->endElement();
405
-			} else {
406
-				$writer->writeElement($k, $v);
407
-			}
408
-		}
409
-	}
410
-
411
-	/**
412
-	 * @return string
413
-	 */
414
-	public static function requestedFormat() {
415
-		$formats = array('json', 'xml');
416
-
417
-		$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
418
-		return $format;
419
-	}
420
-
421
-	/**
422
-	 * Based on the requested format the response content type is set
423
-	 * @param string $format
424
-	 */
425
-	public static function setContentType($format = null) {
426
-		$format = is_null($format) ? self::requestedFormat() : $format;
427
-		if ($format === 'xml') {
428
-			header('Content-type: text/xml; charset=UTF-8');
429
-			return;
430
-		}
431
-
432
-		if ($format === 'json') {
433
-			header('Content-Type: application/json; charset=utf-8');
434
-			return;
435
-		}
436
-
437
-		header('Content-Type: application/octet-stream; charset=utf-8');
438
-	}
439
-
440
-	/**
441
-	 * @param \OCP\IRequest $request
442
-	 * @return bool
443
-	 */
444
-	protected static function isV2(\OCP\IRequest $request) {
445
-		$script = $request->getScriptName();
446
-
447
-		return substr($script, -11) === '/ocs/v2.php';
448
-	}
449
-
450
-	/**
451
-	 * @param integer $sc
452
-	 * @return int
453
-	 */
454
-	public static function mapStatusCodes($sc) {
455
-		switch ($sc) {
456
-			case API::RESPOND_NOT_FOUND:
457
-				return Http::STATUS_NOT_FOUND;
458
-			case API::RESPOND_SERVER_ERROR:
459
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
460
-			case API::RESPOND_UNKNOWN_ERROR:
461
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
462
-			case API::RESPOND_UNAUTHORISED:
463
-				// already handled for v1
464
-				return null;
465
-			case 100:
466
-				return Http::STATUS_OK;
467
-		}
468
-		// any 2xx, 4xx and 5xx will be used as is
469
-		if ($sc >= 200 && $sc < 600) {
470
-			return $sc;
471
-		}
472
-
473
-		return Http::STATUS_BAD_REQUEST;
474
-	}
475
-
476
-	/**
477
-	 * @param string $format
478
-	 * @return string
479
-	 */
480
-	public static function renderResult($format, $meta, $data) {
481
-		$response = array(
482
-			'ocs' => array(
483
-				'meta' => $meta,
484
-				'data' => $data,
485
-			),
486
-		);
487
-		if ($format == 'json') {
488
-			return OC_JSON::encode($response);
489
-		}
490
-
491
-		$writer = new XMLWriter();
492
-		$writer->openMemory();
493
-		$writer->setIndent(true);
494
-		$writer->startDocument();
495
-		self::toXML($response, $writer);
496
-		$writer->endDocument();
497
-		return $writer->outputMemory(true);
498
-	}
40
+    /**
41
+     * API authentication levels
42
+     */
43
+
44
+    /** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
+    const GUEST_AUTH = 0;
46
+
47
+    /** @deprecated Use \OCP\API::USER_AUTH instead */
48
+    const USER_AUTH = 1;
49
+
50
+    /** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
+    const SUBADMIN_AUTH = 2;
52
+
53
+    /** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
+    const ADMIN_AUTH = 3;
55
+
56
+    /**
57
+     * API Response Codes
58
+     */
59
+
60
+    /** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
+    const RESPOND_UNAUTHORISED = 997;
62
+
63
+    /** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
+    const RESPOND_SERVER_ERROR = 996;
65
+
66
+    /** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
+    const RESPOND_NOT_FOUND = 998;
68
+
69
+    /** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
+    const RESPOND_UNKNOWN_ERROR = 999;
71
+
72
+    /**
73
+     * api actions
74
+     */
75
+    protected static $actions = array();
76
+    private static $logoutRequired = false;
77
+    private static $isLoggedIn = false;
78
+
79
+    /**
80
+     * registers an api call
81
+     * @param string $method the http method
82
+     * @param string $url the url to match
83
+     * @param callable $action the function to run
84
+     * @param string $app the id of the app registering the call
85
+     * @param int $authLevel the level of authentication required for the call
86
+     * @param array $defaults
87
+     * @param array $requirements
88
+     */
89
+    public static function register($method, $url, $action, $app,
90
+                $authLevel = API::USER_AUTH,
91
+                $defaults = array(),
92
+                $requirements = array()) {
93
+        $name = strtolower($method).$url;
94
+        $name = str_replace(array('/', '{', '}'), '_', $name);
95
+        if(!isset(self::$actions[$name])) {
96
+            $oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
+            OC::$server->getRouter()->useCollection('ocs');
98
+            OC::$server->getRouter()->create($name, $url)
99
+                ->method($method)
100
+                ->defaults($defaults)
101
+                ->requirements($requirements)
102
+                ->action('OC_API', 'call');
103
+            self::$actions[$name] = array();
104
+            OC::$server->getRouter()->useCollection($oldCollection);
105
+        }
106
+        self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
+    }
108
+
109
+    /**
110
+     * handles an api call
111
+     * @param array $parameters
112
+     */
113
+    public static function call($parameters) {
114
+        $request = \OC::$server->getRequest();
115
+        $method = $request->getMethod();
116
+
117
+        // Prepare the request variables
118
+        if($method === 'PUT') {
119
+            $parameters['_put'] = $request->getParams();
120
+        } else if($method === 'DELETE') {
121
+            $parameters['_delete'] = $request->getParams();
122
+        }
123
+        $name = $parameters['_route'];
124
+        // Foreach registered action
125
+        $responses = array();
126
+        $appManager = \OC::$server->getAppManager();
127
+        foreach(self::$actions[$name] as $action) {
128
+            // Check authentication and availability
129
+            if(!self::isAuthorised($action)) {
130
+                $responses[] = array(
131
+                    'app' => $action['app'],
132
+                    'response' => new \OC\OCS\Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
133
+                    'shipped' => $appManager->isShipped($action['app']),
134
+                    );
135
+                continue;
136
+            }
137
+            if(!is_callable($action['action'])) {
138
+                $responses[] = array(
139
+                    'app' => $action['app'],
140
+                    'response' => new \OC\OCS\Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
141
+                    'shipped' => $appManager->isShipped($action['app']),
142
+                    );
143
+                continue;
144
+            }
145
+            // Run the action
146
+            $responses[] = array(
147
+                'app' => $action['app'],
148
+                'response' => call_user_func($action['action'], $parameters),
149
+                'shipped' => $appManager->isShipped($action['app']),
150
+                );
151
+        }
152
+        $response = self::mergeResponses($responses);
153
+        $format = self::requestedFormat();
154
+        if (self::$logoutRequired) {
155
+            \OC::$server->getUserSession()->logout();
156
+        }
157
+
158
+        self::respond($response, $format);
159
+    }
160
+
161
+    /**
162
+     * merge the returned result objects into one response
163
+     * @param array $responses
164
+     * @return \OC\OCS\Result
165
+     */
166
+    public static function mergeResponses($responses) {
167
+        // Sort into shipped and third-party
168
+        $shipped = array(
169
+            'succeeded' => array(),
170
+            'failed' => array(),
171
+            );
172
+        $thirdparty = array(
173
+            'succeeded' => array(),
174
+            'failed' => array(),
175
+            );
176
+
177
+        foreach($responses as $response) {
178
+            if($response['shipped'] || ($response['app'] === 'core')) {
179
+                if($response['response']->succeeded()) {
180
+                    $shipped['succeeded'][$response['app']] = $response;
181
+                } else {
182
+                    $shipped['failed'][$response['app']] = $response;
183
+                }
184
+            } else {
185
+                if($response['response']->succeeded()) {
186
+                    $thirdparty['succeeded'][$response['app']] = $response;
187
+                } else {
188
+                    $thirdparty['failed'][$response['app']] = $response;
189
+                }
190
+            }
191
+        }
192
+
193
+        // Remove any error responses if there is one shipped response that succeeded
194
+        if(!empty($shipped['failed'])) {
195
+            // Which shipped response do we use if they all failed?
196
+            // They may have failed for different reasons (different status codes)
197
+            // Which response code should we return?
198
+            // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
199
+            // Merge failed responses if more than one
200
+            $data = array();
201
+            foreach($shipped['failed'] as $failure) {
202
+                $data = array_merge_recursive($data, $failure['response']->getData());
203
+            }
204
+            $picked = reset($shipped['failed']);
205
+            $code = $picked['response']->getStatusCode();
206
+            $meta = $picked['response']->getMeta();
207
+            $headers = $picked['response']->getHeaders();
208
+            $response = new \OC\OCS\Result($data, $code, $meta['message'], $headers);
209
+            return $response;
210
+        } elseif(!empty($shipped['succeeded'])) {
211
+            $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
212
+        } elseif(!empty($thirdparty['failed'])) {
213
+            // Merge failed responses if more than one
214
+            $data = array();
215
+            foreach($thirdparty['failed'] as $failure) {
216
+                $data = array_merge_recursive($data, $failure['response']->getData());
217
+            }
218
+            $picked = reset($thirdparty['failed']);
219
+            $code = $picked['response']->getStatusCode();
220
+            $meta = $picked['response']->getMeta();
221
+            $headers = $picked['response']->getHeaders();
222
+            $response = new \OC\OCS\Result($data, $code, $meta['message'], $headers);
223
+            return $response;
224
+        } else {
225
+            $responses = $thirdparty['succeeded'];
226
+        }
227
+        // Merge the successful responses
228
+        $data = [];
229
+        $codes = [];
230
+        $header = [];
231
+
232
+        foreach($responses as $response) {
233
+            if($response['shipped']) {
234
+                $data = array_merge_recursive($response['response']->getData(), $data);
235
+            } else {
236
+                $data = array_merge_recursive($data, $response['response']->getData());
237
+            }
238
+            $header = array_merge_recursive($header, $response['response']->getHeaders());
239
+            $codes[] = ['code' => $response['response']->getStatusCode(),
240
+                'meta' => $response['response']->getMeta()];
241
+        }
242
+
243
+        // Use any non 100 status codes
244
+        $statusCode = 100;
245
+        $statusMessage = null;
246
+        foreach($codes as $code) {
247
+            if($code['code'] != 100) {
248
+                $statusCode = $code['code'];
249
+                $statusMessage = $code['meta']['message'];
250
+                break;
251
+            }
252
+        }
253
+
254
+        return new \OC\OCS\Result($data, $statusCode, $statusMessage, $header);
255
+    }
256
+
257
+    /**
258
+     * authenticate the api call
259
+     * @param array $action the action details as supplied to OC_API::register()
260
+     * @return bool
261
+     */
262
+    private static function isAuthorised($action) {
263
+        $level = $action['authlevel'];
264
+        switch($level) {
265
+            case API::GUEST_AUTH:
266
+                // Anyone can access
267
+                return true;
268
+            case API::USER_AUTH:
269
+                // User required
270
+                return self::loginUser();
271
+            case API::SUBADMIN_AUTH:
272
+                // Check for subadmin
273
+                $user = self::loginUser();
274
+                if(!$user) {
275
+                    return false;
276
+                } else {
277
+                    $userObject = \OC::$server->getUserSession()->getUser();
278
+                    if($userObject === null) {
279
+                        return false;
280
+                    }
281
+                    $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
282
+                    $admin = OC_User::isAdminUser($user);
283
+                    if($isSubAdmin || $admin) {
284
+                        return true;
285
+                    } else {
286
+                        return false;
287
+                    }
288
+                }
289
+            case API::ADMIN_AUTH:
290
+                // Check for admin
291
+                $user = self::loginUser();
292
+                if(!$user) {
293
+                    return false;
294
+                } else {
295
+                    return OC_User::isAdminUser($user);
296
+                }
297
+            default:
298
+                // oops looks like invalid level supplied
299
+                return false;
300
+        }
301
+    }
302
+
303
+    /**
304
+     * http basic auth
305
+     * @return string|false (username, or false on failure)
306
+     */
307
+    private static function loginUser() {
308
+        if(self::$isLoggedIn === true) {
309
+            return \OC_User::getUser();
310
+        }
311
+
312
+        // reuse existing login
313
+        $loggedIn = \OC::$server->getUserSession()->isLoggedIn();
314
+        if ($loggedIn === true) {
315
+            if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
316
+                // Do not allow access to OCS until the 2FA challenge was solved successfully
317
+                return false;
318
+            }
319
+            $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
320
+            if ($ocsApiRequest) {
321
+
322
+                // initialize the user's filesystem
323
+                \OC_Util::setupFS(\OC_User::getUser());
324
+                self::$isLoggedIn = true;
325
+
326
+                return OC_User::getUser();
327
+            }
328
+            return false;
329
+        }
330
+
331
+        // basic auth - because OC_User::login will create a new session we shall only try to login
332
+        // if user and pass are set
333
+        $userSession = \OC::$server->getUserSession();
334
+        $request = \OC::$server->getRequest();
335
+        try {
336
+            if ($userSession->tryTokenLogin($request)
337
+                || $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
338
+                self::$logoutRequired = true;
339
+            } else {
340
+                return false;
341
+            }
342
+            // initialize the user's filesystem
343
+            \OC_Util::setupFS(\OC_User::getUser());
344
+            self::$isLoggedIn = true;
345
+
346
+            return \OC_User::getUser();
347
+        } catch (\OC\User\LoginException $e) {
348
+            return false;
349
+        }
350
+    }
351
+
352
+    /**
353
+     * respond to a call
354
+     * @param \OC\OCS\Result $result
355
+     * @param string $format the format xml|json
356
+     */
357
+    public static function respond($result, $format='xml') {
358
+        $request = \OC::$server->getRequest();
359
+
360
+        // Send 401 headers if unauthorised
361
+        if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
362
+            // If request comes from JS return dummy auth request
363
+            if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
364
+                header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
365
+            } else {
366
+                header('WWW-Authenticate: Basic realm="Authorisation Required"');
367
+            }
368
+            header('HTTP/1.0 401 Unauthorized');
369
+        }
370
+
371
+        foreach($result->getHeaders() as $name => $value) {
372
+            header($name . ': ' . $value);
373
+        }
374
+
375
+        $meta = $result->getMeta();
376
+        $data = $result->getData();
377
+        if (self::isV2($request)) {
378
+            $statusCode = self::mapStatusCodes($result->getStatusCode());
379
+            if (!is_null($statusCode)) {
380
+                $meta['statuscode'] = $statusCode;
381
+                OC_Response::setStatus($statusCode);
382
+            }
383
+        }
384
+
385
+        self::setContentType($format);
386
+        $body = self::renderResult($format, $meta, $data);
387
+        echo $body;
388
+    }
389
+
390
+    /**
391
+     * @param XMLWriter $writer
392
+     */
393
+    private static function toXML($array, $writer) {
394
+        foreach($array as $k => $v) {
395
+            if ($k[0] === '@') {
396
+                $writer->writeAttribute(substr($k, 1), $v);
397
+                continue;
398
+            } else if (is_numeric($k)) {
399
+                $k = 'element';
400
+            }
401
+            if(is_array($v)) {
402
+                $writer->startElement($k);
403
+                self::toXML($v, $writer);
404
+                $writer->endElement();
405
+            } else {
406
+                $writer->writeElement($k, $v);
407
+            }
408
+        }
409
+    }
410
+
411
+    /**
412
+     * @return string
413
+     */
414
+    public static function requestedFormat() {
415
+        $formats = array('json', 'xml');
416
+
417
+        $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
418
+        return $format;
419
+    }
420
+
421
+    /**
422
+     * Based on the requested format the response content type is set
423
+     * @param string $format
424
+     */
425
+    public static function setContentType($format = null) {
426
+        $format = is_null($format) ? self::requestedFormat() : $format;
427
+        if ($format === 'xml') {
428
+            header('Content-type: text/xml; charset=UTF-8');
429
+            return;
430
+        }
431
+
432
+        if ($format === 'json') {
433
+            header('Content-Type: application/json; charset=utf-8');
434
+            return;
435
+        }
436
+
437
+        header('Content-Type: application/octet-stream; charset=utf-8');
438
+    }
439
+
440
+    /**
441
+     * @param \OCP\IRequest $request
442
+     * @return bool
443
+     */
444
+    protected static function isV2(\OCP\IRequest $request) {
445
+        $script = $request->getScriptName();
446
+
447
+        return substr($script, -11) === '/ocs/v2.php';
448
+    }
449
+
450
+    /**
451
+     * @param integer $sc
452
+     * @return int
453
+     */
454
+    public static function mapStatusCodes($sc) {
455
+        switch ($sc) {
456
+            case API::RESPOND_NOT_FOUND:
457
+                return Http::STATUS_NOT_FOUND;
458
+            case API::RESPOND_SERVER_ERROR:
459
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
460
+            case API::RESPOND_UNKNOWN_ERROR:
461
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
462
+            case API::RESPOND_UNAUTHORISED:
463
+                // already handled for v1
464
+                return null;
465
+            case 100:
466
+                return Http::STATUS_OK;
467
+        }
468
+        // any 2xx, 4xx and 5xx will be used as is
469
+        if ($sc >= 200 && $sc < 600) {
470
+            return $sc;
471
+        }
472
+
473
+        return Http::STATUS_BAD_REQUEST;
474
+    }
475
+
476
+    /**
477
+     * @param string $format
478
+     * @return string
479
+     */
480
+    public static function renderResult($format, $meta, $data) {
481
+        $response = array(
482
+            'ocs' => array(
483
+                'meta' => $meta,
484
+                'data' => $data,
485
+            ),
486
+        );
487
+        if ($format == 'json') {
488
+            return OC_JSON::encode($response);
489
+        }
490
+
491
+        $writer = new XMLWriter();
492
+        $writer->openMemory();
493
+        $writer->setIndent(true);
494
+        $writer->startDocument();
495
+        self::toXML($response, $writer);
496
+        $writer->endDocument();
497
+        return $writer->outputMemory(true);
498
+    }
499 499
 }
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 				$requirements = array()) {
93 93
 		$name = strtolower($method).$url;
94 94
 		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
95
+		if (!isset(self::$actions[$name])) {
96 96
 			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97 97
 			OC::$server->getRouter()->useCollection('ocs');
98 98
 			OC::$server->getRouter()->create($name, $url)
@@ -115,18 +115,18 @@  discard block
 block discarded – undo
115 115
 		$method = $request->getMethod();
116 116
 
117 117
 		// Prepare the request variables
118
-		if($method === 'PUT') {
118
+		if ($method === 'PUT') {
119 119
 			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
120
+		} else if ($method === 'DELETE') {
121 121
 			$parameters['_delete'] = $request->getParams();
122 122
 		}
123 123
 		$name = $parameters['_route'];
124 124
 		// Foreach registered action
125 125
 		$responses = array();
126 126
 		$appManager = \OC::$server->getAppManager();
127
-		foreach(self::$actions[$name] as $action) {
127
+		foreach (self::$actions[$name] as $action) {
128 128
 			// Check authentication and availability
129
-			if(!self::isAuthorised($action)) {
129
+			if (!self::isAuthorised($action)) {
130 130
 				$responses[] = array(
131 131
 					'app' => $action['app'],
132 132
 					'response' => new \OC\OCS\Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 					);
135 135
 				continue;
136 136
 			}
137
-			if(!is_callable($action['action'])) {
137
+			if (!is_callable($action['action'])) {
138 138
 				$responses[] = array(
139 139
 					'app' => $action['app'],
140 140
 					'response' => new \OC\OCS\Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
@@ -174,15 +174,15 @@  discard block
 block discarded – undo
174 174
 			'failed' => array(),
175 175
 			);
176 176
 
177
-		foreach($responses as $response) {
178
-			if($response['shipped'] || ($response['app'] === 'core')) {
179
-				if($response['response']->succeeded()) {
177
+		foreach ($responses as $response) {
178
+			if ($response['shipped'] || ($response['app'] === 'core')) {
179
+				if ($response['response']->succeeded()) {
180 180
 					$shipped['succeeded'][$response['app']] = $response;
181 181
 				} else {
182 182
 					$shipped['failed'][$response['app']] = $response;
183 183
 				}
184 184
 			} else {
185
-				if($response['response']->succeeded()) {
185
+				if ($response['response']->succeeded()) {
186 186
 					$thirdparty['succeeded'][$response['app']] = $response;
187 187
 				} else {
188 188
 					$thirdparty['failed'][$response['app']] = $response;
@@ -191,14 +191,14 @@  discard block
 block discarded – undo
191 191
 		}
192 192
 
193 193
 		// Remove any error responses if there is one shipped response that succeeded
194
-		if(!empty($shipped['failed'])) {
194
+		if (!empty($shipped['failed'])) {
195 195
 			// Which shipped response do we use if they all failed?
196 196
 			// They may have failed for different reasons (different status codes)
197 197
 			// Which response code should we return?
198 198
 			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
199 199
 			// Merge failed responses if more than one
200 200
 			$data = array();
201
-			foreach($shipped['failed'] as $failure) {
201
+			foreach ($shipped['failed'] as $failure) {
202 202
 				$data = array_merge_recursive($data, $failure['response']->getData());
203 203
 			}
204 204
 			$picked = reset($shipped['failed']);
@@ -207,12 +207,12 @@  discard block
 block discarded – undo
207 207
 			$headers = $picked['response']->getHeaders();
208 208
 			$response = new \OC\OCS\Result($data, $code, $meta['message'], $headers);
209 209
 			return $response;
210
-		} elseif(!empty($shipped['succeeded'])) {
210
+		} elseif (!empty($shipped['succeeded'])) {
211 211
 			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
212
-		} elseif(!empty($thirdparty['failed'])) {
212
+		} elseif (!empty($thirdparty['failed'])) {
213 213
 			// Merge failed responses if more than one
214 214
 			$data = array();
215
-			foreach($thirdparty['failed'] as $failure) {
215
+			foreach ($thirdparty['failed'] as $failure) {
216 216
 				$data = array_merge_recursive($data, $failure['response']->getData());
217 217
 			}
218 218
 			$picked = reset($thirdparty['failed']);
@@ -229,8 +229,8 @@  discard block
 block discarded – undo
229 229
 		$codes = [];
230 230
 		$header = [];
231 231
 
232
-		foreach($responses as $response) {
233
-			if($response['shipped']) {
232
+		foreach ($responses as $response) {
233
+			if ($response['shipped']) {
234 234
 				$data = array_merge_recursive($response['response']->getData(), $data);
235 235
 			} else {
236 236
 				$data = array_merge_recursive($data, $response['response']->getData());
@@ -243,8 +243,8 @@  discard block
 block discarded – undo
243 243
 		// Use any non 100 status codes
244 244
 		$statusCode = 100;
245 245
 		$statusMessage = null;
246
-		foreach($codes as $code) {
247
-			if($code['code'] != 100) {
246
+		foreach ($codes as $code) {
247
+			if ($code['code'] != 100) {
248 248
 				$statusCode = $code['code'];
249 249
 				$statusMessage = $code['meta']['message'];
250 250
 				break;
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	private static function isAuthorised($action) {
263 263
 		$level = $action['authlevel'];
264
-		switch($level) {
264
+		switch ($level) {
265 265
 			case API::GUEST_AUTH:
266 266
 				// Anyone can access
267 267
 				return true;
@@ -271,16 +271,16 @@  discard block
 block discarded – undo
271 271
 			case API::SUBADMIN_AUTH:
272 272
 				// Check for subadmin
273 273
 				$user = self::loginUser();
274
-				if(!$user) {
274
+				if (!$user) {
275 275
 					return false;
276 276
 				} else {
277 277
 					$userObject = \OC::$server->getUserSession()->getUser();
278
-					if($userObject === null) {
278
+					if ($userObject === null) {
279 279
 						return false;
280 280
 					}
281 281
 					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
282 282
 					$admin = OC_User::isAdminUser($user);
283
-					if($isSubAdmin || $admin) {
283
+					if ($isSubAdmin || $admin) {
284 284
 						return true;
285 285
 					} else {
286 286
 						return false;
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 			case API::ADMIN_AUTH:
290 290
 				// Check for admin
291 291
 				$user = self::loginUser();
292
-				if(!$user) {
292
+				if (!$user) {
293 293
 					return false;
294 294
 				} else {
295 295
 					return OC_User::isAdminUser($user);
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 	 * @return string|false (username, or false on failure)
306 306
 	 */
307 307
 	private static function loginUser() {
308
-		if(self::$isLoggedIn === true) {
308
+		if (self::$isLoggedIn === true) {
309 309
 			return \OC_User::getUser();
310 310
 		}
311 311
 
@@ -354,13 +354,13 @@  discard block
 block discarded – undo
354 354
 	 * @param \OC\OCS\Result $result
355 355
 	 * @param string $format the format xml|json
356 356
 	 */
357
-	public static function respond($result, $format='xml') {
357
+	public static function respond($result, $format = 'xml') {
358 358
 		$request = \OC::$server->getRequest();
359 359
 
360 360
 		// Send 401 headers if unauthorised
361
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
361
+		if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
362 362
 			// If request comes from JS return dummy auth request
363
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
363
+			if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
364 364
 				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
365 365
 			} else {
366 366
 				header('WWW-Authenticate: Basic realm="Authorisation Required"');
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 			header('HTTP/1.0 401 Unauthorized');
369 369
 		}
370 370
 
371
-		foreach($result->getHeaders() as $name => $value) {
372
-			header($name . ': ' . $value);
371
+		foreach ($result->getHeaders() as $name => $value) {
372
+			header($name.': '.$value);
373 373
 		}
374 374
 
375 375
 		$meta = $result->getMeta();
@@ -391,14 +391,14 @@  discard block
 block discarded – undo
391 391
 	 * @param XMLWriter $writer
392 392
 	 */
393 393
 	private static function toXML($array, $writer) {
394
-		foreach($array as $k => $v) {
394
+		foreach ($array as $k => $v) {
395 395
 			if ($k[0] === '@') {
396 396
 				$writer->writeAttribute(substr($k, 1), $v);
397 397
 				continue;
398 398
 			} else if (is_numeric($k)) {
399 399
 				$k = 'element';
400 400
 			}
401
-			if(is_array($v)) {
401
+			if (is_array($v)) {
402 402
 				$writer->startElement($k);
403 403
 				self::toXML($v, $writer);
404 404
 				$writer->endElement();
Please login to merge, or discard this patch.
lib/private/legacy/eventsource.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@
 block discarded – undo
88 88
 	 * send a message to the client
89 89
 	 *
90 90
 	 * @param string $type
91
-	 * @param mixed $data
91
+	 * @param string $data
92 92
 	 *
93 93
 	 * @throws \BadMethodCallException
94 94
 	 * if only one parameter is given, a typeless message will be send with that parameter as data
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 		header('X-Accel-Buffering: no');
61 61
 		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62 62
 		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
63
+			$this->fallBackId = (int) $_GET['fallback_id'];
64 64
 			/**
65 65
 			 * FIXME: The default content-security-policy of ownCloud forbids inline
66 66
 			 * JavaScript for security reasons. IE starting on Windows 10 will
@@ -73,11 +73,11 @@  discard block
 block discarded – undo
73 73
 			 */
74 74
 			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75 75
 			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
76
+			echo str_repeat('<span></span>'.PHP_EOL, 10); //dummy data to keep IE happy
77 77
 		} else {
78 78
 			header("Content-Type: text/event-stream");
79 79
 		}
80
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
80
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81 81
 			header('Location: '.\OC::$WEBROOT);
82 82
 			exit();
83 83
 		}
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function send($type, $data = null) {
102 102
 		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
103
+			throw new BadMethodCallException('Type needs to be alphanumeric ('.$type.')');
104 104
 		}
105 105
 		$this->init();
106 106
 		if (is_null($data)) {
@@ -109,13 +109,13 @@  discard block
 block discarded – undo
109 109
 		}
110 110
 		if ($this->fallback) {
111 111
 			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
112
+				. $this->fallBackId.',"'.$type.'",'.OCP\JSON::encode($data).')</script>'.PHP_EOL;
113 113
 			echo $response;
114 114
 		} else {
115 115
 			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
116
+				echo 'event: '.$type.PHP_EOL;
117 117
 			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
118
+			echo 'data: '.OCP\JSON::encode($data).PHP_EOL;
119 119
 		}
120 120
 		echo PHP_EOL;
121 121
 		flush();
Please login to merge, or discard this patch.
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -33,99 +33,99 @@
 block discarded – undo
33 33
  * use server side events with caution, to many open requests can hang the server
34 34
  */
35 35
 class OC_EventSource implements \OCP\IEventSource {
36
-	/**
37
-	 * @var bool
38
-	 */
39
-	private $fallback;
36
+    /**
37
+     * @var bool
38
+     */
39
+    private $fallback;
40 40
 
41
-	/**
42
-	 * @var int
43
-	 */
44
-	private $fallBackId = 0;
41
+    /**
42
+     * @var int
43
+     */
44
+    private $fallBackId = 0;
45 45
 
46
-	/**
47
-	 * @var bool
48
-	 */
49
-	private $started = false;
46
+    /**
47
+     * @var bool
48
+     */
49
+    private $started = false;
50 50
 
51
-	protected function init() {
52
-		if ($this->started) {
53
-			return;
54
-		}
55
-		$this->started = true;
51
+    protected function init() {
52
+        if ($this->started) {
53
+            return;
54
+        }
55
+        $this->started = true;
56 56
 
57
-		// prevent php output buffering, caching and nginx buffering
58
-		OC_Util::obEnd();
59
-		header('Cache-Control: no-cache');
60
-		header('X-Accel-Buffering: no');
61
-		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
-		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
64
-			/**
65
-			 * FIXME: The default content-security-policy of ownCloud forbids inline
66
-			 * JavaScript for security reasons. IE starting on Windows 10 will
67
-			 * however also obey the CSP which will break the event source fallback.
68
-			 *
69
-			 * As a workaround thus we set a custom policy which allows the execution
70
-			 * of inline JavaScript.
71
-			 *
72
-			 * @link https://github.com/owncloud/core/issues/14286
73
-			 */
74
-			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
-			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
-		} else {
78
-			header("Content-Type: text/event-stream");
79
-		}
80
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
-			header('Location: '.\OC::$WEBROOT);
82
-			exit();
83
-		}
84
-		if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
-			$this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
-			$this->close();
87
-			exit();
88
-		}
89
-		flush();
90
-	}
57
+        // prevent php output buffering, caching and nginx buffering
58
+        OC_Util::obEnd();
59
+        header('Cache-Control: no-cache');
60
+        header('X-Accel-Buffering: no');
61
+        $this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62
+        if ($this->fallback) {
63
+            $this->fallBackId = (int)$_GET['fallback_id'];
64
+            /**
65
+             * FIXME: The default content-security-policy of ownCloud forbids inline
66
+             * JavaScript for security reasons. IE starting on Windows 10 will
67
+             * however also obey the CSP which will break the event source fallback.
68
+             *
69
+             * As a workaround thus we set a custom policy which allows the execution
70
+             * of inline JavaScript.
71
+             *
72
+             * @link https://github.com/owncloud/core/issues/14286
73
+             */
74
+            header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75
+            header("Content-Type: text/html");
76
+            echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
77
+        } else {
78
+            header("Content-Type: text/event-stream");
79
+        }
80
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81
+            header('Location: '.\OC::$WEBROOT);
82
+            exit();
83
+        }
84
+        if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
85
+            $this->send('error', 'Possible CSRF attack. Connection will be closed.');
86
+            $this->close();
87
+            exit();
88
+        }
89
+        flush();
90
+    }
91 91
 
92
-	/**
93
-	 * send a message to the client
94
-	 *
95
-	 * @param string $type
96
-	 * @param mixed $data
97
-	 *
98
-	 * @throws \BadMethodCallException
99
-	 * if only one parameter is given, a typeless message will be send with that parameter as data
100
-	 * @suppress PhanDeprecatedFunction
101
-	 */
102
-	public function send($type, $data = null) {
103
-		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
104
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
105
-		}
106
-		$this->init();
107
-		if (is_null($data)) {
108
-			$data = $type;
109
-			$type = null;
110
-		}
111
-		if ($this->fallback) {
112
-			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
113
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
114
-			echo $response;
115
-		} else {
116
-			if ($type) {
117
-				echo 'event: ' . $type . PHP_EOL;
118
-			}
119
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
120
-		}
121
-		echo PHP_EOL;
122
-		flush();
123
-	}
92
+    /**
93
+     * send a message to the client
94
+     *
95
+     * @param string $type
96
+     * @param mixed $data
97
+     *
98
+     * @throws \BadMethodCallException
99
+     * if only one parameter is given, a typeless message will be send with that parameter as data
100
+     * @suppress PhanDeprecatedFunction
101
+     */
102
+    public function send($type, $data = null) {
103
+        if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
104
+            throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
105
+        }
106
+        $this->init();
107
+        if (is_null($data)) {
108
+            $data = $type;
109
+            $type = null;
110
+        }
111
+        if ($this->fallback) {
112
+            $response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
113
+                . $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
114
+            echo $response;
115
+        } else {
116
+            if ($type) {
117
+                echo 'event: ' . $type . PHP_EOL;
118
+            }
119
+            echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
120
+        }
121
+        echo PHP_EOL;
122
+        flush();
123
+    }
124 124
 
125
-	/**
126
-	 * close the connection of the event source
127
-	 */
128
-	public function close() {
129
-		$this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
130
-	}
125
+    /**
126
+     * close the connection of the event source
127
+     */
128
+    public function close() {
129
+        $this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
130
+    }
131 131
 }
Please login to merge, or discard this patch.
lib/private/Memcache/Memcached.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@
 block discarded – undo
155 155
 	 * Set a value in the cache if it's not already stored
156 156
 	 *
157 157
 	 * @param string $key
158
-	 * @param mixed $value
158
+	 * @param integer $value
159 159
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
160 160
 	 * @return bool
161 161
 	 * @throws \Exception
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -33,193 +33,193 @@
 block discarded – undo
33 33
 use OCP\IMemcache;
34 34
 
35 35
 class Memcached extends Cache implements IMemcache {
36
-	use CASTrait;
37
-
38
-	/**
39
-	 * @var \Memcached $cache
40
-	 */
41
-	private static $cache = null;
42
-
43
-	use CADTrait;
44
-
45
-	public function __construct($prefix = '') {
46
-		parent::__construct($prefix);
47
-		if (is_null(self::$cache)) {
48
-			self::$cache = new \Memcached();
49
-
50
-			$defaultOptions = [
51
-				\Memcached::OPT_CONNECT_TIMEOUT => 50,
52
-				\Memcached::OPT_RETRY_TIMEOUT =>   50,
53
-				\Memcached::OPT_SEND_TIMEOUT =>    50,
54
-				\Memcached::OPT_RECV_TIMEOUT =>    50,
55
-				\Memcached::OPT_POLL_TIMEOUT =>    50,
56
-
57
-				// Enable compression
58
-				\Memcached::OPT_COMPRESSION =>          true,
59
-
60
-				// Turn on consistent hashing
61
-				\Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
62
-
63
-				// Enable Binary Protocol
64
-				//\Memcached::OPT_BINARY_PROTOCOL =>      true,
65
-			];
66
-			// by default enable igbinary serializer if available
67
-			if (\Memcached::HAVE_IGBINARY) {
68
-				$defaultOptions[\Memcached::OPT_SERIALIZER] =
69
-					\Memcached::SERIALIZER_IGBINARY;
70
-			}
71
-			$options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
72
-			if (is_array($options)) {
73
-				$options = $options + $defaultOptions;
74
-				self::$cache->setOptions($options);
75
-			} else {
76
-				throw new HintException("Expected 'memcached_options' config to be an array, got $options");
77
-			}
78
-
79
-			$servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
80
-			if (!$servers) {
81
-				$server = \OC::$server->getSystemConfig()->getValue('memcached_server');
82
-				if ($server) {
83
-					$servers = [$server];
84
-				} else {
85
-					$servers = [['localhost', 11211]];
86
-				}
87
-			}
88
-			self::$cache->addServers($servers);
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
94
-	 */
95
-	protected function getNameSpace() {
96
-		return $this->prefix;
97
-	}
98
-
99
-	public function get($key) {
100
-		$result = self::$cache->get($this->getNameSpace() . $key);
101
-		if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
102
-			return null;
103
-		} else {
104
-			return $result;
105
-		}
106
-	}
107
-
108
-	public function set($key, $value, $ttl = 0) {
109
-		if ($ttl > 0) {
110
-			$result =  self::$cache->set($this->getNameSpace() . $key, $value, $ttl);
111
-		} else {
112
-			$result = self::$cache->set($this->getNameSpace() . $key, $value);
113
-		}
114
-		if ($result !== true) {
115
-			$this->verifyReturnCode();
116
-		}
117
-		return $result;
118
-	}
119
-
120
-	public function hasKey($key) {
121
-		self::$cache->get($this->getNameSpace() . $key);
122
-		return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
123
-	}
124
-
125
-	public function remove($key) {
126
-		$result= self::$cache->delete($this->getNameSpace() . $key);
127
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
128
-			$this->verifyReturnCode();
129
-		}
130
-		return $result;
131
-	}
132
-
133
-	public function clear($prefix = '') {
134
-		$prefix = $this->getNameSpace() . $prefix;
135
-		$allKeys = self::$cache->getAllKeys();
136
-		if ($allKeys === false) {
137
-			// newer Memcached doesn't like getAllKeys(), flush everything
138
-			self::$cache->flush();
139
-			return true;
140
-		}
141
-		$keys = array();
142
-		$prefixLength = strlen($prefix);
143
-		foreach ($allKeys as $key) {
144
-			if (substr($key, 0, $prefixLength) === $prefix) {
145
-				$keys[] = $key;
146
-			}
147
-		}
148
-		if (method_exists(self::$cache, 'deleteMulti')) {
149
-			self::$cache->deleteMulti($keys);
150
-		} else {
151
-			foreach ($keys as $key) {
152
-				self::$cache->delete($key);
153
-			}
154
-		}
155
-		return true;
156
-	}
157
-
158
-	/**
159
-	 * Set a value in the cache if it's not already stored
160
-	 *
161
-	 * @param string $key
162
-	 * @param mixed $value
163
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
164
-	 * @return bool
165
-	 * @throws \Exception
166
-	 */
167
-	public function add($key, $value, $ttl = 0) {
168
-		$result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
169
-		if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
170
-			$this->verifyReturnCode();
171
-		}
172
-		return $result;
173
-	}
174
-
175
-	/**
176
-	 * Increase a stored number
177
-	 *
178
-	 * @param string $key
179
-	 * @param int $step
180
-	 * @return int | bool
181
-	 */
182
-	public function inc($key, $step = 1) {
183
-		$this->add($key, 0);
184
-		$result = self::$cache->increment($this->getPrefix() . $key, $step);
185
-
186
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
187
-			return false;
188
-		}
189
-
190
-		return $result;
191
-	}
192
-
193
-	/**
194
-	 * Decrease a stored number
195
-	 *
196
-	 * @param string $key
197
-	 * @param int $step
198
-	 * @return int | bool
199
-	 */
200
-	public function dec($key, $step = 1) {
201
-		$result = self::$cache->decrement($this->getPrefix() . $key, $step);
202
-
203
-		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
204
-			return false;
205
-		}
206
-
207
-		return $result;
208
-	}
209
-
210
-	static public function isAvailable() {
211
-		return extension_loaded('memcached');
212
-	}
213
-
214
-	/**
215
-	 * @throws \Exception
216
-	 */
217
-	private function verifyReturnCode() {
218
-		$code = self::$cache->getResultCode();
219
-		if ($code === \Memcached::RES_SUCCESS) {
220
-			return;
221
-		}
222
-		$message = self::$cache->getResultMessage();
223
-		throw new \Exception("Error $code interacting with memcached : $message");
224
-	}
36
+    use CASTrait;
37
+
38
+    /**
39
+     * @var \Memcached $cache
40
+     */
41
+    private static $cache = null;
42
+
43
+    use CADTrait;
44
+
45
+    public function __construct($prefix = '') {
46
+        parent::__construct($prefix);
47
+        if (is_null(self::$cache)) {
48
+            self::$cache = new \Memcached();
49
+
50
+            $defaultOptions = [
51
+                \Memcached::OPT_CONNECT_TIMEOUT => 50,
52
+                \Memcached::OPT_RETRY_TIMEOUT =>   50,
53
+                \Memcached::OPT_SEND_TIMEOUT =>    50,
54
+                \Memcached::OPT_RECV_TIMEOUT =>    50,
55
+                \Memcached::OPT_POLL_TIMEOUT =>    50,
56
+
57
+                // Enable compression
58
+                \Memcached::OPT_COMPRESSION =>          true,
59
+
60
+                // Turn on consistent hashing
61
+                \Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
62
+
63
+                // Enable Binary Protocol
64
+                //\Memcached::OPT_BINARY_PROTOCOL =>      true,
65
+            ];
66
+            // by default enable igbinary serializer if available
67
+            if (\Memcached::HAVE_IGBINARY) {
68
+                $defaultOptions[\Memcached::OPT_SERIALIZER] =
69
+                    \Memcached::SERIALIZER_IGBINARY;
70
+            }
71
+            $options = \OC::$server->getConfig()->getSystemValue('memcached_options', []);
72
+            if (is_array($options)) {
73
+                $options = $options + $defaultOptions;
74
+                self::$cache->setOptions($options);
75
+            } else {
76
+                throw new HintException("Expected 'memcached_options' config to be an array, got $options");
77
+            }
78
+
79
+            $servers = \OC::$server->getSystemConfig()->getValue('memcached_servers');
80
+            if (!$servers) {
81
+                $server = \OC::$server->getSystemConfig()->getValue('memcached_server');
82
+                if ($server) {
83
+                    $servers = [$server];
84
+                } else {
85
+                    $servers = [['localhost', 11211]];
86
+                }
87
+            }
88
+            self::$cache->addServers($servers);
89
+        }
90
+    }
91
+
92
+    /**
93
+     * entries in XCache gets namespaced to prevent collisions between owncloud instances and users
94
+     */
95
+    protected function getNameSpace() {
96
+        return $this->prefix;
97
+    }
98
+
99
+    public function get($key) {
100
+        $result = self::$cache->get($this->getNameSpace() . $key);
101
+        if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
102
+            return null;
103
+        } else {
104
+            return $result;
105
+        }
106
+    }
107
+
108
+    public function set($key, $value, $ttl = 0) {
109
+        if ($ttl > 0) {
110
+            $result =  self::$cache->set($this->getNameSpace() . $key, $value, $ttl);
111
+        } else {
112
+            $result = self::$cache->set($this->getNameSpace() . $key, $value);
113
+        }
114
+        if ($result !== true) {
115
+            $this->verifyReturnCode();
116
+        }
117
+        return $result;
118
+    }
119
+
120
+    public function hasKey($key) {
121
+        self::$cache->get($this->getNameSpace() . $key);
122
+        return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
123
+    }
124
+
125
+    public function remove($key) {
126
+        $result= self::$cache->delete($this->getNameSpace() . $key);
127
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
128
+            $this->verifyReturnCode();
129
+        }
130
+        return $result;
131
+    }
132
+
133
+    public function clear($prefix = '') {
134
+        $prefix = $this->getNameSpace() . $prefix;
135
+        $allKeys = self::$cache->getAllKeys();
136
+        if ($allKeys === false) {
137
+            // newer Memcached doesn't like getAllKeys(), flush everything
138
+            self::$cache->flush();
139
+            return true;
140
+        }
141
+        $keys = array();
142
+        $prefixLength = strlen($prefix);
143
+        foreach ($allKeys as $key) {
144
+            if (substr($key, 0, $prefixLength) === $prefix) {
145
+                $keys[] = $key;
146
+            }
147
+        }
148
+        if (method_exists(self::$cache, 'deleteMulti')) {
149
+            self::$cache->deleteMulti($keys);
150
+        } else {
151
+            foreach ($keys as $key) {
152
+                self::$cache->delete($key);
153
+            }
154
+        }
155
+        return true;
156
+    }
157
+
158
+    /**
159
+     * Set a value in the cache if it's not already stored
160
+     *
161
+     * @param string $key
162
+     * @param mixed $value
163
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
164
+     * @return bool
165
+     * @throws \Exception
166
+     */
167
+    public function add($key, $value, $ttl = 0) {
168
+        $result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
169
+        if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
170
+            $this->verifyReturnCode();
171
+        }
172
+        return $result;
173
+    }
174
+
175
+    /**
176
+     * Increase a stored number
177
+     *
178
+     * @param string $key
179
+     * @param int $step
180
+     * @return int | bool
181
+     */
182
+    public function inc($key, $step = 1) {
183
+        $this->add($key, 0);
184
+        $result = self::$cache->increment($this->getPrefix() . $key, $step);
185
+
186
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
187
+            return false;
188
+        }
189
+
190
+        return $result;
191
+    }
192
+
193
+    /**
194
+     * Decrease a stored number
195
+     *
196
+     * @param string $key
197
+     * @param int $step
198
+     * @return int | bool
199
+     */
200
+    public function dec($key, $step = 1) {
201
+        $result = self::$cache->decrement($this->getPrefix() . $key, $step);
202
+
203
+        if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
204
+            return false;
205
+        }
206
+
207
+        return $result;
208
+    }
209
+
210
+    static public function isAvailable() {
211
+        return extension_loaded('memcached');
212
+    }
213
+
214
+    /**
215
+     * @throws \Exception
216
+     */
217
+    private function verifyReturnCode() {
218
+        $code = self::$cache->getResultCode();
219
+        if ($code === \Memcached::RES_SUCCESS) {
220
+            return;
221
+        }
222
+        $message = self::$cache->getResultMessage();
223
+        throw new \Exception("Error $code interacting with memcached : $message");
224
+    }
225 225
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 	}
98 98
 
99 99
 	public function get($key) {
100
-		$result = self::$cache->get($this->getNameSpace() . $key);
100
+		$result = self::$cache->get($this->getNameSpace().$key);
101 101
 		if ($result === false and self::$cache->getResultCode() == \Memcached::RES_NOTFOUND) {
102 102
 			return null;
103 103
 		} else {
@@ -107,9 +107,9 @@  discard block
 block discarded – undo
107 107
 
108 108
 	public function set($key, $value, $ttl = 0) {
109 109
 		if ($ttl > 0) {
110
-			$result =  self::$cache->set($this->getNameSpace() . $key, $value, $ttl);
110
+			$result = self::$cache->set($this->getNameSpace().$key, $value, $ttl);
111 111
 		} else {
112
-			$result = self::$cache->set($this->getNameSpace() . $key, $value);
112
+			$result = self::$cache->set($this->getNameSpace().$key, $value);
113 113
 		}
114 114
 		if ($result !== true) {
115 115
 			$this->verifyReturnCode();
@@ -118,12 +118,12 @@  discard block
 block discarded – undo
118 118
 	}
119 119
 
120 120
 	public function hasKey($key) {
121
-		self::$cache->get($this->getNameSpace() . $key);
121
+		self::$cache->get($this->getNameSpace().$key);
122 122
 		return self::$cache->getResultCode() === \Memcached::RES_SUCCESS;
123 123
 	}
124 124
 
125 125
 	public function remove($key) {
126
-		$result= self::$cache->delete($this->getNameSpace() . $key);
126
+		$result = self::$cache->delete($this->getNameSpace().$key);
127 127
 		if (self::$cache->getResultCode() !== \Memcached::RES_NOTFOUND) {
128 128
 			$this->verifyReturnCode();
129 129
 		}
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 	}
132 132
 
133 133
 	public function clear($prefix = '') {
134
-		$prefix = $this->getNameSpace() . $prefix;
134
+		$prefix = $this->getNameSpace().$prefix;
135 135
 		$allKeys = self::$cache->getAllKeys();
136 136
 		if ($allKeys === false) {
137 137
 			// newer Memcached doesn't like getAllKeys(), flush everything
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 	 * @throws \Exception
166 166
 	 */
167 167
 	public function add($key, $value, $ttl = 0) {
168
-		$result = self::$cache->add($this->getPrefix() . $key, $value, $ttl);
168
+		$result = self::$cache->add($this->getPrefix().$key, $value, $ttl);
169 169
 		if (self::$cache->getResultCode() !== \Memcached::RES_NOTSTORED) {
170 170
 			$this->verifyReturnCode();
171 171
 		}
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 	 */
182 182
 	public function inc($key, $step = 1) {
183 183
 		$this->add($key, 0);
184
-		$result = self::$cache->increment($this->getPrefix() . $key, $step);
184
+		$result = self::$cache->increment($this->getPrefix().$key, $step);
185 185
 
186 186
 		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
187 187
 			return false;
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 	 * @return int | bool
199 199
 	 */
200 200
 	public function dec($key, $step = 1) {
201
-		$result = self::$cache->decrement($this->getPrefix() . $key, $step);
201
+		$result = self::$cache->decrement($this->getPrefix().$key, $step);
202 202
 
203 203
 		if (self::$cache->getResultCode() !== \Memcached::RES_SUCCESS) {
204 204
 			return false;
Please login to merge, or discard this patch.
lib/private/Repair.php 3 patches
Doc Comments   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 	 * Returns expensive repair steps to be run on the
140 140
 	 * command line with a special option.
141 141
 	 *
142
-	 * @return IRepairStep[]
142
+	 * @return OldGroupMembershipShares[]
143 143
 	 */
144 144
 	public static function getExpensiveRepairSteps() {
145 145
 		return [
@@ -216,7 +216,6 @@  discard block
 block discarded – undo
216 216
 	}
217 217
 
218 218
 	/**
219
-	 * @param int $max
220 219
 	 */
221 220
 	public function finishProgress() {
222 221
 		// for now just emit as we did in the past
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@
 block discarded – undo
58 58
 use Symfony\Component\EventDispatcher\EventDispatcher;
59 59
 use Symfony\Component\EventDispatcher\GenericEvent;
60 60
 
61
-class Repair implements IOutput{
61
+class Repair implements IOutput {
62 62
 	/* @var IRepairStep[] */
63 63
 	private $repairSteps;
64 64
 	/** @var EventDispatcher */
Please login to merge, or discard this patch.
Indentation   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -57,182 +57,182 @@
 block discarded – undo
57 57
 use Symfony\Component\EventDispatcher\GenericEvent;
58 58
 
59 59
 class Repair implements IOutput{
60
-	/* @var IRepairStep[] */
61
-	private $repairSteps;
62
-	/** @var EventDispatcher */
63
-	private $dispatcher;
64
-	/** @var string */
65
-	private $currentStep;
66
-
67
-	/**
68
-	 * Creates a new repair step runner
69
-	 *
70
-	 * @param IRepairStep[] $repairSteps array of RepairStep instances
71
-	 * @param EventDispatcher $dispatcher
72
-	 */
73
-	public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
74
-		$this->repairSteps = $repairSteps;
75
-		$this->dispatcher = $dispatcher;
76
-	}
77
-
78
-	/**
79
-	 * Run a series of repair steps for common problems
80
-	 */
81
-	public function run() {
82
-		if (count($this->repairSteps) === 0) {
83
-			$this->emit('\OC\Repair', 'info', array('No repair steps available'));
84
-			return;
85
-		}
86
-		// run each repair step
87
-		foreach ($this->repairSteps as $step) {
88
-			$this->currentStep = $step->getName();
89
-			$this->emit('\OC\Repair', 'step', [$this->currentStep]);
90
-			$step->run($this);
91
-		}
92
-	}
93
-
94
-	/**
95
-	 * Add repair step
96
-	 *
97
-	 * @param IRepairStep|string $repairStep repair step
98
-	 * @throws \Exception
99
-	 */
100
-	public function addStep($repairStep) {
101
-		if (is_string($repairStep)) {
102
-			try {
103
-				$s = \OC::$server->query($repairStep);
104
-			} catch (QueryException $e) {
105
-				if (class_exists($repairStep)) {
106
-					$s = new $repairStep();
107
-				} else {
108
-					throw new \Exception("Repair step '$repairStep' is unknown");
109
-				}
110
-			}
111
-
112
-			if ($s instanceof IRepairStep) {
113
-				$this->repairSteps[] = $s;
114
-			} else {
115
-				throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
116
-			}
117
-		} else {
118
-			$this->repairSteps[] = $repairStep;
119
-		}
120
-	}
121
-
122
-	/**
123
-	 * Returns the default repair steps to be run on the
124
-	 * command line or after an upgrade.
125
-	 *
126
-	 * @return IRepairStep[]
127
-	 */
128
-	public static function getRepairSteps() {
129
-		return [
130
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
131
-			new RepairMimeTypes(\OC::$server->getConfig()),
132
-			new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
133
-			new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
134
-			new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
135
-			new MoveUpdaterStepFile(\OC::$server->getConfig()),
136
-			new MoveAvatars(
137
-				\OC::$server->getJobList(),
138
-				\OC::$server->getConfig()
139
-			),
140
-			new CleanPreviews(
141
-				\OC::$server->getJobList(),
142
-				\OC::$server->getUserManager(),
143
-				\OC::$server->getConfig()
144
-			),
145
-			new FixMountStorages(\OC::$server->getDatabaseConnection()),
146
-			new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
147
-			new InstallCoreBundle(
148
-				\OC::$server->query(BundleFetcher::class),
149
-				\OC::$server->getConfig(),
150
-				\OC::$server->query(Installer::class)
151
-			),
152
-			new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
153
-			new RepairIdentityProofKeyFolders(\OC::$server->getConfig(), \OC::$server->query(Factory::class), \OC::$server->getRootFolder()),
154
-			new AddLogRotateJob(\OC::$server->getJobList()),
155
-		];
156
-	}
157
-
158
-	/**
159
-	 * Returns expensive repair steps to be run on the
160
-	 * command line with a special option.
161
-	 *
162
-	 * @return IRepairStep[]
163
-	 */
164
-	public static function getExpensiveRepairSteps() {
165
-		return [
166
-			new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager())
167
-		];
168
-	}
169
-
170
-	/**
171
-	 * Returns the repair steps to be run before an
172
-	 * upgrade.
173
-	 *
174
-	 * @return IRepairStep[]
175
-	 */
176
-	public static function getBeforeUpgradeRepairSteps() {
177
-		$connection = \OC::$server->getDatabaseConnection();
178
-		$config = \OC::$server->getConfig();
179
-		$steps = [
180
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
181
-			new SqliteAutoincrement($connection),
182
-			new SaveAccountsTableData($connection, $config),
183
-			new DropAccountTermsTable($connection),
184
-		];
185
-
186
-		return $steps;
187
-	}
188
-
189
-	/**
190
-	 * @param string $scope
191
-	 * @param string $method
192
-	 * @param array $arguments
193
-	 */
194
-	public function emit($scope, $method, array $arguments = []) {
195
-		if (!is_null($this->dispatcher)) {
196
-			$this->dispatcher->dispatch("$scope::$method",
197
-				new GenericEvent("$scope::$method", $arguments));
198
-		}
199
-	}
200
-
201
-	public function info($string) {
202
-		// for now just emit as we did in the past
203
-		$this->emit('\OC\Repair', 'info', array($string));
204
-	}
205
-
206
-	/**
207
-	 * @param string $message
208
-	 */
209
-	public function warning($message) {
210
-		// for now just emit as we did in the past
211
-		$this->emit('\OC\Repair', 'warning', [$message]);
212
-	}
213
-
214
-	/**
215
-	 * @param int $max
216
-	 */
217
-	public function startProgress($max = 0) {
218
-		// for now just emit as we did in the past
219
-		$this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
220
-	}
221
-
222
-	/**
223
-	 * @param int $step
224
-	 * @param string $description
225
-	 */
226
-	public function advance($step = 1, $description = '') {
227
-		// for now just emit as we did in the past
228
-		$this->emit('\OC\Repair', 'advance', [$step, $description]);
229
-	}
230
-
231
-	/**
232
-	 * @param int $max
233
-	 */
234
-	public function finishProgress() {
235
-		// for now just emit as we did in the past
236
-		$this->emit('\OC\Repair', 'finishProgress', []);
237
-	}
60
+    /* @var IRepairStep[] */
61
+    private $repairSteps;
62
+    /** @var EventDispatcher */
63
+    private $dispatcher;
64
+    /** @var string */
65
+    private $currentStep;
66
+
67
+    /**
68
+     * Creates a new repair step runner
69
+     *
70
+     * @param IRepairStep[] $repairSteps array of RepairStep instances
71
+     * @param EventDispatcher $dispatcher
72
+     */
73
+    public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
74
+        $this->repairSteps = $repairSteps;
75
+        $this->dispatcher = $dispatcher;
76
+    }
77
+
78
+    /**
79
+     * Run a series of repair steps for common problems
80
+     */
81
+    public function run() {
82
+        if (count($this->repairSteps) === 0) {
83
+            $this->emit('\OC\Repair', 'info', array('No repair steps available'));
84
+            return;
85
+        }
86
+        // run each repair step
87
+        foreach ($this->repairSteps as $step) {
88
+            $this->currentStep = $step->getName();
89
+            $this->emit('\OC\Repair', 'step', [$this->currentStep]);
90
+            $step->run($this);
91
+        }
92
+    }
93
+
94
+    /**
95
+     * Add repair step
96
+     *
97
+     * @param IRepairStep|string $repairStep repair step
98
+     * @throws \Exception
99
+     */
100
+    public function addStep($repairStep) {
101
+        if (is_string($repairStep)) {
102
+            try {
103
+                $s = \OC::$server->query($repairStep);
104
+            } catch (QueryException $e) {
105
+                if (class_exists($repairStep)) {
106
+                    $s = new $repairStep();
107
+                } else {
108
+                    throw new \Exception("Repair step '$repairStep' is unknown");
109
+                }
110
+            }
111
+
112
+            if ($s instanceof IRepairStep) {
113
+                $this->repairSteps[] = $s;
114
+            } else {
115
+                throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
116
+            }
117
+        } else {
118
+            $this->repairSteps[] = $repairStep;
119
+        }
120
+    }
121
+
122
+    /**
123
+     * Returns the default repair steps to be run on the
124
+     * command line or after an upgrade.
125
+     *
126
+     * @return IRepairStep[]
127
+     */
128
+    public static function getRepairSteps() {
129
+        return [
130
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
131
+            new RepairMimeTypes(\OC::$server->getConfig()),
132
+            new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
133
+            new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
134
+            new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
135
+            new MoveUpdaterStepFile(\OC::$server->getConfig()),
136
+            new MoveAvatars(
137
+                \OC::$server->getJobList(),
138
+                \OC::$server->getConfig()
139
+            ),
140
+            new CleanPreviews(
141
+                \OC::$server->getJobList(),
142
+                \OC::$server->getUserManager(),
143
+                \OC::$server->getConfig()
144
+            ),
145
+            new FixMountStorages(\OC::$server->getDatabaseConnection()),
146
+            new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
147
+            new InstallCoreBundle(
148
+                \OC::$server->query(BundleFetcher::class),
149
+                \OC::$server->getConfig(),
150
+                \OC::$server->query(Installer::class)
151
+            ),
152
+            new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
153
+            new RepairIdentityProofKeyFolders(\OC::$server->getConfig(), \OC::$server->query(Factory::class), \OC::$server->getRootFolder()),
154
+            new AddLogRotateJob(\OC::$server->getJobList()),
155
+        ];
156
+    }
157
+
158
+    /**
159
+     * Returns expensive repair steps to be run on the
160
+     * command line with a special option.
161
+     *
162
+     * @return IRepairStep[]
163
+     */
164
+    public static function getExpensiveRepairSteps() {
165
+        return [
166
+            new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager())
167
+        ];
168
+    }
169
+
170
+    /**
171
+     * Returns the repair steps to be run before an
172
+     * upgrade.
173
+     *
174
+     * @return IRepairStep[]
175
+     */
176
+    public static function getBeforeUpgradeRepairSteps() {
177
+        $connection = \OC::$server->getDatabaseConnection();
178
+        $config = \OC::$server->getConfig();
179
+        $steps = [
180
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
181
+            new SqliteAutoincrement($connection),
182
+            new SaveAccountsTableData($connection, $config),
183
+            new DropAccountTermsTable($connection),
184
+        ];
185
+
186
+        return $steps;
187
+    }
188
+
189
+    /**
190
+     * @param string $scope
191
+     * @param string $method
192
+     * @param array $arguments
193
+     */
194
+    public function emit($scope, $method, array $arguments = []) {
195
+        if (!is_null($this->dispatcher)) {
196
+            $this->dispatcher->dispatch("$scope::$method",
197
+                new GenericEvent("$scope::$method", $arguments));
198
+        }
199
+    }
200
+
201
+    public function info($string) {
202
+        // for now just emit as we did in the past
203
+        $this->emit('\OC\Repair', 'info', array($string));
204
+    }
205
+
206
+    /**
207
+     * @param string $message
208
+     */
209
+    public function warning($message) {
210
+        // for now just emit as we did in the past
211
+        $this->emit('\OC\Repair', 'warning', [$message]);
212
+    }
213
+
214
+    /**
215
+     * @param int $max
216
+     */
217
+    public function startProgress($max = 0) {
218
+        // for now just emit as we did in the past
219
+        $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
220
+    }
221
+
222
+    /**
223
+     * @param int $step
224
+     * @param string $description
225
+     */
226
+    public function advance($step = 1, $description = '') {
227
+        // for now just emit as we did in the past
228
+        $this->emit('\OC\Repair', 'advance', [$step, $description]);
229
+    }
230
+
231
+    /**
232
+     * @param int $max
233
+     */
234
+    public function finishProgress() {
235
+        // for now just emit as we did in the past
236
+        $this->emit('\OC\Repair', 'finishProgress', []);
237
+    }
238 238
 }
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.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 	public function __destruct() {
67 67
 		try {
68 68
 			$this->close();
69
-		} catch (SessionNotAvailableException $e){
69
+		} catch (SessionNotAvailableException $e) {
70 70
 			// This exception can occur if session is already closed
71 71
 			// So it is safe to ignore it and let the garbage collector to proceed
72 72
 		}
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 	 * @return string|null Either the value or null
103 103
 	 */
104 104
 	public function get($key) {
105
-		if(isset($this->sessionValues[$key])) {
105
+		if (isset($this->sessionValues[$key])) {
106 106
 			return $this->sessionValues[$key];
107 107
 		}
108 108
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 	 * Close the session and release the lock, also writes all changed data in batch
169 169
 	 */
170 170
 	public function close() {
171
-		if($this->isModified) {
171
+		if ($this->isModified) {
172 172
 			$encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
173 173
 			$this->session->set(self::encryptedSessionName, $encryptedValue);
174 174
 			$this->isModified = false;
Please login to merge, or discard this patch.
Indentation   +172 added lines, -172 removed lines patch added patch discarded remove patch
@@ -36,176 +36,176 @@
 block discarded – undo
36 36
  * @package OC\Session
37 37
  */
38 38
 class CryptoSessionData implements \ArrayAccess, ISession {
39
-	/** @var ISession */
40
-	protected $session;
41
-	/** @var \OCP\Security\ICrypto */
42
-	protected $crypto;
43
-	/** @var string */
44
-	protected $passphrase;
45
-	/** @var array */
46
-	protected $sessionValues;
47
-	/** @var bool */
48
-	protected $isModified = false;
49
-	CONST encryptedSessionName = 'encrypted_session_data';
50
-
51
-	/**
52
-	 * @param ISession $session
53
-	 * @param ICrypto $crypto
54
-	 * @param string $passphrase
55
-	 */
56
-	public function __construct(ISession $session,
57
-								ICrypto $crypto,
58
-								$passphrase) {
59
-		$this->crypto = $crypto;
60
-		$this->session = $session;
61
-		$this->passphrase = $passphrase;
62
-		$this->initializeSession();
63
-	}
64
-
65
-	/**
66
-	 * Close session if class gets destructed
67
-	 */
68
-	public function __destruct() {
69
-		try {
70
-			$this->close();
71
-		} catch (SessionNotAvailableException $e){
72
-			// This exception can occur if session is already closed
73
-			// So it is safe to ignore it and let the garbage collector to proceed
74
-		}
75
-	}
76
-
77
-	protected function initializeSession() {
78
-		$encryptedSessionData = $this->session->get(self::encryptedSessionName) ?: '';
79
-		try {
80
-			$this->sessionValues = json_decode(
81
-				$this->crypto->decrypt($encryptedSessionData, $this->passphrase),
82
-				true
83
-			);
84
-		} catch (\Exception $e) {
85
-			$this->sessionValues = [];
86
-		}
87
-	}
88
-
89
-	/**
90
-	 * Set a value in the session
91
-	 *
92
-	 * @param string $key
93
-	 * @param mixed $value
94
-	 */
95
-	public function set($key, $value) {
96
-		$this->sessionValues[$key] = $value;
97
-		$this->isModified = true;
98
-	}
99
-
100
-	/**
101
-	 * Get a value from the session
102
-	 *
103
-	 * @param string $key
104
-	 * @return string|null Either the value or null
105
-	 */
106
-	public function get($key) {
107
-		if(isset($this->sessionValues[$key])) {
108
-			return $this->sessionValues[$key];
109
-		}
110
-
111
-		return null;
112
-	}
113
-
114
-	/**
115
-	 * Check if a named key exists in the session
116
-	 *
117
-	 * @param string $key
118
-	 * @return bool
119
-	 */
120
-	public function exists($key) {
121
-		return isset($this->sessionValues[$key]);
122
-	}
123
-
124
-	/**
125
-	 * Remove a $key/$value pair from the session
126
-	 *
127
-	 * @param string $key
128
-	 */
129
-	public function remove($key) {
130
-		$this->isModified = true;
131
-		unset($this->sessionValues[$key]);
132
-		$this->session->remove(self::encryptedSessionName);
133
-	}
134
-
135
-	/**
136
-	 * Reset and recreate the session
137
-	 */
138
-	public function clear() {
139
-		$requesttoken = $this->get('requesttoken');
140
-		$this->sessionValues = [];
141
-		if ($requesttoken !== null) {
142
-			$this->set('requesttoken', $requesttoken);
143
-		}
144
-		$this->isModified = true;
145
-		$this->session->clear();
146
-	}
147
-
148
-	/**
149
-	 * Wrapper around session_regenerate_id
150
-	 *
151
-	 * @param bool $deleteOldSession Whether to delete the old associated session file or not.
152
-	 * @return void
153
-	 */
154
-	public function regenerateId($deleteOldSession = true) {
155
-		$this->session->regenerateId($deleteOldSession);
156
-	}
157
-
158
-	/**
159
-	 * Wrapper around session_id
160
-	 *
161
-	 * @return string
162
-	 * @throws SessionNotAvailableException
163
-	 * @since 9.1.0
164
-	 */
165
-	public function getId() {
166
-		return $this->session->getId();
167
-	}
168
-
169
-	/**
170
-	 * Close the session and release the lock, also writes all changed data in batch
171
-	 */
172
-	public function close() {
173
-		if($this->isModified) {
174
-			$encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
175
-			$this->session->set(self::encryptedSessionName, $encryptedValue);
176
-			$this->isModified = false;
177
-		}
178
-		$this->session->close();
179
-	}
180
-
181
-	/**
182
-	 * @param mixed $offset
183
-	 * @return bool
184
-	 */
185
-	public function offsetExists($offset) {
186
-		return $this->exists($offset);
187
-	}
188
-
189
-	/**
190
-	 * @param mixed $offset
191
-	 * @return mixed
192
-	 */
193
-	public function offsetGet($offset) {
194
-		return $this->get($offset);
195
-	}
196
-
197
-	/**
198
-	 * @param mixed $offset
199
-	 * @param mixed $value
200
-	 */
201
-	public function offsetSet($offset, $value) {
202
-		$this->set($offset, $value);
203
-	}
204
-
205
-	/**
206
-	 * @param mixed $offset
207
-	 */
208
-	public function offsetUnset($offset) {
209
-		$this->remove($offset);
210
-	}
39
+    /** @var ISession */
40
+    protected $session;
41
+    /** @var \OCP\Security\ICrypto */
42
+    protected $crypto;
43
+    /** @var string */
44
+    protected $passphrase;
45
+    /** @var array */
46
+    protected $sessionValues;
47
+    /** @var bool */
48
+    protected $isModified = false;
49
+    CONST encryptedSessionName = 'encrypted_session_data';
50
+
51
+    /**
52
+     * @param ISession $session
53
+     * @param ICrypto $crypto
54
+     * @param string $passphrase
55
+     */
56
+    public function __construct(ISession $session,
57
+                                ICrypto $crypto,
58
+                                $passphrase) {
59
+        $this->crypto = $crypto;
60
+        $this->session = $session;
61
+        $this->passphrase = $passphrase;
62
+        $this->initializeSession();
63
+    }
64
+
65
+    /**
66
+     * Close session if class gets destructed
67
+     */
68
+    public function __destruct() {
69
+        try {
70
+            $this->close();
71
+        } catch (SessionNotAvailableException $e){
72
+            // This exception can occur if session is already closed
73
+            // So it is safe to ignore it and let the garbage collector to proceed
74
+        }
75
+    }
76
+
77
+    protected function initializeSession() {
78
+        $encryptedSessionData = $this->session->get(self::encryptedSessionName) ?: '';
79
+        try {
80
+            $this->sessionValues = json_decode(
81
+                $this->crypto->decrypt($encryptedSessionData, $this->passphrase),
82
+                true
83
+            );
84
+        } catch (\Exception $e) {
85
+            $this->sessionValues = [];
86
+        }
87
+    }
88
+
89
+    /**
90
+     * Set a value in the session
91
+     *
92
+     * @param string $key
93
+     * @param mixed $value
94
+     */
95
+    public function set($key, $value) {
96
+        $this->sessionValues[$key] = $value;
97
+        $this->isModified = true;
98
+    }
99
+
100
+    /**
101
+     * Get a value from the session
102
+     *
103
+     * @param string $key
104
+     * @return string|null Either the value or null
105
+     */
106
+    public function get($key) {
107
+        if(isset($this->sessionValues[$key])) {
108
+            return $this->sessionValues[$key];
109
+        }
110
+
111
+        return null;
112
+    }
113
+
114
+    /**
115
+     * Check if a named key exists in the session
116
+     *
117
+     * @param string $key
118
+     * @return bool
119
+     */
120
+    public function exists($key) {
121
+        return isset($this->sessionValues[$key]);
122
+    }
123
+
124
+    /**
125
+     * Remove a $key/$value pair from the session
126
+     *
127
+     * @param string $key
128
+     */
129
+    public function remove($key) {
130
+        $this->isModified = true;
131
+        unset($this->sessionValues[$key]);
132
+        $this->session->remove(self::encryptedSessionName);
133
+    }
134
+
135
+    /**
136
+     * Reset and recreate the session
137
+     */
138
+    public function clear() {
139
+        $requesttoken = $this->get('requesttoken');
140
+        $this->sessionValues = [];
141
+        if ($requesttoken !== null) {
142
+            $this->set('requesttoken', $requesttoken);
143
+        }
144
+        $this->isModified = true;
145
+        $this->session->clear();
146
+    }
147
+
148
+    /**
149
+     * Wrapper around session_regenerate_id
150
+     *
151
+     * @param bool $deleteOldSession Whether to delete the old associated session file or not.
152
+     * @return void
153
+     */
154
+    public function regenerateId($deleteOldSession = true) {
155
+        $this->session->regenerateId($deleteOldSession);
156
+    }
157
+
158
+    /**
159
+     * Wrapper around session_id
160
+     *
161
+     * @return string
162
+     * @throws SessionNotAvailableException
163
+     * @since 9.1.0
164
+     */
165
+    public function getId() {
166
+        return $this->session->getId();
167
+    }
168
+
169
+    /**
170
+     * Close the session and release the lock, also writes all changed data in batch
171
+     */
172
+    public function close() {
173
+        if($this->isModified) {
174
+            $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
175
+            $this->session->set(self::encryptedSessionName, $encryptedValue);
176
+            $this->isModified = false;
177
+        }
178
+        $this->session->close();
179
+    }
180
+
181
+    /**
182
+     * @param mixed $offset
183
+     * @return bool
184
+     */
185
+    public function offsetExists($offset) {
186
+        return $this->exists($offset);
187
+    }
188
+
189
+    /**
190
+     * @param mixed $offset
191
+     * @return mixed
192
+     */
193
+    public function offsetGet($offset) {
194
+        return $this->get($offset);
195
+    }
196
+
197
+    /**
198
+     * @param mixed $offset
199
+     * @param mixed $value
200
+     */
201
+    public function offsetSet($offset, $value) {
202
+        $this->set($offset, $value);
203
+    }
204
+
205
+    /**
206
+     * @param mixed $offset
207
+     */
208
+    public function offsetUnset($offset) {
209
+        $this->remove($offset);
210
+    }
211 211
 }
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.
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.
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.