Completed
Pull Request — master (#5881)
by Thomas
18:04
created
lib/private/Files/Config/UserMountCache.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -206,7 +206,7 @@
 block discarded – undo
206 206
 	}
207 207
 
208 208
 	/**
209
-	 * @param $fileId
209
+	 * @param integer $fileId
210 210
 	 * @return array
211 211
 	 * @throws \OCP\Files\NotFoundException
212 212
 	 */
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 
25 25
 namespace OC\Files\Config;
26 26
 
27
-use OC\DB\QueryBuilder\Literal;
28 27
 use OCA\Files_Sharing\SharedMount;
29 28
 use OCP\DB\QueryBuilder\IQueryBuilder;
30 29
 use OCP\Files\Config\ICachedMountInfo;
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -87,11 +87,11 @@  discard block
 block discarded – undo
87 87
 
88 88
 	public function registerMounts(IUser $user, array $mounts) {
89 89
 		// filter out non-proper storages coming from unit tests
90
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
90
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
91 91
 			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
92 92
 		});
93 93
 		/** @var ICachedMountInfo[] $newMounts */
94
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
94
+		$newMounts = array_map(function(IMountPoint $mount) use ($user) {
95 95
 			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
96 96
 			if ($mount->getStorageRootId() === -1) {
97 97
 				return null;
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 		$newMounts = array_values(array_filter($newMounts));
103 103
 
104 104
 		$cachedMounts = $this->getMountsForUser($user);
105
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
105
+		$mountDiff = function(ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
106 106
 			// since we are only looking for mounts for a specific user comparing on root id is enough
107 107
 			return $mount1->getRootId() - $mount2->getRootId();
108 108
 		};
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			], ['root_id', 'user_id']);
164 164
 		} else {
165 165
 			// in some cases this is legitimate, like orphaned shares
166
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
166
+			$this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint());
167 167
 		}
168 168
 	}
169 169
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 		if (is_null($user)) {
195 195
 			return null;
196 196
 		}
197
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
197
+		return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
198 198
 	}
199 199
 
200 200
 	/**
@@ -268,12 +268,12 @@  discard block
 block discarded – undo
268 268
 			$row = $query->execute()->fetch();
269 269
 			if (is_array($row)) {
270 270
 				$this->cacheInfoCache[$fileId] = [
271
-					(int)$row['storage'],
271
+					(int) $row['storage'],
272 272
 					$row['path'],
273
-					(int)$row['mimetype']
273
+					(int) $row['mimetype']
274 274
 				];
275 275
 			} else {
276
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
276
+				throw new NotFoundException('File with id "'.$fileId.'" not found');
277 277
 			}
278 278
 		}
279 279
 		return $this->cacheInfoCache[$fileId];
@@ -294,13 +294,13 @@  discard block
 block discarded – undo
294 294
 		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
295 295
 
296 296
 		// filter mounts that are from the same storage but a different directory
297
-		return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
297
+		return array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) {
298 298
 			if ($fileId === $mount->getRootId()) {
299 299
 				return true;
300 300
 			}
301 301
 			$internalMountPath = $mount->getRootInternalPath();
302 302
 
303
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
303
+			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/';
304 304
 		});
305 305
 	}
306 306
 
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 			$slash
345 345
 		);
346 346
 
347
-		$userIds = array_map(function (IUser $user) {
347
+		$userIds = array_map(function(IUser $user) {
348 348
 			return $user->getUID();
349 349
 		}, $users);
350 350
 
Please login to merge, or discard this patch.
Indentation   +325 added lines, -325 removed lines patch added patch discarded remove patch
@@ -42,329 +42,329 @@
 block discarded – undo
42 42
  * Cache mounts points per user in the cache so we can easilly look them up
43 43
  */
44 44
 class UserMountCache implements IUserMountCache {
45
-	/**
46
-	 * @var IDBConnection
47
-	 */
48
-	private $connection;
49
-
50
-	/**
51
-	 * @var IUserManager
52
-	 */
53
-	private $userManager;
54
-
55
-	/**
56
-	 * Cached mount info.
57
-	 * Map of $userId to ICachedMountInfo.
58
-	 *
59
-	 * @var ICache
60
-	 **/
61
-	private $mountsForUsers;
62
-
63
-	/**
64
-	 * @var ILogger
65
-	 */
66
-	private $logger;
67
-
68
-	/**
69
-	 * @var ICache
70
-	 */
71
-	private $cacheInfoCache;
72
-
73
-	/**
74
-	 * UserMountCache constructor.
75
-	 *
76
-	 * @param IDBConnection $connection
77
-	 * @param IUserManager $userManager
78
-	 * @param ILogger $logger
79
-	 */
80
-	public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
81
-		$this->connection = $connection;
82
-		$this->userManager = $userManager;
83
-		$this->logger = $logger;
84
-		$this->cacheInfoCache = new CappedMemoryCache();
85
-		$this->mountsForUsers = new CappedMemoryCache();
86
-	}
87
-
88
-	public function registerMounts(IUser $user, array $mounts) {
89
-		// filter out non-proper storages coming from unit tests
90
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
91
-			return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
92
-		});
93
-		/** @var ICachedMountInfo[] $newMounts */
94
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
95
-			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
96
-			if ($mount->getStorageRootId() === -1) {
97
-				return null;
98
-			} else {
99
-				return new LazyStorageMountInfo($user, $mount);
100
-			}
101
-		}, $mounts);
102
-		$newMounts = array_values(array_filter($newMounts));
103
-
104
-		$cachedMounts = $this->getMountsForUser($user);
105
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
106
-			// since we are only looking for mounts for a specific user comparing on root id is enough
107
-			return $mount1->getRootId() - $mount2->getRootId();
108
-		};
109
-
110
-		/** @var ICachedMountInfo[] $addedMounts */
111
-		$addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
112
-		/** @var ICachedMountInfo[] $removedMounts */
113
-		$removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
114
-
115
-		$changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
116
-
117
-		foreach ($addedMounts as $mount) {
118
-			$this->addToCache($mount);
119
-			$this->mountsForUsers[$user->getUID()][] = $mount;
120
-		}
121
-		foreach ($removedMounts as $mount) {
122
-			$this->removeFromCache($mount);
123
-			$index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
124
-			unset($this->mountsForUsers[$user->getUID()][$index]);
125
-		}
126
-		foreach ($changedMounts as $mount) {
127
-			$this->updateCachedMount($mount);
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * @param ICachedMountInfo[] $newMounts
133
-	 * @param ICachedMountInfo[] $cachedMounts
134
-	 * @return ICachedMountInfo[]
135
-	 */
136
-	private function findChangedMounts(array $newMounts, array $cachedMounts) {
137
-		$changed = [];
138
-		foreach ($newMounts as $newMount) {
139
-			foreach ($cachedMounts as $cachedMount) {
140
-				if (
141
-					$newMount->getRootId() === $cachedMount->getRootId() &&
142
-					(
143
-						$newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
144
-						$newMount->getStorageId() !== $cachedMount->getStorageId() ||
145
-						$newMount->getMountId() !== $cachedMount->getMountId()
146
-					)
147
-				) {
148
-					$changed[] = $newMount;
149
-				}
150
-			}
151
-		}
152
-		return $changed;
153
-	}
154
-
155
-	private function addToCache(ICachedMountInfo $mount) {
156
-		if ($mount->getStorageId() !== -1) {
157
-			$this->connection->insertIfNotExist('*PREFIX*mounts', [
158
-				'storage_id' => $mount->getStorageId(),
159
-				'root_id' => $mount->getRootId(),
160
-				'user_id' => $mount->getUser()->getUID(),
161
-				'mount_point' => $mount->getMountPoint(),
162
-				'mount_id' => $mount->getMountId()
163
-			], ['root_id', 'user_id']);
164
-		} else {
165
-			// in some cases this is legitimate, like orphaned shares
166
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
167
-		}
168
-	}
169
-
170
-	private function updateCachedMount(ICachedMountInfo $mount) {
171
-		$builder = $this->connection->getQueryBuilder();
172
-
173
-		$query = $builder->update('mounts')
174
-			->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
175
-			->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
176
-			->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
177
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
178
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
179
-
180
-		$query->execute();
181
-	}
182
-
183
-	private function removeFromCache(ICachedMountInfo $mount) {
184
-		$builder = $this->connection->getQueryBuilder();
185
-
186
-		$query = $builder->delete('mounts')
187
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
188
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
189
-		$query->execute();
190
-	}
191
-
192
-	private function dbRowToMountInfo(array $row) {
193
-		$user = $this->userManager->get($row['user_id']);
194
-		if (is_null($user)) {
195
-			return null;
196
-		}
197
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
198
-	}
199
-
200
-	/**
201
-	 * @param IUser $user
202
-	 * @return ICachedMountInfo[]
203
-	 */
204
-	public function getMountsForUser(IUser $user) {
205
-		if (!isset($this->mountsForUsers[$user->getUID()])) {
206
-			$builder = $this->connection->getQueryBuilder();
207
-			$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
208
-				->from('mounts', 'm')
209
-				->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
210
-				->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
211
-
212
-			$rows = $query->execute()->fetchAll();
213
-
214
-			$this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
215
-		}
216
-		return $this->mountsForUsers[$user->getUID()];
217
-	}
218
-
219
-	/**
220
-	 * @param int $numericStorageId
221
-	 * @param string|null $user limit the results to a single user
222
-	 * @return CachedMountInfo[]
223
-	 */
224
-	public function getMountsForStorageId($numericStorageId, $user = null) {
225
-		$builder = $this->connection->getQueryBuilder();
226
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
227
-			->from('mounts', 'm')
228
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
229
-			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
230
-
231
-		if ($user) {
232
-			$query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
233
-		}
234
-
235
-		$rows = $query->execute()->fetchAll();
236
-
237
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
238
-	}
239
-
240
-	/**
241
-	 * @param int $rootFileId
242
-	 * @return CachedMountInfo[]
243
-	 */
244
-	public function getMountsForRootId($rootFileId) {
245
-		$builder = $this->connection->getQueryBuilder();
246
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
247
-			->from('mounts', 'm')
248
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
249
-			->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
250
-
251
-		$rows = $query->execute()->fetchAll();
252
-
253
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
254
-	}
255
-
256
-	/**
257
-	 * @param $fileId
258
-	 * @return array
259
-	 * @throws \OCP\Files\NotFoundException
260
-	 */
261
-	private function getCacheInfoFromFileId($fileId) {
262
-		if (!isset($this->cacheInfoCache[$fileId])) {
263
-			$builder = $this->connection->getQueryBuilder();
264
-			$query = $builder->select('storage', 'path', 'mimetype')
265
-				->from('filecache')
266
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
267
-
268
-			$row = $query->execute()->fetch();
269
-			if (is_array($row)) {
270
-				$this->cacheInfoCache[$fileId] = [
271
-					(int)$row['storage'],
272
-					$row['path'],
273
-					(int)$row['mimetype']
274
-				];
275
-			} else {
276
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
277
-			}
278
-		}
279
-		return $this->cacheInfoCache[$fileId];
280
-	}
281
-
282
-	/**
283
-	 * @param int $fileId
284
-	 * @param string|null $user optionally restrict the results to a single user
285
-	 * @return ICachedMountInfo[]
286
-	 * @since 9.0.0
287
-	 */
288
-	public function getMountsForFileId($fileId, $user = null) {
289
-		try {
290
-			list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
291
-		} catch (NotFoundException $e) {
292
-			return [];
293
-		}
294
-		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
295
-
296
-		// filter mounts that are from the same storage but a different directory
297
-		return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
298
-			if ($fileId === $mount->getRootId()) {
299
-				return true;
300
-			}
301
-			$internalMountPath = $mount->getRootInternalPath();
302
-
303
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
304
-		});
305
-	}
306
-
307
-	/**
308
-	 * Remove all cached mounts for a user
309
-	 *
310
-	 * @param IUser $user
311
-	 */
312
-	public function removeUserMounts(IUser $user) {
313
-		$builder = $this->connection->getQueryBuilder();
314
-
315
-		$query = $builder->delete('mounts')
316
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
317
-		$query->execute();
318
-	}
319
-
320
-	public function removeUserStorageMount($storageId, $userId) {
321
-		$builder = $this->connection->getQueryBuilder();
322
-
323
-		$query = $builder->delete('mounts')
324
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
325
-			->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
326
-		$query->execute();
327
-	}
328
-
329
-	public function remoteStorageMounts($storageId) {
330
-		$builder = $this->connection->getQueryBuilder();
331
-
332
-		$query = $builder->delete('mounts')
333
-			->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
334
-		$query->execute();
335
-	}
336
-
337
-	/**
338
-	 * @param array $users
339
-	 * @return array
340
-	 * @suppress SqlInjectionChecker
341
-	 */
342
-	public function getUsedSpaceForUsers(array $users) {
343
-		$builder = $this->connection->getQueryBuilder();
344
-
345
-		$slash = $builder->createNamedParameter('/');
346
-
347
-		$mountPoint = $builder->func()->concat(
348
-			$builder->func()->concat($slash, 'user_id'),
349
-			$slash
350
-		);
351
-
352
-		$userIds = array_map(function (IUser $user) {
353
-			return $user->getUID();
354
-		}, $users);
355
-
356
-		$query = $builder->select('m.user_id', 'f.size')
357
-			->from('mounts', 'm')
358
-			->innerJoin('m', 'filecache', 'f',
359
-				$builder->expr()->andX(
360
-					$builder->expr()->eq('m.storage_id', 'f.storage'),
361
-					$builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
362
-				))
363
-			->where($builder->expr()->eq('m.mount_point', $mountPoint))
364
-			->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
365
-
366
-		$result = $query->execute();
367
-
368
-		return $result->fetchAll(\PDO::FETCH_KEY_PAIR);
369
-	}
45
+    /**
46
+     * @var IDBConnection
47
+     */
48
+    private $connection;
49
+
50
+    /**
51
+     * @var IUserManager
52
+     */
53
+    private $userManager;
54
+
55
+    /**
56
+     * Cached mount info.
57
+     * Map of $userId to ICachedMountInfo.
58
+     *
59
+     * @var ICache
60
+     **/
61
+    private $mountsForUsers;
62
+
63
+    /**
64
+     * @var ILogger
65
+     */
66
+    private $logger;
67
+
68
+    /**
69
+     * @var ICache
70
+     */
71
+    private $cacheInfoCache;
72
+
73
+    /**
74
+     * UserMountCache constructor.
75
+     *
76
+     * @param IDBConnection $connection
77
+     * @param IUserManager $userManager
78
+     * @param ILogger $logger
79
+     */
80
+    public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
81
+        $this->connection = $connection;
82
+        $this->userManager = $userManager;
83
+        $this->logger = $logger;
84
+        $this->cacheInfoCache = new CappedMemoryCache();
85
+        $this->mountsForUsers = new CappedMemoryCache();
86
+    }
87
+
88
+    public function registerMounts(IUser $user, array $mounts) {
89
+        // filter out non-proper storages coming from unit tests
90
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
91
+            return $mount instanceof SharedMount || $mount->getStorage() && $mount->getStorage()->getCache();
92
+        });
93
+        /** @var ICachedMountInfo[] $newMounts */
94
+        $newMounts = array_map(function (IMountPoint $mount) use ($user) {
95
+            // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
96
+            if ($mount->getStorageRootId() === -1) {
97
+                return null;
98
+            } else {
99
+                return new LazyStorageMountInfo($user, $mount);
100
+            }
101
+        }, $mounts);
102
+        $newMounts = array_values(array_filter($newMounts));
103
+
104
+        $cachedMounts = $this->getMountsForUser($user);
105
+        $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
106
+            // since we are only looking for mounts for a specific user comparing on root id is enough
107
+            return $mount1->getRootId() - $mount2->getRootId();
108
+        };
109
+
110
+        /** @var ICachedMountInfo[] $addedMounts */
111
+        $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
112
+        /** @var ICachedMountInfo[] $removedMounts */
113
+        $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
114
+
115
+        $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
116
+
117
+        foreach ($addedMounts as $mount) {
118
+            $this->addToCache($mount);
119
+            $this->mountsForUsers[$user->getUID()][] = $mount;
120
+        }
121
+        foreach ($removedMounts as $mount) {
122
+            $this->removeFromCache($mount);
123
+            $index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
124
+            unset($this->mountsForUsers[$user->getUID()][$index]);
125
+        }
126
+        foreach ($changedMounts as $mount) {
127
+            $this->updateCachedMount($mount);
128
+        }
129
+    }
130
+
131
+    /**
132
+     * @param ICachedMountInfo[] $newMounts
133
+     * @param ICachedMountInfo[] $cachedMounts
134
+     * @return ICachedMountInfo[]
135
+     */
136
+    private function findChangedMounts(array $newMounts, array $cachedMounts) {
137
+        $changed = [];
138
+        foreach ($newMounts as $newMount) {
139
+            foreach ($cachedMounts as $cachedMount) {
140
+                if (
141
+                    $newMount->getRootId() === $cachedMount->getRootId() &&
142
+                    (
143
+                        $newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
144
+                        $newMount->getStorageId() !== $cachedMount->getStorageId() ||
145
+                        $newMount->getMountId() !== $cachedMount->getMountId()
146
+                    )
147
+                ) {
148
+                    $changed[] = $newMount;
149
+                }
150
+            }
151
+        }
152
+        return $changed;
153
+    }
154
+
155
+    private function addToCache(ICachedMountInfo $mount) {
156
+        if ($mount->getStorageId() !== -1) {
157
+            $this->connection->insertIfNotExist('*PREFIX*mounts', [
158
+                'storage_id' => $mount->getStorageId(),
159
+                'root_id' => $mount->getRootId(),
160
+                'user_id' => $mount->getUser()->getUID(),
161
+                'mount_point' => $mount->getMountPoint(),
162
+                'mount_id' => $mount->getMountId()
163
+            ], ['root_id', 'user_id']);
164
+        } else {
165
+            // in some cases this is legitimate, like orphaned shares
166
+            $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
167
+        }
168
+    }
169
+
170
+    private function updateCachedMount(ICachedMountInfo $mount) {
171
+        $builder = $this->connection->getQueryBuilder();
172
+
173
+        $query = $builder->update('mounts')
174
+            ->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
175
+            ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
176
+            ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
177
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
178
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
179
+
180
+        $query->execute();
181
+    }
182
+
183
+    private function removeFromCache(ICachedMountInfo $mount) {
184
+        $builder = $this->connection->getQueryBuilder();
185
+
186
+        $query = $builder->delete('mounts')
187
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
188
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
189
+        $query->execute();
190
+    }
191
+
192
+    private function dbRowToMountInfo(array $row) {
193
+        $user = $this->userManager->get($row['user_id']);
194
+        if (is_null($user)) {
195
+            return null;
196
+        }
197
+        return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
198
+    }
199
+
200
+    /**
201
+     * @param IUser $user
202
+     * @return ICachedMountInfo[]
203
+     */
204
+    public function getMountsForUser(IUser $user) {
205
+        if (!isset($this->mountsForUsers[$user->getUID()])) {
206
+            $builder = $this->connection->getQueryBuilder();
207
+            $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
208
+                ->from('mounts', 'm')
209
+                ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
210
+                ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
211
+
212
+            $rows = $query->execute()->fetchAll();
213
+
214
+            $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
215
+        }
216
+        return $this->mountsForUsers[$user->getUID()];
217
+    }
218
+
219
+    /**
220
+     * @param int $numericStorageId
221
+     * @param string|null $user limit the results to a single user
222
+     * @return CachedMountInfo[]
223
+     */
224
+    public function getMountsForStorageId($numericStorageId, $user = null) {
225
+        $builder = $this->connection->getQueryBuilder();
226
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
227
+            ->from('mounts', 'm')
228
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
229
+            ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
230
+
231
+        if ($user) {
232
+            $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
233
+        }
234
+
235
+        $rows = $query->execute()->fetchAll();
236
+
237
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
238
+    }
239
+
240
+    /**
241
+     * @param int $rootFileId
242
+     * @return CachedMountInfo[]
243
+     */
244
+    public function getMountsForRootId($rootFileId) {
245
+        $builder = $this->connection->getQueryBuilder();
246
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
247
+            ->from('mounts', 'm')
248
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
249
+            ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
250
+
251
+        $rows = $query->execute()->fetchAll();
252
+
253
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
254
+    }
255
+
256
+    /**
257
+     * @param $fileId
258
+     * @return array
259
+     * @throws \OCP\Files\NotFoundException
260
+     */
261
+    private function getCacheInfoFromFileId($fileId) {
262
+        if (!isset($this->cacheInfoCache[$fileId])) {
263
+            $builder = $this->connection->getQueryBuilder();
264
+            $query = $builder->select('storage', 'path', 'mimetype')
265
+                ->from('filecache')
266
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
267
+
268
+            $row = $query->execute()->fetch();
269
+            if (is_array($row)) {
270
+                $this->cacheInfoCache[$fileId] = [
271
+                    (int)$row['storage'],
272
+                    $row['path'],
273
+                    (int)$row['mimetype']
274
+                ];
275
+            } else {
276
+                throw new NotFoundException('File with id "' . $fileId . '" not found');
277
+            }
278
+        }
279
+        return $this->cacheInfoCache[$fileId];
280
+    }
281
+
282
+    /**
283
+     * @param int $fileId
284
+     * @param string|null $user optionally restrict the results to a single user
285
+     * @return ICachedMountInfo[]
286
+     * @since 9.0.0
287
+     */
288
+    public function getMountsForFileId($fileId, $user = null) {
289
+        try {
290
+            list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
291
+        } catch (NotFoundException $e) {
292
+            return [];
293
+        }
294
+        $mountsForStorage = $this->getMountsForStorageId($storageId, $user);
295
+
296
+        // filter mounts that are from the same storage but a different directory
297
+        return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
298
+            if ($fileId === $mount->getRootId()) {
299
+                return true;
300
+            }
301
+            $internalMountPath = $mount->getRootInternalPath();
302
+
303
+            return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
304
+        });
305
+    }
306
+
307
+    /**
308
+     * Remove all cached mounts for a user
309
+     *
310
+     * @param IUser $user
311
+     */
312
+    public function removeUserMounts(IUser $user) {
313
+        $builder = $this->connection->getQueryBuilder();
314
+
315
+        $query = $builder->delete('mounts')
316
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
317
+        $query->execute();
318
+    }
319
+
320
+    public function removeUserStorageMount($storageId, $userId) {
321
+        $builder = $this->connection->getQueryBuilder();
322
+
323
+        $query = $builder->delete('mounts')
324
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
325
+            ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
326
+        $query->execute();
327
+    }
328
+
329
+    public function remoteStorageMounts($storageId) {
330
+        $builder = $this->connection->getQueryBuilder();
331
+
332
+        $query = $builder->delete('mounts')
333
+            ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
334
+        $query->execute();
335
+    }
336
+
337
+    /**
338
+     * @param array $users
339
+     * @return array
340
+     * @suppress SqlInjectionChecker
341
+     */
342
+    public function getUsedSpaceForUsers(array $users) {
343
+        $builder = $this->connection->getQueryBuilder();
344
+
345
+        $slash = $builder->createNamedParameter('/');
346
+
347
+        $mountPoint = $builder->func()->concat(
348
+            $builder->func()->concat($slash, 'user_id'),
349
+            $slash
350
+        );
351
+
352
+        $userIds = array_map(function (IUser $user) {
353
+            return $user->getUID();
354
+        }, $users);
355
+
356
+        $query = $builder->select('m.user_id', 'f.size')
357
+            ->from('mounts', 'm')
358
+            ->innerJoin('m', 'filecache', 'f',
359
+                $builder->expr()->andX(
360
+                    $builder->expr()->eq('m.storage_id', 'f.storage'),
361
+                    $builder->expr()->eq('f.path', $builder->createNamedParameter('files'))
362
+                ))
363
+            ->where($builder->expr()->eq('m.mount_point', $mountPoint))
364
+            ->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
365
+
366
+        $result = $query->execute();
367
+
368
+        return $result->fetchAll(\PDO::FETCH_KEY_PAIR);
369
+    }
370 370
 }
