Completed
Branch fix/noid/ldap-unsupported-avat... (a4dda4)
by Morris
25:29
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 = \OC::$server->getTempManager()->getTemporaryFile();
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 = \OC::$server->getTempManager()->getTemporaryFile();
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 = \OC::$server->getTempManager()->getTemporaryFile();
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   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -32,181 +32,181 @@
 block discarded – undo
32 32
 
33 33
 class Quota extends Wrapper {
34 34
 
35
-	/**
36
-	 * @var int $quota
37
-	 */
38
-	protected $quota;
39
-
40
-	/**
41
-	 * @var string $sizeRoot
42
-	 */
43
-	protected $sizeRoot;
44
-
45
-	/**
46
-	 * @param array $parameters
47
-	 */
48
-	public function __construct($parameters) {
49
-		parent::__construct($parameters);
50
-		$this->quota = $parameters['quota'];
51
-		$this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
52
-	}
53
-
54
-	/**
55
-	 * @return int quota value
56
-	 */
57
-	public function getQuota() {
58
-		return $this->quota;
59
-	}
60
-
61
-	/**
62
-	 * @param string $path
63
-	 * @param \OC\Files\Storage\Storage $storage
64
-	 */
65
-	protected function getSize($path, $storage = null) {
66
-		if (is_null($storage)) {
67
-			$cache = $this->getCache();
68
-		} else {
69
-			$cache = $storage->getCache();
70
-		}
71
-		$data = $cache->get($path);
72
-		if ($data instanceof ICacheEntry and isset($data['size'])) {
73
-			return $data['size'];
74
-		} else {
75
-			return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
76
-		}
77
-	}
78
-
79
-	/**
80
-	 * Get free space as limited by the quota
81
-	 *
82
-	 * @param string $path
83
-	 * @return int
84
-	 */
85
-	public function free_space($path) {
86
-		if ($this->quota < 0 || strpos($path, 'cache') === 0) {
87
-			return $this->storage->free_space($path);
88
-		} else {
89
-			$used = $this->getSize($this->sizeRoot);
90
-			if ($used < 0) {
91
-				return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
92
-			} else {
93
-				$free = $this->storage->free_space($path);
94
-				$quotaFree = max($this->quota - $used, 0);
95
-				// if free space is known
96
-				if ($free >= 0) {
97
-					$free = min($free, $quotaFree);
98
-				} else {
99
-					$free = $quotaFree;
100
-				}
101
-				return $free;
102
-			}
103
-		}
104
-	}
105
-
106
-	/**
107
-	 * see http://php.net/manual/en/function.file_put_contents.php
108
-	 *
109
-	 * @param string $path
110
-	 * @param string $data
111
-	 * @return bool
112
-	 */
113
-	public function file_put_contents($path, $data) {
114
-		$free = $this->free_space($path);
115
-		if ($free < 0 or strlen($data) < $free) {
116
-			return $this->storage->file_put_contents($path, $data);
117
-		} else {
118
-			return false;
119
-		}
120
-	}
121
-
122
-	/**
123
-	 * see http://php.net/manual/en/function.copy.php
124
-	 *
125
-	 * @param string $source
126
-	 * @param string $target
127
-	 * @return bool
128
-	 */
129
-	public function copy($source, $target) {
130
-		$free = $this->free_space($target);
131
-		if ($free < 0 or $this->getSize($source) < $free) {
132
-			return $this->storage->copy($source, $target);
133
-		} else {
134
-			return false;
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * see http://php.net/manual/en/function.fopen.php
140
-	 *
141
-	 * @param string $path
142
-	 * @param string $mode
143
-	 * @return resource
144
-	 */
145
-	public function fopen($path, $mode) {
146
-		$source = $this->storage->fopen($path, $mode);
147
-
148
-		// don't apply quota for part files
149
-		if (!$this->isPartFile($path)) {
150
-			$free = $this->free_space($path);
151
-			if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
152
-				// only apply quota for files, not metadata, trash or others
153
-				if (strpos(ltrim($path, '/'), 'files/') === 0) {
154
-					return \OC\Files\Stream\Quota::wrap($source, $free);
155
-				}
156
-			}
157
-		}
158
-		return $source;
159
-	}
160
-
161
-	/**
162
-	 * Checks whether the given path is a part file
163
-	 *
164
-	 * @param string $path Path that may identify a .part file
165
-	 * @return string File path without .part extension
166
-	 * @note this is needed for reusing keys
167
-	 */
168
-	private function isPartFile($path) {
169
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
170
-
171
-		return ($extension === 'part');
172
-	}
173
-
174
-	/**
175
-	 * @param IStorage $sourceStorage
176
-	 * @param string $sourceInternalPath
177
-	 * @param string $targetInternalPath
178
-	 * @return bool
179
-	 */
180
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
181
-		$free = $this->free_space($targetInternalPath);
182
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
183
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
184
-		} else {
185
-			return false;
186
-		}
187
-	}
188
-
189
-	/**
190
-	 * @param IStorage $sourceStorage
191
-	 * @param string $sourceInternalPath
192
-	 * @param string $targetInternalPath
193
-	 * @return bool
194
-	 */
195
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
196
-		$free = $this->free_space($targetInternalPath);
197
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
198
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
199
-		} else {
200
-			return false;
201
-		}
202
-	}
203
-
204
-	public function mkdir($path) {
205
-		$free = $this->free_space($path);
206
-		if ($free === 0.0) {
207
-			return false;
208
-		}
209
-
210
-		return parent::mkdir($path);
211
-	}
35
+    /**
36
+     * @var int $quota
37
+     */
38
+    protected $quota;
39
+
40
+    /**
41
+     * @var string $sizeRoot
42
+     */
43
+    protected $sizeRoot;
44
+
45
+    /**
46
+     * @param array $parameters
47
+     */
48
+    public function __construct($parameters) {
49
+        parent::__construct($parameters);
50
+        $this->quota = $parameters['quota'];
51
+        $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
52
+    }
53
+
54
+    /**
55
+     * @return int quota value
56
+     */
57
+    public function getQuota() {
58
+        return $this->quota;
59
+    }
60
+
61
+    /**
62
+     * @param string $path
63
+     * @param \OC\Files\Storage\Storage $storage
64
+     */
65
+    protected function getSize($path, $storage = null) {
66
+        if (is_null($storage)) {
67
+            $cache = $this->getCache();
68
+        } else {
69
+            $cache = $storage->getCache();
70
+        }
71
+        $data = $cache->get($path);
72
+        if ($data instanceof ICacheEntry and isset($data['size'])) {
73
+            return $data['size'];
74
+        } else {
75
+            return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
76
+        }
77
+    }
78
+
79
+    /**
80
+     * Get free space as limited by the quota
81
+     *
82
+     * @param string $path
83
+     * @return int
84
+     */
85
+    public function free_space($path) {
86
+        if ($this->quota < 0 || strpos($path, 'cache') === 0) {
87
+            return $this->storage->free_space($path);
88
+        } else {
89
+            $used = $this->getSize($this->sizeRoot);
90
+            if ($used < 0) {
91
+                return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
92
+            } else {
93
+                $free = $this->storage->free_space($path);
94
+                $quotaFree = max($this->quota - $used, 0);
95
+                // if free space is known
96
+                if ($free >= 0) {
97
+                    $free = min($free, $quotaFree);
98
+                } else {
99
+                    $free = $quotaFree;
100
+                }
101
+                return $free;
102
+            }
103
+        }
104
+    }
105
+
106
+    /**
107
+     * see http://php.net/manual/en/function.file_put_contents.php
108
+     *
109
+     * @param string $path
110
+     * @param string $data
111
+     * @return bool
112
+     */
113
+    public function file_put_contents($path, $data) {
114
+        $free = $this->free_space($path);
115
+        if ($free < 0 or strlen($data) < $free) {
116
+            return $this->storage->file_put_contents($path, $data);
117
+        } else {
118
+            return false;
119
+        }
120
+    }
121
+
122
+    /**
123
+     * see http://php.net/manual/en/function.copy.php
124
+     *
125
+     * @param string $source
126
+     * @param string $target
127
+     * @return bool
128
+     */
129
+    public function copy($source, $target) {
130
+        $free = $this->free_space($target);
131
+        if ($free < 0 or $this->getSize($source) < $free) {
132
+            return $this->storage->copy($source, $target);
133
+        } else {
134
+            return false;
135
+        }
136
+    }
137
+
138
+    /**
139
+     * see http://php.net/manual/en/function.fopen.php
140
+     *
141
+     * @param string $path
142
+     * @param string $mode
143
+     * @return resource
144
+     */
145
+    public function fopen($path, $mode) {
146
+        $source = $this->storage->fopen($path, $mode);
147
+
148
+        // don't apply quota for part files
149
+        if (!$this->isPartFile($path)) {
150
+            $free = $this->free_space($path);
151
+            if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
152
+                // only apply quota for files, not metadata, trash or others
153
+                if (strpos(ltrim($path, '/'), 'files/') === 0) {
154
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
155
+                }
156
+            }
157
+        }
158
+        return $source;
159
+    }
160
+
161
+    /**
162
+     * Checks whether the given path is a part file
163
+     *
164
+     * @param string $path Path that may identify a .part file
165
+     * @return string File path without .part extension
166
+     * @note this is needed for reusing keys
167
+     */
168
+    private function isPartFile($path) {
169
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
170
+
171
+        return ($extension === 'part');
172
+    }
173
+
174
+    /**
175
+     * @param IStorage $sourceStorage
176
+     * @param string $sourceInternalPath
177
+     * @param string $targetInternalPath
178
+     * @return bool
179
+     */
180
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
181
+        $free = $this->free_space($targetInternalPath);
182
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
183
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
184
+        } else {
185
+            return false;
186
+        }
187
+    }
188
+
189
+    /**
190
+     * @param IStorage $sourceStorage
191
+     * @param string $sourceInternalPath
192
+     * @param string $targetInternalPath
193
+     * @return bool
194
+     */
195
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
196
+        $free = $this->free_space($targetInternalPath);
197
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
198
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
199
+        } else {
200
+            return false;
201
+        }
202
+    }
203
+
204
+    public function mkdir($path) {
205
+        $free = $this->free_space($path);
206
+        if ($free === 0.0) {
207
+            return false;
208
+        }
209
+
210
+        return parent::mkdir($path);
211
+    }
212 212
 }
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.
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 . '",' . OC_JSON::encode($data) . ')</script>' . PHP_EOL;
114
-			echo $response;
115
-		} else {
116
-			if ($type) {
117
-				echo 'event: ' . $type . PHP_EOL;
118
-			}
119
-			echo 'data: ' . OC_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 . '",' . OC_JSON::encode($data) . ')</script>' . PHP_EOL;
114
+            echo $response;
115
+        } else {
116
+            if ($type) {
117
+                echo 'event: ' . $type . PHP_EOL;
118
+            }
119
+            echo 'data: ' . OC_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.
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
 		}
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 	 */
102 102
 	public function send($type, $data = null) {
103 103
 		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
104
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
+			throw new BadMethodCallException('Type needs to be alphanumeric ('.$type.')');
105 105
 		}
106 106
 		$this->init();
107 107
 		if (is_null($data)) {
@@ -110,13 +110,13 @@  discard block
 block discarded – undo
110 110
 		}
111 111
 		if ($this->fallback) {
112 112
 			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
113
-				. $this->fallBackId . ',"' . $type . '",' . OC_JSON::encode($data) . ')</script>' . PHP_EOL;
113
+				. $this->fallBackId.',"'.$type.'",'.OC_JSON::encode($data).')</script>'.PHP_EOL;
114 114
 			echo $response;
115 115
 		} else {
116 116
 			if ($type) {
117
-				echo 'event: ' . $type . PHP_EOL;
117
+				echo 'event: '.$type.PHP_EOL;
118 118
 			}
119
-			echo 'data: ' . OC_JSON::encode($data) . PHP_EOL;
119
+			echo 'data: '.OC_JSON::encode($data).PHP_EOL;
120 120
 		}
121 121
 		echo PHP_EOL;
122 122
 		flush();
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   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -55,169 +55,169 @@
 block discarded – undo
55 55
 use Symfony\Component\EventDispatcher\GenericEvent;
56 56
 