Please login to merge, or discard this patch.
lib/private/Files/Node/LazyRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@
 block discarded – undo
52 52
 	 * Magic method to first get the real rootFolder and then
53 53
 	 * call $method with $args on it
54 54
 	 *
55
-	 * @param $method
55
+	 * @param string $method
56 56
 	 * @param $args
57 57
 	 * @return mixed
58 58
 	 */
Please login to merge, or discard this patch.
Indentation   +443 added lines, -443 removed lines patch added patch discarded remove patch
@@ -34,447 +34,447 @@
 block discarded – undo
34 34
  * @package OC\Files\Node
35 35
  */
36 36
 class LazyRoot implements IRootFolder {
37
-	/** @var \Closure */
38
-	private $rootFolderClosure;
39
-
40
-	/** @var IRootFolder */
41
-	private $rootFolder;
42
-
43
-	/**
44
-	 * LazyRoot constructor.
45
-	 *
46
-	 * @param \Closure $rootFolderClosure
47
-	 */
48
-	public function __construct(\Closure $rootFolderClosure) {
49
-		$this->rootFolderClosure = $rootFolderClosure;
50
-	}
51
-
52
-	/**
53
-	 * Magic method to first get the real rootFolder and then
54
-	 * call $method with $args on it
55
-	 *
56
-	 * @param $method
57
-	 * @param $args
58
-	 * @return mixed
59
-	 */
60
-	public function __call($method, $args) {
61
-		if ($this->rootFolder === null) {
62
-			$this->rootFolder = call_user_func($this->rootFolderClosure);
63
-		}
64
-
65
-		return call_user_func_array([$this->rootFolder, $method], $args);
66
-	}
67
-
68
-	/**
69
-	 * @inheritDoc
70
-	 */
71
-	public function getUser() {
72
-		return $this->__call(__FUNCTION__, func_get_args());
73
-	}
74
-
75
-	/**
76
-	 * @inheritDoc
77
-	 */
78
-	public function listen($scope, $method, callable $callback) {
79
-		$this->__call(__FUNCTION__, func_get_args());
80
-	}
81
-
82
-	/**
83
-	 * @inheritDoc
84
-	 */
85
-	public function removeListener($scope = null, $method = null, callable $callback = null) {
86
-		$this->__call(__FUNCTION__, func_get_args());
87
-	}
88
-
89
-	/**
90
-	 * @inheritDoc
91
-	 */
92
-	public function emit($scope, $method, $arguments = array()) {
93
-		$this->__call(__FUNCTION__, func_get_args());
94
-	}
95
-
96
-	/**
97
-	 * @inheritDoc
98
-	 */
99
-	public function mount($storage, $mountPoint, $arguments = array()) {
100
-		$this->__call(__FUNCTION__, func_get_args());
101
-	}
102
-
103
-	/**
104
-	 * @inheritDoc
105
-	 */
106
-	public function getMount($mountPoint) {
107
-		return $this->__call(__FUNCTION__, func_get_args());
108
-	}
109
-
110
-	/**
111
-	 * @inheritDoc
112
-	 */
113
-	public function getMountsIn($mountPoint) {
114
-		return $this->__call(__FUNCTION__, func_get_args());
115
-	}
116
-
117
-	/**
118
-	 * @inheritDoc
119
-	 */
120
-	public function getMountByStorageId($storageId) {
121
-		return $this->__call(__FUNCTION__, func_get_args());
122
-	}
123
-
124
-	/**
125
-	 * @inheritDoc
126
-	 */
127
-	public function getMountByNumericStorageId($numericId) {
128
-		return $this->__call(__FUNCTION__, func_get_args());
129
-	}
130
-
131
-	/**
132
-	 * @inheritDoc
133
-	 */
134
-	public function unMount($mount) {
135
-		$this->__call(__FUNCTION__, func_get_args());
136
-	}
137
-
138
-	/**
139
-	 * @inheritDoc
140
-	 */
141
-	public function get($path) {
142
-		return $this->__call(__FUNCTION__, func_get_args());
143
-	}
144
-
145
-	/**
146
-	 * @inheritDoc
147
-	 */
148
-	public function rename($targetPath) {
149
-		return $this->__call(__FUNCTION__, func_get_args());
150
-	}
151
-
152
-	/**
153
-	 * @inheritDoc
154
-	 */
155
-	public function delete() {
156
-		return $this->__call(__FUNCTION__, func_get_args());
157
-	}
158
-
159
-	/**
160
-	 * @inheritDoc
161
-	 */
162
-	public function copy($targetPath) {
163
-		return $this->__call(__FUNCTION__, func_get_args());
164
-	}
165
-
166
-	/**
167
-	 * @inheritDoc
168
-	 */
169
-	public function touch($mtime = null) {
170
-		$this->__call(__FUNCTION__, func_get_args());
171
-	}
172
-
173
-	/**
174
-	 * @inheritDoc
175
-	 */
176
-	public function getStorage() {
177
-		return $this->__call(__FUNCTION__, func_get_args());
178
-	}
179
-
180
-	/**
181
-	 * @inheritDoc
182
-	 */
183
-	public function getPath() {
184
-		return $this->__call(__FUNCTION__, func_get_args());
185
-	}
186
-
187
-	/**
188
-	 * @inheritDoc
189
-	 */
190
-	public function getInternalPath() {
191
-		return $this->__call(__FUNCTION__, func_get_args());
192
-	}
193
-
194
-	/**
195
-	 * @inheritDoc
196
-	 */
197
-	public function getId() {
198
-		return $this->__call(__FUNCTION__, func_get_args());
199
-	}
200
-
201
-	/**
202
-	 * @inheritDoc
203
-	 */
204
-	public function stat() {
205
-		return $this->__call(__FUNCTION__, func_get_args());
206
-	}
207
-
208
-	/**
209
-	 * @inheritDoc
210
-	 */
211
-	public function getMTime() {
212
-		return $this->__call(__FUNCTION__, func_get_args());
213
-	}
214
-
215
-	/**
216
-	 * @inheritDoc
217
-	 */
218
-	public function getSize() {
219
-		return $this->__call(__FUNCTION__, func_get_args());
220
-	}
221
-
222
-	/**
223
-	 * @inheritDoc
224
-	 */
225
-	public function getEtag() {
226
-		return $this->__call(__FUNCTION__, func_get_args());
227
-	}
228
-
229
-	/**
230
-	 * @inheritDoc
231
-	 */
232
-	public function getPermissions() {
233
-		return $this->__call(__FUNCTION__, func_get_args());
234
-	}
235
-
236
-	/**
237
-	 * @inheritDoc
238
-	 */
239
-	public function isReadable() {
240
-		return $this->__call(__FUNCTION__, func_get_args());
241
-	}
242
-
243
-	/**
244
-	 * @inheritDoc
245
-	 */
246
-	public function isUpdateable() {
247
-		return $this->__call(__FUNCTION__, func_get_args());
248
-	}
249
-
250
-	/**
251
-	 * @inheritDoc
252
-	 */
253
-	public function isDeletable() {
254
-		return $this->__call(__FUNCTION__, func_get_args());
255
-	}
256
-
257
-	/**
258
-	 * @inheritDoc
259
-	 */
260
-	public function isShareable() {
261
-		return $this->__call(__FUNCTION__, func_get_args());
262
-	}
263
-
264
-	/**
265
-	 * @inheritDoc
266
-	 */
267
-	public function getParent() {
268
-		return $this->__call(__FUNCTION__, func_get_args());
269
-	}
270
-
271
-	/**
272
-	 * @inheritDoc
273
-	 */
274
-	public function getName() {
275
-		return $this->__call(__FUNCTION__, func_get_args());
276
-	}
277
-
278
-	/**
279
-	 * @inheritDoc
280
-	 */
281
-	public function getUserFolder($userId) {
282
-		return $this->__call(__FUNCTION__, func_get_args());
283
-	}
284
-
285
-	/**
286
-	 * @inheritDoc
287
-	 */
288
-	public function getMimetype() {
289
-		return $this->__call(__FUNCTION__, func_get_args());
290
-	}
291
-
292
-	/**
293
-	 * @inheritDoc
294
-	 */
295
-	public function getMimePart() {
296
-		return $this->__call(__FUNCTION__, func_get_args());
297
-	}
298
-
299
-	/**
300
-	 * @inheritDoc
301
-	 */
302
-	public function isEncrypted() {
303
-		return $this->__call(__FUNCTION__, func_get_args());
304
-	}
305
-
306
-	/**
307
-	 * @inheritDoc
308
-	 */
309
-	public function getType() {
310
-		return $this->__call(__FUNCTION__, func_get_args());
311
-	}
312
-
313
-	/**
314
-	 * @inheritDoc
315
-	 */
316
-	public function isShared() {
317
-		return $this->__call(__FUNCTION__, func_get_args());
318
-	}
319
-
320
-	/**
321
-	 * @inheritDoc
322
-	 */
323
-	public function isMounted() {
324
-		return $this->__call(__FUNCTION__, func_get_args());
325
-	}
326
-
327
-	/**
328
-	 * @inheritDoc
329
-	 */
330
-	public function getMountPoint() {
331
-		return $this->__call(__FUNCTION__, func_get_args());
332
-	}
333
-
334
-	/**
335
-	 * @inheritDoc
336
-	 */
337
-	public function getOwner() {
338
-		return $this->__call(__FUNCTION__, func_get_args());
339
-	}
340
-
341
-	/**
342
-	 * @inheritDoc
343
-	 */
344
-	public function getChecksum() {
345
-		return $this->__call(__FUNCTION__, func_get_args());
346
-	}
347
-
348
-	/**
349
-	 * @inheritDoc
350
-	 */
351
-	public function getFullPath($path) {
352
-		return $this->__call(__FUNCTION__, func_get_args());
353
-	}
354
-
355
-	/**
356
-	 * @inheritDoc
357
-	 */
358
-	public function getRelativePath($path) {
359
-		return $this->__call(__FUNCTION__, func_get_args());
360
-	}
361
-
362
-	/**
363
-	 * @inheritDoc
364
-	 */
365
-	public function isSubNode($node) {
366
-		return $this->__call(__FUNCTION__, func_get_args());
367
-	}
368
-
369
-	/**
370
-	 * @inheritDoc
371
-	 */
372
-	public function getDirectoryListing() {
373
-		return $this->__call(__FUNCTION__, func_get_args());
374
-	}
375
-
376
-	/**
377
-	 * @inheritDoc
378
-	 */
379
-	public function nodeExists($path) {
380
-		return $this->__call(__FUNCTION__, func_get_args());
381
-	}
382
-
383
-	/**
384
-	 * @inheritDoc
385
-	 */
386
-	public function newFolder($path) {
387
-		return $this->__call(__FUNCTION__, func_get_args());
388
-	}
389
-
390
-	/**
391
-	 * @inheritDoc
392
-	 */
393
-	public function newFile($path) {
394
-		return $this->__call(__FUNCTION__, func_get_args());
395
-	}
396
-
397
-	/**
398
-	 * @inheritDoc
399
-	 */
400
-	public function search($query) {
401
-		return $this->__call(__FUNCTION__, func_get_args());
402
-	}
403
-
404
-	/**
405
-	 * @inheritDoc
406
-	 */
407
-	public function searchByMime($mimetype) {
408
-		return $this->__call(__FUNCTION__, func_get_args());
409
-	}
410
-
411
-	/**
412
-	 * @inheritDoc
413
-	 */
414
-	public function searchByTag($tag, $userId) {
415
-		return $this->__call(__FUNCTION__, func_get_args());
416
-	}
417
-
418
-	/**
419
-	 * @inheritDoc
420
-	 */
421
-	public function getById($id) {
422
-		return $this->__call(__FUNCTION__, func_get_args());
423
-	}
424
-
425
-	/**
426
-	 * @inheritDoc
427
-	 */
428
-	public function getFreeSpace() {
429
-		return $this->__call(__FUNCTION__, func_get_args());
430
-	}
431
-
432
-	/**
433
-	 * @inheritDoc
434
-	 */
435
-	public function isCreatable() {
436
-		return $this->__call(__FUNCTION__, func_get_args());
437
-	}
438
-
439
-	/**
440
-	 * @inheritDoc
441
-	 */
442
-	public function getNonExistingName($name) {
443
-		return $this->__call(__FUNCTION__, func_get_args());
444
-	}
445
-
446
-	/**
447
-	 * @inheritDoc
448
-	 */
449
-	public function move($targetPath) {
450
-		return $this->__call(__FUNCTION__, func_get_args());
451
-	}
452
-
453
-	/**
454
-	 * @inheritDoc
455
-	 */
456
-	public function lock($type) {
457
-		return $this->__call(__FUNCTION__, func_get_args());
458
-	}
459
-
460
-	/**
461
-	 * @inheritDoc
462
-	 */
463
-	public function changeLock($targetType) {
464
-		return $this->__call(__FUNCTION__, func_get_args());
465
-	}
466
-
467
-	/**
468
-	 * @inheritDoc
469
-	 */
470
-	public function unlock($type) {
471
-		return $this->__call(__FUNCTION__, func_get_args());
472
-	}
473
-
474
-	/**
475
-	 * @inheritDoc
476
-	 */
477
-	public function getRecent($limit, $offset = 0) {
478
-		return $this->__call(__FUNCTION__, func_get_args());
479
-	}
37
+    /** @var \Closure */
38
+    private $rootFolderClosure;
39
+
40
+    /** @var IRootFolder */
41
+    private $rootFolder;
42
+
43
+    /**
44
+     * LazyRoot constructor.
45
+     *
46
+     * @param \Closure $rootFolderClosure
47
+     */
48
+    public function __construct(\Closure $rootFolderClosure) {
49
+        $this->rootFolderClosure = $rootFolderClosure;
50
+    }
51
+
52
+    /**
53
+     * Magic method to first get the real rootFolder and then
54
+     * call $method with $args on it
55
+     *
56
+     * @param $method
57
+     * @param $args
58
+     * @return mixed
59
+     */
60
+    public function __call($method, $args) {
61
+        if ($this->rootFolder === null) {
62
+            $this->rootFolder = call_user_func($this->rootFolderClosure);
63
+        }
64
+
65
+        return call_user_func_array([$this->rootFolder, $method], $args);
66
+    }
67
+
68
+    /**
69
+     * @inheritDoc
70
+     */
71
+    public function getUser() {
72
+        return $this->__call(__FUNCTION__, func_get_args());
73
+    }
74
+
75
+    /**
76
+     * @inheritDoc
77
+     */
78
+    public function listen($scope, $method, callable $callback) {
79
+        $this->__call(__FUNCTION__, func_get_args());
80
+    }
81
+
82
+    /**
83
+     * @inheritDoc
84
+     */
85
+    public function removeListener($scope = null, $method = null, callable $callback = null) {
86
+        $this->__call(__FUNCTION__, func_get_args());
87
+    }
88
+
89
+    /**
90
+     * @inheritDoc
91
+     */
92
+    public function emit($scope, $method, $arguments = array()) {
93
+        $this->__call(__FUNCTION__, func_get_args());
94
+    }
95
+
96
+    /**
97
+     * @inheritDoc
98
+     */
99
+    public function mount($storage, $mountPoint, $arguments = array()) {
100
+        $this->__call(__FUNCTION__, func_get_args());
101
+    }
102
+
103
+    /**
104
+     * @inheritDoc
105
+     */
106
+    public function getMount($mountPoint) {
107
+        return $this->__call(__FUNCTION__, func_get_args());
108
+    }
109
+
110
+    /**
111
+     * @inheritDoc
112
+     */
113
+    public function getMountsIn($mountPoint) {
114
+        return $this->__call(__FUNCTION__, func_get_args());
115
+    }
116
+
117
+    /**
118
+     * @inheritDoc
119
+     */
120
+    public function getMountByStorageId($storageId) {
121
+        return $this->__call(__FUNCTION__, func_get_args());
122
+    }
123
+
124
+    /**
125
+     * @inheritDoc
126
+     */
127
+    public function getMountByNumericStorageId($numericId) {
128
+        return $this->__call(__FUNCTION__, func_get_args());
129
+    }
130
+
131
+    /**
132
+     * @inheritDoc
133
+     */
134
+    public function unMount($mount) {
135
+        $this->__call(__FUNCTION__, func_get_args());
136
+    }
137
+
138
+    /**
139
+     * @inheritDoc
140
+     */
141
+    public function get($path) {
142
+        return $this->__call(__FUNCTION__, func_get_args());
143
+    }
144
+
145
+    /**
146
+     * @inheritDoc
147
+     */
148
+    public function rename($targetPath) {
149
+        return $this->__call(__FUNCTION__, func_get_args());
150
+    }
151
+
152
+    /**
153
+     * @inheritDoc
154
+     */
155
+    public function delete() {
156
+        return $this->__call(__FUNCTION__, func_get_args());
157
+    }
158
+
159
+    /**
160
+     * @inheritDoc
161
+     */
162
+    public function copy($targetPath) {
163
+        return $this->__call(__FUNCTION__, func_get_args());
164
+    }
165
+
166
+    /**
167
+     * @inheritDoc
168
+     */
169
+    public function touch($mtime = null) {
170
+        $this->__call(__FUNCTION__, func_get_args());
171
+    }
172
+
173
+    /**
174
+     * @inheritDoc
175
+     */
176
+    public function getStorage() {
177
+        return $this->__call(__FUNCTION__, func_get_args());
178
+    }
179
+
180
+    /**
181
+     * @inheritDoc
182
+     */
183
+    public function getPath() {
184
+        return $this->__call(__FUNCTION__, func_get_args());
185
+    }
186
+
187
+    /**
188
+     * @inheritDoc
189
+     */
190
+    public function getInternalPath() {
191
+        return $this->__call(__FUNCTION__, func_get_args());
192
+    }
193
+
194
+    /**
195
+     * @inheritDoc
196
+     */
197
+    public function getId() {
198
+        return $this->__call(__FUNCTION__, func_get_args());
199
+    }
200
+
201
+    /**
202
+     * @inheritDoc
203
+     */
204
+    public function stat() {
205
+        return $this->__call(__FUNCTION__, func_get_args());
206
+    }
207
+
208
+    /**
209
+     * @inheritDoc
210
+     */
211
+    public function getMTime() {
212
+        return $this->__call(__FUNCTION__, func_get_args());
213
+    }
214
+
215
+    /**
216
+     * @inheritDoc
217
+     */
218
+    public function getSize() {
219
+        return $this->__call(__FUNCTION__, func_get_args());
220
+    }
221
+
222
+    /**
223
+     * @inheritDoc
224
+     */
225
+    public function getEtag() {
226
+        return $this->__call(__FUNCTION__, func_get_args());
227
+    }
228
+
229
+    /**
230
+     * @inheritDoc
231
+     */
232
+    public function getPermissions() {
233
+        return $this->__call(__FUNCTION__, func_get_args());
234
+    }
235
+
236
+    /**
237
+     * @inheritDoc
238
+     */
239
+    public function isReadable() {
240
+        return $this->__call(__FUNCTION__, func_get_args());
241
+    }
242
+
243
+    /**
244
+     * @inheritDoc
245
+     */
246
+    public function isUpdateable() {
247
+        return $this->__call(__FUNCTION__, func_get_args());
248
+    }
249
+
250
+    /**
251
+     * @inheritDoc
252
+     */
253
+    public function isDeletable() {
254
+        return $this->__call(__FUNCTION__, func_get_args());
255
+    }
256
+
257
+    /**
258
+     * @inheritDoc
259
+     */
260
+    public function isShareable() {
261
+        return $this->__call(__FUNCTION__, func_get_args());
262
+    }
263
+
264
+    /**
265
+     * @inheritDoc
266
+     */
267
+    public function getParent() {
268
+        return $this->__call(__FUNCTION__, func_get_args());
269
+    }
270
+
271
+    /**
272
+     * @inheritDoc
273
+     */
274
+    public function getName() {
275
+        return $this->__call(__FUNCTION__, func_get_args());
276
+    }
277
+
278
+    /**
279
+     * @inheritDoc
280
+     */
281
+    public function getUserFolder($userId) {
282
+        return $this->__call(__FUNCTION__, func_get_args());
283
+    }
284
+
285
+    /**
286
+     * @inheritDoc
287
+     */
288
+    public function getMimetype() {
289
+        return $this->__call(__FUNCTION__, func_get_args());
290
+    }
291
+
292
+    /**
293
+     * @inheritDoc
294
+     */
295
+    public function getMimePart() {
296
+        return $this->__call(__FUNCTION__, func_get_args());
297
+    }
298
+
299
+    /**
300
+     * @inheritDoc
301
+     */
302
+    public function isEncrypted() {
303
+        return $this->__call(__FUNCTION__, func_get_args());
304
+    }
305
+
306
+    /**
307
+     * @inheritDoc
308
+     */
309
+    public function getType() {
310
+        return $this->__call(__FUNCTION__, func_get_args());
311
+    }
312
+
313
+    /**
314
+     * @inheritDoc
315
+     */
316
+    public function isShared() {
317
+        return $this->__call(__FUNCTION__, func_get_args());
318
+    }
319
+
320
+    /**
321
+     * @inheritDoc
322
+     */
323
+    public function isMounted() {
324
+        return $this->__call(__FUNCTION__, func_get_args());
325
+    }
326
+
327
+    /**
328
+     * @inheritDoc
329
+     */
330
+    public function getMountPoint() {
331
+        return $this->__call(__FUNCTION__, func_get_args());
332
+    }
333
+
334
+    /**
335
+     * @inheritDoc
336
+     */
337
+    public function getOwner() {
338
+        return $this->__call(__FUNCTION__, func_get_args());
339
+    }
340
+
341
+    /**
342
+     * @inheritDoc
343
+     */
344
+    public function getChecksum() {
345
+        return $this->__call(__FUNCTION__, func_get_args());
346
+    }
347
+
348
+    /**
349
+     * @inheritDoc
350
+     */
351
+    public function getFullPath($path) {
352
+        return $this->__call(__FUNCTION__, func_get_args());
353
+    }
354
+
355
+    /**
356
+     * @inheritDoc
357
+     */
358
+    public function getRelativePath($path) {
359
+        return $this->__call(__FUNCTION__, func_get_args());
360
+    }
361
+
362
+    /**
363
+     * @inheritDoc
364
+     */
365
+    public function isSubNode($node) {
366
+        return $this->__call(__FUNCTION__, func_get_args());
367
+    }
368
+
369
+    /**
370
+     * @inheritDoc
371
+     */
372
+    public function getDirectoryListing() {
373
+        return $this->__call(__FUNCTION__, func_get_args());
374
+    }
375
+
376
+    /**
377
+     * @inheritDoc
378
+     */
379
+    public function nodeExists($path) {
380
+        return $this->__call(__FUNCTION__, func_get_args());
381
+    }
382
+
383
+    /**
384
+     * @inheritDoc
385
+     */
386
+    public function newFolder($path) {
387
+        return $this->__call(__FUNCTION__, func_get_args());
388
+    }
389
+
390
+    /**
391
+     * @inheritDoc
392
+     */
393
+    public function newFile($path) {
394
+        return $this->__call(__FUNCTION__, func_get_args());
395
+    }
396
+
397
+    /**
398
+     * @inheritDoc
399
+     */
400
+    public function search($query) {
401
+        return $this->__call(__FUNCTION__, func_get_args());
402
+    }
403
+
404
+    /**
405
+     * @inheritDoc
406
+     */
407
+    public function searchByMime($mimetype) {
408
+        return $this->__call(__FUNCTION__, func_get_args());
409
+    }
410
+
411
+    /**
412
+     * @inheritDoc
413
+     */
414
+    public function searchByTag($tag, $userId) {
415
+        return $this->__call(__FUNCTION__, func_get_args());
416
+    }
417
+
418
+    /**
419
+     * @inheritDoc
420
+     */
421
+    public function getById($id) {
422
+        return $this->__call(__FUNCTION__, func_get_args());
423
+    }
424
+
425
+    /**
426
+     * @inheritDoc
427
+     */
428
+    public function getFreeSpace() {
429
+        return $this->__call(__FUNCTION__, func_get_args());
430
+    }
431
+
432
+    /**
433
+     * @inheritDoc
434
+     */
435
+    public function isCreatable() {
436
+        return $this->__call(__FUNCTION__, func_get_args());
437
+    }
438
+
439
+    /**
440
+     * @inheritDoc
441
+     */
442
+    public function getNonExistingName($name) {
443
+        return $this->__call(__FUNCTION__, func_get_args());
444
+    }
445
+
446
+    /**
447
+     * @inheritDoc
448
+     */
449
+    public function move($targetPath) {
450
+        return $this->__call(__FUNCTION__, func_get_args());
451
+    }
452
+
453
+    /**
454
+     * @inheritDoc
455
+     */
456
+    public function lock($type) {
457
+        return $this->__call(__FUNCTION__, func_get_args());
458
+    }
459
+
460
+    /**
461
+     * @inheritDoc
462
+     */
463
+    public function changeLock($targetType) {
464
+        return $this->__call(__FUNCTION__, func_get_args());
465
+    }
466
+
467
+    /**
468
+     * @inheritDoc
469
+     */
470
+    public function unlock($type) {
471
+        return $this->__call(__FUNCTION__, func_get_args());
472
+    }
473
+
474
+    /**
475
+     * @inheritDoc
476
+     */
477
+    public function getRecent($limit, $offset = 0) {
478
+        return $this->__call(__FUNCTION__, func_get_args());
479
+    }
480 480
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Flysystem.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -54,6 +54,9 @@
 block discarded – undo
54 54
 		$this->flysystem->addPlugin(new GetWithMetadata());
55 55
 	}
56 56
 
57
+	/**
58
+	 * @param string $path
59
+	 */
57 60
 	protected function buildPath($path) {
58 61
 		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59 62
 		return ltrim($fullPath, '/');
Please login to merge, or discard this patch.
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -35,223 +35,223 @@
 block discarded – undo
35 35
  * To use: subclass and call $this->buildFlysystem with the flysystem adapter of choice
36 36
  */
37 37
 abstract class Flysystem extends Common {
38
-	/**
39
-	 * @var Filesystem
40
-	 */
41
-	protected $flysystem;
38
+    /**
39
+     * @var Filesystem
40
+     */
41
+    protected $flysystem;
42 42
 
43
-	/**
44
-	 * @var string
45
-	 */
46
-	protected $root = '';
43
+    /**
44
+     * @var string
45
+     */
46
+    protected $root = '';
47 47
 
48
-	/**
49
-	 * Initialize the storage backend with a flyssytem adapter
50
-	 *
51
-	 * @param \League\Flysystem\AdapterInterface $adapter
52
-	 */
53
-	protected function buildFlySystem(AdapterInterface $adapter) {
54
-		$this->flysystem = new Filesystem($adapter);
55
-		$this->flysystem->addPlugin(new GetWithMetadata());
56
-	}
48
+    /**
49
+     * Initialize the storage backend with a flyssytem adapter
50
+     *
51
+     * @param \League\Flysystem\AdapterInterface $adapter
52
+     */
53
+    protected function buildFlySystem(AdapterInterface $adapter) {
54
+        $this->flysystem = new Filesystem($adapter);
55
+        $this->flysystem->addPlugin(new GetWithMetadata());
56
+    }
57 57
 
58
-	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
-		return ltrim($fullPath, '/');
61
-	}
58
+    protected function buildPath($path) {
59
+        $fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
60
+        return ltrim($fullPath, '/');
61
+    }
62 62
 
63
-	/**
64
-	 * {@inheritdoc}
65
-	 */
66
-	public function file_get_contents($path) {
67
-		return $this->flysystem->read($this->buildPath($path));
68
-	}
63
+    /**
64
+     * {@inheritdoc}
65
+     */
66
+    public function file_get_contents($path) {
67
+        return $this->flysystem->read($this->buildPath($path));
68
+    }
69 69
 
70
-	/**
71
-	 * {@inheritdoc}
72
-	 */
73
-	public function file_put_contents($path, $data) {
74
-		return $this->flysystem->put($this->buildPath($path), $data);
75
-	}
70
+    /**
71
+     * {@inheritdoc}
72
+     */
73
+    public function file_put_contents($path, $data) {
74
+        return $this->flysystem->put($this->buildPath($path), $data);
75
+    }
76 76
 
77
-	/**
78
-	 * {@inheritdoc}
79
-	 */
80
-	public function file_exists($path) {
81
-		return $this->flysystem->has($this->buildPath($path));
82
-	}
77
+    /**
78
+     * {@inheritdoc}
79
+     */
80
+    public function file_exists($path) {
81
+        return $this->flysystem->has($this->buildPath($path));
82
+    }
83 83
 
84
-	/**
85
-	 * {@inheritdoc}
86
-	 */
87
-	public function unlink($path) {
88
-		if ($this->is_dir($path)) {
89
-			return $this->rmdir($path);
90
-		}
91
-		try {
92
-			return $this->flysystem->delete($this->buildPath($path));
93
-		} catch (FileNotFoundException $e) {
94
-			return false;
95
-		}
96
-	}
84
+    /**
85
+     * {@inheritdoc}
86
+     */
87
+    public function unlink($path) {
88
+        if ($this->is_dir($path)) {
89
+            return $this->rmdir($path);
90
+        }
91
+        try {
92
+            return $this->flysystem->delete($this->buildPath($path));
93
+        } catch (FileNotFoundException $e) {
94
+            return false;
95
+        }
96
+    }
97 97
 
98
-	/**
99
-	 * {@inheritdoc}
100
-	 */
101
-	public function rename($source, $target) {
102
-		if ($this->file_exists($target)) {
103
-			$this->unlink($target);
104
-		}
105
-		return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
-	}
98
+    /**
99
+     * {@inheritdoc}
100
+     */
101
+    public function rename($source, $target) {
102
+        if ($this->file_exists($target)) {
103
+            $this->unlink($target);
104
+        }
105
+        return $this->flysystem->rename($this->buildPath($source), $this->buildPath($target));
106
+    }
107 107
 
108
-	/**
109
-	 * {@inheritdoc}
110
-	 */
111
-	public function copy($source, $target) {
112
-		if ($this->file_exists($target)) {
113
-			$this->unlink($target);
114
-		}
115
-		return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
-	}
108
+    /**
109
+     * {@inheritdoc}
110
+     */
111
+    public function copy($source, $target) {
112
+        if ($this->file_exists($target)) {
113
+            $this->unlink($target);
114
+        }
115
+        return $this->flysystem->copy($this->buildPath($source), $this->buildPath($target));
116
+    }
117 117
 
118
-	/**
119
-	 * {@inheritdoc}
120
-	 */
121
-	public function filesize($path) {
122
-		if ($this->is_dir($path)) {
123
-			return 0;
124
-		} else {
125
-			return $this->flysystem->getSize($this->buildPath($path));
126
-		}
127
-	}
118
+    /**
119
+     * {@inheritdoc}
120
+     */
121
+    public function filesize($path) {
122
+        if ($this->is_dir($path)) {
123
+            return 0;
124
+        } else {
125
+            return $this->flysystem->getSize($this->buildPath($path));
126
+        }
127
+    }
128 128
 
129
-	/**
130
-	 * {@inheritdoc}
131
-	 */
132
-	public function mkdir($path) {
133
-		if ($this->file_exists($path)) {
134
-			return false;
135
-		}
136
-		return $this->flysystem->createDir($this->buildPath($path));
137
-	}
129
+    /**
130
+     * {@inheritdoc}
131
+     */
132
+    public function mkdir($path) {
133
+        if ($this->file_exists($path)) {
134
+            return false;
135
+        }
136
+        return $this->flysystem->createDir($this->buildPath($path));
137
+    }
138 138
 
139
-	/**
140
-	 * {@inheritdoc}
141
-	 */
142
-	public function filemtime($path) {
143
-		return $this->flysystem->getTimestamp($this->buildPath($path));
144
-	}
139
+    /**
140
+     * {@inheritdoc}
141
+     */
142
+    public function filemtime($path) {
143
+        return $this->flysystem->getTimestamp($this->buildPath($path));
144
+    }
145 145
 
146
-	/**
147
-	 * {@inheritdoc}
148
-	 */
149
-	public function rmdir($path) {
150
-		try {
151
-			return @$this->flysystem->deleteDir($this->buildPath($path));
152
-		} catch (FileNotFoundException $e) {
153
-			return false;
154
-		}
155
-	}
146
+    /**
147
+     * {@inheritdoc}
148
+     */
149
+    public function rmdir($path) {
150
+        try {
151
+            return @$this->flysystem->deleteDir($this->buildPath($path));
152
+        } catch (FileNotFoundException $e) {
153
+            return false;
154
+        }
155
+    }
156 156
 
157
-	/**
158
-	 * {@inheritdoc}
159
-	 */
160
-	public function opendir($path) {
161
-		try {
162
-			$content = $this->flysystem->listContents($this->buildPath($path));
163
-		} catch (FileNotFoundException $e) {
164
-			return false;
165
-		}
166
-		$names = array_map(function ($object) {
167
-			return $object['basename'];
168
-		}, $content);
169
-		return IteratorDirectory::wrap($names);
170
-	}
157
+    /**
158
+     * {@inheritdoc}
159
+     */
160
+    public function opendir($path) {
161
+        try {
162
+            $content = $this->flysystem->listContents($this->buildPath($path));
163
+        } catch (FileNotFoundException $e) {
164
+            return false;
165
+        }
166
+        $names = array_map(function ($object) {
167
+            return $object['basename'];
168
+        }, $content);
169
+        return IteratorDirectory::wrap($names);
170
+    }
171 171
 
172
-	/**
173
-	 * {@inheritdoc}
174
-	 */
175
-	public function fopen($path, $mode) {
176
-		$fullPath = $this->buildPath($path);
177
-		$useExisting = true;
178
-		switch ($mode) {
179
-			case 'r':
180
-			case 'rb':
181
-				try {
182
-					return $this->flysystem->readStream($fullPath);
183
-				} catch (FileNotFoundException $e) {
184
-					return false;
185
-				}
186
-			case 'w':
187
-			case 'w+':
188
-			case 'wb':
189
-			case 'wb+':
190
-				$useExisting = false;
191
-			case 'a':
192
-			case 'ab':
193
-			case 'r+':
194
-			case 'a+':
195
-			case 'x':
196
-			case 'x+':
197
-			case 'c':
198
-			case 'c+':
199
-				//emulate these
200
-				if ($useExisting and $this->file_exists($path)) {
201
-					if (!$this->isUpdatable($path)) {
202
-						return false;
203
-					}
204
-					$tmpFile = $this->getCachedFile($path);
205
-				} else {
206
-					if (!$this->isCreatable(dirname($path))) {
207
-						return false;
208
-					}
209
-					$tmpFile = \OCP\Files::tmpFile();
210
-				}
211
-				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
-					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
-					unlink($tmpFile);
215
-				});
216
-		}
217
-		return false;
218
-	}
172
+    /**
173
+     * {@inheritdoc}
174
+     */
175
+    public function fopen($path, $mode) {
176
+        $fullPath = $this->buildPath($path);
177
+        $useExisting = true;
178
+        switch ($mode) {
179
+            case 'r':
180
+            case 'rb':
181
+                try {
182
+                    return $this->flysystem->readStream($fullPath);
183
+                } catch (FileNotFoundException $e) {
184
+                    return false;
185
+                }
186
+            case 'w':
187
+            case 'w+':
188
+            case 'wb':
189
+            case 'wb+':
190
+                $useExisting = false;
191
+            case 'a':
192
+            case 'ab':
193
+            case 'r+':
194
+            case 'a+':
195
+            case 'x':
196
+            case 'x+':
197
+            case 'c':
198
+            case 'c+':
199
+                //emulate these
200
+                if ($useExisting and $this->file_exists($path)) {
201
+                    if (!$this->isUpdatable($path)) {
202
+                        return false;
203
+                    }
204
+                    $tmpFile = $this->getCachedFile($path);
205
+                } else {
206
+                    if (!$this->isCreatable(dirname($path))) {
207
+                        return false;
208
+                    }
209
+                    $tmpFile = \OCP\Files::tmpFile();
210
+                }
211
+                $source = fopen($tmpFile, $mode);
212
+                return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
213
+                    $this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214
+                    unlink($tmpFile);
215
+                });
216
+        }
217
+        return false;
218
+    }
219 219
 
220
-	/**
221
-	 * {@inheritdoc}
222
-	 */
223
-	public function touch($path, $mtime = null) {
224
-		if ($this->file_exists($path)) {
225
-			return false;
226
-		} else {
227
-			$this->file_put_contents($path, '');
228
-			return true;
229
-		}
230
-	}
220
+    /**
221
+     * {@inheritdoc}
222
+     */
223
+    public function touch($path, $mtime = null) {
224
+        if ($this->file_exists($path)) {
225
+            return false;
226
+        } else {
227
+            $this->file_put_contents($path, '');
228
+            return true;
229
+        }
230
+    }
231 231
 
232
-	/**
233
-	 * {@inheritdoc}
234
-	 */
235
-	public function stat($path) {
236
-		$info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
-		return [
238
-			'mtime' => $info['timestamp'],
239
-			'size' => $info['size']
240
-		];
241
-	}
232
+    /**
233
+     * {@inheritdoc}
234
+     */
235
+    public function stat($path) {
236
+        $info = $this->flysystem->getWithMetadata($this->buildPath($path), ['timestamp', 'size']);
237
+        return [
238
+            'mtime' => $info['timestamp'],
239
+            'size' => $info['size']
240
+        ];
241
+    }
242 242
 
243
-	/**
244
-	 * {@inheritdoc}
245
-	 */
246
-	public function filetype($path) {
247
-		if ($path === '' or $path === '/' or $path === '.') {
248
-			return 'dir';
249
-		}
250
-		try {
251
-			$info = $this->flysystem->getMetadata($this->buildPath($path));
252
-		} catch (FileNotFoundException $e) {
253
-			return false;
254
-		}
255
-		return $info['type'];
256
-	}
243
+    /**
244
+     * {@inheritdoc}
245
+     */
246
+    public function filetype($path) {
247
+        if ($path === '' or $path === '/' or $path === '.') {
248
+            return 'dir';
249
+        }
250
+        try {
251
+            $info = $this->flysystem->getMetadata($this->buildPath($path));
252
+        } catch (FileNotFoundException $e) {
253
+            return false;
254
+        }
255
+        return $info['type'];
256
+    }
257 257
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	}
57 57
 
58 58
 	protected function buildPath($path) {
59
-		$fullPath = \OC\Files\Filesystem::normalizePath($this->root . '/' . $path);
59
+		$fullPath = \OC\Files\Filesystem::normalizePath($this->root.'/'.$path);
60 60
 		return ltrim($fullPath, '/');
61 61
 	}
62 62
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		} catch (FileNotFoundException $e) {
164 164
 			return false;
165 165
 		}
166
-		$names = array_map(function ($object) {
166
+		$names = array_map(function($object) {
167 167
 			return $object['basename'];
168 168
 		}, $content);
169 169
 		return IteratorDirectory::wrap($names);
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 					$tmpFile = \OCP\Files::tmpFile();
210 210
 				}
211 211
 				$source = fopen($tmpFile, $mode);
212
-				return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath) {
212
+				return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath) {
213 213
 					$this->flysystem->putStream($fullPath, fopen($tmpFile, 'r'));
214 214
 					unlink($tmpFile);
215 215
 				});
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Quota.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -159,7 +159,7 @@
 block discarded – undo
159 159
 	 * Checks whether the given path is a part file
160 160
 	 *
161 161
 	 * @param string $path Path that may identify a .part file
162
-	 * @return string File path without .part extension
162
+	 * @return boolean File path without .part extension
163 163
 	 * @note this is needed for reusing keys
164 164
 	 */