57 57
 class Repair implements IOutput{
58
-	/* @var IRepairStep[] */
59
-	private $repairSteps;
60
-	/** @var EventDispatcher */
61
-	private $dispatcher;
62
-	/** @var string */
63
-	private $currentStep;
64
-
65
-	/**
66
-	 * Creates a new repair step runner
67
-	 *
68
-	 * @param IRepairStep[] $repairSteps array of RepairStep instances
69
-	 * @param EventDispatcher $dispatcher
70
-	 */
71
-	public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
72
-		$this->repairSteps = $repairSteps;
73
-		$this->dispatcher = $dispatcher;
74
-	}
75
-
76
-	/**
77
-	 * Run a series of repair steps for common problems
78
-	 */
79
-	public function run() {
80
-		if (count($this->repairSteps) === 0) {
81
-			$this->emit('\OC\Repair', 'info', array('No repair steps available'));
82
-			return;
83
-		}
84
-		// run each repair step
85
-		foreach ($this->repairSteps as $step) {
86
-			$this->currentStep = $step->getName();
87
-			$this->emit('\OC\Repair', 'step', [$this->currentStep]);
88
-			$step->run($this);
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * Add repair step
94
-	 *
95
-	 * @param IRepairStep|string $repairStep repair step
96
-	 * @throws \Exception
97
-	 */
98
-	public function addStep($repairStep) {
99
-		if (is_string($repairStep)) {
100
-			try {
101
-				$s = \OC::$server->query($repairStep);
102
-			} catch (QueryException $e) {
103
-				if (class_exists($repairStep)) {
104
-					$s = new $repairStep();
105
-				} else {
106
-					throw new \Exception("Repair step '$repairStep' is unknown");
107
-				}
108
-			}
109
-
110
-			if ($s instanceof IRepairStep) {
111
-				$this->repairSteps[] = $s;
112
-			} else {
113
-				throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
114
-			}
115
-		} else {
116
-			$this->repairSteps[] = $repairStep;
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * Returns the default repair steps to be run on the
122
-	 * command line or after an upgrade.
123
-	 *
124
-	 * @return IRepairStep[]
125
-	 */
126
-	public static function getRepairSteps() {
127
-		return [
128
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
129
-			new RepairMimeTypes(\OC::$server->getConfig()),
130
-			new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
131
-			new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
132
-			new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
133
-			new MoveUpdaterStepFile(\OC::$server->getConfig()),
134
-			new FixMountStorages(\OC::$server->getDatabaseConnection()),
135
-			new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
136
-			new AddLogRotateJob(\OC::$server->getJobList()),
137
-			new ClearFrontendCaches(\OC::$server->getMemCacheFactory(), \OC::$server->query(SCSSCacher::class), \OC::$server->query(JSCombiner::class)),
138
-			new AddPreviewBackgroundCleanupJob(\OC::$server->getJobList()),
139
-			new AddCleanupUpdaterBackupsJob(\OC::$server->getJobList()),
140
-		];
141
-	}
142
-
143
-	/**
144
-	 * Returns expensive repair steps to be run on the
145
-	 * command line with a special option.
146
-	 *
147
-	 * @return IRepairStep[]
148
-	 */
149
-	public static function getExpensiveRepairSteps() {
150
-		return [
151
-			new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
152
-		];
153
-	}
154
-
155
-	/**
156
-	 * Returns the repair steps to be run before an
157
-	 * upgrade.
158
-	 *
159
-	 * @return IRepairStep[]
160
-	 */
161
-	public static function getBeforeUpgradeRepairSteps() {
162
-		$connection = \OC::$server->getDatabaseConnection();
163
-		$config = \OC::$server->getConfig();
164
-		$steps = [
165
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
166
-			new SqliteAutoincrement($connection),
167
-			new SaveAccountsTableData($connection, $config),
168
-			new DropAccountTermsTable($connection),
169
-		];
170
-
171
-		return $steps;
172
-	}
173
-
174
-	/**
175
-	 * @param string $scope
176
-	 * @param string $method
177
-	 * @param array $arguments
178
-	 */
179
-	public function emit($scope, $method, array $arguments = []) {
180
-		if (!is_null($this->dispatcher)) {
181
-			$this->dispatcher->dispatch("$scope::$method",
182
-				new GenericEvent("$scope::$method", $arguments));
183
-		}
184
-	}
185
-
186
-	public function info($string) {
187
-		// for now just emit as we did in the past
188
-		$this->emit('\OC\Repair', 'info', array($string));
189
-	}
190
-
191
-	/**
192
-	 * @param string $message
193
-	 */
194
-	public function warning($message) {
195
-		// for now just emit as we did in the past
196
-		$this->emit('\OC\Repair', 'warning', [$message]);
197
-	}
198
-
199
-	/**
200
-	 * @param int $max
201
-	 */
202
-	public function startProgress($max = 0) {
203
-		// for now just emit as we did in the past
204
-		$this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
205
-	}
206
-
207
-	/**
208
-	 * @param int $step
209
-	 * @param string $description
210
-	 */
211
-	public function advance($step = 1, $description = '') {
212
-		// for now just emit as we did in the past
213
-		$this->emit('\OC\Repair', 'advance', [$step, $description]);
214
-	}
215
-
216
-	/**
217
-	 * @param int $max
218
-	 */
219
-	public function finishProgress() {
220
-		// for now just emit as we did in the past
221
-		$this->emit('\OC\Repair', 'finishProgress', []);
222
-	}
58
+    /* @var IRepairStep[] */
59
+    private $repairSteps;
60
+    /** @var EventDispatcher */
61
+    private $dispatcher;
62
+    /** @var string */
63
+    private $currentStep;
64
+
65
+    /**
66
+     * Creates a new repair step runner
67
+     *
68
+     * @param IRepairStep[] $repairSteps array of RepairStep instances
69
+     * @param EventDispatcher $dispatcher
70
+     */
71
+    public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
72
+        $this->repairSteps = $repairSteps;
73
+        $this->dispatcher = $dispatcher;
74
+    }
75
+
76
+    /**
77
+     * Run a series of repair steps for common problems
78
+     */
79
+    public function run() {
80
+        if (count($this->repairSteps) === 0) {
81
+            $this->emit('\OC\Repair', 'info', array('No repair steps available'));
82
+            return;
83
+        }
84
+        // run each repair step
85
+        foreach ($this->repairSteps as $step) {
86
+            $this->currentStep = $step->getName();
87
+            $this->emit('\OC\Repair', 'step', [$this->currentStep]);
88
+            $step->run($this);
89
+        }
90
+    }
91
+
92
+    /**
93
+     * Add repair step
94
+     *
95
+     * @param IRepairStep|string $repairStep repair step
96
+     * @throws \Exception
97
+     */
98
+    public function addStep($repairStep) {
99
+        if (is_string($repairStep)) {
100
+            try {
101
+                $s = \OC::$server->query($repairStep);
102
+            } catch (QueryException $e) {
103
+                if (class_exists($repairStep)) {
104
+                    $s = new $repairStep();
105
+                } else {
106
+                    throw new \Exception("Repair step '$repairStep' is unknown");
107
+                }
108
+            }
109
+
110
+            if ($s instanceof IRepairStep) {
111
+                $this->repairSteps[] = $s;
112
+            } else {
113
+                throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
114
+            }
115
+        } else {
116
+            $this->repairSteps[] = $repairStep;
117
+        }
118
+    }
119
+
120
+    /**
121
+     * Returns the default repair steps to be run on the
122
+     * command line or after an upgrade.
123
+     *
124
+     * @return IRepairStep[]
125
+     */
126
+    public static function getRepairSteps() {
127
+        return [
128
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
129
+            new RepairMimeTypes(\OC::$server->getConfig()),
130
+            new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
131
+            new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
132
+            new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
133
+            new MoveUpdaterStepFile(\OC::$server->getConfig()),
134
+            new FixMountStorages(\OC::$server->getDatabaseConnection()),
135
+            new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
136
+            new AddLogRotateJob(\OC::$server->getJobList()),
137
+            new ClearFrontendCaches(\OC::$server->getMemCacheFactory(), \OC::$server->query(SCSSCacher::class), \OC::$server->query(JSCombiner::class)),
138
+            new AddPreviewBackgroundCleanupJob(\OC::$server->getJobList()),
139
+            new AddCleanupUpdaterBackupsJob(\OC::$server->getJobList()),
140
+        ];
141
+    }
142
+
143
+    /**
144
+     * Returns expensive repair steps to be run on the
145
+     * command line with a special option.
146
+     *
147
+     * @return IRepairStep[]
148
+     */
149
+    public static function getExpensiveRepairSteps() {
150
+        return [
151
+            new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager()),
152
+        ];
153
+    }
154
+
155
+    /**
156
+     * Returns the repair steps to be run before an
157
+     * upgrade.
158
+     *
159
+     * @return IRepairStep[]
160
+     */
161
+    public static function getBeforeUpgradeRepairSteps() {
162
+        $connection = \OC::$server->getDatabaseConnection();
163
+        $config = \OC::$server->getConfig();
164
+        $steps = [
165
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
166
+            new SqliteAutoincrement($connection),
167
+            new SaveAccountsTableData($connection, $config),
168
+            new DropAccountTermsTable($connection),
169
+        ];
170
+
171
+        return $steps;
172
+    }
173
+
174
+    /**
175
+     * @param string $scope
176
+     * @param string $method
177
+     * @param array $arguments
178
+     */
179
+    public function emit($scope, $method, array $arguments = []) {
180
+        if (!is_null($this->dispatcher)) {
181
+            $this->dispatcher->dispatch("$scope::$method",
182
+                new GenericEvent("$scope::$method", $arguments));
183
+        }
184
+    }
185
+
186
+    public function info($string) {
187
+        // for now just emit as we did in the past
188
+        $this->emit('\OC\Repair', 'info', array($string));
189
+    }
190
+
191
+    /**
192
+     * @param string $message
193
+     */
194
+    public function warning($message) {
195
+        // for now just emit as we did in the past
196
+        $this->emit('\OC\Repair', 'warning', [$message]);
197
+    }
198
+
199
+    /**
200
+     * @param int $max
201
+     */
202
+    public function startProgress($max = 0) {
203
+        // for now just emit as we did in the past
204
+        $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
205
+    }
206
+
207
+    /**
208
+     * @param int $step
209
+     * @param string $description
210
+     */
211
+    public function advance($step = 1, $description = '') {
212
+        // for now just emit as we did in the past
213
+        $this->emit('\OC\Repair', 'advance', [$step, $description]);
214
+    }
215
+
216
+    /**
217
+     * @param int $max
218
+     */
219
+    public function finishProgress() {
220
+        // for now just emit as we did in the past
221
+        $this->emit('\OC\Repair', 'finishProgress', []);
222
+    }
223 223
 }
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
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	public function __destruct() {
70 70
 		try {
71 71
 			$this->close();
72
-		} catch (SessionNotAvailableException $e){
72
+		} catch (SessionNotAvailableException $e) {
73 73
 			// This exception can occur if session is already closed
74 74
 			// So it is safe to ignore it and let the garbage collector to proceed
75 75
 		}
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 	 * @return string|null Either the value or null
106 106
 	 */
107 107
 	public function get(string $key) {
108
-		if(isset($this->sessionValues[$key])) {
108
+		if (isset($this->sessionValues[$key])) {
109 109
 			return $this->sessionValues[$key];
110 110
 		}
111 111
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 	 * Close the session and release the lock, also writes all changed data in batch
172 172
 	 */
173 173
 	public function close() {
174
-		if($this->isModified) {
174
+		if ($this->isModified) {
175 175
 			$encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
176 176
 			$this->session->set(self::encryptedSessionName, $encryptedValue);
177 177
 			$this->isModified = false;
Please login to merge, or discard this patch.
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -37,177 +37,177 @@
 block discarded – undo
37 37
  * @package OC\Session
38 38
  */
39 39
 class CryptoSessionData implements \ArrayAccess, ISession {
40
-	/** @var ISession */
41
-	protected $session;
42
-	/** @var \OCP\Security\ICrypto */
43
-	protected $crypto;
44
-	/** @var string */
45
-	protected $passphrase;
46
-	/** @var array */
47
-	protected $sessionValues;
48
-	/** @var bool */
49
-	protected $isModified = false;
50
-	CONST encryptedSessionName = 'encrypted_session_data';
51
-
52
-	/**
53
-	 * @param ISession $session
54
-	 * @param ICrypto $crypto
55
-	 * @param string $passphrase
56
-	 */
57
-	public function __construct(ISession $session,
58
-								ICrypto $crypto,
59
-								string $passphrase) {
60
-		$this->crypto = $crypto;
61
-		$this->session = $session;
62
-		$this->passphrase = $passphrase;
63
-		$this->initializeSession();
64
-	}
65
-
66
-	/**
67
-	 * Close session if class gets destructed
68
-	 */
69
-	public function __destruct() {
70
-		try {
71
-			$this->close();
72
-		} catch (SessionNotAvailableException $e){
73
-			// This exception can occur if session is already closed
74
-			// So it is safe to ignore it and let the garbage collector to proceed
75
-		}
76
-	}
77
-
78
-	protected function initializeSession() {
79
-		$encryptedSessionData = $this->session->get(self::encryptedSessionName) ?: '';
80
-		try {
81
-			$this->sessionValues = json_decode(
82
-				$this->crypto->decrypt($encryptedSessionData, $this->passphrase),
83
-				true
84
-			);
85
-		} catch (\Exception $e) {
86
-			$this->sessionValues = [];
87
-		}
88
-	}
89
-
90
-	/**
91
-	 * Set a value in the session
92
-	 *
93
-	 * @param string $key
94
-	 * @param mixed $value
95
-	 */
96
-	public function set(string $key, $value) {
97
-		$this->sessionValues[$key] = $value;
98
-		$this->isModified = true;
99
-	}
100
-
101
-	/**
102
-	 * Get a value from the session
103
-	 *
104
-	 * @param string $key
105
-	 * @return string|null Either the value or null
106
-	 */
107
-	public function get(string $key) {
108
-		if(isset($this->sessionValues[$key])) {
109
-			return $this->sessionValues[$key];
110
-		}
111
-
112
-		return null;
113
-	}
114
-
115
-	/**
116
-	 * Check if a named key exists in the session
117
-	 *
118
-	 * @param string $key
119
-	 * @return bool
120
-	 */
121
-	public function exists(string $key): bool {
122
-		return isset($this->sessionValues[$key]);
123
-	}
124
-
125
-	/**
126
-	 * Remove a $key/$value pair from the session
127
-	 *
128
-	 * @param string $key
129
-	 */
130
-	public function remove(string $key) {
131
-		$this->isModified = true;
132
-		unset($this->sessionValues[$key]);
133
-		$this->session->remove(self::encryptedSessionName);
134
-	}
135
-
136
-	/**
137
-	 * Reset and recreate the session
138
-	 */
139
-	public function clear() {
140
-		$requesttoken = $this->get('requesttoken');
141
-		$this->sessionValues = [];
142
-		if ($requesttoken !== null) {
143
-			$this->set('requesttoken', $requesttoken);
144
-		}
145
-		$this->isModified = true;
146
-		$this->session->clear();
147
-	}
148
-
149
-	/**
150
-	 * Wrapper around session_regenerate_id
151
-	 *
152
-	 * @param bool $deleteOldSession Whether to delete the old associated session file or not.
153
-	 * @param bool $updateToken Wheater to update the associated auth token
154
-	 * @return void
155
-	 */
156
-	public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) {
157
-		$this->session->regenerateId($deleteOldSession, $updateToken);
158
-	}
159
-
160
-	/**
161
-	 * Wrapper around session_id
162
-	 *
163
-	 * @return string
164
-	 * @throws SessionNotAvailableException
165
-	 * @since 9.1.0
166
-	 */
167
-	public function getId(): string {
168
-		return $this->session->getId();
169
-	}
170
-
171
-	/**
172
-	 * Close the session and release the lock, also writes all changed data in batch
173
-	 */
174
-	public function close() {
175
-		if($this->isModified) {
176
-			$encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
177
-			$this->session->set(self::encryptedSessionName, $encryptedValue);
178
-			$this->isModified = false;
179
-		}
180
-		$this->session->close();
181
-	}
182
-
183
-	/**
184
-	 * @param mixed $offset
185
-	 * @return bool
186
-	 */
187
-	public function offsetExists($offset): bool {
188
-		return $this->exists($offset);
189
-	}
190
-
191
-	/**
192
-	 * @param mixed $offset
193
-	 * @return mixed
194
-	 */
195
-	public function offsetGet($offset) {
196
-		return $this->get($offset);
197
-	}
198
-
199
-	/**
200
-	 * @param mixed $offset
201
-	 * @param mixed $value
202
-	 */
203
-	public function offsetSet($offset, $value) {
204
-		$this->set($offset, $value);
205
-	}
206
-
207
-	/**
208
-	 * @param mixed $offset
209
-	 */
210
-	public function offsetUnset($offset) {
211
-		$this->remove($offset);
212
-	}
40
+    /** @var ISession */
41
+    protected $session;
42
+    /** @var \OCP\Security\ICrypto */
43
+    protected $crypto;
44
+    /** @var string */
45
+    protected $passphrase;
46
+    /** @var array */
47
+    protected $sessionValues;
48
+    /** @var bool */
49
+    protected $isModified = false;
50
+    CONST encryptedSessionName = 'encrypted_session_data';
51
+
52
+    /**
53
+     * @param ISession $session
54
+     * @param ICrypto $crypto
55
+     * @param string $passphrase
56
+     */
57
+    public function __construct(ISession $session,
58
+                                ICrypto $crypto,
59
+                                string $passphrase) {
60
+        $this->crypto = $crypto;
61
+        $this->session = $session;
62
+        $this->passphrase = $passphrase;
63
+        $this->initializeSession();
64
+    }
65
+
66
+    /**
67
+     * Close session if class gets destructed
68
+     */
69
+    public function __destruct() {
70
+        try {
71
+            $this->close();
72
+        } catch (SessionNotAvailableException $e){
73
+            // This exception can occur if session is already closed
74
+            // So it is safe to ignore it and let the garbage collector to proceed
75
+        }
76
+    }
77
+
78
+    protected function initializeSession() {
79
+        $encryptedSessionData = $this->session->get(self::encryptedSessionName) ?: '';
80
+        try {
81
+            $this->sessionValues = json_decode(
82
+                $this->crypto->decrypt($encryptedSessionData, $this->passphrase),
83
+                true
84
+            );
85
+        } catch (\Exception $e) {
86
+            $this->sessionValues = [];
87
+        }
88
+    }
89
+
90
+    /**
91
+     * Set a value in the session
92
+     *
93
+     * @param string $key
94
+     * @param mixed $value
95
+     */
96
+    public function set(string $key, $value) {
97
+        $this->sessionValues[$key] = $value;
98
+        $this->isModified = true;
99
+    }
100
+
101
+    /**
102
+     * Get a value from the session
103
+     *
104
+     * @param string $key
105
+     * @return string|null Either the value or null
106
+     */
107
+    public function get(string $key) {
108
+        if(isset($this->sessionValues[$key])) {
109
+            return $this->sessionValues[$key];
110
+        }
111
+
112
+        return null;
113
+    }
114
+
115
+    /**
116
+     * Check if a named key exists in the session
117
+     *
118
+     * @param string $key
119
+     * @return bool
120
+     */
121
+    public function exists(string $key): bool {
122
+        return isset($this->sessionValues[$key]);
123
+    }
124
+
125
+    /**
126
+     * Remove a $key/$value pair from the session
127
+     *
128
+     * @param string $key
129
+     */
130
+    public function remove(string $key) {
131
+        $this->isModified = true;
132
+        unset($this->sessionValues[$key]);
133
+        $this->session->remove(self::encryptedSessionName);
134
+    }
135
+
136
+    /**
137
+     * Reset and recreate the session
138
+     */
139
+    public function clear() {
140
+        $requesttoken = $this->get('requesttoken');
141
+        $this->sessionValues = [];
142
+        if ($requesttoken !== null) {
143
+            $this->set('requesttoken', $requesttoken);
144
+        }
145
+        $this->isModified = true;
146
+        $this->session->clear();
147
+    }
148
+
149
+    /**
150
+     * Wrapper around session_regenerate_id
151
+     *
152
+     * @param bool $deleteOldSession Whether to delete the old associated session file or not.
153
+     * @param bool $updateToken Wheater to update the associated auth token
154
+     * @return void
155
+     */
156
+    public function regenerateId(bool $deleteOldSession = true, bool $updateToken = false) {
157
+        $this->session->regenerateId($deleteOldSession, $updateToken);
158
+    }
159
+
160
+    /**
161
+     * Wrapper around session_id
162
+     *
163
+     * @return string
164
+     * @throws SessionNotAvailableException
165
+     * @since 9.1.0
166
+     */
167
+    public function getId(): string {
168
+        return $this->session->getId();
169
+    }
170
+
171
+    /**
172
+     * Close the session and release the lock, also writes all changed data in batch
173
+     */
174
+    public function close() {
175
+        if($this->isModified) {
176
+            $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase);
177
+            $this->session->set(self::encryptedSessionName, $encryptedValue);
178
+            $this->isModified = false;
179
+        }
180
+        $this->session->close();
181
+    }
182
+
183
+    /**
184
+     * @param mixed $offset
185
+     * @return bool
186
+     */
187
+    public function offsetExists($offset): bool {
188
+        return $this->exists($offset);
189
+    }
190
+
191
+    /**
192
+     * @param mixed $offset
193
+     * @return mixed
194
+     */
195
+    public function offsetGet($offset) {
196
+        return $this->get($offset);
197
+    }
198
+
199
+    /**
200
+     * @param mixed $offset
201
+     * @param mixed $value
202
+     */
203
+    public function offsetSet($offset, $value) {
204
+        $this->set($offset, $value);
205
+    }
206
+
207
+    /**
208
+     * @param mixed $offset
209
+     */
210
+    public function offsetUnset($offset) {
211
+        $this->remove($offset);
212
+    }
213 213
 }
Please login to merge, or discard this patch.
lib/private/Tags.php 3 patches
Doc Comments   +10 added lines, -2 removed lines patch added patch discarded remove patch
@@ -742,11 +742,19 @@  discard block
 block discarded – undo
742 742
 	}
743 743
 
744 744
 	// case-insensitive array_search
745
+
746
+	/**
747
+	 * @param string $needle
748
+	 */
745 749
 	protected function array_searchi($needle, $haystack, $mem='getName') {
746 750
 		if(!is_array($haystack)) {
747 751
 			return false;
748 752
 		}
749 753
 		return array_search(strtolower($needle), array_map(
754
+
755
+			/**
756
+			 * @param string $tag
757
+			 */
750 758
 			function($tag) use($mem) {
751 759
 				return strtolower(call_user_func(array($tag, $mem)));
752 760
 			}, $haystack)
@@ -771,7 +779,7 @@  discard block
 block discarded – undo
771 779
 	* Get a tag by its name.
772 780
 	*
773 781
 	* @param string $name The tag name.
774
-	* @return integer|bool The tag object's offset within the $this->tags
782
+	* @return \OCP\AppFramework\Db\Entity The tag object's offset within the $this->tags
775 783
 	*                      array or false if it doesn't exist.
776 784
 	*/
777 785
 	private function getTagByName($name) {
@@ -782,7 +790,7 @@  discard block
 block discarded – undo
782 790
 	* Get a tag by its ID.
783 791
 	*
784 792
 	* @param string $id The tag ID to look for.
785
-	* @return integer|bool The tag object's offset within the $this->tags
793
+	* @return \OCP\AppFramework\Db\Entity The tag object's offset within the $this->tags
786 794
 	*                      array or false if it doesn't exist.
787 795
 	*/
788 796
 	private function getTagById($id) {
Please login to merge, or discard this patch.
Indentation   +803 added lines, -803 removed lines patch added patch discarded remove patch
@@ -51,807 +51,807 @@
 block discarded – undo
51 51
 
52 52
 class Tags implements \OCP\ITags {
53 53
 
54
-	/**
55
-	 * Tags
56
-	 *
57
-	 * @var array
58
-	 */
59
-	private $tags = array();
60
-
61
-	/**
62
-	 * Used for storing objectid/categoryname pairs while rescanning.
63
-	 *
64
-	 * @var array
65
-	 */
66
-	private static $relations = array();
67
-
68
-	/**
69
-	 * Type
70
-	 *
71
-	 * @var string
72
-	 */
73
-	private $type;
74
-
75
-	/**
76
-	 * User
77
-	 *
78
-	 * @var string
79
-	 */
80
-	private $user;
81
-
82
-	/**
83
-	 * Are we including tags for shared items?
84
-	 *
85
-	 * @var bool
86
-	 */
87
-	private $includeShared = false;
88
-
89
-	/**
90
-	 * The current user, plus any owners of the items shared with the current
91
-	 * user, if $this->includeShared === true.
92
-	 *
93
-	 * @var array
94
-	 */
95
-	private $owners = array();
96
-
97
-	/**
98
-	 * The Mapper we're using to communicate our Tag objects to the database.
99
-	 *
100
-	 * @var TagMapper
101
-	 */
102
-	private $mapper;
103
-
104
-	/**
105
-	 * The sharing backend for objects of $this->type. Required if
106
-	 * $this->includeShared === true to determine ownership of items.
107
-	 *
108
-	 * @var \OCP\Share_Backend
109
-	 */
110
-	private $backend;
111
-
112
-	const TAG_TABLE = '*PREFIX*vcategory';
113
-	const RELATION_TABLE = '*PREFIX*vcategory_to_object';
114
-
115
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
116
-
117
-	/**
118
-	* Constructor.
119
-	*
120
-	* @param TagMapper $mapper Instance of the TagMapper abstraction layer.
121
-	* @param string $user The user whose data the object will operate on.
122
-	* @param string $type The type of items for which tags will be loaded.
123
-	* @param array $defaultTags Tags that should be created at construction.
124
-	* @param boolean $includeShared Whether to include tags for items shared with this user by others.
125
-	*/
126
-	public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
127
-		$this->mapper = $mapper;
128
-		$this->user = $user;
129
-		$this->type = $type;
130
-		$this->includeShared = $includeShared;
131
-		$this->owners = array($this->user);
132
-		if ($this->includeShared) {
133
-			$this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
134
-			$this->backend = \OC\Share\Share::getBackend($this->type);
135
-		}
136
-		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
137
-
138
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
139
-			$this->addMultiple($defaultTags, true);
140
-		}
141
-	}
142
-
143
-	/**
144
-	* Check if any tags are saved for this type and user.
145
-	*
146
-	* @return boolean
147
-	*/
148
-	public function isEmpty() {
149
-		return count($this->tags) === 0;
150
-	}
151
-
152
-	/**
153
-	* Returns an array mapping a given tag's properties to its values:
154
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
155
-	*
156
-	* @param string $id The ID of the tag that is going to be mapped
157
-	* @return array|false
158
-	*/
159
-	public function getTag($id) {
160
-		$key = $this->getTagById($id);
161
-		if ($key !== false) {
162
-			return $this->tagMap($this->tags[$key]);
163
-		}
164
-		return false;
165
-	}
166
-
167
-	/**
168
-	* Get the tags for a specific user.
169
-	*
170
-	* This returns an array with maps containing each tag's properties:
171
-	* [
172
-	* 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
173
-	* 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
174
-	* ]
175
-	*
176
-	* @return array
177
-	*/
178
-	public function getTags() {
179
-		if(!count($this->tags)) {
180
-			return array();
181
-		}
182
-
183
-		usort($this->tags, function($a, $b) {
184
-			return strnatcasecmp($a->getName(), $b->getName());
185
-		});
186
-		$tagMap = array();
187
-
188
-		foreach($this->tags as $tag) {
189
-			if($tag->getName() !== self::TAG_FAVORITE) {
190
-				$tagMap[] = $this->tagMap($tag);
191
-			}
192
-		}
193
-		return $tagMap;
194
-
195
-	}
196
-
197
-	/**
198
-	* Return only the tags owned by the given user, omitting any tags shared
199
-	* by other users.
200
-	*
201
-	* @param string $user The user whose tags are to be checked.
202
-	* @return array An array of Tag objects.
203
-	*/
204
-	public function getTagsForUser($user) {
205
-		return array_filter($this->tags,
206
-			function($tag) use($user) {
207
-				return $tag->getOwner() === $user;
208
-			}
209
-		);
210
-	}
211
-
212
-	/**
213
-	 * Get the list of tags for the given ids.
214
-	 *
215
-	 * @param array $objIds array of object ids
216
-	 * @return array|boolean of tags id as key to array of tag names
217
-	 * or false if an error occurred
218
-	 */
219
-	public function getTagsForObjects(array $objIds) {
220
-		$entries = array();
221
-
222
-		try {
223
-			$conn = \OC::$server->getDatabaseConnection();
224
-			$chunks = array_chunk($objIds, 900, false);
225
-			foreach ($chunks as $chunk) {
226
-				$result = $conn->executeQuery(
227
-					'SELECT `category`, `categoryid`, `objid` ' .
228
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
229
-					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230
-					array($this->user, $this->type, $chunk),
231
-					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232
-				);
233
-				while ($row = $result->fetch()) {
234
-					$objId = (int)$row['objid'];
235
-					if (!isset($entries[$objId])) {
236
-						$entries[$objId] = array();
237
-					}
238
-					$entries[$objId][] = $row['category'];
239
-				}
240
-				if ($result === null) {
241
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242
-					return false;
243
-				}
244
-			}
245
-		} catch(\Exception $e) {
246
-			\OC::$server->getLogger()->logException($e, [
247
-				'message' => __METHOD__,
248
-				'level' => ILogger::ERROR,
249
-				'app' => 'core',
250
-			]);
251
-			return false;
252
-		}
253
-
254
-		return $entries;
255
-	}
256
-
257
-	/**
258
-	* Get the a list if items tagged with $tag.
259
-	*
260
-	* Throws an exception if the tag could not be found.
261
-	*
262
-	* @param string $tag Tag id or name.
263
-	* @return array|false An array of object ids or false on error.
264
-	* @throws \Exception
265
-	*/
266
-	public function getIdsForTag($tag) {
267
-		$result = null;
268
-		$tagId = false;
269
-		if(is_numeric($tag)) {
270
-			$tagId = $tag;
271
-		} elseif(is_string($tag)) {
272
-			$tag = trim($tag);
273
-			if($tag === '') {
274
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275
-				return false;
276
-			}
277
-			$tagId = $this->getTagId($tag);
278
-		}
279
-
280
-		if($tagId === false) {
281
-			$l10n = \OC::$server->getL10N('core');
282
-			throw new \Exception(
283
-				$l10n->t('Could not find category "%s"', [$tag])
284
-			);
285
-		}
286
-
287
-		$ids = array();
288
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
289
-			. '` WHERE `categoryid` = ?';
290
-
291
-		try {
292
-			$stmt = \OC_DB::prepare($sql);
293
-			$result = $stmt->execute(array($tagId));
294
-			if ($result === null) {
295
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296
-				return false;
297
-			}
298
-		} catch(\Exception $e) {
299
-			\OC::$server->getLogger()->logException($e, [
300
-				'message' => __METHOD__,
301
-				'level' => ILogger::ERROR,
302
-				'app' => 'core',
303
-			]);
304
-			return false;
305
-		}
306
-
307
-		if(!is_null($result)) {
308
-			while( $row = $result->fetchRow()) {
309
-				$id = (int)$row['objid'];
310
-
311
-				if ($this->includeShared) {
312
-					// We have to check if we are really allowed to access the
313
-					// items that are tagged with $tag. To that end, we ask the
314
-					// corresponding sharing backend if the item identified by $id
315
-					// is owned by any of $this->owners.
316
-					foreach ($this->owners as $owner) {
317
-						if ($this->backend->isValidSource($id, $owner)) {
318
-							$ids[] = $id;
319
-							break;
320
-						}
321
-					}
322
-				} else {
323
-					$ids[] = $id;
324
-				}
325
-			}
326
-		}
327
-
328
-		return $ids;
329
-	}
330
-
331
-	/**
332
-	* Checks whether a tag is saved for the given user,
333
-	* disregarding the ones shared with him or her.
334
-	*
335
-	* @param string $name The tag name to check for.
336
-	* @param string $user The user whose tags are to be checked.
337
-	* @return bool
338
-	*/
339
-	public function userHasTag($name, $user) {
340
-		$key = $this->array_searchi($name, $this->getTagsForUser($user));
341
-		return ($key !== false) ? $this->tags[$key]->getId() : false;
342
-	}
343
-
344
-	/**
345
-	* Checks whether a tag is saved for or shared with the current user.
346
-	*
347
-	* @param string $name The tag name to check for.
348
-	* @return bool
349
-	*/
350
-	public function hasTag($name) {
351
-		return $this->getTagId($name) !== false;
352
-	}
353
-
354
-	/**
355
-	* Add a new tag.
356
-	*
357
-	* @param string $name A string with a name of the tag
358
-	* @return false|int the id of the added tag or false on error.
359
-	*/
360
-	public function add($name) {
361
-		$name = trim($name);
362
-
363
-		if($name === '') {
364
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365
-			return false;
366
-		}
367
-		if($this->userHasTag($name, $this->user)) {
368
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
369
-			return false;
370
-		}
371
-		try {
372
-			$tag = new Tag($this->user, $this->type, $name);
373
-			$tag = $this->mapper->insert($tag);
374
-			$this->tags[] = $tag;
375
-		} catch(\Exception $e) {
376
-			\OC::$server->getLogger()->logException($e, [
377
-				'message' => __METHOD__,
378
-				'level' => ILogger::ERROR,
379
-				'app' => 'core',
380
-			]);
381
-			return false;
382
-		}
383
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
384
-		return $tag->getId();
385
-	}
386
-
387
-	/**
388
-	* Rename tag.
389
-	*
390
-	* @param string|integer $from The name or ID of the existing tag
391
-	* @param string $to The new name of the tag.
392
-	* @return bool
393
-	*/
394
-	public function rename($from, $to) {
395
-		$from = trim($from);
396
-		$to = trim($to);
397
-
398
-		if($to === '' || $from === '') {
399
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400
-			return false;
401
-		}
402
-
403
-		if (is_numeric($from)) {
404
-			$key = $this->getTagById($from);
405
-		} else {
406
-			$key = $this->getTagByName($from);
407
-		}
408
-		if($key === false) {
409
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
410
-			return false;
411
-		}
412
-		$tag = $this->tags[$key];
413
-
414
-		if($this->userHasTag($to, $tag->getOwner())) {
415
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
416
-			return false;
417
-		}
418
-
419
-		try {
420
-			$tag->setName($to);
421
-			$this->tags[$key] = $this->mapper->update($tag);
422
-		} catch(\Exception $e) {
423
-			\OC::$server->getLogger()->logException($e, [
424
-				'message' => __METHOD__,
425
-				'level' => ILogger::ERROR,
426
-				'app' => 'core',
427
-			]);
428
-			return false;
429
-		}
430
-		return true;
431
-	}
432
-
433
-	/**
434
-	* Add a list of new tags.
435
-	*
436
-	* @param string[] $names A string with a name or an array of strings containing
437
-	* the name(s) of the tag(s) to add.
438
-	* @param bool $sync When true, save the tags
439
-	* @param int|null $id int Optional object id to add to this|these tag(s)
440
-	* @return bool Returns false on error.
441
-	*/
442
-	public function addMultiple($names, $sync=false, $id = null) {
443
-		if(!is_array($names)) {
444
-			$names = array($names);
445
-		}
446
-		$names = array_map('trim', $names);
447
-		array_filter($names);
448
-
449
-		$newones = array();
450
-		foreach($names as $name) {
451
-			if(!$this->hasTag($name) && $name !== '') {
452
-				$newones[] = new Tag($this->user, $this->type, $name);
453
-			}
454
-			if(!is_null($id) ) {
455
-				// Insert $objectid, $categoryid  pairs if not exist.
456
-				self::$relations[] = array('objid' => $id, 'tag' => $name);
457
-			}
458
-		}
459
-		$this->tags = array_merge($this->tags, $newones);
460
-		if($sync === true) {
461
-			$this->save();
462
-		}
463
-
464
-		return true;
465
-	}
466
-
467
-	/**
468
-	 * Save the list of tags and their object relations
469
-	 */
470
-	protected function save() {
471
-		if(is_array($this->tags)) {
472
-			foreach($this->tags as $tag) {
473
-				try {
474
-					if (!$this->mapper->tagExists($tag)) {
475
-						$this->mapper->insert($tag);
476
-					}
477
-				} catch(\Exception $e) {
478
-					\OC::$server->getLogger()->logException($e, [
479
-						'message' => __METHOD__,
480
-						'level' => ILogger::ERROR,
481
-						'app' => 'core',
482
-					]);
483
-				}
484
-			}
485
-
486
-			// reload tags to get the proper ids.
487
-			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
489
-				ILogger::DEBUG);
490
-			// Loop through temporarily cached objectid/tagname pairs
491
-			// and save relations.
492
-			$tags = $this->tags;
493
-			// For some reason this is needed or array_search(i) will return 0..?
494
-			ksort($tags);
495
-			$dbConnection = \OC::$server->getDatabaseConnection();
496
-			foreach(self::$relations as $relation) {
497
-				$tagId = $this->getTagId($relation['tag']);
498
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
-				if($tagId) {
500
-					try {
501
-						$dbConnection->insertIfNotExist(self::RELATION_TABLE,
502
-							array(
503
-								'objid' => $relation['objid'],
504
-								'categoryid' => $tagId,
505
-								'type' => $this->type,
506
-								));
507
-					} catch(\Exception $e) {
508
-						\OC::$server->getLogger()->logException($e, [
509
-							'message' => __METHOD__,
510
-							'level' => ILogger::ERROR,
511
-							'app' => 'core',
512
-						]);
513
-					}
514
-				}
515
-			}
516
-			self::$relations = array(); // reset
517
-		} else {
518
-			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
519
-				. print_r($this->tags, true), ILogger::ERROR);
520
-		}
521
-	}
522
-
523
-	/**
524
-	* Delete tags and tag/object relations for a user.
525
-	*
526
-	* For hooking up on post_deleteUser
527
-	*
528
-	* @param array $arguments
529
-	*/
530
-	public static function post_deleteUser($arguments) {
531
-		// Find all objectid/tagId pairs.
532
-		$result = null;
533
-		try {
534
-			$stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
535
-				. 'WHERE `uid` = ?');
536
-			$result = $stmt->execute(array($arguments['uid']));
537
-			if ($result === null) {
538
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539
-			}
540
-		} catch(\Exception $e) {
541
-			\OC::$server->getLogger()->logException($e, [
542
-				'message' => __METHOD__,
543
-				'level' => ILogger::ERROR,
544
-				'app' => 'core',
545
-			]);
546
-		}
547
-
548
-		if(!is_null($result)) {
549
-			try {
550
-				$stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
551
-					. 'WHERE `categoryid` = ?');
552
-				while( $row = $result->fetchRow()) {
553
-					try {
554
-						$stmt->execute(array($row['id']));
555
-					} catch(\Exception $e) {
556
-						\OC::$server->getLogger()->logException($e, [
557
-							'message' => __METHOD__,
558
-							'level' => ILogger::ERROR,
559
-							'app' => 'core',
560
-						]);
561
-					}
562
-				}
563
-			} catch(\Exception $e) {
564
-				\OC::$server->getLogger()->logException($e, [
565
-					'message' => __METHOD__,
566
-					'level' => ILogger::ERROR,
567
-					'app' => 'core',
568
-				]);
569
-			}
570
-		}
571
-		try {
572
-			$stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
573
-				. 'WHERE `uid` = ?');
574
-			$result = $stmt->execute(array($arguments['uid']));
575
-			if ($result === null) {
576
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577
-			}
578
-		} catch(\Exception $e) {
579
-			\OC::$server->getLogger()->logException($e, [
580
-				'message' => __METHOD__,
581
-				'level' => ILogger::ERROR,
582
-				'app' => 'core',
583
-			]);
584
-		}
585
-	}
586
-
587
-	/**
588
-	* Delete tag/object relations from the db
589
-	*
590
-	* @param array $ids The ids of the objects
591
-	* @return boolean Returns false on error.
592
-	*/
593
-	public function purgeObjects(array $ids) {
594
-		if(count($ids) === 0) {
595
-			// job done ;)
596
-			return true;
597
-		}
598
-		$updates = $ids;
599
-		try {
600
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
602
-			$query .= 'AND `type`= ?';
603
-			$updates[] = $this->type;
604
-			$stmt = \OC_DB::prepare($query);
605
-			$result = $stmt->execute($updates);
606
-			if ($result === null) {
607
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608
-				return false;
609
-			}
610
-		} catch(\Exception $e) {
611
-			\OC::$server->getLogger()->logException($e, [
612
-				'message' => __METHOD__,
613
-				'level' => ILogger::ERROR,
614
-				'app' => 'core',
615
-			]);
616
-			return false;
617
-		}
618
-		return true;
619
-	}
620
-
621
-	/**
622
-	* Get favorites for an object type
623
-	*
624
-	* @return array|false An array of object ids.
625
-	*/
626
-	public function getFavorites() {
627
-		try {
628
-			return $this->getIdsForTag(self::TAG_FAVORITE);
629
-		} catch(\Exception $e) {
630
-			\OC::$server->getLogger()->logException($e, [
631
-				'message' => __METHOD__,
632
-				'level' => ILogger::ERROR,
633
-				'app' => 'core',
634
-			]);
635
-			return array();
636
-		}
637
-	}
638
-
639
-	/**
640
-	* Add an object to favorites
641
-	*
642
-	* @param int $objid The id of the object
643
-	* @return boolean
644
-	*/
645
-	public function addToFavorites($objid) {
646
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647
-			$this->add(self::TAG_FAVORITE);
648
-		}
649
-		return $this->tagAs($objid, self::TAG_FAVORITE);
650
-	}
651
-
652
-	/**
653
-	* Remove an object from favorites
654
-	*
655
-	* @param int $objid The id of the object
656
-	* @return boolean
657
-	*/
658
-	public function removeFromFavorites($objid) {
659
-		return $this->unTag($objid, self::TAG_FAVORITE);
660
-	}
661
-
662
-	/**
663
-	* Creates a tag/object relation.
664
-	*
665
-	* @param int $objid The id of the object
666
-	* @param string $tag The id or name of the tag
667
-	* @return boolean Returns false on error.
668
-	*/
669
-	public function tagAs($objid, $tag) {
670
-		if(is_string($tag) && !is_numeric($tag)) {
671
-			$tag = trim($tag);
672
-			if($tag === '') {
673
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674
-				return false;
675
-			}
676
-			if(!$this->hasTag($tag)) {
677
-				$this->add($tag);
678
-			}
679
-			$tagId =  $this->getTagId($tag);
680
-		} else {
681
-			$tagId = $tag;
682
-		}
683
-		try {
684
-			\OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE,
685
-				array(
686
-					'objid' => $objid,
687
-					'categoryid' => $tagId,
688
-					'type' => $this->type,
689
-				));
690
-		} catch(\Exception $e) {
691
-			\OC::$server->getLogger()->logException($e, [
692
-				'message' => __METHOD__,
693
-				'level' => ILogger::ERROR,
694
-				'app' => 'core',
695
-			]);
696
-			return false;
697
-		}
698
-		return true;
699
-	}
700
-
701
-	/**
702
-	* Delete single tag/object relation from the db
703
-	*
704
-	* @param int $objid The id of the object
705
-	* @param string $tag The id or name of the tag
706
-	* @return boolean
707
-	*/
708
-	public function unTag($objid, $tag) {
709
-		if(is_string($tag) && !is_numeric($tag)) {
710
-			$tag = trim($tag);
711
-			if($tag === '') {
712
-				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713
-				return false;
714
-			}
715
-			$tagId =  $this->getTagId($tag);
716
-		} else {
717
-			$tagId = $tag;
718
-		}
719
-
720
-		try {
721
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
722
-					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723
-			$stmt = \OC_DB::prepare($sql);
724
-			$stmt->execute(array($objid, $tagId, $this->type));
725
-		} catch(\Exception $e) {
726
-			\OC::$server->getLogger()->logException($e, [
727
-				'message' => __METHOD__,
728
-				'level' => ILogger::ERROR,
729
-				'app' => 'core',
730
-			]);
731
-			return false;
732
-		}
733
-		return true;
734
-	}
735
-
736
-	/**
737
-	* Delete tags from the database.
738
-	*
739
-	* @param string[]|integer[] $names An array of tags (names or IDs) to delete
740
-	* @return bool Returns false on error
741
-	*/
742
-	public function delete($names) {
743
-		if(!is_array($names)) {
744
-			$names = array($names);
745
-		}
746
-
747
-		$names = array_map('trim', $names);
748
-		array_filter($names);
749
-
750
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
751
-			. print_r($this->tags, true), ILogger::DEBUG);
752
-		foreach($names as $name) {
753
-			$id = null;
754
-
755
-			if (is_numeric($name)) {
756
-				$key = $this->getTagById($name);
757
-			} else {
758
-				$key = $this->getTagByName($name);
759
-			}
760
-			if ($key !== false) {
761
-				$tag = $this->tags[$key];
762
-				$id = $tag->getId();
763
-				unset($this->tags[$key]);
764
-				$this->mapper->delete($tag);
765
-			} else {
766
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
767
-					. ': not found.', ILogger::ERROR);
768
-			}
769
-			if(!is_null($id) && $id !== false) {
770
-				try {
771
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
772
-							. 'WHERE `categoryid` = ?';
773
-					$stmt = \OC_DB::prepare($sql);
774
-					$result = $stmt->execute(array($id));
775
-					if ($result === null) {
776
-						\OCP\Util::writeLog('core',
777
-							__METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
778
-							ILogger::ERROR);
779
-						return false;
780
-					}
781
-				} catch(\Exception $e) {
782
-					\OC::$server->getLogger()->logException($e, [
783
-						'message' => __METHOD__,
784
-						'level' => ILogger::ERROR,
785
-						'app' => 'core',
786
-					]);
787
-					return false;
788
-				}
789
-			}
790
-		}
791
-		return true;
792
-	}
793
-
794
-	// case-insensitive array_search
795
-	protected function array_searchi($needle, $haystack, $mem='getName') {
796
-		if(!is_array($haystack)) {
797
-			return false;
798
-		}
799
-		return array_search(strtolower($needle), array_map(
800
-			function($tag) use($mem) {
801
-				return strtolower(call_user_func(array($tag, $mem)));
802
-			}, $haystack)
803
-		);
804
-	}
805
-
806
-	/**
807
-	* Get a tag's ID.
808
-	*
809
-	* @param string $name The tag name to look for.
810
-	* @return string|bool The tag's id or false if no matching tag is found.
811
-	*/
812
-	private function getTagId($name) {
813
-		$key = $this->array_searchi($name, $this->tags);
814
-		if ($key !== false) {
815
-			return $this->tags[$key]->getId();
816
-		}
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	* Get a tag by its name.
822
-	*
823
-	* @param string $name The tag name.
824
-	* @return integer|bool The tag object's offset within the $this->tags
825
-	*                      array or false if it doesn't exist.
826
-	*/
827
-	private function getTagByName($name) {
828
-		return $this->array_searchi($name, $this->tags, 'getName');
829
-	}
830
-
831
-	/**
832
-	* Get a tag by its ID.
833
-	*
834
-	* @param string $id The tag ID to look for.
835
-	* @return integer|bool The tag object's offset within the $this->tags
836
-	*                      array or false if it doesn't exist.
837
-	*/
838
-	private function getTagById($id) {
839
-		return $this->array_searchi($id, $this->tags, 'getId');
840
-	}
841
-
842
-	/**
843
-	* Returns an array mapping a given tag's properties to its values:
844
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
845
-	*
846
-	* @param Tag $tag The tag that is going to be mapped
847
-	* @return array
848
-	*/
849
-	private function tagMap(Tag $tag) {
850
-		return array(
851
-			'id'    => $tag->getId(),
852
-			'name'  => $tag->getName(),
853
-			'owner' => $tag->getOwner(),
854
-			'type'  => $tag->getType()
855
-		);
856
-	}
54
+    /**
55
+     * Tags
56
+     *
57
+     * @var array
58
+     */
59
+    private $tags = array();
60
+
61
+    /**
62
+     * Used for storing objectid/categoryname pairs while rescanning.
63
+     *
64
+     * @var array
65
+     */
66
+    private static $relations = array();
67
+
68
+    /**
69
+     * Type
70
+     *
71
+     * @var string
72
+     */
73
+    private $type;
74
+
75
+    /**
76
+     * User
77
+     *
78
+     * @var string
79
+     */
80
+    private $user;
81
+
82
+    /**
83
+     * Are we including tags for shared items?
84
+     *
85
+     * @var bool
86
+     */
87
+    private $includeShared = false;
88
+
89
+    /**
90
+     * The current user, plus any owners of the items shared with the current
91
+     * user, if $this->includeShared === true.
92
+     *
93
+     * @var array
94
+     */
95
+    private $owners = array();
96
+
97
+    /**
98
+     * The Mapper we're using to communicate our Tag objects to the database.
99
+     *
100
+     * @var TagMapper
101
+     */
102
+    private $mapper;
103
+
104
+    /**
105
+     * The sharing backend for objects of $this->type. Required if
106
+     * $this->includeShared === true to determine ownership of items.
107
+     *
108
+     * @var \OCP\Share_Backend
109
+     */
110
+    private $backend;
111
+
112
+    const TAG_TABLE = '*PREFIX*vcategory';
113
+    const RELATION_TABLE = '*PREFIX*vcategory_to_object';
114
+
115
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
116
+
117
+    /**
118
+     * Constructor.
119
+     *
120
+     * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
121
+     * @param string $user The user whose data the object will operate on.
122
+     * @param string $type The type of items for which tags will be loaded.
123
+     * @param array $defaultTags Tags that should be created at construction.
124
+     * @param boolean $includeShared Whether to include tags for items shared with this user by others.
125
+     */
126
+    public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
127
+        $this->mapper = $mapper;
128
+        $this->user = $user;
129
+        $this->type = $type;
130
+        $this->includeShared = $includeShared;
131
+        $this->owners = array($this->user);
132
+        if ($this->includeShared) {
133
+            $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
134
+            $this->backend = \OC\Share\Share::getBackend($this->type);
135
+        }
136
+        $this->tags = $this->mapper->loadTags($this->owners, $this->type);
137
+
138
+        if(count($defaultTags) > 0 && count($this->tags) === 0) {
139
+            $this->addMultiple($defaultTags, true);
140
+        }
141
+    }
142
+
143
+    /**
144
+     * Check if any tags are saved for this type and user.
145
+     *
146
+     * @return boolean
147
+     */
148
+    public function isEmpty() {
149
+        return count($this->tags) === 0;
150
+    }
151
+
152
+    /**
153
+     * Returns an array mapping a given tag's properties to its values:
154
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
155
+     *
156
+     * @param string $id The ID of the tag that is going to be mapped
157
+     * @return array|false
158
+     */
159
+    public function getTag($id) {
160
+        $key = $this->getTagById($id);
161
+        if ($key !== false) {
162
+            return $this->tagMap($this->tags[$key]);
163
+        }
164
+        return false;
165
+    }
166
+
167
+    /**
168
+     * Get the tags for a specific user.
169
+     *
170
+     * This returns an array with maps containing each tag's properties:
171
+     * [
172
+     * 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
173
+     * 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
174
+     * ]
175
+     *
176
+     * @return array
177
+     */
178
+    public function getTags() {
179
+        if(!count($this->tags)) {
180
+            return array();
181
+        }
182
+
183
+        usort($this->tags, function($a, $b) {
184
+            return strnatcasecmp($a->getName(), $b->getName());
185
+        });
186
+        $tagMap = array();
187
+
188
+        foreach($this->tags as $tag) {
189
+            if($tag->getName() !== self::TAG_FAVORITE) {
190
+                $tagMap[] = $this->tagMap($tag);
191
+            }
192
+        }
193
+        return $tagMap;
194
+
195
+    }
196
+
197
+    /**
198
+     * Return only the tags owned by the given user, omitting any tags shared
199
+     * by other users.
200
+     *
201
+     * @param string $user The user whose tags are to be checked.
202
+     * @return array An array of Tag objects.
203
+     */
204
+    public function getTagsForUser($user) {
205
+        return array_filter($this->tags,
206
+            function($tag) use($user) {
207
+                return $tag->getOwner() === $user;
208
+            }
209
+        );
210
+    }
211
+
212
+    /**
213
+     * Get the list of tags for the given ids.
214
+     *
215
+     * @param array $objIds array of object ids
216
+     * @return array|boolean of tags id as key to array of tag names
217
+     * or false if an error occurred
218
+     */
219
+    public function getTagsForObjects(array $objIds) {
220
+        $entries = array();
221
+
222
+        try {
223
+            $conn = \OC::$server->getDatabaseConnection();
224
+            $chunks = array_chunk($objIds, 900, false);
225
+            foreach ($chunks as $chunk) {
226
+                $result = $conn->executeQuery(
227
+                    'SELECT `category`, `categoryid`, `objid` ' .
228
+                    'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
229
+                    'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230
+                    array($this->user, $this->type, $chunk),
231
+                    array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232
+                );
233
+                while ($row = $result->fetch()) {
234
+                    $objId = (int)$row['objid'];
235
+                    if (!isset($entries[$objId])) {
236
+                        $entries[$objId] = array();
237
+                    }
238
+                    $entries[$objId][] = $row['category'];
239
+                }
240
+                if ($result === null) {
241
+                    \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242
+                    return false;
243
+                }
244
+            }
245
+        } catch(\Exception $e) {
246
+            \OC::$server->getLogger()->logException($e, [
247
+                'message' => __METHOD__,
248
+                'level' => ILogger::ERROR,
249
+                'app' => 'core',
250
+            ]);
251
+            return false;
252
+        }
253
+
254
+        return $entries;
255
+    }
256
+
257
+    /**
258
+     * Get the a list if items tagged with $tag.
259
+     *
260
+     * Throws an exception if the tag could not be found.
261
+     *
262
+     * @param string $tag Tag id or name.
263
+     * @return array|false An array of object ids or false on error.
264
+     * @throws \Exception
265
+     */
266
+    public function getIdsForTag($tag) {
267
+        $result = null;
268
+        $tagId = false;
269
+        if(is_numeric($tag)) {
270
+            $tagId = $tag;
271
+        } elseif(is_string($tag)) {
272
+            $tag = trim($tag);
273
+            if($tag === '') {
274
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275
+                return false;
276
+            }
277
+            $tagId = $this->getTagId($tag);
278
+        }
279
+
280
+        if($tagId === false) {
281
+            $l10n = \OC::$server->getL10N('core');
282
+            throw new \Exception(
283
+                $l10n->t('Could not find category "%s"', [$tag])
284
+            );
285
+        }
286
+
287
+        $ids = array();
288
+        $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
289
+            . '` WHERE `categoryid` = ?';
290
+
291
+        try {
292
+            $stmt = \OC_DB::prepare($sql);
293
+            $result = $stmt->execute(array($tagId));
294
+            if ($result === null) {
295
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296
+                return false;
297
+            }
298
+        } catch(\Exception $e) {
299
+            \OC::$server->getLogger()->logException($e, [
300
+                'message' => __METHOD__,
301
+                'level' => ILogger::ERROR,
302
+                'app' => 'core',
303
+            ]);
304
+            return false;
305
+        }
306
+
307
+        if(!is_null($result)) {
308
+            while( $row = $result->fetchRow()) {
309
+                $id = (int)$row['objid'];
310
+
311
+                if ($this->includeShared) {
312
+                    // We have to check if we are really allowed to access the
313
+                    // items that are tagged with $tag. To that end, we ask the
314
+                    // corresponding sharing backend if the item identified by $id
315
+                    // is owned by any of $this->owners.
316
+                    foreach ($this->owners as $owner) {
317
+                        if ($this->backend->isValidSource($id, $owner)) {
318
+                            $ids[] = $id;
319
+                            break;
320
+                        }
321
+                    }
322
+                } else {
323
+                    $ids[] = $id;
324
+                }
325
+            }
326
+        }
327
+
328
+        return $ids;
329
+    }
330
+
331
+    /**
332
+     * Checks whether a tag is saved for the given user,
333
+     * disregarding the ones shared with him or her.
334
+     *
335
+     * @param string $name The tag name to check for.
336
+     * @param string $user The user whose tags are to be checked.
337
+     * @return bool
338
+     */
339
+    public function userHasTag($name, $user) {
340
+        $key = $this->array_searchi($name, $this->getTagsForUser($user));
341
+        return ($key !== false) ? $this->tags[$key]->getId() : false;
342
+    }
343
+
344
+    /**
345
+     * Checks whether a tag is saved for or shared with the current user.
346
+     *
347
+     * @param string $name The tag name to check for.
348
+     * @return bool
349
+     */
350
+    public function hasTag($name) {
351
+        return $this->getTagId($name) !== false;
352
+    }
353
+
354
+    /**
355
+     * Add a new tag.
356
+     *
357
+     * @param string $name A string with a name of the tag
358
+     * @return false|int the id of the added tag or false on error.
359
+     */
360
+    public function add($name) {
361
+        $name = trim($name);
362
+
363
+        if($name === '') {
364
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365
+            return false;
366
+        }
367
+        if($this->userHasTag($name, $this->user)) {
368
+            \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
369
+            return false;
370
+        }
371
+        try {
372
+            $tag = new Tag($this->user, $this->type, $name);
373
+            $tag = $this->mapper->insert($tag);
374
+            $this->tags[] = $tag;
375
+        } catch(\Exception $e) {
376
+            \OC::$server->getLogger()->logException($e, [
377
+                'message' => __METHOD__,
378
+                'level' => ILogger::ERROR,
379
+                'app' => 'core',
380
+            ]);
381
+            return false;
382
+        }
383
+        \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
384
+        return $tag->getId();
385
+    }
386
+
387
+    /**
388
+     * Rename tag.
389
+     *
390
+     * @param string|integer $from The name or ID of the existing tag
391
+     * @param string $to The new name of the tag.
392
+     * @return bool
393
+     */
394
+    public function rename($from, $to) {
395
+        $from = trim($from);
396
+        $to = trim($to);
397
+
398
+        if($to === '' || $from === '') {
399
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400
+            return false;
401
+        }
402
+
403
+        if (is_numeric($from)) {
404
+            $key = $this->getTagById($from);
405
+        } else {
406
+            $key = $this->getTagByName($from);
407
+        }
408
+        if($key === false) {
409
+            \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
410
+            return false;
411
+        }
412
+        $tag = $this->tags[$key];
413
+
414
+        if($this->userHasTag($to, $tag->getOwner())) {
415
+            \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
416
+            return false;
417
+        }
418
+
419
+        try {
420
+            $tag->setName($to);
421
+            $this->tags[$key] = $this->mapper->update($tag);
422
+        } catch(\Exception $e) {
423
+            \OC::$server->getLogger()->logException($e, [
424
+                'message' => __METHOD__,
425
+                'level' => ILogger::ERROR,
426
+                'app' => 'core',
427
+            ]);
428
+            return false;
429
+        }
430
+        return true;
431
+    }
432
+
433
+    /**
434
+     * Add a list of new tags.
435
+     *
436
+     * @param string[] $names A string with a name or an array of strings containing
437
+     * the name(s) of the tag(s) to add.
438
+     * @param bool $sync When true, save the tags
439
+     * @param int|null $id int Optional object id to add to this|these tag(s)
440
+     * @return bool Returns false on error.
441
+     */
442
+    public function addMultiple($names, $sync=false, $id = null) {
443
+        if(!is_array($names)) {
444
+            $names = array($names);
445
+        }
446
+        $names = array_map('trim', $names);
447
+        array_filter($names);
448
+
449
+        $newones = array();
450
+        foreach($names as $name) {
451
+            if(!$this->hasTag($name) && $name !== '') {
452
+                $newones[] = new Tag($this->user, $this->type, $name);
453
+            }
454
+            if(!is_null($id) ) {
455
+                // Insert $objectid, $categoryid  pairs if not exist.
456
+                self::$relations[] = array('objid' => $id, 'tag' => $name);
457
+            }
458
+        }
459
+        $this->tags = array_merge($this->tags, $newones);
460
+        if($sync === true) {
461
+            $this->save();
462
+        }
463
+
464
+        return true;
465
+    }
466
+
467
+    /**
468
+     * Save the list of tags and their object relations
469
+     */
470
+    protected function save() {
471
+        if(is_array($this->tags)) {
472
+            foreach($this->tags as $tag) {
473
+                try {
474
+                    if (!$this->mapper->tagExists($tag)) {
475
+                        $this->mapper->insert($tag);
476
+                    }
477
+                } catch(\Exception $e) {
478
+                    \OC::$server->getLogger()->logException($e, [
479
+                        'message' => __METHOD__,
480
+                        'level' => ILogger::ERROR,
481
+                        'app' => 'core',
482
+                    ]);
483
+                }
484
+            }
485
+
486
+            // reload tags to get the proper ids.
487
+            $this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
+            \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
489
+                ILogger::DEBUG);
490
+            // Loop through temporarily cached objectid/tagname pairs
491
+            // and save relations.
492
+            $tags = $this->tags;
493
+            // For some reason this is needed or array_search(i) will return 0..?
494
+            ksort($tags);
495
+            $dbConnection = \OC::$server->getDatabaseConnection();
496
+            foreach(self::$relations as $relation) {
497
+                $tagId = $this->getTagId($relation['tag']);
498
+                \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
+                if($tagId) {
500
+                    try {
501
+                        $dbConnection->insertIfNotExist(self::RELATION_TABLE,
502
+                            array(
503
+                                'objid' => $relation['objid'],
504
+                                'categoryid' => $tagId,
505
+                                'type' => $this->type,
506
+                                ));
507
+                    } catch(\Exception $e) {
508
+                        \OC::$server->getLogger()->logException($e, [
509
+                            'message' => __METHOD__,
510
+                            'level' => ILogger::ERROR,
511
+                            'app' => 'core',
512
+                        ]);
513
+                    }
514
+                }
515
+            }
516
+            self::$relations = array(); // reset
517
+        } else {
518
+            \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
519
+                . print_r($this->tags, true), ILogger::ERROR);
520
+        }
521
+    }
522
+
523
+    /**
524
+     * Delete tags and tag/object relations for a user.
525
+     *
526
+     * For hooking up on post_deleteUser
527
+     *
528
+     * @param array $arguments
529
+     */
530
+    public static function post_deleteUser($arguments) {
531
+        // Find all objectid/tagId pairs.
532
+        $result = null;
533
+        try {
534
+            $stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
535
+                . 'WHERE `uid` = ?');
536
+            $result = $stmt->execute(array($arguments['uid']));
537
+            if ($result === null) {
538
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539
+            }
540
+        } catch(\Exception $e) {
541
+            \OC::$server->getLogger()->logException($e, [
542
+                'message' => __METHOD__,
543
+                'level' => ILogger::ERROR,
544
+                'app' => 'core',
545
+            ]);
546
+        }
547
+
548
+        if(!is_null($result)) {
549
+            try {
550
+                $stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
551
+                    . 'WHERE `categoryid` = ?');
552
+                while( $row = $result->fetchRow()) {
553
+                    try {
554
+                        $stmt->execute(array($row['id']));
555
+                    } catch(\Exception $e) {
556
+                        \OC::$server->getLogger()->logException($e, [
557
+                            'message' => __METHOD__,
558
+                            'level' => ILogger::ERROR,
559
+                            'app' => 'core',
560
+                        ]);
561
+                    }
562
+                }
563
+            } catch(\Exception $e) {
564
+                \OC::$server->getLogger()->logException($e, [
565
+                    'message' => __METHOD__,
566
+                    'level' => ILogger::ERROR,
567
+                    'app' => 'core',
568
+                ]);
569
+            }
570
+        }
571
+        try {
572
+            $stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
573
+                . 'WHERE `uid` = ?');
574
+            $result = $stmt->execute(array($arguments['uid']));
575
+            if ($result === null) {
576
+                \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577
+            }
578
+        } catch(\Exception $e) {
579
+            \OC::$server->getLogger()->logException($e, [
580
+                'message' => __METHOD__,
581
+                'level' => ILogger::ERROR,
582
+                'app' => 'core',
583
+            ]);
584
+        }
585
+    }
586
+
587
+    /**
588
+     * Delete tag/object relations from the db
589
+     *
590
+     * @param array $ids The ids of the objects
591
+     * @return boolean Returns false on error.
592
+     */
593
+    public function purgeObjects(array $ids) {
594
+        if(count($ids) === 0) {
595
+            // job done ;)
596
+            return true;
597
+        }
598
+        $updates = $ids;
599
+        try {
600
+            $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
+            $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
602
+            $query .= 'AND `type`= ?';
603
+            $updates[] = $this->type;
604
+            $stmt = \OC_DB::prepare($query);
605
+            $result = $stmt->execute($updates);
606
+            if ($result === null) {
607
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608
+                return false;
609
+            }
610
+        } catch(\Exception $e) {
611
+            \OC::$server->getLogger()->logException($e, [
612
+                'message' => __METHOD__,
613
+                'level' => ILogger::ERROR,
614
+                'app' => 'core',
615
+            ]);
616
+            return false;
617
+        }
618
+        return true;
619
+    }
620
+
621
+    /**
622
+     * Get favorites for an object type
623
+     *
624
+     * @return array|false An array of object ids.
625
+     */
626
+    public function getFavorites() {
627
+        try {
628
+            return $this->getIdsForTag(self::TAG_FAVORITE);
629
+        } catch(\Exception $e) {
630
+            \OC::$server->getLogger()->logException($e, [
631
+                'message' => __METHOD__,
632
+                'level' => ILogger::ERROR,
633
+                'app' => 'core',
634
+            ]);
635
+            return array();
636
+        }
637
+    }
638
+
639
+    /**
640
+     * Add an object to favorites
641
+     *
642
+     * @param int $objid The id of the object
643
+     * @return boolean
644
+     */
645
+    public function addToFavorites($objid) {
646
+        if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647
+            $this->add(self::TAG_FAVORITE);
648
+        }
649
+        return $this->tagAs($objid, self::TAG_FAVORITE);
650
+    }
651
+
652
+    /**
653
+     * Remove an object from favorites
654
+     *
655
+     * @param int $objid The id of the object
656
+     * @return boolean
657
+     */
658
+    public function removeFromFavorites($objid) {
659
+        return $this->unTag($objid, self::TAG_FAVORITE);
660
+    }
661
+
662
+    /**
663
+     * Creates a tag/object relation.
664
+     *
665
+     * @param int $objid The id of the object
666
+     * @param string $tag The id or name of the tag
667
+     * @return boolean Returns false on error.
668
+     */
669
+    public function tagAs($objid, $tag) {
670
+        if(is_string($tag) && !is_numeric($tag)) {
671
+            $tag = trim($tag);
672
+            if($tag === '') {
673
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674
+                return false;
675
+            }
676
+            if(!$this->hasTag($tag)) {
677
+                $this->add($tag);
678
+            }
679
+            $tagId =  $this->getTagId($tag);
680
+        } else {
681
+            $tagId = $tag;
682
+        }
683
+        try {
684
+            \OC::$server->getDatabaseConnection()->insertIfNotExist(self::RELATION_TABLE,
685
+                array(
686
+                    'objid' => $objid,
687
+                    'categoryid' => $tagId,
688
+                    'type' => $this->type,
689
+                ));
690
+        } catch(\Exception $e) {
691
+            \OC::$server->getLogger()->logException($e, [
692
+                'message' => __METHOD__,
693
+                'level' => ILogger::ERROR,
694
+                'app' => 'core',
695
+            ]);
696
+            return false;
697
+        }
698
+        return true;
699
+    }
700
+
701
+    /**
702
+     * Delete single tag/object relation from the db
703
+     *
704
+     * @param int $objid The id of the object
705
+     * @param string $tag The id or name of the tag
706
+     * @return boolean
707
+     */
708
+    public function unTag($objid, $tag) {
709
+        if(is_string($tag) && !is_numeric($tag)) {
710
+            $tag = trim($tag);
711
+            if($tag === '') {
712
+                \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713
+                return false;
714
+            }
715
+            $tagId =  $this->getTagId($tag);
716
+        } else {
717
+            $tagId = $tag;
718
+        }
719
+
720
+        try {
721
+            $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
722
+                    . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723
+            $stmt = \OC_DB::prepare($sql);
724
+            $stmt->execute(array($objid, $tagId, $this->type));
725
+        } catch(\Exception $e) {
726
+            \OC::$server->getLogger()->logException($e, [
727
+                'message' => __METHOD__,
728
+                'level' => ILogger::ERROR,
729
+                'app' => 'core',
730
+            ]);
731
+            return false;
732
+        }
733
+        return true;
734
+    }
735
+
736
+    /**
737
+     * Delete tags from the database.
738
+     *
739
+     * @param string[]|integer[] $names An array of tags (names or IDs) to delete
740
+     * @return bool Returns false on error
741
+     */
742
+    public function delete($names) {
743
+        if(!is_array($names)) {
744
+            $names = array($names);
745
+        }
746
+
747
+        $names = array_map('trim', $names);
748
+        array_filter($names);
749
+
750
+        \OCP\Util::writeLog('core', __METHOD__ . ', before: '
751
+            . print_r($this->tags, true), ILogger::DEBUG);
752
+        foreach($names as $name) {
753
+            $id = null;
754
+
755
+            if (is_numeric($name)) {
756
+                $key = $this->getTagById($name);
757
+            } else {
758
+                $key = $this->getTagByName($name);
759
+            }
760
+            if ($key !== false) {
761
+                $tag = $this->tags[$key];
762
+                $id = $tag->getId();
763
+                unset($this->tags[$key]);
764
+                $this->mapper->delete($tag);
765
+            } else {
766
+                \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
767
+                    . ': not found.', ILogger::ERROR);
768
+            }
769
+            if(!is_null($id) && $id !== false) {
770
+                try {
771
+                    $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
772
+                            . 'WHERE `categoryid` = ?';
773
+                    $stmt = \OC_DB::prepare($sql);
774
+                    $result = $stmt->execute(array($id));
775
+                    if ($result === null) {
776
+                        \OCP\Util::writeLog('core',
777
+                            __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
778
+                            ILogger::ERROR);
779
+                        return false;
780
+                    }
781
+                } catch(\Exception $e) {
782
+                    \OC::$server->getLogger()->logException($e, [
783
+                        'message' => __METHOD__,
784
+                        'level' => ILogger::ERROR,
785
+                        'app' => 'core',
786
+                    ]);
787
+                    return false;
788
+                }
789
+            }
790
+        }
791
+        return true;
792
+    }
793
+
794
+    // case-insensitive array_search
795
+    protected function array_searchi($needle, $haystack, $mem='getName') {
796
+        if(!is_array($haystack)) {
797
+            return false;
798
+        }
799
+        return array_search(strtolower($needle), array_map(
800
+            function($tag) use($mem) {
801
+                return strtolower(call_user_func(array($tag, $mem)));
802
+            }, $haystack)
803
+        );
804
+    }
805
+
806
+    /**
807
+     * Get a tag's ID.
808
+     *
809
+     * @param string $name The tag name to look for.
810
+     * @return string|bool The tag's id or false if no matching tag is found.
811
+     */
812
+    private function getTagId($name) {
813
+        $key = $this->array_searchi($name, $this->tags);
814
+        if ($key !== false) {
815
+            return $this->tags[$key]->getId();
816
+        }
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Get a tag by its name.
822
+     *
823
+     * @param string $name The tag name.
824
+     * @return integer|bool The tag object's offset within the $this->tags
825
+     *                      array or false if it doesn't exist.
826
+     */
827
+    private function getTagByName($name) {
828
+        return $this->array_searchi($name, $this->tags, 'getName');
829
+    }
830
+
831
+    /**
832
+     * Get a tag by its ID.
833
+     *
834
+     * @param string $id The tag ID to look for.
835
+     * @return integer|bool The tag object's offset within the $this->tags
836
+     *                      array or false if it doesn't exist.
837
+     */
838
+    private function getTagById($id) {
839
+        return $this->array_searchi($id, $this->tags, 'getId');
840
+    }
841
+
842
+    /**
843
+     * Returns an array mapping a given tag's properties to its values:
844
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
845
+     *
846
+     * @param Tag $tag The tag that is going to be mapped
847
+     * @return array
848
+     */
849
+    private function tagMap(Tag $tag) {
850
+        return array(
851
+            'id'    => $tag->getId(),
852
+            'name'  => $tag->getName(),
853
+            'owner' => $tag->getOwner(),
854
+            'type'  => $tag->getType()
855
+        );
856
+    }
857 857
 }
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 		}
136 136
 		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