165 165
 	private function isPartFile($path) {
Please login to merge, or discard this patch.
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -30,172 +30,172 @@
 block discarded – undo
30 30
 
31 31
 class Quota extends Wrapper {
32 32
 
33
-	/**
34
-	 * @var int $quota
35
-	 */
36
-	protected $quota;
37
-
38
-	/**
39
-	 * @var string $sizeRoot
40
-	 */
41
-	protected $sizeRoot;
42
-
43
-	/**
44
-	 * @param array $parameters
45
-	 */
46
-	public function __construct($parameters) {
47
-		$this->storage = $parameters['storage'];
48
-		$this->quota = $parameters['quota'];
49
-		$this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
-	}
51
-
52
-	/**
53
-	 * @return int quota value
54
-	 */
55
-	public function getQuota() {
56
-		return $this->quota;
57
-	}
58
-
59
-	/**
60
-	 * @param string $path
61
-	 * @param \OC\Files\Storage\Storage $storage
62
-	 */
63
-	protected function getSize($path, $storage = null) {
64
-		if (is_null($storage)) {
65
-			$cache = $this->getCache();
66
-		} else {
67
-			$cache = $storage->getCache();
68
-		}
69
-		$data = $cache->get($path);
70
-		if ($data instanceof ICacheEntry and isset($data['size'])) {
71
-			return $data['size'];
72
-		} else {
73
-			return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
-		}
75
-	}
76
-
77
-	/**
78
-	 * Get free space as limited by the quota
79
-	 *
80
-	 * @param string $path
81
-	 * @return int
82
-	 */
83
-	public function free_space($path) {
84
-		if ($this->quota < 0) {
85
-			return $this->storage->free_space($path);
86
-		} else {
87
-			$used = $this->getSize($this->sizeRoot);
88
-			if ($used < 0) {
89
-				return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
-			} else {
91
-				$free = $this->storage->free_space($path);
92
-				$quotaFree = max($this->quota - $used, 0);
93
-				// if free space is known
94
-				if ($free >= 0) {
95
-					$free = min($free, $quotaFree);
96
-				} else {
97
-					$free = $quotaFree;
98
-				}
99
-				return $free;
100
-			}
101
-		}
102
-	}
103
-
104
-	/**
105
-	 * see http://php.net/manual/en/function.file_put_contents.php
106
-	 *
107
-	 * @param string $path
108
-	 * @param string $data
109
-	 * @return bool
110
-	 */
111
-	public function file_put_contents($path, $data) {
112
-		$free = $this->free_space('');
113
-		if ($free < 0 or strlen($data) < $free) {
114
-			return $this->storage->file_put_contents($path, $data);
115
-		} else {
116
-			return false;
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * see http://php.net/manual/en/function.copy.php
122
-	 *
123
-	 * @param string $source
124
-	 * @param string $target
125
-	 * @return bool
126
-	 */
127
-	public function copy($source, $target) {
128
-		$free = $this->free_space('');
129
-		if ($free < 0 or $this->getSize($source) < $free) {
130
-			return $this->storage->copy($source, $target);
131
-		} else {
132
-			return false;
133
-		}
134
-	}
135
-
136
-	/**
137
-	 * see http://php.net/manual/en/function.fopen.php
138
-	 *
139
-	 * @param string $path
140
-	 * @param string $mode
141
-	 * @return resource
142
-	 */
143
-	public function fopen($path, $mode) {
144
-		$source = $this->storage->fopen($path, $mode);
145
-
146
-		// don't apply quota for part files
147
-		if (!$this->isPartFile($path)) {
148
-			$free = $this->free_space('');
149
-			if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
-				// only apply quota for files, not metadata, trash or others
151
-				if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
-					return \OC\Files\Stream\Quota::wrap($source, $free);
153
-				}
154
-			}
155
-		}
156
-		return $source;
157
-	}
158
-
159
-	/**
160
-	 * Checks whether the given path is a part file
161
-	 *
162
-	 * @param string $path Path that may identify a .part file
163
-	 * @return string File path without .part extension
164
-	 * @note this is needed for reusing keys
165
-	 */
166
-	private function isPartFile($path) {
167
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
168
-
169
-		return ($extension === 'part');
170
-	}
171
-
172
-	/**
173
-	 * @param \OCP\Files\Storage $sourceStorage
174
-	 * @param string $sourceInternalPath
175
-	 * @param string $targetInternalPath
176
-	 * @return bool
177
-	 */
178
-	public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
-		$free = $this->free_space('');
180
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
-		} else {
183
-			return false;
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * @param \OCP\Files\Storage $sourceStorage
189
-	 * @param string $sourceInternalPath
190
-	 * @param string $targetInternalPath
191
-	 * @return bool
192
-	 */
193
-	public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
-		$free = $this->free_space('');
195
-		if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
-		} else {
198
-			return false;
199
-		}
200
-	}
33
+    /**
34
+     * @var int $quota
35
+     */
36
+    protected $quota;
37
+
38
+    /**
39
+     * @var string $sizeRoot
40
+     */
41
+    protected $sizeRoot;
42
+
43
+    /**
44
+     * @param array $parameters
45
+     */
46
+    public function __construct($parameters) {
47
+        $this->storage = $parameters['storage'];
48
+        $this->quota = $parameters['quota'];
49
+        $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : '';
50
+    }
51
+
52
+    /**
53
+     * @return int quota value
54
+     */
55
+    public function getQuota() {
56
+        return $this->quota;
57
+    }
58
+
59
+    /**
60
+     * @param string $path
61
+     * @param \OC\Files\Storage\Storage $storage
62
+     */
63
+    protected function getSize($path, $storage = null) {
64
+        if (is_null($storage)) {
65
+            $cache = $this->getCache();
66
+        } else {
67
+            $cache = $storage->getCache();
68
+        }
69
+        $data = $cache->get($path);
70
+        if ($data instanceof ICacheEntry and isset($data['size'])) {
71
+            return $data['size'];
72
+        } else {
73
+            return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
74
+        }
75
+    }
76
+
77
+    /**
78
+     * Get free space as limited by the quota
79
+     *
80
+     * @param string $path
81
+     * @return int
82
+     */
83
+    public function free_space($path) {
84
+        if ($this->quota < 0) {
85
+            return $this->storage->free_space($path);
86
+        } else {
87
+            $used = $this->getSize($this->sizeRoot);
88
+            if ($used < 0) {
89
+                return \OCP\Files\FileInfo::SPACE_NOT_COMPUTED;
90
+            } else {
91
+                $free = $this->storage->free_space($path);
92
+                $quotaFree = max($this->quota - $used, 0);
93
+                // if free space is known
94
+                if ($free >= 0) {
95
+                    $free = min($free, $quotaFree);
96
+                } else {
97
+                    $free = $quotaFree;
98
+                }
99
+                return $free;
100
+            }
101
+        }
102
+    }
103
+
104
+    /**
105
+     * see http://php.net/manual/en/function.file_put_contents.php
106
+     *
107
+     * @param string $path
108
+     * @param string $data
109
+     * @return bool
110
+     */
111
+    public function file_put_contents($path, $data) {
112
+        $free = $this->free_space('');
113
+        if ($free < 0 or strlen($data) < $free) {
114
+            return $this->storage->file_put_contents($path, $data);
115
+        } else {
116
+            return false;
117
+        }
118
+    }
119
+
120
+    /**
121
+     * see http://php.net/manual/en/function.copy.php
122
+     *
123
+     * @param string $source
124
+     * @param string $target
125
+     * @return bool
126
+     */
127
+    public function copy($source, $target) {
128
+        $free = $this->free_space('');
129
+        if ($free < 0 or $this->getSize($source) < $free) {
130
+            return $this->storage->copy($source, $target);
131
+        } else {
132
+            return false;
133
+        }
134
+    }
135
+
136
+    /**
137
+     * see http://php.net/manual/en/function.fopen.php
138
+     *
139
+     * @param string $path
140
+     * @param string $mode
141
+     * @return resource
142
+     */
143
+    public function fopen($path, $mode) {
144
+        $source = $this->storage->fopen($path, $mode);
145
+
146
+        // don't apply quota for part files
147
+        if (!$this->isPartFile($path)) {
148
+            $free = $this->free_space('');
149
+            if ($source && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
150
+                // only apply quota for files, not metadata, trash or others
151
+                if (strpos(ltrim($path, '/'), 'files/') === 0) {
152
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
153
+                }
154
+            }
155
+        }
156
+        return $source;
157
+    }
158
+
159
+    /**
160
+     * Checks whether the given path is a part file
161
+     *
162
+     * @param string $path Path that may identify a .part file
163
+     * @return string File path without .part extension
164
+     * @note this is needed for reusing keys
165
+     */
166
+    private function isPartFile($path) {
167
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
168
+
169
+        return ($extension === 'part');
170
+    }
171
+
172
+    /**
173
+     * @param \OCP\Files\Storage $sourceStorage
174
+     * @param string $sourceInternalPath
175
+     * @param string $targetInternalPath
176
+     * @return bool
177
+     */
178
+    public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
179
+        $free = $this->free_space('');
180
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
181
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
182
+        } else {
183
+            return false;
184
+        }
185
+    }
186
+
187
+    /**
188
+     * @param \OCP\Files\Storage $sourceStorage
189
+     * @param string $sourceInternalPath
190
+     * @param string $targetInternalPath
191
+     * @return bool
192
+     */
193
+    public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
194
+        $free = $this->free_space('');
195
+        if ($free < 0 or $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
196
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
197
+        } else {
198
+            return false;
199
+        }
200
+    }
201 201
 }
Please login to merge, or discard this patch.
lib/private/legacy/api.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -331,7 +331,7 @@
 block discarded – undo
331 331
 
332 332
 	/**
333 333
 	 * http basic auth
334
-	 * @return string|false (username, or false on failure)
334
+	 * @return string (username, or false on failure)
335 335
 	 */