137 137
 
138
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
138
+		if (count($defaultTags) > 0 && count($this->tags) === 0) {
139 139
 			$this->addMultiple($defaultTags, true);
140 140
 		}
141 141
 	}
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 	* @return array
177 177
 	*/
178 178
 	public function getTags() {
179
-		if(!count($this->tags)) {
179
+		if (!count($this->tags)) {
180 180
 			return array();
181 181
 		}
182 182
 
@@ -185,8 +185,8 @@  discard block
 block discarded – undo
185 185
 		});
186 186
 		$tagMap = array();
187 187
 
188
-		foreach($this->tags as $tag) {
189
-			if($tag->getName() !== self::TAG_FAVORITE) {
188
+		foreach ($this->tags as $tag) {
189
+			if ($tag->getName() !== self::TAG_FAVORITE) {
190 190
 				$tagMap[] = $this->tagMap($tag);
191 191
 			}
192 192
 		}
@@ -224,25 +224,25 @@  discard block
 block discarded – undo
224 224
 			$chunks = array_chunk($objIds, 900, false);
225 225
 			foreach ($chunks as $chunk) {
226 226
 				$result = $conn->executeQuery(
227
-					'SELECT `category`, `categoryid`, `objid` ' .
228
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
227
+					'SELECT `category`, `categoryid`, `objid` '.
228
+					'FROM `'.self::RELATION_TABLE.'` r, `'.self::TAG_TABLE.'` '.
229 229
 					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
230 230
 					array($this->user, $this->type, $chunk),
231 231
 					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
232 232
 				);
233 233
 				while ($row = $result->fetch()) {
234
-					$objId = (int)$row['objid'];
234
+					$objId = (int) $row['objid'];
235 235
 					if (!isset($entries[$objId])) {
236 236
 						$entries[$objId] = array();
237 237
 					}
238 238
 					$entries[$objId][] = $row['category'];
239 239
 				}
240 240
 				if ($result === null) {
241
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
241
+					\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
242 242
 					return false;
243 243
 				}
244 244
 			}
245
-		} catch(\Exception $e) {
245
+		} catch (\Exception $e) {
246 246
 			\OC::$server->getLogger()->logException($e, [
247 247
 				'message' => __METHOD__,
248 248
 				'level' => ILogger::ERROR,
@@ -266,18 +266,18 @@  discard block
 block discarded – undo
266 266
 	public function getIdsForTag($tag) {
267 267
 		$result = null;
268 268
 		$tagId = false;
269
-		if(is_numeric($tag)) {
269
+		if (is_numeric($tag)) {
270 270
 			$tagId = $tag;
271
-		} elseif(is_string($tag)) {
271
+		} elseif (is_string($tag)) {
272 272
 			$tag = trim($tag);
273
-			if($tag === '') {
273
+			if ($tag === '') {
274 274
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
275 275
 				return false;
276 276
 			}
277 277
 			$tagId = $this->getTagId($tag);
278 278
 		}
279 279
 
280
-		if($tagId === false) {
280
+		if ($tagId === false) {
281 281
 			$l10n = \OC::$server->getL10N('core');
282 282
 			throw new \Exception(
283 283
 				$l10n->t('Could not find category "%s"', [$tag])
@@ -285,17 +285,17 @@  discard block
 block discarded – undo
285 285
 		}
286 286
 
287 287
 		$ids = array();
288
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
288
+		$sql = 'SELECT `objid` FROM `'.self::RELATION_TABLE
289 289
 			. '` WHERE `categoryid` = ?';
290 290
 
291 291
 		try {
292 292
 			$stmt = \OC_DB::prepare($sql);
293 293
 			$result = $stmt->execute(array($tagId));
294 294
 			if ($result === null) {
295
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
295
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
296 296
 				return false;
297 297
 			}
298
-		} catch(\Exception $e) {
298
+		} catch (\Exception $e) {
299 299
 			\OC::$server->getLogger()->logException($e, [
300 300
 				'message' => __METHOD__,
301 301
 				'level' => ILogger::ERROR,
@@ -304,9 +304,9 @@  discard block
 block discarded – undo
304 304
 			return false;
305 305
 		}
306 306
 
307
-		if(!is_null($result)) {
308
-			while( $row = $result->fetchRow()) {
309
-				$id = (int)$row['objid'];
307
+		if (!is_null($result)) {
308
+			while ($row = $result->fetchRow()) {
309
+				$id = (int) $row['objid'];
310 310
 
311 311
 				if ($this->includeShared) {
312 312
 					// We have to check if we are really allowed to access the
@@ -360,19 +360,19 @@  discard block
 block discarded – undo
360 360
 	public function add($name) {
361 361
 		$name = trim($name);
362 362
 
363
-		if($name === '') {
363
+		if ($name === '') {
364 364
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
365 365
 			return false;
366 366
 		}
367
-		if($this->userHasTag($name, $this->user)) {
368
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', ILogger::DEBUG);
367
+		if ($this->userHasTag($name, $this->user)) {
368
+			\OCP\Util::writeLog('core', __METHOD__.', name: '.$name.' exists already', ILogger::DEBUG);
369 369
 			return false;
370 370
 		}
371 371
 		try {
372 372
 			$tag = new Tag($this->user, $this->type, $name);
373 373
 			$tag = $this->mapper->insert($tag);
374 374
 			$this->tags[] = $tag;
375
-		} catch(\Exception $e) {
375
+		} catch (\Exception $e) {
376 376
 			\OC::$server->getLogger()->logException($e, [
377 377
 				'message' => __METHOD__,
378 378
 				'level' => ILogger::ERROR,
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 			]);
381 381
 			return false;
382 382
 		}
383
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), ILogger::DEBUG);
383
+		\OCP\Util::writeLog('core', __METHOD__.', id: '.$tag->getId(), ILogger::DEBUG);
384 384
 		return $tag->getId();
385 385
 	}
386 386
 
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
 		$from = trim($from);
396 396
 		$to = trim($to);
397 397
 
398
-		if($to === '' || $from === '') {
398
+		if ($to === '' || $from === '') {
399 399
 			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', ILogger::DEBUG);
400 400
 			return false;
401 401
 		}
@@ -405,21 +405,21 @@  discard block
 block discarded – undo
405 405
 		} else {
406 406
 			$key = $this->getTagByName($from);
407 407
 		}
408
-		if($key === false) {
409
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', ILogger::DEBUG);
408
+		if ($key === false) {
409
+			\OCP\Util::writeLog('core', __METHOD__.', tag: '.$from.' does not exist', ILogger::DEBUG);
410 410
 			return false;
411 411
 		}
412 412
 		$tag = $this->tags[$key];
413 413
 
414
-		if($this->userHasTag($to, $tag->getOwner())) {
415
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', ILogger::DEBUG);
414
+		if ($this->userHasTag($to, $tag->getOwner())) {
415
+			\OCP\Util::writeLog('core', __METHOD__.', A tag named '.$to.' already exists for user '.$tag->getOwner().'.', ILogger::DEBUG);
416 416
 			return false;
417 417
 		}
418 418
 
419 419
 		try {
420 420
 			$tag->setName($to);
421 421
 			$this->tags[$key] = $this->mapper->update($tag);
422
-		} catch(\Exception $e) {
422
+		} catch (\Exception $e) {
423 423
 			\OC::$server->getLogger()->logException($e, [
424 424
 				'message' => __METHOD__,
425 425
 				'level' => ILogger::ERROR,
@@ -439,25 +439,25 @@  discard block
 block discarded – undo
439 439
 	* @param int|null $id int Optional object id to add to this|these tag(s)
440 440
 	* @return bool Returns false on error.
441 441
 	*/
442
-	public function addMultiple($names, $sync=false, $id = null) {
443
-		if(!is_array($names)) {
442
+	public function addMultiple($names, $sync = false, $id = null) {
443
+		if (!is_array($names)) {
444 444
 			$names = array($names);
445 445
 		}
446 446
 		$names = array_map('trim', $names);
447 447
 		array_filter($names);
448 448
 
449 449
 		$newones = array();
450
-		foreach($names as $name) {
451
-			if(!$this->hasTag($name) && $name !== '') {
450
+		foreach ($names as $name) {
451
+			if (!$this->hasTag($name) && $name !== '') {
452 452
 				$newones[] = new Tag($this->user, $this->type, $name);
453 453
 			}
454
-			if(!is_null($id) ) {
454
+			if (!is_null($id)) {
455 455
 				// Insert $objectid, $categoryid  pairs if not exist.
456 456
 				self::$relations[] = array('objid' => $id, 'tag' => $name);
457 457
 			}
458 458
 		}
459 459
 		$this->tags = array_merge($this->tags, $newones);
460
-		if($sync === true) {
460
+		if ($sync === true) {
461 461
 			$this->save();
462 462
 		}
463 463
 
@@ -468,13 +468,13 @@  discard block
 block discarded – undo
468 468
 	 * Save the list of tags and their object relations
469 469
 	 */
470 470
 	protected function save() {
471
-		if(is_array($this->tags)) {
472
-			foreach($this->tags as $tag) {
471
+		if (is_array($this->tags)) {
472
+			foreach ($this->tags as $tag) {
473 473
 				try {
474 474
 					if (!$this->mapper->tagExists($tag)) {
475 475
 						$this->mapper->insert($tag);
476 476
 					}
477
-				} catch(\Exception $e) {
477
+				} catch (\Exception $e) {
478 478
 					\OC::$server->getLogger()->logException($e, [
479 479
 						'message' => __METHOD__,
480 480
 						'level' => ILogger::ERROR,
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 
486 486
 			// reload tags to get the proper ids.
487 487
 			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
488
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
488
+			\OCP\Util::writeLog('core', __METHOD__.', tags: '.print_r($this->tags, true),
489 489
 				ILogger::DEBUG);
490 490
 			// Loop through temporarily cached objectid/tagname pairs
491 491
 			// and save relations.
@@ -493,10 +493,10 @@  discard block
 block discarded – undo
493 493
 			// For some reason this is needed or array_search(i) will return 0..?
494 494
 			ksort($tags);
495 495
 			$dbConnection = \OC::$server->getDatabaseConnection();
496
-			foreach(self::$relations as $relation) {
496
+			foreach (self::$relations as $relation) {
497 497
 				$tagId = $this->getTagId($relation['tag']);
498
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, ILogger::DEBUG);
499
-				if($tagId) {
498
+				\OCP\Util::writeLog('core', __METHOD__.'catid, '.$relation['tag'].' '.$tagId, ILogger::DEBUG);
499
+				if ($tagId) {
500 500
 					try {
501 501
 						$dbConnection->insertIfNotExist(self::RELATION_TABLE,
502 502
 							array(
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
 								'categoryid' => $tagId,
505 505
 								'type' => $this->type,
506 506
 								));
507
-					} catch(\Exception $e) {
507
+					} catch (\Exception $e) {
508 508
 						\OC::$server->getLogger()->logException($e, [
509 509
 							'message' => __METHOD__,
510 510
 							'level' => ILogger::ERROR,
@@ -531,13 +531,13 @@  discard block
 block discarded – undo
531 531
 		// Find all objectid/tagId pairs.
532 532
 		$result = null;
533 533
 		try {
534
-			$stmt = \OC_DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
534
+			$stmt = \OC_DB::prepare('SELECT `id` FROM `'.self::TAG_TABLE.'` '
535 535
 				. 'WHERE `uid` = ?');
536 536
 			$result = $stmt->execute(array($arguments['uid']));
537 537
 			if ($result === null) {
538
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
538
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
539 539
 			}
540
-		} catch(\Exception $e) {
540
+		} catch (\Exception $e) {
541 541
 			\OC::$server->getLogger()->logException($e, [
542 542
 				'message' => __METHOD__,
543 543
 				'level' => ILogger::ERROR,
@@ -545,14 +545,14 @@  discard block
 block discarded – undo
545 545
 			]);
546 546
 		}
547 547
 
548
-		if(!is_null($result)) {
548
+		if (!is_null($result)) {
549 549
 			try {
550
-				$stmt = \OC_DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
550
+				$stmt = \OC_DB::prepare('DELETE FROM `'.self::RELATION_TABLE.'` '
551 551
 					. 'WHERE `categoryid` = ?');
552
-				while( $row = $result->fetchRow()) {
552
+				while ($row = $result->fetchRow()) {
553 553
 					try {
554 554
 						$stmt->execute(array($row['id']));
555
-					} catch(\Exception $e) {
555
+					} catch (\Exception $e) {
556 556
 						\OC::$server->getLogger()->logException($e, [
557 557
 							'message' => __METHOD__,
558 558
 							'level' => ILogger::ERROR,
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 						]);
561 561
 					}
562 562
 				}
563
-			} catch(\Exception $e) {
563
+			} catch (\Exception $e) {
564 564
 				\OC::$server->getLogger()->logException($e, [
565 565
 					'message' => __METHOD__,
566 566
 					'level' => ILogger::ERROR,
@@ -569,13 +569,13 @@  discard block
 block discarded – undo
569 569
 			}
570 570
 		}
571 571
 		try {
572
-			$stmt = \OC_DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
572
+			$stmt = \OC_DB::prepare('DELETE FROM `'.self::TAG_TABLE.'` '
573 573
 				. 'WHERE `uid` = ?');
574 574
 			$result = $stmt->execute(array($arguments['uid']));
575 575
 			if ($result === null) {
576
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
576
+				\OCP\Util::writeLog('core', __METHOD__.', DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
577 577
 			}
578
-		} catch(\Exception $e) {
578
+		} catch (\Exception $e) {
579 579
 			\OC::$server->getLogger()->logException($e, [
580 580
 				'message' => __METHOD__,
581 581
 				'level' => ILogger::ERROR,
@@ -591,23 +591,23 @@  discard block
 block discarded – undo
591 591
 	* @return boolean Returns false on error.
592 592
 	*/
593 593
 	public function purgeObjects(array $ids) {
594
-		if(count($ids) === 0) {
594
+		if (count($ids) === 0) {
595 595
 			// job done ;)
596 596
 			return true;
597 597
 		}
598 598
 		$updates = $ids;
599 599
 		try {
600
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
601
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
600
+			$query = 'DELETE FROM `'.self::RELATION_TABLE.'` ';
601
+			$query .= 'WHERE `objid` IN ('.str_repeat('?,', count($ids) - 1).'?) ';
602 602
 			$query .= 'AND `type`= ?';
603 603
 			$updates[] = $this->type;
604 604
 			$stmt = \OC_DB::prepare($query);
605 605
 			$result = $stmt->execute($updates);
606 606
 			if ($result === null) {
607
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
607
+				\OCP\Util::writeLog('core', __METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(), ILogger::ERROR);
608 608
 				return false;
609 609
 			}
610
-		} catch(\Exception $e) {
610
+		} catch (\Exception $e) {
611 611
 			\OC::$server->getLogger()->logException($e, [
612 612
 				'message' => __METHOD__,
613 613
 				'level' => ILogger::ERROR,
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 	public function getFavorites() {
627 627
 		try {
628 628
 			return $this->getIdsForTag(self::TAG_FAVORITE);
629
-		} catch(\Exception $e) {
629
+		} catch (\Exception $e) {
630 630
 			\OC::$server->getLogger()->logException($e, [
631 631
 				'message' => __METHOD__,
632 632
 				'level' => ILogger::ERROR,
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
 	* @return boolean
644 644
 	*/
645 645
 	public function addToFavorites($objid) {
646
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
646
+		if (!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
647 647
 			$this->add(self::TAG_FAVORITE);
648 648
 		}
649 649
 		return $this->tagAs($objid, self::TAG_FAVORITE);
@@ -667,16 +667,16 @@  discard block
 block discarded – undo
667 667
 	* @return boolean Returns false on error.
668 668
 	*/
669 669
 	public function tagAs($objid, $tag) {
670
-		if(is_string($tag) && !is_numeric($tag)) {
670
+		if (is_string($tag) && !is_numeric($tag)) {
671 671
 			$tag = trim($tag);
672
-			if($tag === '') {
672
+			if ($tag === '') {
673 673
 				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', ILogger::DEBUG);
674 674
 				return false;
675 675
 			}
676
-			if(!$this->hasTag($tag)) {
676
+			if (!$this->hasTag($tag)) {
677 677
 				$this->add($tag);
678 678
 			}
679
-			$tagId =  $this->getTagId($tag);
679
+			$tagId = $this->getTagId($tag);
680 680
 		} else {
681 681
 			$tagId = $tag;
682 682
 		}
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 					'categoryid' => $tagId,
688 688
 					'type' => $this->type,
689 689
 				));
690
-		} catch(\Exception $e) {
690
+		} catch (\Exception $e) {
691 691
 			\OC::$server->getLogger()->logException($e, [
692 692
 				'message' => __METHOD__,
693 693
 				'level' => ILogger::ERROR,
@@ -706,23 +706,23 @@  discard block
 block discarded – undo
706 706
 	* @return boolean
707 707
 	*/
708 708
 	public function unTag($objid, $tag) {
709
-		if(is_string($tag) && !is_numeric($tag)) {
709
+		if (is_string($tag) && !is_numeric($tag)) {
710 710
 			$tag = trim($tag);
711
-			if($tag === '') {
711
+			if ($tag === '') {
712 712
 				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', ILogger::DEBUG);
713 713
 				return false;
714 714
 			}
715
-			$tagId =  $this->getTagId($tag);
715
+			$tagId = $this->getTagId($tag);
716 716
 		} else {
717 717
 			$tagId = $tag;
718 718
 		}
719 719
 
720 720
 		try {
721
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
721
+			$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
722 722
 					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
723 723
 			$stmt = \OC_DB::prepare($sql);
724 724
 			$stmt->execute(array($objid, $tagId, $this->type));
725
-		} catch(\Exception $e) {
725
+		} catch (\Exception $e) {
726 726
 			\OC::$server->getLogger()->logException($e, [
727 727
 				'message' => __METHOD__,
728 728
 				'level' => ILogger::ERROR,
@@ -740,16 +740,16 @@  discard block
 block discarded – undo
740 740
 	* @return bool Returns false on error
741 741
 	*/
742 742
 	public function delete($names) {
743
-		if(!is_array($names)) {
743
+		if (!is_array($names)) {
744 744
 			$names = array($names);
745 745
 		}
746 746
 
747 747
 		$names = array_map('trim', $names);
748 748
 		array_filter($names);
749 749
 
750
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
750
+		\OCP\Util::writeLog('core', __METHOD__.', before: '
751 751
 			. print_r($this->tags, true), ILogger::DEBUG);
752
-		foreach($names as $name) {
752
+		foreach ($names as $name) {
753 753
 			$id = null;
754 754
 
755 755
 			if (is_numeric($name)) {
@@ -763,22 +763,22 @@  discard block
 block discarded – undo
763 763
 				unset($this->tags[$key]);
764 764
 				$this->mapper->delete($tag);
765 765
 			} else {
766
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
766
+				\OCP\Util::writeLog('core', __METHOD__.'Cannot delete tag '.$name
767 767
 					. ': not found.', ILogger::ERROR);
768 768
 			}
769
-			if(!is_null($id) && $id !== false) {
769
+			if (!is_null($id) && $id !== false) {
770 770
 				try {
771
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
771
+					$sql = 'DELETE FROM `'.self::RELATION_TABLE.'` '
772 772
 							. 'WHERE `categoryid` = ?';
773 773
 					$stmt = \OC_DB::prepare($sql);
774 774
 					$result = $stmt->execute(array($id));
775 775
 					if ($result === null) {
776 776
 						\OCP\Util::writeLog('core',
777
-							__METHOD__. 'DB error: ' . \OC::$server->getDatabaseConnection()->getError(),
777
+							__METHOD__.'DB error: '.\OC::$server->getDatabaseConnection()->getError(),
778 778
 							ILogger::ERROR);
779 779
 						return false;
780 780
 					}
781
-				} catch(\Exception $e) {
781
+				} catch (\Exception $e) {
782 782
 					\OC::$server->getLogger()->logException($e, [
783 783
 						'message' => __METHOD__,
784 784
 						'level' => ILogger::ERROR,
@@ -792,8 +792,8 @@  discard block
 block discarded – undo
792 792
 	}
793 793
 
794 794
 	// case-insensitive array_search
795
-	protected function array_searchi($needle, $haystack, $mem='getName') {
796
-		if(!is_array($haystack)) {
795
+	protected function array_searchi($needle, $haystack, $mem = 'getName') {
796
+		if (!is_array($haystack)) {
797 797
 			return false;
798 798
 		}
799 799
 		return array_search(strtolower($needle), array_map(
Please login to merge, or discard this patch.
lib/private/Template/Base.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -103,7 +103,7 @@
 block discarded – undo
103 103
 	/**
104 104
 	 * Appends a variable
105 105
 	 * @param string $key key
106
-	 * @param mixed $value value
106
+	 * @param string $value value
107 107
 	 * @return boolean|null
108 108
 	 *
109 109
 	 * This function assigns a variable in an array context. If the key already
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -114,8 +114,7 @@  discard block
 block discarded – undo
114 114
 	public function append( $key, $value ) {
115 115
 		if( array_key_exists( $key, $this->vars )) {
116 116
 			$this->vars[$key][] = $value;
117
-		}
118
-		else{
117
+		} else{
119 118
 			$this->vars[$key] = array( $value );
120 119
 		}
121 120
 	}
@@ -130,8 +129,7 @@  discard block
 block discarded – undo
130 129
 		$data = $this->fetchPage();
131 130
 		if( $data === false ) {
132 131
 			return false;
133
-		}
134
-		else{
132
+		} else{
135 133
 			print $data;
136 134
 			return true;
137 135
 		}
Please login to merge, or discard this patch.
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -31,161 +31,161 @@
 block discarded – undo
31 31
 use OCP\Defaults;
32 32
 
33 33
 class Base {
34
-	private $template; // The template
35
-	private $vars; // Vars
36
-
37
-	/** @var \OCP\IL10N */
38
-	private $l10n;
39
-
40
-	/** @var Defaults */
41
-	private $theme;
42
-
43
-	/**
44
-	 * @param string $template
45
-	 * @param string $requestToken
46
-	 * @param \OCP\IL10N $l10n
47
-	 * @param Defaults $theme
48
-	 */
49
-	public function __construct($template, $requestToken, $l10n, $theme ) {
50
-		$this->vars = array();
51
-		$this->vars['requesttoken'] = $requestToken;
52
-		$this->l10n = $l10n;
53
-		$this->template = $template;
54
-		$this->theme = $theme;
55
-	}
56
-
57
-	/**
58
-	 * @param string $serverRoot
59
-	 * @param string|false $app_dir
60
-	 * @param string $theme
61
-	 * @param string $app
62
-	 * @return string[]
63
-	 */
64
-	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65
-		// Check if the app is in the app folder or in the root
66
-		if( file_exists($app_dir.'/templates/' )) {
67
-			return [
68
-				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69
-				$app_dir.'/templates/',
70
-			];
71
-		}
72
-		return [
73
-			$serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
74
-			$serverRoot.'/'.$app.'/templates/',
75
-		];
76
-	}
77
-
78
-	/**
79
-	 * @param string $serverRoot
80
-	 * @param string $theme
81
-	 * @return string[]
82
-	 */
83
-	protected function getCoreTemplateDirs($theme, $serverRoot) {
84
-		return [
85
-			$serverRoot.'/themes/'.$theme.'/core/templates/',
86
-			$serverRoot.'/core/templates/',
87
-		];
88
-	}
89
-
90
-	/**
91
-	 * Assign variables
92
-	 * @param string $key key
93
-	 * @param array|bool|integer|string $value value
94
-	 * @return bool
95
-	 *
96
-	 * This function assigns a variable. It can be accessed via $_[$key] in
97
-	 * the template.
98
-	 *
99
-	 * If the key existed before, it will be overwritten
100
-	 */
101
-	public function assign( $key, $value) {
102
-		$this->vars[$key] = $value;
103
-		return true;
104
-	}
105
-
106
-	/**
107
-	 * Appends a variable
108
-	 * @param string $key key
109
-	 * @param mixed $value value
110
-	 * @return boolean|null
111
-	 *
112
-	 * This function assigns a variable in an array context. If the key already
113
-	 * exists, the value will be appended. It can be accessed via
114
-	 * $_[$key][$position] in the template.
115
-	 */
116
-	public function append( $key, $value ) {
117
-		if( array_key_exists( $key, $this->vars )) {
118
-			$this->vars[$key][] = $value;
119
-		}
120
-		else{
121
-			$this->vars[$key] = array( $value );
122
-		}
123
-	}
124
-
125
-	/**
126
-	 * Prints the proceeded template
127
-	 * @return bool
128
-	 *
129
-	 * This function proceeds the template and prints its output.
130
-	 */
131
-	public function printPage() {
132
-		$data = $this->fetchPage();
133
-		if( $data === false ) {
134
-			return false;
135
-		}
136
-		else{
137
-			print $data;
138
-			return true;
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * Process the template
144
-	 *
145
-	 * @param array|null $additionalParams
146
-	 * @return string This function processes the template.
147
-	 *
148
-	 * This function processes the template.
149
-	 */
150
-	public function fetchPage($additionalParams = null) {
151
-		return $this->load($this->template, $additionalParams);
152
-	}
153
-
154
-	/**
155
-	 * doing the actual work
156
-	 *
157
-	 * @param string $file
158
-	 * @param array|null $additionalParams
159
-	 * @return string content
160
-	 *
161
-	 * Includes the template file, fetches its output
162
-	 */
163
-	protected function load($file, $additionalParams = null) {
164
-		// Register the variables
165
-		$_ = $this->vars;
166
-		$l = $this->l10n;
167
-		$theme = $this->theme;
168
-
169
-		if(!is_null($additionalParams)) {
170
-			$_ = array_merge( $additionalParams, $this->vars );
171
-			foreach ($_ as $var => $value) {
172
-				${$var} = $value;
173
-			}
174
-		}
175
-
176
-		// Include
177
-		ob_start();
178
-		try {
179
-			include $file;
180
-			$data = ob_get_contents();
181
-		} catch (\Exception $e) {
182
-			@ob_end_clean();
183
-			throw $e;
184
-		}
185
-		@ob_end_clean();
186
-
187
-		// Return data
188
-		return $data;
189
-	}
34
+    private $template; // The template
35
+    private $vars; // Vars
36
+
37
+    /** @var \OCP\IL10N */
38
+    private $l10n;
39
+
40
+    /** @var Defaults */
41
+    private $theme;
42
+
43
+    /**
44
+     * @param string $template
45
+     * @param string $requestToken
46
+     * @param \OCP\IL10N $l10n
47
+     * @param Defaults $theme
48
+     */
49
+    public function __construct($template, $requestToken, $l10n, $theme ) {
50
+        $this->vars = array();
51
+        $this->vars['requesttoken'] = $requestToken;
52
+        $this->l10n = $l10n;
53
+        $this->template = $template;
54
+        $this->theme = $theme;
55
+    }
56
+
57
+    /**
58
+     * @param string $serverRoot
59
+     * @param string|false $app_dir
60
+     * @param string $theme
61
+     * @param string $app
62
+     * @return string[]
63
+     */
64
+    protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65
+        // Check if the app is in the app folder or in the root
66
+        if( file_exists($app_dir.'/templates/' )) {
67
+            return [
68
+                $serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69
+                $app_dir.'/templates/',
70
+            ];
71
+        }
72
+        return [
73
+            $serverRoot.'/themes/'.$theme.'/'.$app.'/templates/',
74
+            $serverRoot.'/'.$app.'/templates/',
75
+        ];
76
+    }
77
+
78
+    /**
79
+     * @param string $serverRoot
80
+     * @param string $theme
81
+     * @return string[]
82
+     */
83
+    protected function getCoreTemplateDirs($theme, $serverRoot) {
84
+        return [
85
+            $serverRoot.'/themes/'.$theme.'/core/templates/',
86
+            $serverRoot.'/core/templates/',
87
+        ];
88
+    }
89
+
90
+    /**
91
+     * Assign variables
92
+     * @param string $key key
93
+     * @param array|bool|integer|string $value value
94
+     * @return bool
95
+     *
96
+     * This function assigns a variable. It can be accessed via $_[$key] in
97
+     * the template.
98
+     *
99
+     * If the key existed before, it will be overwritten
100
+     */
101
+    public function assign( $key, $value) {
102
+        $this->vars[$key] = $value;
103
+        return true;
104
+    }
105
+
106
+    /**
107
+     * Appends a variable
108
+     * @param string $key key
109
+     * @param mixed $value value
110
+     * @return boolean|null
111
+     *
112
+     * This function assigns a variable in an array context. If the key already
113
+     * exists, the value will be appended. It can be accessed via
114
+     * $_[$key][$position] in the template.
115
+     */
116
+    public function append( $key, $value ) {
117
+        if( array_key_exists( $key, $this->vars )) {
118
+            $this->vars[$key][] = $value;
119
+        }
120
+        else{
121
+            $this->vars[$key] = array( $value );
122
+        }
123
+    }
124
+
125
+    /**
126
+     * Prints the proceeded template
127
+     * @return bool
128
+     *
129
+     * This function proceeds the template and prints its output.
130
+     */
131
+    public function printPage() {
132
+        $data = $this->fetchPage();
133
+        if( $data === false ) {
134
+            return false;
135
+        }
136
+        else{
137
+            print $data;
138
+            return true;
139
+        }
140
+    }
141
+
142
+    /**
143
+     * Process the template
144
+     *
145
+     * @param array|null $additionalParams
146
+     * @return string This function processes the template.
147
+     *
148
+     * This function processes the template.
149
+     */
150
+    public function fetchPage($additionalParams = null) {
151
+        return $this->load($this->template, $additionalParams);
152
+    }
153
+
154
+    /**
155
+     * doing the actual work
156
+     *
157
+     * @param string $file
158
+     * @param array|null $additionalParams
159
+     * @return string content
160
+     *
161
+     * Includes the template file, fetches its output
162
+     */
163
+    protected function load($file, $additionalParams = null) {
164
+        // Register the variables
165
+        $_ = $this->vars;
166
+        $l = $this->l10n;
167
+        $theme = $this->theme;
168
+
169
+        if(!is_null($additionalParams)) {
170
+            $_ = array_merge( $additionalParams, $this->vars );
171
+            foreach ($_ as $var => $value) {
172
+                ${$var} = $value;
173
+            }
174
+        }
175
+
176
+        // Include
177
+        ob_start();
178
+        try {
179
+            include $file;
180
+            $data = ob_get_contents();
181
+        } catch (\Exception $e) {
182
+            @ob_end_clean();
183
+            throw $e;
184
+        }
185
+        @ob_end_clean();
186
+
187
+        // Return data
188
+        return $data;
189
+    }
190 190
 
191 191
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 	 * @param \OCP\IL10N $l10n
47 47
 	 * @param Defaults $theme
48 48
 	 */
49
-	public function __construct($template, $requestToken, $l10n, $theme ) {
49
+	public function __construct($template, $requestToken, $l10n, $theme) {
50 50
 		$this->vars = array();
51 51
 		$this->vars['requesttoken'] = $requestToken;
52 52
 		$this->l10n = $l10n;
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 	 */
64 64
 	protected function getAppTemplateDirs($theme, $app, $serverRoot, $app_dir) {
65 65
 		// Check if the app is in the app folder or in the root
66
-		if( file_exists($app_dir.'/templates/' )) {
66
+		if (file_exists($app_dir.'/templates/')) {
67 67
 			return [
68 68
 				$serverRoot.'/themes/'.$theme.'/apps/'.$app.'/templates/',
69 69
 				$app_dir.'/templates/',
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
 	 *
99 99
 	 * If the key existed before, it will be overwritten
100 100
 	 */
101
-	public function assign( $key, $value) {
101
+	public function assign($key, $value) {
102 102
 		$this->vars[$key] = $value;
103 103
 		return true;
104 104
 	}
@@ -113,12 +113,12 @@  discard block
 block discarded – undo
113 113
 	 * exists, the value will be appended. It can be accessed via
114 114
 	 * $_[$key][$position] in the template.
115 115
 	 */
116
-	public function append( $key, $value ) {
117
-		if( array_key_exists( $key, $this->vars )) {
116
+	public function append($key, $value) {
117
+		if (array_key_exists($key, $this->vars)) {
118 118
 			$this->vars[$key][] = $value;
119 119
 		}
120
-		else{
121
-			$this->vars[$key] = array( $value );
120
+		else {
121
+			$this->vars[$key] = array($value);
122 122
 		}
123 123
 	}
124 124
 
@@ -130,10 +130,10 @@  discard block
 block discarded – undo
130 130
 	 */
131 131
 	public function printPage() {
132 132
 		$data = $this->fetchPage();
133
-		if( $data === false ) {
133
+		if ($data === false) {
134 134
 			return false;
135 135
 		}
136
-		else{
136
+		else {
137 137
 			print $data;
138 138
 			return true;
139 139
 		}
@@ -166,8 +166,8 @@  discard block
 block discarded – undo
166 166
 		$l = $this->l10n;
167 167
 		$theme = $this->theme;
168 168
 
169
-		if(!is_null($additionalParams)) {
170
-			$_ = array_merge( $additionalParams, $this->vars );
169
+		if (!is_null($additionalParams)) {
170
+			$_ = array_merge($additionalParams, $this->vars);
171 171
 			foreach ($_ as $var => $value) {
172 172
 				${$var} = $value;
173 173
 			}
Please login to merge, or discard this patch.
lib/public/Migration/IOutput.php 2 patches
Doc Comments   +5 added lines, -1 removed lines patch added patch discarded remove patch
@@ -32,18 +32,21 @@  discard block
 block discarded – undo
32 32
 	/**
33 33
 	 * @param string $message
34 34
 	 * @since 9.1.0
35
+	 * @return void
35 36
 	 */
36 37
 	public function info($message);
37 38
 
38 39
 	/**
39 40
 	 * @param string $message
40 41
 	 * @since 9.1.0
42
+	 * @return void
41 43
 	 */
42 44
 	public function warning($message);
43 45
 
44 46
 	/**
45 47
 	 * @param int $max
46 48
 	 * @since 9.1.0
49
+	 * @return void
47 50
 	 */
48 51
 	public function startProgress($max = 0);
49 52
 
@@ -51,12 +54,13 @@  discard block
 block discarded – undo
51 54
 	 * @param int $step
52 55
 	 * @param string $description
53 56
 	 * @since 9.1.0
57
+	 * @return void
54 58
 	 */
55 59
 	public function advance($step = 1, $description = '');
56 60
 
57 61
 	/**
58
-	 * @param int $max
59 62
 	 * @since 9.1.0
63
+	 * @return void
60 64
 	 */
61 65
 	public function finishProgress();
62 66
 
Please login to merge, or discard this patch.
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -30,35 +30,35 @@
 block discarded – undo
30 30
  */
31 31
 interface IOutput {
32 32
 
33
-	/**
34
-	 * @param string $message
35
-	 * @since 9.1.0
36
-	 */
37
-	public function info($message);
33
+    /**
34
+     * @param string $message
35
+     * @since 9.1.0
36
+     */
37
+    public function info($message);
38 38
 
39
-	/**
40
-	 * @param string $message
41
-	 * @since 9.1.0
42
-	 */
43
-	public function warning($message);
39
+    /**
40
+     * @param string $message
41
+     * @since 9.1.0
42
+     */
43
+    public function warning($message);
44 44
 
45
-	/**
46
-	 * @param int $max
47
-	 * @since 9.1.0
48
-	 */
49
-	public function startProgress($max = 0);
45
+    /**
46
+     * @param int $max
47
+     * @since 9.1.0
48
+     */
49
+    public function startProgress($max = 0);
50 50
 
51
-	/**
52
-	 * @param int $step
53
-	 * @param string $description
54
-	 * @since 9.1.0
55
-	 */
56
-	public function advance($step = 1, $description = '');
51
+    /**
52
+     * @param int $step
53
+     * @param string $description
54
+     * @since 9.1.0
55
+     */
56
+    public function advance($step = 1, $description = '');
57 57
 
58
-	/**
59
-	 * @param int $max
60
-	 * @since 9.1.0
61
-	 */
62
-	public function finishProgress();
58
+    /**
59
+     * @param int $max
60
+     * @since 9.1.0
61
+     */
62
+    public function finishProgress();
63 63
 
64 64
 }
Please login to merge, or discard this patch.