336 336
 	private static function loginUser() {
337 337
 		if(self::$isLoggedIn === true) {
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 				$requirements = array()) {
93 93
 		$name = strtolower($method).$url;
94 94
 		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
95
+		if (!isset(self::$actions[$name])) {
96 96
 			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97 97
 			OC::$server->getRouter()->useCollection('ocs');
98 98
 			OC::$server->getRouter()->create($name, $url)
@@ -115,17 +115,17 @@  discard block
 block discarded – undo
115 115
 		$method = $request->getMethod();
116 116
 
117 117
 		// Prepare the request variables
118
-		if($method === 'PUT') {
118
+		if ($method === 'PUT') {
119 119
 			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
120
+		} else if ($method === 'DELETE') {
121 121
 			$parameters['_delete'] = $request->getParams();
122 122
 		}
123 123
 		$name = $parameters['_route'];
124 124
 		// Foreach registered action
125 125
 		$responses = array();
126
-		foreach(self::$actions[$name] as $action) {
126
+		foreach (self::$actions[$name] as $action) {
127 127
 			// Check authentication and availability
128
-			if(!self::isAuthorised($action)) {
128
+			if (!self::isAuthorised($action)) {
129 129
 				$responses[] = array(
130 130
 					'app' => $action['app'],
131 131
 					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 					);
134 134
 				continue;
135 135
 			}
136
-			if(!is_callable($action['action'])) {
136
+			if (!is_callable($action['action'])) {
137 137
 				$responses[] = array(
138 138
 					'app' => $action['app'],
139 139
 					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
@@ -173,15 +173,15 @@  discard block
 block discarded – undo
173 173
 			'failed' => array(),
174 174
 			);
175 175
 
176
-		foreach($responses as $response) {
177
-			if($response['shipped'] || ($response['app'] === 'core')) {
178
-				if($response['response']->succeeded()) {
176
+		foreach ($responses as $response) {
177
+			if ($response['shipped'] || ($response['app'] === 'core')) {
178
+				if ($response['response']->succeeded()) {
179 179
 					$shipped['succeeded'][$response['app']] = $response;
180 180
 				} else {
181 181
 					$shipped['failed'][$response['app']] = $response;
182 182
 				}
183 183
 			} else {
184
-				if($response['response']->succeeded()) {
184
+				if ($response['response']->succeeded()) {
185 185
 					$thirdparty['succeeded'][$response['app']] = $response;
186 186
 				} else {
187 187
 					$thirdparty['failed'][$response['app']] = $response;
@@ -190,14 +190,14 @@  discard block
 block discarded – undo
190 190
 		}
191 191
 
192 192
 		// Remove any error responses if there is one shipped response that succeeded
193
-		if(!empty($shipped['failed'])) {
193
+		if (!empty($shipped['failed'])) {
194 194
 			// Which shipped response do we use if they all failed?
195 195
 			// They may have failed for different reasons (different status codes)
196 196
 			// Which response code should we return?
197 197
 			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198 198
 			// Merge failed responses if more than one
199 199
 			$data = array();
200
-			foreach($shipped['failed'] as $failure) {
200
+			foreach ($shipped['failed'] as $failure) {
201 201
 				$data = array_merge_recursive($data, $failure['response']->getData());
202 202
 			}
203 203
 			$picked = reset($shipped['failed']);
@@ -206,12 +206,12 @@  discard block
 block discarded – undo
206 206
 			$headers = $picked['response']->getHeaders();
207 207
 			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208 208
 			return $response;
209
-		} elseif(!empty($shipped['succeeded'])) {
209
+		} elseif (!empty($shipped['succeeded'])) {
210 210
 			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
-		} elseif(!empty($thirdparty['failed'])) {
211
+		} elseif (!empty($thirdparty['failed'])) {
212 212
 			// Merge failed responses if more than one
213 213
 			$data = array();
214
-			foreach($thirdparty['failed'] as $failure) {
214
+			foreach ($thirdparty['failed'] as $failure) {
215 215
 				$data = array_merge_recursive($data, $failure['response']->getData());
216 216
 			}
217 217
 			$picked = reset($thirdparty['failed']);
@@ -228,8 +228,8 @@  discard block
 block discarded – undo
228 228
 		$codes = [];
229 229
 		$header = [];
230 230
 
231
-		foreach($responses as $response) {
232
-			if($response['shipped']) {
231
+		foreach ($responses as $response) {
232
+			if ($response['shipped']) {
233 233
 				$data = array_merge_recursive($response['response']->getData(), $data);
234 234
 			} else {
235 235
 				$data = array_merge_recursive($data, $response['response']->getData());
@@ -242,8 +242,8 @@  discard block
 block discarded – undo
242 242
 		// Use any non 100 status codes
243 243
 		$statusCode = 100;
244 244
 		$statusMessage = null;
245
-		foreach($codes as $code) {
246
-			if($code['code'] != 100) {
245
+		foreach ($codes as $code) {
246
+			if ($code['code'] != 100) {
247 247
 				$statusCode = $code['code'];
248 248
 				$statusMessage = $code['meta']['message'];
249 249
 				break;
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 	 */
261 261
 	private static function isAuthorised($action) {
262 262
 		$level = $action['authlevel'];
263
-		switch($level) {
263
+		switch ($level) {
264 264
 			case API::GUEST_AUTH:
265 265
 				// Anyone can access
266 266
 				return true;
@@ -270,16 +270,16 @@  discard block
 block discarded – undo
270 270
 			case API::SUBADMIN_AUTH:
271 271
 				// Check for subadmin
272 272
 				$user = self::loginUser();
273
-				if(!$user) {
273
+				if (!$user) {
274 274
 					return false;
275 275
 				} else {
276 276
 					$userObject = \OC::$server->getUserSession()->getUser();
277
-					if($userObject === null) {
277
+					if ($userObject === null) {
278 278
 						return false;
279 279
 					}
280 280
 					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281 281
 					$admin = OC_User::isAdminUser($user);
282
-					if($isSubAdmin || $admin) {
282
+					if ($isSubAdmin || $admin) {
283 283
 						return true;
284 284
 					} else {
285 285
 						return false;
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			case API::ADMIN_AUTH:
289 289
 				// Check for admin
290 290
 				$user = self::loginUser();
291
-				if(!$user) {
291
+				if (!$user) {
292 292
 					return false;
293 293
 				} else {
294 294
 					return OC_User::isAdminUser($user);
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 	 * @return string|false (username, or false on failure)
305 305
 	 */
306 306
 	private static function loginUser() {
307
-		if(self::$isLoggedIn === true) {
307
+		if (self::$isLoggedIn === true) {
308 308
 			return \OC_User::getUser();
309 309
 		}
310 310
 
@@ -358,13 +358,13 @@  discard block
 block discarded – undo
358 358
 	 * @param OC_OCS_Result $result
359 359
 	 * @param string $format the format xml|json
360 360
 	 */
361
-	public static function respond($result, $format='xml') {
361
+	public static function respond($result, $format = 'xml') {
362 362
 		$request = \OC::$server->getRequest();
363 363
 
364 364
 		// Send 401 headers if unauthorised
365
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
365
+		if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
366 366
 			// If request comes from JS return dummy auth request
367
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
367
+			if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
368 368
 				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
369 369
 			} else {
370 370
 				header('WWW-Authenticate: Basic realm="Authorisation Required"');
@@ -372,8 +372,8 @@  discard block
 block discarded – undo
372 372
 			header('HTTP/1.0 401 Unauthorized');
373 373
 		}
374 374
 
375
-		foreach($result->getHeaders() as $name => $value) {
376
-			header($name . ': ' . $value);
375
+		foreach ($result->getHeaders() as $name => $value) {
376
+			header($name.': '.$value);
377 377
 		}
378 378
 
379 379
 		$meta = $result->getMeta();
@@ -395,14 +395,14 @@  discard block
 block discarded – undo
395 395
 	 * @param XMLWriter $writer
396 396
 	 */
397 397
 	private static function toXML($array, $writer) {
398
-		foreach($array as $k => $v) {
398
+		foreach ($array as $k => $v) {
399 399
 			if ($k[0] === '@') {
400 400
 				$writer->writeAttribute(substr($k, 1), $v);
401 401
 				continue;
402 402
 			} else if (is_numeric($k)) {
403 403
 				$k = 'element';
404 404
 			}
405
-			if(is_array($v)) {
405
+			if (is_array($v)) {
406 406
 				$writer->startElement($k);
407 407
 				self::toXML($v, $writer);
408 408
 				$writer->endElement();
Please login to merge, or discard this patch.
Indentation   +458 added lines, -458 removed lines patch added patch discarded remove patch
@@ -37,462 +37,462 @@
 block discarded – undo
37 37
 
38 38
 class OC_API {
39 39
 
40
-	/**
41
-	 * API authentication levels
42
-	 */
43
-
44
-	/** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
-	const GUEST_AUTH = 0;
46
-
47
-	/** @deprecated Use \OCP\API::USER_AUTH instead */
48
-	const USER_AUTH = 1;
49
-
50
-	/** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
-	const SUBADMIN_AUTH = 2;
52
-
53
-	/** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
-	const ADMIN_AUTH = 3;
55
-
56
-	/**
57
-	 * API Response Codes
58
-	 */
59
-
60
-	/** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
-	const RESPOND_UNAUTHORISED = 997;
62
-
63
-	/** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
-	const RESPOND_SERVER_ERROR = 996;
65
-
66
-	/** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
-	const RESPOND_NOT_FOUND = 998;
68
-
69
-	/** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
-	const RESPOND_UNKNOWN_ERROR = 999;
71
-
72
-	/**
73
-	 * api actions
74
-	 */
75
-	protected static $actions = array();
76
-	private static $logoutRequired = false;
77
-	private static $isLoggedIn = false;
78
-
79
-	/**
80
-	 * registers an api call
81
-	 * @param string $method the http method
82
-	 * @param string $url the url to match
83
-	 * @param callable $action the function to run
84
-	 * @param string $app the id of the app registering the call
85
-	 * @param int $authLevel the level of authentication required for the call
86
-	 * @param array $defaults
87
-	 * @param array $requirements
88
-	 */
89
-	public static function register($method, $url, $action, $app,
90
-				$authLevel = API::USER_AUTH,
91
-				$defaults = array(),
92
-				$requirements = array()) {
93
-		$name = strtolower($method).$url;
94
-		$name = str_replace(array('/', '{', '}'), '_', $name);
95
-		if(!isset(self::$actions[$name])) {
96
-			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
-			OC::$server->getRouter()->useCollection('ocs');
98
-			OC::$server->getRouter()->create($name, $url)
99
-				->method($method)
100
-				->defaults($defaults)
101
-				->requirements($requirements)
102
-				->action('OC_API', 'call');
103
-			self::$actions[$name] = array();
104
-			OC::$server->getRouter()->useCollection($oldCollection);
105
-		}
106
-		self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
-	}
108
-
109
-	/**
110
-	 * handles an api call
111
-	 * @param array $parameters
112
-	 */
113
-	public static function call($parameters) {
114
-		$request = \OC::$server->getRequest();
115
-		$method = $request->getMethod();
116
-
117
-		// Prepare the request variables
118
-		if($method === 'PUT') {
119
-			$parameters['_put'] = $request->getParams();
120
-		} else if($method === 'DELETE') {
121
-			$parameters['_delete'] = $request->getParams();
122
-		}
123
-		$name = $parameters['_route'];
124
-		// Foreach registered action
125
-		$responses = array();
126
-		foreach(self::$actions[$name] as $action) {
127
-			// Check authentication and availability
128
-			if(!self::isAuthorised($action)) {
129
-				$responses[] = array(
130
-					'app' => $action['app'],
131
-					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
132
-					'shipped' => OC_App::isShipped($action['app']),
133
-					);
134
-				continue;
135
-			}
136
-			if(!is_callable($action['action'])) {
137
-				$responses[] = array(
138
-					'app' => $action['app'],
139
-					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
140
-					'shipped' => OC_App::isShipped($action['app']),
141
-					);
142
-				continue;
143
-			}
144
-			// Run the action
145
-			$responses[] = array(
146
-				'app' => $action['app'],
147
-				'response' => call_user_func($action['action'], $parameters),
148
-				'shipped' => OC_App::isShipped($action['app']),
149
-				);
150
-		}
151
-		$response = self::mergeResponses($responses);
152
-		$format = self::requestedFormat();
153
-		if (self::$logoutRequired) {
154
-			\OC::$server->getUserSession()->logout();
155
-		}
156
-
157
-		self::respond($response, $format);
158
-	}
159
-
160
-	/**
161
-	 * merge the returned result objects into one response
162
-	 * @param array $responses
163
-	 * @return OC_OCS_Result
164
-	 */
165
-	public static function mergeResponses($responses) {
166
-		// Sort into shipped and third-party
167
-		$shipped = array(
168
-			'succeeded' => array(),
169
-			'failed' => array(),
170
-			);
171
-		$thirdparty = array(
172
-			'succeeded' => array(),
173
-			'failed' => array(),
174
-			);
175
-
176
-		foreach($responses as $response) {
177
-			if($response['shipped'] || ($response['app'] === 'core')) {
178
-				if($response['response']->succeeded()) {
179
-					$shipped['succeeded'][$response['app']] = $response;
180
-				} else {
181
-					$shipped['failed'][$response['app']] = $response;
182
-				}
183
-			} else {
184
-				if($response['response']->succeeded()) {
185
-					$thirdparty['succeeded'][$response['app']] = $response;
186
-				} else {
187
-					$thirdparty['failed'][$response['app']] = $response;
188
-				}
189
-			}
190
-		}
191
-
192
-		// Remove any error responses if there is one shipped response that succeeded
193
-		if(!empty($shipped['failed'])) {
194
-			// Which shipped response do we use if they all failed?
195
-			// They may have failed for different reasons (different status codes)
196
-			// Which response code should we return?
197
-			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198
-			// Merge failed responses if more than one
199
-			$data = array();
200
-			foreach($shipped['failed'] as $failure) {
201
-				$data = array_merge_recursive($data, $failure['response']->getData());
202
-			}
203
-			$picked = reset($shipped['failed']);
204
-			$code = $picked['response']->getStatusCode();
205
-			$meta = $picked['response']->getMeta();
206
-			$headers = $picked['response']->getHeaders();
207
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208
-			return $response;
209
-		} elseif(!empty($shipped['succeeded'])) {
210
-			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
-		} elseif(!empty($thirdparty['failed'])) {
212
-			// Merge failed responses if more than one
213
-			$data = array();
214
-			foreach($thirdparty['failed'] as $failure) {
215
-				$data = array_merge_recursive($data, $failure['response']->getData());
216
-			}
217
-			$picked = reset($thirdparty['failed']);
218
-			$code = $picked['response']->getStatusCode();
219
-			$meta = $picked['response']->getMeta();
220
-			$headers = $picked['response']->getHeaders();
221
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
222
-			return $response;
223
-		} else {
224
-			$responses = $thirdparty['succeeded'];
225
-		}
226
-		// Merge the successful responses
227
-		$data = [];
228
-		$codes = [];
229
-		$header = [];
230
-
231
-		foreach($responses as $response) {
232
-			if($response['shipped']) {
233
-				$data = array_merge_recursive($response['response']->getData(), $data);
234
-			} else {
235
-				$data = array_merge_recursive($data, $response['response']->getData());
236
-			}
237
-			$header = array_merge_recursive($header, $response['response']->getHeaders());
238
-			$codes[] = ['code' => $response['response']->getStatusCode(),
239
-				'meta' => $response['response']->getMeta()];
240
-		}
241
-
242
-		// Use any non 100 status codes
243
-		$statusCode = 100;
244
-		$statusMessage = null;
245
-		foreach($codes as $code) {
246
-			if($code['code'] != 100) {
247
-				$statusCode = $code['code'];
248
-				$statusMessage = $code['meta']['message'];
249
-				break;
250
-			}
251
-		}
252
-
253
-		return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
254
-	}
255
-
256
-	/**
257
-	 * authenticate the api call
258
-	 * @param array $action the action details as supplied to OC_API::register()
259
-	 * @return bool
260
-	 */
261
-	private static function isAuthorised($action) {
262
-		$level = $action['authlevel'];
263
-		switch($level) {
264
-			case API::GUEST_AUTH:
265
-				// Anyone can access
266
-				return true;
267
-			case API::USER_AUTH:
268
-				// User required
269
-				return self::loginUser();
270
-			case API::SUBADMIN_AUTH:
271
-				// Check for subadmin
272
-				$user = self::loginUser();
273
-				if(!$user) {
274
-					return false;
275
-				} else {
276
-					$userObject = \OC::$server->getUserSession()->getUser();
277
-					if($userObject === null) {
278
-						return false;
279
-					}
280
-					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281
-					$admin = OC_User::isAdminUser($user);
282
-					if($isSubAdmin || $admin) {
283
-						return true;
284
-					} else {
285
-						return false;
286
-					}
287
-				}
288
-			case API::ADMIN_AUTH:
289
-				// Check for admin
290
-				$user = self::loginUser();
291
-				if(!$user) {
292
-					return false;
293
-				} else {
294
-					return OC_User::isAdminUser($user);
295
-				}
296
-			default:
297
-				// oops looks like invalid level supplied
298
-				return false;
299
-		}
300
-	}
301
-
302
-	/**
303
-	 * http basic auth
304
-	 * @return string|false (username, or false on failure)
305
-	 */
306
-	private static function loginUser() {
307
-		if(self::$isLoggedIn === true) {
308
-			return \OC_User::getUser();
309
-		}
310
-
311
-		// reuse existing login
312
-		$loggedIn = \OC::$server->getUserSession()->isLoggedIn();
313
-		if ($loggedIn === true) {
314
-			if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
315
-				// Do not allow access to OCS until the 2FA challenge was solved successfully
316
-				return false;
317
-			}
318
-			$ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
319
-			if ($ocsApiRequest) {
320
-
321
-				// initialize the user's filesystem
322
-				\OC_Util::setupFS(\OC_User::getUser());
323
-				self::$isLoggedIn = true;
324
-
325
-				return OC_User::getUser();
326
-			}
327
-			return false;
328
-		}
329
-
330
-		// basic auth - because OC_User::login will create a new session we shall only try to login
331
-		// if user and pass are set
332
-		$userSession = \OC::$server->getUserSession();
333
-		$request = \OC::$server->getRequest();
334
-		try {
335
-			if ($userSession->tryTokenLogin($request)
336
-				|| $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
337
-				self::$logoutRequired = true;
338
-			} else {
339
-				return false;
340
-			}
341
-			// initialize the user's filesystem
342
-			\OC_Util::setupFS(\OC_User::getUser());
343
-			self::$isLoggedIn = true;
344
-
345
-			return \OC_User::getUser();
346
-		} catch (\OC\User\LoginException $e) {
347
-			return false;
348
-		}
349
-	}
350
-
351
-	/**
352
-	 * respond to a call
353
-	 * @param OC_OCS_Result $result
354
-	 * @param string $format the format xml|json
355
-	 */
356
-	public static function respond($result, $format='xml') {
357
-		$request = \OC::$server->getRequest();
358
-
359
-		// Send 401 headers if unauthorised
360
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
361
-			// If request comes from JS return dummy auth request
362
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
363
-				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
364
-			} else {
365
-				header('WWW-Authenticate: Basic realm="Authorisation Required"');
366
-			}
367
-			header('HTTP/1.0 401 Unauthorized');
368
-		}
369
-
370
-		foreach($result->getHeaders() as $name => $value) {
371
-			header($name . ': ' . $value);
372
-		}
373
-
374
-		$meta = $result->getMeta();
375
-		$data = $result->getData();
376
-		if (self::isV2($request)) {
377
-			$statusCode = self::mapStatusCodes($result->getStatusCode());
378
-			if (!is_null($statusCode)) {
379
-				$meta['statuscode'] = $statusCode;
380
-				OC_Response::setStatus($statusCode);
381
-			}
382
-		}
383
-
384
-		self::setContentType($format);
385
-		$body = self::renderResult($format, $meta, $data);
386
-		echo $body;
387
-	}
388
-
389
-	/**
390
-	 * @param XMLWriter $writer
391
-	 */
392
-	private static function toXML($array, $writer) {
393
-		foreach($array as $k => $v) {
394
-			if ($k[0] === '@') {
395
-				$writer->writeAttribute(substr($k, 1), $v);
396
-				continue;
397
-			} else if (is_numeric($k)) {
398
-				$k = 'element';
399
-			}
400
-			if(is_array($v)) {
401
-				$writer->startElement($k);
402
-				self::toXML($v, $writer);
403
-				$writer->endElement();
404
-			} else {
405
-				$writer->writeElement($k, $v);
406
-			}
407
-		}
408
-	}
409
-
410
-	/**
411
-	 * @return string
412
-	 */
413
-	public static function requestedFormat() {
414
-		$formats = array('json', 'xml');
415
-
416
-		$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
417
-		return $format;
418
-	}
419
-
420
-	/**
421
-	 * Based on the requested format the response content type is set
422
-	 * @param string $format
423
-	 */
424
-	public static function setContentType($format = null) {
425
-		$format = is_null($format) ? self::requestedFormat() : $format;
426
-		if ($format === 'xml') {
427
-			header('Content-type: text/xml; charset=UTF-8');
428
-			return;
429
-		}
430
-
431
-		if ($format === 'json') {
432
-			header('Content-Type: application/json; charset=utf-8');
433
-			return;
434
-		}
435
-
436
-		header('Content-Type: application/octet-stream; charset=utf-8');
437
-	}
438
-
439
-	/**
440
-	 * @param \OCP\IRequest $request
441
-	 * @return bool
442
-	 */
443
-	protected static function isV2(\OCP\IRequest $request) {
444
-		$script = $request->getScriptName();
445
-
446
-		return substr($script, -11) === '/ocs/v2.php';
447
-	}
448
-
449
-	/**
450
-	 * @param integer $sc
451
-	 * @return int
452
-	 */
453
-	public static function mapStatusCodes($sc) {
454
-		switch ($sc) {
455
-			case API::RESPOND_NOT_FOUND:
456
-				return Http::STATUS_NOT_FOUND;
457
-			case API::RESPOND_SERVER_ERROR:
458
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
459
-			case API::RESPOND_UNKNOWN_ERROR:
460
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
461
-			case API::RESPOND_UNAUTHORISED:
462
-				// already handled for v1
463
-				return null;
464
-			case 100:
465
-				return Http::STATUS_OK;
466
-		}
467
-		// any 2xx, 4xx and 5xx will be used as is
468
-		if ($sc >= 200 && $sc < 600) {
469
-			return $sc;
470
-		}
471
-
472
-		return Http::STATUS_BAD_REQUEST;
473
-	}
474
-
475
-	/**
476
-	 * @param string $format
477
-	 * @return string
478
-	 */
479
-	public static function renderResult($format, $meta, $data) {
480
-		$response = array(
481
-			'ocs' => array(
482
-				'meta' => $meta,
483
-				'data' => $data,
484
-			),
485
-		);
486
-		if ($format == 'json') {
487
-			return OC_JSON::encode($response);
488
-		}
489
-
490
-		$writer = new XMLWriter();
491
-		$writer->openMemory();
492
-		$writer->setIndent(true);
493
-		$writer->startDocument();
494
-		self::toXML($response, $writer);
495
-		$writer->endDocument();
496
-		return $writer->outputMemory(true);
497
-	}
40
+    /**
41
+     * API authentication levels
42
+     */
43
+
44
+    /** @deprecated Use \OCP\API::GUEST_AUTH instead */
45
+    const GUEST_AUTH = 0;
46
+
47
+    /** @deprecated Use \OCP\API::USER_AUTH instead */
48
+    const USER_AUTH = 1;
49
+
50
+    /** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
51
+    const SUBADMIN_AUTH = 2;
52
+
53
+    /** @deprecated Use \OCP\API::ADMIN_AUTH instead */
54
+    const ADMIN_AUTH = 3;
55
+
56
+    /**
57
+     * API Response Codes
58
+     */
59
+
60
+    /** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
61
+    const RESPOND_UNAUTHORISED = 997;
62
+
63
+    /** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
64
+    const RESPOND_SERVER_ERROR = 996;
65
+
66
+    /** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
67
+    const RESPOND_NOT_FOUND = 998;
68
+
69
+    /** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
70
+    const RESPOND_UNKNOWN_ERROR = 999;
71
+
72
+    /**
73
+     * api actions
74
+     */
75
+    protected static $actions = array();
76
+    private static $logoutRequired = false;
77
+    private static $isLoggedIn = false;
78
+
79
+    /**
80
+     * registers an api call
81
+     * @param string $method the http method
82
+     * @param string $url the url to match
83
+     * @param callable $action the function to run
84
+     * @param string $app the id of the app registering the call
85
+     * @param int $authLevel the level of authentication required for the call
86
+     * @param array $defaults
87
+     * @param array $requirements
88
+     */
89
+    public static function register($method, $url, $action, $app,
90
+                $authLevel = API::USER_AUTH,
91
+                $defaults = array(),
92
+                $requirements = array()) {
93
+        $name = strtolower($method).$url;
94
+        $name = str_replace(array('/', '{', '}'), '_', $name);
95
+        if(!isset(self::$actions[$name])) {
96
+            $oldCollection = OC::$server->getRouter()->getCurrentCollection();
97
+            OC::$server->getRouter()->useCollection('ocs');
98
+            OC::$server->getRouter()->create($name, $url)
99
+                ->method($method)
100
+                ->defaults($defaults)
101
+                ->requirements($requirements)
102
+                ->action('OC_API', 'call');
103
+            self::$actions[$name] = array();
104
+            OC::$server->getRouter()->useCollection($oldCollection);
105
+        }
106
+        self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
107
+    }
108
+
109
+    /**
110
+     * handles an api call
111
+     * @param array $parameters
112
+     */
113
+    public static function call($parameters) {
114
+        $request = \OC::$server->getRequest();
115
+        $method = $request->getMethod();
116
+
117
+        // Prepare the request variables
118
+        if($method === 'PUT') {
119
+            $parameters['_put'] = $request->getParams();
120
+        } else if($method === 'DELETE') {
121
+            $parameters['_delete'] = $request->getParams();
122
+        }
123
+        $name = $parameters['_route'];
124
+        // Foreach registered action
125
+        $responses = array();
126
+        foreach(self::$actions[$name] as $action) {
127
+            // Check authentication and availability
128
+            if(!self::isAuthorised($action)) {
129
+                $responses[] = array(
130
+                    'app' => $action['app'],
131
+                    'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
132
+                    'shipped' => OC_App::isShipped($action['app']),
133
+                    );
134
+                continue;
135
+            }
136
+            if(!is_callable($action['action'])) {
137
+                $responses[] = array(
138
+                    'app' => $action['app'],
139
+                    'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
140
+                    'shipped' => OC_App::isShipped($action['app']),
141
+                    );
142
+                continue;
143
+            }
144
+            // Run the action
145
+            $responses[] = array(
146
+                'app' => $action['app'],
147
+                'response' => call_user_func($action['action'], $parameters),
148
+                'shipped' => OC_App::isShipped($action['app']),
149
+                );
150
+        }
151
+        $response = self::mergeResponses($responses);
152
+        $format = self::requestedFormat();
153
+        if (self::$logoutRequired) {
154
+            \OC::$server->getUserSession()->logout();
155
+        }
156
+
157
+        self::respond($response, $format);
158
+    }
159
+
160
+    /**
161
+     * merge the returned result objects into one response
162
+     * @param array $responses
163
+     * @return OC_OCS_Result
164
+     */
165
+    public static function mergeResponses($responses) {
166
+        // Sort into shipped and third-party
167
+        $shipped = array(
168
+            'succeeded' => array(),
169
+            'failed' => array(),
170
+            );
171
+        $thirdparty = array(
172
+            'succeeded' => array(),
173
+            'failed' => array(),
174
+            );
175
+
176
+        foreach($responses as $response) {
177
+            if($response['shipped'] || ($response['app'] === 'core')) {
178
+                if($response['response']->succeeded()) {
179
+                    $shipped['succeeded'][$response['app']] = $response;
180
+                } else {
181
+                    $shipped['failed'][$response['app']] = $response;
182
+                }
183
+            } else {
184
+                if($response['response']->succeeded()) {
185
+                    $thirdparty['succeeded'][$response['app']] = $response;
186
+                } else {
187
+                    $thirdparty['failed'][$response['app']] = $response;
188
+                }
189
+            }
190
+        }
191
+
192
+        // Remove any error responses if there is one shipped response that succeeded
193
+        if(!empty($shipped['failed'])) {
194
+            // Which shipped response do we use if they all failed?
195
+            // They may have failed for different reasons (different status codes)
196
+            // Which response code should we return?
197
+            // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
198
+            // Merge failed responses if more than one
199
+            $data = array();
200
+            foreach($shipped['failed'] as $failure) {
201
+                $data = array_merge_recursive($data, $failure['response']->getData());
202
+            }
203
+            $picked = reset($shipped['failed']);
204
+            $code = $picked['response']->getStatusCode();
205
+            $meta = $picked['response']->getMeta();
206
+            $headers = $picked['response']->getHeaders();
207
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
208
+            return $response;
209
+        } elseif(!empty($shipped['succeeded'])) {
210
+            $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
211
+        } elseif(!empty($thirdparty['failed'])) {
212
+            // Merge failed responses if more than one
213
+            $data = array();
214
+            foreach($thirdparty['failed'] as $failure) {
215
+                $data = array_merge_recursive($data, $failure['response']->getData());
216
+            }
217
+            $picked = reset($thirdparty['failed']);
218
+            $code = $picked['response']->getStatusCode();
219
+            $meta = $picked['response']->getMeta();
220
+            $headers = $picked['response']->getHeaders();
221
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
222
+            return $response;
223
+        } else {
224
+            $responses = $thirdparty['succeeded'];
225
+        }
226
+        // Merge the successful responses
227
+        $data = [];
228
+        $codes = [];
229
+        $header = [];
230
+
231
+        foreach($responses as $response) {
232
+            if($response['shipped']) {
233
+                $data = array_merge_recursive($response['response']->getData(), $data);
234
+            } else {
235
+                $data = array_merge_recursive($data, $response['response']->getData());
236
+            }
237
+            $header = array_merge_recursive($header, $response['response']->getHeaders());
238
+            $codes[] = ['code' => $response['response']->getStatusCode(),
239
+                'meta' => $response['response']->getMeta()];
240
+        }
241
+
242
+        // Use any non 100 status codes
243
+        $statusCode = 100;
244
+        $statusMessage = null;
245
+        foreach($codes as $code) {
246
+            if($code['code'] != 100) {
247
+                $statusCode = $code['code'];
248
+                $statusMessage = $code['meta']['message'];
249
+                break;
250
+            }
251
+        }
252
+
253
+        return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
254
+    }
255
+
256
+    /**
257
+     * authenticate the api call
258
+     * @param array $action the action details as supplied to OC_API::register()
259
+     * @return bool
260
+     */
261
+    private static function isAuthorised($action) {
262
+        $level = $action['authlevel'];
263
+        switch($level) {
264
+            case API::GUEST_AUTH:
265
+                // Anyone can access
266
+                return true;
267
+            case API::USER_AUTH:
268
+                // User required
269
+                return self::loginUser();
270
+            case API::SUBADMIN_AUTH:
271
+                // Check for subadmin
272
+                $user = self::loginUser();
273
+                if(!$user) {
274
+                    return false;
275
+                } else {
276
+                    $userObject = \OC::$server->getUserSession()->getUser();
277
+                    if($userObject === null) {
278
+                        return false;
279
+                    }
280
+                    $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
281
+                    $admin = OC_User::isAdminUser($user);
282
+                    if($isSubAdmin || $admin) {
283
+                        return true;
284
+                    } else {
285
+                        return false;
286
+                    }
287
+                }
288
+            case API::ADMIN_AUTH:
289
+                // Check for admin
290
+                $user = self::loginUser();
291
+                if(!$user) {
292
+                    return false;
293
+                } else {
294
+                    return OC_User::isAdminUser($user);
295
+                }
296
+            default:
297
+                // oops looks like invalid level supplied
298
+                return false;
299
+        }
300
+    }
301
+
302
+    /**
303
+     * http basic auth
304
+     * @return string|false (username, or false on failure)
305
+     */
306
+    private static function loginUser() {
307
+        if(self::$isLoggedIn === true) {
308
+            return \OC_User::getUser();
309
+        }
310
+
311
+        // reuse existing login
312
+        $loggedIn = \OC::$server->getUserSession()->isLoggedIn();
313
+        if ($loggedIn === true) {
314
+            if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
315
+                // Do not allow access to OCS until the 2FA challenge was solved successfully
316
+                return false;
317
+            }
318
+            $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
319
+            if ($ocsApiRequest) {
320
+
321
+                // initialize the user's filesystem
322
+                \OC_Util::setupFS(\OC_User::getUser());
323
+                self::$isLoggedIn = true;
324
+
325
+                return OC_User::getUser();
326
+            }
327
+            return false;
328
+        }
329
+
330
+        // basic auth - because OC_User::login will create a new session we shall only try to login
331
+        // if user and pass are set
332
+        $userSession = \OC::$server->getUserSession();
333
+        $request = \OC::$server->getRequest();
334
+        try {
335
+            if ($userSession->tryTokenLogin($request)
336
+                || $userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
337
+                self::$logoutRequired = true;
338
+            } else {
339
+                return false;
340
+            }
341
+            // initialize the user's filesystem
342
+            \OC_Util::setupFS(\OC_User::getUser());
343
+            self::$isLoggedIn = true;
344
+
345
+            return \OC_User::getUser();
346
+        } catch (\OC\User\LoginException $e) {
347
+            return false;
348
+        }
349
+    }
350
+
351
+    /**
352
+     * respond to a call
353
+     * @param OC_OCS_Result $result
354
+     * @param string $format the format xml|json
355
+     */
356
+    public static function respond($result, $format='xml') {
357
+        $request = \OC::$server->getRequest();
358
+
359
+        // Send 401 headers if unauthorised
360
+        if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
361
+            // If request comes from JS return dummy auth request
362
+            if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
363
+                header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
364
+            } else {
365
+                header('WWW-Authenticate: Basic realm="Authorisation Required"');
366
+            }
367
+            header('HTTP/1.0 401 Unauthorized');
368
+        }
369
+
370
+        foreach($result->getHeaders() as $name => $value) {
371
+            header($name . ': ' . $value);
372
+        }
373
+
374
+        $meta = $result->getMeta();
375
+        $data = $result->getData();
376
+        if (self::isV2($request)) {
377
+            $statusCode = self::mapStatusCodes($result->getStatusCode());
378
+            if (!is_null($statusCode)) {
379
+                $meta['statuscode'] = $statusCode;
380
+                OC_Response::setStatus($statusCode);
381
+            }
382
+        }
383
+
384
+        self::setContentType($format);
385
+        $body = self::renderResult($format, $meta, $data);
386
+        echo $body;
387
+    }
388
+
389
+    /**
390
+     * @param XMLWriter $writer
391
+     */
392
+    private static function toXML($array, $writer) {
393
+        foreach($array as $k => $v) {
394
+            if ($k[0] === '@') {
395
+                $writer->writeAttribute(substr($k, 1), $v);
396
+                continue;
397
+            } else if (is_numeric($k)) {
398
+                $k = 'element';
399
+            }
400
+            if(is_array($v)) {
401
+                $writer->startElement($k);
402
+                self::toXML($v, $writer);
403
+                $writer->endElement();
404
+            } else {
405
+                $writer->writeElement($k, $v);
406
+            }
407
+        }
408
+    }
409
+
410
+    /**
411
+     * @return string
412
+     */
413
+    public static function requestedFormat() {
414
+        $formats = array('json', 'xml');
415
+
416
+        $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
417
+        return $format;
418
+    }
419
+
420
+    /**
421
+     * Based on the requested format the response content type is set
422
+     * @param string $format
423
+     */
424
+    public static function setContentType($format = null) {
425
+        $format = is_null($format) ? self::requestedFormat() : $format;
426
+        if ($format === 'xml') {
427
+            header('Content-type: text/xml; charset=UTF-8');
428
+            return;
429
+        }
430
+
431
+        if ($format === 'json') {
432
+            header('Content-Type: application/json; charset=utf-8');
433
+            return;
434
+        }
435
+
436
+        header('Content-Type: application/octet-stream; charset=utf-8');
437
+    }
438
+
439
+    /**
440
+     * @param \OCP\IRequest $request
441
+     * @return bool
442
+     */
443
+    protected static function isV2(\OCP\IRequest $request) {
444
+        $script = $request->getScriptName();
445
+
446
+        return substr($script, -11) === '/ocs/v2.php';
447
+    }
448
+
449
+    /**
450
+     * @param integer $sc
451
+     * @return int
452
+     */
453
+    public static function mapStatusCodes($sc) {
454
+        switch ($sc) {
455
+            case API::RESPOND_NOT_FOUND:
456
+                return Http::STATUS_NOT_FOUND;
457
+            case API::RESPOND_SERVER_ERROR:
458
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
459
+            case API::RESPOND_UNKNOWN_ERROR:
460
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
461
+            case API::RESPOND_UNAUTHORISED:
462
+                // already handled for v1
463
+                return null;
464
+            case 100:
465
+                return Http::STATUS_OK;
466
+        }
467
+        // any 2xx, 4xx and 5xx will be used as is
468
+        if ($sc >= 200 && $sc < 600) {
469
+            return $sc;
470
+        }
471
+
472
+        return Http::STATUS_BAD_REQUEST;
473
+    }
474
+
475
+    /**
476
+     * @param string $format
477
+     * @return string
478
+     */
479
+    public static function renderResult($format, $meta, $data) {
480
+        $response = array(
481
+            'ocs' => array(
482
+                'meta' => $meta,
483
+                'data' => $data,
484
+            ),
485
+        );
486
+        if ($format == 'json') {
487
+            return OC_JSON::encode($response);
488
+        }
489
+
490
+        $writer = new XMLWriter();
491
+        $writer->openMemory();
492
+        $writer->setIndent(true);
493
+        $writer->startDocument();
494
+        self::toXML($response, $writer);
495
+        $writer->endDocument();
496
+        return $writer->outputMemory(true);
497
+    }
498 498
 }
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   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -33,98 +33,98 @@
 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
-	 */
101
-	public function send($type, $data = null) {
102
-		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
-		}
105
-		$this->init();
106
-		if (is_null($data)) {
107
-			$data = $type;
108
-			$type = null;
109
-		}
110
-		if ($this->fallback) {
111
-			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
-			echo $response;
114
-		} else {
115
-			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
117
-			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
-		}
120
-		echo PHP_EOL;
121
-		flush();
122
-	}
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
+     */
101
+    public function send($type, $data = null) {
102
+        if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
+            throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
104
+        }
105
+        $this->init();
106
+        if (is_null($data)) {
107
+            $data = $type;
108
+            $type = null;
109
+        }
110
+        if ($this->fallback) {
111
+            $response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
+                . $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
113
+            echo $response;
114
+        } else {
115
+            if ($type) {
116
+                echo 'event: ' . $type . PHP_EOL;
117
+            }
118
+            echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
119
+        }
120
+        echo PHP_EOL;
121
+        flush();
122
+    }
123 123
 
124
-	/**
125
-	 * close the connection of the event source
126
-	 */
127
-	public function close() {
128
-		$this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
-	}
124
+    /**
125
+     * close the connection of the event source
126
+     */
127
+    public function close() {
128
+        $this->send('__internal__', 'close'); //server side closing can be an issue, let the client do it
129
+    }
130 130
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 		header('X-Accel-Buffering: no');
61 61
 		$this->fallback = isset($_GET['fallback']) and $_GET['fallback'] == 'true';
62 62
 		if ($this->fallback) {
63
-			$this->fallBackId = (int)$_GET['fallback_id'];
63
+			$this->fallBackId = (int) $_GET['fallback_id'];
64 64
 			/**
65 65
 			 * FIXME: The default content-security-policy of ownCloud forbids inline
66 66
 			 * JavaScript for security reasons. IE starting on Windows 10 will
@@ -73,11 +73,11 @@  discard block
 block discarded – undo
73 73
 			 */
74 74
 			header("Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'");
75 75
 			header("Content-Type: text/html");
76
-			echo str_repeat('<span></span>' . PHP_EOL, 10); //dummy data to keep IE happy
76
+			echo str_repeat('<span></span>'.PHP_EOL, 10); //dummy data to keep IE happy
77 77
 		} else {
78 78
 			header("Content-Type: text/event-stream");
79 79
 		}
80
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
80
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
81 81
 			header('Location: '.\OC::$WEBROOT);
82 82
 			exit();
83 83
 		}
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function send($type, $data = null) {
102 102
 		if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) {
103
-			throw new BadMethodCallException('Type needs to be alphanumeric ('. $type .')');
103
+			throw new BadMethodCallException('Type needs to be alphanumeric ('.$type.')');
104 104
 		}
105 105
 		$this->init();
106 106
 		if (is_null($data)) {
@@ -109,13 +109,13 @@  discard block
 block discarded – undo
109 109
 		}
110 110
 		if ($this->fallback) {
111 111
 			$response = '<script type="text/javascript">window.parent.OC.EventSource.fallBackCallBack('
112
-				. $this->fallBackId . ',"' . $type . '",' . OCP\JSON::encode($data) . ')</script>' . PHP_EOL;
112
+				. $this->fallBackId.',"'.$type.'",'.OCP\JSON::encode($data).')</script>'.PHP_EOL;
113 113
 			echo $response;
114 114
 		} else {
115 115
 			if ($type) {
116
-				echo 'event: ' . $type . PHP_EOL;
116
+				echo 'event: '.$type.PHP_EOL;
117 117
 			}
118
-			echo 'data: ' . OCP\JSON::encode($data) . PHP_EOL;
118
+			echo 'data: '.OCP\JSON::encode($data).PHP_EOL;
119 119
 		}
120 120
 		echo PHP_EOL;
121 121
 		flush();
Please login to merge, or discard this patch.
lib/private/legacy/helper.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -560,7 +560,7 @@
 block discarded – undo
560 560
 	 *
561 561
 	 * @param string $path
562 562
 	 * @param \OCP\Files\FileInfo $rootInfo (optional)
563
-	 * @return array
563
+	 * @return string
564 564
 	 * @throws \OCP\Files\NotFoundException
565 565
 	 */
566 566
 	public static function getStorageInfo($path, $rootInfo = null) {
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 		} else {
65 65
 			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
66 66
 		}
67
-		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
67
+		return $url.(($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68 68
 	}
69 69
 
70 70
 	/**
@@ -114,18 +114,18 @@  discard block
 block discarded – undo
114 114
 			return "?";
115 115
 		}
116 116
 		if ($bytes < 1024) {
117
-			return $bytes . "B";
117
+			return $bytes."B";
118 118
 		}
119 119
 		$bytes = round($bytes / 1024, 1);
120 120
 		if ($bytes < 1024) {
121
-			return $bytes . "K";
121
+			return $bytes."K";
122 122
 		}
123 123
 		$bytes = round($bytes / 1024, 1);
124 124
 		if ($bytes < 1024) {
125
-			return $bytes . "M";
125
+			return $bytes."M";
126 126
 		}
127 127
 		$bytes = round($bytes / 1024, 1);
128
-		return $bytes . "G";
128
+		return $bytes."G";
129 129
 	}
130 130
 
131 131
 	/**
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 		}
272 272
 		foreach ($dirs as $dir) {
273 273
 			foreach ($exts as $ext) {
274
-				if ($check_fn("$dir/$name" . $ext))
274
+				if ($check_fn("$dir/$name".$ext))
275 275
 					return true;
276 276
 			}
277 277
 		}
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 			$ext = '';
343 343
 		}
344 344
 
345
-		$newpath = $path . '/' . $filename;
345
+		$newpath = $path.'/'.$filename;
346 346
 		if ($view->file_exists($newpath)) {
347 347
 			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
348 348
 				//Replace the last "(number)" with "(number+1)"
@@ -358,11 +358,11 @@  discard block
 block discarded – undo
358 358
 			do {
359 359
 				if ($offset) {
360 360
 					//Replace the last "(number)" with "(number+1)"
361
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
361
+					$newname = substr_replace($name, '('.$counter.')', $offset, $match_length);
362 362
 				} else {
363
-					$newname = $name . ' (' . $counter . ')';
363
+					$newname = $name.' ('.$counter.')';
364 364
 				}
365
-				$newpath = $path . '/' . $newname . $ext;
365
+				$newpath = $path.'/'.$newname.$ext;
366 366
 				$counter++;
367 367
 			} while ($view->file_exists($newpath));
368 368
 		}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 	 * @return int number of bytes representing
426 426
 	 */
427 427
 	public static function maxUploadFilesize($dir, $freeSpace = null) {
428
-		if (is_null($freeSpace) || $freeSpace < 0){
428
+		if (is_null($freeSpace) || $freeSpace < 0) {
429 429
 			$freeSpace = self::freeSpace($dir);
430 430
 		}
431 431
 		return min($freeSpace, self::uploadLimit());
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
 			$freeSpace = max($freeSpace, 0);
444 444
 			return $freeSpace;
445 445
 		} else {
446
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
446
+			return (INF > 0) ? INF : PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
447 447
 		}
448 448
 	}
449 449
 
@@ -456,9 +456,9 @@  discard block
 block discarded – undo
456 456
 		$ini = \OC::$server->getIniWrapper();
457 457
 		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
458 458
 		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
459
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
459
+		if ((int) $upload_max_filesize === 0 and (int) $post_max_size === 0) {
460 460
 			return INF;
461
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
461
+		} elseif ((int) $upload_max_filesize === 0 or (int) $post_max_size === 0) {
462 462
 			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
463 463
 		} else {
464 464
 			return min($upload_max_filesize, $post_max_size);
@@ -510,9 +510,9 @@  discard block
 block discarded – undo
510 510
 				if (empty($paths)) {
511 511
 					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
512 512
 				} else {
513
-					$paths = str_replace(':',' ',getenv('PATH'));
513
+					$paths = str_replace(':', ' ', getenv('PATH'));
514 514
 				}
515
-				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
515
+				$command = 'find '.$paths.' -name '.escapeshellarg($program).' 2> /dev/null';
516 516
 				exec($command, $output, $returnCode);
517 517
 				if (count($output) > 0) {
518 518
 					$result = escapeshellcmd($output[0]);
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
 		$ownerId = $storage->getOwner($path);
598 598
 		$ownerDisplayName = '';
599 599
 		$owner = \OC::$server->getUserManager()->get($ownerId);
600
-		if($owner) {
600
+		if ($owner) {
601 601
 			$ownerDisplayName = $owner->getDisplayName();
602 602
 		}
603 603
 
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -271,8 +271,9 @@
 block discarded – undo
271 271
 		}
272 272
 		foreach ($dirs as $dir) {
273 273
 			foreach ($exts as $ext) {
274
-				if ($check_fn("$dir/$name" . $ext))
275
-					return true;
274
+				if ($check_fn("$dir/$name" . $ext)) {
275
+									return true;
276
+				}
276 277
 			}
277 278
 		}
278 279
 		return false;
Please login to merge, or discard this patch.
Indentation   +602 added lines, -602 removed lines patch added patch discarded remove patch
@@ -48,606 +48,606 @@
 block discarded – undo
48 48
  * Collection of useful functions
49 49
  */
50 50
 class OC_Helper {
51
-	private static $templateManager;
52
-
53
-	/**
54
-	 * Creates an absolute url for public use
55
-	 * @param string $service id
56
-	 * @param bool $add_slash
57
-	 * @return string the url
58
-	 *
59
-	 * Returns a absolute url to the given service.
60
-	 */
61
-	public static function linkToPublic($service, $add_slash = false) {
62
-		if ($service === 'files') {
63
-			$url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
64
-		} else {
65
-			$url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
66
-		}
67
-		return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68
-	}
69
-
70
-	/**
71
-	 * Make a human file size
72
-	 * @param int $bytes file size in bytes
73
-	 * @return string a human readable file size
74
-	 *
75
-	 * Makes 2048 to 2 kB.
76
-	 */
77
-	public static function humanFileSize($bytes) {
78
-		if ($bytes < 0) {
79
-			return "?";
80
-		}
81
-		if ($bytes < 1024) {
82
-			return "$bytes B";
83
-		}
84
-		$bytes = round($bytes / 1024, 0);
85
-		if ($bytes < 1024) {
86
-			return "$bytes KB";
87
-		}
88
-		$bytes = round($bytes / 1024, 1);
89
-		if ($bytes < 1024) {
90
-			return "$bytes MB";
91
-		}
92
-		$bytes = round($bytes / 1024, 1);
93
-		if ($bytes < 1024) {
94
-			return "$bytes GB";
95
-		}
96
-		$bytes = round($bytes / 1024, 1);
97
-		if ($bytes < 1024) {
98
-			return "$bytes TB";
99
-		}
100
-
101
-		$bytes = round($bytes / 1024, 1);
102
-		return "$bytes PB";
103
-	}
104
-
105
-	/**
106
-	 * Make a php file size
107
-	 * @param int $bytes file size in bytes
108
-	 * @return string a php parseable file size
109
-	 *
110
-	 * Makes 2048 to 2k and 2^41 to 2048G
111
-	 */
112
-	public static function phpFileSize($bytes) {
113
-		if ($bytes < 0) {
114
-			return "?";
115
-		}
116
-		if ($bytes < 1024) {
117
-			return $bytes . "B";
118
-		}
119
-		$bytes = round($bytes / 1024, 1);
120
-		if ($bytes < 1024) {
121
-			return $bytes . "K";
122
-		}
123
-		$bytes = round($bytes / 1024, 1);
124
-		if ($bytes < 1024) {
125
-			return $bytes . "M";
126
-		}
127
-		$bytes = round($bytes / 1024, 1);
128
-		return $bytes . "G";
129
-	}
130
-
131
-	/**
132
-	 * Make a computer file size
133
-	 * @param string $str file size in human readable format
134
-	 * @return float a file size in bytes
135
-	 *
136
-	 * Makes 2kB to 2048.
137
-	 *
138
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
139
-	 */
140
-	public static function computerFileSize($str) {
141
-		$str = strtolower($str);
142
-		if (is_numeric($str)) {
143
-			return floatval($str);
144
-		}
145
-
146
-		$bytes_array = array(
147
-			'b' => 1,
148
-			'k' => 1024,
149
-			'kb' => 1024,
150
-			'mb' => 1024 * 1024,
151
-			'm' => 1024 * 1024,
152
-			'gb' => 1024 * 1024 * 1024,
153
-			'g' => 1024 * 1024 * 1024,
154
-			'tb' => 1024 * 1024 * 1024 * 1024,
155
-			't' => 1024 * 1024 * 1024 * 1024,
156
-			'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
157
-			'p' => 1024 * 1024 * 1024 * 1024 * 1024,
158
-		);
159
-
160
-		$bytes = floatval($str);
161
-
162
-		if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
163
-			$bytes *= $bytes_array[$matches[1]];
164
-		} else {
165
-			return false;
166
-		}
167
-
168
-		$bytes = round($bytes);
169
-
170
-		return $bytes;
171
-	}
172
-
173
-	/**
174
-	 * Recursive copying of folders
175
-	 * @param string $src source folder
176
-	 * @param string $dest target folder
177
-	 *
178
-	 */
179
-	static function copyr($src, $dest) {
180
-		if (is_dir($src)) {
181
-			if (!is_dir($dest)) {
182
-				mkdir($dest);
183
-			}
184
-			$files = scandir($src);
185
-			foreach ($files as $file) {
186
-				if ($file != "." && $file != "..") {
187
-					self::copyr("$src/$file", "$dest/$file");
188
-				}
189
-			}
190
-		} elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
191
-			copy($src, $dest);
192
-		}
193
-	}
194
-
195
-	/**
196
-	 * Recursive deletion of folders
197
-	 * @param string $dir path to the folder
198
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
199
-	 * @return bool
200
-	 */
201
-	static function rmdirr($dir, $deleteSelf = true) {
202
-		if (is_dir($dir)) {
203
-			$files = new RecursiveIteratorIterator(
204
-				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
205
-				RecursiveIteratorIterator::CHILD_FIRST
206
-			);
207
-
208
-			foreach ($files as $fileInfo) {
209
-				/** @var SplFileInfo $fileInfo */
210
-				if ($fileInfo->isLink()) {
211
-					unlink($fileInfo->getPathname());
212
-				} else if ($fileInfo->isDir()) {
213
-					rmdir($fileInfo->getRealPath());
214
-				} else {
215
-					unlink($fileInfo->getRealPath());
216
-				}
217
-			}
218
-			if ($deleteSelf) {
219
-				rmdir($dir);
220
-			}
221
-		} elseif (file_exists($dir)) {
222
-			if ($deleteSelf) {
223
-				unlink($dir);
224
-			}
225
-		}
226
-		if (!$deleteSelf) {
227
-			return true;
228
-		}
229
-
230
-		return !file_exists($dir);
231
-	}
232
-
233
-	/**
234
-	 * @return \OC\Files\Type\TemplateManager
235
-	 */
236
-	static public function getFileTemplateManager() {
237
-		if (!self::$templateManager) {
238
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
239
-		}
240
-		return self::$templateManager;
241
-	}
242
-
243
-	/**
244
-	 * detect if a given program is found in the search PATH
245
-	 *
246
-	 * @param string $name
247
-	 * @param bool $path
248
-	 * @internal param string $program name
249
-	 * @internal param string $optional search path, defaults to $PATH
250
-	 * @return bool    true if executable program found in path
251
-	 */
252
-	public static function canExecute($name, $path = false) {
253
-		// path defaults to PATH from environment if not set
254
-		if ($path === false) {
255
-			$path = getenv("PATH");
256
-		}
257
-		// we look for an executable file of that name
258
-		$exts = [""];
259
-		$check_fn = "is_executable";
260
-		// Default check will be done with $path directories :
261
-		$dirs = explode(PATH_SEPARATOR, $path);
262
-		// WARNING : We have to check if open_basedir is enabled :
263
-		$obd = OC::$server->getIniWrapper()->getString('open_basedir');
264
-		if ($obd != "none") {
265
-			$obd_values = explode(PATH_SEPARATOR, $obd);
266
-			if (count($obd_values) > 0 and $obd_values[0]) {
267
-				// open_basedir is in effect !
268
-				// We need to check if the program is in one of these dirs :
269
-				$dirs = $obd_values;
270
-			}
271
-		}
272
-		foreach ($dirs as $dir) {
273
-			foreach ($exts as $ext) {
274
-				if ($check_fn("$dir/$name" . $ext))
275
-					return true;
276
-			}
277
-		}
278
-		return false;
279
-	}
280
-
281
-	/**
282
-	 * copy the contents of one stream to another
283
-	 *
284
-	 * @param resource $source
285
-	 * @param resource $target
286
-	 * @return array the number of bytes copied and result
287
-	 */
288
-	public static function streamCopy($source, $target) {
289
-		if (!$source or !$target) {
290
-			return array(0, false);
291
-		}
292
-		$bufSize = 8192;
293
-		$result = true;
294
-		$count = 0;
295
-		while (!feof($source)) {
296
-			$buf = fread($source, $bufSize);
297
-			$bytesWritten = fwrite($target, $buf);
298
-			if ($bytesWritten !== false) {
299
-				$count += $bytesWritten;
300
-			}
301
-			// note: strlen is expensive so only use it when necessary,
302
-			// on the last block
303
-			if ($bytesWritten === false
304
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
305
-			) {
306
-				// write error, could be disk full ?
307
-				$result = false;
308
-				break;
309
-			}
310
-		}
311
-		return array($count, $result);
312
-	}
313
-
314
-	/**
315
-	 * Adds a suffix to the name in case the file exists
316
-	 *
317
-	 * @param string $path
318
-	 * @param string $filename
319
-	 * @return string
320
-	 */
321
-	public static function buildNotExistingFileName($path, $filename) {
322
-		$view = \OC\Files\Filesystem::getView();
323
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
324
-	}
325
-
326
-	/**
327
-	 * Adds a suffix to the name in case the file exists
328
-	 *
329
-	 * @param string $path
330
-	 * @param string $filename
331
-	 * @return string
332
-	 */
333
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
334
-		if ($path === '/') {
335
-			$path = '';
336
-		}
337
-		if ($pos = strrpos($filename, '.')) {
338
-			$name = substr($filename, 0, $pos);
339
-			$ext = substr($filename, $pos);
340
-		} else {
341
-			$name = $filename;
342
-			$ext = '';
343
-		}
344
-
345
-		$newpath = $path . '/' . $filename;
346
-		if ($view->file_exists($newpath)) {
347
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
348
-				//Replace the last "(number)" with "(number+1)"
349
-				$last_match = count($matches[0]) - 1;
350
-				$counter = $matches[1][$last_match][0] + 1;
351
-				$offset = $matches[0][$last_match][1];
352
-				$match_length = strlen($matches[0][$last_match][0]);
353
-			} else {
354
-				$counter = 2;
355
-				$match_length = 0;
356
-				$offset = false;
357
-			}
358
-			do {
359
-				if ($offset) {
360
-					//Replace the last "(number)" with "(number+1)"
361
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
362
-				} else {
363
-					$newname = $name . ' (' . $counter . ')';
364
-				}
365
-				$newpath = $path . '/' . $newname . $ext;
366
-				$counter++;
367
-			} while ($view->file_exists($newpath));
368
-		}
369
-
370
-		return $newpath;
371
-	}
372
-
373
-	/**
374
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
375
-	 *
376
-	 * @param array $input The array to work on
377
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
378
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
379
-	 * @return array
380
-	 *
381
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
382
-	 * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
383
-	 *
384
-	 */
385
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
386
-		$case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
387
-		$ret = array();
388
-		foreach ($input as $k => $v) {
389
-			$ret[mb_convert_case($k, $case, $encoding)] = $v;
390
-		}
391
-		return $ret;
392
-	}
393
-
394
-	/**
395
-	 * performs a search in a nested array
396
-	 * @param array $haystack the array to be searched
397
-	 * @param string $needle the search string
398
-	 * @param string $index optional, only search this key name
399
-	 * @return mixed the key of the matching field, otherwise false
400
-	 *
401
-	 * performs a search in a nested array
402
-	 *
403
-	 * taken from http://www.php.net/manual/en/function.array-search.php#97645
404
-	 */
405
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
406
-		$aIt = new RecursiveArrayIterator($haystack);
407
-		$it = new RecursiveIteratorIterator($aIt);
408
-
409
-		while ($it->valid()) {
410
-			if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
411
-				return $aIt->key();
412
-			}
413
-
414
-			$it->next();
415
-		}
416
-
417
-		return false;
418
-	}
419
-
420
-	/**
421
-	 * calculates the maximum upload size respecting system settings, free space and user quota
422
-	 *
423
-	 * @param string $dir the current folder where the user currently operates
424
-	 * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
425
-	 * @return int number of bytes representing
426
-	 */
427
-	public static function maxUploadFilesize($dir, $freeSpace = null) {
428
-		if (is_null($freeSpace) || $freeSpace < 0){
429
-			$freeSpace = self::freeSpace($dir);
430
-		}
431
-		return min($freeSpace, self::uploadLimit());
432
-	}
433
-
434
-	/**
435
-	 * Calculate free space left within user quota
436
-	 *
437
-	 * @param string $dir the current folder where the user currently operates
438
-	 * @return int number of bytes representing
439
-	 */
440
-	public static function freeSpace($dir) {
441
-		$freeSpace = \OC\Files\Filesystem::free_space($dir);
442
-		if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
443
-			$freeSpace = max($freeSpace, 0);
444
-			return $freeSpace;
445
-		} else {
446
-			return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * Calculate PHP upload limit
452
-	 *
453
-	 * @return int PHP upload file size limit
454
-	 */
455
-	public static function uploadLimit() {
456
-		$ini = \OC::$server->getIniWrapper();
457
-		$upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
458
-		$post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
459
-		if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
460
-			return INF;
461
-		} elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
462
-			return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
463
-		} else {
464
-			return min($upload_max_filesize, $post_max_size);
465
-		}
466
-	}
467
-
468
-	/**
469
-	 * Checks if a function is available
470
-	 *
471
-	 * @param string $function_name
472
-	 * @return bool
473
-	 */
474
-	public static function is_function_enabled($function_name) {
475
-		if (!function_exists($function_name)) {
476
-			return false;
477
-		}
478
-		$ini = \OC::$server->getIniWrapper();
479
-		$disabled = explode(',', $ini->get('disable_functions'));
480
-		$disabled = array_map('trim', $disabled);
481
-		if (in_array($function_name, $disabled)) {
482
-			return false;
483
-		}
484
-		$disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
485
-		$disabled = array_map('trim', $disabled);
486
-		if (in_array($function_name, $disabled)) {
487
-			return false;
488
-		}
489
-		return true;
490
-	}
491
-
492
-	/**
493
-	 * Try to find a program
494
-	 *
495
-	 * @param string $program
496
-	 * @return null|string
497
-	 */
498
-	public static function findBinaryPath($program) {
499
-		$memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
500
-		if ($memcache->hasKey($program)) {
501
-			return $memcache->get($program);
502
-		}
503
-		$result = null;
504
-		if (self::is_function_enabled('exec')) {
505
-			$exeSniffer = new ExecutableFinder();
506
-			// Returns null if nothing is found
507
-			$result = $exeSniffer->find($program);
508
-			if (empty($result)) {
509
-				$paths = getenv('PATH');
510
-				if (empty($paths)) {
511
-					$paths = '/usr/local/bin /usr/bin /opt/bin /bin';
512
-				} else {
513
-					$paths = str_replace(':',' ',getenv('PATH'));
514
-				}
515
-				$command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
516
-				exec($command, $output, $returnCode);
517
-				if (count($output) > 0) {
518
-					$result = escapeshellcmd($output[0]);
519
-				}
520
-			}
521
-		}
522
-		// store the value for 5 minutes
523
-		$memcache->set($program, $result, 300);
524
-		return $result;
525
-	}
526
-
527
-	/**
528
-	 * Calculate the disc space for the given path
529
-	 *
530
-	 * @param string $path
531
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
532
-	 * @return array
533
-	 * @throws \OCP\Files\NotFoundException
534
-	 */
535
-	public static function getStorageInfo($path, $rootInfo = null) {
536
-		// return storage info without adding mount points
537
-		$includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
538
-
539
-		if (!$rootInfo) {
540
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
541
-		}
542
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
543
-			throw new \OCP\Files\NotFoundException();
544
-		}
545
-		$used = $rootInfo->getSize();
546
-		if ($used < 0) {
547
-			$used = 0;
548
-		}
549
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
550
-		$storage = $rootInfo->getStorage();
551
-		$sourceStorage = $storage;
552
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
553
-			$includeExtStorage = false;
554
-			$sourceStorage = $storage->getSourceStorage();
555
-		}
556
-		if ($includeExtStorage) {
557
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
558
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
559
-			) {
560
-				/** @var \OC\Files\Storage\Home $storage */
561
-				$user = $storage->getUser();
562
-			} else {
563
-				$user = \OC::$server->getUserSession()->getUser()->getUID();
564
-			}
565
-			if ($user) {
566
-				$quota = OC_Util::getUserQuota($user);
567
-			} else {
568
-				$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
569
-			}
570
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
571
-				// always get free space / total space from root + mount points
572
-				return self::getGlobalStorageInfo();
573
-			}
574
-		}
575
-
576
-		// TODO: need a better way to get total space from storage
577
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
578
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
579
-			$quota = $sourceStorage->getQuota();
580
-		}
581
-		$free = $sourceStorage->free_space($rootInfo->getInternalPath());
582
-		if ($free >= 0) {
583
-			$total = $free + $used;
584
-		} else {
585
-			$total = $free; //either unknown or unlimited
586
-		}
587
-		if ($total > 0) {
588
-			if ($quota > 0 && $total > $quota) {
589
-				$total = $quota;
590
-			}
591
-			// prevent division by zero or error codes (negative values)
592
-			$relative = round(($used / $total) * 10000) / 100;
593
-		} else {
594
-			$relative = 0;
595
-		}
596
-
597
-		$ownerId = $storage->getOwner($path);
598
-		$ownerDisplayName = '';
599
-		$owner = \OC::$server->getUserManager()->get($ownerId);
600
-		if($owner) {
601
-			$ownerDisplayName = $owner->getDisplayName();
602
-		}
603
-
604
-		return [
605
-			'free' => $free,
606
-			'used' => $used,
607
-			'quota' => $quota,
608
-			'total' => $total,
609
-			'relative' => $relative,
610
-			'owner' => $ownerId,
611
-			'ownerDisplayName' => $ownerDisplayName,
612
-		];
613
-	}
614
-
615
-	/**
616
-	 * Get storage info including all mount points and quota
617
-	 *
618
-	 * @return array
619
-	 */
620
-	private static function getGlobalStorageInfo() {
621
-		$quota = OC_Util::getUserQuota(\OCP\User::getUser());
622
-
623
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
624
-		$used = $rootInfo['size'];
625
-		if ($used < 0) {
626
-			$used = 0;
627
-		}
628
-
629
-		$total = $quota;
630
-		$free = $quota - $used;
631
-
632
-		if ($total > 0) {
633
-			if ($quota > 0 && $total > $quota) {
634
-				$total = $quota;
635
-			}
636
-			// prevent division by zero or error codes (negative values)
637
-			$relative = round(($used / $total) * 10000) / 100;
638
-		} else {
639
-			$relative = 0;
640
-		}
641
-
642
-		return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
643
-
644
-	}
645
-
646
-	/**
647
-	 * Returns whether the config file is set manually to read-only
648
-	 * @return bool
649
-	 */
650
-	public static function isReadOnlyConfigEnabled() {
651
-		return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
652
-	}
51
+    private static $templateManager;
52
+
53
+    /**
54
+     * Creates an absolute url for public use
55
+     * @param string $service id
56
+     * @param bool $add_slash
57
+     * @return string the url
58
+     *
59
+     * Returns a absolute url to the given service.
60
+     */
61
+    public static function linkToPublic($service, $add_slash = false) {
62
+        if ($service === 'files') {
63
+            $url = OC::$server->getURLGenerator()->getAbsoluteURL('/s');
64
+        } else {
65
+            $url = OC::$server->getURLGenerator()->getAbsoluteURL(OC::$server->getURLGenerator()->linkTo('', 'public.php').'?service='.$service);
66
+        }
67
+        return $url . (($add_slash && $service[strlen($service) - 1] != '/') ? '/' : '');
68
+    }
69
+
70
+    /**
71
+     * Make a human file size
72
+     * @param int $bytes file size in bytes
73
+     * @return string a human readable file size
74
+     *
75
+     * Makes 2048 to 2 kB.
76
+     */
77
+    public static function humanFileSize($bytes) {
78
+        if ($bytes < 0) {
79
+            return "?";
80
+        }
81
+        if ($bytes < 1024) {
82
+            return "$bytes B";
83
+        }
84
+        $bytes = round($bytes / 1024, 0);
85
+        if ($bytes < 1024) {
86
+            return "$bytes KB";
87
+        }
88
+        $bytes = round($bytes / 1024, 1);
89
+        if ($bytes < 1024) {
90
+            return "$bytes MB";
91
+        }
92
+        $bytes = round($bytes / 1024, 1);
93
+        if ($bytes < 1024) {
94
+            return "$bytes GB";
95
+        }
96
+        $bytes = round($bytes / 1024, 1);
97
+        if ($bytes < 1024) {
98
+            return "$bytes TB";
99
+        }
100
+
101
+        $bytes = round($bytes / 1024, 1);
102
+        return "$bytes PB";
103
+    }
104
+
105
+    /**
106
+     * Make a php file size
107
+     * @param int $bytes file size in bytes
108
+     * @return string a php parseable file size
109
+     *
110
+     * Makes 2048 to 2k and 2^41 to 2048G
111
+     */
112
+    public static function phpFileSize($bytes) {
113
+        if ($bytes < 0) {
114
+            return "?";
115
+        }
116
+        if ($bytes < 1024) {
117
+            return $bytes . "B";
118
+        }
119
+        $bytes = round($bytes / 1024, 1);
120
+        if ($bytes < 1024) {
121
+            return $bytes . "K";
122
+        }
123
+        $bytes = round($bytes / 1024, 1);
124
+        if ($bytes < 1024) {
125
+            return $bytes . "M";
126
+        }
127
+        $bytes = round($bytes / 1024, 1);
128
+        return $bytes . "G";
129
+    }
130
+
131
+    /**
132
+     * Make a computer file size
133
+     * @param string $str file size in human readable format
134
+     * @return float a file size in bytes
135
+     *
136
+     * Makes 2kB to 2048.
137
+     *
138
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
139
+     */
140
+    public static function computerFileSize($str) {
141
+        $str = strtolower($str);
142
+        if (is_numeric($str)) {
143
+            return floatval($str);
144
+        }
145
+
146
+        $bytes_array = array(
147
+            'b' => 1,
148
+            'k' => 1024,
149
+            'kb' => 1024,
150
+            'mb' => 1024 * 1024,
151
+            'm' => 1024 * 1024,
152
+            'gb' => 1024 * 1024 * 1024,
153
+            'g' => 1024 * 1024 * 1024,
154
+            'tb' => 1024 * 1024 * 1024 * 1024,
155
+            't' => 1024 * 1024 * 1024 * 1024,
156
+            'pb' => 1024 * 1024 * 1024 * 1024 * 1024,
157
+            'p' => 1024 * 1024 * 1024 * 1024 * 1024,
158
+        );
159
+
160
+        $bytes = floatval($str);
161
+
162
+        if (preg_match('#([kmgtp]?b?)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
163
+            $bytes *= $bytes_array[$matches[1]];
164
+        } else {
165
+            return false;
166
+        }
167
+
168
+        $bytes = round($bytes);
169
+
170
+        return $bytes;
171
+    }
172
+
173
+    /**
174
+     * Recursive copying of folders
175
+     * @param string $src source folder
176
+     * @param string $dest target folder
177
+     *
178
+     */
179
+    static function copyr($src, $dest) {
180
+        if (is_dir($src)) {
181
+            if (!is_dir($dest)) {
182
+                mkdir($dest);
183
+            }
184
+            $files = scandir($src);
185
+            foreach ($files as $file) {
186
+                if ($file != "." && $file != "..") {
187
+                    self::copyr("$src/$file", "$dest/$file");
188
+                }
189
+            }
190
+        } elseif (file_exists($src) && !\OC\Files\Filesystem::isFileBlacklisted($src)) {
191
+            copy($src, $dest);
192
+        }
193
+    }
194
+
195
+    /**
196
+     * Recursive deletion of folders
197
+     * @param string $dir path to the folder
198
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
199
+     * @return bool
200
+     */
201
+    static function rmdirr($dir, $deleteSelf = true) {
202
+        if (is_dir($dir)) {
203
+            $files = new RecursiveIteratorIterator(
204
+                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
205
+                RecursiveIteratorIterator::CHILD_FIRST
206
+            );
207
+
208
+            foreach ($files as $fileInfo) {
209
+                /** @var SplFileInfo $fileInfo */
210
+                if ($fileInfo->isLink()) {
211
+                    unlink($fileInfo->getPathname());
212
+                } else if ($fileInfo->isDir()) {
213
+                    rmdir($fileInfo->getRealPath());
214
+                } else {
215
+                    unlink($fileInfo->getRealPath());
216
+                }
217
+            }
218
+            if ($deleteSelf) {
219
+                rmdir($dir);
220
+            }
221
+        } elseif (file_exists($dir)) {
222
+            if ($deleteSelf) {
223
+                unlink($dir);
224
+            }
225
+        }
226
+        if (!$deleteSelf) {
227
+            return true;
228
+        }
229
+
230
+        return !file_exists($dir);
231
+    }
232
+
233
+    /**
234
+     * @return \OC\Files\Type\TemplateManager
235
+     */
236
+    static public function getFileTemplateManager() {
237
+        if (!self::$templateManager) {
238
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
239
+        }
240
+        return self::$templateManager;
241
+    }
242
+
243
+    /**
244
+     * detect if a given program is found in the search PATH
245
+     *
246
+     * @param string $name
247
+     * @param bool $path
248
+     * @internal param string $program name
249
+     * @internal param string $optional search path, defaults to $PATH
250
+     * @return bool    true if executable program found in path
251
+     */
252
+    public static function canExecute($name, $path = false) {
253
+        // path defaults to PATH from environment if not set
254
+        if ($path === false) {
255
+            $path = getenv("PATH");
256
+        }
257
+        // we look for an executable file of that name
258
+        $exts = [""];
259
+        $check_fn = "is_executable";
260
+        // Default check will be done with $path directories :
261
+        $dirs = explode(PATH_SEPARATOR, $path);
262
+        // WARNING : We have to check if open_basedir is enabled :
263
+        $obd = OC::$server->getIniWrapper()->getString('open_basedir');
264
+        if ($obd != "none") {
265
+            $obd_values = explode(PATH_SEPARATOR, $obd);
266
+            if (count($obd_values) > 0 and $obd_values[0]) {
267
+                // open_basedir is in effect !
268
+                // We need to check if the program is in one of these dirs :
269
+                $dirs = $obd_values;
270
+            }
271
+        }
272
+        foreach ($dirs as $dir) {
273
+            foreach ($exts as $ext) {
274
+                if ($check_fn("$dir/$name" . $ext))
275
+                    return true;
276
+            }
277
+        }
278
+        return false;
279
+    }
280
+
281
+    /**
282
+     * copy the contents of one stream to another
283
+     *
284
+     * @param resource $source
285
+     * @param resource $target
286
+     * @return array the number of bytes copied and result
287
+     */
288
+    public static function streamCopy($source, $target) {
289
+        if (!$source or !$target) {
290
+            return array(0, false);
291
+        }
292
+        $bufSize = 8192;
293
+        $result = true;
294
+        $count = 0;
295
+        while (!feof($source)) {
296
+            $buf = fread($source, $bufSize);
297
+            $bytesWritten = fwrite($target, $buf);
298
+            if ($bytesWritten !== false) {
299
+                $count += $bytesWritten;
300
+            }
301
+            // note: strlen is expensive so only use it when necessary,
302
+            // on the last block
303
+            if ($bytesWritten === false
304
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
305
+            ) {
306
+                // write error, could be disk full ?
307
+                $result = false;
308
+                break;
309
+            }
310
+        }
311
+        return array($count, $result);
312
+    }
313
+
314
+    /**
315
+     * Adds a suffix to the name in case the file exists
316
+     *
317
+     * @param string $path
318
+     * @param string $filename
319
+     * @return string
320
+     */
321
+    public static function buildNotExistingFileName($path, $filename) {
322
+        $view = \OC\Files\Filesystem::getView();
323
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
324
+    }
325
+
326
+    /**
327
+     * Adds a suffix to the name in case the file exists
328
+     *
329
+     * @param string $path
330
+     * @param string $filename
331
+     * @return string
332
+     */
333
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
334
+        if ($path === '/') {
335
+            $path = '';
336
+        }
337
+        if ($pos = strrpos($filename, '.')) {
338
+            $name = substr($filename, 0, $pos);
339
+            $ext = substr($filename, $pos);
340
+        } else {
341
+            $name = $filename;
342
+            $ext = '';
343
+        }
344
+
345
+        $newpath = $path . '/' . $filename;
346
+        if ($view->file_exists($newpath)) {
347
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
348
+                //Replace the last "(number)" with "(number+1)"
349
+                $last_match = count($matches[0]) - 1;
350
+                $counter = $matches[1][$last_match][0] + 1;
351
+                $offset = $matches[0][$last_match][1];
352
+                $match_length = strlen($matches[0][$last_match][0]);
353
+            } else {
354
+                $counter = 2;
355
+                $match_length = 0;
356
+                $offset = false;
357
+            }
358
+            do {
359
+                if ($offset) {
360
+                    //Replace the last "(number)" with "(number+1)"
361
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
362
+                } else {
363
+                    $newname = $name . ' (' . $counter . ')';
364
+                }
365
+                $newpath = $path . '/' . $newname . $ext;
366
+                $counter++;
367
+            } while ($view->file_exists($newpath));
368
+        }
369
+
370
+        return $newpath;
371
+    }
372
+
373
+    /**
374
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
375
+     *
376
+     * @param array $input The array to work on
377
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
378
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
379
+     * @return array
380
+     *
381
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
382
+     * based on http://www.php.net/manual/en/function.array-change-key-case.php#107715
383
+     *
384
+     */
385
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
386
+        $case = ($case != MB_CASE_UPPER) ? MB_CASE_LOWER : MB_CASE_UPPER;
387
+        $ret = array();
388
+        foreach ($input as $k => $v) {
389
+            $ret[mb_convert_case($k, $case, $encoding)] = $v;
390
+        }
391
+        return $ret;
392
+    }
393
+
394
+    /**
395
+     * performs a search in a nested array
396
+     * @param array $haystack the array to be searched
397
+     * @param string $needle the search string
398
+     * @param string $index optional, only search this key name
399
+     * @return mixed the key of the matching field, otherwise false
400
+     *
401
+     * performs a search in a nested array
402
+     *
403
+     * taken from http://www.php.net/manual/en/function.array-search.php#97645
404
+     */
405
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
406
+        $aIt = new RecursiveArrayIterator($haystack);
407
+        $it = new RecursiveIteratorIterator($aIt);
408
+
409
+        while ($it->valid()) {
410
+            if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
411
+                return $aIt->key();
412
+            }
413
+
414
+            $it->next();
415
+        }
416
+
417
+        return false;
418
+    }
419
+
420
+    /**
421
+     * calculates the maximum upload size respecting system settings, free space and user quota
422
+     *
423
+     * @param string $dir the current folder where the user currently operates
424
+     * @param int $freeSpace the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
425
+     * @return int number of bytes representing
426
+     */
427
+    public static function maxUploadFilesize($dir, $freeSpace = null) {
428
+        if (is_null($freeSpace) || $freeSpace < 0){
429
+            $freeSpace = self::freeSpace($dir);
430
+        }
431
+        return min($freeSpace, self::uploadLimit());
432
+    }
433
+
434
+    /**
435
+     * Calculate free space left within user quota
436
+     *
437
+     * @param string $dir the current folder where the user currently operates
438
+     * @return int number of bytes representing
439
+     */
440
+    public static function freeSpace($dir) {
441
+        $freeSpace = \OC\Files\Filesystem::free_space($dir);
442
+        if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
443
+            $freeSpace = max($freeSpace, 0);
444
+            return $freeSpace;
445
+        } else {
446
+            return (INF > 0)? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
447
+        }
448
+    }
449
+
450
+    /**
451
+     * Calculate PHP upload limit
452
+     *
453
+     * @return int PHP upload file size limit
454
+     */
455
+    public static function uploadLimit() {
456
+        $ini = \OC::$server->getIniWrapper();
457
+        $upload_max_filesize = OCP\Util::computerFileSize($ini->get('upload_max_filesize'));
458
+        $post_max_size = OCP\Util::computerFileSize($ini->get('post_max_size'));
459
+        if ((int)$upload_max_filesize === 0 and (int)$post_max_size === 0) {
460
+            return INF;
461
+        } elseif ((int)$upload_max_filesize === 0 or (int)$post_max_size === 0) {
462
+            return max($upload_max_filesize, $post_max_size); //only the non 0 value counts
463
+        } else {
464
+            return min($upload_max_filesize, $post_max_size);
465
+        }
466
+    }
467
+
468
+    /**
469
+     * Checks if a function is available
470
+     *
471
+     * @param string $function_name
472
+     * @return bool
473
+     */
474
+    public static function is_function_enabled($function_name) {
475
+        if (!function_exists($function_name)) {
476
+            return false;
477
+        }
478
+        $ini = \OC::$server->getIniWrapper();
479
+        $disabled = explode(',', $ini->get('disable_functions'));
480
+        $disabled = array_map('trim', $disabled);
481
+        if (in_array($function_name, $disabled)) {
482
+            return false;
483
+        }
484
+        $disabled = explode(',', $ini->get('suhosin.executor.func.blacklist'));
485
+        $disabled = array_map('trim', $disabled);
486
+        if (in_array($function_name, $disabled)) {
487
+            return false;
488
+        }
489
+        return true;
490
+    }
491
+
492
+    /**
493
+     * Try to find a program
494
+     *
495
+     * @param string $program
496
+     * @return null|string
497
+     */
498
+    public static function findBinaryPath($program) {
499
+        $memcache = \OC::$server->getMemCacheFactory()->create('findBinaryPath');
500
+        if ($memcache->hasKey($program)) {
501
+            return $memcache->get($program);
502
+        }
503
+        $result = null;
504
+        if (self::is_function_enabled('exec')) {
505
+            $exeSniffer = new ExecutableFinder();
506
+            // Returns null if nothing is found
507
+            $result = $exeSniffer->find($program);
508
+            if (empty($result)) {
509
+                $paths = getenv('PATH');
510
+                if (empty($paths)) {
511
+                    $paths = '/usr/local/bin /usr/bin /opt/bin /bin';
512
+                } else {
513
+                    $paths = str_replace(':',' ',getenv('PATH'));
514
+                }
515
+                $command = 'find ' . $paths . ' -name ' . escapeshellarg($program) . ' 2> /dev/null';
516
+                exec($command, $output, $returnCode);
517
+                if (count($output) > 0) {
518
+                    $result = escapeshellcmd($output[0]);
519
+                }
520
+            }
521
+        }
522
+        // store the value for 5 minutes
523
+        $memcache->set($program, $result, 300);
524
+        return $result;
525
+    }
526
+
527
+    /**
528
+     * Calculate the disc space for the given path
529
+     *
530
+     * @param string $path
531
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
532
+     * @return array
533
+     * @throws \OCP\Files\NotFoundException
534
+     */
535
+    public static function getStorageInfo($path, $rootInfo = null) {
536
+        // return storage info without adding mount points
537
+        $includeExtStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
538
+
539
+        if (!$rootInfo) {
540
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, $includeExtStorage ? 'ext' : false);
541
+        }
542
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
543
+            throw new \OCP\Files\NotFoundException();
544
+        }
545
+        $used = $rootInfo->getSize();
546
+        if ($used < 0) {
547
+            $used = 0;
548
+        }
549
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
550
+        $storage = $rootInfo->getStorage();
551
+        $sourceStorage = $storage;
552
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
553
+            $includeExtStorage = false;
554
+            $sourceStorage = $storage->getSourceStorage();
555
+        }
556
+        if ($includeExtStorage) {
557
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
558
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
559
+            ) {
560
+                /** @var \OC\Files\Storage\Home $storage */
561
+                $user = $storage->getUser();
562
+            } else {
563
+                $user = \OC::$server->getUserSession()->getUser()->getUID();
564
+            }
565
+            if ($user) {
566
+                $quota = OC_Util::getUserQuota($user);
567
+            } else {
568
+                $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
569
+            }
570
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
571
+                // always get free space / total space from root + mount points
572
+                return self::getGlobalStorageInfo();
573
+            }
574
+        }
575
+
576
+        // TODO: need a better way to get total space from storage
577
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
578
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
579
+            $quota = $sourceStorage->getQuota();
580
+        }
581
+        $free = $sourceStorage->free_space($rootInfo->getInternalPath());
582
+        if ($free >= 0) {
583
+            $total = $free + $used;
584
+        } else {
585
+            $total = $free; //either unknown or unlimited
586
+        }
587
+        if ($total > 0) {
588
+            if ($quota > 0 && $total > $quota) {
589
+                $total = $quota;
590
+            }
591
+            // prevent division by zero or error codes (negative values)
592
+            $relative = round(($used / $total) * 10000) / 100;
593
+        } else {
594
+            $relative = 0;
595
+        }
596
+
597
+        $ownerId = $storage->getOwner($path);
598
+        $ownerDisplayName = '';
599
+        $owner = \OC::$server->getUserManager()->get($ownerId);
600
+        if($owner) {
601
+            $ownerDisplayName = $owner->getDisplayName();
602
+        }
603
+
604
+        return [
605
+            'free' => $free,
606
+            'used' => $used,
607
+            'quota' => $quota,
608
+            'total' => $total,
609
+            'relative' => $relative,
610
+            'owner' => $ownerId,
611
+            'ownerDisplayName' => $ownerDisplayName,
612
+        ];
613
+    }
614
+
615
+    /**
616
+     * Get storage info including all mount points and quota
617
+     *
618
+     * @return array
619
+     */
620
+    private static function getGlobalStorageInfo() {
621
+        $quota = OC_Util::getUserQuota(\OCP\User::getUser());
622
+
623
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
624
+        $used = $rootInfo['size'];
625
+        if ($used < 0) {
626
+            $used = 0;
627
+        }
628
+
629
+        $total = $quota;
630
+        $free = $quota - $used;
631
+
632
+        if ($total > 0) {
633
+            if ($quota > 0 && $total > $quota) {
634
+                $total = $quota;
635
+            }
636
+            // prevent division by zero or error codes (negative values)
637
+            $relative = round(($used / $total) * 10000) / 100;
638
+        } else {
639
+            $relative = 0;
640
+        }
641
+
642
+        return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
643
+
644
+    }
645
+
646
+    /**
647
+     * Returns whether the config file is set manually to read-only
648
+     * @return bool
649
+     */
650
+    public static function isReadOnlyConfigEnabled() {
651
+        return \OC::$server->getConfig()->getSystemValue('config_is_read_only', false);
652
+    }
653 653
 }
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   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -53,179 +53,179 @@
 block discarded – undo
53 53
 use Symfony\Component\EventDispatcher\GenericEvent;
54 54
 
55 55
 class Repair implements IOutput{
56
-	/* @var IRepairStep[] */
57
-	private $repairSteps;
58
-	/** @var EventDispatcher */
59
-	private $dispatcher;
60
-	/** @var string */
61
-	private $currentStep;
62
-
63
-	/**
64
-	 * Creates a new repair step runner
65
-	 *
66
-	 * @param IRepairStep[] $repairSteps array of RepairStep instances
67
-	 * @param EventDispatcher $dispatcher
68
-	 */
69
-	public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
70
-		$this->repairSteps = $repairSteps;
71
-		$this->dispatcher = $dispatcher;
72
-	}
73
-
74
-	/**
75
-	 * Run a series of repair steps for common problems
76
-	 */
77
-	public function run() {
78
-		if (count($this->repairSteps) === 0) {
79
-			$this->emit('\OC\Repair', 'info', array('No repair steps available'));
80
-			return;
81
-		}
82
-		// run each repair step
83
-		foreach ($this->repairSteps as $step) {
84
-			$this->currentStep = $step->getName();
85
-			$this->emit('\OC\Repair', 'step', [$this->currentStep]);
86
-			$step->run($this);
87
-		}
88
-	}
89
-
90
-	/**
91
-	 * Add repair step
92
-	 *
93
-	 * @param IRepairStep|string $repairStep repair step
94
-	 * @throws \Exception
95
-	 */
96
-	public function addStep($repairStep) {
97
-		if (is_string($repairStep)) {
98
-			try {
99
-				$s = \OC::$server->query($repairStep);
100
-			} catch (QueryException $e) {
101
-				if (class_exists($repairStep)) {
102
-					$s = new $repairStep();
103
-				} else {
104
-					throw new \Exception("Repair step '$repairStep' is unknown");
105
-				}
106
-			}
107
-
108
-			if ($s instanceof IRepairStep) {
109
-				$this->repairSteps[] = $s;
110
-			} else {
111
-				throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
112
-			}
113
-		} else {
114
-			$this->repairSteps[] = $repairStep;
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * Returns the default repair steps to be run on the
120
-	 * command line or after an upgrade.
121
-	 *
122
-	 * @return IRepairStep[]
123
-	 */
124
-	public static function getRepairSteps() {
125
-		return [
126
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
127
-			new RepairMimeTypes(\OC::$server->getConfig()),
128
-			new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
129
-			new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
130
-			new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
131
-			new MoveUpdaterStepFile(\OC::$server->getConfig()),
132
-			new MoveAvatars(
133
-				\OC::$server->getJobList(),
134
-				\OC::$server->getConfig()
135
-			),
136
-			new CleanPreviews(
137
-				\OC::$server->getJobList(),
138
-				\OC::$server->getUserManager(),
139
-				\OC::$server->getConfig()
140
-			),
141
-			new FixMountStorages(\OC::$server->getDatabaseConnection()),
142
-			new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
143
-			new InstallCoreBundle(
144
-				\OC::$server->query(BundleFetcher::class),
145
-				\OC::$server->getConfig(),
146
-				\OC::$server->query(Installer::class)
147
-			),
148
-			new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig())
149
-		];
150
-	}
151
-
152
-	/**
153
-	 * Returns expensive repair steps to be run on the
154
-	 * command line with a special option.
155
-	 *
156
-	 * @return IRepairStep[]
157
-	 */
158
-	public static function getExpensiveRepairSteps() {
159
-		return [
160
-			new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager())
161
-		];
162
-	}
163
-
164
-	/**
165
-	 * Returns the repair steps to be run before an
166
-	 * upgrade.
167
-	 *
168
-	 * @return IRepairStep[]
169
-	 */
170
-	public static function getBeforeUpgradeRepairSteps() {
171
-		$connection = \OC::$server->getDatabaseConnection();
172
-		$config = \OC::$server->getConfig();
173
-		$steps = [
174
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
175
-			new SqliteAutoincrement($connection),
176
-			new SaveAccountsTableData($connection, $config),
177
-		];
178
-
179
-		return $steps;
180
-	}
181
-
182
-	/**
183
-	 * @param string $scope
184
-	 * @param string $method
185
-	 * @param array $arguments
186
-	 */
187
-	public function emit($scope, $method, array $arguments = []) {
188
-		if (!is_null($this->dispatcher)) {
189
-			$this->dispatcher->dispatch("$scope::$method",
190
-				new GenericEvent("$scope::$method", $arguments));
191
-		}
192
-	}
193
-
194
-	public function info($string) {
195
-		// for now just emit as we did in the past
196
-		$this->emit('\OC\Repair', 'info', array($string));
197
-	}
198
-
199
-	/**
200
-	 * @param string $message
201
-	 */
202
-	public function warning($message) {
203
-		// for now just emit as we did in the past
204
-		$this->emit('\OC\Repair', 'warning', [$message]);
205
-	}
206
-
207
-	/**
208
-	 * @param int $max
209
-	 */
210
-	public function startProgress($max = 0) {
211
-		// for now just emit as we did in the past
212
-		$this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
213
-	}
214
-
215
-	/**
216
-	 * @param int $step
217
-	 * @param string $description
218
-	 */
219
-	public function advance($step = 1, $description = '') {
220
-		// for now just emit as we did in the past
221
-		$this->emit('\OC\Repair', 'advance', [$step, $description]);
222
-	}
223
-
224
-	/**
225
-	 * @param int $max
226
-	 */
227
-	public function finishProgress() {
228
-		// for now just emit as we did in the past
229
-		$this->emit('\OC\Repair', 'finishProgress', []);
230
-	}
56
+    /* @var IRepairStep[] */
57
+    private $repairSteps;
58
+    /** @var EventDispatcher */
59
+    private $dispatcher;
60
+    /** @var string */
61
+    private $currentStep;
62
+
63
+    /**
64
+     * Creates a new repair step runner
65
+     *
66
+     * @param IRepairStep[] $repairSteps array of RepairStep instances
67
+     * @param EventDispatcher $dispatcher
68
+     */
69
+    public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
70
+        $this->repairSteps = $repairSteps;
71
+        $this->dispatcher = $dispatcher;
72
+    }
73
+
74
+    /**
75
+     * Run a series of repair steps for common problems
76
+     */
77
+    public function run() {
78
+        if (count($this->repairSteps) === 0) {
79
+            $this->emit('\OC\Repair', 'info', array('No repair steps available'));
80
+            return;
81
+        }
82
+        // run each repair step
83
+        foreach ($this->repairSteps as $step) {
84
+            $this->currentStep = $step->getName();
85
+            $this->emit('\OC\Repair', 'step', [$this->currentStep]);
86
+            $step->run($this);
87
+        }
88
+    }
89
+
90
+    /**
91
+     * Add repair step
92
+     *
93
+     * @param IRepairStep|string $repairStep repair step
94
+     * @throws \Exception
95
+     */
96
+    public function addStep($repairStep) {
97
+        if (is_string($repairStep)) {
98
+            try {
99
+                $s = \OC::$server->query($repairStep);
100
+            } catch (QueryException $e) {
101
+                if (class_exists($repairStep)) {
102
+                    $s = new $repairStep();
103
+                } else {
104
+                    throw new \Exception("Repair step '$repairStep' is unknown");
105
+                }
106
+            }
107
+
108
+            if ($s instanceof IRepairStep) {
109
+                $this->repairSteps[] = $s;
110
+            } else {
111
+                throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
112
+            }
113
+        } else {
114
+            $this->repairSteps[] = $repairStep;
115
+        }
116
+    }
117
+
118
+    /**
119
+     * Returns the default repair steps to be run on the
120
+     * command line or after an upgrade.
121
+     *
122
+     * @return IRepairStep[]
123
+     */
124
+    public static function getRepairSteps() {
125
+        return [
126
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
127
+            new RepairMimeTypes(\OC::$server->getConfig()),
128
+            new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
129
+            new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
130
+            new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
131
+            new MoveUpdaterStepFile(\OC::$server->getConfig()),
132
+            new MoveAvatars(
133
+                \OC::$server->getJobList(),
134
+                \OC::$server->getConfig()
135
+            ),
136
+            new CleanPreviews(
137
+                \OC::$server->getJobList(),
138
+                \OC::$server->getUserManager(),
139
+                \OC::$server->getConfig()
140
+            ),
141
+            new FixMountStorages(\OC::$server->getDatabaseConnection()),
142
+            new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
143
+            new InstallCoreBundle(
144
+                \OC::$server->query(BundleFetcher::class),
145
+                \OC::$server->getConfig(),
146
+                \OC::$server->query(Installer::class)
147
+            ),
148
+            new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig())
149
+        ];
150
+    }
151
+
152
+    /**
153
+     * Returns expensive repair steps to be run on the
154
+     * command line with a special option.
155
+     *
156
+     * @return IRepairStep[]
157
+     */
158
+    public static function getExpensiveRepairSteps() {
159
+        return [
160
+            new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager())
161
+        ];
162
+    }
163
+
164
+    /**
165
+     * Returns the repair steps to be run before an
166
+     * upgrade.
167
+     *
168
+     * @return IRepairStep[]
169
+     */
170
+    public static function getBeforeUpgradeRepairSteps() {
171
+        $connection = \OC::$server->getDatabaseConnection();
172
+        $config = \OC::$server->getConfig();
173
+        $steps = [
174
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
175
+            new SqliteAutoincrement($connection),
176
+            new SaveAccountsTableData($connection, $config),
177
+        ];
178
+
179
+        return $steps;
180
+    }
181
+
182
+    /**
183
+     * @param string $scope
184
+     * @param string $method
185
+     * @param array $arguments
186
+     */
187
+    public function emit($scope, $method, array $arguments = []) {
188
+        if (!is_null($this->dispatcher)) {
189
+            $this->dispatcher->dispatch("$scope::$method",
190
+                new GenericEvent("$scope::$method", $arguments));
191
+        }
192
+    }
193
+
194
+    public function info($string) {
195
+        // for now just emit as we did in the past
196
+        $this->emit('\OC\Repair', 'info', array($string));
197
+    }
198
+
199
+    /**
200
+     * @param string $message
201
+     */
202
+    public function warning($message) {
203
+        // for now just emit as we did in the past
204
+        $this->emit('\OC\Repair', 'warning', [$message]);
205
+    }
206
+
207
+    /**
208
+     * @param int $max
209
+     */
210
+    public function startProgress($max = 0) {
211
+        // for now just emit as we did in the past
212
+        $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
213
+    }
214
+
215
+    /**
216
+     * @param int $step
217
+     * @param string $description
218
+     */
219
+    public function advance($step = 1, $description = '') {
220
+        // for now just emit as we did in the past
221
+        $this->emit('\OC\Repair', 'advance', [$step, $description]);
222
+    }
223
+
224
+    /**
225
+     * @param int $max
226
+     */
227
+    public function finishProgress() {
228
+        // for now just emit as we did in the past
229
+        $this->emit('\OC\Repair', 'finishProgress', []);
230
+    }
231 231
 }
Please login to merge, or discard this patch.